import math import os import threading import time import traceback from io import BytesIO from fastapi import FastAPI, File, HTTPException, UploadFile from fastapi.middleware.cors import CORSMiddleware from PIL import Image, ImageOps from pydantic import BaseModel from ultralytics import YOLO app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) MIN_CONFIDENCE = float(os.environ.get("SAEF_MIN_CONFIDENCE", "0.20")) MAX_IMAGE_DIMENSION = int(os.environ.get("SAEF_MAX_IMAGE_DIMENSION", "960")) MODEL_PATH = os.environ.get("SAEF_MODEL_PATH", "best.pt") model = YOLO(MODEL_PATH) # Ultralytics/torch models are not guaranteed safe to call concurrently from # multiple threads on one instance. FastAPI runs sync `def` routes in a # threadpool, so without this lock two simultaneous requests could corrupt # each other's inference. _inference_lock = threading.Lock() responders_db = [] class Responder(BaseModel): name: str phone: str qualifications: str lat: float lng: float class AlertRequest(BaseModel): latitude: float longitude: float condition: str def _to_dict(model_instance: BaseModel) -> dict: # Works whether the deployed pydantic is v1 or v2. dump = getattr(model_instance, "model_dump", None) if callable(dump): return dump() return model_instance.dict() @app.on_event("startup") def warmup() -> None: """Run one dummy inference at startup so the first real request from a responder isn't the one paying for model/JIT warmup latency.""" try: dummy = Image.new("RGB", (640, 640), color=(128, 128, 128)) with _inference_lock: model(dummy, imgsz=640, conf=MIN_CONFIDENCE, verbose=False) except Exception: traceback.print_exc() @app.get("/") def read_root(): return {"status": "SA'EF API is live and running!"} @app.get("/health") def health(): return {"status": "ok", "model_loaded": model is not None} def clamp01(value: float) -> float: return max(0.0, min(1.0, float(value))) def run_wound_detection(image_bytes: bytes) -> dict: started = time.time() try: image = Image.open(BytesIO(image_bytes)) # VERY IMPORTANT for phone camera images. Without this, YOLO can # detect correctly but boxes appear shifted/rotated in-app. image = ImageOps.exif_transpose(image).convert("RGB") except Exception as exc: raise HTTPException(status_code=400, detail=f"Could not decode image: {exc}") # Defensive resize: keeps latency predictable even if a client sends an # unexpectedly large frame, without affecting the normalized coordinates # returned to the app (aspect ratio is preserved). if max(image.size) > MAX_IMAGE_DIMENSION: ratio = MAX_IMAGE_DIMENSION / max(image.size) image = image.resize( (max(1, round(image.width * ratio)), max(1, round(image.height * ratio))) ) image_width, image_height = image.size with _inference_lock: results = model( image, imgsz=640, conf=MIN_CONFIDENCE, verbose=False, ) result = results[0] detections = [] if result.boxes is not None and len(result.boxes) > 0: for i, box in enumerate(result.boxes): confidence = float(box.conf.item()) if confidence < MIN_CONFIDENCE: continue class_id = int(box.cls.item()) class_name = result.names[class_id] # Normalized YOLO center format: x_center, y_center, width, height x_center, y_center, width, height = box.xywhn[0].tolist() # Normalized corner format: x_min, y_min, x_max, y_max x_min, y_min, x_max, y_max = box.xyxyn[0].tolist() detections.append( { "id": i, "wound_type": class_name, "confidence": confidence, "x_center": clamp01(x_center), "y_center": clamp01(y_center), "width": clamp01(width), "height": clamp01(height), "x_min": clamp01(x_min), "y_min": clamp01(y_min), "x_max": clamp01(x_max), "y_max": clamp01(y_max), } ) if not detections: return { "status": "not_found", "message": "No confident wound detected", "image_width": image_width, "image_height": image_height, "detections": [], "latency_ms": round((time.time() - started) * 1000, 2), } detections.sort(key=lambda item: item["confidence"], reverse=True) best = detections[0] return { "status": "success", "wound_type": best["wound_type"], "confidence": best["confidence"], "x_center": best["x_center"], "y_center": best["y_center"], "width": best["width"], "height": best["height"], "x_min": best["x_min"], "y_min": best["y_min"], "x_max": best["x_max"], "y_max": best["y_max"], "image_width": image_width, "image_height": image_height, "detections": detections, "latency_ms": round((time.time() - started) * 1000, 2), } # NOTE: these routes are intentionally plain `def`, not `async def`. YOLO # inference is a blocking, CPU-bound call — running it inside an `async def` # route would execute it directly on the single event loop thread and stall # every other in-flight request (health checks, other responders' frames) # until it finished. A sync `def` route is automatically dispatched by # FastAPI to a worker threadpool, so one slow inference no longer blocks # the whole server. # # These also now take the JPEG as a raw multipart file instead of a # base64-encoded JSON string. Base64 inflates the payload by ~33% and costs # encode/decode CPU time on both ends for zero benefit on a binary upload — # cutting it out is a straightforward latency win on every single frame. @app.post("/predict") def predict(image: UploadFile = File(...)): try: image_bytes = image.file.read() return run_wound_detection(image_bytes) except HTTPException: raise except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/track") def track(image: UploadFile = File(...)): try: image_bytes = image.file.read() return run_wound_detection(image_bytes) except HTTPException: raise except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/register-responder") def register_responder(responder: Responder): responder_dict = _to_dict(responder) responder_dict["active"] = True responders_db.append(responder_dict) return { "success": True, "responder": responder_dict, } @app.post("/alert-nearby") def alert_nearby(req: AlertRequest): threshold_km = 5.0 nearby = [] for r in responders_db: if not r.get("active"): continue d_lat = (r["lat"] - req.latitude) * 111.0 d_lng = (r["lng"] - req.longitude) * 111.0 dist = math.sqrt(d_lat**2 + d_lng**2) if dist <= threshold_km: nearby.append(r) return { "success": True, "notifiedCount": len(nearby), "responders": nearby, }