Coverage for src/romfarmer/ai/rescue_generator_cli.py: 0%
111 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1#!/usr/bin/env python3
2"""Generate AI-powered rescue lists for 1G1Gen cross-platform deduplication.
4This tool queries the Copilot SDK (Claude Haiku) to identify games where a
5non-primary platform has the definitively superior version, overriding
6the deterministic priority system.
8Usage:
9 # Generate rescue lists for gen6 (PS2 > GC > Xbox > DC)
10 python -m romfarmer.ai.rescue_generator_cli gen6
12 # Generate for gen5 (PSX > Saturn)
13 python -m romfarmer.ai.rescue_generator_cli gen5
15 # Force regenerate (ignore cache)
16 python -m romfarmer.ai.rescue_generator_cli gen6 --force
18 # Dry run — show duplicates without calling AI
19 python -m romfarmer.ai.rescue_generator_cli gen6 --dry-run
21 # Use specific build output to find real duplicates
22 python -m romfarmer.ai.rescue_generator_cli gen6 --output-dir output/redump-1g1r-eng-chd-batocera-v2
23"""
25from __future__ import annotations
27import argparse
28import asyncio
29import logging
30import sys
31from pathlib import Path
33# Ensure rom-farmer src is importable
34sys.path.insert(0, str(Path(__file__).parent.parent.parent))
36from romfarmer.ai.generation import CONSOLE_GENERATIONS, get_generation
37from romfarmer.ai.rescue_generator import (
38 generate_rescue_lists,
39)
40from romfarmer.cross_platform.game_normalizer import GameNameNormalizer
42logger = logging.getLogger(__name__)
45def _get_workspace_root() -> Path:
46 from romfarmer.core.paths import paths
48 return paths.workspace_root
51WORKSPACE_ROOT: Path # resolved lazily via _get_workspace_root()
54def find_cross_platform_duplicates(
55 generation_name: str,
56 output_dir: Path | None = None,
57) -> tuple[list[str], list[dict[str, list[str]]]]:
58 """Scan build output to find actual cross-platform duplicate games.
60 Args:
61 generation_name: e.g. "gen6"
62 output_dir: Build output directory containing platform subdirs.
63 If None, scans all output/ dirs for matching platforms.
65 Returns:
66 Tuple of (platform_priority, duplicate_games).
67 duplicate_games is list of {"name": str, "platforms": [str, ...]}.
68 """
69 gen = get_generation(generation_name)
70 if not gen:
71 print(f"ERROR: Unknown generation: {generation_name}")
72 print(f"Available: {', '.join(g.name for g in CONSOLE_GENERATIONS)}")
73 sys.exit(1)
75 platforms = gen.platforms
76 normalizer = GameNameNormalizer()
78 # Find platform directories in build output
79 if output_dir:
80 search_dirs = [output_dir]
81 else:
82 # Scan all output directories
83 output_base = _get_workspace_root() / "output"
84 search_dirs = (
85 [d for d in output_base.iterdir() if d.is_dir()] if output_base.exists() else []
86 )
88 # Collect normalized game names per platform
89 from collections import defaultdict
91 platform_games: dict[str, dict[str, str]] = {} # platform -> {match_key: original_name}
93 for search_dir in search_dirs:
94 for platform in platforms:
95 platform_dir = search_dir / platform
96 if not platform_dir.exists():
97 continue
99 if platform not in platform_games:
100 platform_games[platform] = {}
102 # Find game files
103 for pattern in [
104 "*.chd",
105 "*.rvz",
106 "*.iso",
107 "*.xiso",
108 "*.cue",
109 "*.7z",
110 "*.zip",
111 "*.m3u",
112 "*.cso",
113 "*.pbp",
114 ]:
115 for f in platform_dir.glob(pattern):
116 norm = normalizer.normalize(f.stem, platform, str(f))
117 key = norm.match_key()
118 if key not in platform_games[platform]:
119 platform_games[platform][key] = f.stem
121 if not platform_games:
122 print(f"No platform directories found for {generation_name} in output/")
123 print(f"Looking for: {', '.join(platforms)}")
124 return platforms, []
126 print("\nPlatforms found:")
127 for p in platforms:
128 count = len(platform_games.get(p, {}))
129 marker = " (primary)" if p == platforms[0] else ""
130 print(f" {p:15s}: {count:5d} games{marker}")
132 # Find games on 2+ platforms
133 all_keys: dict[str, dict[str, str]] = defaultdict(dict) # match_key -> {platform: name}
134 for platform, games in platform_games.items():
135 for key, name in games.items():
136 all_keys[key][platform] = name
138 duplicates = []
139 for _key, plats in sorted(all_keys.items()):
140 if len(plats) >= 2:
141 # Use the name from the primary platform if available
142 primary_name = None
143 for p in platforms:
144 if p in plats:
145 primary_name = plats[p]
146 break
147 duplicates.append(
148 {
149 "name": primary_name or list(plats.values())[0],
150 "platforms": list(plats.keys()),
151 }
152 )
154 print(f"\nCross-platform duplicates: {len(duplicates)}")
156 return platforms, duplicates
159async def run_generate(args: argparse.Namespace) -> None:
160 """Run the rescue list generation."""
161 platforms, duplicates = find_cross_platform_duplicates(
162 args.generation,
163 Path(args.output_dir) if args.output_dir else None,
164 )
166 if not duplicates:
167 print("No duplicates found. Nothing to do.")
168 return
170 if args.dry_run:
171 print(f"\n[DRY RUN] Would evaluate {len(duplicates)} games")
172 print(f"Primary platform: {platforms[0]}")
173 print("\nSample duplicates:")
174 for d in duplicates[:20]:
175 print(f" {d['name']:50s} — {', '.join(d['platforms'])}")
176 if len(duplicates) > 20:
177 print(f" ... and {len(duplicates) - 20} more")
178 return
180 from romfarmer.core.paths import get_paths
182 cache_dir = get_paths().workspace_root / "config" / "curations" / "rescue"
184 rescue_lists = await generate_rescue_lists(
185 generation_name=args.generation,
186 platform_priority=platforms,
187 duplicate_games=duplicates,
188 model=args.model,
189 cache_dir=cache_dir,
190 force_regenerate=args.force,
191 )
193 # Summary
194 total_rescued = sum(len(v) for v in rescue_lists.values())
195 print(f"\n{'=' * 60}")
196 print(f"RESCUE LIST SUMMARY: {args.generation}")
197 print(f"{'=' * 60}")
198 print(f"Total cross-platform duplicates: {len(duplicates)}")
199 print(f"Total rescued (kept on non-primary): {total_rescued}")
200 print(f"Rescue rate: {total_rescued / max(len(duplicates), 1) * 100:.1f}%")
201 print()
202 for platform, games in sorted(rescue_lists.items()):
203 print(f" {platform} ({len(games)} rescued):")
204 for g in sorted(games)[:10]:
205 print(f" - {g}")
206 if len(games) > 10:
207 print(f" ... and {len(games) - 10} more")
208 print(f"\nSaved to: {cache_dir / f'rescue-{args.generation}.yaml'}")
211def main():
212 parser = argparse.ArgumentParser(
213 description="Generate AI-powered rescue lists for 1G1Gen deduplication"
214 )
215 parser.add_argument(
216 "generation",
217 help="Generation name (gen4cd, gen5, gen6, gen7)",
218 )
219 parser.add_argument(
220 "--output-dir",
221 help="Build output directory with platform subdirs (default: scan all output/)",
222 )
223 parser.add_argument(
224 "--model",
225 default="claude-haiku-4.5",
226 help="Copilot model to use (default: claude-haiku-4.5)",
227 )
228 parser.add_argument(
229 "--force",
230 action="store_true",
231 help="Force regeneration (ignore cache)",
232 )
233 parser.add_argument(
234 "--dry-run",
235 action="store_true",
236 help="Show duplicates without calling AI",
237 )
238 parser.add_argument(
239 "--verbose",
240 "-v",
241 action="store_true",
242 help="Verbose logging",
243 )
245 args = parser.parse_args()
247 logging.basicConfig(
248 level=logging.DEBUG if args.verbose else logging.INFO,
249 format="%(levelname)s: %(message)s",
250 )
252 asyncio.run(run_generate(args))
255if __name__ == "__main__":
256 main()