Coverage for src/romfarmer/cli/generation.py: 0%

270 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1"""Generation-level cross-platform deduplication commands. 

2 

3Provides analysis and rescue list generation for 1G1Gen filtering. 

4""" 

5 

6import asyncio 

7import json 

8import sqlite3 

9from collections import defaultdict 

10from pathlib import Path 

11 

12import click 

13import yaml 

14from rich.console import Console 

15from rich.panel import Panel 

16from rich.table import Table 

17 

18from romfarmer.cross_platform.game_normalizer import GameNameNormalizer 

19 

20console = Console() 

21 

22 

23# These are resolved lazily at call-time via the paths system to support any workspace layout. 

24# They can be overridden via CLI flags or environment variables. 

25def _default_output_base() -> Path: 

26 from romfarmer.core.paths import paths 

27 

28 return paths.output_dir.parent / "roms-retrobat" 

29 

30 

31def _default_generations_yaml() -> Path: 

32 from romfarmer.core.paths import paths 

33 

34 return paths.workspace_root / "config" / "generations.yaml" 

35 

36 

37def _default_rescue_dir() -> Path: 

38 from romfarmer.core.paths import paths 

39 

40 return paths.workspace_root / "config" / "curations" / "rescue" 

41 

42 

43def _default_metadata_db() -> Path: 

44 from romfarmer.core.paths import paths 

45 

46 return paths.metadata_db 

47 

48 

49# File extensions to scan per type 

50GAME_EXTENSIONS = ["*.chd", "*.rvz", "*.iso", "*.xiso", "*.cue", "*.m3u"] 

51# Folder-based platforms (games are directories, not files) 

52FOLDER_PLATFORMS = {"ps3"} 

53 

54 

55def _load_generations() -> dict: 

56 """Load generation definitions from YAML.""" 

57 data = yaml.safe_load(_default_generations_yaml().read_text()) 

58 return {g["name"]: g for g in data["generations"]} 

59 

60 

61def _load_platform_games(platform: str, output_base: Path) -> list[Path]: 

62 """Load game files/folders from a platform output directory.""" 

63 platform_dir = output_base / platform 

64 if not platform_dir.exists(): 

65 return [] 

66 

67 if platform in FOLDER_PLATFORMS: 

68 # Folder-based: each subdirectory (except Best Games) is a game 

69 return [ 

70 p 

71 for p in platform_dir.iterdir() 

72 if p.is_dir() and p.name not in ("Best Games", "_Best Games") 

73 ] 

74 else: 

75 # File-based: glob game files 

76 games = [] 

77 for pattern in GAME_EXTENSIONS: 

78 games.extend(platform_dir.glob(pattern)) 

79 return games 

80 

81 

82def _find_duplicates( 

83 output_base: Path, 

84 platforms: list[str], 

85) -> tuple[dict, dict[str, list]]: 

86 """Find cross-platform duplicate games. 

87 

88 Returns: 

89 (duplicates, platform_games) where: 

90 - duplicates: {match_key: {platform: NormalizedGame}} 

91 - platform_games: {platform: [NormalizedGame]} 

92 """ 

93 normalizer = GameNameNormalizer() 

94 platform_games = {} 

95 game_index = defaultdict(dict) 

96 

97 for platform_name in platforms: 

98 files = _load_platform_games(platform_name, output_base) 

99 normalized = [] 

100 for f in files: 

101 game_name = f.stem 

102 ng = normalizer.normalize(game_name, platform_name, str(f)) 

103 normalized.append(ng) 

104 game_index[ng.match_key()][platform_name] = ng 

105 platform_games[platform_name] = normalized 

106 

107 # Filter to games on 2+ platforms 

108 duplicates = { 

109 key: platforms_dict 

110 for key, platforms_dict in game_index.items() 

111 if len(platforms_dict) >= 2 

112 } 

113 return duplicates, platform_games 

114 

115 

116def _enrich_with_metadata( 

117 duplicate_games: list[dict], 

118 db_path: Path | None = None, 

119) -> list[dict]: 

120 """Enrich duplicate game records with ScreenScraper metadata. 

121 

122 Queries the scraped_games table using fuzzy name matching to add 

123 genre, rating, developer, and player count per platform version. 

124 """ 

125 if db_path is None: 

126 db_path = _default_metadata_db() 

127 if not db_path.exists(): 

128 return duplicate_games 

129 

130 db = sqlite3.connect(str(db_path)) 

131 db.row_factory = sqlite3.Row 

132 

133 # System name mapping (our platform names → ScreenScraper system names) 

