diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5bf07da --- /dev/null +++ b/.env.example @@ -0,0 +1,30 @@ +# Конфигурация open_cv — скопируйте в .env и заполните (docs/07 §7.4). +# .env не коммитится (в .gitignore); APP_API_KEY храните в секрет-хранилище. + +# --- обязательные --- +APP_API_KEY=change-me + +# --- привязка uvicorn --- +HOST=0.0.0.0 +PORT=8000 +WORKERS=2 + +# --- лимиты входа --- +MAX_IMAGE_MB=20 +VERIFY_MAX_BODY_MB=64 +MAX_REFERENCES_PER_REQUEST=32 + +# --- параметры извлечения (низший приоритет; входят в algo_id) --- +SIFT_MAX_IMAGE_SIZE=1600 +SIFT_MAX_KEYPOINTS=16384 + +# --- параметры сравнения и пороги (низший приоритет) --- +LOWE_RATIO=0.75 +RANSAC_REPROJ_THRESHOLD=5.0 +MATCH_INLIERS_MIN=50 +MATCH_INLIERS_RATIO_MIN=0.30 +MATCH_COVERAGE_MIN=0.05 +UNCERTAIN_INLIERS_MIN=20 + +# --- логирование --- +LOG_LEVEL=INFO diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2c3447a --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,63 @@ +{ + // Отладка open_cv в VS Code (F5). Репозиторий открывать как папку WSL + // (Remote - WSL), чтобы путь к интерпретатору .venv работал. + // APP_API_KEY обязательна — без неё процесс падает на старте (fail-fast). + "version": "0.2.0", + "configurations": [ + { + "name": "open_cv: uvicorn (debug)", + "type": "debugpy", + "request": "launch", + "module": "uvicorn", + "args": [ + "app.main:create_app", + "--factory", + "--no-access-log", + "--host", "127.0.0.1", + "--port", "8000" + ], + "cwd": "${workspaceFolder}", + "python": "${workspaceFolder}/.venv/bin/python", + "env": { + "APP_API_KEY": "dev-key", + "LOG_LEVEL": "INFO" + }, + "console": "integratedTerminal" + }, + { + // Автоперезагрузка при изменении файлов. После reload uvicorn + // порождает подпроцесс — брейкпоинты могут не переподключиться; + // для отладки со стоп-поинтами используйте конфигурацию выше. + "name": "open_cv: uvicorn (reload)", + "type": "debugpy", + "request": "launch", + "module": "uvicorn", + "args": [ + "app.main:create_app", + "--factory", + "--no-access-log", + "--reload", + "--host", "127.0.0.1", + "--port", "8000" + ], + "cwd": "${workspaceFolder}", + "python": "${workspaceFolder}/.venv/bin/python", + "env": { + "APP_API_KEY": "dev-key", + "LOG_LEVEL": "INFO" + }, + "console": "integratedTerminal" + }, + { + // Прогон тестов под отладчиком: стоп-поинты в app/ и tests/. + "name": "open_cv: pytest", + "type": "debugpy", + "request": "launch", + "module": "pytest", + "args": ["-q"], + "cwd": "${workspaceFolder}", + "python": "${workspaceFolder}/.venv/bin/python", + "console": "integratedTerminal" + } + ] +} diff --git a/AGENTS.md b/AGENTS.md index 04b735a..9033a53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,7 @@ Guidance for ZCode agents working in this repository. Фотографии, блобы признаков, реестр зданий и аудит принадлежат **основному сервису** (отдельный репозиторий) и S3 — этот сервис ничего не хранит и не имеет доступа к S3/БД/диску. -**Проект находится на стадии анализа: кода нет, вся проектная документация — в `docs/`.** +**Проект реализован по документации в `docs/` (MVP); ключевые контракты — там же.** ## Documentation-first workflow @@ -52,12 +52,27 @@ Guidance for ZCode agents working in this repository. ## Current state — what does and does not exist -- No `requirements.txt`, `pyproject.toml`, `setup.py`, or lockfile. Do not assume - any package manager (pip/poetry/uv/pdm); confirm with the user before adding one. -- No test framework, linter, or type-checker is configured. Planned per docs: - pytest + httpx; `.gitignore` anticipates pytest, mypy, and ruff caches. -- Планируемый стек (см. docs/03): FastAPI, opencv-python-headless, numpy, Pillow. - БД/ORM отсутствуют по архитектуре — не добавлять. +- Service is **implemented** (Python 3.12, FastAPI): `app/api` (transport layer) + and `app/cv` (pure CV core; layer rule `api → cv` — see «Fixed technology + decisions»). +- Dependencies: `requirements.txt` (runtime) and `requirements-dev.txt` + (+pytest/httpx) via **pip**; local venv in `.venv/` (gitignored). + Do not introduce another package manager (poetry/uv/pdm) without user + confirmation. +- Test framework: **pytest** (configured in `pytest.ini`, `testpaths=tests`). + Unit tests in `tests/unit` (UT-01..18), integration in `tests/api` (IT-01..17) + per `docs/08`; fixtures are synthetic OpenCV images (`tests/synth.py`) — + real photos are never committed (docs/08 §8.6). +- Common commands (from repo root): + - run tests: `.venv/bin/python -m pytest` + - run dev server: `APP_API_KEY=... .venv/bin/uvicorn app.main:create_app --factory --no-access-log` + - prod: `docker compose up -d` (multi-stage Dockerfile, python:3.12-slim, + `opencv-python-headless`, non-root `appuser`, port 8000, env from `.env`). +- Planned but **not implemented**: acceptance dataset/calibration script + (docs/08 §8.4), Prometheus metrics (outside MVP), v2 extensions + (`/identify`, embeddings). +- No linter/type-checker configured yet (`.gitignore` anticipates ruff/mypy). +- БД/ORM/S3-клиент отсутствуют по архитектуре — не добавлять. - Virtual environments (`venv/`, `.venv/`, `env/`) and `.env` files are gitignored; never commit them or secrets within them. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f9bdcd2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +# open_cv — stateless CV-сервис (docs/07-развертывание.md §7.2) +# Multi-stage: сборка зависимостей → тонкий runtime-слой. +# Только opencv-python-headless: обычный пакет тянет GTK/Qt и падает +# в контейнере без X-библиотек. + +FROM python:3.12-slim AS builder +WORKDIR /build +COPY requirements.txt . +RUN pip install --no-cache-dir --no-compile --prefix=/install -r requirements.txt + +FROM python:3.12-slim +RUN useradd --create-home --shell /usr/sbin/nologin appuser +WORKDIR /srv/app +COPY --from=builder /install /usr/local +COPY app ./app + +# Непривилегированный пользователь; томов с данными нет — состояние +# процесса только конфигурация из окружения (FR-006, NFR-008). +USER appuser +ENV HOST=0.0.0.0 \ + PORT=8000 \ + WORKERS=2 + +EXPOSE 8000 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD ["python", "-c", "import urllib.request,sys; r=urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3); sys.exit(0 if r.status==200 else 1)"] + +ENTRYPOINT ["sh", "-c", "exec uvicorn app.main:create_app --factory --no-access-log --host ${HOST} --port ${PORT} --workers ${WORKERS}"] diff --git a/README.md b/README.md index a665c9c..3f2142d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,11 @@ flowchart LR ## Статус проекта -**Стадия анализа.** Кода пока нет; репозиторий содержит пакет проектной документации, по которой ведётся разработка. +**MVP реализован** по документации из `docs/`: два вычислительных эндпоинта, +валидация/версионирование блобов, профили настроек, аутентификация, +Docker-развёртывание, юнит- и интеграционные тесты (pytest + httpx, синтетика +на OpenCV — реальных фото в git нет). За рамками MVP — приёмочный набор и +калибровка порогов на реальных данных (docs/08 §8.4) и метрики Prometheus. ## Документация @@ -36,15 +40,55 @@ flowchart LR | [07-развертывание.md](docs/07-развертывание.md) | Docker, переменные окружения, масштабирование репликами | | [08-план-тестирования.md](docs/08-план-тестирования.md) | Тест-план, метрики качества, калибровка порогов | -## Быстрый старт (после реализации) +## Быстрый старт + +### Docker (боевой путь) ```bash +cp .env.example .env # задать APP_API_KEY docker compose up -d curl -s http://localhost:8000/ready +# -> {"status":"ready"} +``` -# раундтрип: признаки → верификация тем же фото +Smoke-раундтрип (docs/07 §7.5): + +```bash curl -X POST http://localhost:8000/api/v1/features -H "X-API-Key: $KEY" \ -F "image=@facade.jpg" -o features.npz curl -X POST http://localhost:8000/api/v1/verify -H "X-API-Key: $KEY" \ -F "probe=@facade.jpg" -F "reference=@features.npz" +# -> {"verdict":"match","is_match":true,...} + +# отладочный режим: эталон передаётся изображением, без /features +curl -X POST http://localhost:8000/api/v1/verify -H "X-API-Key: $KEY" \ + -F "probe=@facade.jpg" -F "reference=@facade.jpg" +``` + +### Локальная разработка + +Python ≥ 3.11, зависимости — pip (`requirements.txt`; тесты — `requirements-dev.txt`). + +```bash +python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt +export APP_API_KEY=dev-key +.venv/bin/uvicorn app.main:create_app --factory --no-access-log --port 8000 +``` + +### Тесты + +```bash +.venv/bin/python -m pytest # 64 теста: UT-01..18 + IT-01..17 (docs/08) +``` + +### Структура + +``` +app/ + main.py сборка приложения, middleware (trace_id, лимиты тела, логи) + config.py конфигурация из env (docs/07 §7.4), fail-fast + api/ транспорт: маршруты, X-API-Key, единый формат ошибок + cv/ CV-ядро: extraction, comparison, blob-кодек, резолвер настроек +tests/ юнит (tests/unit) и интеграционные (tests/api) тесты +Dockerfile multi-stage python:3.12-slim, непривилегированный пользователь ``` diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..190a263 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,4 @@ +"""open_cv — stateless-сервис компьютерного зрения (SIFT-извлечение и верификация). + +Слои: ``app.api`` (транспорт, FastAPI) → ``app.cv`` (чистое CV-ядро). +""" diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..36fe4df --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1,5 @@ +"""API-слой: маршруты, multipart, лимиты, X-API-Key, единый формат ошибок. + +Бизнес-логики нет — только валидация транспорта и делегация в CV-ядро +(docs/03 §3.2.1). +""" diff --git a/app/api/deps.py b/app/api/deps.py new file mode 100644 index 0000000..656d30a --- /dev/null +++ b/app/api/deps.py @@ -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}, + ) diff --git a/app/api/errors.py b/app/api/errors.py new file mode 100644 index 0000000..6aa231a --- /dev/null +++ b/app/api/errors.py @@ -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), + ), + ) diff --git a/app/api/routes.py b/app/api/routes.py new file mode 100644 index 0000000..ea99876 --- /dev/null +++ b/app/api/routes.py @@ -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", + ) diff --git a/app/api/schemas.py b/app/api/schemas.py new file mode 100644 index 0000000..7b6ee7b --- /dev/null +++ b/app/api/schemas.py @@ -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] diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..0df81c0 --- /dev/null +++ b/app/config.py @@ -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)) diff --git a/app/cv/__init__.py b/app/cv/__init__.py new file mode 100644 index 0000000..e60dd9a --- /dev/null +++ b/app/cv/__init__.py @@ -0,0 +1,6 @@ +"""CV-ядро: extract / compare / резолвер настроек / блоб-кодек. + +Чистый Python-модуль без зависимостей от FastAPI: не импортирует веб-слой, +не знает HTTP-кодов, ошибки выражает типизированными исключениями +(правило слоёв — docs/03-архитектура.md §3.5). +""" diff --git a/app/cv/blob.py b/app/cv/blob.py new file mode 100644 index 0000000..c2b4c26 --- /dev/null +++ b/app/cv/blob.py @@ -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 хранит массивы как .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)) diff --git a/app/cv/comparison.py b/app/cv/comparison.py new file mode 100644 index 0000000..2dbbe07 --- /dev/null +++ b/app/cv/comparison.py @@ -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) diff --git a/app/cv/exceptions.py b/app/cv/exceptions.py new file mode 100644 index 0000000..0dc3b80 --- /dev/null +++ b/app/cv/exceptions.py @@ -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).""" diff --git a/app/cv/extraction.py b/app/cv/extraction.py new file mode 100644 index 0000000..53c8fb9 --- /dev/null +++ b/app/cv/extraction.py @@ -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) diff --git a/app/cv/params.py b/app/cv/params.py new file mode 100644 index 0000000..5dfc1a8 --- /dev/null +++ b/app/cv/params.py @@ -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, + }, + }, +} diff --git a/app/cv/resolver.py b/app/cv/resolver.py new file mode 100644 index 0000000..1545934 --- /dev/null +++ b/app/cv/resolver.py @@ -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)} diff --git a/app/cv/service.py b/app/cv/service.py new file mode 100644 index 0000000..a7c12a1 --- /dev/null +++ b/app/cv/service.py @@ -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" diff --git a/app/logging_setup.py b/app/logging_setup.py new file mode 100644 index 0000000..20e5999 --- /dev/null +++ b/app/logging_setup.py @@ -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}) diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..8a93f51 --- /dev/null +++ b/app/main.py @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..96cf855 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +# docs/07-развертывание.md §7.3: stateless-реплики за балансировщиком. +# Реплики обязаны иметь идентичную конфигурацию (общий env из .env). +services: + opencv-service: + image: opencv-service:latest + build: . + ports: + - "8000:8000" + env_file: .env # секреты не коммитятся + restart: unless-stopped + deploy: + replicas: 2 # stateless: реплики за балансировщиком diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..505a8a0 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +testpaths = tests +filterwarnings = + ignore::DeprecationWarning diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..82cc840 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,4 @@ +# Инструменты разработки — docs/08-план-тестирования.md §8.1 +-r requirements.txt +pytest>=8 +httpx>=0.27 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..57f2b4f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +# Планируемый стек — docs/03-архитектура.md §3.4 +fastapi>=0.115 +uvicorn>=0.30 +opencv-python-headless>=4.10,<5 +numpy>=1.26,<3 +Pillow>=10 +python-multipart>=0.0.9 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/api/__init__.py b/tests/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/api/helpers.py b/tests/api/helpers.py new file mode 100644 index 0000000..0236236 --- /dev/null +++ b/tests/api/helpers.py @@ -0,0 +1,55 @@ +"""Помощники интеграционных тестов: вызовы API и модификация блобов.""" +from __future__ import annotations + +import io +import json + +import numpy as np + +API_KEY_HEADERS = {"X-API-Key": "test-key"} + + +def post_features(client, image: bytes, settings: dict | None = None): + data = {"settings": json.dumps(settings)} if settings else None + return client.post( + "/api/v1/features", + headers=API_KEY_HEADERS, + files={"image": ("image.jpg", image, "image/jpeg")}, + data=data, + ) + + +def post_verify(client, probe: bytes, references: list[tuple[str, bytes, str]], settings: dict | None = None): + """references — список (имя, байты, content_type).""" + files = [("probe", ("probe.jpg", probe, "image/jpeg"))] + files += [("reference", (name, body, ctype)) for name, body, ctype in references] + data = {"settings": json.dumps(settings)} if settings else None + return client.post( + "/api/v1/verify", + headers=API_KEY_HEADERS, + files=files, + data=data, + ) + + +def make_blob_ref(blob: bytes) -> tuple[str, bytes, str]: + return ("reference.npz", blob, "application/octet-stream") + + +def make_image_ref(image: bytes) -> tuple[str, bytes, str]: + return ("reference.jpg", image, "image/jpeg") + + +def rewrite_blob_meta(blob: bytes, **overrides) -> bytes: + """Пересобирает блоб с изменёнными полями meta (для IT-05).""" + npz = np.load(io.BytesIO(blob), allow_pickle=False) + meta = json.loads(str(npz["meta"].item())) + meta.update(overrides) + buffer = io.BytesIO() + np.savez_compressed( + buffer, + descriptors=npz["descriptors"], + keypoints=npz["keypoints"], + meta=np.array(json.dumps(meta)), + ) + return buffer.getvalue() diff --git a/tests/api/test_auth_profiles_health.py b/tests/api/test_auth_profiles_health.py new file mode 100644 index 0000000..0e4253f --- /dev/null +++ b/tests/api/test_auth_profiles_health.py @@ -0,0 +1,86 @@ +"""Интеграционные тесты: аутентификация, единый формат ошибок, профили, +health/ready — docs/08 §8.3, IT-08, IT-09, IT-17.""" +from __future__ import annotations + +import numpy as np + +from tests.api.helpers import make_blob_ref, post_features, post_verify + + +class TestAuth: + def test_it08_missing_key_401(self, client, facade_a): + response = client.post( + "/api/v1/features", + files={"image": ("image.jpg", facade_a, "image/jpeg")}, + ) + assert response.status_code == 401 + assert response.json()["error"]["code"] == "UNAUTHORIZED" + + def test_it08_wrong_key_403(self, client, facade_a): + response = client.post( + "/api/v1/features", + headers={"X-API-Key": "wrong-key"}, + files={"image": ("image.jpg", facade_a, "image/jpeg")}, + ) + assert response.status_code == 403 + assert response.json()["error"]["code"] == "FORBIDDEN" + + def test_it08_health_without_key(self, client): + """IT-08: /health без ключа — 200 (FR-004).""" + response = client.get("/health") + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + def test_ready_without_key(self, client): + response = client.get("/ready") + assert response.status_code == 200 + assert response.json() == {"status": "ready"} + + def test_profiles_require_key(self, client): + assert client.get("/api/v1/profiles").status_code == 401 + assert client.get("/api/v1/profiles", headers={"X-API-Key": "bad"}).status_code == 403 + + +class TestErrorFormat: + def test_it09_unified_error_shape(self, client, facade_a, blob_a): + """IT-09: все 4xx соответствуют единому формату ошибки.""" + cases = [ + client.post("/api/v1/verify", headers={"X-API-Key": "nope"}, files=[]), + post_features(client, b"not an image"), + post_verify(client, facade_a, []), + post_verify(client, facade_a, [make_blob_ref(blob_a[:100])]), + ] + for response in cases: + assert 400 <= response.status_code < 500, response.status_code + body = response.json() + error = body["error"] + assert set(error) >= {"code", "message", "details", "trace_id"} + assert isinstance(error["code"], str) and error["code"] + assert len(error["trace_id"]) == 12 + + +class TestProfiles: + def test_it17_catalog(self, client): + """IT-17: каталог содержит facade, monument, repetitive (FR-009).""" + response = client.get("/api/v1/profiles", headers={"X-API-Key": "test-key"}) + assert response.status_code == 200 + body = response.json() + names = {p["name"] for p in body["profiles"]} + assert {"facade", "monument", "repetitive"} <= names + + monument = next(p for p in body["profiles"] if p["name"] == "monument") + assert monument["comparison"]["geometry_model"] == "fundamental" + assert monument["extraction"]["clahe_clip_limit"] == 3.0 + + repetitive = next(p for p in body["profiles"] if p["name"] == "repetitive") + assert repetitive["comparison"]["lowe_ratio"] == 0.70 + assert repetitive["comparison"]["match_inliers_min"] == 60 + + # базовые значения для наследования незаполненных полей + assert body["defaults"]["comparison"]["inliers_match"] == 50 + + def test_facade_profile_is_default(self, client): + response = client.get("/api/v1/profiles", headers={"X-API-Key": "test-key"}) + facade = next(p for p in response.json()["profiles"] if p["name"] == "facade") + assert facade["extraction"] == {} + assert facade["comparison"] == {} diff --git a/tests/api/test_features.py b/tests/api/test_features.py new file mode 100644 index 0000000..863f26f --- /dev/null +++ b/tests/api/test_features.py @@ -0,0 +1,131 @@ +"""Интеграционные тесты POST /api/v1/features — docs/08 §8.3, IT-01, IT-07, +IT-10, IT-14, IT-15.""" +from __future__ import annotations + +import io +import json + +import numpy as np +import pytest + +from tests.api.helpers import post_features + + +class TestFeaturesEndpoint: + def test_it01_valid_photo(self, client, facade_a): + """IT-01: 200, контрактные заголовки, тело читается numpy.load.""" + response = post_features(client, facade_a) + assert response.status_code == 200 + assert response.headers["content-type"] == "application/octet-stream" + assert response.headers["x-feature-format-version"] == "1" + assert response.headers["x-algo-id"].startswith("sift-v1:") + kp_count = int(response.headers["x-keypoints-count"]) + assert kp_count > 0 + assert int(response.headers["x-image-width"]) == 1400 + assert int(response.headers["x-image-height"]) == 900 + + npz = np.load(io.BytesIO(response.content), allow_pickle=False) + assert npz["descriptors"].shape == (kp_count, 128) + meta = json.loads(str(npz["meta"].item())) + assert meta["format_version"] == 1 + assert meta["keypoints_count"] == kp_count + + def test_it10_idempotency(self, client, facade_a): + """IT-10: два вызова с тем же файлом — эквивалентные массивы (FR-007).""" + first = post_features(client, facade_a) + second = post_features(client, facade_a) + assert first.status_code == second.status_code == 200 + + n1 = np.load(io.BytesIO(first.content), allow_pickle=False) + n2 = np.load(io.BytesIO(second.content), allow_pickle=False) + assert np.array_equal(n1["descriptors"], n2["descriptors"]) + assert np.array_equal(n1["keypoints"], n2["keypoints"]) + m1 = json.loads(str(n1["meta"].item())) + m2 = json.loads(str(n2["meta"].item())) + m1.pop("created_at"), m2.pop("created_at") # различие метки времени допустимо + assert m1 == m2 + + def test_it14_settings_change_algo_id(self, client, facade_a): + """IT-14: профиль monument + переопределение меняют X-Algo-Id; + meta.settings записываются в блоб.""" + plain = post_features(client, facade_a) + tuned = post_features( + client, facade_a, + settings={"profile": "monument", "extraction": {"clahe_clip_limit": 4.0}}, + ) + assert plain.status_code == tuned.status_code == 200 + assert tuned.headers["x-algo-id"] != plain.headers["x-algo-id"] + + npz = np.load(io.BytesIO(tuned.content), allow_pickle=False) + meta = json.loads(str(npz["meta"].item())) + assert meta["settings"] == { + "profile": "monument", + "extraction": {"clahe_clip_limit": 4.0}, + } + + def test_it15_unknown_profile(self, client, facade_a): + response = post_features(client, facade_a, settings={"profile": "castle"}) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "UNKNOWN_PROFILE" + + def test_it15_unknown_settings_key(self, client, facade_a): + response = post_features(client, facade_a, settings={"comparison": {"threshold": 5}}) + assert response.status_code == 422 + assert response.json()["error"]["code"] == "INVALID_SETTINGS" + + def test_it15_value_out_of_range(self, client, facade_a): + response = post_features(client, facade_a, settings={"comparison": {"lowe_ratio": 2.0}}) + assert response.status_code == 422 + assert response.json()["error"]["code"] == "INVALID_SETTINGS" + + def test_it07_invalid_images(self, client, tiny_image): + """IT-07: пустой файл, текст .jpg, 300×200 — 4xx, процесс жив.""" + empty = post_features(client, b"") + assert empty.status_code == 400 + assert empty.json()["error"]["code"] == "IMAGE_DECODE_FAILED" + + text = post_features(client, b"this is definitely not an image") + assert text.status_code == 400 + assert text.json()["error"]["code"] == "IMAGE_DECODE_FAILED" + + small = post_features(client, tiny_image) + assert small.status_code == 400 + assert small.json()["error"]["code"] == "IMAGE_TOO_SMALL" + + # процесс жив после некорректного ввода (NFR-004) + assert post_features(client, tiny_image).status_code == 400 + assert client.get("/health").status_code == 200 + + def test_it07_oversized_image_413(self, client): + """IT-07: изображение больше MAX_IMAGE_MB — 413 (CL проверяется рано).""" + big = b"\xff\xd8\xff\xe0" + b"\x00" * (2 * 1024 * 1024) # > 1 МБ тестового лимита + response = post_features(client, big) + assert response.status_code == 413 + assert response.json()["error"]["code"] == "PAYLOAD_TOO_LARGE" + + def test_415_unsupported_media_type(self, client): + """415: часть image заявлена как image/gif (05 §5.3).""" + response = client.post( + "/api/v1/features", + headers={"X-API-Key": "test-key"}, + files={"image": ("image.gif", b"GIF89a....", "image/gif")}, + ) + assert response.status_code == 415 + assert response.json()["error"]["code"] == "UNSUPPORTED_MEDIA_TYPE" + + def test_missing_image_part(self, client, facade_a): + response = client.post( + "/api/v1/features", + headers={"X-API-Key": "test-key"}, + files={"photo": ("image.jpg", facade_a, "image/jpeg")}, + ) + assert response.status_code == 422 + assert response.json()["error"]["code"] == "VALIDATION_ERROR" + assert response.json()["error"]["details"]["part"] == "image" + + def test_exif_orientation_headers(self, client, exif_image): + """EXIF-ориентация применяется сервером: 1400×900 с orientation 6 → 900×1400.""" + response = post_features(client, exif_image) + assert response.status_code == 200 + assert int(response.headers["x-image-width"]) == 900 + assert int(response.headers["x-image-height"]) == 1400 diff --git a/tests/api/test_verify.py b/tests/api/test_verify.py new file mode 100644 index 0000000..fbeda6f --- /dev/null +++ b/tests/api/test_verify.py @@ -0,0 +1,145 @@ +"""Интеграционные тесты POST /api/v1/verify — docs/08 §8.3, IT-02..IT-07, +IT-11..IT-13, IT-16.""" +from __future__ import annotations + +import pytest + +from tests.api.helpers import ( + make_blob_ref, + make_image_ref, + post_features, + post_verify, + rewrite_blob_meta, +) + + +class TestVerifyEndpoint: + def test_it02_roundtrip_same_photo(self, client, facade_a, blob_a): + """IT-02: /features → /verify с той же пробой — match.""" + response = post_verify(client, facade_a, [make_blob_ref(blob_a)]) + assert response.status_code == 200 + body = response.json() + assert body["verdict"] == "match" + assert body["is_match"] is True + assert body["confidence"] >= 0.6 + assert body["details"]["best_reference_index"] == 0 + assert body["details"]["references_compared"] == 1 + assert len(body["probe_sha256"]) == 64 + assert body["processing_ms"] >= 0 + thresholds = body["details"]["thresholds"] + assert thresholds["inliers_match"] == 50 + assert thresholds["inlier_ratio_match"] == pytest.approx(0.30) + assert thresholds["coverage_min"] == pytest.approx(0.05) + assert thresholds["inliers_uncertain_min"] == 20 + + def test_it03_probe_of_other_building(self, client, facade_b, blob_a): + """IT-03: проба другого здания — no_match/uncertain, не match.""" + response = post_verify(client, facade_b, [make_blob_ref(blob_a)]) + assert response.status_code == 200 + body = response.json() + assert body["verdict"] in ("no_match", "uncertain") + assert body["is_match"] is False + + def test_it04_no_references(self, client, facade_a): + """IT-04: 0 частей reference — 422 VALIDATION_ERROR.""" + response = post_verify(client, facade_a, []) + assert response.status_code == 422 + body = response.json() + assert body["error"]["code"] == "VALIDATION_ERROR" + assert body["error"]["details"]["part"] == "reference" + + def test_it04_too_many_references(self, client, facade_a): + """IT-04: 33 части reference — 400 TOO_MANY_REFERENCES. + + Части-пустышки: лимит числа эталонов проверяется до разбора контента, + но после ранней CL-проверки тела. + """ + refs = [("reference.bin", b"garbage", "application/octet-stream")] * 33 + response = post_verify(client, facade_a, refs) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "TOO_MANY_REFERENCES" + + def test_it05_unsupported_format_version(self, client, facade_a, blob_a): + """IT-05: блоб с format_version=99 — 400 FEATURE_FORMAT_UNSUPPORTED, + в details — индекс эталона.""" + foreign = rewrite_blob_meta(blob_a, format_version=99) + response = post_verify(client, facade_a, [make_blob_ref(foreign)]) + assert response.status_code == 400 + body = response.json() + assert body["error"]["code"] == "FEATURE_FORMAT_UNSUPPORTED" + assert body["error"]["details"]["reference_index"] == 0 + assert body["error"]["details"]["received"] == 99 + + def test_it06_corrupted_blob(self, client, facade_a, blob_a): + """IT-06: повреждённый блоб (обрезаны байты) — 400 FEATURE_BLOB_INVALID.""" + response = post_verify(client, facade_a, [make_blob_ref(blob_a[: len(blob_a) // 2])]) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "FEATURE_BLOB_INVALID" + + def test_unrecognized_reference_content(self, client, facade_a): + response = post_verify( + client, facade_a, [("reference.bin", b"\x00\x01\x02garbage", "application/octet-stream")] + ) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "IMAGE_DECODE_FAILED" + + def test_it11_determinism(self, client, facade_a, blob_a): + """IT-11: два одинаковых /verify — идентичные результаты (NFR-009).""" + first = post_verify(client, facade_a, [make_blob_ref(blob_a)]).json() + second = post_verify(client, facade_a, [make_blob_ref(blob_a)]).json() + assert first["verdict"] == second["verdict"] + assert first["confidence"] == second["confidence"] + assert first["details"]["metrics"] == second["details"]["metrics"] + + def test_it12_debug_mode_image_reference(self, client, facade_a): + """IT-12: эталон-изображение без /features — 200, match (Q-4).""" + response = post_verify(client, facade_a, [make_image_ref(facade_a)]) + assert response.status_code == 200 + assert response.json()["verdict"] == "match" + + def test_it13_mixed_references(self, client, facade_a, facade_b, blob_a): + """IT-13: смешанные эталоны; best_reference_index сквозной по порядку.""" + refs = [make_image_ref(facade_b), make_blob_ref(blob_a), make_image_ref(facade_a)] + response = post_verify(client, facade_a, refs) + assert response.status_code == 200 + body = response.json() + assert body["details"]["references_compared"] == 3 + assert body["verdict"] == "match" + assert body["details"]["best_reference_index"] == 1 + + def test_it16_request_override_beats_blob(self, client, facade_a): + """IT-16: переопределение порога в /verify побеждает значение из блоба.""" + blob = post_features( + client, facade_a, settings={"comparison": {"match_inliers_min": 500}} + ).content + + no_override = post_verify(client, facade_a, [make_blob_ref(blob)]).json() + assert no_override["details"]["thresholds"]["inliers_match"] == 500 + + overridden = post_verify( + client, facade_a, [make_blob_ref(blob)], + settings={"comparison": {"match_inliers_min": 30}}, + ).json() + assert overridden["details"]["thresholds"]["inliers_match"] == 30 + + def test_it16_profile_from_blob(self, client, facade_a): + """Профиль, сохранённый в блобе, действует при /verify без настроек.""" + blob = post_features(client, facade_a, settings={"profile": "monument"}).content + body = post_verify(client, facade_a, [make_blob_ref(blob)]).json() + assert body["details"]["thresholds"]["geometry_model"] == "fundamental" + + def test_verify_413_body_limit(self, client, facade_a, facade_b): + """Суммарный запрос сверх VERIFY_MAX_BODY_MB (8 МБ в тестах) — 413.""" + heavy = [make_image_ref(facade_b)] * 32 # 32 × ~0.3 МБ + проба > 8 МБ + response = post_verify(client, facade_a, heavy) + assert response.status_code == 413 + assert response.json()["error"]["code"] == "PAYLOAD_TOO_LARGE" + + def test_missing_probe_part(self, client, facade_a, blob_a): + response = client.post( + "/api/v1/verify", + headers={"X-API-Key": "test-key"}, + files=[("reference", ("reference.npz", blob_a, "application/octet-stream"))], + ) + assert response.status_code == 422 + assert response.json()["error"]["details"]["part"] == "probe" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..95a92e2 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,107 @@ +"""Общие фикстуры: конфиг, приложение, клиент, синтетические изображения. + +Лимиты входа в тестовом конфиге меньше боевых (1 МБ на изображение), +чтобы сценарии 413/IT-07 не генерировали десятки мегабайт. +""" +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from app.config import Config +from app.main import create_app +from tests import synth + +TEST_API_KEY = "test-key" + + +def make_config(**overrides) -> Config: + values = dict( + api_key=TEST_API_KEY, + host="127.0.0.1", + port=8000, + workers=1, + log_level="WARNING", + max_image_bytes=1 * 1024 * 1024, + verify_max_body_bytes=8 * 1024 * 1024, + max_references=32, + sift_max_image_size=1600, + sift_max_keypoints=16384, + lowe_ratio=0.75, + ransac_reproj_threshold=5.0, + match_inliers_min=50, + match_inliers_ratio_min=0.30, + match_coverage_min=0.05, + uncertain_inliers_min=20, + ) + values.update(overrides) + return Config(**values) + + +@pytest.fixture(scope="session") +def config() -> Config: + return make_config() + + +@pytest.fixture(scope="session") +def app(config: Config): + return create_app(config) + + +@pytest.fixture(scope="session") +def client(app) -> TestClient: + with TestClient(app, raise_server_exceptions=False) as test_client: + yield test_client + + +@pytest.fixture(scope="session") +def blob_a(client: TestClient, facade_a: bytes) -> bytes: + """Блоб признаков базового «фасада», вычисленный через боевой эндпоинт.""" + from tests.api.helpers import post_features + + response = post_features(client, facade_a) + assert response.status_code == 200 + return response.content + + +# ------------------------------------------------------------ изображения + + +@pytest.fixture(scope="session") +def facade_a() -> bytes: + return synth.encode_jpg(synth.make_facade(seed=7)) + + +@pytest.fixture(scope="session") +def facade_a_warp() -> bytes: + return synth.encode_jpg(synth.warp_perspective(synth.make_facade(seed=7))) + + +@pytest.fixture(scope="session") +def facade_a_half() -> bytes: + return synth.encode_jpg(synth.scale_half(synth.make_facade(seed=7))) + + +@pytest.fixture(scope="session") +def facade_a_crop() -> bytes: + return synth.encode_jpg(synth.crop_center(synth.make_facade(seed=7))) + + +@pytest.fixture(scope="session") +def facade_b() -> bytes: + return synth.encode_jpg(synth.make_facade(seed=99)) + + +@pytest.fixture(scope="session") +def flat_image() -> bytes: + return synth.encode_jpg(synth.make_flat()) + + +@pytest.fixture(scope="session") +def tiny_image() -> bytes: + return synth.encode_jpg(synth.make_flat(width=300, height=200)) + + +@pytest.fixture(scope="session") +def exif_image() -> bytes: + return synth.encode_exif_oriented(synth.make_facade(seed=11)) diff --git a/tests/synth.py b/tests/synth.py new file mode 100644 index 0000000..a0b372a --- /dev/null +++ b/tests/synth.py @@ -0,0 +1,73 @@ +"""Синтетические изображения для тестов (docs/08 §8.2, §8.6). + +Реальных фото в git нет — только детерминированная генерация OpenCV/NumPy. +""" +from __future__ import annotations + +import cv2 +import numpy as np + + +def make_facade(seed: int = 7, width: int = 1400, height: int = 900) -> np.ndarray: + """Текстурированный «фасад»: сетка окон со случайными цветами + швы + шум.""" + rng = np.random.default_rng(seed) + img = np.full((height, width, 3), 118, np.uint8) + for y in range(0, height, 28): # кладка + cv2.line(img, (0, y), (width, y), (132, 128, 122), 1) + for y in range(40, height - 160, 140): + for x in range(60, width - 200, 190): + col = tuple(int(c) for c in rng.integers(28, 225, 3)) + cv2.rectangle(img, (x, y), (x + 110, y + 95), col, -1) + cv2.rectangle(img, (x, y), (x + 110, y + 95), (205, 198, 170), 3) + cv2.circle(img, (x + 55, y + 47), 8, (240, 240, 235), 2) + return cv2.add(img, rng.integers(0, 16, img.shape, dtype=np.uint8)) + + +def encode_jpg(img: np.ndarray, quality: int = 92) -> bytes: + ok, buf = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, quality]) + if not ok: + raise RuntimeError("не удалось закодировать JPEG") + return buf.tobytes() + + +def warp_perspective(img: np.ndarray) -> np.ndarray: + """Проективное искажение — имитация смены ракурса (UT-02).""" + h, w = img.shape[:2] + src = np.float32([[0, 0], [w, 0], [w, h], [0, h]]) + dst = np.float32( + [[w * 0.12, h * 0.10], [w * 0.95, h * 0.04], [w * 0.90, h * 0.97], [w * 0.05, h * 0.90]] + ) + m = cv2.getPerspectiveTransform(src, dst) + return cv2.warpPerspective(img, m, (w, h), flags=cv2.INTER_LINEAR) + + +def scale_half(img: np.ndarray) -> np.ndarray: + h, w = img.shape[:2] + return cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA) + + +def crop_center(img: np.ndarray, fraction: float = 0.45) -> np.ndarray: + """Фрагмент фасада — частичная видимость (UT-06).""" + h, w = img.shape[:2] + ch, cw = int(h * fraction), int(w * fraction) + y0, x0 = (h - ch) // 2, (w - cw) // 2 + return img[y0 : y0 + ch, x0 : x0 + cw] + + +def make_flat(width: int = 700, height: int = 520) -> np.ndarray: + """Однотонная заливка — «бедная» текстура (UT-07).""" + return np.full((height, width, 3), 128, np.uint8) + + +def encode_exif_oriented(img: np.ndarray, orientation: int = 6) -> bytes: + """JPEG с EXIF-ориентацией (UT-09): 6 = поворот на 90° по часовой.""" + import io + + from PIL import Image + + pil = Image.fromarray(img) + exif = Image.Exif() + exif[274] = orientation # Orientation + buffer = io.BytesIO() + pil.save(buffer, format="JPEG", exif=exif) + return buffer.getvalue() diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_blob.py b/tests/unit/test_blob.py new file mode 100644 index 0000000..4ade94a --- /dev/null +++ b/tests/unit/test_blob.py @@ -0,0 +1,149 @@ +"""Юнит-тесты блоб-кодека — docs/08 §8.2, UT-10..UT-15.""" +from __future__ import annotations + +import io +import json +import zipfile + +import numpy as np +import pytest + +from app.cv.blob import UnpackedBlob, build_meta, compute_algo_id, pack, unpack +from app.cv.exceptions import BlobInvalid, FormatUnsupported +from app.cv.extraction import Features, extract +from app.cv.params import base_extraction +from tests import synth +from tests.conftest import make_config + + +@pytest.fixture(scope="module") +def config(): + return make_config() + + +@pytest.fixture(scope="module") +def sample(config) -> tuple[Features, dict, bytes]: + features = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config)) + params = base_extraction(config) + meta = build_meta( + params=params, + algo_id=compute_algo_id(params), + features=features, + settings_payload={"profile": "monument", "comparison": {"lowe_ratio": 0.70}}, + source_sha256="ab12cd34", + ) + return features, meta, pack(features, meta) + + +def _repack(descriptors, keypoints, meta) -> bytes: + buffer = io.BytesIO() + np.savez_compressed( + buffer, + descriptors=descriptors, + keypoints=keypoints, + meta=np.array(json.dumps(meta)), + ) + return buffer.getvalue() + + +class TestBlobCodec: + def test_ut10_roundtrip(self, config, sample): + """UT-10: save → load — идентичные массивы, meta сохраняется.""" + features, meta, blob = sample + unpacked = unpack(blob, config) + + assert np.array_equal(unpacked.features.descriptors, features.descriptors) + assert np.array_equal(unpacked.features.keypoints, features.keypoints) + for key, value in meta.items(): + if key == "created_at": + continue + assert unpacked.meta[key] == value, key + + def test_ut10b_descriptor_range(self, config): + """UT-10 (продолжение): uint8-дескрипторы в диапазоне 0–255.""" + features = extract(synth.encode_jpg(synth.make_facade(seed=5)), base_extraction(config)) + assert features.descriptors.dtype == np.uint8 + assert features.descriptors.min() >= 0 and features.descriptors.max() <= 255 + + def test_ut11_uint8_float32_lossless(self): + """UT-11: конверсия uint8 ↔ float32 без потерь (значения целые).""" + descs = np.array([0, 1, 127, 254, 255] * 25 + [3, 3, 3], dtype=np.uint8).reshape(1, 128) + assert descs.dtype == np.uint8 + restored = descs.astype(np.float32).astype(np.uint8) + assert np.array_equal(descs, restored) + + def test_ut12_broken_zip(self, config): + """UT-12: битый zip / не-npz — FEATURE_BLOB_INVALID.""" + with pytest.raises(BlobInvalid): + unpack(b"not a zip at all", config) + with pytest.raises(BlobInvalid): + unpack(b"PK\x03\x04truncated", config) + + def test_ut13a_missing_array(self, config, sample): + """UT-13: отсутствует массив — FEATURE_BLOB_INVALID.""" + _, meta, _ = sample + buffer = io.BytesIO() + np.savez_compressed( + buffer, + descriptors=np.zeros((10, 128), np.uint8), + meta=np.array(json.dumps({**meta, "keypoints_count": 10})), + ) + with pytest.raises(BlobInvalid): + unpack(buffer.getvalue(), config) + + def test_ut13b_shape_mismatch(self, config, sample): + """UT-13: несогласованные формы массивов — FEATURE_BLOB_INVALID.""" + _, meta, _ = sample + descs = np.zeros((10, 128), np.uint8) + kps = np.zeros((7, 5), np.float32) + with pytest.raises(BlobInvalid): + unpack(_repack(descs, kps, {**meta, "keypoints_count": 10}), config) + + def test_ut13c_count_mismatch(self, config, sample): + """UT-13: keypoints_count ≠ N — FEATURE_BLOB_INVALID.""" + _, meta, _ = sample + descs = np.zeros((10, 128), np.uint8) + kps = np.zeros((10, 5), np.float32) + with pytest.raises(BlobInvalid): + unpack(_repack(descs, kps, {**meta, "keypoints_count": 999}), config) + + def test_ut14_format_version(self, config, sample): + """UT-14: meta.format_version не тот — FEATURE_FORMAT_UNSUPPORTED.""" + _, meta, _ = sample + descs = np.zeros((10, 128), np.uint8) + kps = np.zeros((10, 5), np.float32) + foreign = {**meta, "format_version": 99, "keypoints_count": 10} + with pytest.raises(FormatUnsupported) as excinfo: + unpack(_repack(descs, kps, foreign), config) + assert excinfo.value.details["received"] == 99 + assert excinfo.value.details["expected_format_version"] == 1 + + def test_ut15_zip_bomb(self, config, sample): + """UT-15: корректная структура, но массив сверх лимита — отклонение + по SIFT_MAX_KEYPOINTS без распаковки в память.""" + _, meta, _ = sample + small = make_config(sift_max_keypoints=100) + descs = np.zeros((20_000, 128), np.uint8) # 2.56 МБ распакованных + kps = np.zeros((20_000, 5), np.float32) + blob = _repack(descs, kps, {**meta, "keypoints_count": 20_000}) + with pytest.raises(BlobInvalid, match="лимит"): + unpack(blob, small) + + def test_meta_without_settings(self, config): + """meta без необязательного settings — читается, settings = None (06 §6.5).""" + features = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config)) + params = base_extraction(config) + meta = build_meta(params, compute_algo_id(params), features, None, "ff00") + unpacked = unpack(pack(features, meta), config) + assert unpacked.settings is None + + def test_unpacked_resized_dims(self, config, sample): + """Размеры приведённого изображения восстанавливаются из meta.""" + _, meta, blob = sample + unpacked: UnpackedBlob = unpack(blob, config) + assert unpacked.features.width <= meta["extraction_params"]["max_image_size"] + assert unpacked.features.height <= meta["extraction_params"]["max_image_size"] + ratio = unpacked.features.width / unpacked.features.source_width + assert ratio == pytest.approx( + unpacked.features.height / unpacked.features.source_height, rel=0.02 + ) diff --git a/tests/unit/test_extraction.py b/tests/unit/test_extraction.py new file mode 100644 index 0000000..01e1811 --- /dev/null +++ b/tests/unit/test_extraction.py @@ -0,0 +1,159 @@ +"""Юнит-тесты извлечения и сравнения — docs/08 §8.2, UT-01..UT-09, UT-17.""" +from __future__ import annotations + +import cv2 +import numpy as np +import pytest + +from app.cv.comparison import PairResult, compare_features +from app.cv.extraction import extract +from app.cv.params import ComparisonParams, base_extraction, base_comparison +from tests import synth +from tests.conftest import make_config + + +@pytest.fixture(scope="module") +def config(): + return make_config() + + +@pytest.fixture(scope="module") +def features_pair(config): + """Признаки базового «фасада» и его копии — общая база для UT-01..UT-08.""" + base = synth.encode_jpg(synth.make_facade(seed=7)) + f1 = extract(base, base_extraction(config)) + f2 = extract(base, base_extraction(config)) + return f1, f2 + + +def _compare(config, probe, ref, **overrides) -> PairResult: + params = base_comparison(config) + if overrides: + params = ComparisonParams(**{**vars(params), **overrides}) + return compare_features(probe, ref, params) + + +class TestExtractionComparison: + def test_ut01_photo_vs_copy(self, config, features_pair): + """UT-01: фото vs копия — match, высокий confidence, inlier_ratio ≥ 0.8.""" + f1, f2 = features_pair + result = _compare(config, f1, f2) + assert result.verdict == "match" + assert result.confidence >= 0.6 + assert result.metrics.inlier_ratio >= 0.8 + + def test_ut02_photo_vs_warped(self, config): + """UT-02: проективно искажённая копия — match.""" + base = synth.make_facade(seed=7) + f1 = extract(synth.encode_jpg(base), base_extraction(config)) + f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config)) + result = _compare(config, f1, f2) + assert result.verdict == "match" + + def test_ut03_photo_vs_half(self, config): + """UT-03: уменьшенная копия (0.5×) — match. + + База берётся 1600×1200, чтобы уменьшенная копия (800×600) оставалась + выше минимального разрешения 640×480. + """ + base = synth.make_facade(seed=7, width=1600, height=1200) + f1 = extract(synth.encode_jpg(base), base_extraction(config)) + f2 = extract(synth.encode_jpg(synth.scale_half(base)), base_extraction(config)) + result = _compare(config, f1, f2) + assert result.verdict == "match" + + def test_ut04_photo_vs_other_building(self, config): + """UT-04: другое здание — no_match или uncertain, но не match.""" + f1 = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config)) + f2 = extract(synth.encode_jpg(synth.make_facade(seed=99)), base_extraction(config)) + result = _compare(config, f1, f2) + assert result.verdict in ("no_match", "uncertain") + + def test_ut05_photo_vs_other_angle(self, config): + """UT-05: тот же объект, другой ракурс — match при «широком» ракурсе.""" + base = synth.make_facade(seed=7) + h, w = base.shape[:2] + src = np.float32([[0, 0], [w, 0], [w, h], [0, h]]) + dst = np.float32( + [[w * 0.08, h * 0.06], [w * 0.97, h * 0.10], [w * 0.88, h * 0.95], [w * 0.10, h * 0.92]] + ) + m = cv2.getPerspectiveTransform(src, dst) + other_angle = cv2.warpPerspective(base, m, (w, h)) + f1 = extract(synth.encode_jpg(base), base_extraction(config)) + f2 = extract(synth.encode_jpg(other_angle), base_extraction(config)) + assert _compare(config, f1, f2).verdict == "match" + + def test_ut06_cropped_fragment(self, config): + """UT-06: фрагмент как эталон — coverage корректно мал. + + Проба — полный кадр, эталон — кроп 60 %: инлаеры покрывают только + область фрагмента (защита от «локального совпадения» — 04 §4.3). + Кроп 60 % сохраняет разрешение выше 640×480. + """ + base = synth.make_facade(seed=7) + f_full = extract(synth.encode_jpg(base), base_extraction(config)) + f_crop = extract(synth.encode_jpg(synth.crop_center(base, fraction=0.6)), + base_extraction(config)) + result = _compare(config, f_full, f_crop) + assert result.verdict in ("uncertain", "match") + assert result.metrics.coverage == pytest.approx(0.6 * 0.6, abs=0.15) + + def test_ut07_poor_texture(self, config): + """UT-07: однотонная заливка — мало keypoints, деградация без исключений.""" + features = extract(synth.encode_jpg(synth.make_flat()), base_extraction(config)) + assert features.count < 500 + other = extract(synth.encode_jpg(synth.make_facade(seed=3)), base_extraction(config)) + result = _compare(config, features, other) # не должно упасть + assert result.verdict in ("no_match", "uncertain") + + def test_ut08_determinism(self, config, features_pair): + """UT-08: повторный compare тех же входов — идентичные метрики (NFR-009).""" + f1, f2 = features_pair + first = _compare(config, f1, f2) + second = _compare(config, f1, f2) + assert first.metrics == second.metrics + assert first.verdict == second.verdict + assert first.confidence == second.confidence + + def test_ut09_preprocessing(self, config): + """UT-09: EXIF-ориентация, ресайз, CLAHE — корректные размеры/типы.""" + from app.cv.extraction import decode_image, _preprocess + from app.cv.params import ExtractionParams + + # EXIF-ориентация 6 (поворот 90°): размеры меняются местами + raw = synth.make_facade(seed=11, width=1400, height=900) + exif_jpg = synth.encode_exif_oriented(raw, orientation=6) + _, width, height = decode_image(exif_jpg) + assert (width, height) == (900, 1400) + + # ресайз до max_image_size длинной стороны + params = ExtractionParams(max_image_size=800, max_keypoints=4096, + clahe_clip_limit=2.0, clahe_tile_grid=(8, 8)) + gray, w, h = _preprocess(np.asarray(cv2.cvtColor(raw, cv2.COLOR_BGR2RGB)), params) + assert max(w, h) <= 800 + assert gray.dtype == np.uint8 and gray.ndim == 2 + + # CLAHE не меняет размеров и тип + assert (w, h) == (gray.shape[1], gray.shape[0]) + + def test_ut17_fundamental_model(self, config): + """UT-17: fundamental на синтетической паре — метрики считаются и + детерминированы; обе модели дают согласованные вердикты. + + Сравнение абсолютных чисел инлаеров H vs F на плоской синтетике + нестабильно (порог F — расстояние до эпиполярной линии, не пиксели + репроекции), поэтому проверяется вычислимость и детерминизм. + """ + base = synth.make_facade(seed=7) + f1 = extract(synth.encode_jpg(base), base_extraction(config)) + f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config)) + + fund_a = _compare(config, f1, f2, geometry_model="fundamental") + fund_b = _compare(config, f1, f2, geometry_model="fundamental") + homo = _compare(config, f1, f2, geometry_model="homography") + + assert fund_a.metrics.inliers > 0 # метрики считаются + assert fund_a.metrics == fund_b.metrics # детерминизм + assert fund_a.confidence == fund_b.confidence + assert homo.metrics.inliers > 0 + assert homo.verdict == fund_a.verdict # согласованность моделей diff --git a/tests/unit/test_settings_resolver.py b/tests/unit/test_settings_resolver.py new file mode 100644 index 0000000..7cd1e44 --- /dev/null +++ b/tests/unit/test_settings_resolver.py @@ -0,0 +1,119 @@ +"""Юнит-тесты резолвера настроек и валидации — docs/08 §8.2, UT-16, UT-18.""" +from __future__ import annotations + +import pytest + +from app.cv.exceptions import InvalidSettings, UnknownProfile +from app.cv.params import ( + RequestSettings, + parse_settings, + validate_stored_settings, +) +from app.cv.resolver import ( + effective_comparison, + effective_extraction, + effective_probe_extraction, +) +from tests.conftest import make_config + + +@pytest.fixture(scope="module") +def config(): + return make_config() + + +class TestResolver: + def test_ut16_comparison_priority(self, config): + """UT-16: env → профиль → блоб → запрос (docs/04 §4.5.4).""" + blob = RequestSettings( + profile="monument", extraction={}, comparison={"lowe_ratio": 0.70} + ) + request = RequestSettings(profile=None, extraction={}, comparison={}) + + # env-умолчания + base = effective_comparison(config, None, None) + assert base.lowe_ratio == config.lowe_ratio + assert base.geometry_model == "homography" + + # профиль из блоба подключается, если запрос профиль не задаёт + with_blob_profile = effective_comparison(config, request, blob) + assert with_blob_profile.geometry_model == "fundamental" # из monument + assert with_blob_profile.lowe_ratio == 0.70 # из блоба + assert with_blob_profile.match_inliers_min == 40 # из monument + + # профиль запроса сильнее профиля блоба, переопределения запроса — + # сильнее всего + req = RequestSettings( + profile="facade", + extraction={}, + comparison={"match_inliers_min": 70, "lowe_ratio": 0.68}, + ) + top = effective_comparison(config, req, blob) + assert top.geometry_model == "homography" # facade из запроса победил monument + assert top.match_inliers_min == 70 + assert top.lowe_ratio == 0.68 + + def test_ut16_extraction_priority(self, config): + """UT-16: извлечение — env → профиль → переопределения запроса.""" + req = RequestSettings( + profile="monument", + extraction={"max_image_size": 1000}, + comparison={}, + ) + params = effective_extraction(config, req) + assert params.max_image_size == 1000 # запрос + assert params.clahe_clip_limit == 3.0 # профиль monument + assert params.max_keypoints == config.sift_max_keypoints # env + + # проба в /verify: extraction-override запроса не действует (FR-002) + probe = effective_probe_extraction(config, req) + assert probe.max_image_size == config.sift_max_image_size + assert probe.clahe_clip_limit == 3.0 # профиль действует + + def test_cross_field_validation(self, config): + """uncertain_inliers_min > match_inliers_min в эффективных значениях — 422.""" + req = RequestSettings(profile=None, extraction={}, comparison={"match_inliers_min": 15}) + with pytest.raises(InvalidSettings): + effective_comparison(config, req, None) + + +class TestSettingsValidation: + def test_ut18_unknown_profile(self, config): + with pytest.raises(UnknownProfile): + parse_settings({"profile": "skyscraper"}, config) + + def test_ut18_unknown_key(self, config): + with pytest.raises(InvalidSettings, match="(?i)неизвестн") as exc: + parse_settings({"comparison": {"ratio_lowe": 0.7}}, config) + assert exc.value.details.get("key") == "ratio_lowe" + + def test_ut18_out_of_range(self, config): + with pytest.raises(InvalidSettings) as exc: + parse_settings({"comparison": {"lowe_ratio": 0.05}}, config) + assert exc.value.details["key"] == "lowe_ratio" + + def test_ut18_unknown_top_level_key(self, config): + with pytest.raises(InvalidSettings): + parse_settings({"comparson": {}}, config) + + def test_valid_settings_pass(self, config): + parsed = parse_settings( + { + "profile": "monument", + "extraction": {"clahe_clip_limit": 3.0, "clahe_tile_grid": [8, 8]}, + "comparison": {"geometry_model": "fundamental", "lowe_ratio": 0.72}, + }, + config, + ) + assert parsed.profile == "monument" + assert parsed.comparison["geometry_model"] == "fundamental" + + def test_max_keypoints_capped_by_env(self, config): + with pytest.raises(InvalidSettings, match="потолка|ceil"): + parse_settings({"extraction": {"max_keypoints": 60_000}}, config) + + def test_stored_settings_invalid_becomes_blob_invalid(self, config): + from app.cv.exceptions import BlobInvalid + + with pytest.raises(BlobInvalid): + validate_stored_settings({"profile": "no-such-profile"}, config)