import io import base64 from fastapi import FastAPI, File, UploadFile from fastapi.responses import JSONResponse from ultralytics import YOLO from PIL import Image # Load model at startup MODEL_PATH = "yolov8x.pt" # 🔹 Change this to "best.pt" later when you download model = YOLO(MODEL_PATH) print("✅ Model loaded with classes:", model.names) # Create FastAPI app app = FastAPI( title="WeedCrop Detection API", description="YOLOv8 API for detecting weeds and crops", version="1.0" ) # ---------- Single endpoint: JSON + Annotated Image ---------- @app.post("/predict") async def predict(file: UploadFile = File(...)): try: # Read image image_bytes = await file.read() img = Image.open(io.BytesIO(image_bytes)).convert("RGB") # Run inference results = model.predict(img, conf=0.25, imgsz=640) # Draw bounding boxes annotated_frame = results[0].plot() # numpy (BGR) annotated_img = Image.fromarray(annotated_frame[..., ::-1]) # Convert BGR → RGB # Encode as base64 buf = io.BytesIO() annotated_img.save(buf, format="PNG") img_bytes = buf.getvalue() img_base64 = base64.b64encode(img_bytes).decode("utf-8") # Collect detections detections = [] for r in results[0].boxes: cls_id = int(r.cls[0]) label = model.names[cls_id] conf = float(r.conf[0]) bbox = [float(x) for x in r.xyxy[0].tolist()] detections.append({ "class_id": cls_id, "label": label, "confidence": conf, "bbox": bbox }) return JSONResponse(content={ "detections": detections, "image_base64": img_base64 }) except Exception as e: return JSONResponse(content={"error": str(e)}, status_code=500)