init app
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
"""Юнит-тесты блоб-кодека — docs/08 §8.2, UT-10..UT-15."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.cv.blob import UnpackedBlob, build_meta, compute_algo_id, pack, unpack
|
||||
from app.cv.exceptions import BlobInvalid, FormatUnsupported
|
||||
from app.cv.extraction import Features, extract
|
||||
from app.cv.params import base_extraction
|
||||
from tests import synth
|
||||
from tests.conftest import make_config
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def config():
|
||||
return make_config()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def sample(config) -> tuple[Features, dict, bytes]:
|
||||
features = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
||||
params = base_extraction(config)
|
||||
meta = build_meta(
|
||||
params=params,
|
||||
algo_id=compute_algo_id(params),
|
||||
features=features,
|
||||
settings_payload={"profile": "monument", "comparison": {"lowe_ratio": 0.70}},
|
||||
source_sha256="ab12cd34",
|
||||
)
|
||||
return features, meta, pack(features, meta)
|
||||
|
||||
|
||||
def _repack(descriptors, keypoints, meta) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
np.savez_compressed(
|
||||
buffer,
|
||||
descriptors=descriptors,
|
||||
keypoints=keypoints,
|
||||
meta=np.array(json.dumps(meta)),
|
||||
)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class TestBlobCodec:
|
||||
def test_ut10_roundtrip(self, config, sample):
|
||||
"""UT-10: save → load — идентичные массивы, meta сохраняется."""
|
||||
features, meta, blob = sample
|
||||
unpacked = unpack(blob, config)
|
||||
|
||||
assert np.array_equal(unpacked.features.descriptors, features.descriptors)
|
||||
assert np.array_equal(unpacked.features.keypoints, features.keypoints)
|
||||
for key, value in meta.items():
|
||||
if key == "created_at":
|
||||
continue
|
||||
assert unpacked.meta[key] == value, key
|
||||
|
||||
def test_ut10b_descriptor_range(self, config):
|
||||
"""UT-10 (продолжение): uint8-дескрипторы в диапазоне 0–255."""
|
||||
features = extract(synth.encode_jpg(synth.make_facade(seed=5)), base_extraction(config))
|
||||
assert features.descriptors.dtype == np.uint8
|
||||
assert features.descriptors.min() >= 0 and features.descriptors.max() <= 255
|
||||
|
||||
def test_ut11_uint8_float32_lossless(self):
|
||||
"""UT-11: конверсия uint8 ↔ float32 без потерь (значения целые)."""
|
||||
descs = np.array([0, 1, 127, 254, 255] * 25 + [3, 3, 3], dtype=np.uint8).reshape(1, 128)
|
||||
assert descs.dtype == np.uint8
|
||||
restored = descs.astype(np.float32).astype(np.uint8)
|
||||
assert np.array_equal(descs, restored)
|
||||
|
||||
def test_ut12_broken_zip(self, config):
|
||||
"""UT-12: битый zip / не-npz — FEATURE_BLOB_INVALID."""
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(b"not a zip at all", config)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(b"PK\x03\x04truncated", config)
|
||||
|
||||
def test_ut13a_missing_array(self, config, sample):
|
||||
"""UT-13: отсутствует массив — FEATURE_BLOB_INVALID."""
|
||||
_, meta, _ = sample
|
||||
buffer = io.BytesIO()
|
||||
np.savez_compressed(
|
||||
buffer,
|
||||
descriptors=np.zeros((10, 128), np.uint8),
|
||||
meta=np.array(json.dumps({**meta, "keypoints_count": 10})),
|
||||
)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(buffer.getvalue(), config)
|
||||
|
||||
def test_ut13b_shape_mismatch(self, config, sample):
|
||||
"""UT-13: несогласованные формы массивов — FEATURE_BLOB_INVALID."""
|
||||
_, meta, _ = sample
|
||||
descs = np.zeros((10, 128), np.uint8)
|
||||
kps = np.zeros((7, 5), np.float32)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(_repack(descs, kps, {**meta, "keypoints_count": 10}), config)
|
||||
|
||||
def test_ut13c_count_mismatch(self, config, sample):
|
||||
"""UT-13: keypoints_count ≠ N — FEATURE_BLOB_INVALID."""
|
||||
_, meta, _ = sample
|
||||
descs = np.zeros((10, 128), np.uint8)
|
||||
kps = np.zeros((10, 5), np.float32)
|
||||
with pytest.raises(BlobInvalid):
|
||||
unpack(_repack(descs, kps, {**meta, "keypoints_count": 999}), config)
|
||||
|
||||
def test_ut14_format_version(self, config, sample):
|
||||
"""UT-14: meta.format_version не тот — FEATURE_FORMAT_UNSUPPORTED."""
|
||||
_, meta, _ = sample
|
||||
descs = np.zeros((10, 128), np.uint8)
|
||||
kps = np.zeros((10, 5), np.float32)
|
||||
foreign = {**meta, "format_version": 99, "keypoints_count": 10}
|
||||
with pytest.raises(FormatUnsupported) as excinfo:
|
||||
unpack(_repack(descs, kps, foreign), config)
|
||||
assert excinfo.value.details["received"] == 99
|
||||
assert excinfo.value.details["expected_format_version"] == 1
|
||||
|
||||
def test_ut15_zip_bomb(self, config, sample):
|
||||
"""UT-15: корректная структура, но массив сверх лимита — отклонение
|
||||
по SIFT_MAX_KEYPOINTS без распаковки в память."""
|
||||
_, meta, _ = sample
|
||||
small = make_config(sift_max_keypoints=100)
|
||||
descs = np.zeros((20_000, 128), np.uint8) # 2.56 МБ распакованных
|
||||
kps = np.zeros((20_000, 5), np.float32)
|
||||
blob = _repack(descs, kps, {**meta, "keypoints_count": 20_000})
|
||||
with pytest.raises(BlobInvalid, match="лимит"):
|
||||
unpack(blob, small)
|
||||
|
||||
def test_meta_without_settings(self, config):
|
||||
"""meta без необязательного settings — читается, settings = None (06 §6.5)."""
|
||||
features = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
||||
params = base_extraction(config)
|
||||
meta = build_meta(params, compute_algo_id(params), features, None, "ff00")
|
||||
unpacked = unpack(pack(features, meta), config)
|
||||
assert unpacked.settings is None
|
||||
|
||||
def test_unpacked_resized_dims(self, config, sample):
|
||||
"""Размеры приведённого изображения восстанавливаются из meta."""
|
||||
_, meta, blob = sample
|
||||
unpacked: UnpackedBlob = unpack(blob, config)
|
||||
assert unpacked.features.width <= meta["extraction_params"]["max_image_size"]
|
||||
assert unpacked.features.height <= meta["extraction_params"]["max_image_size"]
|
||||
ratio = unpacked.features.width / unpacked.features.source_width
|
||||
assert ratio == pytest.approx(
|
||||
unpacked.features.height / unpacked.features.source_height, rel=0.02
|
||||
)
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Юнит-тесты извлечения и сравнения — docs/08 §8.2, UT-01..UT-09, UT-17."""
|
||||
from __future__ import annotations
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app.cv.comparison import PairResult, compare_features
|
||||
from app.cv.extraction import extract
|
||||
from app.cv.params import ComparisonParams, base_extraction, base_comparison
|
||||
from tests import synth
|
||||
from tests.conftest import make_config
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def config():
|
||||
return make_config()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def features_pair(config):
|
||||
"""Признаки базового «фасада» и его копии — общая база для UT-01..UT-08."""
|
||||
base = synth.encode_jpg(synth.make_facade(seed=7))
|
||||
f1 = extract(base, base_extraction(config))
|
||||
f2 = extract(base, base_extraction(config))
|
||||
return f1, f2
|
||||
|
||||
|
||||
def _compare(config, probe, ref, **overrides) -> PairResult:
|
||||
params = base_comparison(config)
|
||||
if overrides:
|
||||
params = ComparisonParams(**{**vars(params), **overrides})
|
||||
return compare_features(probe, ref, params)
|
||||
|
||||
|
||||
class TestExtractionComparison:
|
||||
def test_ut01_photo_vs_copy(self, config, features_pair):
|
||||
"""UT-01: фото vs копия — match, высокий confidence, inlier_ratio ≥ 0.8."""
|
||||
f1, f2 = features_pair
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict == "match"
|
||||
assert result.confidence >= 0.6
|
||||
assert result.metrics.inlier_ratio >= 0.8
|
||||
|
||||
def test_ut02_photo_vs_warped(self, config):
|
||||
"""UT-02: проективно искажённая копия — match."""
|
||||
base = synth.make_facade(seed=7)
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config))
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict == "match"
|
||||
|
||||
def test_ut03_photo_vs_half(self, config):
|
||||
"""UT-03: уменьшенная копия (0.5×) — match.
|
||||
|
||||
База берётся 1600×1200, чтобы уменьшенная копия (800×600) оставалась
|
||||
выше минимального разрешения 640×480.
|
||||
"""
|
||||
base = synth.make_facade(seed=7, width=1600, height=1200)
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.scale_half(base)), base_extraction(config))
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict == "match"
|
||||
|
||||
def test_ut04_photo_vs_other_building(self, config):
|
||||
"""UT-04: другое здание — no_match или uncertain, но не match."""
|
||||
f1 = extract(synth.encode_jpg(synth.make_facade(seed=7)), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.make_facade(seed=99)), base_extraction(config))
|
||||
result = _compare(config, f1, f2)
|
||||
assert result.verdict in ("no_match", "uncertain")
|
||||
|
||||
def test_ut05_photo_vs_other_angle(self, config):
|
||||
"""UT-05: тот же объект, другой ракурс — match при «широком» ракурсе."""
|
||||
base = synth.make_facade(seed=7)
|
||||
h, w = base.shape[:2]
|
||||
src = np.float32([[0, 0], [w, 0], [w, h], [0, h]])
|
||||
dst = np.float32(
|
||||
[[w * 0.08, h * 0.06], [w * 0.97, h * 0.10], [w * 0.88, h * 0.95], [w * 0.10, h * 0.92]]
|
||||
)
|
||||
m = cv2.getPerspectiveTransform(src, dst)
|
||||
other_angle = cv2.warpPerspective(base, m, (w, h))
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(other_angle), base_extraction(config))
|
||||
assert _compare(config, f1, f2).verdict == "match"
|
||||
|
||||
def test_ut06_cropped_fragment(self, config):
|
||||
"""UT-06: фрагмент как эталон — coverage корректно мал.
|
||||
|
||||
Проба — полный кадр, эталон — кроп 60 %: инлаеры покрывают только
|
||||
область фрагмента (защита от «локального совпадения» — 04 §4.3).
|
||||
Кроп 60 % сохраняет разрешение выше 640×480.
|
||||
"""
|
||||
base = synth.make_facade(seed=7)
|
||||
f_full = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f_crop = extract(synth.encode_jpg(synth.crop_center(base, fraction=0.6)),
|
||||
base_extraction(config))
|
||||
result = _compare(config, f_full, f_crop)
|
||||
assert result.verdict in ("uncertain", "match")
|
||||
assert result.metrics.coverage == pytest.approx(0.6 * 0.6, abs=0.15)
|
||||
|
||||
def test_ut07_poor_texture(self, config):
|
||||
"""UT-07: однотонная заливка — мало keypoints, деградация без исключений."""
|
||||
features = extract(synth.encode_jpg(synth.make_flat()), base_extraction(config))
|
||||
assert features.count < 500
|
||||
other = extract(synth.encode_jpg(synth.make_facade(seed=3)), base_extraction(config))
|
||||
result = _compare(config, features, other) # не должно упасть
|
||||
assert result.verdict in ("no_match", "uncertain")
|
||||
|
||||
def test_ut08_determinism(self, config, features_pair):
|
||||
"""UT-08: повторный compare тех же входов — идентичные метрики (NFR-009)."""
|
||||
f1, f2 = features_pair
|
||||
first = _compare(config, f1, f2)
|
||||
second = _compare(config, f1, f2)
|
||||
assert first.metrics == second.metrics
|
||||
assert first.verdict == second.verdict
|
||||
assert first.confidence == second.confidence
|
||||
|
||||
def test_ut09_preprocessing(self, config):
|
||||
"""UT-09: EXIF-ориентация, ресайз, CLAHE — корректные размеры/типы."""
|
||||
from app.cv.extraction import decode_image, _preprocess
|
||||
from app.cv.params import ExtractionParams
|
||||
|
||||
# EXIF-ориентация 6 (поворот 90°): размеры меняются местами
|
||||
raw = synth.make_facade(seed=11, width=1400, height=900)
|
||||
exif_jpg = synth.encode_exif_oriented(raw, orientation=6)
|
||||
_, width, height = decode_image(exif_jpg)
|
||||
assert (width, height) == (900, 1400)
|
||||
|
||||
# ресайз до max_image_size длинной стороны
|
||||
params = ExtractionParams(max_image_size=800, max_keypoints=4096,
|
||||
clahe_clip_limit=2.0, clahe_tile_grid=(8, 8))
|
||||
gray, w, h = _preprocess(np.asarray(cv2.cvtColor(raw, cv2.COLOR_BGR2RGB)), params)
|
||||
assert max(w, h) <= 800
|
||||
assert gray.dtype == np.uint8 and gray.ndim == 2
|
||||
|
||||
# CLAHE не меняет размеров и тип
|
||||
assert (w, h) == (gray.shape[1], gray.shape[0])
|
||||
|
||||
def test_ut17_fundamental_model(self, config):
|
||||
"""UT-17: fundamental на синтетической паре — метрики считаются и
|
||||
детерминированы; обе модели дают согласованные вердикты.
|
||||
|
||||
Сравнение абсолютных чисел инлаеров H vs F на плоской синтетике
|
||||
нестабильно (порог F — расстояние до эпиполярной линии, не пиксели
|
||||
репроекции), поэтому проверяется вычислимость и детерминизм.
|
||||
"""
|
||||
base = synth.make_facade(seed=7)
|
||||
f1 = extract(synth.encode_jpg(base), base_extraction(config))
|
||||
f2 = extract(synth.encode_jpg(synth.warp_perspective(base)), base_extraction(config))
|
||||
|
||||
fund_a = _compare(config, f1, f2, geometry_model="fundamental")
|
||||
fund_b = _compare(config, f1, f2, geometry_model="fundamental")
|
||||
homo = _compare(config, f1, f2, geometry_model="homography")
|
||||
|
||||
assert fund_a.metrics.inliers > 0 # метрики считаются
|
||||
assert fund_a.metrics == fund_b.metrics # детерминизм
|
||||
assert fund_a.confidence == fund_b.confidence
|
||||
assert homo.metrics.inliers > 0
|
||||
assert homo.verdict == fund_a.verdict # согласованность моделей
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Юнит-тесты резолвера настроек и валидации — docs/08 §8.2, UT-16, UT-18."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.cv.exceptions import InvalidSettings, UnknownProfile
|
||||
from app.cv.params import (
|
||||
RequestSettings,
|
||||
parse_settings,
|
||||
validate_stored_settings,
|
||||
)
|
||||
from app.cv.resolver import (
|
||||
effective_comparison,
|
||||
effective_extraction,
|
||||
effective_probe_extraction,
|
||||
)
|
||||
from tests.conftest import make_config
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def config():
|
||||
return make_config()
|
||||
|
||||
|
||||
class TestResolver:
|
||||
def test_ut16_comparison_priority(self, config):
|
||||
"""UT-16: env → профиль → блоб → запрос (docs/04 §4.5.4)."""
|
||||
blob = RequestSettings(
|
||||
profile="monument", extraction={}, comparison={"lowe_ratio": 0.70}
|
||||
)
|
||||
request = RequestSettings(profile=None, extraction={}, comparison={})
|
||||
|
||||
# env-умолчания
|
||||
base = effective_comparison(config, None, None)
|
||||
assert base.lowe_ratio == config.lowe_ratio
|
||||
assert base.geometry_model == "homography"
|
||||
|
||||
# профиль из блоба подключается, если запрос профиль не задаёт
|
||||
with_blob_profile = effective_comparison(config, request, blob)
|
||||
assert with_blob_profile.geometry_model == "fundamental" # из monument
|
||||
assert with_blob_profile.lowe_ratio == 0.70 # из блоба
|
||||
assert with_blob_profile.match_inliers_min == 40 # из monument
|
||||
|
||||
# профиль запроса сильнее профиля блоба, переопределения запроса —
|
||||
# сильнее всего
|
||||
req = RequestSettings(
|
||||
profile="facade",
|
||||
extraction={},
|
||||
comparison={"match_inliers_min": 70, "lowe_ratio": 0.68},
|
||||
)
|
||||
top = effective_comparison(config, req, blob)
|
||||
assert top.geometry_model == "homography" # facade из запроса победил monument
|
||||
assert top.match_inliers_min == 70
|
||||
assert top.lowe_ratio == 0.68
|
||||
|
||||
def test_ut16_extraction_priority(self, config):
|
||||
"""UT-16: извлечение — env → профиль → переопределения запроса."""
|
||||
req = RequestSettings(
|
||||
profile="monument",
|
||||
extraction={"max_image_size": 1000},
|
||||
comparison={},
|
||||
)
|
||||
params = effective_extraction(config, req)
|
||||
assert params.max_image_size == 1000 # запрос
|
||||
assert params.clahe_clip_limit == 3.0 # профиль monument
|
||||
assert params.max_keypoints == config.sift_max_keypoints # env
|
||||
|
||||
# проба в /verify: extraction-override запроса не действует (FR-002)
|
||||
probe = effective_probe_extraction(config, req)
|
||||
assert probe.max_image_size == config.sift_max_image_size
|
||||
assert probe.clahe_clip_limit == 3.0 # профиль действует
|
||||
|
||||
def test_cross_field_validation(self, config):
|
||||
"""uncertain_inliers_min > match_inliers_min в эффективных значениях — 422."""
|
||||
req = RequestSettings(profile=None, extraction={}, comparison={"match_inliers_min": 15})
|
||||
with pytest.raises(InvalidSettings):
|
||||
effective_comparison(config, req, None)
|
||||
|
||||
|
||||
class TestSettingsValidation:
|
||||
def test_ut18_unknown_profile(self, config):
|
||||
with pytest.raises(UnknownProfile):
|
||||
parse_settings({"profile": "skyscraper"}, config)
|
||||
|
||||
def test_ut18_unknown_key(self, config):
|
||||
with pytest.raises(InvalidSettings, match="(?i)неизвестн") as exc:
|
||||
parse_settings({"comparison": {"ratio_lowe": 0.7}}, config)
|
||||
assert exc.value.details.get("key") == "ratio_lowe"
|
||||
|
||||
def test_ut18_out_of_range(self, config):
|
||||
with pytest.raises(InvalidSettings) as exc:
|
||||
parse_settings({"comparison": {"lowe_ratio": 0.05}}, config)
|
||||
assert exc.value.details["key"] == "lowe_ratio"
|
||||
|
||||
def test_ut18_unknown_top_level_key(self, config):
|
||||
with pytest.raises(InvalidSettings):
|
||||
parse_settings({"comparson": {}}, config)
|
||||
|
||||
def test_valid_settings_pass(self, config):
|
||||
parsed = parse_settings(
|
||||
{
|
||||
"profile": "monument",
|
||||
"extraction": {"clahe_clip_limit": 3.0, "clahe_tile_grid": [8, 8]},
|
||||
"comparison": {"geometry_model": "fundamental", "lowe_ratio": 0.72},
|
||||
},
|
||||
config,
|
||||
)
|
||||
assert parsed.profile == "monument"
|
||||
assert parsed.comparison["geometry_model"] == "fundamental"
|
||||
|
||||
def test_max_keypoints_capped_by_env(self, config):
|
||||
with pytest.raises(InvalidSettings, match="потолка|ceil"):
|
||||
parse_settings({"extraction": {"max_keypoints": 60_000}}, config)
|
||||
|
||||
def test_stored_settings_invalid_becomes_blob_invalid(self, config):
|
||||
from app.cv.exceptions import BlobInvalid
|
||||
|
||||
with pytest.raises(BlobInvalid):
|
||||
validate_stored_settings({"profile": "no-such-profile"}, config)
|
||||
Reference in New Issue
Block a user