diff --git a/AGENTS.md b/AGENTS.md index 9033a53..9fdd257 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,10 @@ Guidance for ZCode agents working in this repository. - REST-фреймворк: **FastAPI** (uvicorn, Pydantic). - Архитектура: **stateless** — без БД, файлового хранилища, S3-клиента и кэша; это функциональное требование (FR-006), а не оптимизация. -- Контракт: два эндпоинта — `POST /api/v1/features` (фото → блоб `.npz`) и - `POST /api/v1/verify` (фото пробы + блобы эталонов → вердикт). Эталоны передаются +- Контракт: три эндпоинта — `POST /api/v1/features` (фото → блоб `.npz`), + `POST /api/v1/verify` (фото пробы + блобы эталонов → вердикт) и + `POST /api/v1/calibrate` (две пачки фото — позитивы объекта + негативы-похожести → + откалиброванные per-объектные настройки сравнения). Эталоны передаются готовыми признаками; ссылки S3 не принимаются; изображения как эталоны — только встроенный отладочный режим `/verify` (признаки извлекаются на лету). - Потребитель — основной сервис на **Java Spring**: хранит фото и блобы в S3, @@ -66,10 +68,15 @@ Guidance for ZCode agents working in this repository. - 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` + - calibrate per-object comparison settings from two photo packs + (positives of one object + negative look-alikes): + `.venv/bin/python tools/calibrate.py pos_dir neg_dir` — или через + `POST /api/v1/calibrate` (ядро общее: app/cv/calibration.py; docs/08 §8.4) - 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 +- Planned but **not implemented**: full acceptance dataset for threshold + regression (docs/08 §8.4; per-object calibration is covered by + `tools/calibrate.py`), Prometheus metrics (outside MVP), v2 extensions (`/identify`, embeddings). - No linter/type-checker configured yet (`.gitignore` anticipates ruff/mypy). - БД/ORM/S3-клиент отсутствуют по архитектуре — не добавлять. diff --git a/app/api/errors.py b/app/api/errors.py index 6aa231a..11d4e6f 100644 --- a/app/api/errors.py +++ b/app/api/errors.py @@ -11,6 +11,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException from app.cv.exceptions import ( BlobInvalid, + CalibrationDatasetInvalid, CvError, FormatUnsupported, ImageDecodeFailed, @@ -30,6 +31,7 @@ _CV_ERROR_MAP: list[tuple[type[CvError], int, str]] = [ (UnknownProfile, 400, "UNKNOWN_PROFILE"), (ImageFormatUnsupported, 415, "UNSUPPORTED_MEDIA_TYPE"), (InvalidSettings, 422, "INVALID_SETTINGS"), + (CalibrationDatasetInvalid, 422, "CALIBRATION_DATASET_INVALID"), ] diff --git a/app/api/routes.py b/app/api/routes.py index ea99876..2192dfe 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -13,6 +13,7 @@ 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 ( + CalibrateResponse, ProfileModel, ProfilesResponse, StatusResponse, @@ -192,6 +193,78 @@ async def verify(request: Request): ) +# ------------------------------------------------------------- /calibrate + + +async def _read_pack_parts(parts: list, name: str, config) -> list[tuple[str, bytes]]: + """Читает повторяемые файловые части пачки: [(имя файла, байты)].""" + payloads: list[tuple[str, bytes]] = [] + for i, part in enumerate(parts): + if isinstance(part, str): + raise ApiError( + 422, "VALIDATION_ERROR", + f"Часть {name}[{i}] должна быть файлом", + {"part": name, "index": i}, + ) + check_image_content_type(part.content_type, f"{name}[{i}]") + data = await part.read() + _check_image_size(data, f"{name}[{i}]", config.max_image_bytes) + payloads.append((part.filename or f"{name}[{i}]", data)) + return payloads + + +def _check_pack_size(parts: list, name: str, minimum: int, maximum: int) -> None: + if len(parts) < minimum: + raise ApiError( + 422, "VALIDATION_ERROR", + f"Частей {name} меньше минимума ({minimum}): калибровка невозможна", + {"part": name, "count": len(parts), "minimum": minimum}, + ) + if len(parts) > maximum: + raise ApiError( + 400, "TOO_MANY_CALIBRATION_IMAGES", + f"Число фото в пачке {name} ({len(parts)}) превышает лимит {maximum}", + {"part": name, "count": len(parts), "limit": maximum}, + ) + + +@router.post("/api/v1/calibrate", dependencies=[Depends(require_api_key)]) +async def calibrate(request: Request): + """Подбор per-объектных настроек сравнения по двум пачкам фото + (docs/05 §5.4.5): positive — один объект с разных ракурсов, negative — + похожие объекты. Тяжёлый запрос: до ~60 с при максимальных пачках.""" + config = _config(request) + form = await request.form() + + positive_raw = form.getlist("positive") + negative_raw = form.getlist("negative") + limit = config.calibration_max_images_per_pack + _check_pack_size(positive_raw, "positive", minimum=2, maximum=limit) + _check_pack_size(negative_raw, "negative", minimum=1, maximum=limit) + positive_parts = await _read_pack_parts(positive_raw, "positive", config) + negative_parts = await _read_pack_parts(negative_raw, "negative", config) + + started = time.perf_counter() + outcome = await run_in_threadpool( + _service(request).calibrate, positive_parts, negative_parts + ) + processing_ms = int((time.perf_counter() - started) * 1000) + + best = outcome.best + log_event( + logger, logging.INFO, "calibration completed", + trace_id=getattr(request.state, "trace_id", ""), + geometry_model=best.geometry_model, + lowe_ratio=best.lowe_ratio, + f1=round(best.selection.f1, 4), + true_matches=best.selection.tp, + false_matches=best.selection.fp, + pairs=outcome.pairs_total, + processing_ms=processing_ms, + ) + return CalibrateResponse(**outcome.payload(), processing_ms=processing_ms) + + # ---------------------------------------------------------------- /profiles diff --git a/app/api/schemas.py b/app/api/schemas.py index 7b6ee7b..e4c5be8 100644 --- a/app/api/schemas.py +++ b/app/api/schemas.py @@ -53,6 +53,66 @@ class ProfilesResponse(BaseModel): defaults: dict = Field(description="Базовые значения (env-умолчания) для наследования") +class CalibrateComboModel(BaseModel): + """Одна комбинация pipeline-параметров с подобранными порогами (docs/05 §5.4.5).""" + + geometry_model: str + lowe_ratio: float + ransac_reproj_threshold: float + thresholds: dict = Field( + description="Подобранные пороги вердикта: inliers_match, inlier_ratio_match, " + "coverage_min, inliers_uncertain_min" + ) + tp: int = Field(description="Позитивные пары с вердиктом match") + fp: int = Field(description="Ложные match на негативных парах") + fn: int + f1: float + uncertain_rate: float + margin: float = Field(description="Нормированный зазор между классами (устойчивость)") + + +class CalibratePairModel(BaseModel): + probe: str + ref: str + is_positive: bool + good_matches: int + inliers: int + inlier_ratio: float + coverage: float + verdict: Literal["match", "uncertain", "no_match"] + + +class CalibrateImageModel(BaseModel): + name: str + group: Literal["positive", "negative"] + keypoints: int + + +class CalibrateSkippedModel(BaseModel): + name: str + group: str + reason: str + + +class CalibrateResponse(BaseModel): + """Полный отчёт калибровки (docs/05 §5.4.5).""" + + settings: dict = Field( + description="Готовый фрагмент settings: передать в /features при регистрации " + "эталонов и/или в /verify для этого объекта" + ) + metrics: dict + best: CalibrateComboModel + ranking: list[CalibrateComboModel] = Field(description="Все комбинации, от лучшей к худшей") + pairs: list[CalibratePairModel] + presets: dict = Field(description="tp/fp стандартных профилей на тех же данных") + images: list[CalibrateImageModel] + skipped: list[CalibrateSkippedModel] + warnings: list[str] + selfcheck: dict + processing_ms: int + + class StatusResponse(BaseModel): status: str diff --git a/app/config.py b/app/config.py index 0df81c0..2a9238e 100644 --- a/app/config.py +++ b/app/config.py @@ -61,6 +61,8 @@ class Config: max_image_bytes: int # MAX_IMAGE_MB verify_max_body_bytes: int # VERIFY_MAX_BODY_MB max_references: int # MAX_REFERENCES_PER_REQUEST + calibration_max_images_per_pack: int # CALIBRATION_MAX_IMAGES_PER_PACK + calibration_max_body_bytes: int # CALIBRATION_MAX_BODY_MB sift_max_image_size: int sift_max_keypoints: int @@ -91,6 +93,14 @@ class Config: _read("MAX_REFERENCES_PER_REQUEST", "32"), 1, 128, ), + calibration_max_images_per_pack=_to_int( + "CALIBRATION_MAX_IMAGES_PER_PACK", + _read("CALIBRATION_MAX_IMAGES_PER_PACK", "8"), + 2, 32, + ), + calibration_max_body_bytes=_to_int( + "CALIBRATION_MAX_BODY_MB", _read("CALIBRATION_MAX_BODY_MB", "64"), 1, 512 + ) * _MB, sift_max_image_size=_to_int( "SIFT_MAX_IMAGE_SIZE", _read("SIFT_MAX_IMAGE_SIZE", "1600"), 320, 8192 ), @@ -126,5 +136,9 @@ class Config: problems.append( "UNCERTAIN_INLIERS_MIN не может превышать MATCH_INLIERS_MIN" ) + if self.calibration_max_body_bytes < self.max_image_bytes: + problems.append( + "CALIBRATION_MAX_BODY_MB не может быть меньше MAX_IMAGE_MB" + ) if problems: raise ConfigError("; ".join(problems)) diff --git a/app/cv/calibration.py b/app/cv/calibration.py new file mode 100644 index 0000000..5e834b9 --- /dev/null +++ b/app/cv/calibration.py @@ -0,0 +1,643 @@ +"""Калибровка параметров сравнения по двум пачкам фото (docs/08 §8.4, шаг 3). + +Позитивы — фото одного объекта с разных ракурсов (они же кандидаты в эталоны), +негативы — фото других, похожих объектов. Подбираются ТОЛЬКИ параметры +сравнения (geometry_model, lowe_ratio, ransac_reproj_threshold и пороги +вердикта) — пересчёт эталонов не нужен (docs/04 §4.5.1). Потребители: +CvService.calibrate (эндпоинт /api/v1/calibrate) и tools/calibrate.py (CLI). + +Схема: + 1) extract по каждому фото выполняет потребитель (боевой пайплайн); + 2) пары «проба–эталон»: эталоны — только позитивы, пробы — позитивы + и негативы (боевой сценарий /verify); + 3) knn-сопоставление считается один раз на пару, далее комбинации + lowe/geometry/ransac дёшевы (фильтрация + RANSAC по ≤нескольким сотням пар); + 4) пороги вердикта подбираются аналитически по наблюдённым метрикам пар — + перебор порогов бесплатен, пересчитывать пары не нужно; + 5) победитель перепроверяется боевым compare_features (защита от расхождения + быстрого пути с реальным пайплайном). +""" +from __future__ import annotations + +import dataclasses +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass + +import cv2 +import numpy as np + +from app.config import Config +from app.cv.comparison import ( + MIN_GOOD_MATCHES, + VERDICT_MATCH, + VERDICT_NO_MATCH, + VERDICT_UNCERTAIN, + _coverage, + _ransac_inliers, + compare_features, +) +from app.cv.exceptions import CalibrationDatasetInvalid +from app.cv.extraction import Features +from app.cv.params import ( + _SETTINGS_LIMITS, + base_comparison, + base_extraction, + parse_settings, +) + +# Число потоков пула knn-сопоставлений (самая тяжёлая стадия; OpenCV +# освобождает GIL). RANSAC выполняется последовательно в вызывающем потоке: +# cv2.setRNGSeed — глобальное состояние, параллельные вызовы ломали бы +# детерминизм (NFR-009). +KNN_POOL_SIZE = 4 + +# Сетка перебора — константа процедуры калибровки (аналог формульных констант +# comparison.py), а не конфигурируемый параметр: в env-таблице 07.4 её нет. +DEFAULT_GRID_GEOMETRY = ("homography", "fundamental") +DEFAULT_GRID_LOWE = (0.70, 0.75, 0.80) +DEFAULT_GRID_RANSAC = (3.0, 5.0, 8.0) + + +@dataclass +class CalibrationPhoto: + """Загруженное фото пачки; дескрипторы конвертированы в float32 один раз.""" + + name: str # отображаемое имя (уникализируется) + group: str # "positive" | "negative" + index: int # индекс в общем списке фото + features: Features + descriptors32: np.ndarray + + +@dataclass +class PairKnn: + """knn-матчи одной упорядоченной пары «проба–эталон» (row[0]/row[1]).""" + + probe_index: int + ref_index: int + is_positive: bool + qidx: np.ndarray # int32 (K,) — индексы keypoints пробы + tidx: np.ndarray # int32 (K,) — индексы keypoints эталона + d0: np.ndarray # float32 (K,) — расстояние лучшего + d1: np.ndarray # float32 (K,) — расстояние второго + + +@dataclass(frozen=True) +class Grid: + geometry_models: tuple[str, ...] = DEFAULT_GRID_GEOMETRY + lowe_ratios: tuple[float, ...] = DEFAULT_GRID_LOWE + ransac_thresholds: tuple[float, ...] = DEFAULT_GRID_RANSAC + + +@dataclass +class PairRow: + probe: str + ref: str + is_positive: bool + good_matches: int + inliers: int + inlier_ratio: float + coverage: float + + +@dataclass +class Selection: + match_inliers_min: int + match_inliers_ratio_min: float + match_coverage_min: float + uncertain_inliers_min: int + tp: int + fp: int + fn: int + f1: float + uncertain_rate: float + margin: float + + +@dataclass +class ComboResult: + geometry_model: str + lowe_ratio: float + ransac_reproj_threshold: float + selection: Selection + rows: list[PairRow] = dataclasses.field(default_factory=list) + + +@dataclass +class CalibrationOutcome: + grid: Grid + extraction: dict + photos: list[dict] # name/group/keypoints для отчёта + skipped: list[dict] + pairs_total: int + pairs_positive: int + ranking: list[ComboResult] # отсортирован от лучшей к худшей + presets: dict # {profile: {"tp": int, "fp": int}} + settings: dict # {"comparison": {...}} — для /features и /verify + selfcheck: dict + warnings: list[str] + + @property + def best(self) -> ComboResult: + return self.ranking[0] + + def _combo_payload(self, combo: ComboResult) -> dict: + """Пороги — в терминах details.thresholds /verify (ThresholdsModel): + имена отображения, а не имена ключей запроса settings.""" + s = combo.selection + return { + "geometry_model": combo.geometry_model, + "lowe_ratio": combo.lowe_ratio, + "ransac_reproj_threshold": combo.ransac_reproj_threshold, + "thresholds": { + "inliers_match": s.match_inliers_min, + "inlier_ratio_match": s.match_inliers_ratio_min, + "coverage_min": s.match_coverage_min, + "inliers_uncertain_min": s.uncertain_inliers_min, + }, + "tp": s.tp, + "fp": s.fp, + "fn": s.fn, + "f1": round(s.f1, 4), + "uncertain_rate": round(s.uncertain_rate, 4), + "margin": round(s.margin, 4), + } + + def payload(self) -> dict: + """Форма ответа POST /api/v1/calibrate (docs/05 §5.4.5).""" + best = self.best + return { + "settings": self.settings, + "metrics": { + "f1": round(best.selection.f1, 4), + "true_matches": best.selection.tp, + "false_matches": best.selection.fp, + "uncertain_rate": round(best.selection.uncertain_rate, 4), + "margin": round(best.selection.margin, 4), + "positive_pairs": self.pairs_positive, + "negative_pairs": self.pairs_total - self.pairs_positive, + }, + "best": self._combo_payload(best), + "ranking": [self._combo_payload(c) for c in self.ranking], + "pairs": [ + { + "probe": r.probe, + "ref": r.ref, + "is_positive": r.is_positive, + "good_matches": r.good_matches, + "inliers": r.inliers, + "inlier_ratio": round(r.inlier_ratio, 4), + "coverage": round(r.coverage, 4), + "verdict": verdict_of(r, best.selection), + } + for r in best.rows + ], + "presets": self.presets, + "images": self.photos, + "skipped": self.skipped, + "warnings": self.warnings, + "selfcheck": self.selfcheck, + } + + +# ---------------------------------------------------------------- быстрый путь метрик + +def _knn_pair(probe: CalibrationPhoto, ref: CalibrationPhoto) -> PairKnn | None: + """knnMatch(k=2) — как в compare_features; None при <2 дескрипторов.""" + if probe.features.count < 2 or ref.features.count < 2: + return None + matcher = cv2.BFMatcher(normType=cv2.NORM_L2, crossCheck=False) + matches = matcher.knnMatch(probe.descriptors32, ref.descriptors32, k=2) + rows = [row for row in matches if len(row) == 2] + return PairKnn( + probe_index=probe.index, + ref_index=ref.index, + is_positive=probe.group == "positive", + qidx=np.array([row[0].queryIdx for row in rows], dtype=np.int32), + tidx=np.array([row[0].trainIdx for row in rows], dtype=np.int32), + d0=np.array([row[0].distance for row in rows], dtype=np.float32), + d1=np.array([row[1].distance for row in rows], dtype=np.float32), + ) + + +def _pair_row( + knn: PairKnn | None, + probe: CalibrationPhoto, + ref: CalibrationPhoto, + lowe: float, + geometry: str, + ransac_thr: float, + base_params, +) -> PairRow: + """Метрики пары для комбинации pipeline-параметров — зеркало compare_features + (тот же тест Лоу, тот же RANSAC через _ransac_inliers, та же coverage).""" + is_positive = probe.group == "positive" + if knn is None: + return PairRow(probe.name, ref.name, is_positive, 0, 0, 0.0, 0.0) + keep = knn.d0 < lowe * knn.d1 + good = int(keep.sum()) + if good < MIN_GOOD_MATCHES: + return PairRow(probe.name, ref.name, is_positive, good, 0, 0.0, 0.0) + probe_pts = probe.features.keypoints[knn.qidx[keep], :2] + ref_pts = ref.features.keypoints[knn.tidx[keep], :2] + params = dataclasses.replace( + base_params, + geometry_model=geometry, + lowe_ratio=lowe, + ransac_reproj_threshold=ransac_thr, + ) + mask = _ransac_inliers(ref_pts, probe_pts, params) + if mask is None or mask.size == 0: + return PairRow(probe.name, ref.name, is_positive, good, 0, 0.0, 0.0) + inliers = int(np.count_nonzero(mask)) + return PairRow( + probe=probe.name, + ref=ref.name, + is_positive=is_positive, + good_matches=good, + inliers=inliers, + inlier_ratio=inliers / good, + coverage=_coverage(probe_pts, mask, probe.features), + ) + + +# ---------------------------------------------------------------- подбор порогов + +def _threshold_candidates(values: np.ndarray, lo: float, hi: float, is_int: bool, + max_candidates: int = 33) -> np.ndarray: + """Кандидаты порога: середины между соседними наблюдёнными значениями + плюс границы диапазона (чтобы можно было «пропустить всё» / «пропустить + ничего» по измерению). Для целых — округление вверх: условие inliers ≥ t.""" + uniq = np.unique(values) + if uniq.size == 0: + uniq = np.array([lo]) + mids = (uniq[:-1] + uniq[1:]) / 2 if uniq.size > 1 else np.array([]) + cands = np.concatenate(([lo], mids, [hi])) + cands = np.clip(cands, lo, hi) + if is_int: + cands = np.unique(np.ceil(cands).astype(np.int64)) + else: + cands = np.unique(cands) + if cands.size > max_candidates: + idx = np.unique(np.linspace(0, cands.size - 1, max_candidates).astype(int)) + cands = cands[idx] + return cands + + +def _separation_margin( + tp_inl, tp_rat, tp_cov, neg_inl, neg_rat, neg_cov, + all_inl, all_rat, all_cov, +) -> float: + """Нормированный зазор между худшей проходящей позитивной парой и лучшим + негативом по самому узкому измерению (чем больше — тем устойчивее пороги).""" + if len(tp_inl) == 0 or len(neg_inl) == 0: + return 0.0 + + def dim(tp, neg, allv): + spread = float(allv.max() - allv.min()) + if spread <= 0: + return 0.0 + return (float(tp.min()) - float(neg.max())) / spread + + return min( + dim(tp_inl, neg_inl, all_inl), + dim(tp_rat, neg_rat, all_rat), + dim(tp_cov, neg_cov, all_cov), + ) + + +def _dim_centeredness(values: np.ndarray, thr: float, pass_bool: np.ndarray) -> float: + """Устойчивость порога одного измерения: насколько он «в центре» зазора + между проходящими и непроходящими наблюдёнными значениями (0.5 — ровно + посередине; ближе к данным — меньше). Измерение, которое ничего не + отсекает, оценивается отступом порога от ближайшего значения данных; + вырожденное (все значения равны) — 0.5.""" + if not pass_bool.any(): + return 0.0 + a = float(values[pass_bool].min()) + fail = ~pass_bool + if fail.any(): + b = float(values[fail].max()) + if a <= b: + return 0.0 + return min(a - thr, thr - b) / (a - b) + spread = float(values.max() - values.min()) + if spread <= 0: + return 0.5 + return float(min(0.5, (a - thr) / spread)) + + +def derive_uncertain_min(neg_inliers: np.ndarray, match_inliers_min: int) -> int: + """Негативы должны попадать в no_match, а не в uncertain: граница зоны + ручной проверки — сразу над худшим негативом (в рамках допустимого + uncertain ≤ match, иначе конфиг невалиден).""" + max_neg = int(neg_inliers.max()) if neg_inliers.size else 0 + return int(min(max(1, max_neg + 1), match_inliers_min)) + + +def select_thresholds(rows: list[PairRow]) -> Selection: + """Аналитический перебор порогов вердикта по наблюдённым метрикам пар. + + Ранжирование: F1 класса match (docs/08 §8.4), затем минимум ложных match, + затем максимум true positives, затем центрированность порогов в зазорах + между классами (устойчивость к дрейфу данных); при равной центрированности + — более строгие пороги (консервативность). `margin` — итоговый + нормированный зазор между классами, возвращается для отчёта. + """ + inl = np.array([r.inliers for r in rows], dtype=np.float64) + rat = np.array([r.inlier_ratio for r in rows], dtype=np.float64) + cov = np.array([r.coverage for r in rows], dtype=np.float64) + pos = np.array([r.is_positive for r in rows], dtype=bool) + n_pos = int(pos.sum()) + + ci = _threshold_candidates(inl, *_SETTINGS_LIMITS["match_inliers_min"][1:], is_int=True) + cr = _threshold_candidates(rat, *_SETTINGS_LIMITS["match_inliers_ratio_min"][1:], is_int=False) + cc = _threshold_candidates(cov, *_SETTINGS_LIMITS["match_coverage_min"][1:], is_int=False) + + pass_i = inl[:, None] >= ci[None, :] + pass_r = rat[:, None] >= cr[None, :] + pass_c = cov[:, None] >= cc[None, :] + + # match = все три условия; считаем tp/fp по срезам третьего измерения, + # чтобы не материализовать (n, Ci, Cr, Cc) + tp = np.zeros((ci.size, cr.size, cc.size), dtype=np.int64) + fp = np.zeros_like(tp) + for k in range(cc.size): + m = pass_i[:, :, None] & pass_r[:, None, :] & pass_c[:, k][:, None, None] + tp[:, :, k] = np.where(pos[:, None, None], m, False).sum(axis=0) + fp[:, :, k] = np.where(~pos[:, None, None], m, False).sum(axis=0) + fn = n_pos - tp + + denom = 2 * tp + fp + fn + with np.errstate(divide="ignore", invalid="ignore"): + f1 = np.where(denom > 0, 2 * tp / np.maximum(denom, 1), 0.0) + + best_f1 = f1.max() + f1_mask = f1 == best_f1 + fp_at = int(fp[f1_mask].min()) + tp_at = int(tp[f1_mask & (fp == fp_at)].max()) + tied = np.argwhere(f1_mask & (fp == fp_at) & (tp == tp_at)) + + def _norm(t: float, arr: np.ndarray) -> float: + span = float(arr[-1] - arr[0]) + return (float(t) - float(arr[0])) / span if span > 0 else 0.0 + + best_cell, best_key = (int(tied[0][0]), int(tied[0][1]), int(tied[0][2])), (-1.0, -1.0) + for i, j, k in tied: + score = round(min( + _dim_centeredness(inl, ci[i], pass_i[:, i]), + _dim_centeredness(rat, cr[j], pass_r[:, j]), + _dim_centeredness(cov, cc[k], pass_c[:, k]), + ), 9) # округление — не давать шуму float решать исход сравнения + key = (score, _norm(ci[i], ci) + _norm(cr[j], cr) + _norm(cc[k], cc)) + if key > best_key: + best_cell, best_key = (int(i), int(j), int(k)), key + + i, j, k = best_cell + ti, tr, tc = int(ci[i]), round(float(cr[j]), 4), round(float(cc[k]), 4) + # после округления пересчитываем итоги по тем же строкам — в settings + # попадают значения, которыми реально классифицировали + match_mask = (inl >= ti) & (rat >= tr) & (cov >= tc) + neg_mask = ~pos + tp_v, fp_v = int((match_mask & pos).sum()), int((match_mask & neg_mask).sum()) + unc = derive_uncertain_min(inl[neg_mask], ti) + uncertain = int(np.count_nonzero((inl >= unc) & ~match_mask)) + margin = _separation_margin( + inl[match_mask & pos], rat[match_mask & pos], cov[match_mask & pos], + inl[neg_mask], rat[neg_mask], cov[neg_mask], + inl, rat, cov, + ) + return Selection( + match_inliers_min=ti, + match_inliers_ratio_min=tr, + match_coverage_min=tc, + uncertain_inliers_min=unc, + tp=tp_v, + fp=fp_v, + fn=n_pos - tp_v, + f1=float(best_f1), + uncertain_rate=uncertain / len(rows), + margin=float(margin), + ) + + +def verdict_of(row: PairRow, sel: Selection) -> str: + if ( + row.inliers >= sel.match_inliers_min + and row.inlier_ratio >= sel.match_inliers_ratio_min + and row.coverage >= sel.match_coverage_min + ): + return VERDICT_MATCH + if row.inliers >= sel.uncertain_inliers_min: + return VERDICT_UNCERTAIN + return VERDICT_NO_MATCH + + +# ---------------------------------------------------------------- оркестрация + +def _preset_thresholds(config: Config) -> dict[str, tuple[int, float, float]]: + """Пороги стандартных профилей (facade/monument/repetitive) — базовые + значения с наложением пресета; для сравнения с подобранными.""" + from app.cv.params import PROFILES + + base = base_comparison(config) + result = {} + for name, preset in PROFILES.items(): + comp = {**dataclasses.asdict(base), **preset["comparison"]} + result[name] = ( + comp["match_inliers_min"], + comp["match_inliers_ratio_min"], + comp["match_coverage_min"], + ) + return result + + +def _preset_counts(rows: list[PairRow], thresholds: tuple[int, float, float]) -> tuple[int, int]: + ti, tr, tc = thresholds + tp = sum( + 1 for r in rows + if r.is_positive and r.inliers >= ti and r.inlier_ratio >= tr and r.coverage >= tc + ) + fp = sum( + 1 for r in rows + if not r.is_positive and r.inliers >= ti and r.inlier_ratio >= tr and r.coverage >= tc + ) + return tp, fp + + +def _unique_names(photos: list[CalibrationPhoto]) -> None: + """Одинаковые имена файлов в двух пачках не должны склеиваться в отчётах.""" + seen: dict[str, int] = {} + for photo in photos: + base = photo.name + count = seen.get(base, 0) + seen[base] = count + 1 + if count: + photo.name = f"{base} [{count}]" + + +def _warnings(sel: Selection, best_rows: list[PairRow], pairs_total: int) -> list[str]: + warnings: list[str] = [] + fp_rows = [r for r in best_rows if not r.is_positive and verdict_of(r, sel) == VERDICT_MATCH] + if fp_rows: + warnings.append( + "Есть ложные match на негативах (" + + ", ".join(f"{r.probe}→{r.ref}" for r in fp_rows) + + ") — добавьте похожих негативов" + ) + bad_pos = [r for r in best_rows if r.is_positive and verdict_of(r, sel) != VERDICT_MATCH] + if bad_pos: + warnings.append( + "Позитивные пары без match (" + + ", ".join(f"{r.probe}→{r.ref}" for r in bad_pos) + + ") — добавьте ракурсов" + ) + if pairs_total < 20: + warnings.append("Пар мало (<20) — статистика неустойчива, добавьте фото в оба набора") + return warnings + + +def run_calibration( + positives: list[CalibrationPhoto], + negatives: list[CalibrationPhoto], + skipped: list[dict], + config: Config, + grid: Grid | None = None, + jobs: int | None = None, +) -> CalibrationOutcome: + """Полный прогон по уже извлечённым фото. Минимумы проверяет вызывающий + (или получается CalibrationDatasetInvalid отсюда — после отбраковки).""" + if len(positives) < 2: + raise CalibrationDatasetInvalid( + f"Нужно ≥ 2 валидных позитивных фото (загружено {len(positives)}), " + "иначе нет ни одной позитивной пары" + ) + if not negatives: + raise CalibrationDatasetInvalid( + "Нужен ≥ 1 валидный негатив (фото похожего объекта) — иначе " + "калибруется только полнота, а ложные срабатывания не оцениваются" + ) + + grid = grid or Grid() + base_comp = base_comparison(config) + extraction_payload = base_extraction(config).fingerprint_payload() + + photos = positives + negatives + for idx, photo in enumerate(photos): + photo.index = idx + _unique_names(photos) + + # Эталоны — позитивы; пробы — все фото. Упорядоченные пары индексов без самосравнений. + positive_indices = [p.index for p in positives] + pair_defs = [ + (probe_idx, ref_idx) + for probe_idx in range(len(photos)) + for ref_idx in positive_indices + if probe_idx != ref_idx + ] + by_index = {p.index: p for p in photos} + workers = jobs or KNN_POOL_SIZE + if len(pair_defs) == 1: + knns = [_knn_pair(by_index[pair_defs[0][0]], by_index[pair_defs[0][1]])] + else: + with ThreadPoolExecutor(max_workers=min(workers, len(pair_defs))) as pool: + knns = list( + pool.map(lambda pr: _knn_pair(by_index[pr[0]], by_index[pr[1]]), pair_defs) + ) + knn_by_pair = { + knn.probe_index * len(photos) + knn.ref_index: knn for knn in knns if knn is not None + } + + combos: list[ComboResult] = [] + for geometry in grid.geometry_models: + for lowe in grid.lowe_ratios: + for ransac in grid.ransac_thresholds: + rows = [ + _pair_row( + knn_by_pair.get(probe_idx * len(photos) + ref_idx), + by_index[probe_idx], by_index[ref_idx], lowe, geometry, ransac, base_comp, + ) + for probe_idx, ref_idx in pair_defs + ] + combos.append(ComboResult( + geometry_model=geometry, + lowe_ratio=lowe, + ransac_reproj_threshold=ransac, + selection=select_thresholds(rows), + rows=rows, + )) + combos.sort( + key=lambda c: ( + -c.selection.f1, + c.selection.fp, + -c.selection.tp, + c.selection.uncertain_rate, + -c.selection.margin, + ) + ) + best = combos[0] + sel = best.selection + + # Контроль: боевой compare_features должен воспроизвести вердикты быстрого пути. + winner_params = dataclasses.replace( + base_comp, + geometry_model=best.geometry_model, + lowe_ratio=best.lowe_ratio, + ransac_reproj_threshold=best.ransac_reproj_threshold, + match_inliers_min=sel.match_inliers_min, + match_inliers_ratio_min=sel.match_inliers_ratio_min, + match_coverage_min=sel.match_coverage_min, + uncertain_inliers_min=sel.uncertain_inliers_min, + ) + selfcheck_total = selfcheck_ok = 0 + mismatches: list[dict] = [] + by_name = {p.name: p for p in photos} + for row in best.rows: + real = compare_features( + by_name[row.probe].features, by_name[row.ref].features, winner_params + ) + selfcheck_total += 1 + if real.verdict == verdict_of(row, sel): + selfcheck_ok += 1 + else: + mismatches.append({ + "probe": row.probe, "ref": row.ref, + "expected": verdict_of(row, sel), "real": real.verdict, + }) + + settings = { + "comparison": { + "geometry_model": best.geometry_model, + "lowe_ratio": best.lowe_ratio, + "ransac_reproj_threshold": best.ransac_reproj_threshold, + "match_inliers_min": sel.match_inliers_min, + "match_inliers_ratio_min": sel.match_inliers_ratio_min, + "match_coverage_min": sel.match_coverage_min, + "uncertain_inliers_min": sel.uncertain_inliers_min, + } + } + # Гарантия, что сервис примет выданные настройки (FR-008: строгая валидация). + parse_settings(settings, config) + + presets = { + name: dict(zip(("tp", "fp"), _preset_counts(best.rows, thr))) + for name, thr in _preset_thresholds(config).items() + } + pairs_positive = sum(1 for probe, _ in pair_defs if by_index[probe].group == "positive") + + return CalibrationOutcome( + grid=grid, + extraction=extraction_payload, + photos=[ + {"name": p.name, "group": p.group, "keypoints": p.features.count} + for p in photos + ], + skipped=skipped, + pairs_total=len(pair_defs), + pairs_positive=pairs_positive, + ranking=combos, + presets=presets, + settings=settings, + selfcheck={"checked": selfcheck_total, "matched": selfcheck_ok, "mismatches": mismatches}, + warnings=_warnings(sel, best.rows, len(pair_defs)), + ) diff --git a/app/cv/exceptions.py b/app/cv/exceptions.py index 0dc3b80..89f6ca1 100644 --- a/app/cv/exceptions.py +++ b/app/cv/exceptions.py @@ -69,3 +69,8 @@ class UnknownProfile(CvError): class InvalidSettings(CvError): """Неизвестный ключ или значение вне диапазона в settings (422 INVALID_SETTINGS).""" + + +class CalibrationDatasetInvalid(CvError): + """После отбраковки битых файлов осталось <2 позитивов или <1 негатива + (422 CALIBRATION_DATASET_INVALID).""" diff --git a/app/cv/service.py b/app/cv/service.py index a7c12a1..ef62fe2 100644 --- a/app/cv/service.py +++ b/app/cv/service.py @@ -17,8 +17,9 @@ 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.calibration import CalibrationOutcome, CalibrationPhoto, run_calibration from app.cv.comparison import PairMetrics, PairResult, compare_features -from app.cv.exceptions import CvError, ImageDecodeFailed +from app.cv.exceptions import CalibrationDatasetInvalid, CvError, ImageDecodeFailed from app.cv.extraction import Features, extract from app.cv.params import RequestSettings, parse_settings, validate_stored_settings @@ -143,6 +144,44 @@ class CvService: # ------------------------------------------------------------- internals + def calibrate( + self, + positive_parts: list[tuple[str, bytes]], + negative_parts: list[tuple[str, bytes]], + ) -> CalibrationOutcome: + """Калибровка per-объектных настроек сравнения по двум пачкам фото + (docs/08 §8.4; эндпоинт /api/v1/calibrate). + + Битовые файлы пропускаются с записью в skipped; недостаток валидных + фото — CalibrationDatasetInvalid. Извлечение — по env-умолчаниям: + калибруются только параметры сравнения, пересчёт эталонов не нужен. + """ + extraction = resolver.effective_extraction(self.config, None) + positives, skipped = self._load_calibration_pack(positive_parts, "positive", extraction) + negatives, skipped_neg = self._load_calibration_pack(negative_parts, "negative", extraction) + skipped += skipped_neg + return run_calibration(positives, negatives, skipped, self.config) + + @staticmethod + def _load_calibration_pack( + parts: list[tuple[str, bytes]], group: str, params + ) -> tuple[list[CalibrationPhoto], list[dict]]: + loaded: list[CalibrationPhoto] = [] + skipped: list[dict] = [] + for name, data in parts: + try: + features = extract(data, params) + except CvError as exc: + skipped.append({"name": name, "group": group, "reason": str(exc)}) + continue + loaded.append( + CalibrationPhoto( + name=name, group=group, index=-1, features=features, + descriptors32=features.descriptors.astype(np.float32), + ) + ) + return loaded, skipped + def _load_reference( self, part: bytes, index: int, settings_req: RequestSettings | None ) -> tuple[Features, RequestSettings | None]: diff --git a/app/main.py b/app/main.py index 4fbe503..bfb343e 100644 --- a/app/main.py +++ b/app/main.py @@ -137,4 +137,6 @@ def _body_limit(path: str, config: Config) -> int | None: return config.verify_max_body_bytes if path == "/api/v1/features": return config.max_image_bytes + _FEATURES_BODY_SLACK_BYTES + if path == "/api/v1/calibrate": + return config.calibration_max_body_bytes return None diff --git a/docs/04-алгоритм-сравнения.md b/docs/04-алгоритм-сравнения.md index 43a96cf..0d82cea 100644 --- a/docs/04-алгоритм-сравнения.md +++ b/docs/04-алгоритм-сравнения.md @@ -118,7 +118,7 @@ confidence = clamp( (inliers / INLIERS_SATURATION) * 0.6 ``` - **Профиль** — именованный пресет обеих групп, поставляется с open_cv (каталог — `GET /api/v1/profiles`, FR-009). Покрывает **тип объекта**. Новый профиль = релиз open_cv. -- **Переопределения** — точечная правка отдельных полей. Тюнинг **конкретного объекта**; набор хранится в основном сервисе и передаётся с каждым соответствующим вызовом. +- **Переопределения** — точечная правка отдельных полей. Тюнинг **конкретного объекта**; набор хранится в основном сервисе и передаётся с каждым соответствующим вызовом. Подбор переопределений автоматизирован: `POST /api/v1/calibrate` принимает пачки фото объекта и похожих объектов и возвращает готовые параметры сравнения (процедура — [08-план-тестирования.md](08-план-тестирования.md) §8.4). - Значения вне диапазонов и неизвестные ключи/профили отвергаются (`400 UNKNOWN_PROFILE` / `422 INVALID_SETTINGS`). Стартовые профили (значения калибруются по [08-план-тестирования.md](08-план-тестирования.md)): diff --git a/docs/05-rest-api.md b/docs/05-rest-api.md index 0ef0f16..ecf7d64 100644 --- a/docs/05-rest-api.md +++ b/docs/05-rest-api.md @@ -8,14 +8,14 @@ |---|---| | Base URL | `http(s):///api/v1` | | Вход | Всегда `multipart/form-data` (файлы и блобы — бинарные части, не base64-JSON) | -| Выход | `/verify` — JSON (`application/json; charset=utf-8`); `/features` — бинарный `.npz` (`application/octet-stream`) | +| Выход | `/verify`, `/calibrate`, `/profiles` — JSON (`application/json; charset=utf-8`); `/features` — бинарный `.npz` (`application/octet-stream`) | | Формат данных | UTF-8; времена ISO 8601 UTC (`2026-09-28T14:05:00Z`) | | Состояние | Сервис stateless: идентификаторы сущностей (здания, фото) не передаются — ссылки на эталоны выражаются индексами частей запроса | | Версирование | Префикс пути API и `format_version` блоба — независимые версии; несовместимые изменения — `/api/v2` / новая версия формата | ## 5.2. Аутентификация -Оба эндпоинта требуют заголовок: +Все эндпоинты (кроме `/health` и `/ready`) требуют заголовок: ``` X-API-Key: <ключ из APP_API_KEY> @@ -47,13 +47,15 @@ X-API-Key: <ключ из APP_API_KEY> | `400` | `FEATURE_BLOB_INVALID` | Блоб не является корректным `.npz` признаков (структура/массивы/лимиты) | | `400` | `FEATURE_FORMAT_UNSUPPORTED` | `format_version`/`algo_id` блоба не поддерживаются | | `400` | `TOO_MANY_REFERENCES` | Число частей `reference` > `MAX_REFERENCES_PER_REQUEST` | +| `400` | `TOO_MANY_CALIBRATION_IMAGES` | Фото в пачке `positive`/`negative` > `CALIBRATION_MAX_IMAGES_PER_PACK` | | `400` | `UNKNOWN_PROFILE` | В `settings.profile` указан неизвестный профиль | | `400` | `IMAGE_TOO_SMALL` | Разрешение < 640×480 после EXIF-ориентации | | `401` / `403` | `UNAUTHORIZED` / `FORBIDDEN` | Проблема API-ключа | -| `413` | `PAYLOAD_TOO_LARGE` | Тело запроса сверх лимита (`MAX_IMAGE_MB` / `VERIFY_MAX_BODY_MB`) | +| `413` | `PAYLOAD_TOO_LARGE` | Тело запроса сверх лимита (`MAX_IMAGE_MB` / `VERIFY_MAX_BODY_MB` / `CALIBRATION_MAX_BODY_MB`) | | `415` | `UNSUPPORTED_MEDIA_TYPE` | Формат изображения не JPEG/PNG/WebP | -| `422` | `VALIDATION_ERROR` | Отсутствуют обязательные multipart-части (`image` / `probe` / `reference`) | +| `422` | `VALIDATION_ERROR` | Отсутствуют обязательные multipart-части (`image` / `probe` / `reference` / пачки `/calibrate` ниже минимума) | | `422` | `INVALID_SETTINGS` | Неизвестный ключ или значение вне допустимого диапазона в `settings` | +| `422` | `CALIBRATION_DATASET_INVALID` | `/calibrate`: после отбраковки битых файлов осталось < 2 позитивов или < 1 негатива | | `500` | `INTERNAL` | Внутренняя ошибка (детали в логах по `trace_id`) | | `503` | — | `/ready` сообщил о неготовности | @@ -225,6 +227,85 @@ curl -X POST "https://host/api/v1/verify" \ В `extraction`/`comparison` профиля указаны только отличия от базовых значений; незаполненные поля наследуются от env-умолчаний. Состав каталога и значения калибруются (08) и версионируются вместе с релизами open_cv. +--- + +### 5.4.5. POST /api/v1/calibrate — подобрать настройки сравнения под объект + +Вызывается основным сервисом при регистрации объекта (или пере-настройке): принимает две пачки фото и возвращает оптимальные параметры **сравнения** для этого объекта. Процедура — [08-план-тестирования.md](08-план-тестирования.md) §8.4: перебор pipeline-параметров (геометрия × lowe × RANSAC, 18 комбинаций) с аналитическим подбором порогов вердикта, ранжирование по F1 класса `match` при минимуме ложных срабатываний. Калибруются только параметры сравнения — пересчёт эталонов не нужен (04 §4.5.1). + +**Запрос** (`multipart/form-data`; часть `settings` не принимается — базы берутся из env-умолчаний): + +| Часть | Тип | Описание | +|---|---|---| +| `positive` | file (binary), **повторяемая** | фото одного объекта с разных ракурсов: 2–`CALIBRATION_MAX_IMAGES_PER_PACK` (умолч. 8) шт., каждое JPEG/PNG/WebP, ≤ `MAX_IMAGE_MB`, ≥ 640×480 | +| `negative` | file (binary), **повторяемая** | фото других, похожих объектов (дистракторы): 1–8 шт., лимиты части те же; суммарный запрос ≤ `CALIBRATION_MAX_BODY_MB` (64 МБ) | + +Битые/мелкие файлы **не валят запрос**: пропускаются и перечисляются в `skipped` с причиной. Если после отбраковки осталось < 2 позитивов или < 1 негатива — `422 CALIBRATION_DATASET_INVALID`. + +**Ответ `200`** (сокращённо; полный пример — openapi.yaml): + +```json +{ + "settings": { + "comparison": { + "geometry_model": "fundamental", + "lowe_ratio": 0.8, + "ransac_reproj_threshold": 3.0, + "match_inliers_min": 45, + "match_inliers_ratio_min": 0.2633, + "match_coverage_min": 0.3454, + "uncertain_inliers_min": 13 + } + }, + "metrics": { "f1": 1.0, "true_matches": 2, "false_matches": 0, "uncertain_rate": 0.0, + "margin": 0.178, "positive_pairs": 2, "negative_pairs": 4 }, + "best": { "geometry_model": "fundamental", "...": "..." }, + "ranking": [ { "...": "все 18 комбинаций, от лучшей к худшей" } ], + "pairs": [ { "probe": "01-3.jpg", "ref": "01-1.png", "is_positive": true, + "good_matches": 320, "inliers": 92, "inlier_ratio": 0.29, + "coverage": 0.38, "verdict": "match" } ], + "presets": { "facade": { "tp": 1, "fp": 0 }, "monument": { "tp": 1, "fp": 0 }, "repetitive": { "tp": 1, "fp": 0 } }, + "images": [ { "name": "01-1.png", "group": "positive", "keypoints": 15202 } ], + "skipped": [ { "name": "01-2.png", "group": "positive", "reason": "Разрешение изображения 375x500 меньше минимального 640x480" } ], + "warnings": ["Пар мало (<20) — статистика неустойчива, добавьте фото в оба набора"], + "selfcheck": { "checked": 6, "matched": 6, "mismatches": [] }, + "processing_ms": 10438 +} +``` + +Семантика ключевых полей: + +| Поле | Значение | +|---|---| +| `settings` | готовый фрагмент `settings`: передайте его как form-часть `settings` в `/features` при регистрации эталонов этого объекта (запишется в блоб и станет умолчанием для `/verify`) и/или в `/verify` | +| `metrics` | качество лучшей комбинации: `true_matches`/`false_matches` — вердикты `match` на позитивных/негативных парах, `margin` — нормированный зазор между классами (устойчивость порогов) | +| `ranking` | все комбинации с подобранными порогами — для ручного выбора альтернативы | +| `pairs` | метрики всех пар «проба–эталон» при лучшей комбинации (эталоны — позитивы, пробы — все фото) | +| `presets` | как показали бы себя стандартные профили на тех же данных | +| `warnings` | диагностика датасета: ложные match, позитивы без match, мало пар | +| `selfcheck` | контроль: боевой пайплайн `compare_features` воспроизвёл вердикты быстрого пути (число совпадений) | + +**Интеграторам**: запрос синхронный и тяжёлый — до ~60 с при максимальных пачках 8+8 (stateless, фоновых задач нет); настройте таймаут клиента. Результат детерминирован (NFR-009). Откалиброванный `settings` привязан к датасету: при пополнении эталонов существенными ракурсами калибровку стоит повторить. + +**Ошибки**: `400` (`TOO_MANY_CALIBRATION_IMAGES`), `401/403`, `413`, `415`, `422` (`VALIDATION_ERROR` — меньше 2 частей `positive` или 0 частей `negative`; `CALIBRATION_DATASET_INVALID`). + +```bash +curl -X POST "https://host/api/v1/calibrate" \ + -H "X-API-Key: $KEY" \ + -F "positive=@bld-042_north.jpg" \ + -F "positive=@bld-042_south.jpg" \ + -F "positive=@bld-042_entrance.jpg" \ + -F "negative=@bld-051_same_series.jpg" \ + -F "negative=@bld-067_same_series.jpg" + +# затем регистрация эталонов с откалиброванными настройками +curl -X POST "https://host/api/v1/features" \ + -H "X-API-Key: $KEY" \ + -F "image=@bld-042_north.jpg" \ + -F 'settings={"comparison":{"geometry_model":"fundamental","lowe_ratio":0.8,"match_inliers_min":45}}' \ + -o bld-042_north.npz +``` + ## 5.5. Правила входных данных (общие) 1. Изображения (`image`, `probe`): content-type части `image/jpeg`, `image/png` или `image/webp`; фактический формат определяется при декодировании, не по расширению. @@ -233,6 +314,7 @@ curl -X POST "https://host/api/v1/verify" \ 4. EXIF-ориентация применяется сервером; прочие EXIF-данные (включая GPS) игнорируются и не возвращаются. 5. Порядок частей `reference` определяет их индексы в ответе. 6. `settings`: JSON ≤ 4 КБ; профиль обязан существовать (`400 UNKNOWN_PROFILE`), ключи и значения валидируются строго (`422 INVALID_SETTINGS`). Эффективные параметры возвращаются в ответе (заголовок `X-Algo-Id`, поле `details.thresholds`) — вызов с неверными настройками не «молчит». +7. Части `positive`/`negative` в `/calibrate` — только изображения (валидация как у `probe`); часть `settings` эндпоинтом не принимается. Имена файлов используются в отчёте (`pairs`, `skipped`); при совпадении имён добавляется суффикс `[n]`. ## 5.6. Обратная совместимость diff --git a/docs/07-развертывание.md b/docs/07-развертывание.md index 6d7e0b1..4658a00 100644 --- a/docs/07-развертывание.md +++ b/docs/07-развертывание.md @@ -48,9 +48,11 @@ services: | `HOST`, `PORT` | `0.0.0.0`, `8000` | привязка uvicorn | | `WORKERS` | `2` | число процессов uvicorn | | **Лимиты входа**: | | | -| `MAX_IMAGE_MB` | `20` | лимит изображения (`image`, `probe`) → `413` | +| `MAX_IMAGE_MB` | `20` | лимит изображения (`image`, `probe`, части пачек `/calibrate`) → `413` | | `VERIFY_MAX_BODY_MB` | `64` | лимит всего запроса `/verify` | | `MAX_REFERENCES_PER_REQUEST` | `32` | максимальное число блобов эталонов | +| `CALIBRATION_MAX_IMAGES_PER_PACK` | `8` | фото в пачке `positive`/`negative` запроса `/calibrate` (диапазон 2–32) | +| `CALIBRATION_MAX_BODY_MB` | `64` | лимит всего запроса `/calibrate`; ≥ `MAX_IMAGE_MB` | | **Параметры извлечения** (низший приоритет: перекрываются профилем и `settings` запроса; входят в `algo_id`): | | | | `SIFT_MAX_IMAGE_SIZE` | `1600` | длинная сторона после ресайза, px | | `SIFT_MAX_KEYPOINTS` | `16384` | потолок ключевых точек (размер блоба, защита памяти) | diff --git a/docs/08-план-тестирования.md b/docs/08-план-тестирования.md index ef760fc..2b4ae9c 100644 --- a/docs/08-план-тестирования.md +++ b/docs/08-план-тестирования.md @@ -66,6 +66,14 @@ | IT-15 | Неизвестный профиль; неизвестный ключ в `settings`; значение вне диапазона | `400 UNKNOWN_PROFILE`; `422 INVALID_SETTINGS` | | IT-16 | `/verify`: переопределение порога в `settings` побеждает значение из блоба | `details.thresholds` отражает переопределение | | IT-17 | `GET /api/v1/profiles` | `200`; каталог содержит `facade`, `monument`, `repetitive` | +| IT-18 | `/calibrate`: 2 позитивa + 1 негатив (синтетика) | `200`; `settings.comparison` полон; позитивные пары `match`, негативные — нет; `selfcheck` сошёлся; выданный `settings` принимается `/features` | +| IT-19 | `/calibrate`: битый файл (мелкий) среди валидных | `200`; файл в `skipped` с причиной; калибровка по оставшимся | +| IT-20 | `/calibrate`: все позитивы битые | `422 CALIBRATION_DATASET_INVALID` | +| IT-21 | `/calibrate`: 1 часть `positive` | `422 VALIDATION_ERROR` (`details.part = positive`) | +| IT-22 | `/calibrate`: 0 частей `negative` | `422 VALIDATION_ERROR` (`details.part = negative`) | +| IT-23 | `/calibrate`: фото в пачке больше `CALIBRATION_MAX_IMAGES_PER_PACK` | `400 TOO_MANY_CALIBRATION_IMAGES` | +| IT-24 | `/calibrate`: часть больше `MAX_IMAGE_MB` | `413 PAYLOAD_TOO_LARGE` | +| IT-25 | `/calibrate` без ключа / с неверным ключом | `401` / `403` | ## 8.4. Уровень 3 — приёмочные метрики качества @@ -102,6 +110,14 @@ Калибровка меняет только **параметры сравнения** — пересчёт блобов эталонов не требуется (разделение групп параметров — 04 §4.5). +Шаги 2–3 в упрощённом per-объектном виде автоматизированы **эндпоинтом `POST /api/v1/calibrate`** (контракт — [05-rest-api.md](05-rest-api.md) §5.4.5): на вход — две пачки фото (позитивы: один объект с разных ракурсов; негативы: похожие объекты), на выходе — ранжированные комбинации параметров сравнения (`geometry_model`, `lowe_ratio`, `ransac_reproj_threshold`) с подобранными порогами вердикта и готовый фрагмент `settings` для `/features` и `/verify`. Ядро калибровки (`app/cv/calibration.py`) переиспользуется CLI-скриптом: + +``` +.venv/bin/python tools/calibrate.py pos_dir neg_dir --out report.json --csv pairs.csv +``` + +Ранжирование — F1 класса `match`, затем минимум ложных срабатываний; победитель перепроверяется боевым `compare_features`. Это не заменяет приёмочный набор §8.4 (тот покрывает все профили и фиксирует базовые метрики регресса), а подбирает per-объектные переопределения (docs/04 §4.5.2). + ## 8.5. Регресс - Юнит/интеграционные тесты — обязательны в CI на каждый коммит. diff --git a/openapi.yaml b/openapi.yaml index 2816bd3..1a23583 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -32,6 +32,8 @@ tags: description: Извлечение признаков — один раз на эталонное фото - name: verify description: Верификация пробы по блобам/изображениям эталонов + - name: calibrate + description: Подбор per-объектных настроек сравнения по двум пачкам фото - name: profiles description: Каталог профилей настроек распознавания - name: service @@ -191,6 +193,87 @@ paths: schema: {$ref: '#/components/schemas/ErrorResponse'} '500': {$ref: '#/components/responses/Internal'} + /api/v1/calibrate: + post: + tags: [calibrate] + operationId: calibrateSettings + summary: Подобрать настройки сравнения под объект + description: | + Принимает две пачки фото и возвращает оптимальные параметры + **сравнения** для этого объекта: пачка `positive` — фото одного + объекта с разных ракурсов (≥ 2), пачка `negative` — фото других, + похожих объектов (≥ 1). Калибруются только параметры сравнения — + пересчёт эталонов не требуется; передайте выданный `settings` + в `/features` при регистрации эталонов и/или в `/verify`. + + Битые файлы пропускаются и перечисляются в `skipped`; если после + отбраковки осталось < 2 позитивов или < 1 негатива — + 422 CALIBRATION_DATASET_INVALID. + + Тяжёлый синхронный запрос (stateless — фоновых задач нет): + до ~60 с при максимальных пачках 8+8. Настройте таймаут клиента + соответственно. + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [positive, negative] + properties: + positive: + type: array + items: {type: string, format: binary} + minItems: 2 + maxItems: 8 + description: | + Фото одного объекта с разных ракурсов + (2…CALIBRATION_MAX_IMAGES_PER_PACK, по умолчанию 8). + Каждое — JPEG/PNG/WebP, ≤ MAX_IMAGE_MB, ≥ 640×480. + negative: + type: array + items: {type: string, format: binary} + minItems: 1 + maxItems: 8 + description: | + Фото других, похожих объектов (дистракторы) — по ним + калибруется защита от ложных срабатываний. + Лимиты части — как у positive. + Суммарный запрос ≤ CALIBRATION_MAX_BODY_MB (64 МБ). + encoding: + positive: + contentType: application/octet-stream + negative: + contentType: application/octet-stream + responses: + '200': + description: Полный отчёт калибровки; `settings` — готовый фрагмент для /features и /verify + content: + application/json: + schema: {$ref: '#/components/schemas/CalibrateResponse'} + '400': + description: | + TOO_MANY_CALIBRATION_IMAGES — фото в пачке больше + CALIBRATION_MAX_IMAGES_PER_PACK; + IMAGE_DECODE_FAILED/IMAGE_TOO_SMALL — возможны только в `skipped` + (битые файлы не валят запрос), в ответе 200. + content: + application/json: + schema: {$ref: '#/components/schemas/ErrorResponse'} + '401': {$ref: '#/components/responses/Unauthorized'} + '403': {$ref: '#/components/responses/Forbidden'} + '413': {$ref: '#/components/responses/PayloadTooLarge'} + '415': {$ref: '#/components/responses/UnsupportedMediaType'} + '422': + description: | + VALIDATION_ERROR — меньше 2 частей positive или 0 частей negative; + CALIBRATION_DATASET_INVALID — после отбраковки битых файлов + осталось < 2 позитивов или < 1 негатива. + content: + application/json: + schema: {$ref: '#/components/schemas/ErrorResponse'} + '500': {$ref: '#/components/responses/Internal'} + /api/v1/profiles: get: tags: [profiles] @@ -264,7 +347,7 @@ components: application/json: schema: {$ref: '#/components/schemas/ErrorResponse'} PayloadTooLarge: - description: PAYLOAD_TOO_LARGE — тело запроса сверх лимита (MAX_IMAGE_MB / VERIFY_MAX_BODY_MB) + description: PAYLOAD_TOO_LARGE — тело запроса сверх лимита (MAX_IMAGE_MB / VERIFY_MAX_BODY_MB / CALIBRATION_MAX_BODY_MB) content: application/json: schema: {$ref: '#/components/schemas/ErrorResponse'} @@ -437,6 +520,111 @@ components: lowe_ratio: {type: number, example: 0.75} ransac_reproj_threshold: {type: number, example: 5.0} + CalibrateResponse: + type: object + description: Полный отчёт калибровки (docs/05 §5.4.5) + required: [settings, metrics, best, ranking, pairs, presets, images, skipped, warnings, selfcheck, processing_ms] + properties: + settings: + type: object + description: | + Готовый фрагмент settings: `{"comparison": {...}}` в терминах + ComparisonSettings. Передайте его как form-часть settings + в /features (запишется в блоб эталона) и/или в /verify. + properties: + comparison: {$ref: '#/components/schemas/ComparisonSettings'} + metrics: + type: object + description: Метрики лучшей комбинации + properties: + f1: {type: number, description: F1 класса match} + true_matches: {type: integer, description: Позитивные пары с вердиктом match} + false_matches: {type: integer, description: Ложные match на негативных парах} + uncertain_rate: {type: number, description: Доля пар в зоне uncertain} + margin: {type: number, description: Нормированный зазор между классами (устойчивость)} + positive_pairs: {type: integer} + negative_pairs: {type: integer} + best: {$ref: '#/components/schemas/CalibrateCombo'} + ranking: + type: array + description: Все перебранные комбинации, от лучшей к худшей + items: {$ref: '#/components/schemas/CalibrateCombo'} + pairs: + type: array + description: Метрики всех пар при лучшей комбинации + items: {$ref: '#/components/schemas/CalibratePair'} + presets: + type: object + description: tp/fp стандартных профилей на тех же данных (facade/monument/repetitive) + additionalProperties: true + images: + type: array + items: {$ref: '#/components/schemas/CalibrateImage'} + skipped: + type: array + description: Файлы, отбракованные при загрузке (с причиной) + items: {$ref: '#/components/schemas/CalibrateSkipped'} + warnings: + type: array + items: {type: string} + selfcheck: + type: object + description: "Контроль: боевой compare_features воспроизвёл вердикты быстрого пути" + additionalProperties: true + processing_ms: {type: integer} + + CalibrateCombo: + type: object + description: Комбинация pipeline-параметров с подобранными порогами вердикта + required: [geometry_model, lowe_ratio, ransac_reproj_threshold, thresholds, tp, fp, fn, f1, uncertain_rate, margin] + properties: + geometry_model: {type: string, enum: [homography, fundamental]} + lowe_ratio: {type: number} + ransac_reproj_threshold: {type: number} + thresholds: + type: object + description: Подобранные пороги вердикта + properties: + inliers_match: {type: integer} + inlier_ratio_match: {type: number} + coverage_min: {type: number} + inliers_uncertain_min: {type: integer} + tp: {type: integer} + fp: {type: integer} + fn: {type: integer} + f1: {type: number} + uncertain_rate: {type: number} + margin: {type: number} + + CalibratePair: + type: object + required: [probe, ref, is_positive, good_matches, inliers, inlier_ratio, coverage, verdict] + properties: + probe: {type: string, description: Имя файла пробы} + ref: {type: string, description: Имя файла эталона} + is_positive: {type: boolean} + good_matches: {type: integer} + inliers: {type: integer} + inlier_ratio: {type: number} + coverage: {type: number} + verdict: {type: string, enum: [match, uncertain, no_match]} + + CalibrateImage: + type: object + required: [name, group, keypoints] + properties: + name: {type: string} + group: {type: string, enum: [positive, negative]} + keypoints: {type: integer} + + CalibrateSkipped: + type: object + required: [name, group, reason] + properties: + name: {type: string} + group: {type: string} + reason: {type: string} + ProfilesResponse: type: object required: [profiles] @@ -502,6 +690,8 @@ components: - FEATURE_BLOB_INVALID - FEATURE_FORMAT_UNSUPPORTED - TOO_MANY_REFERENCES + - TOO_MANY_CALIBRATION_IMAGES + - CALIBRATION_DATASET_INVALID - UNKNOWN_PROFILE - IMAGE_TOO_SMALL - UNAUTHORIZED diff --git a/tests/api/helpers.py b/tests/api/helpers.py index 0236236..3780331 100644 --- a/tests/api/helpers.py +++ b/tests/api/helpers.py @@ -32,6 +32,14 @@ def post_verify(client, probe: bytes, references: list[tuple[str, bytes, str]], ) +def post_calibrate(client, positives: list[tuple[str, bytes, str]], + negatives: list[tuple[str, bytes, str]]): + """Пачки калибровки — списки (имя, байты, content_type).""" + files = [("positive", p) for p in positives] + files += [("negative", n) for n in negatives] + return client.post("/api/v1/calibrate", headers=API_KEY_HEADERS, files=files) + + def make_blob_ref(blob: bytes) -> tuple[str, bytes, str]: return ("reference.npz", blob, "application/octet-stream") diff --git a/tests/api/test_calibrate.py b/tests/api/test_calibrate.py new file mode 100644 index 0000000..3d62ac6 --- /dev/null +++ b/tests/api/test_calibrate.py @@ -0,0 +1,134 @@ +"""Интеграционные тесты POST /api/v1/calibrate — docs/08 §8.3 (IT-18..IT-25). + +Фикстуры — синтетические изображения (docs/08 §8.6): позитивы — «фасад» и его +проективный поворот, негатив — фасад с другой раскраской. +""" +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from tests import synth +from tests.api.helpers import API_KEY_HEADERS, post_calibrate, post_features + +_ONE_MB = 1024 * 1024 # как в тестовом конфиге conftest.make_config + + +@pytest.fixture(scope="module") +def positive_pack(): + facade = synth.make_facade(seed=7, width=900, height=640) + return [ + ("pos-a.jpg", synth.encode_jpg(facade), "image/jpeg"), + ("pos-b.jpg", synth.encode_jpg(synth.warp_perspective(facade)), "image/jpeg"), + ] + + +@pytest.fixture(scope="module") +def negative_pack(): + other = synth.make_facade(seed=99, width=900, height=640) + return [("neg-c.jpg", synth.encode_jpg(other), "image/jpeg")] + + +@pytest.fixture(scope="module") +def tiny_jpg(): + return ("tiny.jpg", synth.encode_jpg(synth.make_flat(width=300, height=200)), "image/jpeg") + + +class TestCalibrateEndpoint: + def test_it18_returns_settings_and_report(self, client, positive_pack, negative_pack): + """IT-18: две пачки → 200, готовый settings + полный отчёт; + выданные настройки принимаются /features (цикл регистрации эталонов).""" + response = post_calibrate(client, positive_pack, negative_pack) + assert response.status_code == 200 + body = response.json() + + settings = body["settings"]["comparison"] + assert set(settings) == { + "geometry_model", "lowe_ratio", "ransac_reproj_threshold", + "match_inliers_min", "match_inliers_ratio_min", + "match_coverage_min", "uncertain_inliers_min", + } + assert body["metrics"]["false_matches"] == 0 + assert body["metrics"]["positive_pairs"] == 2 + assert body["metrics"]["negative_pairs"] == 2 + assert len(body["ranking"]) == 18 # 2 геометрии × 3 lowe × 3 ransac + verdicts = {(p["probe"], p["ref"]): p["verdict"] for p in body["pairs"]} + assert verdicts[("pos-a.jpg", "pos-b.jpg")] == "match" + assert verdicts[("pos-b.jpg", "pos-a.jpg")] == "match" + assert verdicts[("neg-c.jpg", "pos-a.jpg")] != "match" + assert verdicts[("neg-c.jpg", "pos-b.jpg")] != "match" + assert body["selfcheck"]["matched"] == body["selfcheck"]["checked"] == 4 + assert body["skipped"] == [] + + # финал цикла пользователя: /features с откалиброванными настройками + features = post_features(client, positive_pack[0][1], settings=body["settings"]) + assert features.status_code == 200 + + def test_it19_skips_invalid_files(self, client, positive_pack, negative_pack, tiny_jpg): + """IT-19: битый файл в пачке пропускается и попадает в skipped.""" + response = post_calibrate( + client, positive_pack + [tiny_jpg], negative_pack + ) + assert response.status_code == 200 + body = response.json() + assert len(body["skipped"]) == 1 + assert body["skipped"][0]["name"] == "tiny.jpg" + assert body["skipped"][0]["group"] == "positive" + assert "640x480" in body["skipped"][0]["reason"] + + def test_it20_all_positives_invalid(self, client, tiny_jpg, negative_pack): + """IT-20: после отбраковки <2 позитивов → 422 CALIBRATION_DATASET_INVALID.""" + response = post_calibrate(client, [tiny_jpg, tiny_jpg], negative_pack) + assert response.status_code == 422 + error = response.json()["error"] + assert error["code"] == "CALIBRATION_DATASET_INVALID" + + def test_it21_single_positive_part(self, client, negative_pack): + response = post_calibrate(client, [negative_pack[0]], negative_pack) + assert response.status_code == 422 + error = response.json()["error"] + assert error["code"] == "VALIDATION_ERROR" + assert error["details"]["part"] == "positive" + + def test_it22_no_negative_parts(self, client, positive_pack): + response = post_calibrate(client, positive_pack, []) + assert response.status_code == 422 + error = response.json()["error"] + assert error["code"] == "VALIDATION_ERROR" + assert error["details"]["part"] == "negative" + + def test_it23_too_many_images_in_pack(self, client, negative_pack): + """IT-23: > CALIBRATION_MAX_IMAGES_PER_PACK (8 в тестовом конфиге).""" + flats = [ + (f"flat-{i}.jpg", synth.encode_jpg(synth.make_flat(width=640, height=480)), "image/jpeg") + for i in range(9) + ] + response = post_calibrate(client, flats, negative_pack) + assert response.status_code == 400 + error = response.json()["error"] + assert error["code"] == "TOO_MANY_CALIBRATION_IMAGES" + assert error["details"]["limit"] == 8 + + def test_it24_oversized_part(self, client, positive_pack, negative_pack): + response = post_calibrate( + client, + [("huge.jpg", b"0" * (_ONE_MB + 1), "image/jpeg")] + positive_pack[1:], + negative_pack, + ) + assert response.status_code == 413 + error = response.json()["error"] + assert error["code"] == "PAYLOAD_TOO_LARGE" + assert error["details"]["part"] == "positive[0]" + + def test_it25_auth(self, client, positive_pack, negative_pack): + files = [("positive", p) for p in positive_pack] + files += [("negative", n) for n in negative_pack] + assert client.post("/api/v1/calibrate", files=files).status_code == 401 + assert ( + client.post( + "/api/v1/calibrate", + headers={"X-API-Key": "wrong"}, + files=files, + ).status_code + == 403 + ) diff --git a/tests/api/test_openapi.py b/tests/api/test_openapi.py index da9fca8..f91c442 100644 --- a/tests/api/test_openapi.py +++ b/tests/api/test_openapi.py @@ -23,7 +23,10 @@ class TestSpecFile: def test_version_and_paths(self, spec): assert spec["openapi"].startswith("3.") paths = spec["paths"] - for path in ("/api/v1/features", "/api/v1/verify", "/api/v1/profiles", "/health", "/ready"): + for path in ( + "/api/v1/features", "/api/v1/verify", "/api/v1/calibrate", + "/api/v1/profiles", "/health", "/ready", + ): assert path in paths, path def test_security_scheme(self, spec): @@ -68,11 +71,22 @@ class TestSpecFile: # все коды из таблицы docs/05 §5.3 assert codes == { "IMAGE_DECODE_FAILED", "FEATURE_BLOB_INVALID", "FEATURE_FORMAT_UNSUPPORTED", - "TOO_MANY_REFERENCES", "UNKNOWN_PROFILE", "IMAGE_TOO_SMALL", + "TOO_MANY_REFERENCES", "TOO_MANY_CALIBRATION_IMAGES", "CALIBRATION_DATASET_INVALID", + "UNKNOWN_PROFILE", "IMAGE_TOO_SMALL", "UNAUTHORIZED", "FORBIDDEN", "PAYLOAD_TOO_LARGE", "UNSUPPORTED_MEDIA_TYPE", "VALIDATION_ERROR", "INVALID_SETTINGS", "INTERNAL", } + def test_calibrate_packs_are_repeated_parts(self, spec): + schema = spec["paths"]["/api/v1/calibrate"]["post"]["requestBody"]["content"][ + "multipart/form-data" + ]["schema"] + assert schema["required"] == ["positive", "negative"] + positive = schema["properties"]["positive"] + assert positive["type"] == "array" + assert positive["minItems"] == 2 + assert positive["maxItems"] == 8 # CALIBRATION_MAX_IMAGES_PER_PACK по умолчанию + def test_settings_match_validation_ranges(self, spec): comparison = spec["components"]["schemas"]["ComparisonSettings"]["properties"] assert comparison["lowe_ratio"]["minimum"] == 0.5 diff --git a/tests/conftest.py b/tests/conftest.py index 95a92e2..2adca01 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -25,6 +25,8 @@ def make_config(**overrides) -> Config: max_image_bytes=1 * 1024 * 1024, verify_max_body_bytes=8 * 1024 * 1024, max_references=32, + calibration_max_images_per_pack=8, + calibration_max_body_bytes=8 * 1024 * 1024, sift_max_image_size=1600, sift_max_keypoints=16384, lowe_ratio=0.75, diff --git a/tests/unit/test_calibrate.py b/tests/unit/test_calibrate.py new file mode 100644 index 0000000..d962410 --- /dev/null +++ b/tests/unit/test_calibrate.py @@ -0,0 +1,144 @@ +"""Юнит-тесты калибровщика настроек сравнения (app/cv/calibration.py, docs/08 §8.4). + +Логика подбора порогов проверяется на синтетических метриках пар (без CV); +сквозной смоук — на синтетических изображениях (tests/synth.py, docs/08 §8.6) +через CLI-обёртку tools/calibrate.py (то же ядро, что и в /api/v1/calibrate). +""" +from __future__ import annotations + +import pytest +import numpy as np + +from app.cv.calibration import ( + Grid, + PairRow, + _threshold_candidates, + derive_uncertain_min, + select_thresholds, + verdict_of, +) +from app.cv.exceptions import CalibrationDatasetInvalid +from tests import synth +from tests.conftest import make_config +from tools.calibrate import calibrate + + +def _row(is_positive: bool, inliers: int, ratio: float = 0.6, coverage: float = 0.3) -> PairRow: + return PairRow("probe", "ref", is_positive, good_matches=200, inliers=inliers, + inlier_ratio=ratio, coverage=coverage) + + +# ------------------------------------------------------------- кандидаты порогов + +def test_candidates_clip_to_allowed_range(): + # наблюдённые значения ниже допустимого минимума (5) — порог не может опуститься ниже + assert list(_threshold_candidates(np.array([3, 4]), 5, 1000, is_int=True)) == [5, 1000] + + +def test_candidates_are_midpoints_and_bounds(): + cands = _threshold_candidates(np.array([10, 20, 30]), 5, 1000, is_int=True) + assert list(cands) == [5, 15, 25, 1000] + + +# ------------------------------------------------------------- подбор порогов + +def test_select_perfect_separation(): + rows = [ + _row(True, 80, 0.6, 0.30), + _row(True, 100, 0.7, 0.40), + _row(True, 120, 0.65, 0.35), + _row(False, 5, 0.1, 0.01), + _row(False, 10, 0.2, 0.01), + _row(False, 30, 0.15, 0.02), + ] + sel = select_thresholds(rows) + assert sel.f1 == 1.0 and sel.tp == 3 and sel.fp == 0 and sel.fn == 0 + assert 30 < sel.match_inliers_min <= 80 + assert 0.2 < sel.match_inliers_ratio_min <= 0.6 + assert 0.02 < sel.match_coverage_min <= 0.3 + assert sel.margin > 0 + assert sel.uncertain_inliers_min == 31 # над худшим негативом (30) + for row in rows: + expected = "match" if row.is_positive else "no_match" + assert verdict_of(row, sel) == expected + + +def test_select_prefers_zero_false_matches_on_f1_tie(): + # ti=5: tp=2, fp=2 → F1=0.667; ti=80: tp=1, fp=0 → F1=0.667. + # При равном F1 выбираем вариант без ложных срабатываний. + rows = [_row(True, 50), _row(True, 90), _row(False, 60), _row(False, 70)] + sel = select_thresholds(rows) + assert sel.f1 == pytest.approx(2 / 3) + assert sel.fp == 0 and sel.tp == 1 + assert sel.match_inliers_min == 80 # максимум_TP-позитив (90) выше худшего негатива (70) + assert sel.uncertain_inliers_min == 71 + + +def test_select_degenerate_metrics_do_not_crash(): + rows = [_row(True, 3), _row(False, 0)] + sel = select_thresholds(rows) + assert sel.f1 == 0.0 and sel.tp == 0 + + +def test_derive_uncertain_min_clamped_by_match_threshold(): + assert derive_uncertain_min(np.array([30, 12]), match_inliers_min=60) == 31 + assert derive_uncertain_min(np.array([90, 40]), match_inliers_min=80) == 80 + + +# ------------------------------------------------------------- сквозной смоук + +@pytest.fixture() +def small_facade_dirs(tmp_path): + """Позитивы: синтетический «фасад» + его проективный поворот; + негатив: другой фасад (другая раскраска окон).""" + pos = tmp_path / "pos" + neg = tmp_path / "neg" + pos.mkdir() + neg.mkdir() + facade = synth.make_facade(seed=7, width=900, height=640) + (pos / "a.jpg").write_bytes(synth.encode_jpg(facade)) + (pos / "b.jpg").write_bytes(synth.encode_jpg(synth.warp_perspective(facade))) + (neg / "c.jpg").write_bytes(synth.encode_jpg(synth.make_facade(seed=99, width=900, height=640))) + return pos, neg + + +def test_calibrate_synthetic(small_facade_dirs): + pos, neg = small_facade_dirs + outcome = calibrate( + pos, neg, make_config(), + Grid(geometry_models=("homography",), lowe_ratios=(0.75,), ransac_thresholds=(5.0,)), + jobs=2, + ) + # пробы: a, b, c; эталоны: a, b → 4 упорядоченные пары (2 позитивные, 2 негативные) + assert outcome.pairs_total == 4 + assert outcome.pairs_positive == 2 + assert outcome.skipped == [] + + best = outcome.best + assert best.selection.fp == 0 + assert best.selection.tp == 2 + assert best.selection.f1 == 1.0 + assert outcome.settings["comparison"]["geometry_model"] == "homography" + verdicts = {(r.probe, r.ref): verdict_of(r, best.selection) for r in best.rows} + assert verdicts[("a.jpg", "b.jpg")] == "match" + assert verdicts[("b.jpg", "a.jpg")] == "match" + assert verdicts[("c.jpg", "a.jpg")] != "match" + assert verdicts[("c.jpg", "b.jpg")] != "match" + # выданные настройки валидны для сервиса и самопроверка боевым пайплайном сошлась + assert outcome.selfcheck["matched"] == outcome.selfcheck["checked"] == 4 + assert outcome.settings["comparison"]["lowe_ratio"] == 0.75 + + +def test_calibrate_requires_minimum_inputs(tmp_path): + pos = tmp_path / "pos" + neg = tmp_path / "neg" + pos.mkdir() + neg.mkdir() + (pos / "only.jpg").write_bytes(synth.encode_jpg(synth.make_facade(seed=3, width=640, height=480))) + with pytest.raises(CalibrationDatasetInvalid): + calibrate(pos, neg, make_config(), jobs=1) # один позитив — нет позитивных пар + (pos / "second.jpg").write_bytes( + synth.encode_jpg(synth.make_facade(seed=4, width=640, height=480)) + ) + with pytest.raises(CalibrationDatasetInvalid): + calibrate(pos, neg, make_config(), jobs=1) # нет негативов diff --git a/tools/__init__.py b/tools/__init__.py new file mode 100644 index 0000000..5470df9 --- /dev/null +++ b/tools/__init__.py @@ -0,0 +1 @@ +"""Инструменты разработки поверх CV-ядра (без изменения сервиса).""" diff --git a/tools/calibrate.py b/tools/calibrate.py new file mode 100644 index 0000000..169e925 --- /dev/null +++ b/tools/calibrate.py @@ -0,0 +1,214 @@ +"""CLI-калибровщик настроек сравнения по двум каталогам фото (docs/08 §8.4). + +Позитивы — фото одного объекта с разных ракурсов; негативы — фото других, +похожих объектов. Ядро калибровки — app/cv/calibration.py (тот же код, что и +в эндпоинте POST /api/v1/calibrate); этот скрипт удобен для локального +подбора без HTTP и пишет отчёт в JSON/CSV. + +Использование: + .venv/bin/python tools/calibrate.py pos_dir neg_dir \ + [--out report.json] [--csv pairs.csv] [--jobs N] [--top N] \ + [--geometry homography,fundamental] [--lowe 0.7,0.75] [--ransac 3,5] +""" +from __future__ import annotations + +import argparse +import datetime as _dt +import json +import os +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +from app.config import Config +from app.cv.calibration import ( + CalibrationOutcome, + CalibrationPhoto, + Grid, + run_calibration, + verdict_of, +) +from app.cv.exceptions import CalibrationDatasetInvalid, CvError +from app.cv.extraction import extract +from app.cv.params import GEOMETRY_MODELS, _SETTINGS_LIMITS, base_extraction + +IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} + + +class CalibrationError(RuntimeError): + """Некорректные входы CLI (нет каталога и т.п.).""" + + +def load_photos(directory: Path, group: str, params) -> tuple[list[CalibrationPhoto], list[dict]]: + """Читает фото из каталога; некорректные — в skipped с причиной.""" + if not directory.is_dir(): + raise CalibrationError(f"Каталог не найден: {directory}") + loaded: list[CalibrationPhoto] = [] + skipped: list[dict] = [] + for path in sorted(directory.iterdir()): + if not path.is_file() or path.suffix.lower() not in IMAGE_EXTENSIONS: + continue + try: + features = extract(path.read_bytes(), params) + except CvError as exc: + skipped.append({"name": path.name, "group": group, "reason": str(exc)}) + continue + loaded.append( + CalibrationPhoto( + name=path.name, group=group, index=-1, features=features, + descriptors32=features.descriptors.astype(np.float32), + ) + ) + return loaded, skipped + + +def calibrate( + positive_dir: Path | str, + negative_dir: Path | str, + config: Config, + grid: Grid | None = None, + jobs: int | None = None, +) -> CalibrationOutcome: + """Загрузка каталогов + прогон ядра калибровки (app/cv/calibration.py).""" + extraction = base_extraction(config) + positives, skipped_p = load_photos(Path(positive_dir), "positive", extraction) + negatives, skipped_n = load_photos(Path(negative_dir), "negative", extraction) + return run_calibration(positives, negatives, skipped_p + skipped_n, config, grid, jobs) + + +# ---------------------------------------------------------------- CLI + +def _parse_csv_floats(raw: str) -> tuple[float, ...]: + return tuple(float(x) for x in raw.split(",") if x.strip()) + + +def _print_report(outcome: CalibrationOutcome, top: int) -> None: + best = outcome.best + sel = best.selection + neg_total = outcome.pairs_total - outcome.pairs_positive + print("Калибровка настроек сравнения (docs/08 §8.4)") + print( + f"Фото: позитивов {sum(1 for i in outcome.photos if i['group'] == 'positive')}, " + f"негативов {sum(1 for i in outcome.photos if i['group'] == 'negative')}; " + f"пар: {outcome.pairs_total} ({outcome.pairs_positive} позитивных, {neg_total} негативных)" + ) + if outcome.skipped: + print(f"Пропущено файлов: {len(outcome.skipped)}:") + for s in outcome.skipped: + print(f" {s['name']} [{s['group']}]: {s['reason']}") + print(f"Параметры извлечения (не калибруются): {outcome.extraction}") + print() + + print(f"Топ-{min(top, len(outcome.ranking))} комбинаций (F1 класса match; fp — ложные match):") + print(" # geometry lowe ransac inl_min ratio_min cov_min tp fp unc F1 margin") + for i, combo in enumerate(outcome.ranking[:top], 1): + s = combo.selection + print( + f"{i:3d} {combo.geometry_model:<11} {combo.lowe_ratio:.2f} {combo.ransac_reproj_threshold:4.1f} " + f"{s.match_inliers_min:7d} {s.match_inliers_ratio_min:9.2f} {s.match_coverage_min:7.2f} " + f"{s.tp:4d} {s.fp:3d} {s.uncertain_rate:.0%} {s.f1:.3f} {s.margin:6.3f}" + ) + print() + + print(f"Лучшая комбинация: {best.geometry_model}, lowe={best.lowe_ratio}, ransac={best.ransac_reproj_threshold}") + print(f"recall(match) = {sel.tp}/{outcome.pairs_positive}, ложных match = {sel.fp}/{neg_total}, uncertain = {sel.uncertain_rate:.0%}") + presets = " | ".join(f"{name}: tp={v['tp']} fp={v['fp']}" for name, v in outcome.presets.items()) + print(f"Стандартные профили на тех же данных: {presets}") + print() + + print("Пары (лучшая комбинация):") + print(" probe → ref good inl ratio cov вердикт") + for r in best.rows: + mark = "+" if r.is_positive else "-" + print( + f" {mark} {r.probe[:18]:<18} → {r.ref[:18]:<18} {r.good_matches:5d} {r.inliers:4d} " + f"{r.inlier_ratio:5.2f} {r.coverage:4.2f} {verdict_of(r, sel)}" + ) + print() + + for warning in outcome.warnings: + print(f"⚠ {warning}") + if outcome.warnings: + print() + + print("settings для /verify и /features (per-объектное переопределение; пересчёт эталонов не нужен):") + print(json.dumps({"settings": outcome.settings}, ensure_ascii=False, indent=2)) + sc = outcome.selfcheck + print(f"\nКонтроль боевым compare_features: {sc['matched']}/{sc['checked']} вердиктов совпали") + if sc["mismatches"]: + print(f"⚠ Расхождения: {sc['mismatches']}") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Подбор оптимальных настроек сравнения по двум наборам фото " + "(docs/08 §8.4): позитивы — один объект с разных ракурсов, " + "негативы — похожие объекты." + ) + parser.add_argument("positive_dir", type=Path, help="фото одного объекта (разные ракурсы)") + parser.add_argument("negative_dir", type=Path, help="фото других похожих объектов") + parser.add_argument("--out", type=Path, default=None, help="записать полный отчёт в JSON") + parser.add_argument("--csv", type=Path, default=None, help="записать метрики пар лучшей комбинации в CSV") + parser.add_argument("--jobs", type=int, default=None, help="потоков для knn-сопоставления (умолч. 4)") + parser.add_argument("--top", type=int, default=10, help="показать топ-N комбинаций") + parser.add_argument("--geometry", default=",".join(Grid.geometry_models), + help=f"список через запятую: {GEOMETRY_MODELS}") + parser.add_argument("--lowe", default=",".join(str(x) for x in Grid.lowe_ratios), + help="список через запятую (диапазон 0.5–0.95)") + parser.add_argument("--ransac", default=",".join(str(x) for x in Grid.ransac_thresholds), + help="список через запятую (диапазон 1–15)") + args = parser.parse_args(argv) + + geometry = tuple(g.strip() for g in args.geometry.split(",") if g.strip()) + bad = [g for g in geometry if g not in GEOMETRY_MODELS] + if bad: + parser.error(f"неизвестные модели геометрии {bad}: допустимы {list(GEOMETRY_MODELS)}") + lowe = _parse_csv_floats(args.lowe) + ransac = _parse_csv_floats(args.ransac) + for name, values, (lo, hi) in ( + ("lowe", lowe, _SETTINGS_LIMITS["lowe_ratio"][1:]), + ("ransac", ransac, _SETTINGS_LIMITS["ransac_reproj_threshold"][1:]), + ): + out_of_range = [v for v in values if not lo <= v <= hi] + if out_of_range: + parser.error(f"--{name}: значения {out_of_range} вне диапазона [{lo}, {hi}]") + + # Локальный инструмент: ключ не используется, но Config требует его наличия. + os.environ.setdefault("APP_API_KEY", "calibrate-local") + outcome = calibrate( + args.positive_dir, args.negative_dir, + Config.from_env(), + Grid(geometry_models=geometry, lowe_ratios=lowe, ransac_thresholds=ransac), + jobs=args.jobs, + ) + _print_report(outcome, args.top) + + if args.out: + report = {"generated": _dt.datetime.now().isoformat(timespec="seconds"), **outcome.payload()} + args.out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"\nОтчёт: {args.out}") + if args.csv: + rows = outcome.payload()["pairs"] + lines = ["probe,ref,is_positive,good_matches,inliers,inlier_ratio,coverage,verdict"] + lines += [ + f"{r['probe']},{r['ref']},{r['is_positive']},{r['good_matches']},{r['inliers']}," + f"{r['inlier_ratio']},{r['coverage']},{r['verdict']}" + for r in rows + ] + args.csv.write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"CSV пар: {args.csv}") + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except CalibrationError as exc: + print(f"ОШИБКА: {exc}", file=sys.stderr) + sys.exit(2) + except CalibrationDatasetInvalid as exc: + print(f"ОШИБКА: {exc}", file=sys.stderr) + sys.exit(2)