"""Validate the frozen cohort and prepare one model's matched local media.""" from __future__ import annotations import hashlib import shutil import json import subprocess from collections import Counter from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parent COHORT = ROOT / "resources/cohort1015.jsonl" COHORT_SHA256 = "1f27841f079259e7ebc5249bce114ec9542af36c7fc9a117f32eeac2f652dd62" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): digest.update(block) return digest.hexdigest() def read_jsonl(path: Path) -> list[dict]: return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] def atomic_json(path: Path, data: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") temporary.replace(path) def write_jsonl(path: Path, rows: list[dict]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") temporary.write_text( "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows), encoding="utf-8", ) temporary.replace(path) def frozen_rows() -> list[dict]: if sha256(COHORT) != COHORT_SHA256: raise ValueError("Frozen cohort SHA256 differs from the release") rows = read_jsonl(COHORT) ids = [row["videoId"] for row in rows] counts = Counter(row["interaction"] for row in rows) if len(rows) != 1015 or len(set(ids)) != 1015 or counts["event"] != 165 or counts["perspective"] != 150: raise ValueError(f"Frozen membership is invalid: n={len(rows)}, scopes={counts}") return rows def _indexed_media(path: Path, expected_ids: set[str], label: str) -> dict[str, dict]: rows = read_jsonl(path) if len(rows) != len(expected_ids): raise ValueError(f"{label}: expected {len(expected_ids)} rows, got {len(rows)}") indexed = {} for row in rows: sample_id = row.get("sample_id", row.get("videoId")) if not isinstance(sample_id, str) or sample_id in indexed: raise ValueError(f"{label}: invalid or duplicate sample_id {sample_id!r}") indexed[sample_id] = row if set(indexed) != expected_ids: raise ValueError(f"{label}: missing={len(expected_ids - set(indexed))}, extra={len(set(indexed) - expected_ids)}") return indexed def _check_media(row: dict, label: str) -> tuple[str, str]: value = row.get("path", row.get("local_video_file")) expected = row.get("sha256", row.get("media_sha256")) if not isinstance(value, str) or not isinstance(expected, str) or len(expected) != 64: raise ValueError(f"{label}: provide absolute path and sha256") path = Path(value) if not path.is_absolute() or not path.is_file() or path.suffix.lower() != ".mp4": raise ValueError(f"{label}: MP4 path missing or not absolute: {path}") actual = sha256(path) if actual != expected.lower(): raise ValueError(f"{label}: SHA256 mismatch: {path}") try: probe = json.loads(subprocess.check_output([ "ffprobe", "-v", "error", "-show_streams", "-of", "json", str(path), ], stderr=subprocess.PIPE, timeout=60)) video = next(item for item in probe["streams"] if item["codec_type"] == "video") audio = next(item for item in probe["streams"] if item["codec_type"] == "audio") video_ok = (int(video["width"]), int(video["height"]), video["avg_frame_rate"], int(video["nb_frames"])) == (768, 512, "24/1", 121) audio_ok = (int(audio["sample_rate"]), int(audio["channels"])) == (48000, 2) duration_ok = float(audio["duration"]) >= 5.0 if not (video_ok and audio_ok and duration_ok): raise ValueError(f"{label}: expected 768x512, 121 frames at 24 fps, stereo 48 kHz and >=5 s audio") except (KeyError, StopIteration, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: raise ValueError(f"{label}: ffprobe failed or missing required streams: {path}") from exc return str(path.resolve()), actual def prepare(generated: Path, gt: Path | None, run_dir: Path, model_id: str) -> dict: if not model_id or any(character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for character in model_id): raise ValueError("model_id may contain only letters, digits, hyphen and underscore") cohort = frozen_rows() ids = {row["videoId"] for row in cohort} generated_index = _indexed_media(generated, ids, "generated") gt_index = _indexed_media(gt, ids, "gt") if gt else None manifest_dir = run_dir / "manifests" complete_path = run_dir / "INPUTS_COMPLETE.json" if complete_path.exists(): raise FileExistsError(f"Run already prepared: {complete_path}; use another run_dir") rows, gt_rows = [], [] for cohort_row in cohort: sample_id = cohort_row["videoId"] media, media_sha = _check_media(generated_index[sample_id], f"generated/{sample_id}") gt_media, gt_sha = _check_media(gt_index[sample_id], f"gt/{sample_id}") if gt_index else ("", cohort_row["media_sha256"]) row = { "sample_id": sample_id, "clip_id": f"{model_id}__{sample_id}", "group": model_id, "checkpoint_label": model_id, "local_video_file": media, "media_sha256": media_sha, "source_video": media, "audio_uri": media, "gt_file": gt_media, "gt_sha256": gt_sha, "imagebind_id": f"{model_id}__{sample_id}", "imagebind_group": model_id, "caption_av": cohort_row["caption_av"], "interaction": cohort_row["interaction"], "scene": cohort_row["scene"], "source_group": sample_id, "sample_partition": "frozen1015", "dataset_family": "Helixbench", "first_frame_sha256": cohort_row["first_frame_sha256"], } rows.append(row) gt_rows.append({"sample_id": sample_id, "media_sha256": gt_sha, **({"local_video_file": gt_media} if gt_index else {})}) for name, selected in ( ("all1015", rows), ("text1015", rows), ("imagebind1015", rows), ("event165", [r for r in rows if r["interaction"] == "event"]), ("perspective150", [r for r in rows if r["interaction"] == "perspective"]), ("gt1015", gt_rows), ): write_jsonl(manifest_dir / f"{name}.jsonl", selected) if not gt_index: _copy_reference_features(run_dir, ids) payload = { "model_id": model_id, "cohort_sha256": COHORT_SHA256, "generated_input_sha256": sha256(generated), "gt_input_sha256": sha256(gt) if gt else "packaged_reference_features", "counts": {"all": 1015, "event": 165, "perspective": 150}, "manifests": {name: sha256(manifest_dir / f"{name}.jsonl") for name in ("all1015", "text1015", "imagebind1015", "event165", "perspective150", "gt1015")}, } atomic_json(complete_path, payload) return payload def validate_prepared(run_dir: Path) -> dict: payload = json.loads((run_dir / "INPUTS_COMPLETE.json").read_text()) if payload["cohort_sha256"] != COHORT_SHA256: raise ValueError("Prepared run uses a different frozen cohort") for name, expected in payload["manifests"].items(): path = run_dir / "manifests" / f"{name}.jsonl" if sha256(path) != expected: raise ValueError(f"Manifest modified after preparation: {name}") return payload def verify_media_manifest(run_dir: Path, include_gt: bool = True) -> None: """Reject changed or missing MP4 files before using cached model features.""" names = ("all1015", "gt1015") if include_gt else ("all1015",) rows = [row for name in names for row in read_jsonl(run_dir / "manifests" / f"{name}.jsonl") if "local_video_file" in row] def check(row: dict) -> None: path = Path(row["local_video_file"]) if not path.is_file() or sha256(path) != row["media_sha256"]: raise ValueError(f"Media changed since prepare: {path}") with ThreadPoolExecutor(max_workers=8) as pool: list(pool.map(check, rows)) def _copy_reference_features(run_dir: Path, ids: set[str]) -> None: """Verify packaged GT features, then copy them into the standard run layout.""" source_root = ROOT.parents[2] / "reference" index = json.loads((source_root / "SHA256SUMS.json").read_text()) expected = {f"{metric}/gt/{sample_id}.npz" for metric in ("passt", "vggish") for sample_id in ids} if set(index) != expected: raise ValueError("Packaged reference features must cover the frozen 1015 twice") for relative, digest in index.items(): source = source_root / relative if sha256(source) != digest: raise ValueError(f"Reference feature changed: {relative}") dest = run_dir / "results" / relative dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, dest) def verify_packaged_gt_features(run_dir: Path) -> None: """Ensure cached GT arrays still match the published reference package.""" source_root = ROOT.parents[2] / "reference" index = json.loads((source_root / "SHA256SUMS.json").read_text()) for relative, digest in index.items(): path = run_dir / "results" / relative if sha256(path) != digest: raise ValueError(f"Packaged GT feature changed: {relative}")