-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
93 lines (70 loc) · 2.72 KB
/
Copy pathapi.py
File metadata and controls
93 lines (70 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# from pathlib import Path
# import os
# import shutil
# from fastapi import FastAPI, UploadFile, File, HTTPException
# from fastapi.middleware.cors import CORSMiddleware
# app = FastAPI(title="Food Nutrition ML API")
# app.add_middleware(
# CORSMiddleware,
# allow_origins=["*"],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
# # Use system ephemeral tmp directory on Cloud Run
# TEMP_DIR = Path("/tmp/temp_uploads")
# TEMP_DIR.mkdir(parents=True, exist_ok=True)
# @app.get("/")
# def health_check():
# """Health check endpoint for Cloud Run/monitoring."""
# return {"status": "healthy", "service": "Food Nutrition ML API"}
# @app.post("/analyze-food")
# async def analyze_food(file: UploadFile = File(...)):
# if not file.content_type or not file.content_type.startswith("image/"):
# raise HTTPException(status_code=400, detail="File must be an image.")
# temp_path = TEMP_DIR / file.filename
# try:
# with open(temp_path, "wb") as buffer:
# shutil.copyfileobj(file.file, buffer)
# # Defer heavy ML pipeline import until request execution
# # This keeps container startup under 1 second for Cloud Run health checks
# from inference.pipeline import process_image
# result = process_image(temp_path)
# return result
# except Exception as e:
# raise HTTPException(status_code=500, detail=str(e))
# finally:
# if temp_path.exists():
# os.remove(temp_path)
#new
import io
from pathlib import Path
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
app = FastAPI(title="Food Nutrition ML API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def health_check():
"""Health check endpoint for Cloud Run/monitoring."""
return {"status": "healthy", "service": "Food Nutrition ML API"}
@app.post("/analyze-food")
async def analyze_food(file: UploadFile = File(...)):
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image.")
try:
# Read file bytes directly in memory
contents = await file.read()
pil_img = Image.open(io.BytesIO(contents)).convert("RGB")
# Lazy import of pipeline to preserve fast container cold-starts
from inference.pipeline import process_image_in_memory
result = process_image_in_memory(pil_img, filename=file.filename)
return result
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))