forked from rosebudai/OpenRCT2-Web
Add per-cell descriptions and Playwright sprite verification
- describe_grid.py: Uses Gemini CLI to analyze each grid image and describe individual sprite cells, producing JSON descriptions that feed into the FAL.ai prompt for much better restyling fidelity - verify_sprites.py: Builds HTML comparison page (original vs restyled at 1x and 4x zoom), screenshots via Playwright, optionally judges with Gemini CLI - reskin.py: Add "describe" step between batch and generate; auto- resolve descriptions_dir for both describe and generate steps - Tests for describe_grid (6 tests covering parsing edge cases) - Fix 4x zoom CSS overflow in verification page Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
e90704e437
commit
1fac077da8
4 files changed
+490
-4
No files matched your search
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate per-cell descriptions for batch grids using Gemini CLI.
|
||||
|
||||
Looks at each grid image and asks Gemini to describe what's in each cell.
|
||||
Writes description JSON files that generate_restyled.py uses for better prompts.
|
||||
|
||||
Usage:
|
||||
python3 describe_grid.py --manifest batches/manifest.json
|
||||
python3 describe_grid.py --manifest batches/manifest.json --skip-existing
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import argparse
|
||||
import subprocess
|
||||
import re
|
||||
|
||||
|
||||
def invoke_gemini(prompt, image_dirs):
|
||||
"""Shell out to Gemini CLI for image analysis."""
|
||||
cmd = [
|
||||
"gemini", "-p", prompt,
|
||||
"-m", "gemini-3.1-pro-preview",
|
||||
"--yolo",
|
||||
"--output-format", "text",
|
||||
]
|
||||
for d in image_dirs:
|
||||
cmd.extend(["--include-directories", d])
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True, timeout=120,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
except FileNotFoundError:
|
||||
print("ERROR: gemini CLI not found. Install: npm install -g @anthropic-ai/gemini-cli")
|
||||
return None
|
||||
except subprocess.TimeoutExpired:
|
||||
print("WARNING: Gemini timed out")
|
||||
return None
|
||||
|
||||
|
||||
def parse_descriptions(gemini_output, expected_labels):
|
||||
"""Parse Gemini's response into a {label: description} dict.
|
||||
|
||||
Looks for patterns like:
|
||||
A1: description text
|
||||
A2: description text
|
||||
"""
|
||||
descriptions = {}
|
||||
if not gemini_output:
|
||||
return descriptions
|
||||
|
||||
for label in expected_labels:
|
||||
# Match "A1:" or "**A1:**" or "- A1:" etc.
|
||||
pattern = rf'(?:^|\n)\s*(?:[-*]*\s*)?(?:\*\*)?{re.escape(label)}(?:\*\*)?[:\s]+(.+?)(?:\n|$)'
|
||||
m = re.search(pattern, gemini_output, re.IGNORECASE)
|
||||
if m:
|
||||
desc = m.group(1).strip().rstrip('.')
|
||||
# Clean up markdown formatting
|
||||
desc = re.sub(r'\*\*', '', desc)
|
||||
desc = re.sub(r'^\s*[-*]\s*', '', desc)
|
||||
if desc:
|
||||
descriptions[label] = desc
|
||||
|
||||
return descriptions
|
||||
|
||||
|
||||
def describe_batch(batch_meta, grid_dir, hint=""):
|
||||
"""Use Gemini to describe what's in each cell of a grid image."""
|
||||
grid_file = batch_meta["grid_file"]
|
||||
if not os.path.isabs(grid_file):
|
||||
grid_file = os.path.abspath(grid_file)
|
||||
|
||||
labels = [s["cell_label"] for s in batch_meta["sprites"]]
|
||||
cols = batch_meta["cols"]
|
||||
rows = batch_meta["rows"]
|
||||
|
||||
label_list = ", ".join(labels)
|
||||
hint_text = f" These are {hint}." if hint else ""
|
||||
|
||||
prompt = (
|
||||
f"This image is a {cols}x{rows} grid of game sprites on a gray background, "
|
||||
f"separated by black grid lines. The cells are labeled {label_list} "
|
||||
f"(row letter + column number, left to right, top to bottom).{hint_text}\n\n"
|
||||
f"For EACH cell, write exactly one short description (5-15 words) of what "
|
||||
f"the sprite depicts. Focus on the object's shape, material, and purpose.\n\n"
|
||||
f"Format your response EXACTLY like this, one line per cell:\n"
|
||||
)
|
||||
for label in labels:
|
||||
prompt += f"{label}: <description>\n"
|
||||
|
||||
image_dir = os.path.dirname(grid_file)
|
||||
output = invoke_gemini(prompt, [image_dir])
|
||||
|
||||
if output is None:
|
||||
return {label: hint or "game sprite" for label in labels}
|
||||
|
||||
descriptions = parse_descriptions(output, labels)
|
||||
|
||||
# Fill in any missing labels with the hint
|
||||
for label in labels:
|
||||
if label not in descriptions:
|
||||
descriptions[label] = hint or "game sprite"
|
||||
|
||||
return descriptions
|
||||
|
||||
|
||||
def describe_all(manifest_path, descriptions_dir=None, skip_existing=False):
|
||||
"""Generate descriptions for all batches in a manifest."""
|
||||
with open(manifest_path) as f:
|
||||
manifest = json.load(f)
|
||||
|
||||
batch_dir = os.path.dirname(manifest_path)
|
||||
if descriptions_dir is None:
|
||||
descriptions_dir = os.path.join(os.path.dirname(batch_dir), "descriptions")
|
||||
|
||||
os.makedirs(descriptions_dir, exist_ok=True)
|
||||
hint = manifest.get("description_hint", "")
|
||||
|
||||
for i, batch_meta in enumerate(manifest["batches"]):
|
||||
batch_id = batch_meta["batch_id"]
|
||||
desc_path = os.path.join(descriptions_dir, f"{batch_id}.json")
|
||||
|
||||
if skip_existing and os.path.exists(desc_path):
|
||||
print(f"[{i + 1}/{len(manifest['batches'])}] {batch_id}: skipping (exists)")
|
||||
continue
|
||||
|
||||
n = len(batch_meta["sprites"])
|
||||
print(f"[{i + 1}/{len(manifest['batches'])}] {batch_id}: describing {n} sprites...")
|
||||
|
||||
descriptions = describe_batch(batch_meta, batch_dir, hint)
|
||||
|
||||
with open(desc_path, "w") as f:
|
||||
json.dump(descriptions, f, indent=2)
|
||||
|
||||
for label, desc in sorted(descriptions.items()):
|
||||
print(f" {label}: {desc}")
|
||||
|
||||
print(f"\nDescriptions saved to {descriptions_dir}/")
|
||||
return descriptions_dir
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate per-cell sprite descriptions using Gemini CLI"
|
||||
)
|
||||
parser.add_argument("--manifest", required=True, help="Path to manifest.json")
|
||||
parser.add_argument("--descriptions-dir", default=None,
|
||||
help="Output directory for description JSON files")
|
||||
parser.add_argument("--skip-existing", action="store_true",
|
||||
help="Skip batches with existing descriptions")
|
||||
args = parser.parse_args()
|
||||
|
||||
describe_all(
|
||||
manifest_path=args.manifest,
|
||||
descriptions_dir=args.descriptions_dir,
|
||||
skip_existing=args.skip_existing,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Orchestrate the OpenRCT2 sprite reskin pipeline.
|
||||
|
||||
Chains: batch -> generate -> parse for a sprite directory or workspace.
|
||||
Chains: batch -> describe -> generate -> parse for a sprite directory or workspace.
|
||||
|
||||
Workspace mode (from init-reskin-object-workspace.sh):
|
||||
python3 reskin.py --workspace ./reskin-workbench/my-object --style "fantasy style"
|
||||
@@ -11,7 +11,7 @@ Standalone mode (any PNG directory):
|
||||
python3 reskin.py --sprites-dir ./sprites --style "pixel art" --through generate
|
||||
python3 reskin.py --sprites-dir ./sprites --step parse
|
||||
|
||||
Steps: batch -> generate -> parse
|
||||
Steps: batch -> describe -> generate -> parse
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -23,10 +23,11 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from categories import CATEGORIES
|
||||
from batch_sprites import batch_sprites
|
||||
from describe_grid import describe_all
|
||||
from generate_restyled import generate_all
|
||||
from parse_restyled import parse_restyled
|
||||
|
||||
STEPS = ["batch", "generate", "parse"]
|
||||
STEPS = ["batch", "describe", "generate", "parse"]
|
||||
|
||||
|
||||
def resolve_dirs(args):
|
||||
@@ -107,6 +108,21 @@ def run_step(step, sprites_dir, batch_dir, restyled_dir, output_dir, args):
|
||||
tiling=tiling if tiling is not None else False,
|
||||
)
|
||||
|
||||
elif step == "describe":
|
||||
print("\n--- Describe ---")
|
||||
if not os.path.exists(manifest_path):
|
||||
print(f"ERROR: {manifest_path} not found. Run batch step first.")
|
||||
return False
|
||||
|
||||
descriptions_dir = args.descriptions_dir or os.path.join(
|
||||
os.path.dirname(batch_dir.rstrip("/")), "descriptions"
|
||||
)
|
||||
describe_all(
|
||||
manifest_path=manifest_path,
|
||||
descriptions_dir=descriptions_dir,
|
||||
skip_existing=args.skip_existing,
|
||||
)
|
||||
|
||||
elif step == "generate":
|
||||
print("\n--- Generate ---")
|
||||
if not os.path.exists(manifest_path):
|
||||
@@ -118,7 +134,9 @@ def run_step(step, sprites_dir, batch_dir, restyled_dir, output_dir, args):
|
||||
return False
|
||||
|
||||
style = resolve_style(args)
|
||||
descriptions_dir = args.descriptions_dir
|
||||
descriptions_dir = args.descriptions_dir or os.path.join(
|
||||
os.path.dirname(batch_dir.rstrip("/")), "descriptions"
|
||||
)
|
||||
generate_all(
|
||||
manifest_path=manifest_path,
|
||||
restyled_dir=restyled_dir,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Tests for describe_grid.py."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from describe_grid import parse_descriptions
|
||||
|
||||
|
||||
def test_parse_descriptions_standard():
|
||||
output = "A1: A wooden park bench with armrests\nA2: A metal lamp post with round light"
|
||||
result = parse_descriptions(output, ["A1", "A2"])
|
||||
assert result["A1"] == "A wooden park bench with armrests"
|
||||
assert result["A2"] == "A metal lamp post with round light"
|
||||
|
||||
|
||||
def test_parse_descriptions_markdown():
|
||||
output = "**A1:** A wooden park bench\n**A2:** A lamp post"
|
||||
result = parse_descriptions(output, ["A1", "A2"])
|
||||
assert "bench" in result["A1"]
|
||||
assert "lamp" in result["A2"]
|
||||
|
||||
|
||||
def test_parse_descriptions_with_bullets():
|
||||
output = "- A1: A wooden bench\n- A2: A lamp post"
|
||||
result = parse_descriptions(output, ["A1", "A2"])
|
||||
assert "bench" in result["A1"]
|
||||
assert "lamp" in result["A2"]
|
||||
|
||||
|
||||
def test_parse_descriptions_missing_label():
|
||||
output = "A1: A bench"
|
||||
result = parse_descriptions(output, ["A1", "A2"])
|
||||
assert "A1" in result
|
||||
assert "A2" not in result
|
||||
|
||||
|
||||
def test_parse_descriptions_empty():
|
||||
result = parse_descriptions("", ["A1"])
|
||||
assert result == {}
|
||||
|
||||
|
||||
def test_parse_descriptions_none():
|
||||
result = parse_descriptions(None, ["A1"])
|
||||
assert result == {}
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify restyled sprites render correctly using Playwright.
|
||||
|
||||
Creates a comparison HTML page showing original vs restyled sprites side by side,
|
||||
serves it, takes a screenshot with Playwright, and optionally judges the result
|
||||
with Gemini CLI.
|
||||
|
||||
Usage:
|
||||
python3 verify_sprites.py --originals ./sprites_original --restyled ./sprites_restyled
|
||||
python3 verify_sprites.py --originals ./sprites_original --restyled ./sprites_restyled --judge
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import argparse
|
||||
import tempfile
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
COMPARISON_HTML = """<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sprite Reskin Verification</title>
|
||||
<style>
|
||||
body {{
|
||||
background: #1a1a2e; color: #eee; font-family: monospace;
|
||||
margin: 20px; font-size: 14px;
|
||||
}}
|
||||
h1 {{ color: #e94560; margin-bottom: 5px; }}
|
||||
.info {{ color: #888; margin-bottom: 20px; }}
|
||||
table {{ border-collapse: collapse; }}
|
||||
th {{ padding: 8px 16px; text-align: center; color: #e94560; font-size: 16px; }}
|
||||
td {{
|
||||
padding: 8px 16px; text-align: center; vertical-align: middle;
|
||||
border: 1px solid #333;
|
||||
}}
|
||||
td.sprite {{
|
||||
background: repeating-conic-gradient(#2a2a3e 0% 25%, #1a1a2e 0% 50%) 50% / 16px 16px;
|
||||
min-width: 80px; min-height: 60px;
|
||||
}}
|
||||
img {{
|
||||
image-rendering: pixelated;
|
||||
display: block; margin: 0 auto;
|
||||
}}
|
||||
.filename {{ color: #888; font-size: 11px; }}
|
||||
.zoom-4x td.sprite {{
|
||||
padding: 40px 48px;
|
||||
overflow: hidden;
|
||||
}}
|
||||
.zoom-4x img {{ transform: scale(4); }}
|
||||
#status {{
|
||||
position: fixed; bottom: 10px; right: 10px;
|
||||
background: #16213e; padding: 8px 12px; border-radius: 4px;
|
||||
border: 1px solid #e94560;
|
||||
}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Sprite Reskin Verification</h1>
|
||||
<div class="info">{sprite_count} sprites • {timestamp}</div>
|
||||
|
||||
<h2>1x (Original Size)</h2>
|
||||
<table>
|
||||
<tr><th>File</th><th>Original</th><th>Restyled</th></tr>
|
||||
{rows_1x}
|
||||
</table>
|
||||
|
||||
<h2>4x (Zoomed)</h2>
|
||||
<table class="zoom-4x">
|
||||
<tr><th>File</th><th>Original</th><th>Restyled</th></tr>
|
||||
{rows_4x}
|
||||
</table>
|
||||
|
||||
<div id="status">Rendered OK</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def build_comparison_page(originals_dir, restyled_dir, output_dir):
|
||||
"""Build an HTML comparison page with original vs restyled sprites.
|
||||
|
||||
Copies sprites into output_dir and generates index.html.
|
||||
Returns path to index.html.
|
||||
"""
|
||||
os.makedirs(os.path.join(output_dir, "orig"), exist_ok=True)
|
||||
os.makedirs(os.path.join(output_dir, "restyled"), exist_ok=True)
|
||||
|
||||
# Find matching files
|
||||
orig_files = set(f for f in os.listdir(originals_dir) if f.lower().endswith(".png"))
|
||||
rest_files = set(f for f in os.listdir(restyled_dir) if f.lower().endswith(".png"))
|
||||
common = sorted(orig_files & rest_files)
|
||||
|
||||
if not common:
|
||||
print(f"ERROR: No matching PNG files between {originals_dir} and {restyled_dir}")
|
||||
return None
|
||||
|
||||
# Copy sprites
|
||||
for f in common:
|
||||
shutil.copy2(os.path.join(originals_dir, f), os.path.join(output_dir, "orig", f))
|
||||
shutil.copy2(os.path.join(restyled_dir, f), os.path.join(output_dir, "restyled", f))
|
||||
|
||||
# Build table rows
|
||||
rows_1x = []
|
||||
rows_4x = []
|
||||
for f in common:
|
||||
rows_1x.append(
|
||||
f'<tr>'
|
||||
f'<td class="filename">{f}</td>'
|
||||
f'<td class="sprite"><img src="orig/{f}"></td>'
|
||||
f'<td class="sprite"><img src="restyled/{f}"></td>'
|
||||
f'</tr>'
|
||||
)
|
||||
rows_4x.append(
|
||||
f'<tr>'
|
||||
f'<td class="filename">{f}</td>'
|
||||
f'<td class="sprite"><img src="orig/{f}"></td>'
|
||||
f'<td class="sprite"><img src="restyled/{f}"></td>'
|
||||
f'</tr>'
|
||||
)
|
||||
|
||||
from datetime import datetime
|
||||
html = COMPARISON_HTML.format(
|
||||
sprite_count=len(common),
|
||||
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M"),
|
||||
rows_1x="\n".join(rows_1x),
|
||||
rows_4x="\n".join(rows_4x),
|
||||
)
|
||||
|
||||
html_path = os.path.join(output_dir, "index.html")
|
||||
with open(html_path, "w") as f:
|
||||
f.write(html)
|
||||
|
||||
print(f"Comparison page: {html_path} ({len(common)} sprites)")
|
||||
return html_path
|
||||
|
||||
|
||||
def screenshot_comparison(html_dir, output_path, port=0):
|
||||
"""Use Playwright to screenshot the comparison page."""
|
||||
from screenshot_game import start_server, stop_server
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError:
|
||||
print("ERROR: playwright not installed. Run: pip install playwright")
|
||||
return False
|
||||
|
||||
server, actual_port = start_server(html_dir, port=port)
|
||||
url = f"http://127.0.0.1:{actual_port}/index.html"
|
||||
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1280, "height": 2048})
|
||||
page.goto(url, wait_until="networkidle")
|
||||
|
||||
# Wait for the status indicator
|
||||
page.wait_for_selector("#status", timeout=5000)
|
||||
|
||||
# Take full-page screenshot
|
||||
page.screenshot(path=output_path, full_page=True)
|
||||
browser.close()
|
||||
|
||||
print(f"Screenshot saved: {output_path}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Playwright error: {e}")
|
||||
return False
|
||||
finally:
|
||||
stop_server(server)
|
||||
|
||||
|
||||
def judge_comparison(screenshot_path):
|
||||
"""Use Gemini to judge the comparison screenshot."""
|
||||
from judge_screenshot import invoke_gemini, parse_rating
|
||||
|
||||
prompt = (
|
||||
"This screenshot shows a sprite reskin verification page. "
|
||||
"It displays original game sprites on the left and AI-restyled versions on the right, "
|
||||
"at 1x and 4x zoom.\n\n"
|
||||
"Evaluate:\n"
|
||||
"1. Are the restyled sprites visibly different from the originals?\n"
|
||||
"2. Do the restyled sprites preserve the original silhouette/shape?\n"
|
||||
"3. Are the restyled sprites rendering correctly (no black boxes, no corruption, proper transparency)?\n"
|
||||
"4. Does the restyled style look cohesive and intentional?\n\n"
|
||||
"Rate the overall reskin quality 1-10 and explain."
|
||||
)
|
||||
|
||||
image_dir = os.path.dirname(os.path.abspath(screenshot_path))
|
||||
output = invoke_gemini(prompt, [image_dir])
|
||||
|
||||
if output:
|
||||
print(f"\n--- Gemini Judgment ---\n{output}\n")
|
||||
rating = parse_rating(output)
|
||||
if rating is not None:
|
||||
print(f"Rating: {rating}/10")
|
||||
return rating >= 5
|
||||
else:
|
||||
print("Could not parse rating from Gemini output")
|
||||
return None
|
||||
else:
|
||||
print("Gemini invocation failed")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Verify restyled sprites render correctly using Playwright"
|
||||
)
|
||||
parser.add_argument("--originals", required=True,
|
||||
help="Directory with original sprite PNGs")
|
||||
parser.add_argument("--restyled", required=True,
|
||||
help="Directory with restyled sprite PNGs")
|
||||
parser.add_argument("--output", default=None,
|
||||
help="Screenshot output path (default: /tmp/reskin-verify.png)")
|
||||
parser.add_argument("--judge", action="store_true",
|
||||
help="Also judge the screenshot with Gemini CLI")
|
||||
parser.add_argument("--port", type=int, default=0,
|
||||
help="Server port (default: random free port)")
|
||||
parser.add_argument("--keep-html", action="store_true",
|
||||
help="Keep the generated HTML comparison dir")
|
||||
args = parser.parse_args()
|
||||
|
||||
output_path = args.output or "/tmp/reskin-verify.png"
|
||||
|
||||
# Build comparison page in temp dir
|
||||
html_dir = tempfile.mkdtemp(prefix="reskin-verify-")
|
||||
try:
|
||||
html_path = build_comparison_page(args.originals, args.restyled, html_dir)
|
||||
if not html_path:
|
||||
sys.exit(1)
|
||||
|
||||
# Screenshot with Playwright
|
||||
ok = screenshot_comparison(html_dir, output_path, port=args.port)
|
||||
if not ok:
|
||||
sys.exit(1)
|
||||
|
||||
# Optional Gemini judgment
|
||||
if args.judge:
|
||||
passed = judge_comparison(output_path)
|
||||
if passed is False:
|
||||
print("FAIL: Gemini rated the reskin below threshold")
|
||||
sys.exit(1)
|
||||
elif passed is True:
|
||||
print("PASS: Gemini approved the reskin")
|
||||
finally:
|
||||
if args.keep_html:
|
||||
print(f"HTML comparison kept at: {html_dir}")
|
||||
else:
|
||||
shutil.rmtree(html_dir, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user