Download runs/scripts/finalize.py from BlueSourceJY/ERCBench-MultiShotMaster-400: direct link, hf CLI and curl.
- Browser
- Download file 6.78 kB
-
https://huggingface.co/datasets/BlueSourceJY/ERCBench-MultiShotMaster-400/resolve/main/runs/scripts/finalize.py
- Command line
-
hf download hf://datasets/BlueSourceJY/ERCBench-MultiShotMaster-400/runs/scripts/finalize.py
-
curl -L -o finalize.py https://huggingface.co/datasets/BlueSourceJY/ERCBench-MultiShotMaster-400/resolve/main/runs/scripts/finalize.py
6.78 kB
| # MultiShotMaster: validates outputs, checks prompts/tokens, measures the visible cuts, writes per-episode metadata, | |
| # timing table, and builds the release dir (~/msm_run/release) in the same layout as ERCBench-ShotStream-400. | |
| import csv, datetime as dt, glob, hashlib, json, os, re, shutil, subprocess, sys | |
| import av, numpy as np | |
| W = os.path.expanduser("~/msm_run") | |
| idx = json.load(open(os.path.expanduser("~/shotstream_run/inputs/prompts_index.json"))) | |
| DXB = dt.timezone(dt.timedelta(hours=4)) | |
| F = 75 # frames per shot (configured shot_groups [75k, 75(k+1)]) | |
| # ---- timing + token records, per worker log (later runs of an episode override earlier ones) | |
| timing, tok_of, tok_problems = {}, {}, [] | |
| for logp in sorted(glob.glob(f"{W}/logs/worker_gpu*.log")): | |
| gpu = int(re.search(r"gpu(\d+)", logp).group(1)) | |
| tokp = f"{W}/logs/tokens_gpu{gpu}.jsonl" | |
| tok = [json.loads(l) for l in open(tokp, encoding="utf-8")] if os.path.exists(tokp) else [] | |
| pos, st = 0, {} | |
| for line in open(logp, errors="replace"): | |
| m = re.search(r"(\d{4}-\d\d-\d\dT[\d:.]+Z) \[EPISODE\] (start|saved) (\S+)", line) | |
| if not m: continue | |
| ts = dt.datetime.strptime(m.group(1), "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=dt.timezone.utc) | |
| eid = m.group(3); n = idx[eid]["shot_count"] | |
| if m.group(2) == "start": | |
| st[eid] = ts | |
| recs = tok[pos:pos + 2 * n]; pos += 2 * n # n positive prompts, then n negative prompts | |
| if len(recs) < 2 * n: continue # interrupted before encoding finished | |
| probs = [] | |
| for k, s in enumerate(idx[eid]["shots"]): | |
| r = recs[k] | |
| if r["raw"] != "Story: Now: " + s["prompt"]: probs.append((eid, k + 1, "text mismatch / misaligned")) | |
| if hashlib.sha256(r["raw"][len("Story: Now: "):].encode()).hexdigest() != s["sha256"]: probs.append((eid, k + 1, "sha mismatch")) | |
| if r["n_tokens"] > r["seq_len"]: probs.append((eid, k + 1, f"{r['n_tokens']} tokens > {r['seq_len']}")) | |
| tok_of[eid] = ([recs[k]["n_tokens"] for k in range(n)], recs[n]["n_tokens"], probs) | |
| else: | |
| mem = re.search(r"peak_mem_gb=([\d.]+)", line) | |
| timing[eid] = {"seconds": round((ts - st[eid]).total_seconds(), 2), "gpu": gpu, "start": st[eid], "end": ts, | |
| "peak_mem_gb": float(mem.group(1)) if mem else None, "log": os.path.basename(logp)} | |
| def probe(p): | |
| out = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", | |
| "stream=width,height,r_frame_rate,nb_read_frames", "-of", "json", p], capture_output=True, text=True) | |
| s = json.loads(out.stdout)["streams"][0] | |
| dec = subprocess.run(["ffmpeg", "-v", "error", "-xerror", "-i", p, "-f", "null", "-"], capture_output=True, text=True) | |
| return s, dec.returncode == 0 and not dec.stderr.strip() | |
| def measure_cuts(p, n): | |
| """Per configured cut 75k: frame index with the strongest consecutive-frame change in [75k-2, 75k+8].""" | |
| fr = [f.to_ndarray(format="gray").astype(np.float32) for f in av.open(p).decode(video=0)] | |
| d = np.array([np.abs(fr[i] - fr[i - 1]).mean() for i in range(1, len(fr))]) # d[i-1]: change into frame i | |
| med = float(np.median(d)); out = [] | |
| for k in range(1, n): | |
| c = F * k; lo, hi = c - 2, c + 8 | |
| i = lo + int(np.argmax(d[lo - 1:hi])) | |
| out.append({"configured": c, "measured": i, "offset": i - c, "strength": round(float(d[i - 1]) / med, 1)}) | |
| return out | |
| rel = f"{W}/release"; problems = []; rows = [] | |
| for eid, info in sorted(idx.items(), key=lambda x: x[1]["priority"]): | |
| n = info["shot_count"]; src = f"{W}/outputs/{eid}.mp4"; nf = F * n | |
| if not os.path.exists(src): problems.append((eid, "missing")); continue | |
| s, ok = probe(src) | |
| if not (s["width"] == 832 and s["height"] == 480 and s["r_frame_rate"] == "15/1" and int(s["nb_read_frames"]) == nf and ok): | |
| problems.append((eid, s, ok)); continue | |
| if eid not in timing: problems.append((eid, "no timing")); continue | |
| if eid not in tok_of: problems.append((eid, "no token record")); continue | |
| tok_problems += tok_of[eid][2] | |
| cuts = measure_cuts(src, n) | |
| d = f"{rel}/episodes/{eid}"; os.makedirs(d, exist_ok=True) | |
| shutil.copy2(src, f"{d}/episode.mp4") | |
| vsha = hashlib.sha256(open(src, "rb").read()).hexdigest() | |
| t = timing[eid] | |
| md = {"episode_id": eid, "priority": info["priority"], "shot_count": n, | |
| "shot_frame_ranges": [[F * k, F * (k + 1)] for k in range(n)], | |
| "cut_frames": [F * k for k in range(1, n)], | |
| "measured_cut_frames": [c["measured"] for c in cuts], | |
| "measured_cuts": cuts, | |
| "fps": 15, "resolution": {"width": 832, "height": 480}, "num_frames": nf, | |
| "seed": 42, "seed_scope": "set before every episode (code default)", "global_caption": "", | |
| "shots": [{"shot": p["shot"], "prompt": p["prompt"], "prompt_sha256": p["sha256"], | |
| "text_encoder_input": "Story: Now: " + p["prompt"], "umt5_tokens": tok_of[eid][0][i]} | |
| for i, p in enumerate(info["shots"])], | |
| "negative_prompt_umt5_tokens": tok_of[eid][1], | |
| "video_sha256": vsha, "generation_seconds": t["seconds"], "peak_mem_gb": t["peak_mem_gb"], "gpu_index": t["gpu"], | |
| "generated_at_dubai": t["end"].astimezone(DXB).isoformat(), "source_log": t["log"]} | |
| json.dump(md, open(f"{d}/metadata.json", "w"), ensure_ascii=False, indent=2) | |
| rows.append([eid, info["priority"], n, t["gpu"], t["seconds"], round(t["seconds"] / n, 2), | |
| t["start"].astimezone(DXB).isoformat(), t["end"].astimezone(DXB).isoformat(), | |
| " ".join(str(c["offset"]) for c in cuts), vsha]) | |
| print("ok episodes:", len(rows), "problems:", len(problems), "| token problems:", len(tok_problems)) | |
| for p in problems[:20]: print("PROBLEM", p) | |
| for p in tok_problems[:20]: print("TOKEN PROBLEM", p) | |
| offs = [int(o) for r in rows for o in r[8].split()] | |
| if offs: print("measured cut offsets (frames after configured cut):", {o: offs.count(o) for o in sorted(set(offs))}) | |
| allt = [x for e in tok_of.values() for x in e[0]] | |
| if allt: print("tokens per shot: max", max(allt), "min", min(allt)) | |
| os.makedirs(f"{rel}/runs", exist_ok=True) | |
| with open(f"{rel}/runs/timing.csv", "w", newline="") as f: | |
| w = csv.writer(f); w.writerow(["episode_id", "priority", "shot_count", "gpu", "seconds", "seconds_per_shot", "start_dubai", "end_dubai", "cut_offsets", "video_sha256"]) | |
| w.writerows(rows) | |
| if rows: | |
| tot_s = sum(r[4] for r in rows); tot_shots = sum(r[2] for r in rows) | |
| print("sum gen seconds", round(tot_s, 1), "shots", tot_shots, "avg s/shot", round(tot_s / tot_shots, 3)) | |
| sys.exit(1 if problems or tok_problems else 0) | |