Приложение: FastAPI-фабрика, ядро DINOv2 (torch.hub ViT-S/14, CLS-эмбеддинги), POST /api/v1/verify

This commit is contained in:
2026-10-07 13:54:40 +03:00
parent 06d1c53f74
commit 01d54a5e03
14 changed files with 827 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""Транспортный слой: маршруты, auth, схемы ответов, маппинг ошибок на HTTP."""
+25
View File
@@ -0,0 +1,25 @@
"""Аутентификация по заголовку X-API-Key: 401 нет ключа, 403 неверный ключ.
Если APP_API_KEY не задан — режим разработки без аутентификации
(warning фиксируется при старте в app/main.py).
"""
from __future__ import annotations
import secrets
from fastapi import Request
from .errors import ApiError
async def require_api_key(request: Request) -> None:
config = request.app.state.config
expected = config.api_key
if not expected:
return
provided = request.headers.get("X-API-Key")
if provided is None:
raise ApiError(401, "UNAUTHORIZED", "заголовок X-API-Key отсутствует")
if not secrets.compare_digest(provided, expected):
raise ApiError(403, "FORBIDDEN", "неверный X-API-Key")
+87
View File
@@ -0,0 +1,87 @@
"""Единый конверт ошибок {"error": {code, message, details, trace_id}}
и маппинг исключений ядра на HTTP-коды в одном месте."""
from __future__ import annotations
import logging
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from ..dino import exceptions as dino_exc
logger = logging.getLogger(__name__)
class ApiError(Exception):
"""Ошибка уровня API с готовым HTTP-статусом и кодом."""
def __init__(self, status_code: int, code: str, message: str, details: object | None = None):
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.details = details
def error_body(
code: str, message: str, trace_id: str | None, details: object | None = None
) -> dict:
return {
"error": {
"code": code,
"message": message,
"details": details,
"trace_id": trace_id,
}
}
def error_response(
status_code: int, code: str, message: str, trace_id: str | None, details: object | None = None
) -> JSONResponse:
return JSONResponse(
status_code=status_code,
content=error_body(code, message, trace_id, details),
)
# Ошибки CV-ядра -> (HTTP-статус, код)
_DINO_ERROR_MAP: dict[type, tuple[int, str]] = {
dino_exc.ImageDecodeError: (400, "IMAGE_DECODE_FAILED"),
dino_exc.ImageTooSmallError: (400, "IMAGE_TOO_SMALL"),
dino_exc.UnsupportedImageFormatError: (415, "UNSUPPORTED_MEDIA_TYPE"),
dino_exc.ModelNotReadyError: (503, "SERVICE_UNAVAILABLE"),
dino_exc.ModelLoadError: (500, "MODEL_LOAD_FAILED"),
}
def _trace_id(request: Request) -> str | None:
return getattr(request.state, "trace_id", None)
def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(ApiError)
async def _api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
return error_response(exc.status_code, exc.code, exc.message, _trace_id(request), exc.details)
@app.exception_handler(dino_exc.DinoError)
async def _dino_error_handler(request: Request, exc: dino_exc.DinoError) -> JSONResponse:
for cls, (status, code) in _DINO_ERROR_MAP.items():
if isinstance(exc, cls):
return error_response(status, code, str(exc), _trace_id(request))
return error_response(500, "INTERNAL", str(exc), _trace_id(request))
@app.exception_handler(RequestValidationError)
async def _validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
return error_response(
422, "VALIDATION_ERROR", "некорректный запрос", _trace_id(request), exc.errors()
)
@app.exception_handler(Exception)
async def _unhandled_handler(request: Request, exc: Exception) -> JSONResponse:
logger.exception("необработанная ошибка", extra={"trace_id": _trace_id(request)})
return error_response(
500, "INTERNAL", "внутренняя ошибка сервиса", _trace_id(request)
)
+112
View File
@@ -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(),
)
+36
View File
@@ -0,0 +1,36 @@
"""Pydantic-схемы JSON-ответов (вход — multipart, разбирается вручную)."""
from __future__ import annotations
from typing import List, Literal
from pydantic import BaseModel, Field
class Thresholds(BaseModel):
match: float = Field(description="Порог best_similarity >= X -> match")
no_match: float = Field(description="Порог best_similarity < X -> no_match")
class VerifyDetails(BaseModel):
references_compared: int = Field(description="Сколько эталонов сравнено")
best_reference_index: int = Field(description="Индекс лучшего эталона (0-based)")
best_similarity: float = Field(description="Лучшая косинусная близость")
similarities: List[float] = Field(description="Близости к каждому эталону по порядку")
thresholds: Thresholds
class VerifyResponse(BaseModel):
verdict: Literal["match", "uncertain", "no_match"] = Field(
description="match — то же здание/памятник; no_match — другое; uncertain — между порогами"
)
is_match: bool = Field(description="Удобный флаг: verdict == match")
confidence: float = Field(description="= best_similarity, косинусная близость 0..1")
details: VerifyDetails
probe_sha256: str = Field(description="SHA-256 проверяемого фото для аудита")
processing_ms: float
class ReadyResponse(BaseModel):
status: Literal["ready", "unavailable"]
reasons: List[str] = Field(default_factory=list, description="Причины неготовности")