Spaces:
Sleeping
Sleeping
Update api.py
Browse files
api.py
CHANGED
|
@@ -1,41 +1,47 @@
|
|
| 1 |
-
# api.py
|
| 2 |
-
import os, tempfile
|
| 3 |
-
from fastapi import FastAPI, UploadFile, File
|
| 4 |
-
from fastapi.responses import JSONResponse
|
| 5 |
-
from inference import predict
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# api.py
|
| 2 |
+
import os, tempfile
|
| 3 |
+
from fastapi import FastAPI, UploadFile, File
|
| 4 |
+
from fastapi.responses import JSONResponse
|
| 5 |
+
from inference import predict
|
| 6 |
+
from fastapi.responses import JSONResponse, PlainTextResponse
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
@app.get("/", response_class=PlainTextResponse)
|
| 12 |
+
def root():
|
| 13 |
+
return "Meat Freshness API is running. Try /health or POST /predict"
|
| 14 |
+
|
| 15 |
+
@app.get("/health")
|
| 16 |
+
def health():
|
| 17 |
+
return {"ok": True}
|
| 18 |
+
|
| 19 |
+
@app.post("/predict")
|
| 20 |
+
async def predict_endpoint(file: UploadFile = File(...)):
|
| 21 |
+
tmp_path = None
|
| 22 |
+
try:
|
| 23 |
+
# Lưu tạm file ảnh
|
| 24 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
|
| 25 |
+
tmp.write(await file.read())
|
| 26 |
+
tmp_path = tmp.name
|
| 27 |
+
|
| 28 |
+
label_en, conf = predict(tmp_path)
|
| 29 |
+
|
| 30 |
+
# Mapping theo UI hiện tại của bạn
|
| 31 |
+
map_vi = {"FRESH": "Tươi", "HALF-FRESH": "Vừa", "SPOILED": "Hỏng"}
|
| 32 |
+
map_pct = {"FRESH": 100, "HALF-FRESH": 50, "SPOILED": 0}
|
| 33 |
+
|
| 34 |
+
result = {
|
| 35 |
+
"meat_type": "pork", # sửa nếu bạn phân loại nhiều loại thịt
|
| 36 |
+
"freshness_percent": map_pct.get(label_en, 50),
|
| 37 |
+
"label_vi": map_vi.get(label_en, label_en),
|
| 38 |
+
"label_en": label_en,
|
| 39 |
+
"confidence": conf
|
| 40 |
+
}
|
| 41 |
+
return JSONResponse(result)
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return JSONResponse({"error": str(e)}, status_code=500)
|
| 44 |
+
finally:
|
| 45 |
+
if tmp_path:
|
| 46 |
+
try: os.remove(tmp_path)
|
| 47 |
+
except Exception: pass
|