Download onepass_inputs/evaluation/run.py from yang1232009/VOLBench: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/datasets/yang1232009/VOLBench/resolve/main/onepass_inputs/evaluation/run.py
- Command line
-
hf download hf://datasets/yang1232009/VOLBench/onepass_inputs/evaluation/run.py
-
curl -L -o run.py https://huggingface.co/datasets/yang1232009/VOLBench/resolve/main/onepass_inputs/evaluation/run.py
13.1 kB
| #!/usr/bin/env python3 | |
| """Validate the one-pass handoff and score its generated shots with the V4 rubric.""" | |
| import argparse | |
| from concurrent.futures import ThreadPoolExecutor | |
| from functools import lru_cache | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| from statistics import mean | |
| import subprocess | |
| import sys | |
| import time | |
| HERE = Path(__file__).resolve().parent | |
| BUNDLE = HERE.parent | |
| DIMS = ("entity_consistency", "scene_consistency", "transition_smoothness", | |
| "semantic_alignment", "cinematic_aesthetics", "narrative_coherence", "action_staging") | |
| def read(path): | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def save(path, data): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = path.with_suffix(".tmp") | |
| temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| temporary.replace(path) | |
| def digest(path): | |
| for delay in (0, 0.25, 1): | |
| if delay: | |
| time.sleep(delay) | |
| try: | |
| with path.open("rb") as stream: | |
| return hashlib.file_digest(stream, "sha256").hexdigest() | |
| except FileNotFoundError: | |
| raise | |
| except OSError as error: | |
| last_error = error | |
| raise OSError(f"Cannot read {path}: {last_error}") from last_error | |
| def verify(path, expected): | |
| if digest(path.resolve()) != expected: | |
| raise ValueError(f"SHA256 mismatch: {path}") | |
| def load_films(selected, first=None): | |
| manifest = read(HERE / "manifest.json") | |
| if manifest["format_version"] != 1: | |
| raise ValueError("Unsupported evaluation manifest version") | |
| verify(HERE / "rubric.txt", manifest["rubric_sha256"]) | |
| generation = read(BUNDLE / "manifest.json") | |
| if generation.get("prompt_revision") != manifest["generation_prompt_revision"]: | |
| raise ValueError("Generation prompt revision differs from the evaluation manifest") | |
| generation_rows = {(r["film_id"], r["shot_id"]): r for r in generation["shots"]} | |
| known = {r["film_id"] for r in manifest["films"]} | |
| if selected - known: | |
| raise ValueError(f"Unknown film ID: {sorted(selected - known)}") | |
| if len(known) != manifest["film_count"] or sum(r["shots"] for r in manifest["films"]) != manifest["shot_count"]: | |
| raise ValueError("Incorrect evaluation manifest counts") | |
| if len(generation_rows) != manifest["shot_count"] or {f for f, _ in generation_rows} != known: | |
| raise ValueError("Generation manifest and evaluation manifest disagree") | |
| films = [] | |
| reference_checks = {} | |
| for entry in manifest["films"]: | |
| fid = entry["film_id"] | |
| if selected and fid not in selected: | |
| continue | |
| path = HERE / entry["path"] | |
| verify(path, entry["sha256"]) | |
| film = read(path) | |
| shots = film["shots"] | |
| ids = [s["shot_id"] for s in shots] | |
| if film["film_id"] != fid or len(ids) != entry["shots"] or len(set(ids)) != len(ids): | |
| raise ValueError(f"Incorrect or duplicated shot roster: {fid}") | |
| if first is not None: | |
| if first > len(shots): | |
| raise ValueError(f"{fid} only has {len(shots)} shots") | |
| shots = film["shots"] = shots[:first] | |
| previous = None | |
| for ordinal, shot in enumerate(shots, 1): | |
| sid = shot["shot_id"] | |
| folder = Path(generation_rows[fid, sid]["folder"]) | |
| meta = read(BUNDLE / folder / "shot.json") | |
| current = (folder / meta["new_model_result"]).as_posix() | |
| if (shot["ordinal"] != ordinal or shot["id"] != f"{fid}__{sid}" | |
| or not shot["initial_beat"].strip() or shot["current_video"] != current | |
| or shot["previous_video"] != previous): | |
| raise ValueError(f"Broken beat/result/predecessor binding: {fid}/{sid}") | |
| refs = shot["entity_refs"] + shot["scene_refs"] + shot["excluded_refs"] | |
| ordered = sorted(refs, key=lambda ref: ref["picture_number"]) | |
| if [(r["picture_number"], r["sha256"]) for r in ordered] != [ | |
| (r["picture_number"], r["sha256"]) for r in meta["reference_images"] | |
| ]: | |
| raise ValueError(f"Generation reference order changed: {fid}/{sid}") | |
| for ref in shot["entity_refs"] + shot["scene_refs"]: | |
| original = meta["reference_images"][ref["picture_number"] - 1] | |
| ref["path"] = (folder / original["file"]).as_posix() | |
| resolved = (BUNDLE / ref["path"]).resolve() | |
| if reference_checks.setdefault(resolved, ref["sha256"]) != ref["sha256"]: | |
| raise ValueError(f"Conflicting reference hashes: {resolved}") | |
| previous = current | |
| films.append(film) | |
| with ThreadPoolExecutor(max_workers=6) as pool: | |
| list(pool.map(verify, reference_checks, reference_checks.values())) | |
| return manifest, films | |
| def probe(path): | |
| data = json.loads(subprocess.check_output([ | |
| "ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type", | |
| "-of", "json", str(path), | |
| ])) | |
| kinds = {s["codec_type"] for s in data["streams"]} | |
| duration = float(data["format"]["duration"]) | |
| if "video" not in kinds or not 0 < duration < float("inf"): | |
| raise ValueError(f"Invalid video: {path}") | |
| return duration, "audio" in kinds | |
| def transport(path, budget, cache): | |
| duration, audio = probe(path) | |
| if path.stat().st_size <= budget: | |
| return path | |
| cache.mkdir(parents=True, exist_ok=True) | |
| target = cache / f"{digest(path.resolve())}-{budget}.mp4" | |
| if target.exists(): | |
| return target | |
| temporary = target.with_suffix(".tmp.mp4") | |
| rate = int(budget * 8 * 0.86 / duration) - (48000 if audio else 0) | |
| try: | |
| for scale, multiplier in ((720, 1), (480, 0.65), (360, 0.4)): | |
| bitrate = str(max(80_000, int(rate * multiplier))) | |
| subprocess.run([ | |
| "ffmpeg", "-y", "-nostdin", "-v", "error", "-xerror", "-i", str(path), | |
| "-map", "0:v:0", "-map", "0:a:0?", "-vf", f"scale=-2:'min({scale},ih)'", | |
| "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", | |
| "-b:v", bitrate, "-maxrate", bitrate, "-bufsize", str(2 * int(bitrate)), | |
| "-c:a", "aac", "-b:a", "48k", "-movflags", "+faststart", str(temporary), | |
| ], check=True) | |
| if temporary.stat().st_size <= budget: | |
| adjusted_duration, adjusted_audio = probe(temporary) | |
| if abs(adjusted_duration - duration) > 0.15 or audio != adjusted_audio: | |
| raise ValueError(f"Transport copy changed duration or audio: {path}") | |
| temporary.replace(target) | |
| return target | |
| raise ValueError(f"Full-length video exceeds the transport budget: {path}") | |
| finally: | |
| temporary.unlink(missing_ok=True) | |
| def prepare(films, result_root, out, video_budget): | |
| manifest = [] | |
| for film in films: | |
| for shot in film["shots"]: | |
| videos = {key: result_root / shot[key] for key in ("previous_video", "current_video") if shot[key]} | |
| sample = {key: shot[key] for key in ("id", "initial_beat")} | |
| if shot["previous_video"]: | |
| sample["require_boundary_anchors"] = True | |
| durations = {key: probe(path)[0] for key, path in videos.items()} | |
| if sum(path.stat().st_size for path in videos.values()) > video_budget: | |
| total = sum(durations.values()) | |
| sizes = {key: path.stat().st_size for key, path in videos.items()} | |
| for key, path in videos.items(): | |
| budget = int(video_budget * (0.10 + 0.80 * durations[key] / total)) | |
| if len(videos) == 1: | |
| budget = video_budget | |
| else: | |
| other = next(k for k in videos if k != key) | |
| budget = max(budget, video_budget - sizes[other]) | |
| sample[key] = str(transport(path, budget, out / "transport_cache")) | |
| else: | |
| sample.update({key: str(path) for key, path in videos.items()}) | |
| for role in ("entity_refs", "scene_refs"): | |
| sample[role] = [{"path": str((BUNDLE / ref["path"]).resolve()), "label": ref["label"]} | |
| for ref in shot[role]] | |
| manifest.append(sample) | |
| return manifest | |
| def valid_mean(values): | |
| valid = [v for v in values if v is not None] | |
| return mean(valid) if valid else None | |
| def average(dimensions): | |
| return mean(dimensions.values()) if all(v is not None for v in dimensions.values()) else None | |
| def summarize(films, out): | |
| per_film = [] | |
| for film in films: | |
| rows = [read(out / "scores" / f"{s['id']}.json") for s in film["shots"]] | |
| values = {d: [row["scores"][d]["score"] for row in rows] for d in DIMS} | |
| dimensions = {d: valid_mean(v) for d, v in values.items()} | |
| per_film.append({"film_id": film["film_id"], "scored": len(rows), "dimensions": dimensions, | |
| "valid_counts": {d: sum(x is not None for x in v) for d, v in values.items()}, | |
| "average": average(dimensions)}) | |
| dimensions = {d: valid_mean([f["dimensions"][d] for f in per_film]) for d in DIMS} | |
| save(out / "summary.json", { | |
| "film_count": len(per_film), "scored": sum(f["scored"] for f in per_film), | |
| "dimensions": dimensions, "average": average(dimensions), "films": per_film, | |
| }) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| mode = parser.add_mutually_exclusive_group() | |
| mode.add_argument("--check", action="store_true", help="Validate the handoff before generation, no API") | |
| mode.add_argument("--preflight", action="store_true", help="Require and probe generated videos, no API") | |
| parser.add_argument("--film", action="append", default=[], help="Select film ID, repeat for multiple films") | |
| parser.add_argument("--first", type=int, help="Evaluate the first N shots in each selected film") | |
| parser.add_argument("--results-root", type=Path, default=BUNDLE, help="Root with generated films/.../result.mp4") | |
| parser.add_argument("--out", type=Path, default=BUNDLE / "evaluation_results") | |
| parser.add_argument("--video-budget-mib", type=float, default=14) | |
| parser.add_argument("--base-url", default=os.getenv("EASYAPI_BASE_URL", "https://easymax.ai")) | |
| parser.add_argument("--max-attempts", type=int, default=3) | |
| args = parser.parse_args() | |
| if args.video_budget_mib <= 0 or args.max_attempts < 1: | |
| parser.error("Video budget and max attempts must be positive") | |
| if args.first is not None and (args.first < 1 or not args.film): | |
| parser.error("--first requires a positive count and an explicit --film") | |
| manifest, films = load_films(set(args.film), args.first) | |
| result_root = args.results_root.resolve() | |
| shots = [s for film in films for s in film["shots"]] | |
| missing = [s["current_video"] for s in shots | |
| if not (result_root / s["current_video"]).is_file() | |
| or (result_root / s["current_video"]).stat().st_size == 0] | |
| print(json.dumps({"films": len(films), "shots": len(shots), "missing_results": len(missing), | |
| "entity_refs": sum(len(s["entity_refs"]) for s in shots), | |
| "scene_refs": sum(len(s["scene_refs"]) for s in shots), | |
| "excluded_refs": sum(len(s["excluded_refs"]) for s in shots)}, ensure_ascii=False), flush=True) | |
| if args.check: | |
| return | |
| if missing: | |
| parser.error("Missing or empty generated videos, first paths:\n" + "\n".join(missing[:10])) | |
| if args.preflight: | |
| for shot in shots: | |
| probe(result_root / shot["current_video"]) | |
| print(f"Media preflight passed: {len(shots)} generated videos") | |
| return | |
| if not os.environ.get("EASYAPI_API_KEY"): | |
| parser.error("Set EASYAPI_API_KEY") | |
| out = args.out.resolve() | |
| config = {"model": "gemini-3.8-flash", "base_url": args.base_url, | |
| "rubric_sha256": manifest["rubric_sha256"], "film_ids": [f["film_id"] for f in films]} | |
| if args.first is not None: | |
| config["first"] = args.first | |
| config_path = out / "run_config.json" | |
| if config_path.exists() and read(config_path) != config: | |
| parser.error("Evaluation configuration changed. Choose a new --out directory.") | |
| save(config_path, config) | |
| samples = prepare(films, result_root, out, int(args.video_budget_mib * 1024**2)) | |
| input_path = out / "evaluator_inputs.json" | |
| save(input_path, samples) | |
| subprocess.run([sys.executable, str(HERE / "evaluate.py"), str(input_path), | |
| "--out", str(out), "--base-url", args.base_url, | |
| "--max-attempts", str(args.max_attempts)], check=True) | |
| summarize(films, out) | |
| print(f"Completed {len(shots)} shots. Summary: {out / 'summary.json'}") | |
| if __name__ == "__main__": | |
| main() | |