meat / api.py
thienphuc12339's picture
Update api.py
6c19c1d verified
# api.py
import os, tempfile
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
from inference import predict
from fastapi.responses import JSONResponse, PlainTextResponse
app = FastAPI()
@app.get("/", response_class=PlainTextResponse)
def root():
return "Meat Freshness API is running. Try /health or POST /predict"
@app.get("/health")
def health():
return {"ok": True}
@app.post("/predict")
async def predict_endpoint(file: UploadFile = File(...)):
tmp_path = None
try:
# Lưu tạm file ảnh
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
tmp.write(await file.read())
tmp_path = tmp.name
label_en, conf = predict(tmp_path)
# Mapping theo UI hiện tại của bạn
map_vi = {"FRESH": "Tươi", "HALF-FRESH": "Vừa", "SPOILED": "Hỏng"}
map_pct = {"FRESH": 100, "HALF-FRESH": 50, "SPOILED": 0}
result = {
"meat_type": "pork", # sửa nếu bạn phân loại nhiều loại thịt
"freshness_percent": map_pct.get(label_en, 50),
"label_vi": map_vi.get(label_en, label_en),
"label_en": label_en,
"confidence": conf
}
return JSONResponse(result)
except Exception as e:
return JSONResponse({"error": str(e)}, status_code=500)
finally:
if tmp_path:
try: os.remove(tmp_path)
except Exception: pass