Fix focus endpoint crash

This commit is contained in:
2026-04-11 17:12:51 +02:00
parent ecbf948a74
commit 19a5ac16b7
2 changed files with 17 additions and 5 deletions

View File

@@ -1,3 +1,5 @@
from io import BytesIO
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import HTMLResponse, StreamingResponse
from app.config import settings
@@ -113,7 +115,18 @@ async def focus(
try:
payload = await file.read()
return process_image(payload, file.filename or "upload", buffer_ratio=buffer_ratio, detector=detector)
result = process_image(payload, file.filename or "upload", buffer_ratio=buffer_ratio, detector=detector)
return {
"filename": result["filename"],
"detector": result["detector"],
"method": result["method"],
"buffer_ratio": result["buffer_ratio"],
"detected_bbox": result["detected_bbox"],
"square_bbox": result["square_bbox"],
"source_size": result["source_size"],
"crop_data_url": result["crop_data_url"],
"annotated_data_url": result["annotated_data_url"],
}
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -129,6 +142,6 @@ async def focus_image(
try:
payload = await file.read()
result = process_image(payload, file.filename or "upload", buffer_ratio=buffer_ratio, detector=detector)
return StreamingResponse(result["crop_bytes_io"], media_type=result["mime_type"])
return StreamingResponse(BytesIO(result["crop_bytes"]), media_type=result["mime_type"])
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc

View File

@@ -1,7 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
from typing import Any
@@ -91,7 +90,7 @@ def detect_face(image: np.ndarray) -> BBox | None:
faces = FACE_CASCADE.detectMultiScale(gray, scaleFactor=1.08, minNeighbors=5, minSize=(24, 24))
if len(faces) == 0:
return None
x, y, w, h = max((map(int, face) for face in faces), key=lambda rect: rect[2] * rect[3])
x, y, w, h = max((tuple(map(int, face)) for face in faces), key=lambda rect: rect[2] * rect[3])
return BBox(x=x, y=y, w=w, h=h)
@@ -192,5 +191,5 @@ def process_image(image_bytes: bytes, filename: str, buffer_ratio: float = 0.15,
"crop_data_url": _data_url(crop_bytes, mime_type),
"annotated_data_url": _data_url(annotated_bytes, mime_type),
"mime_type": mime_type,
"crop_bytes_io": BytesIO(crop_bytes),
"crop_bytes": crop_bytes,
}