forked from rosebudai/OpenRCT2-Web
ralph: story-7 Gemini visual judge script
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b7ae76261
commit
34b6440e0e
4 files changed
+343
-1
No files matched your search
@@ -57,7 +57,7 @@
|
||||
"title": "Gemini visual judge script",
|
||||
"description": "Create scripts/reskin/judge_screenshot.py — invokes Gemini CLI to visually judge a game screenshot.\n\nCLI: python3 judge_screenshot.py <screenshot.png> [--reference <ref.png>] [--criteria 'text']\n\nBehavior:\n1. Takes a screenshot path (required) and optional reference image path\n2. Builds a prompt asking Gemini to evaluate the screenshot:\n - If reference provided: 'Compare these two screenshots. The first is the original, the second is reskinned. Evaluate: (1) Did the reskin change the visual style? (2) Are game elements still recognizable? (3) Is the overall quality acceptable? Rate 1-10 and explain.'\n - If no reference: 'Evaluate this game screenshot. Is it rendering correctly? Are there visual artifacts, black screens, or missing textures? Rate quality 1-10 and explain.'\n - If --criteria provided, append it to the prompt\n3. Invokes: gemini -p \"<prompt>\" -m gemini-3.1-pro-preview --include-directories <dir-containing-images> --yolo --output-format text 2>/dev/null\n4. Prints the Gemini response\n5. Parses the rating (look for 'X/10' pattern) and exits 0 if >= 5, exit 1 if < 5 or unparseable\n\nTest: Create scripts/reskin/test_judge_screenshot.py with tests:\n- test_build_prompt_single_image: verify prompt construction without reference\n- test_build_prompt_with_reference: verify prompt includes comparison language\n- test_build_prompt_with_criteria: verify custom criteria is appended\n- test_parse_rating_valid: verify '7/10' parses to 7\n- test_parse_rating_missing: verify None returned when no rating found\n\nKeep the Gemini invocation in a separate function so tests don't need the CLI.",
|
||||
"verify": "cd /workspace/OpenRCT2-Web && python3 -m pytest scripts/reskin/test_judge_screenshot.py -v",
|
||||
"status": "pending",
|
||||
"status": "passed",
|
||||
"retries": 0
|
||||
},
|
||||
{
|
||||
|
||||
@@ -71,3 +71,17 @@ Note: had to pip install playwright (browsers were pre-installed at /root/.cache
|
||||
Verification passed: pytest scripts/reskin/test_screenshot_game.py -v (2/2 passed).
|
||||
Status: PASSED
|
||||
Status: PASSED
|
||||
|
||||
--- Iteration 7 | story-7 | 2026-02-25 00:19:36 ---
|
||||
Created scripts/reskin/judge_screenshot.py — Gemini CLI visual judge for game screenshots.
|
||||
Features: build_prompt() for single/comparison modes with optional criteria,
|
||||
parse_rating() extracts X/10 pattern, invoke_gemini() calls CLI with --include-directories,
|
||||
judge() orchestrates prompt+invoke+parse, CLI with positional screenshot arg + --reference + --criteria.
|
||||
Exits 0 if rating >= 5, exit 1 if < 5 or unparseable.
|
||||
Created scripts/reskin/test_judge_screenshot.py with 8 tests:
|
||||
- test_build_prompt_single_image, test_build_prompt_with_reference,
|
||||
test_build_prompt_with_criteria, test_build_prompt_with_reference_and_criteria,
|
||||
test_parse_rating_valid, test_parse_rating_missing,
|
||||
test_parse_rating_ignores_out_of_range, test_parse_rating_picks_first_match
|
||||
Verification passed: pytest scripts/reskin/test_judge_screenshot.py -v (8/8 passed).
|
||||
Status: PASSED
|
||||
@@ -0,0 +1,242 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Invoke Gemini CLI to visually judge a game screenshot.
|
||||
|
||||
Evaluates a screenshot (optionally against a reference image) using
|
||||
Gemini's vision capabilities and returns a quality rating.
|
||||
|
||||
Usage::
|
||||
|
||||
python3 judge_screenshot.py screenshot.png
|
||||
python3 judge_screenshot.py reskinned.png --reference original.png
|
||||
python3 judge_screenshot.py shot.png --criteria 'Check if trees look natural'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt construction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
PROMPT_SINGLE = (
|
||||
"Evaluate this game screenshot. Is it rendering correctly? "
|
||||
"Are there visual artifacts, black screens, or missing textures? "
|
||||
"Rate quality 1-10 and explain."
|
||||
)
|
||||
|
||||
PROMPT_COMPARISON = (
|
||||
"Compare these two screenshots. The first is the original, the second "
|
||||
"is reskinned. Evaluate: (1) Did the reskin change the visual style? "
|
||||
"(2) Are game elements still recognizable? (3) Is the overall quality "
|
||||
"acceptable? Rate 1-10 and explain."
|
||||
)
|
||||
|
||||
|
||||
def build_prompt(
|
||||
screenshot: str,
|
||||
reference: Optional[str] = None,
|
||||
criteria: Optional[str] = None,
|
||||
) -> str:
|
||||
"""Build the evaluation prompt for Gemini.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
screenshot:
|
||||
Path to the screenshot image (used for context, not embedded).
|
||||
reference:
|
||||
Optional path to a reference image for comparison.
|
||||
criteria:
|
||||
Optional additional evaluation criteria to append.
|
||||
|
||||
Returns
|
||||
-------
|
||||
The assembled prompt string.
|
||||
"""
|
||||
if reference:
|
||||
prompt = PROMPT_COMPARISON
|
||||
else:
|
||||
prompt = PROMPT_SINGLE
|
||||
|
||||
if criteria:
|
||||
prompt = prompt + " " + criteria
|
||||
|
||||
return prompt
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rating parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def parse_rating(text: str) -> Optional[int]:
|
||||
"""Extract an X/10 rating from Gemini's response.
|
||||
|
||||
Looks for patterns like ``7/10``, ``8 / 10``, ``Rating: 9/10``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
The integer rating, or ``None`` if no rating was found.
|
||||
"""
|
||||
match = re.search(r"\b(\d{1,2})\s*/\s*10\b", text)
|
||||
if match:
|
||||
value = int(match.group(1))
|
||||
if 1 <= value <= 10:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gemini invocation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def invoke_gemini(
|
||||
prompt: str,
|
||||
image_dirs: list[str],
|
||||
) -> str:
|
||||
"""Call the Gemini CLI and return its text output.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
prompt:
|
||||
The evaluation prompt.
|
||||
image_dirs:
|
||||
Directories to pass via ``--include-directories`` so Gemini can
|
||||
see the images.
|
||||
|
||||
Returns
|
||||
-------
|
||||
Gemini's response text, or an error string on failure.
|
||||
"""
|
||||
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,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
return result.stdout.strip() or result.stderr.strip()
|
||||
except FileNotFoundError:
|
||||
return "Error: gemini CLI not found on PATH"
|
||||
except subprocess.TimeoutExpired:
|
||||
return "Error: gemini CLI timed out after 120s"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main logic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def judge(
|
||||
screenshot: str,
|
||||
reference: Optional[str] = None,
|
||||
criteria: Optional[str] = None,
|
||||
) -> tuple[str, Optional[int]]:
|
||||
"""Judge a screenshot and return (response_text, rating).
|
||||
|
||||
Parameters
|
||||
----------
|
||||
screenshot:
|
||||
Path to the screenshot PNG.
|
||||
reference:
|
||||
Optional path to a reference PNG for comparison.
|
||||
criteria:
|
||||
Optional additional evaluation criteria.
|
||||
|
||||
Returns
|
||||
-------
|
||||
(response, rating) where rating is an int 1-10 or None.
|
||||
"""
|
||||
prompt = build_prompt(screenshot, reference=reference, criteria=criteria)
|
||||
|
||||
# Collect unique directories containing the images so Gemini can access them.
|
||||
image_dirs: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for path in [screenshot, reference]:
|
||||
if path is not None:
|
||||
d = str(Path(path).resolve().parent)
|
||||
if d not in seen:
|
||||
image_dirs.append(d)
|
||||
seen.add(d)
|
||||
|
||||
response = invoke_gemini(prompt, image_dirs)
|
||||
rating = parse_rating(response)
|
||||
return response, rating
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Use Gemini to visually judge a game screenshot.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"screenshot",
|
||||
help="Path to the screenshot PNG to evaluate.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--reference",
|
||||
default=None,
|
||||
help="Optional reference screenshot for comparison.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--criteria",
|
||||
default=None,
|
||||
help="Additional evaluation criteria to append to the prompt.",
|
||||
)
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
args = parse_args(argv)
|
||||
|
||||
# Validate paths.
|
||||
if not os.path.isfile(args.screenshot):
|
||||
print(f"Error: screenshot not found: {args.screenshot}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if args.reference and not os.path.isfile(args.reference):
|
||||
print(f"Error: reference not found: {args.reference}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
response, rating = judge(
|
||||
args.screenshot,
|
||||
reference=args.reference,
|
||||
criteria=args.criteria,
|
||||
)
|
||||
|
||||
print(response)
|
||||
|
||||
if rating is not None:
|
||||
print(f"\nRating: {rating}/10")
|
||||
sys.exit(0 if rating >= 5 else 1)
|
||||
else:
|
||||
print("\nWarning: could not parse a rating from the response", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Tests for judge_screenshot.py — prompt construction and rating parsing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Ensure the reskin package is importable.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from judge_screenshot import ( # noqa: E402
|
||||
PROMPT_COMPARISON,
|
||||
PROMPT_SINGLE,
|
||||
build_prompt,
|
||||
parse_rating,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# build_prompt tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_build_prompt_single_image():
|
||||
"""Prompt for a single screenshot uses the single-image template."""
|
||||
prompt = build_prompt("shot.png")
|
||||
assert prompt == PROMPT_SINGLE
|
||||
assert "rendering correctly" in prompt
|
||||
assert "Rate quality" in prompt
|
||||
|
||||
|
||||
def test_build_prompt_with_reference():
|
||||
"""Prompt with a reference image uses comparison language."""
|
||||
prompt = build_prompt("reskinned.png", reference="original.png")
|
||||
assert prompt == PROMPT_COMPARISON
|
||||
assert "Compare these two screenshots" in prompt
|
||||
assert "reskin" in prompt.lower()
|
||||
|
||||
|
||||
def test_build_prompt_with_criteria():
|
||||
"""Custom criteria is appended to the prompt."""
|
||||
extra = "Check if trees look natural"
|
||||
prompt = build_prompt("shot.png", criteria=extra)
|
||||
assert prompt.startswith(PROMPT_SINGLE)
|
||||
assert prompt.endswith(extra)
|
||||
assert extra in prompt
|
||||
|
||||
|
||||
def test_build_prompt_with_reference_and_criteria():
|
||||
"""Comparison prompt with extra criteria appends correctly."""
|
||||
extra = "Focus on building rooftops"
|
||||
prompt = build_prompt("shot.png", reference="ref.png", criteria=extra)
|
||||
assert "Compare these two screenshots" in prompt
|
||||
assert extra in prompt
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# parse_rating tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_rating_valid():
|
||||
"""Standard X/10 pattern is extracted."""
|
||||
assert parse_rating("Overall I'd rate this 7/10.") == 7
|
||||
assert parse_rating("Rating: 9/10") == 9
|
||||
assert parse_rating("I give it a 10 / 10!") == 10
|
||||
assert parse_rating("Quality: 1/10 — very bad") == 1
|
||||
|
||||
|
||||
def test_parse_rating_missing():
|
||||
"""Returns None when no rating pattern is found."""
|
||||
assert parse_rating("Looks fine overall, nice colors.") is None
|
||||
assert parse_rating("") is None
|
||||
assert parse_rating("Score: excellent") is None
|
||||
|
||||
|
||||
def test_parse_rating_ignores_out_of_range():
|
||||
"""Ratings outside 1-10 are ignored."""
|
||||
# 0/10 is out of our 1-10 range
|
||||
assert parse_rating("0/10 terrible") is None
|
||||
|
||||
|
||||
def test_parse_rating_picks_first_match():
|
||||
"""When multiple ratings appear, the first is returned."""
|
||||
text = "Visual quality: 6/10. Technical quality: 8/10."
|
||||
assert parse_rating(text) == 6
|
||||
Reference in new issue
Block a user