134 sys_map = { 

135 "psx": "psx", 

136 "saturn": "saturn", 

137 "ps2": "ps2", 

138 "gamecube": "gamecube", 

139 "xbox": "xbox", 

140 "dreamcast": "dreamcast", 

141 "ps3": "ps3", 

142 "xbox360": "xbox360", 

143 "wii": "wii", 

144 "megacd": "megacd", 

145 "pcenginecd": "pcenginecd", 

146 "neogeocd": "neogeocd", 

147 } 

148 

149 for game in duplicate_games: 

150 game["metadata"] = {} 

151 # Sanitize game name for SQL LIKE 

152 base_name = game["name"].split("(")[0].strip() 

153 # Escape SQL LIKE wildcards 

154 safe_name = base_name.replace("%", "\\%").replace("_", "\\_") 

155 like_pattern = f"%{safe_name}%" 

156 

157 for platform in game["platforms"]: 

158 system = sys_map.get(platform, platform) 

159 try: 

160 row = db.execute( 

161 "SELECT name, genre, rating, developer, players " 

162 "FROM scraped_games WHERE system = ? AND name LIKE ? ESCAPE '\\' LIMIT 1", 

163 (system, like_pattern), 

164 ).fetchone() 

165 if row: 

166 game["metadata"][platform] = { 

167 "genre": row["genre"] or "", 

168 "rating": row["rating"] or 0.0, 

169 "developer": row["developer"] or "", 

170 "players": row["players"] or "", 

171 } 

172 except Exception: 

173 pass 

174 

175 db.close() 

176 return duplicate_games 

177 

178 

179@click.group(name="generation") 

180def generation_group(): 

181 """Cross-generation deduplication (1G1Gen).""" 

182 pass 

183 

184 

185@generation_group.command() 

186@click.argument("gen_name") 

187@click.option( 

188 "--output-base", type=click.Path(exists=True), default=None, help="Base output directory" 

189) 

190@click.option("--json-out", type=click.Path(), help="Save analysis as JSON") 

191def analyze(gen_name: str, output_base: str, json_out: str): 

192 """Analyze cross-platform duplicates for a generation. 

193 

194 Scans build output directories and identifies games that exist on 

195 multiple platforms. Does not modify any files. 

196 

197 Example: romfarmer generation analyze gen6 

198 """ 

199 gens = _load_generations() 

200 if gen_name not in gens: 

201 console.print(f"[red]Unknown generation: {gen_name}[/red]") 

202 console.print(f"Available: {', '.join(gens.keys())}") 

203 raise SystemExit(1) 

204 

205 gen = gens[gen_name] 

206 platforms = [p["name"] for p in gen["platforms"]] 

207 

208 console.print( 

209 Panel( 

210 f"[bold]{gen['label']}[/bold]\n" 

211 f"Platforms: {' > '.join(platforms)}\n" 

212 f"Primary: {platforms[0]}", 

213 title="Generation Analysis", 

214 ) 

215 ) 

216 

217 output_path = Path(output_base) 

218 

219 # Count games per platform 

220 console.print("\n[cyan]Scanning platform directories...[/cyan]") 

221 for p in platforms: 

222 files = _load_platform_games(p, output_path) 

223 console.print(f" {p:12s}: {len(files):,} games") 

224 

225 # Find duplicates 

226 duplicates, platform_games = _find_duplicates(output_path, platforms) 

227 total_games = sum(len(g) for g in platform_games.values()) 

228 

229 console.print(f"\n[green]Cross-platform duplicates: {len(duplicates):,}[/green]") 

230 console.print(f"Total games across platforms: {total_games:,}") 

231 

232 # Show platform overlap matrix 

233 table = Table(title="Platform Overlap") 

234 table.add_column("Platforms", style="cyan") 

235 table.add_column("Shared Games", justify="right") 

236 

237 # Count pairwise overlaps 

238 pair_counts = defaultdict(int) 

239 for _match_key, plats in duplicates.items(): 

240 plat_names = sorted(plats.keys()) 

241 for i in range(len(plat_names)): 

242 for j in range(i + 1, len(plat_names)): 

243 pair = f"{plat_names[i]} + {plat_names[j]}" 

244 pair_counts[pair] += 1 

245 

246 for pair, count in sorted(pair_counts.items(), key=lambda x: -x[1]): 

247 table.add_row(pair, str(count)) 

248 console.print(table) 

249 

250 # Show what would be removed (mirrors actual FilterGenerationStage logic) 

251 would_remove = defaultdict(int) 

252 for _match_key, plats in duplicates.items(): 

253 # Find highest priority platform that has this game 

254 keeper = None 

255 for p in platforms: 

256 if p in plats: 

257 keeper = p 

258 break 

259 if not keeper: 

260 continue 

261 for p in plats: 

262 if p != keeper: 

263 would_remove[p] += 1 

264 

265 console.print("\n[yellow]Without rescue lists, would remove:[/yellow]") 

266 for p in platforms[1:]: 

267 before = len(platform_games.get(p, [])) 

