File size: 1,855 Bytes
717b5e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from ultralytics import YOLO
from PIL import Image
import io
import os

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Download and cache model on startup
from huggingface_hub import hf_hub_download

model_path = hf_hub_download(
    repo_id="Decizez/yolov-corrosion-detection",
    filename="Lite_YOLO8_v1.pt"
)

model = YOLO(model_path)
print("✅ Model loaded successfully")

@app.get("/health")
async def health():
    return {"status": "ok"}

@app.post("/detect")
async def detect(file: UploadFile = File(...)):
    contents = await file.read()
    image = Image.open(io.BytesIO(contents)).convert("RGB")
    w, h = image.width, image.height

    results = model(image)

    detections = []
    for result in results:
        boxes = result.boxes
        if boxes is not None:
            for box in boxes:
                conf = float(box.conf[0])
                if conf > 0.3:
                    x1, y1, x2, y2 = box.xyxy[0].tolist()
                    detections.append({
                        "label": "Corrosion Detected",
                        "confidence": round(conf * 100, 1),
                        "area_percent": round(
                            ((x2 - x1) * (y2 - y1)) / (w * h) * 100, 1
                        ),
                        "box": {
                            "x": round(x1 / w * 100, 1),
                            "y": round(y1 / h * 100, 1),
                            "width": round((x2 - x1) / w * 100, 1),
                            "height": round((y2 - y1) / h * 100, 1)
                        }
                    })

    return {
        "detections": detections,
        "frame_size": {"w": w, "h": h}
    }