Upload backend/api/routes/analyze.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""api/routes/analyze.py β Sentinel-AI========================================POST /api/v1/analyze-frame
Accepts a raw image upload (JPEG/PNG/WebP), runs the full inference pipeline: 1. MTCNN detects faces β aligns the highest-confidence face to 112Γ112 2. AdaFace embeds the aligned face β 512-D vector 3. FAISS nearest-neighbour search β cosine similarity + attributes 4. cascadeflow + Gemini generates the security alert
Returns the JSON payload defined in AnalyzeFrameResponse.
Blocking notes--------------PyTorch inference, PIL decoding, and FAISS search are all CPU/GPU blockingoperations. Running them inside an async function directly would stall theuvicorn event loop. We therefore use two strategies:
β’ The entire CV+FAISS pipeline is wrapped in asyncio.to_thread() so it executes in the default thread-pool and releases the event loop. β’ The Gemini call (generate_alert) is natively async and runs normally."""
from __future__ import annotations
import asyncioimport ioimport osfrom typing import Annotated, Any
import torchimport torchvision.transforms as Tfrom fastapi import APIRouter, File, HTTPException, UploadFilefrom PIL import Image, UnidentifiedImageError
from api.schemas import AnalyzeFrameResponse, CascadeflowMetricsfrom core.faiss_store import search_by_vectorfrom core.gemini_agent import generate_alertfrom core.models import ( DEVICE, FACE_CROP_MARGIN, adaface_embed, align_face, detect_faces, load_adaface, square_context_crop,)from core.paths import env_float, env_int
router = APIRouter()
# Reject oversized uploads before decoding them into memory.MAX_UPLOAD_BYTES = env_int("MAX_UPLOAD_BYTES", 10 * 1024 * 1024)
# MTCNN probability below which a detection is discarded.DETECTION_CONFIDENCE = env_float("DETECTION_CONFIDENCE", 0.6)
# Cosine similarity below which the nearest neighbour is *not* considered a# match. With the index and the query both using MTCNN landmark alignment,# correct identities scored ~0.98 (min 0.90 over a 48-image sample) while# unrelated portraits stayed below ~0.35.MATCH_SIMILARITY_THRESHOLD = env_float("MATCH_SIMILARITY_THRESHOLD", 0.50)
# AdaFace input normalisation (must match build_index.py)_FACE_TRANSFORM = T.Compose([ T.Resize((112, 112)), T.ToTensor(), T.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),])
class InvalidImageError(ValueError): """Raised when the uploaded bytes are not a decodable image."""
def _crop_face(image: Image.Image, face: dict) -> torch.Tensor: """ Produce an AdaFace-ready 3x112x112 tensor for one detected face.
Landmark alignment is the default: it matches the preprocessing used to build the index. If the warp fails for a malformed landmark set, fall back to a context-expanded square crop. """ try: aligned = align_face(image, face.get("landmarks", [])) except Exception: aligned = square_context_crop(image, face["box"], margin=FACE_CROP_MARGIN) return _FACE_TRANSFORM(aligned)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Blocking CV + FAISS pipeline β runs in a thread-pool via asyncio.to_thread# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _run_cv_pipeline(raw_bytes: bytes) -> dict[str, Any]: """ Decode image, detect faces, embed the best face, search FAISS.
Returns a plain dict to keep the result serialisable across threads: status : "no_face" | "no_match" | "ok" faces_detected : int detection_score : float attributes : list[str] similarity : float """ # ββ 1. Decode (invalid uploads must not surface as a 500) βββββββββββββββββ try: with Image.open(io.BytesIO(raw_bytes)) as opened: image = opened.convert("RGB") except (UnidentifiedImageError, OSError, ValueError) as exc: raise InvalidImageError("Uploaded file is not a valid image.") from exc
# ββ 2. Detect faces with MTCNN ββββββββββββββββββββββββββββββββββββββββββββ try: faces = detect_faces(image, confidence_threshold=DETECTION_CONFIDENCE) except Exception as exc: # model/runtime error raise RuntimeError(f"Face detection failed: {exc}") from exc
if not faces: return { "status": "no_face", "faces_detected": 0, "detection_score": 0.0, "attributes": [], "similarity": 0.0, }
best = faces[0] # sorted by score faces_detected = len(faces)
# ββ 3. Embed best face ββββββββββββββββββββββββββββββββββββββββββββββββββββ embedder = load_adaface(device=DEVICE) face_tensor = _crop_face(image, best) # (3, 112, 112) embedding = adaface_embed(face_tensor, embedder) # (512,) float32 CPU
# ββ 4. FAISS search βββββββββββββββββββββββββββββββββββββββββββββββββββββββ results = search_by_vector(embedding.numpy(), top_k=1) if not results: return { "status": "no_match", "faces_detected": faces_detected, "detection_score": round(float(best["score"]), 4), "attributes": [], "similarity": 0.0, }
top_match = results[0] similarity = float(top_match["similarity"])
# ββ 5. Threshold: a nearest neighbour is not automatically a match ββββββββ if similarity < MATCH_SIMILARITY_THRESHOLD: return { "status": "no_match", "faces_detected": faces_detected, "detection_score": round(float(best["score"]), 4), "attributes": [], "similarity": similarity, }
return { "status": "ok", "faces_detected": faces_detected, "detection_score": round(float(best["score"]), 4), "attributes": top_match["attributes"], "similarity": similarity, }
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Endpoint# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@router.post( "/analyze-frame", response_model=AnalyzeFrameResponse, summary="Analyse a camera frame: detect faces, embed, match, and generate alert",)async def analyze_frame( file: Annotated[UploadFile, File(description="Raw image file (JPEG, PNG, WebP, β¦)")],) -> AnalyzeFrameResponse: """ Processes a live camera frame through the full Sentinel-AI pipeline.
- **file**: raw image file (JPEG, PNG, WebP, β¦), max 10 MB by default """ # ββ Read upload bytes, enforcing a hard size cap ββββββββββββββββββββββββββ try: raw_bytes = await file.read(MAX_UPLOAD_BYTES + 1) except Exception: raise HTTPException(status_code=422, detail="Could not read uploaded file.")
if not raw_bytes: raise HTTPException(status_code=422, detail="Uploaded file is empty.")
if len(raw_bytes) > MAX_UPLOAD_BYTES: raise HTTPException( status_code=413, detail=f"Uploaded file exceeds the {MAX_UPLOAD_BYTES} byte limit.", )
# ββ CV + FAISS in thread-pool (blocking) ββββββββββββββββββββββββββββββββββ try: cv_result: dict[str, Any] = await asyncio.to_thread(_run_cv_pipeline, raw_bytes) except InvalidImageError as exc: raise HTTPException(status_code=422, detail=str(exc)) except Exception: # Never leak stack traces / absolute paths / internal model details. raise HTTPException(status_code=500, detail="Inference pipeline error.")
# ββ Early exits βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ if cv_result["status"] == "no_face": return AnalyzeFrameResponse( status="no_face_detected", faces_detected=0, match_confidence=None, matched_attributes=[], agent_report=None, cascadeflow_metrics=None, )
if cv_result["status"] == "no_match": return AnalyzeFrameResponse( status="no_match_found", faces_detected=cv_result["faces_detected"], match_confidence=None, matched_attributes=[], agent_report=( "No identity in the database exceeds the " f"{MATCH_SIMILARITY_THRESHOLD:.2f} cosine-similarity threshold." ), cascadeflow_metrics=None, )
# ββ Gemini alert (async, no blocking) ββββββββββββββββββββββββββββββββββββ agent_result: dict[str, Any] = await generate_alert( attributes=cv_result["attributes"], similarity=cv_result["similarity"], )
cf_raw = agent_result.get("cascadeflow_metrics", {}) cf_metrics = CascadeflowMetrics( latency_ms=cf_raw.get("latency_ms", 0.0), cost_usd=cf_raw.get("cost_usd", 0.0), )
clamped_confidence = min(max(float(cv_result["similarity"]), 0.0), 1.0)
return AnalyzeFrameResponse( status="success", faces_detected=cv_result["faces_detected"], match_confidence=round(clamped_confidence, 4), matched_attributes=cv_result["attributes"], agent_report=agent_result.get("agent_report", ""), cascadeflow_metrics=cf_metrics, )backend/api/routes/analyze.pyAdded+256