luigui300's picture
despertador del backend
f45c6a7
Raw History Blame Contribute Delete
7.15 kB
"""
FastAPI backend β€” LSP Facial Expression Recognition
Deployed on Hugging Face Spaces (CPU only).
Endpoints
---------
GET /health β†’ {"status": "ok", "model": "loaded"}
POST /predict β†’ {"top3": [{"clase": str, "confianza": float}, ...]}
"""
import os
import tempfile
import time
from contextlib import asynccontextmanager
from pathlib import Path
import torch
import torch.nn.functional as F
from fastapi import FastAPI, File, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from torch_geometric.data import Batch
from model import load_model
from preprocessing import build_anatomic_edge_index, preprocess_video_tta
# ── Configuration ──────────────────────────────────────────────────────────────
DEVICE = torch.device("cpu")
MODEL_PATH = Path(__file__).parent / "best_model.pth"
LABELS = [
"ANNOYED",
"BORED",
"CRYING",
"DISGUST",
"HAPPY",
"I_DON'T_KNOW",
"LET'S_SEE",
"NO",
"SAD",
"SMELLS_BAD",
"SURPRISE",
"THIEF",
"TIRED",
"YES",
]
# Shared state populated during startup
_state: dict = {}
# ── Lifespan β€” load model once at startup ─────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
print(f"[startup] Loading model from {MODEL_PATH} ...")
if not MODEL_PATH.exists():
raise FileNotFoundError(
f"Checkpoint not found: {MODEL_PATH}\n"
"Place best_model.pth in the same directory as app.py."
)
model = load_model(str(MODEL_PATH), DEVICE)
edge_index = build_anatomic_edge_index()
print(f"[startup] Edge index built: {edge_index.shape[1]} edges")
_state["model"] = model
_state["edge_index"] = edge_index
yield # application runs
_state.clear()
print("[shutdown] Resources released.")
# ── Application ────────────────────────────────────────────────────────────────
app = FastAPI(
title="LSP Facial Expression API",
description="Peruvian Sign Language facial expression recognition (14 classes).",
version="1.0.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ── Endpoints ──────────────────────────────────────────────────────────────────
@app.get("/health")
def health():
"""Health check β€” confirms the model is loaded and ready."""
return {"status": "ok", "model": "loaded"}
@app.get("/warmup")
def warmup():
"""
Warmup endpoint β€” verifies model is loaded and ready for inference.
Call this before the first prediction to wake up the server.
"""
if "model" not in _state or "edge_index" not in _state:
raise HTTPException(
status_code=503,
detail="Model not loaded yet"
)
return {"status": "ready", "model": "loaded"}
@app.post("/predict")
async def predict(video: UploadFile = File(...)):
"""
Predict the top-3 facial expressions from a short video clip.
Parameters
----------
video : video file (mp4 / mov, ~2 s, 30 fps) sent as multipart/form-data
Returns
-------
{"top3": [{"clase": str, "confianza": float, "confianza_norm": float}, ...], "inference_ms": float}
confianza : raw softmax probability (0–100), global across 14 classes.
confianza_norm: re-normalized within top-3 (conditioned on being top-3).
inference_ms : server-side inference time in milliseconds.
Errors
------
422 : preprocessing failed (no face detected, unreadable video, etc.)
500 : inference failed (unexpected model error)
"""
# Determine file suffix for the temp file
suffix = ".mp4"
if video.filename:
ext = Path(video.filename).suffix.lower()
if ext in {".mp4", ".mov", ".avi", ".mkv", ".webm"}:
suffix = ext
tmp_path: str | None = None
try:
# Save uploaded video to a temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
tmp.write(await video.read())
tmp_path = tmp.name
# ── Preprocessing con TTA x5 ───────────────────────────────────────
try:
variants = preprocess_video_tta(tmp_path, _state["edge_index"])
except Exception as exc:
raise HTTPException(
status_code=422,
detail=f"Preprocessing failed: {exc}",
)
# ── Inference β€” promedio de logits sobre 5 variantes ───────────────
try:
model = _state["model"]
t_start = time.perf_counter()
logits_sum = None
for video_tensor, graphs in variants:
video_tensor = video_tensor.to(DEVICE)
batched_graphs = [
Batch.from_data_list([g]).to(DEVICE) for g in graphs
]
with torch.no_grad():
logits, _ = model(video_tensor, batched_graphs)
logits_sum = logits if logits_sum is None else logits_sum + logits
probs = F.softmax(logits_sum, dim=1)[0] # (14,)
inference_ms = round((time.perf_counter() - t_start) * 1000, 1)
top3_indices = probs.argsort(descending=True)[:3].tolist()
top3 = [
{
"clase": LABELS[i],
"confianza": round(probs[i].item() * 100, 1),
}
for i in top3_indices
]
# Re-normalize confianza within top-3
suma_top3 = sum(p["confianza"] for p in top3)
if suma_top3 > 0:
for p in top3:
p["confianza_norm"] = round((p["confianza"] / suma_top3) * 100, 1)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(
status_code=500,
detail=f"Inference failed: {exc}",
)
return {"top3": top3, "inference_ms": inference_ms}
finally:
# Always clean up the temp file
if tmp_path and os.path.exists(tmp_path):
os.remove(tmp_path)
# ── Entry point (local dev) ────────────────────────────────────────────────────
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app:app",
host="0.0.0.0",
port=7860,
reload=False,
)