calibrate
This commit is contained in:
@@ -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")
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) # нет негативов
|
||||
Reference in New Issue
Block a user