"""Оркестрация запроса: декод -> эмбеддинги -> сравнение. Stateless (FR-006).""" from __future__ import annotations import hashlib import io import time from dataclasses import dataclass from typing import Protocol, Sequence import numpy as np from PIL import Image, ImageOps from .comparison import ComparisonResult, cosine_similarities, decide from .exceptions import ( ImageDecodeError, ImageTooSmallError, UnsupportedImageFormatError, ) _SUPPORTED_FORMATS = {"JPEG", "PNG", "WEBP"} class Embedder(Protocol): """Контракт эмбеддера; DinoEmbedder и тестовый FakeEmbedder ему удовлетворяют.""" def load(self) -> None: ... def embed(self, images: Sequence[Image.Image]) -> np.ndarray: ... @dataclass(frozen=True) class VerifyOutcome: """Результат verify(): сравнение + метаданные запроса.""" comparison: ComparisonResult probe_sha256: str processing_ms: float class DinoService: """ Stateless-вычислитель: без состояния между запросами.""" def __init__(self, config, embedder: Embedder): self._config = config self._embedder = embedder def init_core(self) -> None: """Загрузка модели при старте; исключение фиксируется в ready_reasons выше.""" self._embedder.load() def verify(self, probe: bytes, references: Sequence[bytes]) -> VerifyOutcome: started = time.perf_counter() probe_img = self._decode(probe) reference_imgs = [self._decode(blob) for blob in references] embeddings = self._embedder.embed([probe_img, *reference_imgs]) similarities = cosine_similarities(embeddings[0], embeddings[1:]) result = decide( similarities, threshold_match=self._config.threshold_match, threshold_no_match=self._config.threshold_no_match, ) return VerifyOutcome( comparison=result, probe_sha256=hashlib.sha256(probe).hexdigest(), processing_ms=(time.perf_counter() - started) * 1000.0, ) def _decode(self, data: bytes) -> Image.Image: """Байты -> RGB-изображение с проверкой формата и минимального размера.""" try: image = Image.open(io.BytesIO(data)) image.load() except Exception as exc: raise ImageDecodeError(f"не удалось декодировать изображение: {exc}") from exc if image.format not in _SUPPORTED_FORMATS: raise UnsupportedImageFormatError( f"формат {image.format!r} не поддерживается; допустимы JPEG, PNG, WebP" ) # exif_transpose теряет .format — вызываем после проверки формата image = ImageOps.exif_transpose(image) image = image.convert("RGB") if min(image.size) < self._config.min_image_dim: raise ImageTooSmallError( f"сторона {min(image.size)}px меньше минимума {self._config.min_image_dim}px" ) return image