calibrate
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user