calibrate
This commit is contained in:
@@ -11,6 +11,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.cv.exceptions import (
|
||||
BlobInvalid,
|
||||
CalibrationDatasetInvalid,
|
||||
CvError,
|
||||
FormatUnsupported,
|
||||
ImageDecodeFailed,
|
||||
@@ -30,6 +31,7 @@ _CV_ERROR_MAP: list[tuple[type[CvError], int, str]] = [
|
||||
(UnknownProfile, 400, "UNKNOWN_PROFILE"),
|
||||
(ImageFormatUnsupported, 415, "UNSUPPORTED_MEDIA_TYPE"),
|
||||
(InvalidSettings, 422, "INVALID_SETTINGS"),
|
||||
(CalibrationDatasetInvalid, 422, "CALIBRATION_DATASET_INVALID"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from starlette.datastructures import UploadFile
|
||||
from app.api.deps import check_image_content_type, require_api_key
|
||||
from app.api.errors import ApiError
|
||||
from app.api.schemas import (
|
||||
CalibrateResponse,
|
||||
ProfileModel,
|
||||
ProfilesResponse,
|
||||
StatusResponse,
|
||||
@@ -192,6 +193,78 @@ async def verify(request: Request):
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------- /calibrate
|
||||
|
||||
|
||||
async def _read_pack_parts(parts: list, name: str, config) -> list[tuple[str, bytes]]:
|
||||
"""Читает повторяемые файловые части пачки: [(имя файла, байты)]."""
|
||||
payloads: list[tuple[str, bytes]] = []
|
||||
for i, part in enumerate(parts):
|
||||
if isinstance(part, str):
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
f"Часть {name}[{i}] должна быть файлом",
|
||||
{"part": name, "index": i},
|
||||
)
|
||||
check_image_content_type(part.content_type, f"{name}[{i}]")
|
||||
data = await part.read()
|
||||
_check_image_size(data, f"{name}[{i}]", config.max_image_bytes)
|
||||
payloads.append((part.filename or f"{name}[{i}]", data))
|
||||
return payloads
|
||||
|
||||
|
||||
def _check_pack_size(parts: list, name: str, minimum: int, maximum: int) -> None:
|
||||
if len(parts) < minimum:
|
||||
raise ApiError(
|
||||
422, "VALIDATION_ERROR",
|
||||
f"Частей {name} меньше минимума ({minimum}): калибровка невозможна",
|
||||
{"part": name, "count": len(parts), "minimum": minimum},
|
||||
)
|
||||
if len(parts) > maximum:
|
||||
raise ApiError(
|
||||
400, "TOO_MANY_CALIBRATION_IMAGES",
|
||||
f"Число фото в пачке {name} ({len(parts)}) превышает лимит {maximum}",
|
||||
{"part": name, "count": len(parts), "limit": maximum},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/calibrate", dependencies=[Depends(require_api_key)])
|
||||
async def calibrate(request: Request):
|
||||
"""Подбор per-объектных настроек сравнения по двум пачкам фото
|
||||
(docs/05 §5.4.5): positive — один объект с разных ракурсов, negative —
|
||||
похожие объекты. Тяжёлый запрос: до ~60 с при максимальных пачках."""
|
||||
config = _config(request)
|
||||
form = await request.form()
|
||||
|
||||
positive_raw = form.getlist("positive")
|
||||
negative_raw = form.getlist("negative")
|
||||
limit = config.calibration_max_images_per_pack
|
||||
_check_pack_size(positive_raw, "positive", minimum=2, maximum=limit)
|
||||
_check_pack_size(negative_raw, "negative", minimum=1, maximum=limit)
|
||||
positive_parts = await _read_pack_parts(positive_raw, "positive", config)
|
||||
negative_parts = await _read_pack_parts(negative_raw, "negative", config)
|
||||
|
||||
started = time.perf_counter()
|
||||
outcome = await run_in_threadpool(
|
||||
_service(request).calibrate, positive_parts, negative_parts
|
||||
)
|
||||
processing_ms = int((time.perf_counter() - started) * 1000)
|
||||
|
||||
best = outcome.best
|
||||
log_event(
|
||||
logger, logging.INFO, "calibration completed",
|
||||
trace_id=getattr(request.state, "trace_id", ""),
|
||||
geometry_model=best.geometry_model,
|
||||
lowe_ratio=best.lowe_ratio,
|
||||
f1=round(best.selection.f1, 4),
|
||||
true_matches=best.selection.tp,
|
||||
false_matches=best.selection.fp,
|
||||
pairs=outcome.pairs_total,
|
||||
processing_ms=processing_ms,
|
||||
)
|
||||
return CalibrateResponse(**outcome.payload(), processing_ms=processing_ms)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- /profiles
|
||||
|
||||
|
||||
|
||||
@@ -53,6 +53,66 @@ class ProfilesResponse(BaseModel):
|
||||
defaults: dict = Field(description="Базовые значения (env-умолчания) для наследования")
|
||||
|
||||
|
||||
class CalibrateComboModel(BaseModel):
|
||||
"""Одна комбинация pipeline-параметров с подобранными порогами (docs/05 §5.4.5)."""
|
||||
|
||||
geometry_model: str
|
||||
lowe_ratio: float
|
||||
ransac_reproj_threshold: float
|
||||
thresholds: dict = Field(
|
||||
description="Подобранные пороги вердикта: inliers_match, inlier_ratio_match, "
|
||||
"coverage_min, inliers_uncertain_min"
|
||||
)
|
||||
tp: int = Field(description="Позитивные пары с вердиктом match")
|
||||
fp: int = Field(description="Ложные match на негативных парах")
|
||||
fn: int
|
||||
f1: float
|
||||
uncertain_rate: float
|
||||
margin: float = Field(description="Нормированный зазор между классами (устойчивость)")
|
||||
|
||||
|
||||
class CalibratePairModel(BaseModel):
|
||||
probe: str
|
||||
ref: str
|
||||
is_positive: bool
|
||||
good_matches: int
|
||||
inliers: int
|
||||
inlier_ratio: float
|
||||
coverage: float
|
||||
verdict: Literal["match", "uncertain", "no_match"]
|
||||
|
||||
|
||||
class CalibrateImageModel(BaseModel):
|
||||
name: str
|
||||
group: Literal["positive", "negative"]
|
||||
keypoints: int
|
||||
|
||||
|
||||
class CalibrateSkippedModel(BaseModel):
|
||||
name: str
|
||||
group: str
|
||||
reason: str
|
||||
|
||||
|
||||
class CalibrateResponse(BaseModel):
|
||||
"""Полный отчёт калибровки (docs/05 §5.4.5)."""
|
||||
|
||||
settings: dict = Field(
|
||||
description="Готовый фрагмент settings: передать в /features при регистрации "
|
||||
"эталонов и/или в /verify для этого объекта"
|
||||
)
|
||||
metrics: dict
|
||||
best: CalibrateComboModel
|
||||
ranking: list[CalibrateComboModel] = Field(description="Все комбинации, от лучшей к худшей")
|
||||
pairs: list[CalibratePairModel]
|
||||
presets: dict = Field(description="tp/fp стандартных профилей на тех же данных")
|
||||
images: list[CalibrateImageModel]
|
||||
skipped: list[CalibrateSkippedModel]
|
||||
warnings: list[str]
|
||||
selfcheck: dict
|
||||
processing_ms: int
|
||||
|
||||
|
||||
class StatusResponse(BaseModel):
|
||||
status: str
|
||||
|
||||
|
||||
Reference in New Issue
Block a user