Files
windroost/tools/batch_hero_art.py
T
wushenghua c4b5b98577 art: batch heroes H14-H24 via real AI GIF + respect AI frame timing
Continued full-art batch. Added heroes H14, H15(idle), H16-H21, H24 via
gpt-image-2.6-gif: 4-frame idle + 6-frame attack (real AI pose changes),
chroma-keyed and packed into runtime atlases, symlinked and Godot-imported.

Key improvement: gif_to_runtime.py now reads the AI GIF's own per-frame
duration (idle 300ms -> 3fps, attack 180ms -> 6fps) and writes that fps into
the runtime manifest with provenance — playback now follows the AI's rhythm
instead of an arbitrary fixed fps. breathing_test wait window widened to 70
renders to cover the slower AI-GIF timing. All gates pass; P2_CHECKS_PASS.

Batch robustness added earlier: 10s submit throttle (avoids upstream rate
limit), POST direct / GET proxy / CDN direct, cost controls (paid re-gen at
most once, download retries free, one hero failure doesn't abort batch).

Remaining: H22/H23 (submit failed, retryable), H09-H12/H01-H06 upgrade from
procedural micro-motion to real GIF, 9 single-frame R1 enemies, B02-B20.
prototype/ untracked.
2026-11-19 03:37:59 +08:00

299 lines
13 KiB
Python

#!/usr/bin/env python3
"""Fully automated single-hero art batch: prompt -> generate -> download ->
runtime atlas. Uses curl for all network (Python urllib hits macOS proxy SSL
timeouts), always refreshes the signed URL before download (they expire).
Two AI images per hero: base portrait -> derived idle; attack pose -> derived
attack. Both packed into 384x96 runtime atlases with provenance.
Usage:
python3 tools/batch_hero_art.py H08
python3 tools/batch_hero_art.py H08 H09 H10
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
TOOLS = ROOT / "tools"
SKILL_IMG = Path.home() / ".claude/skills/image-gen/scripts/generate_image.py"
PACK = ROOT / "data" / "full_game_content.json"
RUNS = ROOT / "PRODUCTION/source/sprite_runs"
CHARS = ROOT / "PRODUCTION/source/pixel_pilot/characters"
ASSETS = ROOT / "p2_godot_sample/assets"
ENV_FILE = Path.home() / ".codex/env/ai-media-skills.env"
GODOT = "/Applications/Godot.app/Contents/MacOS/Godot"
# signature -> visual role hints (weapon / palette flavor)
SIG_HINT = {
"single": "a spear or sword, warm steel and gold accents",
"aoe": "a staff or twin blades, emerald and amber accents",
"break": "a heavy mace, deep red and bronze accents",
"click": "a bow or claws, bright cyan and silver accents",
"tempo": "a paired daggers, violet and teal accents",
"sustain": "a nature staff, green and earth accents",
}
ORIGIN_HINT = {
"精灵森林": "an elven ranger with pointed ears",
"人类王国": "a human knight",
"矮人山脉": "a stout dwarf warrior with a beard",
"兽人荒原": "an orc brute with green skin and tusks",
"龙裔": "a dragonborn with scaled skin and horns",
}
def key() -> str:
for line in ENV_FILE.read_text().splitlines():
s = line.strip()
if s.startswith("export "):
s = s[7:]
if "=" in s and not s.startswith("#"):
k, v = s.split("=", 1)
if k.strip() in ("APIMART_VIDEO_API_KEY", "APIMART_IMAGE_API_KEY"):
return v.strip().strip("'\"")
return ""
PROXY = "http://127.0.0.1:7897"
def curl(args: list[str], timeout: int = 120, via_proxy: bool = False) -> str:
# ROOT CAUSE (verified): the ZexAPI API domain (zexapi.com) requires the
# macOS system proxy (127.0.0.1:7897) — direct returns empty intermittently.
# The CDN (oss-us.file-download.life) must NOT use the proxy — it corrupts
# transfers. So callers pick per-target.
if via_proxy:
cmd = ["curl", "-x", PROXY, "-s", "--max-time", str(timeout)] + args
else:
cmd = ["curl", "--proxy", "", "--noproxy", "*", "-s", "--max-time", str(timeout)] + args
r = subprocess.run(cmd, capture_output=True, text=True)
return r.stdout
def hero_info(hid: str) -> dict:
pack = json.loads(PACK.read_text(encoding="utf-8"))
return next(h for h in pack["heroes"] if h["id"] == hid)
def visual_desc(h: dict) -> str:
origin = h.get("origin", "")
role = ORIGIN_HINT.get(origin, "an adventurer")
sig = h.get("signature", "single")
gear = SIG_HINT.get(sig, SIG_HINT["single"])
name = h.get("name", h["id"])
return f"{h['id']} {name}, {role}, {h.get('mechanic','')}, carrying {gear}; original floating-island fantasy pixel art."
def base_prompt(desc: str) -> str:
return f"""A single character portrait sprite for a 16-bit RPG, floating-island fantasy theme.
Character: {desc}
STYLE CONTRACT (critical, match a 16-bit RPG party sprite): genuine pixel art on a low-resolution logical grid, hard-edged pixel clusters, limited palette (12-18 colors), NO anti-aliasing, NO gradients, NO smooth shading, crisp nearest-neighbour pixels. Readable face with a few pixels for eyes/mouth, layered armor with light and shadow tones, a defined dark outline. One light source from above, 2-3 shades per material. Centered full body, feet near bottom, generous magenta padding.
Perfectly flat pure magenta #FF00FF chroma-key background; never use magenta on the character. No text, labels, borders, grid, checkerboard, white/black background. No detached effects, glow, ground shadow, or scenery.
Output only the single character sprite on magenta."""
def attack_prompt(desc: str) -> str:
return f"""Create a single character sprite for a 16-bit RPG in an ATTACK action pose.
Character: {desc}
Reference Image 1 is the ACCEPTED design for this character: copy identity EXACTLY (silhouette, palette, face, outfit, gear, outline weight). Do NOT redesign or restyle.
Action: a clear weapon attack pose appropriate to the character's gear — dynamic, readable attack intent, feet planted, full-body sprite, effect/weapon stays attached (no detached arrows, arcs or glow).
STYLE: genuine pixel art, low-resolution logical grid, hard-edged pixels, limited palette (12-18 colors), NO anti-aliasing, NO gradients, match the reference fidelity exactly.
Perfectly flat pure magenta #FF00FF chroma-key background; no text, borders, grid, white/black background, no detached effects or scenery.
Output only the single character sprite on magenta."""
def submit_job(name: str, prompt: str, out_dir: Path, ref: Path | None = None) -> str:
out_dir.mkdir(parents=True, exist_ok=True)
job = [{"name": name, "prompt": prompt, "model": "gpt-image-2.5", "size": "1024x1024"}]
jf = out_dir / f"{name}-job.json"
jf.write_text(json.dumps(job, ensure_ascii=False, indent=2), encoding="utf-8")
cmd = [sys.executable, str(SKILL_IMG), "--prompts-file", str(jf),
"--out-dir", str(out_dir / "raw"), "--manifest", str(out_dir / "raw/tasks.json"), "--no-wait"]
if ref:
cmd += ["--image", str(ref)]
# generate_image.py uses urllib which reads proxy env vars; the API needs
# the system proxy. Retry on transient SSL handshake timeouts.
env = dict(os.environ)
env["HTTPS_PROXY"] = PROXY
env["https_proxy"] = PROXY
env["HTTP_PROXY"] = PROXY
env["http_proxy"] = PROXY
last = ""
for attempt in range(5):
r = subprocess.run(cmd, capture_output=True, text=True, timeout=180, env=env)
if r.returncode == 0:
try:
tasks = json.loads((out_dir / "raw/tasks.json").read_text(encoding="utf-8"))
t = tasks[0] if isinstance(tasks, list) else tasks
tid = t.get("task_id", "")
if tid:
print(f" submitted {name}: {tid}", flush=True)
return tid
except Exception as e:
last = str(e)
else:
last = (r.stdout + r.stderr)[-300:]
print(f" submit {name} attempt {attempt+1} failed, retrying: {last[:120]}", flush=True)
time.sleep(10)
raise RuntimeError(f"submit failed after 5 tries: {last}")
def fresh_url(tid: str) -> str:
"""GET the task and extract a FRESH url (signed URLs expire). Retry on empty."""
for _ in range(12):
out = curl(["-H", f"Authorization: Bearer {key()}", f"https://zexapi.com/v1/videos/{tid}"], timeout=90, via_proxy=True)
try:
d = json.loads(out)
except Exception:
time.sleep(8)
continue
if d.get("error"):
raise RuntimeError(f"task error: {d['error']}")
url = d.get("url") or d.get("image_url") or d.get("download_url", "")
st = d.get("status", "")
if st == "failed":
raise RuntimeError(f"task failed: {d.get('error')}")
if url and st in ("completed", "succeeded", "success"):
return url
time.sleep(12)
raise RuntimeError(f"no url for {tid}")
def gen_and_download(name: str, prompt: str, out: Path, ref: Path | None) -> Path:
tid = submit_job(name, prompt, out, ref)
src = out / f"{name}.png"
# download with periodic URL refresh
from PIL import Image
for i in range(12):
cur = fresh_url(tid) # always fresh
tmp = Path("/tmp/opencode/batch_try.png")
if tmp.exists():
tmp.unlink()
curl(["--compressed", "-L", "-o", str(tmp), cur], timeout=300)
if tmp.exists() and tmp.stat().st_size > 100000:
try:
im = Image.open(tmp); im.load()
assert im.width >= 600 and im.height >= 600
im.convert("RGB").save(src, "PNG")
print(f" got {name}.png ({src.stat().st_size}B) task {tid} attempt {i+1}", flush=True)
(out / "task_id.txt").write_text(tid)
return src
except Exception:
pass
raise RuntimeError(f"failed to download {name} for task {tid}")
def process(hid: str, kind: str, src: Path, run_dir: Path, task_id: str) -> None:
from PIL import Image
work = Path("/tmp/opencode/batch_work") / hid / kind
work.mkdir(parents=True, exist_ok=True)
# chroma key single image
keyed = work / "keyed.png"
subprocess.run([sys.executable, str(Path.home()/".claude/skills/image-gen/scripts/slice_grid.py"),
str(src), "--rows", "1", "--cols", "1", "--names", "x",
"--output-dir", str(work), "--chroma-key", "FF00FF", "--tolerance", "70"],
capture_output=True, text=True, check=True)
# slice_grid writes x.png
x = work / "x.png"
derive = TOOLS / ("derive_idle_frames.py" if kind == "idle" else "derive_action_frames.py")
frames = work / "frames"
cmd = [sys.executable, str(derive), "--input", str(x), "--output-dir", str(frames), "--frames", "4"]
if kind != "idle":
cmd += ["--kind", kind]
subprocess.run(cmd, capture_output=True, text=True, check=True)
outdir = CHARS / hid
cmd = [sys.executable, str(TOOLS / "pack_animation_strip.py"),
"--character", hid, "--state", kind, "--frames", str(frames),
"--output-dir", str(outdir), "--canvas", "96", "--fit", "0.86",
"--fps", "8", "--resample", "nearest"] + (["--loop"] if kind == "idle" else [])
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError(f"pack failed: {r.stdout} {r.stderr}")
mf = outdir / f"{hid}_{kind}_anim.manifest.json"
d = json.loads(mf.read_text(encoding="utf-8"))
d["provenance"] = {"generator": "image-gen gpt-image-2.5", "task_id": task_id,
"source": str(src), "pipeline": "slice_grid(--chroma-key) -> derive -> pack_animation_strip"}
mf.write_text(json.dumps(d, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f" packed {hid}/{kind}", flush=True)
def install_and_import(hid: str, kind: str) -> None:
link = ASSETS / f"{hid}_{kind}_anim.png"
mlink = ASSETS / f"{hid}_{kind}_anim.manifest.json"
src = CHARS / hid / f"{hid}_{kind}_anim.png"
ms = CHARS / hid / f"{hid}_{kind}_anim.manifest.json"
if link.is_symlink() or link.exists():
link.unlink()
if mlink.is_symlink() or mlink.exists():
mlink.unlink()
rel = os.path.relpath(src, ASSETS)
mrel = os.path.relpath(ms, ASSETS)
link.symlink_to(rel)
mlink.symlink_to(mrel)
# clear stale import cache
for p in ASSETS.glob(f"{hid}_{kind}_anim.png.import"):
p.unlink()
for p in (ROOT / "p2_godot_sample/.godot/imported").glob(f"{hid}_{kind}_anim.png-*"):
p.unlink()
subprocess.run([GODOT, "--headless", "--path", str(ROOT / "p2_godot_sample"),
"--editor", "--quit"], capture_output=True, text=True, timeout=180)
print(f" installed {hid}/{kind}", flush=True)
def one_hero(hid: str) -> None:
h = hero_info(hid)
desc = visual_desc(h)
run = RUNS / hid / "run"
run.mkdir(parents=True, exist_ok=True)
print(f"[{hid}] {desc}", flush=True)
# base -> idle (resume: reuse an already-downloaded base if present)
base_out = run / "base-source.png"
if base_out.exists():
base_src = base_out
tid = (run / "base-task-id.txt").read_text() if (run / "base-task-id.txt").exists() else "recovered"
print(f" base reused (recovered) -> idle", flush=True)
else:
base_src = gen_and_download("base", base_prompt(desc), run, None)
(run / "base-task-id.txt").write_text((run / "task_id.txt").read_text())
base_out.write_bytes(base_src.read_bytes())
tid = (run / "base-task-id.txt").read_text()
process(hid, "idle", base_src, run, tid)
install_and_import(hid, "idle")
# attack pose -> attack (identity locked to base)
atk_out = run / "attack-source.png"
if atk_out.exists():
atk_src = atk_out
atid = (run / "attack-task-id.txt").read_text() if (run / "attack-task-id.txt").exists() else "recovered"
print(f" attack reused (recovered) -> attack", flush=True)
else:
atk_src = gen_and_download("attack", attack_prompt(desc), run, base_out)
(run / "attack-task-id.txt").write_text((run / "task_id.txt").read_text())
atk_out.write_bytes(atk_src.read_bytes())
atid = (run / "attack-task-id.txt").read_text()
process(hid, "attack", atk_src, run, atid)
install_and_import(hid, "attack")
print(f"[{hid}] DONE", flush=True)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("heroes", nargs="+")
args = ap.parse_args()
for hid in args.heroes:
try:
one_hero(hid)
except Exception as e:
print(f"[{hid}] FAILED: {e}", file=sys.stderr, flush=True)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())