This commit is contained in:
2026-09-29 00:17:58 +03:00
parent 2f8d4098c5
commit da32158789
38 changed files with 3106 additions and 10 deletions
+4
View File
@@ -0,0 +1,4 @@
"""open_cv — stateless-сервис компьютерного зрения (SIFT-извлечение и верификация).
Слои: ``app.api`` (транспорт, FastAPI) → ``app.cv`` (чистое CV-ядро).
"""
+5
View File
@@ -0,0 +1,5 @@
"""API-слой: маршруты, multipart, лимиты, X-API-Key, единый формат ошибок.
Бизнес-логики нет — только валидация транспорта и делегация в CV-ядро
(docs/03 §3.2.1).
"""
+39
View File
@@ -0,0 +1,39 @@
"""Аутентификация X-API-Key (FR-004, docs/05 §5.2): 401 — нет, 403 — неверен."""
from __future__ import annotations
import secrets
from fastapi import Request
from app.api.errors import ApiError
ALLOWED_IMAGE_CONTENT_TYPES = {"image/jpeg", "image/png", "image/webp"}
def require_api_key(request: Request) -> None:
provided = request.headers.get("x-api-key")
if not provided:
raise ApiError(401, "UNAUTHORIZED", "Требуется заголовок X-API-Key")
expected = request.app.state.config.api_key
if not secrets.compare_digest(provided.encode(), expected.encode()):
raise ApiError(403, "FORBIDDEN", "Неверный API-ключ")
def check_image_content_type(content_type: str | None, part: str) -> None:
"""415, если часть заявлена как изображение недопустимого типа.
application/octet-stream пропускаем: фактический формат определяет
декодер, а не заголовок части (docs/05 §5.5-1).
"""
if content_type is None:
return
base = content_type.split(";", 1)[0].strip().lower()
if base == "application/octet-stream":
return
if base.startswith("image/") and base not in ALLOWED_IMAGE_CONTENT_TYPES:
raise ApiError(
415,
"UNSUPPORTED_MEDIA_TYPE",
f"Часть {part}: формат {base} не поддерживается; разрешены JPEG, PNG, WebP",
{"part": part, "content_type": base},
)
+114
View File
@@ -0,0 +1,114 @@
"""Единый формат ошибок и маппинг исключений на HTTP (docs/05 §5.3).
Тело любой ошибки: {"error": {"code", "message", "details", "trace_id"}}.
"""
from __future__ import annotations
from fastapi import Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.cv.exceptions import (
BlobInvalid,
CvError,
FormatUnsupported,
ImageDecodeFailed,
ImageFormatUnsupported,
ImageTooSmall,
InvalidSettings,
UnknownProfile,
)
# Маппинг исключений CV-ядра на коды ответов — единственная точка,
# где ядро «узнаёт» о HTTP (docs/03 §3.5-1).
_CV_ERROR_MAP: list[tuple[type[CvError], int, str]] = [
(ImageDecodeFailed, 400, "IMAGE_DECODE_FAILED"),
(ImageTooSmall, 400, "IMAGE_TOO_SMALL"),
(BlobInvalid, 400, "FEATURE_BLOB_INVALID"),
(FormatUnsupported, 400, "FEATURE_FORMAT_UNSUPPORTED"),
(UnknownProfile, 400, "UNKNOWN_PROFILE"),
(ImageFormatUnsupported, 415, "UNSUPPORTED_MEDIA_TYPE"),
(InvalidSettings, 422, "INVALID_SETTINGS"),
]
class ApiError(Exception):
"""Транспортная ошибка API-слоя с готовым кодом ответа."""
def __init__(self, status_code: int, code: str, message: str, details: dict | None = None):
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.details = details or {}
def error_body(code: str, message: str, trace_id: str, details: dict | None = None) -> dict:
return {"error": {"code": code, "message": message, "details": details or {}, "trace_id": trace_id}}
def _trace_id(request: Request) -> str:
return getattr(request.state, "trace_id", "")
def install_error_handlers(app) -> None:
@app.exception_handler(ApiError)
async def _api_error(request: Request, exc: ApiError):
return JSONResponse(
status_code=exc.status_code,
content=error_body(exc.code, exc.message, _trace_id(request), exc.details),
)
@app.exception_handler(CvError)
async def _cv_error(request: Request, exc: CvError):
for exc_type, status, code in _CV_ERROR_MAP:
if isinstance(exc, exc_type):
return JSONResponse(
status_code=status,
content=error_body(code, str(exc), _trace_id(request), exc.details),
)
return JSONResponse(
status_code=500,
content=error_body("INTERNAL", "Внутренняя ошибка сервиса", _trace_id(request)),
)
@app.exception_handler(RequestValidationError)
async def _validation(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content=error_body(
"VALIDATION_ERROR", "Некорректный запрос", _trace_id(request),
{"errors": [
{"loc": [str(p) for p in e.get("loc", [])], "msg": e.get("msg", "")}
for e in exc.errors()
]},
),
)
@app.exception_handler(StarletteHTTPException)
async def _http_error(request: Request, exc: StarletteHTTPException):
code = {401: "UNAUTHORIZED", 403: "FORBIDDEN", 404: "NOT_FOUND", 405: "METHOD_NOT_ALLOWED"}.get(
exc.status_code, "HTTP_ERROR"
)
return JSONResponse(
status_code=exc.status_code,
content=error_body(code, str(exc.detail), _trace_id(request)),
headers=getattr(exc, "headers", None),
)
@app.exception_handler(Exception)
async def _unhandled(request: Request, exc: Exception):
import logging
logging.getLogger("opencv").exception(
"Необработанное исключение", extra={"fields": {"trace_id": _trace_id(request)}}
)
return JSONResponse(
status_code=500,
content=error_body(
"INTERNAL",
"Внутренняя ошибка сервиса; детали в логах по trace_id",
_trace_id(request),
),
)
+245
View File
@@ -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",
)
+62
View File
@@ -0,0 +1,62 @@
"""Pydantic-модели JSON-ответов (docs/05 §5.4.2, §5.4.4)."""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field
class PairMetricsModel(BaseModel):
good_matches: int = Field(description="Число пар после теста Лоу")
inliers: int = Field(description="Число инлаеров RANSAC")
inlier_ratio: float = Field(description="inliers / good_matches")
coverage: float = Field(description="Доля площади пробы под оболочкой инлаеров")
class ThresholdsModel(BaseModel):
"""Эффективные пороги сравнения лучшей пары (+ аддитивные поля диагностики)."""
inliers_match: int
inlier_ratio_match: float
coverage_min: float
inliers_uncertain_min: int
geometry_model: str
lowe_ratio: float
ransac_reproj_threshold: float
class VerifyDetailsModel(BaseModel):
references_compared: int
best_reference_index: int = Field(description="Индекс части reference (0-based)")
metrics: PairMetricsModel
thresholds: ThresholdsModel
class VerifyResponse(BaseModel):
verdict: Literal["match", "uncertain", "no_match"]
is_match: bool = Field(description="true только при verdict = match")
confidence: float = Field(ge=0.0, le=1.0)
details: VerifyDetailsModel
probe_sha256: str
processing_ms: int
class ProfileModel(BaseModel):
name: str
description: str
extraction: dict
comparison: dict
class ProfilesResponse(BaseModel):
profiles: list[ProfileModel]
defaults: dict = Field(description="Базовые значения (env-умолчания) для наследования")
class StatusResponse(BaseModel):
status: str
class UnreadyResponse(BaseModel):
status: str
reasons: list[str]
+130
View File
@@ -0,0 +1,130 @@
"""Конфигурация сервиса из переменных окружения.
Полный список переменных и умолчаний — docs/07-развертывание.md §7.4.
Правило fail-fast (7.4-1): невалидная конфигурация — падение на старте
с понятным сообщением, а не молчаливое умолчание.
"""
from __future__ import annotations
import os
from dataclasses import dataclass
# CLAHE-умолчания — константы алгоритма (docs/04 §4.2); в env-таблице 07.4 их нет,
# но профиль/переопределения запроса могут их менять.
DEFAULT_CLAHE_CLIP_LIMIT = 2.0
DEFAULT_CLAHE_TILE_GRID = (8, 8)
_MB = 1024 * 1024
class ConfigError(RuntimeError):
"""Невалидная конфигурация окружения."""
def _read(name: str, default: str | None) -> str:
value = os.environ.get(name)
if value is None or value == "":
if default is None:
raise ConfigError(f"обязательная переменная окружения {name} не задана")
return default
return value
def _to_int(name: str, raw: str, lo: int, hi: int) -> int:
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, lo: float, hi: float) -> float:
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:
api_key: str
host: str
port: int
workers: int
log_level: str
max_image_bytes: int # MAX_IMAGE_MB
verify_max_body_bytes: int # VERIFY_MAX_BODY_MB
max_references: int # MAX_REFERENCES_PER_REQUEST
sift_max_image_size: int
sift_max_keypoints: int
lowe_ratio: float
ransac_reproj_threshold: float
match_inliers_min: int
match_inliers_ratio_min: float
match_coverage_min: float
uncertain_inliers_min: int
@classmethod
def from_env(cls) -> "Config":
return cls(
api_key=_read("APP_API_KEY", None),
host=_read("HOST", "0.0.0.0"),
port=_to_int("PORT", _read("PORT", "8000"), 1, 65535),
workers=_to_int("WORKERS", _read("WORKERS", "2"), 1, 64),
log_level=_read("LOG_LEVEL", "INFO").upper(),
max_image_bytes=_to_int(
"MAX_IMAGE_MB", _read("MAX_IMAGE_MB", "20"), 1, 512
) * _MB,
verify_max_body_bytes=_to_int(
"VERIFY_MAX_BODY_MB", _read("VERIFY_MAX_BODY_MB", "64"), 1, 2048
) * _MB,
max_references=_to_int(
"MAX_REFERENCES_PER_REQUEST",
_read("MAX_REFERENCES_PER_REQUEST", "32"),
1, 128,
),
sift_max_image_size=_to_int(
"SIFT_MAX_IMAGE_SIZE", _read("SIFT_MAX_IMAGE_SIZE", "1600"), 320, 8192
),
sift_max_keypoints=_to_int(
"SIFT_MAX_KEYPOINTS", _read("SIFT_MAX_KEYPOINTS", "16384"), 100, 65536
),
lowe_ratio=_to_float("LOWE_RATIO", _read("LOWE_RATIO", "0.75"), 0.5, 0.95),
ransac_reproj_threshold=_to_float(
"RANSAC_REPROJ_THRESHOLD", _read("RANSAC_REPROJ_THRESHOLD", "5.0"), 1.0, 15.0
),
match_inliers_min=_to_int(
"MATCH_INLIERS_MIN", _read("MATCH_INLIERS_MIN", "50"), 5, 1000
),
match_inliers_ratio_min=_to_float(
"MATCH_INLIERS_RATIO_MIN", _read("MATCH_INLIERS_RATIO_MIN", "0.30"), 0.05, 0.95
),
match_coverage_min=_to_float(
"MATCH_COVERAGE_MIN", _read("MATCH_COVERAGE_MIN", "0.05"), 0.0, 0.5
),
uncertain_inliers_min=_to_int(
"UNCERTAIN_INLIERS_MIN", _read("UNCERTAIN_INLIERS_MIN", "20"), 1, 500
),
)
def validate_cross(self) -> None:
"""Связанные проверки, которые нельзя выразить одним диапазоном."""
problems: list[str] = []
if self.verify_max_body_bytes < self.max_image_bytes:
problems.append(
"VERIFY_MAX_BODY_MB не может быть меньше MAX_IMAGE_MB"
)
if self.uncertain_inliers_min > self.match_inliers_min:
problems.append(
"UNCERTAIN_INLIERS_MIN не может превышать MATCH_INLIERS_MIN"
)
if problems:
raise ConfigError("; ".join(problems))
+6
View File
@@ -0,0 +1,6 @@
"""CV-ядро: extract / compare / резолвер настроек / блоб-кодек.
Чистый Python-модуль без зависимостей от FastAPI: не импортирует веб-слой,
не знает HTTP-кодов, ошибки выражает типизированными исключениями
(правило слоёв — docs/03-архитектура.md §3.5).
"""
+217
View File
@@ -0,0 +1,217 @@
"""Блоб-кодек — единственное место, знающее формат .npz (docs/03 §3.5-3).
Формат блоба — docs/06-формат-признаков.md:
descriptors uint8 (N, 128); keypoints float32 (N, 5); meta — JSON-строка.
Защита от zip-бомбы: суммарный размер распакованных массивов ограничен
SIFT_MAX_KEYPOINTS, формы проверяются до копирования (FR-003 п.3, §6.6-2).
"""
from __future__ import annotations
import hashlib
import io
import json
import zipfile
from datetime import datetime, timezone
import cv2
import numpy as np
from app.config import Config
from app.cv.exceptions import BlobInvalid, FormatUnsupported
from app.cv.extraction import Features
from app.cv.params import ExtractionParams
FORMAT_VERSION = 1
ALGO_PREFIX = "sift-v1"
DESCRIPTOR_COLS = 128
KEYPOINT_COLS = 5
_META_REQUIRED_FIELDS = (
"format_version",
"algo_id",
"extraction_params",
"source_image",
"keypoints_count",
"created_at",
)
def compute_algo_id(params: ExtractionParams) -> str:
"""Отпечаток эффективных параметров извлечения + версия OpenCV.
Информативен (docs/04 §4.5.5): смена настроек меняет отпечаток, но не
format_version — блобы с разными algo_id совместимы.
"""
payload = {"opencv_version": cv2.__version__, **params.fingerprint_payload()}
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:8]
return f"{ALGO_PREFIX}:{digest}"
def build_meta(
params: ExtractionParams,
algo_id: str,
features: Features,
settings_payload: dict | None,
source_sha256: str,
) -> dict:
return {
"format_version": FORMAT_VERSION,
"algo_id": algo_id,
"extraction_params": {
"opencv_version": cv2.__version__,
"max_image_size": params.max_image_size,
"clahe": {
"clip_limit": params.clahe_clip_limit,
"tile_grid_size": list(params.clahe_tile_grid),
},
"sift_nfeatures": params.max_keypoints,
},
"settings": settings_payload,
"source_image": {"width": features.source_width, "height": features.source_height},
"keypoints_count": features.count,
"source_sha256": source_sha256,
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
def pack(features: Features, meta: dict) -> bytes:
"""Упаковка признаков и метаданных в бинарный .npz."""
if features.descriptors.dtype != np.uint8 or features.keypoints.dtype != np.float32:
raise BlobInvalid("Неверные типы массивов при упаковке блоба")
buffer = io.BytesIO()
np.savez_compressed(
buffer,
descriptors=features.descriptors,
keypoints=features.keypoints,
meta=np.array(json.dumps(meta, ensure_ascii=False)),
)
return buffer.getvalue()
class UnpackedBlob:
"""Распакованный блоб: признаки + meta + провалидированные settings."""
__slots__ = ("features", "meta", "settings")
def __init__(self, features: Features, meta: dict, settings: object | None):
self.features = features
self.meta = meta
self.settings = settings
def unpack(data: bytes, config: Config) -> UnpackedBlob:
"""Распаковка с полной валидацией (FR-003): структура → версия → лимиты."""
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
# np.savez хранит массивы как <name>.npy — сравниваем без суффикса
stored = {name.removesuffix(".npy") for name in zf.namelist()}
required = {"descriptors", "keypoints", "meta"}
if not required <= stored:
raise BlobInvalid(
"Блоб не содержит обязательные массивы", {"missing": sorted(required - stored)}
)
# Проверка размеров до распаковки: zip-контейнер не должен
# разворачиваться в гигабайты памяти (FR-003 п.3)
max_kp = config.sift_max_keypoints
limits = {
"descriptors.npy": max_kp * DESCRIPTOR_COLS, # uint8, 1 байт
"keypoints.npy": max_kp * KEYPOINT_COLS * 4, # float32
}
for name, limit in limits.items():
declared = zf.getinfo(name).file_size
if declared > limit:
raise BlobInvalid(
f"Массив {name.removesuffix('.npy')} превышает лимит распаковки: "
f"{declared} байт > {limit} (SIFT_MAX_KEYPOINTS={max_kp})",
{"array": name.removesuffix(".npy"), "declared_size": declared},
)
npz = np.load(io.BytesIO(data), allow_pickle=False)
descriptors = np.asarray(npz["descriptors"])
keypoints = np.asarray(npz["keypoints"])
meta_raw = npz["meta"]
except BlobInvalid:
raise
except (zipfile.BadZipFile, OSError, ValueError, KeyError) as exc:
raise BlobInvalid(f"Блоб не является корректным .npz: {exc.__class__.__name__}") from exc
_validate_arrays(descriptors, keypoints, config)
try:
meta = json.loads(str(meta_raw.item()))
except (ValueError, AttributeError, TypeError) as exc:
raise BlobInvalid("meta блоба не является корректным JSON") from exc
if not isinstance(meta, dict):
raise BlobInvalid("meta блоба должен быть JSON-объектом")
missing = [f for f in _META_REQUIRED_FIELDS if f not in meta]
if missing:
raise BlobInvalid(f"meta блоба не содержит обязательные поля: {missing}",
{"missing": missing})
if meta["format_version"] != FORMAT_VERSION:
raise FormatUnsupported(FORMAT_VERSION, meta["format_version"])
n = int(keypoints.shape[0])
if meta["keypoints_count"] != n:
raise BlobInvalid(
f"keypoints_count ({meta['keypoints_count']}) не совпадает с числом точек ({n})"
)
src_w, src_h = _source_dims(meta)
resized_w, resized_h = _resized_dims(src_w, src_h, meta)
features = Features(
keypoints=keypoints,
descriptors=descriptors,
width=resized_w,
height=resized_h,
source_width=src_w,
source_height=src_h,
)
return UnpackedBlob(features, meta, settings=meta.get("settings"))
def _source_dims(meta: dict) -> tuple[int, int]:
source = meta.get("source_image")
if not isinstance(source, dict):
raise BlobInvalid("meta.source_image должен быть JSON-объектом")
w, h = source.get("width"), source.get("height")
if not isinstance(w, int) or not isinstance(h, int) or w <= 0 or h <= 0:
raise BlobInvalid("meta.source_image.width/height отсутствуют или невалидны")
return w, h
def _validate_arrays(descriptors: np.ndarray, keypoints: np.ndarray, config: Config) -> None:
if descriptors.dtype != np.uint8 or descriptors.ndim != 2 or descriptors.shape[1] != DESCRIPTOR_COLS:
raise BlobInvalid(
f"Массив descriptors должен быть uint8 (N, {DESCRIPTOR_COLS}), "
f"получен {descriptors.dtype} {descriptors.shape}"
)
if keypoints.dtype != np.float32 or keypoints.ndim != 2 or keypoints.shape[1] != KEYPOINT_COLS:
raise BlobInvalid(
f"Массив keypoints должен быть float32 (N, {KEYPOINT_COLS}), "
f"получен {keypoints.dtype} {keypoints.shape}"
)
if descriptors.shape[0] != keypoints.shape[0]:
raise BlobInvalid(
f"Число дескрипторов ({descriptors.shape[0]}) не равно числу keypoints "
f"({keypoints.shape[0]})"
)
if keypoints.shape[0] > config.sift_max_keypoints:
raise BlobInvalid(
f"Число keypoints ({keypoints.shape[0]}) превышает SIFT_MAX_KEYPOINTS "
f"({config.sift_max_keypoints})"
)
def _resized_dims(src_w: int, src_h: int, meta: dict) -> tuple[int, int]:
"""Восстанавливает размеры приведённого изображения из meta.
Координаты keypoints живут в системе приведённого изображения
(docs/06 §6.2); для эталона она не хранится явно и пересчитывается из
source_image и max_image_size по правилу ресайза (docs/04 §4.2).
"""
max_size = meta.get("extraction_params", {}).get("max_image_size")
if not isinstance(max_size, (int, float)) or isinstance(max_size, bool) or max_size <= 0:
raise BlobInvalid("meta.extraction_params.max_image_size отсутствует или невалиден")
scale = min(1.0, float(max_size) / max(src_w, src_h))
return max(1, round(src_w * scale)), max(1, round(src_h * scale))
+148
View File
@@ -0,0 +1,148 @@
"""Операция compare: пара «проба–эталон» → метрики, вердикт, confidence.
Схема — docs/04 §4.3–4.4: BFMatcher(kNN=2) → тест Лоу → RANSAC-геометрия
(homography | fundamental) → метрики пары → трёхзонный вердикт.
"""
from __future__ import annotations
import dataclasses
import cv2
import numpy as np
from app.cv.extraction import Features
from app.cv.params import ComparisonParams
# Ниже — константы формулы confidence и RANSAC из docs/04 §4.4 и §4.3:
# это часть спецификации алгоритма, а не конфигурируемые параметры
# (в env-таблице docs/07 §7.4 их нет).
MIN_GOOD_MATCHES = 10
INLIERS_SATURATION = 150.0
COVERAGE_NORM_SATURATION = 0.25
CONFIDENCE_WEIGHTS = (0.6, 0.25, 0.15) # inliers, inlier_ratio, coverage_norm
RANSAC_CONFIDENCE = 0.995
RANSAC_MAX_ITERS = 5000
# ГПСЧ OpenCV фиксируется перед каждым RANSAC-вызовом для детерминизма
# (NFR-009, docs/04 §4.6); seed-политика не входит в algo_id.
RANSAC_SEED = 42
VERDICT_MATCH = "match"
VERDICT_UNCERTAIN = "uncertain"
VERDICT_NO_MATCH = "no_match"
@dataclasses.dataclass(frozen=True)
class PairMetrics:
good_matches: int
inliers: int
inlier_ratio: float
coverage: float
@dataclasses.dataclass(frozen=True)
class PairResult:
metrics: PairMetrics
verdict: str
confidence: float
thresholds: ComparisonParams
def _zero_metrics(good_matches: int = 0) -> PairMetrics:
return PairMetrics(good_matches=good_matches, inliers=0, inlier_ratio=0.0, coverage=0.0)
def _confidence(metrics: PairMetrics) -> float:
inliers_part = (metrics.inliers / INLIERS_SATURATION) * CONFIDENCE_WEIGHTS[0]
ratio_part = metrics.inlier_ratio * CONFIDENCE_WEIGHTS[1]
coverage_norm = min(metrics.coverage / COVERAGE_NORM_SATURATION, 1.0)
coverage_part = coverage_norm * CONFIDENCE_WEIGHTS[2]
return float(min(1.0, max(0.0, inliers_part + ratio_part + coverage_part)))
def _verdict(metrics: PairMetrics, params: ComparisonParams) -> str:
if (
metrics.inliers >= params.match_inliers_min
and metrics.inlier_ratio >= params.match_inliers_ratio_min
and metrics.coverage >= params.match_coverage_min
):
return VERDICT_MATCH
if metrics.inliers >= params.uncertain_inliers_min:
return VERDICT_UNCERTAIN
return VERDICT_NO_MATCH
def _coverage(probe_pts: np.ndarray, mask: np.ndarray, probe: Features) -> float:
"""Доля площади изображения пробы под выпуклой оболочкой инлаеров."""
inliers = probe_pts[mask.reshape(-1) == 1]
if inliers.shape[0] < 3:
return 0.0
hull = cv2.convexHull(inliers.astype(np.float32))
area = cv2.contourArea(hull)
total = float(probe.width) * float(probe.height)
if total <= 0:
return 0.0
return float(min(area / total, 1.0))
def _ransac_inliers(
ref_pts: np.ndarray, probe_pts: np.ndarray, params: ComparisonParams
) -> np.ndarray | None:
"""Геометрическая проверка RANSAC; возвращает маску инлаеров или None."""
cv2.setRNGSeed(RANSAC_SEED)
if params.geometry_model == "fundamental":
_, mask = cv2.findFundamentalMat(
ref_pts, probe_pts,
cv2.RANSAC,
params.ransac_reproj_threshold,
RANSAC_CONFIDENCE,
RANSAC_MAX_ITERS,
)
else:
_, mask = cv2.findHomography(
ref_pts, probe_pts,
cv2.RANSAC,
params.ransac_reproj_threshold,
maxIters=RANSAC_MAX_ITERS,
confidence=RANSAC_CONFIDENCE,
)
return mask
def compare_features(probe: Features, ref: Features, params: ComparisonParams) -> PairResult:
"""Сравнение пары «проба–эталон» эффективными параметрами сравнения."""
if probe.count < 2 or ref.count < 2:
return PairResult(_zero_metrics(), VERDICT_NO_MATCH, 0.0, params)
matcher = cv2.BFMatcher(normType=cv2.NORM_L2, crossCheck=False)
matches = matcher.knnMatch(probe.descriptors.astype(np.float32),
ref.descriptors.astype(np.float32), k=2)
# Тест Лоу: лучший матч должен быть существенно лучше второго (docs/04 §4.3)
pairs = [
(row[0].queryIdx, row[0].trainIdx)
for row in matches
if len(row) == 2 and row[0].distance < params.lowe_ratio * row[1].distance
]
good_matches = len(pairs)
if good_matches < MIN_GOOD_MATCHES:
metrics = _zero_metrics(good_matches)
return PairResult(metrics, VERDICT_NO_MATCH, _confidence(metrics), params)
probe_kp = probe.keypoints[:, :2]
ref_kp = ref.keypoints[:, :2]
probe_pts = np.array([probe_kp[q] for q, _ in pairs], dtype=np.float32)
ref_pts = np.array([ref_kp[t] for _, t in pairs], dtype=np.float32)
mask = _ransac_inliers(ref_pts, probe_pts, params)
if mask is None or mask.size == 0:
metrics = _zero_metrics(good_matches) # модель не найдена → no_match (docs/04 §4.4)
return PairResult(metrics, VERDICT_NO_MATCH, _confidence(metrics), params)
inliers = int(np.count_nonzero(mask))
metrics = PairMetrics(
good_matches=good_matches,
inliers=inliers,
inlier_ratio=inliers / good_matches,
coverage=_coverage(probe_pts, mask, probe),
)
return PairResult(metrics, _verdict(metrics, params), _confidence(metrics), params)
+71
View File
@@ -0,0 +1,71 @@
"""Типизированные исключения CV-ядра.
Ни один класс не знает HTTP-кодов: маппинг на коды ответов —
исключительная зона API-слоя (docs/03 §3.5, §3.6).
"""
from __future__ import annotations
class CvError(Exception):
"""Базовый класс ошибок CV-ядра."""
def __init__(self, message: str, details: dict | None = None):
super().__init__(message)
self.details = details or {}
class ImageDecodeFailed(CvError):
"""Файл не декодируется как изображение (400 IMAGE_DECODE_FAILED)."""
class ImageFormatUnsupported(CvError):
"""Фактический формат изображения не JPEG/PNG/WebP (415 UNSUPPORTED_MEDIA_TYPE)."""
def __init__(self, fmt: str | None, details: dict | None = None):
super().__init__(
f"Формат изображения {fmt or 'неизвестен'} не поддерживается; "
"разрешены JPEG, PNG, WebP",
details,
)
self.format = fmt
class ImageTooSmall(CvError):
"""Разрешение меньше 640×480 после EXIF-ориентации (400 IMAGE_TOO_SMALL)."""
def __init__(self, width: int, height: int, details: dict | None = None):
super().__init__(
f"Разрешение изображения {width}x{height} меньше минимального 640x480",
details,
)
self.width = width
self.height = height
class BlobInvalid(CvError):
"""Блоб не является корректным .npz признаков (400 FEATURE_BLOB_INVALID)."""
class FormatUnsupported(CvError):
"""format_version блоба не поддерживается (400 FEATURE_FORMAT_UNSUPPORTED)."""
def __init__(self, expected: int, received: int, details: dict | None = None):
super().__init__(
"Блоб признаков имеет несовместимую версию формата; "
"пересчитайте эталоны через POST /api/v1/features",
{"expected_format_version": expected, "received": received, **(details or {})},
)
self.expected = expected
self.received = received
class UnknownProfile(CvError):
"""В settings.profile указан неизвестный профиль (400 UNKNOWN_PROFILE)."""
def __init__(self, name: str):
super().__init__(f"Неизвестный профиль настроек: {name!r}")
self.name = name
class InvalidSettings(CvError):
"""Неизвестный ключ или значение вне диапазона в settings (422 INVALID_SETTINGS)."""
+116
View File
@@ -0,0 +1,116 @@
"""Операция extract: изображение → keypoints + дескрипторы SIFT.
Пайплайн (docs/04 §4.2): EXIF-ориентация → ресайз ≤ max_image_size →
grayscale + CLAHE → SIFT(nfeatures).
"""
from __future__ import annotations
import io
import cv2
import numpy as np
from PIL import Image, ImageOps
from app.cv.exceptions import ImageDecodeFailed, ImageFormatUnsupported, ImageTooSmall
from app.cv.params import ExtractionParams
MIN_WIDTH = 640
MIN_HEIGHT = 480
ALLOWED_IMAGE_FORMATS = {"JPEG", "PNG", "WEBP"}
class Features:
"""Результат извлечения; координаты — в системе приведённого изображения."""
__slots__ = ("keypoints", "descriptors", "width", "height", "source_width", "source_height")
def __init__(
self,
keypoints: np.ndarray,
descriptors: np.ndarray,
width: int,
height: int,
source_width: int,
source_height: int,
):
self.keypoints = keypoints # float32 (N, 5): x, y, size, angle, response
self.descriptors = descriptors # uint8 (N, 128)
self.width = width # размеры приведённого изображения
self.height = height
self.source_width = source_width # размеры оригинала после EXIF-ориентации
self.source_height = source_height
@property
def count(self) -> int:
return int(self.keypoints.shape[0])
def decode_image(data: bytes) -> tuple[np.ndarray, int, int]:
"""Декодирует изображение, применяет EXIF-ориентацию.
Возвращает (RGB-массив, width, height) размеры после ориентации.
Фактический формат определяется при декодировании, не по расширению
(docs/05 §5.5-1).
"""
try:
img = Image.open(io.BytesIO(data))
fmt = img.format
if fmt not in ALLOWED_IMAGE_FORMATS:
raise ImageFormatUnsupported(fmt)
img = ImageOps.exif_transpose(img)
except ImageFormatUnsupported:
raise
except Exception as exc:
raise ImageDecodeFailed(
f"Файл не декодируется как изображение: {exc.__class__.__name__}"
) from exc
arr = np.asarray(img.convert("RGB"))
return arr, img.width, img.height
def _preprocess(rgb: np.ndarray, params: ExtractionParams) -> tuple[np.ndarray, int, int]:
"""Grayscale → ресайз длинной стороны ≤ max_image_size → CLAHE."""
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
h, w = gray.shape[:2]
long_side = max(h, w)
if long_side > params.max_image_size:
scale = params.max_image_size / long_side
gray = cv2.resize(
gray,
(max(1, round(w * scale)), max(1, round(h * scale))),
interpolation=cv2.INTER_AREA,
)
clahe = cv2.createCLAHE(
clipLimit=float(params.clahe_clip_limit),
tileGridSize=(int(params.clahe_tile_grid[0]), int(params.clahe_tile_grid[1])),
)
return clahe.apply(gray), gray.shape[1], gray.shape[0]
def extract(data: bytes, params: ExtractionParams) -> Features:
"""Полный пайплайн извлечения признаков (docs/04 §4.2)."""
rgb, src_w, src_h = decode_image(data)
if src_w < MIN_WIDTH or src_h < MIN_HEIGHT:
raise ImageTooSmall(src_w, src_h)
prepared, width, height = _preprocess(rgb, params)
sift = cv2.SIFT_create(nfeatures=int(params.max_keypoints))
keypoints, descriptors = sift.detectAndCompute(prepared, None)
n = len(keypoints)
if n == 0 or descriptors is None:
# «Бедная» текстура деградирует без исключений (UT-07)
return Features(
np.zeros((0, 5), dtype=np.float32),
np.zeros((0, 128), dtype=np.uint8),
width, height, src_w, src_h,
)
kp_array = np.array(
[[kp.pt[0], kp.pt[1], kp.size, kp.angle, kp.response] for kp in keypoints],
dtype=np.float32,
).reshape(n, 5)
# Значения SIFT-дескрипторов дискретны 0–255: uint8 хранит их без потерь (docs/06 §6.2)
desc_u8 = np.clip(np.rint(descriptors), 0, 255).astype(np.uint8)
return Features(kp_array, desc_u8, width, height, src_w, src_h)
+243
View File
@@ -0,0 +1,243 @@
"""Параметры распознавания: описатели, строгая валидация, профили.
Две группы параметров (docs/04 §4.5.1):
- извлечение (extraction) — входит в отпечаток algo_id блоба;
- сравнение (comparison) — применяется к запросу, в блоб не входит (кроме
секции settings как значений по умолчанию для /verify).
Валидация строгая (FR-008): неизвестные ключи и значения вне диапазонов
отвергаются, чтобы ловить опечатки интегратора.
"""
from __future__ import annotations
from dataclasses import dataclass
from app.config import Config, DEFAULT_CLAHE_CLIP_LIMIT, DEFAULT_CLAHE_TILE_GRID
from app.cv.exceptions import BlobInvalid, InvalidSettings, UnknownProfile
GEOMETRY_MODELS = ("homography", "fundamental")
# Диапазоны допустимых значений settings-запроса. Документация фиксирует
# лишь требование «значения в диапазонах» (NFR-011); конкретные границы
# определены здесь и применяются и к env, и к запросам.
_SETTINGS_LIMITS = {
"max_image_size": ("int", 320, 8192),
"max_keypoints": ("int", 100, 65536),
"clahe_clip_limit": ("float", 0.5, 10.0),
"ransac_reproj_threshold": ("float", 1.0, 15.0),
"lowe_ratio": ("float", 0.5, 0.95),
"match_inliers_min": ("int", 5, 1000),
"match_inliers_ratio_min": ("float", 0.05, 0.95),
"match_coverage_min": ("float", 0.0, 0.5),
"uncertain_inliers_min": ("int", 1, 500),
}
_EXTRACTION_KEYS = {"max_image_size", "max_keypoints", "clahe_clip_limit", "clahe_tile_grid"}
_COMPARISON_KEYS = {
"geometry_model",
"lowe_ratio",
"ransac_reproj_threshold",
"match_inliers_min",
"match_inliers_ratio_min",
"match_coverage_min",
"uncertain_inliers_min",
}
@dataclass(frozen=True)
class ExtractionParams:
"""Эффективные параметры извлечения — полностью входят в algo_id."""
max_image_size: int
max_keypoints: int
clahe_clip_limit: float
clahe_tile_grid: tuple[int, int]
def fingerprint_payload(self) -> dict:
return {
"max_image_size": self.max_image_size,
"max_keypoints": self.max_keypoints,
"clahe_clip_limit": self.clahe_clip_limit,
"clahe_tile_grid": list(self.clahe_tile_grid),
}
@dataclass(frozen=True)
class ComparisonParams:
"""Эффективные параметры сравнения — возвращаются в details.thresholds."""
geometry_model: str
lowe_ratio: float
ransac_reproj_threshold: float
match_inliers_min: int
match_inliers_ratio_min: float
match_coverage_min: float
uncertain_inliers_min: int
def thresholds_payload(self) -> dict:
return {
"inliers_match": self.match_inliers_min,
"inlier_ratio_match": self.match_inliers_ratio_min,
"coverage_min": self.match_coverage_min,
"inliers_uncertain_min": self.uncertain_inliers_min,
"geometry_model": self.geometry_model,
"lowe_ratio": self.lowe_ratio,
"ransac_reproj_threshold": self.ransac_reproj_threshold,
}
@dataclass
class RequestSettings:
"""Разобранные и провалидированные settings запроса (FR-008)."""
profile: str | None
extraction: dict
comparison: dict
def base_extraction(config: Config) -> ExtractionParams:
"""env-умолчания — низший уровень приоритета (docs/04 §4.5.4)."""
return ExtractionParams(
max_image_size=config.sift_max_image_size,
max_keypoints=config.sift_max_keypoints,
clahe_clip_limit=DEFAULT_CLAHE_CLIP_LIMIT,
clahe_tile_grid=DEFAULT_CLAHE_TILE_GRID,
)
def base_comparison(config: Config) -> ComparisonParams:
return ComparisonParams(
geometry_model="homography",
lowe_ratio=config.lowe_ratio,
ransac_reproj_threshold=config.ransac_reproj_threshold,
match_inliers_min=config.match_inliers_min,
match_inliers_ratio_min=config.match_inliers_ratio_min,
match_coverage_min=config.match_coverage_min,
uncertain_inliers_min=config.uncertain_inliers_min,
)
def _validate_scalar(key: str, value) -> None:
kind, lo, hi = _SETTINGS_LIMITS[key]
if kind == "int":
if isinstance(value, bool) or not isinstance(value, int):
raise InvalidSettings(f"Параметр {key}: ожидается целое число", {"key": key})
else:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise InvalidSettings(f"Параметр {key}: ожидается число", {"key": key})
if not lo <= value <= hi:
raise InvalidSettings(
f"Параметр {key}: значение {value} вне допустимого диапазона [{lo}, {hi}]",
{"key": key, "value": value, "min": lo, "max": hi},
)
def _validate_group(group: str, values: dict, allowed_keys: set[str]) -> dict:
if not isinstance(values, dict):
raise InvalidSettings(f"Секция {group} должна быть JSON-объектом", {"key": group})
checked: dict = {}
for key, value in values.items():
if key == "clahe_tile_grid":
if (
not isinstance(value, (list, tuple))
or len(value) != 2
or any(isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 16 for v in value)
):
raise InvalidSettings(
"Параметр clahe_tile_grid: ожидается пара целых [w, h] в диапазоне [1, 16]",
{"key": key, "value": value},
)
checked[key] = [int(value[0]), int(value[1])]
continue
if key == "geometry_model":
if value not in GEOMETRY_MODELS:
raise InvalidSettings(
f"Параметр geometry_model: ожидается одно из {list(GEOMETRY_MODELS)}",
{"key": key, "value": value},
)
checked[key] = value
continue
if key not in allowed_keys:
raise InvalidSettings(
f"Неизвестный параметр {key!r} в секции {group}", {"key": key, "group": group}
)
_validate_scalar(key, value)
checked[key] = value
return checked
def parse_settings(raw: object, config: Config) -> RequestSettings:
"""Строгая валидация settings запроса (FR-008, docs/05 §5.5-6)."""
if not isinstance(raw, dict):
raise InvalidSettings("settings должен быть JSON-объектом")
unknown_top = set(raw) - {"profile", "extraction", "comparison"}
if unknown_top:
raise InvalidSettings(
f"Неизвестные ключи settings: {sorted(unknown_top)}",
{"keys": sorted(unknown_top)},
)
profile = raw.get("profile")
if profile is not None:
if not isinstance(profile, str) or profile not in PROFILES:
raise UnknownProfile(profile if isinstance(profile, str) else repr(profile))
# потолок max_keypoints ограничен сервисным SIFT_MAX_KEYPOINTS: блоб с большим
# числом точек не прошёл бы валидацию распаковки в /verify (FR-003)
extraction = _validate_group("extraction", raw.get("extraction") or {}, _EXTRACTION_KEYS)
if "max_keypoints" in extraction:
hi = min(_SETTINGS_LIMITS["max_keypoints"][2], config.sift_max_keypoints)
if extraction["max_keypoints"] > hi:
raise InvalidSettings(
f"Параметр max_keypoints: значение {extraction['max_keypoints']} "
f"выше сервисного потолка {hi} (SIFT_MAX_KEYPOINTS)",
{"key": "max_keypoints", "max": hi},
)
comparison = _validate_group("comparison", raw.get("comparison") or {}, _COMPARISON_KEYS)
return RequestSettings(profile=profile, extraction=extraction, comparison=comparison)
def validate_stored_settings(raw: object, config: Config) -> RequestSettings:
"""Повторная валидация settings из meta блоба: блоб мог быть повреждён.
Ошибка валидности — это некорректный блоб (FEATURE_BLOB_INVALID), а не
ошибка запроса: содержимое блоба контролирует open_cv при упаковке.
"""
try:
return parse_settings(raw, config)
except InvalidSettings as exc:
raise BlobInvalid(f"meta.settings блоба невалидны: {exc}", exc.details) from exc
except UnknownProfile as exc:
raise BlobInvalid(f"meta.settings блоба содержат неизвестный профиль: {exc}") from exc
# Профили — пресеты в коде open_cv; новый профиль = релиз (FR-009).
# Указаны только отличия от базовых значений (docs/05 §5.4.4).
PROFILES: dict[str, dict] = {
"facade": {
"description": "Плоские фасады зданий (умолчание)",
"extraction": {},
"comparison": {},
},
"monument": {
"description": "Объёмные объекты: памятники, скульптуры (fundamental-модель)",
"extraction": {"clahe_clip_limit": 3.0},
"comparison": {
"geometry_model": "fundamental",
"lowe_ratio": 0.72,
"match_inliers_min": 40,
"match_coverage_min": 0.02,
},
},
"repetitive": {
"description": "Повторяющиеся структуры: лестницы, колоннады, ограды",
"extraction": {},
"comparison": {
"lowe_ratio": 0.70,
"match_inliers_ratio_min": 0.35,
"match_inliers_min": 60,
},
},
}
+92
View File
@@ -0,0 +1,92 @@
"""Резолвер настроек — единственное место слияния уровней параметров
(docs/03 §3.2.2, docs/04 §4.5.4).
Приоритет для сравнения (от слабого к сильному):
env → профиль (запрос, иначе профиль из блоба) → comparison из блоба → запрос.
Для извлечения: env → профиль запроса → extraction запроса.
"""
from __future__ import annotations
import dataclasses
from app.config import Config
from app.cv.exceptions import InvalidSettings
from app.cv.params import (
PROFILES,
ComparisonParams,
ExtractionParams,
RequestSettings,
base_comparison,
base_extraction,
)
def effective_extraction(config: Config, settings: RequestSettings | None) -> ExtractionParams:
"""env → пресет профиля запроса → переопределения extraction запроса.
Применяется в /features и к эталонам-изображениям в /verify (FR-002).
"""
params = base_extraction(config)
if settings is None:
return params
if settings.profile is not None:
params = _apply_extraction(params, PROFILES[settings.profile]["extraction"])
return _apply_extraction(params, settings.extraction)
def effective_probe_extraction(config: Config, settings: RequestSettings | None) -> ExtractionParams:
"""Извлечение пробы в /verify: env → профиль запроса.
extraction-переопределения запроса на пробу не действуют — по букве
FR-002 они применимы только к эталонам-изображениям отладочного режима.
"""
params = base_extraction(config)
if settings is not None and settings.profile is not None:
params = _apply_extraction(params, PROFILES[settings.profile]["extraction"])
return params
def effective_comparison(
config: Config,
settings: RequestSettings | None,
blob_settings: RequestSettings | None,
) -> ComparisonParams:
"""env → профиль (запрос → блоб) → comparison блоба → comparison запроса."""
params = base_comparison(config)
profile_name = settings.profile if settings is not None and settings.profile else (
blob_settings.profile if blob_settings is not None else None
)
if profile_name is not None:
params = _apply_comparison(params, PROFILES[profile_name]["comparison"])
if blob_settings is not None:
params = _apply_comparison(params, blob_settings.comparison)
if settings is not None:
params = _apply_comparison(params, settings.comparison)
if params.uncertain_inliers_min > params.match_inliers_min:
raise InvalidSettings(
"uncertain_inliers_min не может превышать match_inliers_min "
f"(эффективные значения: {params.uncertain_inliers_min} > {params.match_inliers_min})",
{"key": "uncertain_inliers_min"},
)
return params
def _apply_extraction(params: ExtractionParams, overrides: dict) -> ExtractionParams:
changes = {
"max_image_size": overrides.get("max_image_size", params.max_image_size),
"max_keypoints": overrides.get("max_keypoints", params.max_keypoints),
"clahe_clip_limit": overrides.get("clahe_clip_limit", params.clahe_clip_limit),
"clahe_tile_grid": tuple(overrides.get("clahe_tile_grid", params.clahe_tile_grid)),
}
return dataclasses.replace(params, **changes)
def _apply_comparison(params: ComparisonParams, overrides: dict) -> ComparisonParams:
changes = {k: v for k, v in overrides.items() if k in _COMPARISON_FIELD_NAMES}
return dataclasses.replace(params, **changes)
_COMPARISON_FIELD_NAMES = {f.name for f in dataclasses.fields(ComparisonParams)}
+218
View File
@@ -0,0 +1,218 @@
"""Оркестрация вычислительных сценариев: /features и /verify (docs/03 §3.3).
Единственный модуль CV-ядра, собирающий пайплайн целиком; API-слой делегирует
сюда и не касается признаков. Сравнения по эталонам исполняются в пуле
потоков (OpenCV освобождает GIL — docs/04 §4.7); порядок не влияет на итог.
"""
from __future__ import annotations
import concurrent.futures
import hashlib
import logging
from dataclasses import dataclass
import cv2
import numpy as np
from app.config import Config
from app.cv import blob as blob_codec
from app.cv import resolver
from app.cv.comparison import PairMetrics, PairResult, compare_features
from app.cv.exceptions import CvError, ImageDecodeFailed
from app.cv.extraction import Features, extract
from app.cv.params import RequestSettings, parse_settings, validate_stored_settings
logger = logging.getLogger("opencv.cv")
# Число воркеров пула сравнений: покрывает типовой запрос (≤32 эталона),
# не создавая лишних потоков на маленьких запросах.
_COMPARE_POOL_SIZE = 4
_ZIP_MAGICS = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
_JPEG_MAGIC = b"\xff\xd8\xff"
_PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
@dataclass
class ExtractionOutcome:
blob: bytes
format_version: int
algo_id: str
keypoints_count: int
image_width: int
image_height: int
@dataclass
class VerifyOutcome:
verdict: str
is_match: bool
confidence: float
references_compared: int
best_reference_index: int
metrics: PairMetrics
thresholds: dict
probe_sha256: str
class CvService:
"""Stateless-вычислитель: без состояния между запросами (FR-006)."""
def __init__(self, config: Config):
self.config = config
self._ready_reasons: list[str] = []
# ------------------------------------------------------------------ init
def init_core(self) -> tuple[bool, list[str]]:
"""Пробное извлечение признаков служебного изображения при старте (FR-005).
Проверяет работоспособность декодирования и SIFT без транспортных
ограничений (минимальное разрешение) — это диагностика ядра, а не
обработка пользовательского фото.
"""
self._ready_reasons = []
try:
rng = np.random.default_rng(0)
synthetic = (rng.random((480, 640)) * 255).astype("uint8")
sift = cv2.SIFT_create(nfeatures=self.config.sift_max_keypoints)
keypoints, descriptors = sift.detectAndCompute(synthetic, None)
if not keypoints or descriptors is None or len(keypoints) == 0:
self._ready_reasons.append("SIFT не нашёл keypoints на служебном шуме")
except Exception as exc: # noqa: BLE001 - любая ошибка = неготовность
self._ready_reasons.append(f"инициализация CV-ядра: {exc.__class__.__name__}: {exc}")
return not self._ready_reasons, self._ready_reasons
@property
def ready_reasons(self) -> list[str]:
return list(self._ready_reasons)
# ------------------------------------------------------------- /features
def extract_to_blob(self, image_bytes: bytes, settings: dict | None) -> ExtractionOutcome:
settings_req = parse_settings(settings, self.config) if settings is not None else None
params = resolver.effective_extraction(self.config, settings_req)
features = extract(image_bytes, params)
algo_id = blob_codec.compute_algo_id(params)
meta = blob_codec.build_meta(
params=params,
algo_id=algo_id,
features=features,
settings_payload=_settings_payload(settings_req),
source_sha256=hashlib.sha256(image_bytes).hexdigest(),
)
blob = blob_codec.pack(features, meta)
return ExtractionOutcome(
blob=blob,
format_version=blob_codec.FORMAT_VERSION,
algo_id=algo_id,
keypoints_count=features.count,
image_width=features.source_width,
image_height=features.source_height,
)
# --------------------------------------------------------------- /verify
def verify(
self,
probe_bytes: bytes,
reference_parts: list[bytes],
settings: dict | None,
) -> VerifyOutcome:
settings_req = parse_settings(settings, self.config) if settings is not None else None
probe = extract(probe_bytes, resolver.effective_probe_extraction(self.config, settings_req))
pairs: list[tuple[Features, RequestSettings | None]] = [
self._load_reference(part, index, settings_req)
for index, part in enumerate(reference_parts)
]
results = self._compare_all(probe, pairs, settings_req)
best_index, best = _select_best(results)
return VerifyOutcome(
verdict=best.verdict,
is_match=best.verdict == "match",
confidence=best.confidence,
references_compared=len(results),
best_reference_index=best_index,
metrics=best.metrics,
thresholds=best.thresholds.thresholds_payload(),
probe_sha256=hashlib.sha256(probe_bytes).hexdigest(),
)
# ------------------------------------------------------------- internals
def _load_reference(
self, part: bytes, index: int, settings_req: RequestSettings | None
) -> tuple[Features, RequestSettings | None]:
"""Эталон запроса: блоб .npz или изображение (отладочный режим, Q-4)."""
try:
if part[:4] in _ZIP_MAGICS:
unpacked = blob_codec.unpack(part, self.config)
stored = (
validate_stored_settings(unpacked.settings, self.config)
if unpacked.settings is not None
else None
)
return unpacked.features, stored
if _is_image_signature(part):
params = resolver.effective_extraction(self.config, settings_req)
return extract(part, params), None
raise ImageDecodeFailed(
"Часть reference не распознана ни как блоб .npz, ни как изображение"
)
except CvError as exc:
exc.details.setdefault("reference_index", index)
raise
def _compare_all(
self,
probe: Features,
pairs: list[tuple[Features, RequestSettings | None]],
settings_req: RequestSettings | None,
) -> list[PairResult]:
def run(item: tuple[Features, RequestSettings | None]) -> PairResult:
ref_features, blob_settings = item
params = resolver.effective_comparison(self.config, settings_req, blob_settings)
return compare_features(probe, ref_features, params)
if len(pairs) == 1:
return [run(pairs[0])]
with concurrent.futures.ThreadPoolExecutor(
max_workers=min(_COMPARE_POOL_SIZE, len(pairs))
) as pool:
return list(pool.map(run, pairs))
def _select_best(results: list[PairResult]) -> tuple[int, PairResult]:
"""Пара с максимальным confidence; при равенстве — с большим inliers,
затем меньший индекс (docs/04 §4.4)."""
best_index = 0
for i in range(1, len(results)):
cand, best = results[i], results[best_index]
if (cand.confidence, cand.metrics.inliers) > (best.confidence, best.metrics.inliers):
best_index = i
return best_index, results[best_index]
def _settings_payload(settings_req: RequestSettings | None) -> dict | None:
"""settings как переданы в /features — записываются в блоб (docs/06 §6.3)."""
if settings_req is None:
return None
payload: dict = {}
if settings_req.profile is not None:
payload["profile"] = settings_req.profile
if settings_req.extraction:
payload["extraction"] = dict(settings_req.extraction)
if settings_req.comparison:
payload["comparison"] = dict(settings_req.comparison)
return payload
def _is_image_signature(part: bytes) -> bool:
if part[:3] == _JPEG_MAGIC:
return True
if part[:8] == _PNG_MAGIC:
return True
return part[:4] == b"RIFF" and part[8:12] == b"WEBP"
+50
View File
@@ -0,0 +1,50 @@
"""Структурированные JSON-логи в stdout (NFR-006).
Логируются обращения к /api/v1/* (без тел), вердикты и ошибки с trace_id.
X-API-Key и тела запросов не логируются никогда.
"""
from __future__ import annotations
import json
import logging
import sys
import time
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload: dict[str, object] = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created))
+ f".{int(record.msecs):03d}Z",
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
}
fields = getattr(record, "fields", None)
if isinstance(fields, dict):
payload.update(fields)
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload, ensure_ascii=False)
def setup_logging(level: str) -> None:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
root = logging.getLogger()
root.handlers.clear()
root.addHandler(handler)
try:
root.setLevel(level.upper())
except ValueError:
root.setLevel(logging.INFO)
# Логи uvicorn идут через единый JSON-форматтер (NFR-006); access-log
# uvicorn отключается флагом --no-access-log — его роль играет middleware.
for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
uvicorn_logger = logging.getLogger(name)
uvicorn_logger.handlers.clear()
uvicorn_logger.propagate = True
def log_event(logger: logging.Logger, level: int, message: str, **fields: object) -> None:
logger.log(level, message, extra={"fields": fields})
+105
View File
@@ -0,0 +1,105 @@
"""Точка входа FastAPI: сборка приложения, middleware, инициализация ядра.
Запуск: uvicorn app.main:app (см. docs/07-развертывание.md).
"""
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 app.api.errors import error_body, install_error_handlers
from app.api.routes import health_router, router
from app.config import Config
from app.cv.service import CvService
from app.logging_setup import log_event, setup_logging
logger = logging.getLogger("opencv")
# Запас на multipart-обёртки и settings при ранней проверке Content-Length
# для /features: сама image-часть проверяется точно после разбора.
_FEATURES_BODY_SLACK_BYTES = 1024 * 1024
def create_app(config: Config | None = None) -> FastAPI:
config = config or Config.from_env()
config.validate_cross()
setup_logging(config.log_level)
@asynccontextmanager
async def lifespan(app: FastAPI):
# FR-005: пробное извлечение признаков служебного изображения
ok, _ = app.state.cv.init_core()
app.state.ready = ok
if ok:
log_event(logger, logging.INFO, "CV core initialized")
else:
log_event(logger, logging.ERROR, "CV core not ready", reasons=app.state.cv.ready_reasons)
yield
app = FastAPI(title="open_cv", version="1.0.0", lifespan=lifespan)
app.state.config = config
app.state.cv = CvService(config)
app.state.ready = False
app.include_router(router)
app.include_router(health_router)
install_error_handlers(app)
@app.middleware("http")
async def observability(request: Request, call_next):
request.state.trace_id = uuid.uuid4().hex[:12]
# Ранние проверки размера — до чтения тела в память (docs/03 §3.6)
if request.method == "POST":
limit = _body_limit(request.url.path, config)
content_length = request.headers.get("content-length")
if limit is not None and content_length is not None:
try:
declared = int(content_length)
except ValueError:
declared = None
if declared is not None and declared > limit:
return JSONResponse(
status_code=413,
content=error_body(
"PAYLOAD_TOO_LARGE",
f"Тело запроса превышает лимит {limit // (1024 * 1024)} МБ",
request.state.trace_id,
{"limit": limit, "content_length": declared},
),
)
started = time.perf_counter()
try:
response = await call_next(request)
except Exception:
log_event(
logger, logging.ERROR, "request failed",
method=request.method, path=request.url.path,
trace_id=request.state.trace_id,
duration_ms=int((time.perf_counter() - started) * 1000),
)
raise
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=int((time.perf_counter() - started) * 1000),
trace_id=request.state.trace_id,
)
response.headers["X-Trace-Id"] = request.state.trace_id
return response
return app
def _body_limit(path: str, config: Config) -> int | None:
if path == "/api/v1/verify":
return config.verify_max_body_bytes
if path == "/api/v1/features":
return config.max_image_bytes + _FEATURES_BODY_SLACK_BYTES
return None