thienphuc12339 commited on
Commit
6c19c1d
·
verified ·
1 Parent(s): fd1c26e

Update api.py

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