Приложение: FastAPI-фабрика, ядро DINOv2 (torch.hub ViT-S/14, CLS-эмбеддинги), POST /api/v1/verify
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
"""Чистая логика решения: косинусные близости -> вердикт. Без I/O и без модели."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
VERDICT_MATCH = "match"
|
||||
VERDICT_UNCERTAIN = "uncertain"
|
||||
VERDICT_NO_MATCH = "no_match"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ComparisonResult:
|
||||
"""Итог сравнения проверяемого фото с эталонами."""
|
||||
|
||||
verdict: str # match | uncertain | no_match
|
||||
is_match: bool
|
||||
best_reference_index: int
|
||||
best_similarity: float
|
||||
similarities: tuple[float, ...]
|
||||
|
||||
|
||||
def cosine_similarities(probe: "numpy.ndarray", references: "numpy.ndarray") -> list[float]:
|
||||
"""Близости probe к каждой строке references; входы — L2-нормированные векторы."""
|
||||
sims = references @ probe
|
||||
return [float(s) for s in sims]
|
||||
|
||||
|
||||
def decide(
|
||||
similarities: Sequence[float], threshold_match: float, threshold_no_match: float
|
||||
) -> ComparisonResult:
|
||||
"""Вердикт по лучшему совпадению: эталоны сняты с разных ракурсов и в разное
|
||||
время, поэтому агрегат — максимум близости по всем эталонам.
|
||||
"""
|
||||
if not similarities:
|
||||
raise ValueError("similarities пуст: нужен хотя бы один эталон")
|
||||
best_index = max(range(len(similarities)), key=lambda i: similarities[i])
|
||||
best = float(similarities[best_index])
|
||||
if best >= threshold_match:
|
||||
verdict = VERDICT_MATCH
|
||||
elif best < threshold_no_match:
|
||||
verdict = VERDICT_NO_MATCH
|
||||
else:
|
||||
verdict = VERDICT_UNCERTAIN
|
||||
return ComparisonResult(
|
||||
verdict=verdict,
|
||||
is_match=verdict == VERDICT_MATCH,
|
||||
best_reference_index=best_index,
|
||||
best_similarity=best,
|
||||
similarities=tuple(float(s) for s in similarities),
|
||||
)
|
||||
Reference in New Issue
Block a user