Приложение: FastAPI-фабрика, ядро DINOv2 (torch.hub ViT-S/14, CLS-эмбеддинги), POST /api/v1/verify
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"""Маршруты: POST /api/v1/verify, GET /health, GET /ready.
|
||||
|
||||
Multipart разбирается вручную (повторяемая часть reference), поэтому контракт
|
||||
описан в docs/01, а не в автогенерируемой OpenAPI-схеме.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
from ..dino.exceptions import ModelNotReadyError
|
||||
from .deps import require_api_key
|
||||
from .errors import ApiError
|
||||
from .schemas import ReadyResponse, VerifyDetails, VerifyResponse, Thresholds
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/v1/verify", response_model=VerifyResponse)
|
||||
async def verify(request: Request, _: None = Depends(require_api_key)) -> VerifyResponse:
|
||||
if not request.app.state.ready:
|
||||
raise ModelNotReadyError("модель не загружена; см. GET /ready")
|
||||
|
||||
form = await request.form()
|
||||
config = request.app.state.config
|
||||
|
||||
probe_part = form.get("probe")
|
||||
if not isinstance(probe_part, UploadFile):
|
||||
raise ApiError(422, "VALIDATION_ERROR", "multipart-часть 'probe' с файлом обязательна")
|
||||
reference_parts = form.getlist("reference")
|
||||
if not reference_parts:
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR", "нужен хотя бы один эталон: multipart-часть 'reference'"
|
||||
)
|
||||
if len(reference_parts) > config.max_references:
|
||||
raise ApiError(
|
||||
400,
|
||||
"TOO_MANY_REFERENCES",
|
||||
f"эталонов {len(reference_parts)}, максимум {config.max_references}",
|
||||
)
|
||||
for part in reference_parts:
|
||||
if not isinstance(part, UploadFile):
|
||||
raise ApiError(422, "VALIDATION_ERROR", "части 'reference' должны быть файлами")
|
||||
|
||||
probe_bytes = await _read_bounded(probe_part, config.max_image_bytes)
|
||||
reference_blobs = [
|
||||
await _read_bounded(part, config.max_image_bytes) for part in reference_parts
|
||||
]
|
||||
|
||||
service = request.app.state.service
|
||||
outcome = await run_in_threadpool(service.verify, probe_bytes, reference_blobs)
|
||||
result = outcome.comparison
|
||||
logger.info(
|
||||
"verify завершён",
|
||||
extra={
|
||||
"verdict": result.verdict,
|
||||
"best_similarity": round(result.best_similarity, 4),
|
||||
"references": len(reference_blobs),
|
||||
"processing_ms": round(outcome.processing_ms, 1),
|
||||
},
|
||||
)
|
||||
return VerifyResponse(
|
||||
verdict=result.verdict,
|
||||
is_match=result.is_match,
|
||||
confidence=result.best_similarity,
|
||||
details=VerifyDetails(
|
||||
references_compared=len(reference_blobs),
|
||||
best_reference_index=result.best_reference_index,
|
||||
best_similarity=result.best_similarity,
|
||||
similarities=list(result.similarities),
|
||||
thresholds=Thresholds(
|
||||
match=config.threshold_match, no_match=config.threshold_no_match
|
||||
),
|
||||
),
|
||||
probe_sha256=outcome.probe_sha256,
|
||||
processing_ms=outcome.processing_ms,
|
||||
)
|
||||
|
||||
|
||||
async def _read_bounded(part: UploadFile, max_bytes: int) -> bytes:
|
||||
data = await part.read()
|
||||
if len(data) > max_bytes:
|
||||
raise ApiError(
|
||||
413,
|
||||
"PAYLOAD_TOO_LARGE",
|
||||
f"файл {part.filename!r}: {len(data)} байт, максимум {max_bytes}",
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/health", include_in_schema=False)
|
||||
async def health() -> dict:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/ready", response_model=ReadyResponse, include_in_schema=False)
|
||||
async def ready(request: Request):
|
||||
if request.app.state.ready:
|
||||
return ReadyResponse(status="ready")
|
||||
return JSONResponse(
|
||||
status_code=503,
|
||||
content=ReadyResponse(
|
||||
status="unavailable", reasons=list(request.app.state.ready_reasons)
|
||||
).model_dump(),
|
||||
)
|
||||
Reference in New Issue
Block a user