Files
open_cv/app/cv/service.py
T
2026-10-06 17:58:35 +03:00

258 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Оркестрация вычислительных сценариев: /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.calibration import CalibrationOutcome, CalibrationPhoto, run_calibration
from app.cv.comparison import PairMetrics, PairResult, compare_features
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
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 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]:
"""Эталон запроса: блоб .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"