init app
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
"""Маршруты API (docs/05-rest-api.md): /features, /verify, /profiles, /health, /ready."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import Response
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.datastructures import UploadFile
|
||||
|
||||
from app.api.deps import check_image_content_type, require_api_key
|
||||
from app.api.errors import ApiError
|
||||
from app.api.schemas import (
|
||||
ProfileModel,
|
||||
ProfilesResponse,
|
||||
StatusResponse,
|
||||
UnreadyResponse,
|
||||
VerifyResponse,
|
||||
)
|
||||
from app.cv.exceptions import InvalidSettings
|
||||
from app.cv.params import PROFILES, base_comparison, base_extraction
|
||||
from app.cv.service import CvService
|
||||
from app.logging_setup import log_event
|
||||
|
||||
logger = logging.getLogger("opencv.api")
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_SETTINGS_MAX_BYTES = 4096 # settings ≤ 4 КБ (FR-008, docs/05 §5.5-6)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ helpers
|
||||
|
||||
|
||||
def _config(request: Request):
|
||||
return request.app.state.config
|
||||
|
||||
|
||||
def _service(request: Request) -> CvService:
|
||||
return request.app.state.cv
|
||||
|
||||
|
||||
async def _read_file_part(form, name: str) -> tuple[bytes, str | None]:
|
||||
"""Достаёт файловую часть: (байты, content-type). Строковая часть — 422."""
|
||||
part = form.get(name)
|
||||
if part is None or isinstance(part, str):
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
f"Отсутствует обязательная multipart-часть {name!r}",
|
||||
{"part": name},
|
||||
)
|
||||
return await part.read(), part.content_type
|
||||
|
||||
|
||||
async def _read_settings(form) -> dict | None:
|
||||
"""form-часть settings (JSON ≤ 4 КБ); отсутствует → None."""
|
||||
raw = form.get("settings")
|
||||
if raw is None:
|
||||
return None
|
||||
if isinstance(raw, UploadFile):
|
||||
raw = (await raw.read()).decode("utf-8", errors="replace")
|
||||
encoded = raw.encode("utf-8")
|
||||
if len(encoded) > _SETTINGS_MAX_BYTES:
|
||||
raise InvalidSettings(
|
||||
f"settings превышает лимит {_SETTINGS_MAX_BYTES} байт", {"size": len(encoded)}
|
||||
)
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise InvalidSettings(f"settings не является корректным JSON: {exc}") from exc
|
||||
return parsed
|
||||
|
||||
|
||||
def _check_image_size(data: bytes, part: str, limit: int) -> None:
|
||||
if len(data) > limit:
|
||||
raise ApiError(
|
||||
413, "PAYLOAD_TOO_LARGE",
|
||||
f"Часть {part} превышает лимит {limit // (1024 * 1024)} МБ",
|
||||
{"part": part, "size": len(data), "limit": limit},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- /features
|
||||
|
||||
|
||||
@router.post("/api/v1/features", dependencies=[Depends(require_api_key)])
|
||||
async def extract_features(request: Request):
|
||||
form = await request.form()
|
||||
image_bytes, content_type = await _read_file_part(form, "image")
|
||||
check_image_content_type(content_type, "image")
|
||||
_check_image_size(image_bytes, "image", _config(request).max_image_bytes)
|
||||
settings = await _read_settings(form)
|
||||
|
||||
started = time.perf_counter()
|
||||
outcome = await run_in_threadpool(_service(request).extract_to_blob, image_bytes, settings)
|
||||
duration_ms = int((time.perf_counter() - started) * 1000)
|
||||
|
||||
log_event(
|
||||
logger, logging.INFO, "features extracted",
|
||||
trace_id=getattr(request.state, "trace_id", ""),
|
||||
keypoints=outcome.keypoints_count,
|
||||
algo_id=outcome.algo_id,
|
||||
duration_ms=duration_ms,
|
||||
)
|
||||
return Response(
|
||||
content=outcome.blob,
|
||||
media_type="application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="features.npz"',
|
||||
"X-Feature-Format-Version": str(outcome.format_version),
|
||||
"X-Algo-Id": outcome.algo_id,
|
||||
"X-Keypoints-Count": str(outcome.keypoints_count),
|
||||
"X-Image-Width": str(outcome.image_width),
|
||||
"X-Image-Height": str(outcome.image_height),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ /verify
|
||||
|
||||
|
||||
@router.post("/api/v1/verify", dependencies=[Depends(require_api_key)])
|
||||
async def verify(request: Request):
|
||||
config = _config(request)
|
||||
form = await request.form()
|
||||
|
||||
probe_bytes, probe_ct = await _read_file_part(form, "probe")
|
||||
check_image_content_type(probe_ct, "probe")
|
||||
_check_image_size(probe_bytes, "probe", config.max_image_bytes)
|
||||
|
||||
ref_parts = form.getlist("reference")
|
||||
if not ref_parts:
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
"Отсутствуют части reference: нужен хотя бы один эталон",
|
||||
{"part": "reference"},
|
||||
)
|
||||
if len(ref_parts) > config.max_references:
|
||||
raise ApiError(
|
||||
400, "TOO_MANY_REFERENCES",
|
||||
f"Число эталонов {len(ref_parts)} превышает лимит {config.max_references}",
|
||||
{"references": len(ref_parts), "limit": config.max_references},
|
||||
)
|
||||
reference_payloads: list[bytes] = []
|
||||
for i, part in enumerate(ref_parts):
|
||||
if isinstance(part, str):
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
f"Часть reference[{i}] должна быть файлом",
|
||||
{"part": "reference", "index": i},
|
||||
)
|
||||
data = await part.read()
|
||||
_check_image_size(data, f"reference[{i}]", config.verify_max_body_bytes)
|
||||
reference_payloads.append(data)
|
||||
|
||||
settings = await _read_settings(form)
|
||||
|
||||
started = time.perf_counter()
|
||||
outcome = await run_in_threadpool(
|
||||
_service(request).verify, probe_bytes, reference_payloads, settings
|
||||
)
|
||||
processing_ms = int((time.perf_counter() - started) * 1000)
|
||||
|
||||
log_event(
|
||||
logger, logging.INFO, "verify completed",
|
||||
trace_id=getattr(request.state, "trace_id", ""),
|
||||
verdict=outcome.verdict,
|
||||
confidence=round(outcome.confidence, 4),
|
||||
best_reference_index=outcome.best_reference_index,
|
||||
references=outcome.references_compared,
|
||||
processing_ms=processing_ms,
|
||||
)
|
||||
return VerifyResponse(
|
||||
verdict=outcome.verdict,
|
||||
is_match=outcome.is_match,
|
||||
confidence=round(outcome.confidence, 4),
|
||||
details={
|
||||
"references_compared": outcome.references_compared,
|
||||
"best_reference_index": outcome.best_reference_index,
|
||||
"metrics": {
|
||||
"good_matches": outcome.metrics.good_matches,
|
||||
"inliers": outcome.metrics.inliers,
|
||||
"inlier_ratio": round(outcome.metrics.inlier_ratio, 4),
|
||||
"coverage": round(outcome.metrics.coverage, 4),
|
||||
},
|
||||
"thresholds": outcome.thresholds,
|
||||
},
|
||||
probe_sha256=outcome.probe_sha256,
|
||||
processing_ms=processing_ms,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- /profiles
|
||||
|
||||
|
||||
@router.get(
|
||||
"/api/v1/profiles",
|
||||
dependencies=[Depends(require_api_key)],
|
||||
response_model=ProfilesResponse,
|
||||
)
|
||||
async def list_profiles(request: Request):
|
||||
"""Каталог профилей (FR-009): только отличия от базовых значений (docs/05 §5.4.4)."""
|
||||
config = _config(request)
|
||||
return ProfilesResponse(
|
||||
profiles=[
|
||||
ProfileModel(
|
||||
name=name,
|
||||
description=spec["description"],
|
||||
extraction=spec["extraction"],
|
||||
comparison=spec["comparison"],
|
||||
)
|
||||
for name, spec in PROFILES.items()
|
||||
],
|
||||
defaults={
|
||||
"extraction": base_extraction(config).fingerprint_payload(),
|
||||
"comparison": base_comparison(config).thresholds_payload(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------- /health and /ready
|
||||
|
||||
|
||||
health_router = APIRouter()
|
||||
|
||||
|
||||
@health_router.get("/health", response_model=StatusResponse)
|
||||
async def health():
|
||||
return StatusResponse(status="ok")
|
||||
|
||||
|
||||
@health_router.get("/ready")
|
||||
async def ready(request: Request):
|
||||
"""FR-005: конфигурация валидна и CV-ядро инициализировано."""
|
||||
cv: CvService = request.app.state.cv
|
||||
reasons = cv.ready_reasons
|
||||
if request.app.state.ready and not reasons:
|
||||
return StatusResponse(status="ready")
|
||||
return Response(
|
||||
content=UnreadyResponse(status="unavailable", reasons=reasons).model_dump_json(),
|
||||
status_code=503,
|
||||
media_type="application/json",
|
||||
)
|
||||
Reference in New Issue
Block a user