#!/usr/bin/env python3 """Export auditable per-clip results for both checkpoints and all three judges.""" from __future__ import annotations import argparse import csv import json import statistics from collections import defaultdict from pathlib import Path RUNS = ("official_hf_origin_main", "trained_step4572") JUDGES = ( ("gemini", "gemini-3.1-pro-preview", "gemini_gpt55"), ("gpt", "gpt-5.5", "gemini_gpt55"), ("gpt", "gpt-6.1-sol", "gpt61"), ) def read_json(path: Path) -> dict: return json.loads(path.read_text(encoding="utf-8")) def write_csv(path: Path, rows: list[dict]) -> None: with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--benchmark", type=Path, required=True) args = parser.parse_args() benchmark = args.benchmark.resolve() selection = read_json(benchmark / "selection.json") samples = selection["samples"] if len(samples) != 200 or len({item["id"] for item in samples}) != 200: raise ValueError("Expected exactly 200 unique test samples") judgment_rows = [] summary_rows = [] class_rows = [] for run_name in RUNS: visual = read_json(benchmark / f"results_{run_name}_visual.json")["visual"]["per_sample"] visual_by_id = {item["id"]: item for item in visual} if len(visual) != 200 or len(visual_by_id) != 200: raise ValueError(f"Expected 200 visual records for {run_name}") judge_records = {} for judge, expected_model, suffix in JUDGES: result = read_json(benchmark / f"results_{run_name}_{suffix}.json")["mechanics_fidelity"][judge] records = result["records"] if result["n_runs"] != 3 or len(records) != 600: raise ValueError(f"Expected 600 records for {run_name} {expected_model}") grouped = defaultdict(list) for record in records: if record["model"] != expected_model: raise ValueError(f"Unexpected judge model for {run_name}: {record['model']}") grouped[(record["id"], int(record["run"]))].append(record) judge_records[expected_model] = grouped for sample in samples: sample_id = sample["id"] prediction = (benchmark / "generated" / run_name / sample["output_name"]).resolve() if not prediction.is_file(): raise FileNotFoundError(prediction) source = sample["identity"] base = { "id": sample_id, "source_id": sample["source_id"], "model": run_name, "ground_truth": sample["label"], "definition_id": source.get("definition_id", ""), "source_archive": source.get("source_archive", ""), "source_reused": source.get("reused", ""), "source_video": sample["source_video"], "generated_video": str(prediction), "source_video_sha256": source["video_sha256"], } visual_item = visual_by_id[sample_id] summary = {**base, "ssim": visual_item["ssim"], "lpips": visual_item["lpips"]} for _, expected_model, _ in JUDGES: records = [] for judge_run in (1, 2, 3): key = (sample_id, judge_run) grouped = judge_records[expected_model][key] if len(grouped) != 1: raise ValueError(f"Expected one record for {run_name} {expected_model} {key}") record = grouped[0] stat = prediction.stat() if (Path(record["prediction"]).resolve() != prediction or int(record["prediction_size"]) != stat.st_size or int(record["prediction_mtime_ns"]) != stat.st_mtime_ns or record["ground_truth"] != sample["label"]): raise ValueError(f"Judge record is not tied to expected video: {run_name} {key}") records.append(record) judgment_rows.append({ **base, "judge_model": expected_model, "transport": record["transport"], "run": judge_run, "predicted_state": record["predicted_state"], "correct": bool(record["correct"]), "confidence": record.get("confidence"), "evidence": json.dumps(record.get("evidence"), ensure_ascii=False), "reason": record.get("reason"), "protocol_version": record["protocol_version"], }) summary[f"{expected_model}_correct_runs"] = sum(bool(item["correct"]) for item in records) summary[f"{expected_model}_predictions"] = " | ".join(item["predicted_state"] for item in records) summary_rows.append(summary) for label, expected_count in selection["class_counts"].items(): matching = [row for row in summary_rows if row["model"] == run_name and row["ground_truth"] == label] if len(matching) != expected_count: raise ValueError(f"Unexpected class count for {run_name} {label}") row = { "model": run_name, "class": label, "samples": expected_count, "ssim_mean": statistics.fmean(item["ssim"] for item in matching), "lpips_mean": statistics.fmean(item["lpips"] for item in matching), } for _, expected_model, _ in JUDGES: for judge_run in (1, 2, 3): matching_judge = [item for item in judgment_rows if item["model"] == run_name and item["ground_truth"] == label and item["judge_model"] == expected_model and item["run"] == judge_run] if len(matching_judge) != expected_count: raise ValueError(f"Incomplete {expected_model} class {label} run {judge_run}") row[f"{expected_model}_run{judge_run}_correct"] = sum(item["correct"] for item in matching_judge) class_rows.append(row) if len(judgment_rows) != 3600 or len(summary_rows) != 400 or len(class_rows) != 10: raise ValueError("Expected 3600 judgments, 400 clip summaries, and 10 class summaries") write_csv(benchmark / "per_run_judgments.csv", judgment_rows) write_csv(benchmark / "per_clip_summary.csv", summary_rows) write_csv(benchmark / "per_class_summary.csv", class_rows) with (benchmark / "per_run_judgments.jsonl").open("w", encoding="utf-8") as handle: for row in judgment_rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") print("Exported 3600 judgments, 400 clip summaries, and 10 class summaries") if __name__ == "__main__": main()