268 removed = would_remove.get(p, 0) 

269 after = before - removed 

270 pct = (removed / before * 100) if before > 0 else 0 

271 console.print(f" {p:12s}: {before:,} -> {after:,} (-{removed:,}, {pct:.0f}% removed)") 

272 

273 # Show with rescue lists if available 

274 rescue_file = _default_rescue_dir() / f"rescue-{gen_name}.yaml" 

275 if rescue_file.exists(): 

276 import yaml as _yaml 

277 

278 rescue_data = _yaml.safe_load(rescue_file.read_text()) 

279 rescue_lists = rescue_data.get("rescue_lists", {}) if rescue_data else {} 

280 if rescue_lists: 

281 # Recompute with rescue swaps: rescued games swap the keeper 

282 would_remove_r = defaultdict(int) 

283 for _match_key, plats in duplicates.items(): 

284 keeper = None 

285 for p in platforms: 

286 if p in plats: 

287 keeper = p 

288 break 

289 if not keeper: 

290 continue 

291 # Check if any non-keeper platform is rescued 

292 swapped = False 

293 for p in plats: 

294 if p == keeper: 

295 continue 

296 rescued_games = rescue_lists.get(p, []) 

297 any_game = plats[p] 

298 if any_game.original_name.lower() in [ 

299 g.lower() for g in rescued_games 

300 ] or any_game.normalized_name.lower() in [g.lower() for g in rescued_games]: 

301 # Swap: remove keeper instead, keep rescued platform 

302 would_remove_r[keeper] += 1 

303 for other_p in plats: 

304 if other_p != p: 

305 would_remove_r[other_p] += 1 

306 # Undo the rescued platform 

307 would_remove_r[p] -= 1 

308 swapped = True 

309 break 

310 if not swapped: 

311 for p in plats: 

312 if p != keeper: 

313 would_remove_r[p] += 1 

314 

315 total_rescued = sum(len(g) for g in rescue_lists.values()) 

316 console.print( 

317 f"\n[green]With rescue lists ({total_rescued} rescues), would remove:[/green]" 

318 ) 

319 total_removed = 0 

320 for p in platforms: 

321 removed = would_remove_r.get(p, 0) 

322 if removed > 0: 

323 before = len(platform_games.get(p, [])) 

324 after = before - removed 

325 pct = (removed / before * 100) if before > 0 else 0 

326 console.print( 

327 f" {p:12s}: {before:,} -> {after:,} (-{removed:,}, {pct:.0f}% removed)" 

328 ) 

329 total_removed += removed 

330 console.print(f" [bold]Total removals: {total_removed:,}[/bold]") 

331 

332 # Top overlapping games (appear on most platforms) 

333 multi_plat = sorted([(k, v) for k, v in duplicates.items()], key=lambda x: -len(x[1])) 

334 if multi_plat: 

335 table2 = Table(title="Games on Most Platforms (top 20)") 

336 table2.add_column("Game", style="green") 

337 table2.add_column("Platforms", style="cyan") 

338 for _key, plats in multi_plat[:20]: 

339 # Use any platform's original name 

340 name = next(iter(plats.values())).original_name 

341 table2.add_row(name, ", ".join(sorted(plats.keys()))) 

342 console.print(table2) 

343 

344 # Build export data 

345 export = [] 

346 for match_key, plats in duplicates.items(): 

347 any_game = next(iter(plats.values())) 

348 export.append( 

349 { 

350 "name": any_game.original_name, 

351 "match_key": match_key, 

352 "platforms": sorted(plats.keys()), 

353 } 

354 ) 

355 

356 if json_out: 

357 Path(json_out).write_text(json.dumps(export, indent=2)) 

358 console.print(f"\n[green]Saved {len(export)} duplicates to {json_out}[/green]") 

359 

360 return export 

361 

362 

363@generation_group.command() 

364@click.argument("gen_name") 

365@click.option( 

366 "--output-base", type=click.Path(exists=True), default=None, help="Base output directory" 

367) 

368@click.option("--model", default="claude-haiku-4.5", help="Model to use for rescue evaluation") 

369@click.option( 

370 "--batch-size", default=50, type=int, help="Games per LLM batch (higher = fewer API calls)" 

371) 

372@click.option("--force", is_flag=True, help="Regenerate even if cached") 

373@click.option("--dry-run", is_flag=True, help="Show what would be sent without calling LLM") 

374def rescue( 

375 gen_name: str, output_base: str, model: str, batch_size: int, force: bool, dry_run: bool 

376): 

377 """Generate AI rescue lists for a generation. 

378 

379 Finds cross-platform duplicates, enriches with metadata, then asks 

380 an LLM to identify games that should be "rescued" (kept on a 

381 non-primary platform because that version is superior). 

382 

383 Example: romfarmer generation rescue gen6 

384 """ 

