File size: 1,502 Bytes
6c19c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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