#!/usr/bin/env python3 """Process generated magenta-backed sprites into runtime animation atlases. Pipeline (per source image): pixel_sprite_pack.py -> magenta fixed-grid 96x96 atlas + manifest chroma_key_atlas.py -> transparent, foot-aligned PNG + manifest emit UnitView manifest -> the shape UnitView.configure() consumes Runs on already-downloaded raw files; no network calls. Each successful cell is recorded with its source task id and hashes for traceability. Failed cells are reported and never silently skipped into a broken runtime asset. """ from __future__ import annotations import hashlib import json import subprocess import sys from pathlib import Path from typing import Dict, List ROOT = Path(__file__).resolve().parent.parent RAW = Path("/tmp/opencode/art-batch/raw") WORK = Path("/tmp/opencode/art-batch/processed") DEST = ROOT / "PRODUCTION/source/pixel_pilot/characters" TOOLS = ROOT / "tools" # id -> states to produce (single frame per state is fine for the slice) STATES: Dict[str, List[str]] = {} for name in ["H02", "H03", "H04", "H05", "H06"]: STATES[name] = ["idle", "attack"] for name in ["E-R1-F2-V1", "E-R1-F4-V1", "E-R1-F5-V1", "E-R1-F6-V1", "E-R1-F7-V1", "E-R1-F8-V1", "E-R1-F9-V1", "E-R1-F10-V1"]: STATES[name] = ["idle", "hit"] TASK_IDS: Dict[str, str] = {} for manifest in [Path("/tmp/opencode/art-batch/tasks.json"), Path("/tmp/opencode/art-batch/h05_tasks.json")]: if not manifest.exists(): continue for task in json.loads(manifest.read_text(encoding="utf-8")): if isinstance(task, dict) and task.get("name") and task.get("task_id"): TASK_IDS[task["name"]] = task["task_id"] def run(cmd: List[str]) -> None: result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(f"{' '.join(cmd)}\n{result.stdout}\n{result.stderr}") def emit_unit_manifest(char_id: str, state: str, png: Path) -> None: h = hashlib.sha256(png.read_bytes()).hexdigest() manifest = { "schema": 1, "status": "generated_reviewed_pipeline", "character_id": char_id, "state": state, "frame_count": 1, "fps": 8 if state == "idle" else 12, "loop": state == "idle", "cell_size": [96, 96], "atlas_size": [96, 96], "foot_y": 84, "resample": "nearest", "low_power_frame_step": 1, "frames": [{"name": "frame-0", "atlas_rect": [0, 0, 96, 96]}], "atlas_sha256": h, "source_task_id": TASK_IDS.get(f"{char_id}_{state}", ""), "pipeline": ["pixel_sprite_pack.py", "chroma_key_atlas.py"], "note": "AI-generated pixel-art first draft, processed through chroma key and foot-line alignment. Needs human visual sign-off before release.", } out = DEST / char_id / f"{char_id}_{state}_anim.manifest.json" out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") def main() -> int: WORK.mkdir(parents=True, exist_ok=True) ledger: List[Dict] = [] failures: List[str] = [] for char_id, states in STATES.items(): for state in states: raw = RAW / f"{char_id}_{state}.png" if not raw.exists(): failures.append(f"missing raw {char_id}_{state}") continue try: base = WORK / f"{char_id}_{state}" # Step 1: fixed grid 96 cell with magenta background run([ sys.executable, str(TOOLS / "pixel_sprite_pack.py"), "--inputs", str(raw), "--names", "frame-0", "--output", str(base) + "_grid.png", "--cols", "1", "--cell-size", "96x96", "--fit", "0.86", "--resample", "nearest", ]) # Step 2: chroma key to transparency, foot line at 84 keyed = WORK / f"{char_id}_{state}_keyed" run([ sys.executable, str(TOOLS / "chroma_key_atlas.py"), "--input", str(base) + "_grid.png", "--output", str(keyed), "--rows", "1", "--cols", "1", "--names", "frame-0", "--canvas", "96", "--logical", "96", "--display", "96", "--foot-y", "84", "--resample", "nearest", "--key", "255,0,255", "--hard", "65", "--soft", "145", ]) cell = keyed / "frame-0.png" if not cell.exists(): raise RuntimeError(f"no keyed output for {char_id}_{state}") final = DEST / char_id / f"{char_id}_{state}_anim.png" final.parent.mkdir(parents=True, exist_ok=True) final.write_bytes(cell.read_bytes()) emit_unit_manifest(char_id, state, final) ledger.append({ "id": f"{char_id}_{state}", "task_id": TASK_IDS.get(f"{char_id}_{state}", ""), "raw_sha256": hashlib.sha256(raw.read_bytes()).hexdigest(), "runtime_sha256": hashlib.sha256(final.read_bytes()).hexdigest(), "status": "ok", }) print(f"processed {char_id}/{state}") except Exception as exc: # noqa: BLE001 - report and continue the batch failures.append(f"{char_id}_{state}: {exc}") print(f"FAIL {char_id}/{state}: {exc}") report = { "schema": 1, "kind": "generated_art_processing_ledger", "provider": "zexapi / gpt-image-2.6 / 1K", "processed": ledger, "failures": failures, "overall": "PASS" if not failures else "FAIL", } out = ROOT / "data/generated_art_processing_ledger.json" out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(f"\nprocessed {len(ledger)} cells, {len(failures)} failures -> {out}") return 0 if not failures else 1 if __name__ == "__main__": raise SystemExit(main())