Приложение: 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
+128
View File
@@ -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