385 from romfarmer.ai.rescue_generator import RescueListGenerator, RescueListResult 

386 

387 gens = _load_generations() 

388 if gen_name not in gens: 

389 console.print(f"[red]Unknown generation: {gen_name}[/red]") 

390 raise SystemExit(1) 

391 

392 gen = gens[gen_name] 

393 platforms = [p["name"] for p in gen["platforms"]] 

394 primary = platforms[0] 

395 

396 # Check cache first 

397 cache_file = _default_rescue_dir() / f"rescue-{gen_name}.yaml" 

398 if cache_file.exists() and not force: 

399 existing = RescueListResult.from_yaml(cache_file.read_text()) 

400 console.print(f"[yellow]Cached rescue list exists: {cache_file}[/yellow]") 

401 console.print(f" Total rescued: {existing.stats.get('total_rescued', '?')}") 

402 console.print(f" Model: {existing.model}") 

403 console.print(" Use --force to regenerate") 

404 return 

405 

406 console.print( 

407 Panel( 

408 f"[bold]{gen['label']}[/bold] — Rescue List Generation\n" 

409 f"Model: {model} | Batch size: {batch_size}\n" 

410 f"Primary: {primary} | Platforms: {' > '.join(platforms)}", 

411 title="1G1Gen Rescue Generator", 

412 ) 

413 ) 

414 

415 # Find duplicates 

416 output_path = Path(output_base) 

417 duplicates, platform_games = _find_duplicates(output_path, platforms) 

418 

419 console.print(f"Found [green]{len(duplicates):,}[/green] cross-platform duplicates") 

420 

421 # Build game list for LLM 

422 games_for_llm = [] 

423 for _match_key, plats in duplicates.items(): 

424 any_game = next(iter(plats.values())) 

425 games_for_llm.append( 

426 { 

427 "name": any_game.original_name, 

428 "platforms": sorted(plats.keys()), 

429 } 

430 ) 

431 

432 # Enrich with metadata 

433 console.print("[cyan]Enriching with ScreenScraper metadata...[/cyan]") 

434 games_for_llm = _enrich_with_metadata(games_for_llm) 

435 enriched_count = sum(1 for g in games_for_llm if g.get("metadata")) 

436 console.print(f" Enriched {enriched_count}/{len(games_for_llm)} games with metadata") 

437 

438 if dry_run: 

439 console.print( 

440 f"\n[yellow]DRY RUN — would send {len(games_for_llm)} games " 

441 f"in {((len(games_for_llm) - 1) // batch_size) + 1} batches[/yellow]" 

442 ) 

443 # Show first batch as example 

444 sample = games_for_llm[: min(5, len(games_for_llm))] 

445 for g in sample: 

446 meta_str = "" 

447 if g.get("metadata"): 

448 meta_parts = [] 

449 for p, m in g["metadata"].items(): 

450 meta_parts.append(f"{p}: {m.get('genre', '?')} rating={m.get('rating', '?')}") 

451 meta_str = f" [{'; '.join(meta_parts)}]" 

452 console.print(f" {g['name']} — {', '.join(g['platforms'])}{meta_str}") 

453 return 

454 

455 # Generate rescue lists 

456 generator = RescueListGenerator(model=model, batch_size=batch_size) 

457 result = asyncio.run( 

458 generator.generate_via_api( 

459 gen_name, 

460 platforms, 

461 games_for_llm, 

462 ) 

463 ) 

464 

465 # Save 

466 _default_rescue_dir().mkdir(parents=True, exist_ok=True) 

467 generator.save(result, _default_rescue_dir()) 

468 

469 # Display results 

470 console.print("\n[green]Rescue generation complete![/green]") 

471 console.print(f" Total evaluated: {result.stats.get('total_evaluated', 0)}") 

472 console.print(f" Total rescued: {result.stats.get('total_rescued', 0)}") 

473 console.print(f" Rescue rate: {result.stats.get('rescue_rate', '0%')}") 

474 

475 if result.rescue_lists: 

476 table = Table(title="Rescue Summary") 

477 table.add_column("Platform", style="cyan") 

478 table.add_column("Rescued Games", justify="right") 

479 for platform, games in sorted(result.rescue_lists.items()): 

480 table.add_row(platform, str(len(games))) 

481 console.print(table) 

482 

483 # Show rescued games 

484 for platform, games in sorted(result.rescue_lists.items()): 

485 console.print(f"\n[bold]{platform}[/bold] rescued games:") 

486 for g in sorted(games): 

487 # Find reason 

488 reason = "" 

489 for d in result.decisions: 

490 if d.rescue_platform == platform and d.game_name == g: 

491 reason = d.reason 

492 break 

493 console.print(f" • {g}") 

494 if reason: 

495 console.print(f" [dim]{reason}[/dim]")