from fastapi import FastAPI, UploadFile, File from ultralytics import YOLO from PIL import Image from io import BytesIO import os app = FastAPI() model = YOLO("yolov8n.pt") @app.get("/") def home(): return {"message": "Human detection API is running"} @app.post("/detect-human") async def detect_human(file: UploadFile = File(...)): allowed_types = ["image/jpeg", "image/png", "image/webp"] if file.content_type not in allowed_types: return { "allowed": False, "reason": "invalid_file_type" } contents = await file.read() image = Image.open(BytesIO(contents)).convert("RGB") results = model(image, verbose=False) human_found = False confidence = 0 for result in results: for box in result.boxes: class_id = int(box.cls[0]) label = model.names[class_id] score = float(box.conf[0]) if label == "person" and score > 0.35: human_found = True confidence = score break return { "allowed": human_found, "human_found": human_found, "confidence": confidence, "reason": None if human_found else "no_human_detected" }