import hashlib import json import re import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parent CACHE_DIR = ROOT / "video_cache" EXPORT_DIR = ROOT / "exports" def sha256_file(path): digest = hashlib.sha256() with open(path, "rb") as file: for chunk in iter(lambda: file.read(1048576), b""): digest.update(chunk) return digest.hexdigest() def export_index(summary, video_path, output_dir): cache_id = summary["video_cache_id"] if not re.fullmatch(r"[a-f0-9]{16}", cache_id): raise ValueError("Invalid cache ID") if summary.get("status") != "indexed": raise ValueError("Indexing is incomplete") patterns = { "siglip": f"{cache_id}_siglip_*.npz", "whisper": f"{cache_id}_whisper_*.json", "audio_embeddings": f"{cache_id}_audio_embeddings_*.npz", "yolo": f"{cache_id}_yolo11n_*.json", "ocr": f"{cache_id}_easyocr_*.json", "index_manifest": f"{cache_id}_index_manifest.json" } files = {} for name, pattern in patterns.items(): matches = [ p for p in CACHE_DIR.glob(pattern) if p.is_file() and not p.is_symlink() ] if not matches and name == "audio_embeddings": if summary["features"]["transcript_segments"] == 0: continue if len(matches) != 1: raise RuntimeError( f"Expected one {name} cache, found {len(matches)}" ) files[name] = matches[0] manifest = { "format_version": 1, "source_cache_id": cache_id, "video_sha256": sha256_file(video_path), "summary": summary, "files": { name: path.name for name, path in files.items() }, "sha256": { name: sha256_file(path) for name, path in files.items() } } output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) archive = output_dir / f"{cache_id}_index.zip" with zipfile.ZipFile( archive, "w", compression=zipfile.ZIP_DEFLATED ) as package: for path in files.values(): package.write(path, arcname=path.name) package.writestr( "manifest.json", json.dumps(manifest, indent=2) ) return str(archive)