File size: 7,639 Bytes
d4d725d a437062 a82146b d4d725d 2ed8ce7 a82146b d4d725d a437062 d4d725d a82146b d4d725d 7843d77 5d0c942 a82146b 5d0c942 a82146b 5d0c942 d4d725d d639e8e 6cc7005 d639e8e 8960a17 d4d725d 7843d77 a437062 7843d77 d4d725d 7843d77 2ed8ce7 d4d725d 7843d77 5d0c942 f6b11b9 d4d725d 7843d77 5d0c942 7843d77 5d0c942 7843d77 5d0c942 d4d725d a437062 5d0c942 a437062 5d0c942 a437062 d4d725d 5d0c942 f6b11b9 5d0c942 a437062 5d0c942 a437062 d4d725d 2ed8ce7 d639e8e a82146b 5d0c942 a82146b d4d725d a82146b 7843d77 a82146b 5d0c942 a82146b 5d0c942 a82146b 5d0c942 a82146b 5d0c942 a82146b 5d0c942 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | 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,
} |