Files
windroost/tools/batch_hero_gif_parallel.py
T

145 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Parallelized hero-art batch: submit all GIF generations up front, then
download them concurrently. Generation (~107s each) is the bottleneck; doing
N in parallel cuts an 8-hero batch from ~28min to ~3min.
Cost control preserved: submit each (hero,state) at most once; task id persisted
immediately; download retries are free (URL refresh); upstream generation
failure allows ONE re-submit. Existing task ids / gifs are reused.
Usage: python3 tools/batch_hero_gif_parallel.py H30 H31 ... H54 [--workers 4]
"""
from __future__ import annotations
import argparse
import concurrent.futures
import json
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TOOLS = ROOT / "tools"
sys.path.insert(0, str(TOOLS))
from batch_hero_gif import ( # noqa: E402
FRAME_PLAN, TaskFailed, download_gif, gif_prompt, creature_desc,
states_for, install, submit, godot_import_once, CHARS, RUNS,
)
def prepare_jobs(heroes: list[str]) -> list[dict]:
"""Ensure every (hero,state) has a task id and gif path; submit if missing."""
jobs = []
for hid in heroes:
try:
desc = creature_desc(hid)
except StopIteration:
print(f"FATAL: creature_desc cannot find id {hid!r} (len={len(hid)}) in pack", file=sys.stderr, flush=True)
raise
run = RUNS / hid / "run"
run.mkdir(parents=True, exist_ok=True)
for state in states_for(hid):
n, _ = FRAME_PLAN[state]
gif_path = run / f"{state}.gif"
tid_file = run / f"{state}-gif-task.txt"
if gif_path.exists():
print(f"[{hid}/{state}] gif exists, skip", flush=True)
continue
tid = ""
if tid_file.exists():
tid = tid_file.read_text().strip()
print(f"[{hid}/{state}] reuse task {tid}", flush=True)
else:
tid = submit(gif_prompt(desc, state, n), run, f"{state}_gif")
tid_file.write_text(tid)
print(f"[{hid}/{state}] submitted {tid}", flush=True)
jobs.append({"hid": hid, "state": state, "tid": tid, "gif": gif_path, "n": n})
time.sleep(2) # light throttle; parallel test showed 2s is safe
return jobs
def fetch_job(job: dict) -> tuple[dict, bool, str]:
"""Download one gif with cost-aware retry. Returns (job, ok, err)."""
hid, state, tid, gif, n = job["hid"], job["state"], job["tid"], job["gif"], job["n"]
tid_file = RUNS / hid / "run" / f"{state}-gif-task.txt"
for resubmit in range(2):
try:
download_gif(tid, gif, need_frames=n)
return job, True, ""
except TaskFailed as e:
if resubmit == 0:
# one paid re-submit allowed
run = RUNS / hid / "run"
new_tid = submit(gif_prompt(creature_desc(hid), state, n), run, f"{state}_gif")
tid_file.write_text(new_tid)
tid = new_tid
job["tid"] = new_tid
print(f"[{hid}/{state}] upstream failed, one re-submit {new_tid}", flush=True)
continue
return job, False, str(e)
except Exception as e:
# download glitch: keep task id, no new generation
return job, False, str(e)
return job, False, "unknown"
def pack_job(job: dict) -> bool:
import subprocess
hid, state, gif, n = job["hid"], job["state"], job["gif"], job["n"]
_, fps = FRAME_PLAN[state]
tid_file = RUNS / hid / "run" / f"{state}-gif-task.txt"
r = subprocess.run([sys.executable, str(TOOLS / "gif_to_runtime.py"),
"--gif", str(gif), "--character", hid, "--state", state,
"--frames", str(n), "--fps", str(fps),
"--work", f"/tmp/opencode/gifwork/{hid}/{state}",
"--output-dir", str(CHARS / hid),
"--task-id", tid_file.read_text() if tid_file.exists() else "recovered"],
capture_output=True, text=True)
if r.returncode != 0:
print(f"[{hid}/{state}] PACK FAILED: {r.stdout} {r.stderr}", file=sys.stderr, flush=True)
return False
install(hid, state) # now only links + clears cache (no Godot import)
print(f"[{hid}/{state}] packed+linked", flush=True)
return True
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("heroes", nargs="+")
ap.add_argument("--workers", type=int, default=6)
args = ap.parse_args()
print(f"=== PREPARE {len(args.heroes)} heroes ===", flush=True)
jobs = prepare_jobs(args.heroes)
if not jobs:
print("nothing to do", flush=True)
godot_import_once()
return 0
print(f"=== FETCH {len(jobs)} gifs with {args.workers} workers ===", flush=True)
ok_jobs = []
with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as ex:
futures = {ex.submit(fetch_job, j): j for j in jobs}
for fut in concurrent.futures.as_completed(futures):
job, ok, err = fut.result()
if ok:
ok_jobs.append(job)
print(f" OK {job['hid']}/{job['state']}", flush=True)
else:
print(f" FAIL {job['hid']}/{job['state']}: {err[:100]}", flush=True)
print(f"=== PACK+LINK {len(ok_jobs)} gifs ===", flush=True)
packed = 0
for job in ok_jobs:
if pack_job(job):
packed += 1
godot_import_once()
failed = len(jobs) - packed
print(f"PARALLEL BATCH DONE: {packed}/{len(jobs)} gifs packed, {failed} failed", flush=True)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())