File size: 13,089 Bytes
aa7162d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/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)


@lru_cache(maxsize=None)
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


@lru_cache(maxsize=None)
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


@lru_cache(maxsize=None)
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()