Emperor777's picture
Deploy YOLOv11 FastAPI cocoa disease service
03b9474
Raw History Blame Contribute Delete
1.42 kB
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
from ultralytics import YOLO
from PIL import Image
import io
app = FastAPI(
title="Cocoa Disease Detection API (YOLOv11)",
description="FastAPI service for cocoa disease detection using YOLOv11",
version="1.0.0"
)
# Load model once at startup
model = YOLO("cocoa_disease_yolov11.pt")
@app.get("/")
def health_check():
return {"status": "ok", "model": "YOLOv11 Cocoa Disease Detector"}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
try:
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
results = model(image, conf=0.25)[0]
detections = []
if results.boxes is not None:
for box in results.boxes:
detections.append({
"class_id": int(box.cls),
"class_name": results.names[int(box.cls)],
"confidence": float(box.conf),
"bbox": box.xyxy.tolist()[0] # [x1, y1, x2, y2]
})
return JSONResponse(
content={
"num_detections": len(detections),
"detections": detections
}
)
except Exception as e:
return JSONResponse(
status_code=500,
content={"error": str(e)}
)