init app
This commit is contained in:
+217
@@ -0,0 +1,217 @@
|
||||
"""Блоб-кодек — единственное место, знающее формат .npz (docs/03 §3.5-3).
|
||||
|
||||
Формат блоба — docs/06-формат-признаков.md:
|
||||
descriptors uint8 (N, 128); keypoints float32 (N, 5); meta — JSON-строка.
|
||||
Защита от zip-бомбы: суммарный размер распакованных массивов ограничен
|
||||
SIFT_MAX_KEYPOINTS, формы проверяются до копирования (FR-003 п.3, §6.6-2).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from app.config import Config
|
||||
from app.cv.exceptions import BlobInvalid, FormatUnsupported
|
||||
from app.cv.extraction import Features
|
||||
from app.cv.params import ExtractionParams
|
||||
|
||||
FORMAT_VERSION = 1
|
||||
ALGO_PREFIX = "sift-v1"
|
||||
|
||||
DESCRIPTOR_COLS = 128
|
||||
KEYPOINT_COLS = 5
|
||||
|
||||
_META_REQUIRED_FIELDS = (
|
||||
"format_version",
|
||||
"algo_id",
|
||||
"extraction_params",
|
||||
"source_image",
|
||||
"keypoints_count",
|
||||
"created_at",
|
||||
)
|
||||
|
||||
|
||||
def compute_algo_id(params: ExtractionParams) -> str:
|
||||
"""Отпечаток эффективных параметров извлечения + версия OpenCV.
|
||||
|
||||
Информативен (docs/04 §4.5.5): смена настроек меняет отпечаток, но не
|
||||
format_version — блобы с разными algo_id совместимы.
|
||||
"""
|
||||
payload = {"opencv_version": cv2.__version__, **params.fingerprint_payload()}
|
||||
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
|
||||
digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:8]
|
||||
return f"{ALGO_PREFIX}:{digest}"
|
||||
|
||||
|
||||
def build_meta(
|
||||
params: ExtractionParams,
|
||||
algo_id: str,
|
||||
features: Features,
|
||||
settings_payload: dict | None,
|
||||
source_sha256: str,
|
||||
) -> dict:
|
||||
return {
|
||||
"format_version": FORMAT_VERSION,
|
||||
"algo_id": algo_id,
|
||||
"extraction_params": {
|
||||
"opencv_version": cv2.__version__,
|
||||
"max_image_size": params.max_image_size,
|
||||
"clahe": {
|
||||
"clip_limit": params.clahe_clip_limit,
|
||||
"tile_grid_size": list(params.clahe_tile_grid),
|
||||
},
|
||||
"sift_nfeatures": params.max_keypoints,
|
||||
},
|
||||
"settings": settings_payload,
|
||||
"source_image": {"width": features.source_width, "height": features.source_height},
|
||||
"keypoints_count": features.count,
|
||||
"source_sha256": source_sha256,
|
||||
"created_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
}
|
||||
|
||||
|
||||
def pack(features: Features, meta: dict) -> bytes:
|
||||
"""Упаковка признаков и метаданных в бинарный .npz."""
|
||||
if features.descriptors.dtype != np.uint8 or features.keypoints.dtype != np.float32:
|
||||
raise BlobInvalid("Неверные типы массивов при упаковке блоба")
|
||||
buffer = io.BytesIO()
|
||||
np.savez_compressed(
|
||||
buffer,
|
||||
descriptors=features.descriptors,
|
||||
keypoints=features.keypoints,
|
||||
meta=np.array(json.dumps(meta, ensure_ascii=False)),
|
||||
)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class UnpackedBlob:
|
||||
"""Распакованный блоб: признаки + meta + провалидированные settings."""
|
||||
|
||||
__slots__ = ("features", "meta", "settings")
|
||||
|
||||
def __init__(self, features: Features, meta: dict, settings: object | None):
|
||||
self.features = features
|
||||
self.meta = meta
|
||||
self.settings = settings
|
||||
|
||||
|
||||
def unpack(data: bytes, config: Config) -> UnpackedBlob:
|
||||
"""Распаковка с полной валидацией (FR-003): структура → версия → лимиты."""
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||
# np.savez хранит массивы как <name>.npy — сравниваем без суффикса
|
||||
stored = {name.removesuffix(".npy") for name in zf.namelist()}
|
||||
required = {"descriptors", "keypoints", "meta"}
|
||||
if not required <= stored:
|
||||
raise BlobInvalid(
|
||||
"Блоб не содержит обязательные массивы", {"missing": sorted(required - stored)}
|
||||
)
|
||||
# Проверка размеров до распаковки: zip-контейнер не должен
|
||||
# разворачиваться в гигабайты памяти (FR-003 п.3)
|
||||
max_kp = config.sift_max_keypoints
|
||||
limits = {
|
||||
"descriptors.npy": max_kp * DESCRIPTOR_COLS, # uint8, 1 байт
|
||||
"keypoints.npy": max_kp * KEYPOINT_COLS * 4, # float32
|
||||
}
|
||||
for name, limit in limits.items():
|
||||
declared = zf.getinfo(name).file_size
|
||||
if declared > limit:
|
||||
raise BlobInvalid(
|
||||
f"Массив {name.removesuffix('.npy')} превышает лимит распаковки: "
|
||||
f"{declared} байт > {limit} (SIFT_MAX_KEYPOINTS={max_kp})",
|
||||
{"array": name.removesuffix(".npy"), "declared_size": declared},
|
||||
)
|
||||
npz = np.load(io.BytesIO(data), allow_pickle=False)
|
||||
descriptors = np.asarray(npz["descriptors"])
|
||||
keypoints = np.asarray(npz["keypoints"])
|
||||
meta_raw = npz["meta"]
|
||||
except BlobInvalid:
|
||||
raise
|
||||
except (zipfile.BadZipFile, OSError, ValueError, KeyError) as exc:
|
||||
raise BlobInvalid(f"Блоб не является корректным .npz: {exc.__class__.__name__}") from exc
|
||||
|
||||
_validate_arrays(descriptors, keypoints, config)
|
||||
|
||||
try:
|
||||
meta = json.loads(str(meta_raw.item()))
|
||||
except (ValueError, AttributeError, TypeError) as exc:
|
||||
raise BlobInvalid("meta блоба не является корректным JSON") from exc
|
||||
if not isinstance(meta, dict):
|
||||
raise BlobInvalid("meta блоба должен быть JSON-объектом")
|
||||
missing = [f for f in _META_REQUIRED_FIELDS if f not in meta]
|
||||
if missing:
|
||||
raise BlobInvalid(f"meta блоба не содержит обязательные поля: {missing}",
|
||||
{"missing": missing})
|
||||
|
||||
if meta["format_version"] != FORMAT_VERSION:
|
||||
raise FormatUnsupported(FORMAT_VERSION, meta["format_version"])
|
||||
n = int(keypoints.shape[0])
|
||||
if meta["keypoints_count"] != n:
|
||||
raise BlobInvalid(
|
||||
f"keypoints_count ({meta['keypoints_count']}) не совпадает с числом точек ({n})"
|
||||
)
|
||||
|
||||
src_w, src_h = _source_dims(meta)
|
||||
resized_w, resized_h = _resized_dims(src_w, src_h, meta)
|
||||
features = Features(
|
||||
keypoints=keypoints,
|
||||
descriptors=descriptors,
|
||||
width=resized_w,
|
||||
height=resized_h,
|
||||
source_width=src_w,
|
||||
source_height=src_h,
|
||||
)
|
||||
return UnpackedBlob(features, meta, settings=meta.get("settings"))
|
||||
|
||||
|
||||
def _source_dims(meta: dict) -> tuple[int, int]:
|
||||
source = meta.get("source_image")
|
||||
if not isinstance(source, dict):
|
||||
raise BlobInvalid("meta.source_image должен быть JSON-объектом")
|
||||
w, h = source.get("width"), source.get("height")
|
||||
if not isinstance(w, int) or not isinstance(h, int) or w <= 0 or h <= 0:
|
||||
raise BlobInvalid("meta.source_image.width/height отсутствуют или невалидны")
|
||||
return w, h
|
||||
|
||||
|
||||
def _validate_arrays(descriptors: np.ndarray, keypoints: np.ndarray, config: Config) -> None:
|
||||
if descriptors.dtype != np.uint8 or descriptors.ndim != 2 or descriptors.shape[1] != DESCRIPTOR_COLS:
|
||||
raise BlobInvalid(
|
||||
f"Массив descriptors должен быть uint8 (N, {DESCRIPTOR_COLS}), "
|
||||
f"получен {descriptors.dtype} {descriptors.shape}"
|
||||
)
|
||||
if keypoints.dtype != np.float32 or keypoints.ndim != 2 or keypoints.shape[1] != KEYPOINT_COLS:
|
||||
raise BlobInvalid(
|
||||
f"Массив keypoints должен быть float32 (N, {KEYPOINT_COLS}), "
|
||||
f"получен {keypoints.dtype} {keypoints.shape}"
|
||||
)
|
||||
if descriptors.shape[0] != keypoints.shape[0]:
|
||||
raise BlobInvalid(
|
||||
f"Число дескрипторов ({descriptors.shape[0]}) не равно числу keypoints "
|
||||
f"({keypoints.shape[0]})"
|
||||
)
|
||||
if keypoints.shape[0] > config.sift_max_keypoints:
|
||||
raise BlobInvalid(
|
||||
f"Число keypoints ({keypoints.shape[0]}) превышает SIFT_MAX_KEYPOINTS "
|
||||
f"({config.sift_max_keypoints})"
|
||||
)
|
||||
|
||||
|
||||
def _resized_dims(src_w: int, src_h: int, meta: dict) -> tuple[int, int]:
|
||||
"""Восстанавливает размеры приведённого изображения из meta.
|
||||
|
||||
Координаты keypoints живут в системе приведённого изображения
|
||||
(docs/06 §6.2); для эталона она не хранится явно и пересчитывается из
|
||||
source_image и max_image_size по правилу ресайза (docs/04 §4.2).
|
||||
"""
|
||||
max_size = meta.get("extraction_params", {}).get("max_image_size")
|
||||
if not isinstance(max_size, (int, float)) or isinstance(max_size, bool) or max_size <= 0:
|
||||
raise BlobInvalid("meta.extraction_params.max_image_size отсутствует или невалиден")
|
||||
scale = min(1.0, float(max_size) / max(src_w, src_h))
|
||||
return max(1, round(src_w * scale)), max(1, round(src_h * scale))
|
||||
Reference in New Issue
Block a user