"""Dataset storage: dataset//main.bin (metadata) + dataset//patch-N.dat (fingerprint chunks). Each video gets a folder named by its id (the "bin"). main.bin holds the metadata record. Every ingest call writes a new patch-N.dat file holding that call's frame hashes, so future re-ingests / additions just add more patch files instead of rewriting everything. """ import os import struct from datetime import datetime, timezone BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DATASET_DIR = os.path.join(BASE_DIR, "dataset") MAIN_BIN_VERSION = 1 PATCH_ENTRY = struct.Struct(" str: (n,) = struct.unpack(" str: d = os.path.join(DATASET_DIR, video_id) os.makedirs(d, exist_ok=True) return d def _main_bin_path(video_id: str) -> str: return os.path.join(video_dir(video_id), "main.bin") def write_main_bin(video_id, title, source_path, duration_seconds, created_at, num_patches, total_hashes): with open(_main_bin_path(video_id), "wb") as f: f.write(struct.pack(" dict: with open(_main_bin_path(video_id), "rb") as f: f.read(1) # version, unused for now vid = _read_str(f) title = _read_str(f) source_path = _read_str(f) (duration,) = struct.unpack(" list: d = video_dir(video_id) files = [fn for fn in os.listdir(d) if fn.startswith("patch-") and fn.endswith(".dat")] files.sort(key=lambda fn: int(fn[len("patch-"):-len(".dat")])) return [os.path.join(d, fn) for fn in files] def write_patch(video_id: str, patch_index: int, fingerprint: list) -> str: path = os.path.join(video_dir(video_id), f"patch-{patch_index}.dat") with open(path, "wb") as f: f.write(struct.pack(" list: entries = [] with open(path, "rb") as f: (count,) = struct.unpack(" list: hashes = [] for p in list_patch_files(video_id): hashes.extend(read_patch(p)) return hashes def add_video_patch(video_id, title, source_path, duration_seconds, fingerprint) -> dict: """Write a new patch file for this id and refresh main.bin. Works for both brand-new ids and appending more fingerprint data to an existing id.""" next_index = len(list_patch_files(video_id)) write_patch(video_id, next_index, fingerprint) total_hashes = sum(len(read_patch(p)) for p in list_patch_files(video_id)) created_at = datetime.now(timezone.utc).isoformat() write_main_bin( video_id=video_id, title=title, source_path=source_path, duration_seconds=duration_seconds, created_at=created_at, num_patches=next_index + 1, total_hashes=total_hashes, ) return read_main_bin(video_id) def list_videos() -> list: if not os.path.isdir(DATASET_DIR): return [] results = [] for vid in sorted(os.listdir(DATASET_DIR)): if os.path.isfile(os.path.join(DATASET_DIR, vid, "main.bin")): results.append(read_main_bin(vid)) return results def get_video(video_id: str): try: return read_main_bin(video_id) except FileNotFoundError: return None