This commit is contained in:
2026-09-29 00:17:58 +03:00
parent 2f8d4098c5
commit da32158789
38 changed files with 3106 additions and 10 deletions
+6
View File
@@ -0,0 +1,6 @@
"""CV-ядро: extract / compare / резолвер настроек / блоб-кодек.
Чистый Python-модуль без зависимостей от FastAPI: не импортирует веб-слой,
не знает HTTP-кодов, ошибки выражает типизированными исключениями
(правило слоёв — docs/03-архитектура.md §3.5).
"""
+217
View File
@@ -0,0 +1,217 @@
"""Блоб-кодек — единственное место, знающее формат .npz (docs/03 §3.5-3).
Формат блоба — docs/06-формат-признаков.md:
descriptors uint8 (N, 128); keypoints float32 (N, 5); meta — JSON-строка.
Защита от zip-бомбы: суммарный размер распакованных массивов ограничен
SIFT_MAX_KEYPOINTS, формы проверяются до копирования (FR-003 п.3, §6.6-2).
"""
from __future__ import annotations
import hashlib
import io
import json
import zipfile
from datetime import datetime, timezone
import cv2
import numpy as np
from app.config import Config
from app.cv.exceptions import BlobInvalid, FormatUnsupported
from app.cv.extraction import Features
from app.cv.params import ExtractionParams
FORMAT_VERSION = 1
ALGO_PREFIX = "sift-v1"
DESCRIPTOR_COLS = 128
KEYPOINT_COLS = 5
_META_REQUIRED_FIELDS = (
"format_version",
"algo_id",
"extraction_params",
"source_image",
"keypoints_count",
"created_at",
)
def compute_algo_id(params: ExtractionParams) -> str:
"""Отпечаток эффективных параметров извлечения + версия OpenCV.
Информативен (docs/04 §4.5.5): смена настроек меняет отпечаток, но не
format_version — блобы с разными algo_id совместимы.
"""
payload = {"opencv_version": cv2.__version__, **params.fingerprint_payload()}
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:8]
return f"{ALGO_PREFIX}:{digest}"
def build_meta(
params: ExtractionParams,
algo_id: str,
features: Features,
settings_payload: dict | None,
source_sha256: str,
) -> dict:
return {
"format_version": FORMAT_VERSION,
"algo_id": algo_id,
"extraction_params": {
"opencv_version": cv2.__version__,
"max_image_size": params.max_image_size,
"clahe": {
"clip_limit": params.clahe_clip_limit,
"tile_grid_size": list(params.clahe_tile_grid),
},
"sift_nfeatures": params.max_keypoints,
},
"settings": settings_payload,
"source_image": {"width": features.source_width, "height": features.source_height},
"keypoints_count": features.count,
"source_sha256": source_sha256,
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
def pack(features: Features, meta: dict) -> bytes:
"""Упаковка признаков и метаданных в бинарный .npz."""
if features.descriptors.dtype != np.uint8 or features.keypoints.dtype != np.float32:
raise BlobInvalid("Неверные типы массивов при упаковке блоба")
buffer = io.BytesIO()
np.savez_compressed(
buffer,
descriptors=features.descriptors,
keypoints=features.keypoints,
meta=np.array(json.dumps(meta, ensure_ascii=False)),
)
return buffer.getvalue()
class UnpackedBlob:
"""Распакованный блоб: признаки + meta + провалидированные settings."""
__slots__ = ("features", "meta", "settings")
def __init__(self, features: Features, meta: dict, settings: object | None):
self.features = features
self.meta = meta
self.settings = settings
def unpack(data: bytes, config: Config) -> UnpackedBlob:
"""Распаковка с полной валидацией (FR-003): структура → версия → лимиты."""
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
# np.savez хранит массивы как <name>.npy — сравниваем без суффикса
stored = {name.removesuffix(".npy") for name in zf.namelist()}
required = {"descriptors", "keypoints", "meta"}
if not required <= stored:
raise BlobInvalid(
"Блоб не содержит обязательные массивы", {"missing": sorted(required - stored)}
)
# Проверка размеров до распаковки: zip-контейнер не должен
# разворачиваться в гигабайты памяти (FR-003 п.3)
max_kp = config.sift_max_keypoints
limits = {
"descriptors.npy": max_kp * DESCRIPTOR_COLS, # uint8, 1 байт
"keypoints.npy": max_kp * KEYPOINT_COLS * 4, # float32
}
for name, limit in limits.items():
declared = zf.getinfo(name).file_size
if declared > limit:
raise BlobInvalid(
f"Массив {name.removesuffix('.npy')} превышает лимит распаковки: "
f"{declared} байт > {limit} (SIFT_MAX_KEYPOINTS={max_kp})",
{"array": name.removesuffix(".npy"), "declared_size": declared},
)
npz = np.load(io.BytesIO(data), allow_pickle=False)
descriptors = np.asarray(npz["descriptors"])
keypoints = np.asarray(npz["keypoints"])
meta_raw = npz["meta"]
except BlobInvalid:
raise
except (zipfile.BadZipFile, OSError, ValueError, KeyError) as exc:
raise BlobInvalid(f"Блоб не является корректным .npz: {exc.__class__.__name__}") from exc
_validate_arrays(descriptors, keypoints, config)
try:
meta = json.loads(str(meta_raw.item()))
except (ValueError, AttributeError, TypeError) as exc:
raise BlobInvalid("meta блоба не является корректным JSON") from exc
if not isinstance(meta, dict):
raise BlobInvalid("meta блоба должен быть JSON-объектом")
missing = [f for f in _META_REQUIRED_FIELDS if f not in meta]
if missing:
raise BlobInvalid(f"meta блоба не содержит обязательные поля: {missing}",
{"missing": missing})
if meta["format_version"] != FORMAT_VERSION:
raise FormatUnsupported(FORMAT_VERSION, meta["format_version"])
n = int(keypoints.shape[0])
if meta["keypoints_count"] != n:
raise BlobInvalid(
f"keypoints_count ({meta['keypoints_count']}) не совпадает с числом точек ({n})"
)
src_w, src_h = _source_dims(meta)
resized_w, resized_h = _resized_dims(src_w, src_h, meta)
features = Features(
keypoints=keypoints,
descriptors=descriptors,
width=resized_w,
height=resized_h,
source_width=src_w,
source_height=src_h,
)
return UnpackedBlob(features, meta, settings=meta.get("settings"))
def _source_dims(meta: dict) -> tuple[int, int]:
source = meta.get("source_image")
if not isinstance(source, dict):
raise BlobInvalid("meta.source_image должен быть JSON-объектом")
w, h = source.get("width"), source.get("height")
if not isinstance(w, int) or not isinstance(h, int) or w <= 0 or h <= 0:
raise BlobInvalid("meta.source_image.width/height отсутствуют или невалидны")
return w, h
def _validate_arrays(descriptors: np.ndarray, keypoints: np.ndarray, config: Config) -> None:
if descriptors.dtype != np.uint8 or descriptors.ndim != 2 or descriptors.shape[1] != DESCRIPTOR_COLS:
raise BlobInvalid(
f"Массив descriptors должен быть uint8 (N, {DESCRIPTOR_COLS}), "
f"получен {descriptors.dtype} {descriptors.shape}"
)
if keypoints.dtype != np.float32 or keypoints.ndim != 2 or keypoints.shape[1] != KEYPOINT_COLS:
raise BlobInvalid(
f"Массив keypoints должен быть float32 (N, {KEYPOINT_COLS}), "
f"получен {keypoints.dtype} {keypoints.shape}"
)
if descriptors.shape[0] != keypoints.shape[0]:
raise BlobInvalid(
f"Число дескрипторов ({descriptors.shape[0]}) не равно числу keypoints "
f"({keypoints.shape[0]})"
)
if keypoints.shape[0] > config.sift_max_keypoints:
raise BlobInvalid(
f"Число keypoints ({keypoints.shape[0]}) превышает SIFT_MAX_KEYPOINTS "
f"({config.sift_max_keypoints})"
)
def _resized_dims(src_w: int, src_h: int, meta: dict) -> tuple[int, int]:
"""Восстанавливает размеры приведённого изображения из meta.
Координаты keypoints живут в системе приведённого изображения
(docs/06 §6.2); для эталона она не хранится явно и пересчитывается из
source_image и max_image_size по правилу ресайза (docs/04 §4.2).
"""
max_size = meta.get("extraction_params", {}).get("max_image_size")
if not isinstance(max_size, (int, float)) or isinstance(max_size, bool) or max_size <= 0:
raise BlobInvalid("meta.extraction_params.max_image_size отсутствует или невалиден")
scale = min(1.0, float(max_size) / max(src_w, src_h))
return max(1, round(src_w * scale)), max(1, round(src_h * scale))
+148
View File
@@ -0,0 +1,148 @@
"""Операция compare: пара «проба–эталон» → метрики, вердикт, confidence.
Схема — docs/04 §4.3–4.4: BFMatcher(kNN=2) → тест Лоу → RANSAC-геометрия
(homography | fundamental) → метрики пары → трёхзонный вердикт.
"""
from __future__ import annotations
import dataclasses
import cv2
import numpy as np
from app.cv.extraction import Features
from app.cv.params import ComparisonParams
# Ниже — константы формулы confidence и RANSAC из docs/04 §4.4 и §4.3:
# это часть спецификации алгоритма, а не конфигурируемые параметры
# (в env-таблице docs/07 §7.4 их нет).
MIN_GOOD_MATCHES = 10
INLIERS_SATURATION = 150.0
COVERAGE_NORM_SATURATION = 0.25
CONFIDENCE_WEIGHTS = (0.6, 0.25, 0.15) # inliers, inlier_ratio, coverage_norm
RANSAC_CONFIDENCE = 0.995
RANSAC_MAX_ITERS = 5000
# ГПСЧ OpenCV фиксируется перед каждым RANSAC-вызовом для детерминизма
# (NFR-009, docs/04 §4.6); seed-политика не входит в algo_id.
RANSAC_SEED = 42
VERDICT_MATCH = "match"
VERDICT_UNCERTAIN = "uncertain"
VERDICT_NO_MATCH = "no_match"
@dataclasses.dataclass(frozen=True)
class PairMetrics:
good_matches: int
inliers: int
inlier_ratio: float
coverage: float
@dataclasses.dataclass(frozen=True)
class PairResult:
metrics: PairMetrics
verdict: str
confidence: float
thresholds: ComparisonParams
def _zero_metrics(good_matches: int = 0) -> PairMetrics:
return PairMetrics(good_matches=good_matches, inliers=0, inlier_ratio=0.0, coverage=0.0)
def _confidence(metrics: PairMetrics) -> float:
inliers_part = (metrics.inliers / INLIERS_SATURATION) * CONFIDENCE_WEIGHTS[0]
ratio_part = metrics.inlier_ratio * CONFIDENCE_WEIGHTS[1]
coverage_norm = min(metrics.coverage / COVERAGE_NORM_SATURATION, 1.0)
coverage_part = coverage_norm * CONFIDENCE_WEIGHTS[2]
return float(min(1.0, max(0.0, inliers_part + ratio_part + coverage_part)))
def _verdict(metrics: PairMetrics, params: ComparisonParams) -> str:
if (
metrics.inliers >= params.match_inliers_min
and metrics.inlier_ratio >= params.match_inliers_ratio_min
and metrics.coverage >= params.match_coverage_min
):
return VERDICT_MATCH
if metrics.inliers >= params.uncertain_inliers_min:
return VERDICT_UNCERTAIN
return VERDICT_NO_MATCH
def _coverage(probe_pts: np.ndarray, mask: np.ndarray, probe: Features) -> float:
"""Доля площади изображения пробы под выпуклой оболочкой инлаеров."""
inliers = probe_pts[mask.reshape(-1) == 1]
if inliers.shape[0] < 3:
return 0.0
hull = cv2.convexHull(inliers.astype(np.float32))
area = cv2.contourArea(hull)
total = float(probe.width) * float(probe.height)
if total <= 0:
return 0.0
return float(min(area / total, 1.0))
def _ransac_inliers(
ref_pts: np.ndarray, probe_pts: np.ndarray, params: ComparisonParams
) -> np.ndarray | None:
"""Геометрическая проверка RANSAC; возвращает маску инлаеров или None."""
cv2.setRNGSeed(RANSAC_SEED)
if params.geometry_model == "fundamental":
_, mask = cv2.findFundamentalMat(
ref_pts, probe_pts,
cv2.RANSAC,
params.ransac_reproj_threshold,
RANSAC_CONFIDENCE,
RANSAC_MAX_ITERS,
)
else:
_, mask = cv2.findHomography(
ref_pts, probe_pts,
cv2.RANSAC,
params.ransac_reproj_threshold,
maxIters=RANSAC_MAX_ITERS,
confidence=RANSAC_CONFIDENCE,
)
return mask
def compare_features(probe: Features, ref: Features, params: ComparisonParams) -> PairResult:
"""Сравнение пары «проба–эталон» эффективными параметрами сравнения."""
if probe.count < 2 or ref.count < 2:
return PairResult(_zero_metrics(), VERDICT_NO_MATCH, 0.0, params)
matcher = cv2.BFMatcher(normType=cv2.NORM_L2, crossCheck=False)
matches = matcher.knnMatch(probe.descriptors.astype(np.float32),
ref.descriptors.astype(np.float32), k=2)
# Тест Лоу: лучший матч должен быть существенно лучше второго (docs/04 §4.3)
pairs = [
(row[0].queryIdx, row[0].trainIdx)
for row in matches
if len(row) == 2 and row[0].distance < params.lowe_ratio * row[1].distance
]
good_matches = len(pairs)
if good_matches < MIN_GOOD_MATCHES:
metrics = _zero_metrics(good_matches)
return PairResult(metrics, VERDICT_NO_MATCH, _confidence(metrics), params)
probe_kp = probe.keypoints[:, :2]
ref_kp = ref.keypoints[:, :2]
probe_pts = np.array([probe_kp[q] for q, _ in pairs], dtype=np.float32)
ref_pts = np.array([ref_kp[t] for _, t in pairs], dtype=np.float32)
mask = _ransac_inliers(ref_pts, probe_pts, params)
if mask is None or mask.size == 0:
metrics = _zero_metrics(good_matches) # модель не найдена → no_match (docs/04 §4.4)
return PairResult(metrics, VERDICT_NO_MATCH, _confidence(metrics), params)
inliers = int(np.count_nonzero(mask))
metrics = PairMetrics(
good_matches=good_matches,
inliers=inliers,
inlier_ratio=inliers / good_matches,
coverage=_coverage(probe_pts, mask, probe),
)
return PairResult(metrics, _verdict(metrics, params), _confidence(metrics), params)
+71
View File
@@ -0,0 +1,71 @@
"""Типизированные исключения CV-ядра.
Ни один класс не знает HTTP-кодов: маппинг на коды ответов —
исключительная зона API-слоя (docs/03 §3.5, §3.6).
"""
from __future__ import annotations
class CvError(Exception):
"""Базовый класс ошибок CV-ядра."""
def __init__(self, message: str, details: dict | None = None):
super().__init__(message)
self.details = details or {}
class ImageDecodeFailed(CvError):
"""Файл не декодируется как изображение (400 IMAGE_DECODE_FAILED)."""
class ImageFormatUnsupported(CvError):
"""Фактический формат изображения не JPEG/PNG/WebP (415 UNSUPPORTED_MEDIA_TYPE)."""
def __init__(self, fmt: str | None, details: dict | None = None):
super().__init__(
f"Формат изображения {fmt or 'неизвестен'} не поддерживается; "
"разрешены JPEG, PNG, WebP",
details,
)
self.format = fmt
class ImageTooSmall(CvError):
"""Разрешение меньше 640×480 после EXIF-ориентации (400 IMAGE_TOO_SMALL)."""
def __init__(self, width: int, height: int, details: dict | None = None):
super().__init__(
f"Разрешение изображения {width}x{height} меньше минимального 640x480",
details,
)
self.width = width
self.height = height
class BlobInvalid(CvError):
"""Блоб не является корректным .npz признаков (400 FEATURE_BLOB_INVALID)."""
class FormatUnsupported(CvError):
"""format_version блоба не поддерживается (400 FEATURE_FORMAT_UNSUPPORTED)."""
def __init__(self, expected: int, received: int, details: dict | None = None):
super().__init__(
"Блоб признаков имеет несовместимую версию формата; "
"пересчитайте эталоны через POST /api/v1/features",
{"expected_format_version": expected, "received": received, **(details or {})},
)
self.expected = expected
self.received = received
class UnknownProfile(CvError):
"""В settings.profile указан неизвестный профиль (400 UNKNOWN_PROFILE)."""
def __init__(self, name: str):
super().__init__(f"Неизвестный профиль настроек: {name!r}")
self.name = name
class InvalidSettings(CvError):
"""Неизвестный ключ или значение вне диапазона в settings (422 INVALID_SETTINGS)."""
+116
View File
@@ -0,0 +1,116 @@
"""Операция extract: изображение → keypoints + дескрипторы SIFT.
Пайплайн (docs/04 §4.2): EXIF-ориентация → ресайз ≤ max_image_size →
grayscale + CLAHE → SIFT(nfeatures).
"""
from __future__ import annotations
import io
import cv2
import numpy as np
from PIL import Image, ImageOps
from app.cv.exceptions import ImageDecodeFailed, ImageFormatUnsupported, ImageTooSmall
from app.cv.params import ExtractionParams
MIN_WIDTH = 640
MIN_HEIGHT = 480
ALLOWED_IMAGE_FORMATS = {"JPEG", "PNG", "WEBP"}
class Features:
"""Результат извлечения; координаты — в системе приведённого изображения."""
__slots__ = ("keypoints", "descriptors", "width", "height", "source_width", "source_height")
def __init__(
self,
keypoints: np.ndarray,
descriptors: np.ndarray,
width: int,
height: int,
source_width: int,
source_height: int,
):
self.keypoints = keypoints # float32 (N, 5): x, y, size, angle, response
self.descriptors = descriptors # uint8 (N, 128)
self.width = width # размеры приведённого изображения
self.height = height
self.source_width = source_width # размеры оригинала после EXIF-ориентации
self.source_height = source_height
@property
def count(self) -> int:
return int(self.keypoints.shape[0])
def decode_image(data: bytes) -> tuple[np.ndarray, int, int]:
"""Декодирует изображение, применяет EXIF-ориентацию.
Возвращает (RGB-массив, width, height) размеры после ориентации.
Фактический формат определяется при декодировании, не по расширению
(docs/05 §5.5-1).
"""
try:
img = Image.open(io.BytesIO(data))
fmt = img.format
if fmt not in ALLOWED_IMAGE_FORMATS:
raise ImageFormatUnsupported(fmt)
img = ImageOps.exif_transpose(img)
except ImageFormatUnsupported:
raise
except Exception as exc:
raise ImageDecodeFailed(
f"Файл не декодируется как изображение: {exc.__class__.__name__}"
) from exc
arr = np.asarray(img.convert("RGB"))
return arr, img.width, img.height
def _preprocess(rgb: np.ndarray, params: ExtractionParams) -> tuple[np.ndarray, int, int]:
"""Grayscale → ресайз длинной стороны ≤ max_image_size → CLAHE."""
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
h, w = gray.shape[:2]
long_side = max(h, w)
if long_side > params.max_image_size:
scale = params.max_image_size / long_side
gray = cv2.resize(
gray,
(max(1, round(w * scale)), max(1, round(h * scale))),
interpolation=cv2.INTER_AREA,
)
clahe = cv2.createCLAHE(
clipLimit=float(params.clahe_clip_limit),
tileGridSize=(int(params.clahe_tile_grid[0]), int(params.clahe_tile_grid[1])),
)
return clahe.apply(gray), gray.shape[1], gray.shape[0]
def extract(data: bytes, params: ExtractionParams) -> Features:
"""Полный пайплайн извлечения признаков (docs/04 §4.2)."""
rgb, src_w, src_h = decode_image(data)
if src_w < MIN_WIDTH or src_h < MIN_HEIGHT:
raise ImageTooSmall(src_w, src_h)
prepared, width, height = _preprocess(rgb, params)
sift = cv2.SIFT_create(nfeatures=int(params.max_keypoints))
keypoints, descriptors = sift.detectAndCompute(prepared, None)
n = len(keypoints)
if n == 0 or descriptors is None:
# «Бедная» текстура деградирует без исключений (UT-07)
return Features(
np.zeros((0, 5), dtype=np.float32),
np.zeros((0, 128), dtype=np.uint8),
width, height, src_w, src_h,
)
kp_array = np.array(
[[kp.pt[0], kp.pt[1], kp.size, kp.angle, kp.response] for kp in keypoints],
dtype=np.float32,
).reshape(n, 5)
# Значения SIFT-дескрипторов дискретны 0–255: uint8 хранит их без потерь (docs/06 §6.2)
desc_u8 = np.clip(np.rint(descriptors), 0, 255).astype(np.uint8)
return Features(kp_array, desc_u8, width, height, src_w, src_h)
+243
View File
@@ -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,
},
},
}
+92
View File
@@ -0,0 +1,92 @@
"""Резолвер настроек — единственное место слияния уровней параметров
(docs/03 §3.2.2, docs/04 §4.5.4).
Приоритет для сравнения (от слабого к сильному):
env → профиль (запрос, иначе профиль из блоба) → comparison из блоба → запрос.
Для извлечения: env → профиль запроса → extraction запроса.
"""
from __future__ import annotations
import dataclasses
from app.config import Config
from app.cv.exceptions import InvalidSettings
from app.cv.params import (
PROFILES,
ComparisonParams,
ExtractionParams,
RequestSettings,
base_comparison,
base_extraction,
)
def effective_extraction(config: Config, settings: RequestSettings | None) -> ExtractionParams:
"""env → пресет профиля запроса → переопределения extraction запроса.
Применяется в /features и к эталонам-изображениям в /verify (FR-002).
"""
params = base_extraction(config)
if settings is None:
return params
if settings.profile is not None:
params = _apply_extraction(params, PROFILES[settings.profile]["extraction"])
return _apply_extraction(params, settings.extraction)
def effective_probe_extraction(config: Config, settings: RequestSettings | None) -> ExtractionParams:
"""Извлечение пробы в /verify: env → профиль запроса.
extraction-переопределения запроса на пробу не действуют — по букве
FR-002 они применимы только к эталонам-изображениям отладочного режима.
"""
params = base_extraction(config)
if settings is not None and settings.profile is not None:
params = _apply_extraction(params, PROFILES[settings.profile]["extraction"])
return params
def effective_comparison(
config: Config,
settings: RequestSettings | None,
blob_settings: RequestSettings | None,
) -> ComparisonParams:
"""env → профиль (запрос → блоб) → comparison блоба → comparison запроса."""
params = base_comparison(config)
profile_name = settings.profile if settings is not None and settings.profile else (
blob_settings.profile if blob_settings is not None else None
)
if profile_name is not None:
params = _apply_comparison(params, PROFILES[profile_name]["comparison"])
if blob_settings is not None:
params = _apply_comparison(params, blob_settings.comparison)
if settings is not None:
params = _apply_comparison(params, settings.comparison)
if params.uncertain_inliers_min > params.match_inliers_min:
raise InvalidSettings(
"uncertain_inliers_min не может превышать match_inliers_min "
f"(эффективные значения: {params.uncertain_inliers_min} > {params.match_inliers_min})",
{"key": "uncertain_inliers_min"},
)
return params
def _apply_extraction(params: ExtractionParams, overrides: dict) -> ExtractionParams:
changes = {
"max_image_size": overrides.get("max_image_size", params.max_image_size),
"max_keypoints": overrides.get("max_keypoints", params.max_keypoints),
"clahe_clip_limit": overrides.get("clahe_clip_limit", params.clahe_clip_limit),
"clahe_tile_grid": tuple(overrides.get("clahe_tile_grid", params.clahe_tile_grid)),
}
return dataclasses.replace(params, **changes)
def _apply_comparison(params: ComparisonParams, overrides: dict) -> ComparisonParams:
changes = {k: v for k, v in overrides.items() if k in _COMPARISON_FIELD_NAMES}
return dataclasses.replace(params, **changes)
_COMPARISON_FIELD_NAMES = {f.name for f in dataclasses.fields(ComparisonParams)}
+218
View File
@@ -0,0 +1,218 @@
"""Оркестрация вычислительных сценариев: /features и /verify (docs/03 §3.3).
Единственный модуль CV-ядра, собирающий пайплайн целиком; API-слой делегирует
сюда и не касается признаков. Сравнения по эталонам исполняются в пуле
потоков (OpenCV освобождает GIL — docs/04 §4.7); порядок не влияет на итог.
"""
from __future__ import annotations
import concurrent.futures
import hashlib
import logging
from dataclasses import dataclass
import cv2
import numpy as np
from app.config import Config
from app.cv import blob as blob_codec
from app.cv import resolver
from app.cv.comparison import PairMetrics, PairResult, compare_features
from app.cv.exceptions import CvError, ImageDecodeFailed
from app.cv.extraction import Features, extract
from app.cv.params import RequestSettings, parse_settings, validate_stored_settings
logger = logging.getLogger("opencv.cv")
# Число воркеров пула сравнений: покрывает типовой запрос (≤32 эталона),
# не создавая лишних потоков на маленьких запросах.
_COMPARE_POOL_SIZE = 4
_ZIP_MAGICS = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
_JPEG_MAGIC = b"\xff\xd8\xff"
_PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
@dataclass
class ExtractionOutcome:
blob: bytes
format_version: int
algo_id: str
keypoints_count: int
image_width: int
image_height: int
@dataclass
class VerifyOutcome:
verdict: str
is_match: bool
confidence: float
references_compared: int
best_reference_index: int
metrics: PairMetrics
thresholds: dict
probe_sha256: str
class CvService:
"""Stateless-вычислитель: без состояния между запросами (FR-006)."""
def __init__(self, config: Config):
self.config = config
self._ready_reasons: list[str] = []
# ------------------------------------------------------------------ init
def init_core(self) -> tuple[bool, list[str]]:
"""Пробное извлечение признаков служебного изображения при старте (FR-005).
Проверяет работоспособность декодирования и SIFT без транспортных
ограничений (минимальное разрешение) — это диагностика ядра, а не
обработка пользовательского фото.
"""
self._ready_reasons = []
try:
rng = np.random.default_rng(0)
synthetic = (rng.random((480, 640)) * 255).astype("uint8")
sift = cv2.SIFT_create(nfeatures=self.config.sift_max_keypoints)
keypoints, descriptors = sift.detectAndCompute(synthetic, None)
if not keypoints or descriptors is None or len(keypoints) == 0:
self._ready_reasons.append("SIFT не нашёл keypoints на служебном шуме")
except Exception as exc: # noqa: BLE001 - любая ошибка = неготовность
self._ready_reasons.append(f"инициализация CV-ядра: {exc.__class__.__name__}: {exc}")
return not self._ready_reasons, self._ready_reasons
@property
def ready_reasons(self) -> list[str]:
return list(self._ready_reasons)
# ------------------------------------------------------------- /features
def extract_to_blob(self, image_bytes: bytes, settings: dict | None) -> ExtractionOutcome:
settings_req = parse_settings(settings, self.config) if settings is not None else None
params = resolver.effective_extraction(self.config, settings_req)
features = extract(image_bytes, params)
algo_id = blob_codec.compute_algo_id(params)
meta = blob_codec.build_meta(
params=params,
algo_id=algo_id,
features=features,
settings_payload=_settings_payload(settings_req),
source_sha256=hashlib.sha256(image_bytes).hexdigest(),
)
blob = blob_codec.pack(features, meta)
return ExtractionOutcome(
blob=blob,
format_version=blob_codec.FORMAT_VERSION,
algo_id=algo_id,
keypoints_count=features.count,
image_width=features.source_width,
image_height=features.source_height,
)
# --------------------------------------------------------------- /verify
def verify(
self,
probe_bytes: bytes,
reference_parts: list[bytes],
settings: dict | None,
) -> VerifyOutcome:
settings_req = parse_settings(settings, self.config) if settings is not None else None
probe = extract(probe_bytes, resolver.effective_probe_extraction(self.config, settings_req))
pairs: list[tuple[Features, RequestSettings | None]] = [
self._load_reference(part, index, settings_req)
for index, part in enumerate(reference_parts)
]
results = self._compare_all(probe, pairs, settings_req)
best_index, best = _select_best(results)
return VerifyOutcome(
verdict=best.verdict,
is_match=best.verdict == "match",
confidence=best.confidence,
references_compared=len(results),
best_reference_index=best_index,
metrics=best.metrics,
thresholds=best.thresholds.thresholds_payload(),
probe_sha256=hashlib.sha256(probe_bytes).hexdigest(),
)
# ------------------------------------------------------------- internals
def _load_reference(
self, part: bytes, index: int, settings_req: RequestSettings | None
) -> tuple[Features, RequestSettings | None]:
"""Эталон запроса: блоб .npz или изображение (отладочный режим, Q-4)."""
try:
if part[:4] in _ZIP_MAGICS:
unpacked = blob_codec.unpack(part, self.config)
stored = (
validate_stored_settings(unpacked.settings, self.config)
if unpacked.settings is not None
else None
)
return unpacked.features, stored
if _is_image_signature(part):
params = resolver.effective_extraction(self.config, settings_req)
return extract(part, params), None
raise ImageDecodeFailed(
"Часть reference не распознана ни как блоб .npz, ни как изображение"
)
except CvError as exc:
exc.details.setdefault("reference_index", index)
raise
def _compare_all(
self,
probe: Features,
pairs: list[tuple[Features, RequestSettings | None]],
settings_req: RequestSettings | None,
) -> list[PairResult]:
def run(item: tuple[Features, RequestSettings | None]) -> PairResult:
ref_features, blob_settings = item
params = resolver.effective_comparison(self.config, settings_req, blob_settings)
return compare_features(probe, ref_features, params)
if len(pairs) == 1:
return [run(pairs[0])]
with concurrent.futures.ThreadPoolExecutor(
max_workers=min(_COMPARE_POOL_SIZE, len(pairs))
) as pool:
return list(pool.map(run, pairs))
def _select_best(results: list[PairResult]) -> tuple[int, PairResult]:
"""Пара с максимальным confidence; при равенстве — с большим inliers,
затем меньший индекс (docs/04 §4.4)."""
best_index = 0
for i in range(1, len(results)):
cand, best = results[i], results[best_index]
if (cand.confidence, cand.metrics.inliers) > (best.confidence, best.metrics.inliers):
best_index = i
return best_index, results[best_index]
def _settings_payload(settings_req: RequestSettings | None) -> dict | None:
"""settings как переданы в /features — записываются в блоб (docs/06 §6.3)."""
if settings_req is None:
return None
payload: dict = {}
if settings_req.profile is not None:
payload["profile"] = settings_req.profile
if settings_req.extraction:
payload["extraction"] = dict(settings_req.extraction)
if settings_req.comparison:
payload["comparison"] = dict(settings_req.comparison)
return payload
def _is_image_signature(part: bytes) -> bool:
if part[:3] == _JPEG_MAGIC:
return True
if part[:8] == _PNG_MAGIC:
return True
return part[:4] == b"RIFF" and part[8:12] == b"WEBP"