Приложение: FastAPI-фабрика, ядро DINOv2 (torch.hub ViT-S/14, CLS-эмбеддинги), POST /api/v1/verify
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""dinoV2 — stateless-сервис сравнения фотографий зданий и памятников на эмбеддингах DINOv2."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Транспортный слой: маршруты, auth, схемы ответов, маппинг ошибок на HTTP."""
|
||||
@@ -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")
|
||||
@@ -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)
|
||||
)
|
||||
@@ -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(),
|
||||
)
|
||||
@@ -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="Причины неготовности")
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
"""Конфигурация сервиса: frozen-dataclass из переменных окружения, fail-fast при ошибках.
|
||||
|
||||
Все параметры и пороги задаются переменными окружения (см. .env.example);
|
||||
магических чисел в коде нет.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
class ConfigError(ValueError):
|
||||
"""Некорректное значение переменной окружения."""
|
||||
|
||||
|
||||
def _read(name: str, default: str | None = None) -> str | None:
|
||||
"""Читает переменную окружения; пустая строка приравнивается к отсутствию."""
|
||||
value = os.environ.get(name)
|
||||
if value is not None and value.strip() == "":
|
||||
return default
|
||||
return value if value is not None else default
|
||||
|
||||
|
||||
def _to_int(name: str, raw: str | None, default: int, *, lo: int, hi: int) -> int:
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ConfigError(f"{name}: ожидается целое, получено {raw!r}") from exc
|
||||
if not lo <= value <= hi:
|
||||
raise ConfigError(f"{name}: {value} вне диапазона [{lo}, {hi}]")
|
||||
return value
|
||||
|
||||
|
||||
def _to_float(name: str, raw: str | None, default: float, *, lo: float, hi: float) -> float:
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
value = float(raw)
|
||||
except ValueError as exc:
|
||||
raise ConfigError(f"{name}: ожидается число, получено {raw!r}") from exc
|
||||
if not lo <= value <= hi:
|
||||
raise ConfigError(f"{name}: {value} вне диапазона [{lo}, {hi}]")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
"""Иммутуемая конфигурация; создаётся через Config.from_env()."""
|
||||
|
||||
api_key: str | None
|
||||
host: str
|
||||
port: int
|
||||
workers: int
|
||||
|
||||
model_name: str
|
||||
device: str
|
||||
image_size: int
|
||||
torch_home: str | None
|
||||
|
||||
max_image_bytes: int
|
||||
min_image_dim: int
|
||||
max_references: int
|
||||
|
||||
threshold_match: float
|
||||
threshold_no_match: float
|
||||
|
||||
log_level: str
|
||||
|
||||
@property
|
||||
def max_body_bytes(self) -> int:
|
||||
"""Верхняя граница тела запроса /verify: все изображения + запас на multipart-обвязку."""
|
||||
overhead = 64 * 1024 # границы частей и заголовки
|
||||
return (self.max_references + 1) * self.max_image_bytes + overhead
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "Config":
|
||||
config = cls(
|
||||
api_key=_read("APP_API_KEY"),
|
||||
host=_read("HOST", "0.0.0.0"),
|
||||
port=_to_int("PORT", _read("PORT"), 8000, lo=1, hi=65535),
|
||||
workers=_to_int("WORKERS", _read("WORKERS"), 1, lo=1, hi=16),
|
||||
model_name=_read("DINO_MODEL_NAME", "dinov2_vits14"),
|
||||
device=_read("DINO_DEVICE", "cpu"),
|
||||
image_size=_to_int("DINO_IMAGE_SIZE", _read("DINO_IMAGE_SIZE"), 224, lo=56, hi=952),
|
||||
torch_home=_read("TORCH_HOME"),
|
||||
max_image_bytes=_to_int(
|
||||
"MAX_IMAGE_MB", _read("MAX_IMAGE_MB"), 10, lo=1, hi=100
|
||||
)
|
||||
* 1024
|
||||
* 1024,
|
||||
min_image_dim=_to_int("MIN_IMAGE_DIM", _read("MIN_IMAGE_DIM"), 32, lo=8, hi=1024),
|
||||
max_references=_to_int(
|
||||
"MAX_REFERENCES_PER_REQUEST", _read("MAX_REFERENCES_PER_REQUEST"), 8, lo=1, hi=64
|
||||
),
|
||||
threshold_match=_to_float(
|
||||
"THRESHOLD_MATCH", _read("THRESHOLD_MATCH"), 0.55, lo=0.0, hi=1.0
|
||||
),
|
||||
threshold_no_match=_to_float(
|
||||
"THRESHOLD_NO_MATCH", _read("THRESHOLD_NO_MATCH"), 0.40, lo=0.0, hi=1.0
|
||||
),
|
||||
log_level=(_read("LOG_LEVEL", "INFO") or "INFO").upper(),
|
||||
)
|
||||
config.validate_cross()
|
||||
return config
|
||||
|
||||
def validate_cross(self) -> None:
|
||||
"""Связные проверки, невозможные поодиночке в from_env()."""
|
||||
# patch_size DINOv2 = 14: вход обязан быть кратен, иначе модель не соберёт токены
|
||||
if self.image_size % 14 != 0:
|
||||
raise ConfigError(
|
||||
f"DINO_IMAGE_SIZE: {self.image_size} должно быть кратно 14 (patch size DINOv2)"
|
||||
)
|
||||
if self.threshold_no_match >= self.threshold_match:
|
||||
raise ConfigError(
|
||||
"THRESHOLD_NO_MATCH должен быть строго меньше THRESHOLD_MATCH, "
|
||||
f"получено {self.threshold_no_match} >= {self.threshold_match}"
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
"""CV-ядро: эмбеддинги DINOv2 и сравнение. Не импортирует FastAPI и не знает HTTP."""
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Чистая логика решения: косинусные близости -> вердикт. Без I/O и без модели."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
VERDICT_MATCH = "match"
|
||||
VERDICT_UNCERTAIN = "uncertain"
|
||||
VERDICT_NO_MATCH = "no_match"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ComparisonResult:
|
||||
"""Итог сравнения проверяемого фото с эталонами."""
|
||||
|
||||
verdict: str # match | uncertain | no_match
|
||||
is_match: bool
|
||||
best_reference_index: int
|
||||
best_similarity: float
|
||||
similarities: tuple[float, ...]
|
||||
|
||||
|
||||
def cosine_similarities(probe: "numpy.ndarray", references: "numpy.ndarray") -> list[float]:
|
||||
"""Близости probe к каждой строке references; входы — L2-нормированные векторы."""
|
||||
sims = references @ probe
|
||||
return [float(s) for s in sims]
|
||||
|
||||
|
||||
def decide(
|
||||
similarities: Sequence[float], threshold_match: float, threshold_no_match: float
|
||||
) -> ComparisonResult:
|
||||
"""Вердикт по лучшему совпадению: эталоны сняты с разных ракурсов и в разное
|
||||
время, поэтому агрегат — максимум близости по всем эталонам.
|
||||
"""
|
||||
if not similarities:
|
||||
raise ValueError("similarities пуст: нужен хотя бы один эталон")
|
||||
best_index = max(range(len(similarities)), key=lambda i: similarities[i])
|
||||
best = float(similarities[best_index])
|
||||
if best >= threshold_match:
|
||||
verdict = VERDICT_MATCH
|
||||
elif best < threshold_no_match:
|
||||
verdict = VERDICT_NO_MATCH
|
||||
else:
|
||||
verdict = VERDICT_UNCERTAIN
|
||||
return ComparisonResult(
|
||||
verdict=verdict,
|
||||
is_match=verdict == VERDICT_MATCH,
|
||||
best_reference_index=best_index,
|
||||
best_similarity=best,
|
||||
similarities=tuple(float(s) for s in similarities),
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Исключения CV-ядра; на HTTP маппятся в app/api/errors.py, не здесь."""
|
||||
|
||||
|
||||
class DinoError(Exception):
|
||||
"""Базовый класс ошибок ядра."""
|
||||
|
||||
|
||||
class ImageDecodeError(DinoError):
|
||||
"""Байты не декодируются как изображение."""
|
||||
|
||||
|
||||
class UnsupportedImageFormatError(DinoError):
|
||||
"""Формат изображения не входит в поддерживаемые (JPEG/PNG/WebP)."""
|
||||
|
||||
|
||||
class ImageTooSmallError(DinoError):
|
||||
"""Изображение меньше минимальной стороны."""
|
||||
|
||||
|
||||
class ModelNotReadyError(DinoError):
|
||||
"""Модель ещё не загружена (например, упала при старте)."""
|
||||
|
||||
|
||||
class ModelLoadError(DinoError):
|
||||
"""Модель не удалось загрузить; фиксируется в ready_reasons при старте."""
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Обёртка DINOv2: загрузка через torch.hub, препроцессинг, батч-эмбеддинги.
|
||||
|
||||
Импорт torch сознательно ленивый (внутри load()): тесты с подменённым
|
||||
эмбеддером не платят за импорт тяжёлой библиотеки.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Sequence
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from .exceptions import ModelLoadError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Нормализация ImageNet — стандарт для предобученных DINOv2
|
||||
_IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
||||
_IMAGENET_STD = (0.229, 0.224, 0.225)
|
||||
|
||||
|
||||
class DinoEmbedder:
|
||||
"""Вычисляет L2-нормированные CLS-эмбеддинги изображений.
|
||||
|
||||
Соглашение (используется и фейком в тестах): load() один раз, затем
|
||||
embed(images) -> np.ndarray (N, D) float32 с единичной нормой строк.
|
||||
"""
|
||||
|
||||
def __init__(self, model_name: str, device: str, image_size: int, torch_home: str | None = None):
|
||||
self.model_name = model_name
|
||||
self.device = device
|
||||
self.image_size = image_size
|
||||
self.torch_home = torch_home
|
||||
self._model = None
|
||||
self._transform = None
|
||||
|
||||
@property
|
||||
def loaded(self) -> bool:
|
||||
return self._model is not None
|
||||
|
||||
def load(self) -> None:
|
||||
"""Загружает модель и препроцессинг; идемпотентна. Ошибки -> ModelLoadError."""
|
||||
if self._model is not None:
|
||||
return
|
||||
try:
|
||||
if self.torch_home:
|
||||
os.environ["TORCH_HOME"] = self.torch_home
|
||||
import torch
|
||||
from torchvision import transforms
|
||||
|
||||
device = self._resolve_device(torch)
|
||||
logger.info(
|
||||
"загрузка модели DINOv2",
|
||||
extra={"model": self.model_name, "device": device},
|
||||
)
|
||||
repo = "facebookresearch/dinov2"
|
||||
model = torch.hub.load(
|
||||
repo, self.model_name, trust_repo=True, verbose=False
|
||||
)
|
||||
model.eval()
|
||||
model.to(device)
|
||||
self._model = model
|
||||
self._device = device
|
||||
self._torch = torch
|
||||
# Resize по короткой стороне (224/224*256≈256) + center crop — стандарт
|
||||
# DINOv2-препроцессинга для классификационных входов
|
||||
resize_to = round(self.image_size * 256 / 224)
|
||||
self._transform = transforms.Compose(
|
||||
[
|
||||
transforms.Resize(resize_to, antialias=True),
|
||||
transforms.CenterCrop(self.image_size),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(_IMAGENET_MEAN, _IMAGENET_STD),
|
||||
]
|
||||
)
|
||||
self._warmup()
|
||||
except ModelLoadError:
|
||||
raise
|
||||
except Exception as exc: # сеть, диск, несовместимость версий
|
||||
raise ModelLoadError(f"не удалось загрузить {self.model_name}: {exc}") from exc
|
||||
|
||||
def _resolve_device(self, torch) -> str:
|
||||
if self.device in ("", "auto"):
|
||||
return "cuda" if torch.cuda.is_available() else "cpu"
|
||||
return self.device
|
||||
|
||||
def _warmup(self) -> None:
|
||||
"""Прогон синтетического изображения: распаковка графа до боевых запросов."""
|
||||
dummy = Image.new("RGB", (self.image_size, self.image_size), color=(127, 127, 127))
|
||||
self.embed([dummy])
|
||||
|
||||
def embed(self, images: Sequence[Image.Image]) -> np.ndarray:
|
||||
"""Эмбеддинги батча: CLS-токены, float32, строки L2-нормированы."""
|
||||
if self._model is None:
|
||||
raise ModelLoadError("модель не загружена: сначала load()")
|
||||
torch = self._torch
|
||||
batch = torch.stack([self._transform(img) for img in images]).to(self._device)
|
||||
with torch.inference_mode():
|
||||
cls = self._model(batch) # (N, embed_dim) — CLS-токен
|
||||
vectors = cls.cpu().numpy().astype(np.float32)
|
||||
norms = np.linalg.norm(vectors, axis=1, keepdims=True)
|
||||
return vectors / np.maximum(norms, 1e-12)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Оркестрация запроса: декод -> эмбеддинги -> сравнение. Stateless (FR-006)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol, Sequence
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .comparison import ComparisonResult, cosine_similarities, decide
|
||||
from .exceptions import (
|
||||
ImageDecodeError,
|
||||
ImageTooSmallError,
|
||||
UnsupportedImageFormatError,
|
||||
)
|
||||
|
||||
_SUPPORTED_FORMATS = {"JPEG", "PNG", "WEBP"}
|
||||
|
||||
|
||||
class Embedder(Protocol):
|
||||
"""Контракт эмбеддера; DinoEmbedder и тестовый FakeEmbedder ему удовлетворяют."""
|
||||
|
||||
def load(self) -> None: ...
|
||||
|
||||
def embed(self, images: Sequence[Image.Image]) -> np.ndarray: ...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VerifyOutcome:
|
||||
"""Результат verify(): сравнение + метаданные запроса."""
|
||||
|
||||
comparison: ComparisonResult
|
||||
probe_sha256: str
|
||||
processing_ms: float
|
||||
|
||||
|
||||
class DinoService:
|
||||
""" Stateless-вычислитель: без состояния между запросами."""
|
||||
|
||||
def __init__(self, config, embedder: Embedder):
|
||||
self._config = config
|
||||
self._embedder = embedder
|
||||
|
||||
def init_core(self) -> None:
|
||||
"""Загрузка модели при старте; исключение фиксируется в ready_reasons выше."""
|
||||
self._embedder.load()
|
||||
|
||||
def verify(self, probe: bytes, references: Sequence[bytes]) -> VerifyOutcome:
|
||||
started = time.perf_counter()
|
||||
probe_img = self._decode(probe)
|
||||
reference_imgs = [self._decode(blob) for blob in references]
|
||||
|
||||
embeddings = self._embedder.embed([probe_img, *reference_imgs])
|
||||
similarities = cosine_similarities(embeddings[0], embeddings[1:])
|
||||
result = decide(
|
||||
similarities,
|
||||
threshold_match=self._config.threshold_match,
|
||||
threshold_no_match=self._config.threshold_no_match,
|
||||
)
|
||||
return VerifyOutcome(
|
||||
comparison=result,
|
||||
probe_sha256=hashlib.sha256(probe).hexdigest(),
|
||||
processing_ms=(time.perf_counter() - started) * 1000.0,
|
||||
)
|
||||
|
||||
def _decode(self, data: bytes) -> Image.Image:
|
||||
"""Байты -> RGB-изображение с проверкой формата и минимального размера."""
|
||||
try:
|
||||
image = Image.open(io.BytesIO(data))
|
||||
image.load()
|
||||
except Exception as exc:
|
||||
raise ImageDecodeError(f"не удалось декодировать изображение: {exc}") from exc
|
||||
if image.format not in _SUPPORTED_FORMATS:
|
||||
raise UnsupportedImageFormatError(
|
||||
f"формат {image.format!r} не поддерживается; допустимы JPEG, PNG, WebP"
|
||||
)
|
||||
# exif_transpose теряет .format — вызываем после проверки формата
|
||||
image = ImageOps.exif_transpose(image)
|
||||
image = image.convert("RGB")
|
||||
if min(image.size) < self._config.min_image_dim:
|
||||
raise ImageTooSmallError(
|
||||
f"сторона {min(image.size)}px меньше минимума {self._config.min_image_dim}px"
|
||||
)
|
||||
return image
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Структурированные JSON-логи в stdout: один JSON-объект на строку."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
_RESERVED = set(
|
||||
logging.LogRecord("", 0, "", 0, "", (), None).__dict__.keys()
|
||||
) | {"message", "asctime"}
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
payload = {
|
||||
"ts": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat(
|
||||
timespec="milliseconds"
|
||||
),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"message": record.getMessage(),
|
||||
}
|
||||
for key, value in record.__dict__.items():
|
||||
if key not in _RESERVED:
|
||||
payload[key] = value
|
||||
if record.exc_info:
|
||||
payload["exception"] = self.formatException(record.exc_info)
|
||||
return json.dumps(payload, ensure_ascii=False, default=str)
|
||||
|
||||
|
||||
def setup_logging(level: str = "INFO") -> None:
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(JsonFormatter())
|
||||
root = logging.getLogger()
|
||||
root.handlers = [handler]
|
||||
root.setLevel(level)
|
||||
for noisy in ("uvicorn.access", "uvicorn.error", "httpx"):
|
||||
logging.getLogger(noisy).handlers = []
|
||||
logging.getLogger(noisy).propagate = True
|
||||
|
||||
|
||||
def log_event(logger: logging.Logger, level: int, message: str, **fields: object) -> None:
|
||||
"""Логирует событие с полями: log_event(log, logging.INFO, "ready", model=...)."""
|
||||
logger.log(level, message, extra=fields)
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
"""Фабрика приложения: create_app() -> FastAPI.
|
||||
|
||||
Запуск: uvicorn app.main:create_app --factory.
|
||||
Модель загружается один раз в lifespan и живёт в app.state.service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .api.errors import error_response, register_error_handlers
|
||||
from .api.routes import router
|
||||
from .config import Config
|
||||
from .dino.model import DinoEmbedder
|
||||
from .dino.service import DinoService
|
||||
from .logging_setup import log_event, setup_logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_app(config: Config | None = None, embedder=None) -> FastAPI:
|
||||
"""embedder — точка внедрения тестового фейка (контракт Embedder)."""
|
||||
config = config or Config.from_env()
|
||||
setup_logging(config.log_level)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
if not config.api_key:
|
||||
log_event(
|
||||
logger,
|
||||
logging.WARNING,
|
||||
"APP_API_KEY не задан: /api/v1/* открыты без аутентификации",
|
||||
)
|
||||
if config.workers > 1:
|
||||
log_event(
|
||||
logger,
|
||||
logging.WARNING,
|
||||
"WORKERS>1: каждая копия процесса держит свою копию модели в RAM",
|
||||
workers=config.workers,
|
||||
)
|
||||
try:
|
||||
await run_in_threadpool(app.state.service.init_core)
|
||||
app.state.ready = True
|
||||
log_event(
|
||||
logger,
|
||||
logging.INFO,
|
||||
"модель загружена, сервис готов",
|
||||
model=config.model_name,
|
||||
device=config.device,
|
||||
image_size=config.image_size,
|
||||
)
|
||||
except Exception as exc:
|
||||
app.state.ready = False
|
||||
app.state.ready_reasons = [f"model load failed: {exc}"]
|
||||
log_event(
|
||||
logger,
|
||||
logging.ERROR,
|
||||
"модель не загрузилась; /verify отвечает 503, детали на /ready",
|
||||
error=str(exc),
|
||||
)
|
||||
yield
|
||||
|
||||
app = FastAPI(
|
||||
title="dinoV2",
|
||||
description=(
|
||||
"Stateless-сервис: определяет, изображён ли на проверяемом фото "
|
||||
"тот же объект (здание/памятник), что на эталонных фотографиях, "
|
||||
"сравнением эмбеддингов DINOv2."
|
||||
),
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
docs_url="/api/docs",
|
||||
redoc_url="/api/redoc",
|
||||
openapi_url="/api/openapi.json",
|
||||
)
|
||||
app.state.config = config
|
||||
app.state.embedder = embedder or DinoEmbedder(
|
||||
model_name=config.model_name,
|
||||
device=config.device,
|
||||
image_size=config.image_size,
|
||||
torch_home=config.torch_home,
|
||||
)
|
||||
app.state.service = DinoService(config, app.state.embedder)
|
||||
app.state.ready = False
|
||||
app.state.ready_reasons: list[str] = []
|
||||
|
||||
register_error_handlers(app)
|
||||
_register_middleware(app)
|
||||
app.include_router(router)
|
||||
return app
|
||||
|
||||
|
||||
def _register_middleware(app: FastAPI) -> None:
|
||||
@app.middleware("http")
|
||||
async def observability(request: Request, call_next):
|
||||
request.state.trace_id = uuid.uuid4().hex[:12]
|
||||
# Ранний отказ по Content-Length: тело не читаем вообще
|
||||
content_length = request.headers.get("Content-Length")
|
||||
limit = app.state.config.max_body_bytes
|
||||
if content_length and content_length.isdigit() and int(content_length) > limit:
|
||||
return error_response(
|
||||
413,
|
||||
"PAYLOAD_TOO_LARGE",
|
||||
f"тело запроса {content_length} байт, максимум {limit}",
|
||||
request.state.trace_id,
|
||||
)
|
||||
started = time.perf_counter()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Trace-Id"] = request.state.trace_id
|
||||
if request.url.path.startswith("/api/"):
|
||||
log_event(
|
||||
logger,
|
||||
logging.INFO,
|
||||
"request",
|
||||
method=request.method,
|
||||
path=request.url.path,
|
||||
status=response.status_code,
|
||||
duration_ms=round((time.perf_counter() - started) * 1000, 1),
|
||||
trace_id=request.state.trace_id,
|
||||
)
|
||||
return response
|
||||
Reference in New Issue
Block a user