init app
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
"""Параметры распознавания: описатели, строгая валидация, профили.
|
||||
|
||||
Две группы параметров (docs/04 §4.5.1):
|
||||
- извлечение (extraction) — входит в отпечаток algo_id блоба;
|
||||
- сравнение (comparison) — применяется к запросу, в блоб не входит (кроме
|
||||
секции settings как значений по умолчанию для /verify).
|
||||
|
||||
Валидация строгая (FR-008): неизвестные ключи и значения вне диапазонов
|
||||
отвергаются, чтобы ловить опечатки интегратора.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.config import Config, DEFAULT_CLAHE_CLIP_LIMIT, DEFAULT_CLAHE_TILE_GRID
|
||||
from app.cv.exceptions import BlobInvalid, InvalidSettings, UnknownProfile
|
||||
|
||||
GEOMETRY_MODELS = ("homography", "fundamental")
|
||||
|
||||
# Диапазоны допустимых значений settings-запроса. Документация фиксирует
|
||||
# лишь требование «значения в диапазонах» (NFR-011); конкретные границы
|
||||
# определены здесь и применяются и к env, и к запросам.
|
||||
_SETTINGS_LIMITS = {
|
||||
"max_image_size": ("int", 320, 8192),
|
||||
"max_keypoints": ("int", 100, 65536),
|
||||
"clahe_clip_limit": ("float", 0.5, 10.0),
|
||||
"ransac_reproj_threshold": ("float", 1.0, 15.0),
|
||||
"lowe_ratio": ("float", 0.5, 0.95),
|
||||
"match_inliers_min": ("int", 5, 1000),
|
||||
"match_inliers_ratio_min": ("float", 0.05, 0.95),
|
||||
"match_coverage_min": ("float", 0.0, 0.5),
|
||||
"uncertain_inliers_min": ("int", 1, 500),
|
||||
}
|
||||
|
||||
_EXTRACTION_KEYS = {"max_image_size", "max_keypoints", "clahe_clip_limit", "clahe_tile_grid"}
|
||||
_COMPARISON_KEYS = {
|
||||
"geometry_model",
|
||||
"lowe_ratio",
|
||||
"ransac_reproj_threshold",
|
||||
"match_inliers_min",
|
||||
"match_inliers_ratio_min",
|
||||
"match_coverage_min",
|
||||
"uncertain_inliers_min",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractionParams:
|
||||
"""Эффективные параметры извлечения — полностью входят в algo_id."""
|
||||
|
||||
max_image_size: int
|
||||
max_keypoints: int
|
||||
clahe_clip_limit: float
|
||||
clahe_tile_grid: tuple[int, int]
|
||||
|
||||
def fingerprint_payload(self) -> dict:
|
||||
return {
|
||||
"max_image_size": self.max_image_size,
|
||||
"max_keypoints": self.max_keypoints,
|
||||
"clahe_clip_limit": self.clahe_clip_limit,
|
||||
"clahe_tile_grid": list(self.clahe_tile_grid),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ComparisonParams:
|
||||
"""Эффективные параметры сравнения — возвращаются в details.thresholds."""
|
||||
|
||||
geometry_model: str
|
||||
lowe_ratio: float
|
||||
ransac_reproj_threshold: float
|
||||
match_inliers_min: int
|
||||
match_inliers_ratio_min: float
|
||||
match_coverage_min: float
|
||||
uncertain_inliers_min: int
|
||||
|
||||
def thresholds_payload(self) -> dict:
|
||||
return {
|
||||
"inliers_match": self.match_inliers_min,
|
||||
"inlier_ratio_match": self.match_inliers_ratio_min,
|
||||
"coverage_min": self.match_coverage_min,
|
||||
"inliers_uncertain_min": self.uncertain_inliers_min,
|
||||
"geometry_model": self.geometry_model,
|
||||
"lowe_ratio": self.lowe_ratio,
|
||||
"ransac_reproj_threshold": self.ransac_reproj_threshold,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class RequestSettings:
|
||||
"""Разобранные и провалидированные settings запроса (FR-008)."""
|
||||
|
||||
profile: str | None
|
||||
extraction: dict
|
||||
comparison: dict
|
||||
|
||||
|
||||
def base_extraction(config: Config) -> ExtractionParams:
|
||||
"""env-умолчания — низший уровень приоритета (docs/04 §4.5.4)."""
|
||||
return ExtractionParams(
|
||||
max_image_size=config.sift_max_image_size,
|
||||
max_keypoints=config.sift_max_keypoints,
|
||||
clahe_clip_limit=DEFAULT_CLAHE_CLIP_LIMIT,
|
||||
clahe_tile_grid=DEFAULT_CLAHE_TILE_GRID,
|
||||
)
|
||||
|
||||
|
||||
def base_comparison(config: Config) -> ComparisonParams:
|
||||
return ComparisonParams(
|
||||
geometry_model="homography",
|
||||
lowe_ratio=config.lowe_ratio,
|
||||
ransac_reproj_threshold=config.ransac_reproj_threshold,
|
||||
match_inliers_min=config.match_inliers_min,
|
||||
match_inliers_ratio_min=config.match_inliers_ratio_min,
|
||||
match_coverage_min=config.match_coverage_min,
|
||||
uncertain_inliers_min=config.uncertain_inliers_min,
|
||||
)
|
||||
|
||||
|
||||
def _validate_scalar(key: str, value) -> None:
|
||||
kind, lo, hi = _SETTINGS_LIMITS[key]
|
||||
if kind == "int":
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise InvalidSettings(f"Параметр {key}: ожидается целое число", {"key": key})
|
||||
else:
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise InvalidSettings(f"Параметр {key}: ожидается число", {"key": key})
|
||||
if not lo <= value <= hi:
|
||||
raise InvalidSettings(
|
||||
f"Параметр {key}: значение {value} вне допустимого диапазона [{lo}, {hi}]",
|
||||
{"key": key, "value": value, "min": lo, "max": hi},
|
||||
)
|
||||
|
||||
|
||||
def _validate_group(group: str, values: dict, allowed_keys: set[str]) -> dict:
|
||||
if not isinstance(values, dict):
|
||||
raise InvalidSettings(f"Секция {group} должна быть JSON-объектом", {"key": group})
|
||||
checked: dict = {}
|
||||
for key, value in values.items():
|
||||
if key == "clahe_tile_grid":
|
||||
if (
|
||||
not isinstance(value, (list, tuple))
|
||||
or len(value) != 2
|
||||
or any(isinstance(v, bool) or not isinstance(v, int) or not 1 <= v <= 16 for v in value)
|
||||
):
|
||||
raise InvalidSettings(
|
||||
"Параметр clahe_tile_grid: ожидается пара целых [w, h] в диапазоне [1, 16]",
|
||||
{"key": key, "value": value},
|
||||
)
|
||||
checked[key] = [int(value[0]), int(value[1])]
|
||||
continue
|
||||
if key == "geometry_model":
|
||||
if value not in GEOMETRY_MODELS:
|
||||
raise InvalidSettings(
|
||||
f"Параметр geometry_model: ожидается одно из {list(GEOMETRY_MODELS)}",
|
||||
{"key": key, "value": value},
|
||||
)
|
||||
checked[key] = value
|
||||
continue
|
||||
if key not in allowed_keys:
|
||||
raise InvalidSettings(
|
||||
f"Неизвестный параметр {key!r} в секции {group}", {"key": key, "group": group}
|
||||
)
|
||||
_validate_scalar(key, value)
|
||||
checked[key] = value
|
||||
return checked
|
||||
|
||||
|
||||
def parse_settings(raw: object, config: Config) -> RequestSettings:
|
||||
"""Строгая валидация settings запроса (FR-008, docs/05 §5.5-6)."""
|
||||
if not isinstance(raw, dict):
|
||||
raise InvalidSettings("settings должен быть JSON-объектом")
|
||||
|
||||
unknown_top = set(raw) - {"profile", "extraction", "comparison"}
|
||||
if unknown_top:
|
||||
raise InvalidSettings(
|
||||
f"Неизвестные ключи settings: {sorted(unknown_top)}",
|
||||
{"keys": sorted(unknown_top)},
|
||||
)
|
||||
|
||||
profile = raw.get("profile")
|
||||
if profile is not None:
|
||||
if not isinstance(profile, str) or profile not in PROFILES:
|
||||
raise UnknownProfile(profile if isinstance(profile, str) else repr(profile))
|
||||
|
||||
# потолок max_keypoints ограничен сервисным SIFT_MAX_KEYPOINTS: блоб с большим
|
||||
# числом точек не прошёл бы валидацию распаковки в /verify (FR-003)
|
||||
extraction = _validate_group("extraction", raw.get("extraction") or {}, _EXTRACTION_KEYS)
|
||||
if "max_keypoints" in extraction:
|
||||
hi = min(_SETTINGS_LIMITS["max_keypoints"][2], config.sift_max_keypoints)
|
||||
if extraction["max_keypoints"] > hi:
|
||||
raise InvalidSettings(
|
||||
f"Параметр max_keypoints: значение {extraction['max_keypoints']} "
|
||||
f"выше сервисного потолка {hi} (SIFT_MAX_KEYPOINTS)",
|
||||
{"key": "max_keypoints", "max": hi},
|
||||
)
|
||||
|
||||
comparison = _validate_group("comparison", raw.get("comparison") or {}, _COMPARISON_KEYS)
|
||||
return RequestSettings(profile=profile, extraction=extraction, comparison=comparison)
|
||||
|
||||
|
||||
def validate_stored_settings(raw: object, config: Config) -> RequestSettings:
|
||||
"""Повторная валидация settings из meta блоба: блоб мог быть повреждён.
|
||||
|
||||
Ошибка валидности — это некорректный блоб (FEATURE_BLOB_INVALID), а не
|
||||
ошибка запроса: содержимое блоба контролирует open_cv при упаковке.
|
||||
"""
|
||||
try:
|
||||
return parse_settings(raw, config)
|
||||
except InvalidSettings as exc:
|
||||
raise BlobInvalid(f"meta.settings блоба невалидны: {exc}", exc.details) from exc
|
||||
except UnknownProfile as exc:
|
||||
raise BlobInvalid(f"meta.settings блоба содержат неизвестный профиль: {exc}") from exc
|
||||
|
||||
|
||||
# Профили — пресеты в коде open_cv; новый профиль = релиз (FR-009).
|
||||
# Указаны только отличия от базовых значений (docs/05 §5.4.4).
|
||||
PROFILES: dict[str, dict] = {
|
||||
"facade": {
|
||||
"description": "Плоские фасады зданий (умолчание)",
|
||||
"extraction": {},
|
||||
"comparison": {},
|
||||
},
|
||||
"monument": {
|
||||
"description": "Объёмные объекты: памятники, скульптуры (fundamental-модель)",
|
||||
"extraction": {"clahe_clip_limit": 3.0},
|
||||
"comparison": {
|
||||
"geometry_model": "fundamental",
|
||||
"lowe_ratio": 0.72,
|
||||
"match_inliers_min": 40,
|
||||
"match_coverage_min": 0.02,
|
||||
},
|
||||
},
|
||||
"repetitive": {
|
||||
"description": "Повторяющиеся структуры: лестницы, колоннады, ограды",
|
||||
"extraction": {},
|
||||
"comparison": {
|
||||
"lowe_ratio": 0.70,
|
||||
"match_inliers_ratio_min": 0.35,
|
||||
"match_inliers_min": 60,
|
||||
},
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user