File size: 1,654 Bytes
d52b6cc
 
 
 
 
 
 
 
9afae16
d52b6cc
 
9afae16
 
d52b6cc
 
 
 
 
 
9afae16
d52b6cc
 
 
9afae16
 
 
d52b6cc
 
 
 
 
9afae16
d52b6cc
9afae16
d52b6cc
9afae16
 
 
 
 
 
 
 
 
 
d52b6cc
 
 
9afae16
 
d52b6cc
 
 
 
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
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import cv2
import numpy as np
from ultralytics import YOLO

app = FastAPI(title="GiziTrace ML API")


model = YOLO("best.onnx", task="detect")

class_names = {0: "plate", 1: "food"}

@app.post("/predict")
async def predict_waste(file: UploadFile = File(...)):
    try:
        contents = await file.read()
        nparr = np.frombuffer(contents, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        

        results = model(img, conf=0.10)
        
        detections = []
        
        # Proses hasil deteksi
        for result in results:
            if len(result.boxes) == 0:
                continue
                
            clss = result.boxes.cls.cpu().numpy()
            confs = result.boxes.conf.cpu().numpy()
            
            for idx in range(len(clss)):
                class_id = int(clss[idx])
                confidence = float(confs[idx])
                
                # Ambil nama class dari dictionary
                label = class_names.get(class_id, "unknown")
                
                # Masukkan ke dalam list hasil
                detections.append({
                    "class": label,
                    "confidence": round(confidence, 2) 
                })

        return JSONResponse(content={
            "status": "success",
            "total_objects_detected": len(detections),
            "detections": detections
        })
        
    except Exception as e:
        return JSONResponse(status_code=500, content={"message": str(e)})