File size: 1,228 Bytes
8892aa7
 
 
 
f977726
 
 
8892aa7
 
f977726
 
8892aa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f977726
 
8892aa7
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
import ultralytics.engine.results
from fastapi import FastAPI, UploadFile
from PIL import Image
from yolo_model import YoloModel

app = FastAPI()

model = YoloModel("SHOU-ISD/fire-and-smoke", "yolov8n.pt")


@app.get("/")
async def info():
    return {
        "model": f"Fire and Smoke Detection",
        "version": "1.0",
    }


@app.post("/predict")
async def predict(image: UploadFile):
    if image.content_type not in ["image/jpeg", "image/png"]:
        return {"error": "Invalid file type"}

    im = Image.open(image.file)
    res = model.detect(im)
    return {
        "list": [
            detect_item(box, res_item.names)
            for res_item in res
            for box in res_item.boxes
        ]
    }


CXYWH = {
    "cx": float,
    "cy": float,
    "w": float,
    "h": float,
}

DetectItem = {
    "category": str,
    "bbox": CXYWH,
    "score": float,
}


def detect_item(box: ultralytics.engine.results.Boxes, mapping: dict[int, str]) -> DetectItem:
    cx, cy, w, h = box.xywhn.tolist()[0]
    return {
        "category": mapping[int(box.cls)],
        "bbox": {
            "cx": cx,
            "cy": cy,
            "w": w,
            "h": h,
        },
        "score": float(box.conf),
    }