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

333 statements  

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

1""" 

2CLI commands for metadata management. 

3 

4Commands: 

5- import-arrm: Import ARRM gamelist.xml 

6- generate: Generate gamelist.xml for ROM directory 

7- info: Show metadata database statistics 

8- list: List games in database 

9- generate-gamelist: Generate minimal gamelist for ARRM 

10- test-dat: Test DAT manager (from metadata_test_commands) 

11- test-transform: Test transformation recording (from metadata_test_commands) 

12""" 

13 

14import hashlib 

15import zipfile 

16from pathlib import Path 

17 

18import click 

19from rich.console import Console 

20from rich.table import Table 

21 

22from ..metadata.arrm import ARRMImporter, print_import_stats 

23from ..metadata.database import MetadataDatabase 

24from ..metadata.generator import GamelistGenerator, print_generation_stats 

25from .metadata_test_commands import test_dat, test_transform 

26 

27console = Console() 

28 

29 

30# Helper functions for generate-gamelist (must be at module level for multiprocessing) 

31def calculate_md5_from_zip(zip_path: Path) -> tuple[str, str, str]: 

32 """Calculate MD5 of the data file inside a ZIP, return .cue path for ARRM. 

33 

34 For CD-based games (.cue/.bin pairs): 

35 - Hashes the .bin file (actual data for matching) 

36 - Returns the .cue filename (what ARRM expects) 

37 - Caller will create zero-byte .cue file 

38 

39 For cartridge systems with .bin files: 

40 - .bin files are just binary data (BIOS, firmware, etc.) 

41 - Returns the .bin filename directly (no .cue creation) 

42 

43 Returns (filename, md5_hash, data_extension) or (filename, None, None) on error 

44 """ 

45 try: 

46 with zipfile.ZipFile(zip_path, "r") as zf: 

47 # Get all files (exclude directories) 

48 all_files = [f for f in zf.namelist() if not f.endswith("/")] 

49 if not all_files: 

50 return (str(zip_path.name), None, None) 

51 

52 # Find data files to hash (actual game data) 

53 # Check for cartridge ROMs first (higher priority than .bin) 

54 cart_files = [ 

55 f 

56 for f in all_files 

57 if any( 

58 f.lower().endswith(ext) 

59 for ext in [".nds", ".3ds", ".gba", ".gbc", ".gb", ".nes", ".sfc", ".smd"] 

60 ) 

61 ] 

62 cue_files = [f for f in all_files if f.lower().endswith(".cue")] 

63 bin_files = [f for f in all_files if f.lower().endswith(".bin")] 

64 iso_files = [f for f in all_files if f.lower().endswith(".iso")] 

65 chd_files = [f for f in all_files if f.lower().endswith(".chd")] 

66 

67 # Determine which file to hash and whether this is a CD-based system 

68 hash_file = None 

69 is_cd_system = False 

70 

71 if cart_files: 

72 # Cartridge ROM (highest priority) 

73 hash_file = cart_files[0] 

74 is_cd_system = False 

75 elif cue_files and bin_files: 

76 # CD-based system with .cue/.bin pair 

77 hash_file = bin_files[0] 

78 is_cd_system = True 

79 elif bin_files and not cart_files: 

80 # Standalone .bin file (could be BIOS/firmware on cartridge system) 

81 # If there's only a .bin file and no cart ROMs, treat as binary data (not CD) 

82 hash_file = bin_files[0] 

83 is_cd_system = False 

84 elif iso_files: 

85 hash_file = iso_files[0] 

86 is_cd_system = True 

87 elif chd_files: 

88 hash_file = chd_files[0] 

89 is_cd_system = True 

90 else: 

91 hash_file = all_files[0] 

92 is_cd_system = False 

93 

94 # Calculate MD5 of the data file 

95 md5_hash = hashlib.md5() 

96 with zf.open(hash_file) as f: 

97 while chunk := f.read(8192 * 1024): # 8MB chunks 

98 md5_hash.update(chunk) 

99 

100 # Determine what filename to return for the path 

101 # For .bin files on CD-based systems, return .cue filename 

102 # For everything else, return the actual filename 

103 if is_cd_system and hash_file.lower().endswith(".bin"): 

104 # Create .cue filename from .bin filename (CD-based system) 

105 cue_filename = hash_file[:-4] + ".cue" 

106 data_ext = ".bin" 

107 else: 

108 # Use the actual file (ISO, CHD, cartridge ROM, or standalone .bin) 

109 cue_filename = hash_file 

110 data_ext = Path(hash_file).suffix 

111 

112 return (cue_filename, md5_hash.hexdigest(), data_ext) 

113 except Exception: 

114 return (str(zip_path.name), None, None) 

115 

116 

117def calculate_md5_from_file(file_path: Path) -> tuple[str, str]: 

118 """Calculate MD5 of a raw file (ISO, CHD, etc).""" 

119 try: 

120 md5_hash = hashlib.md5() 

121 with open(file_path, "rb") as f: 

122 while chunk := f.read(8192 * 1024): # 8MB chunks 

123 md5_hash.update(chunk) 

124 return (str(file_path.name), md5_hash.hexdigest()) 

125 except Exception: 

126 return (str(file_path.name), None) 

127 

128 

129@click.group(name="metadata") 

130def metadata_group(): 

131 """Manage game metadata and media files.""" 

132 pass 

133 

134 

135@metadata_group.command(name="import-arrm") 

136@click.argument("gamelist_path", type=click.Path(exists=True, path_type=Path)) 

137@click.option( 

138 "--database", 

139 "-d", 

140 type=click.Path(path_type=Path), 

141 default="metadata/database/romfarmer.db", 

142 help="Path to metadata database", 

143) 

144@click.option( 

145 "--media-storage", 

146 "-m", 

147 type=click.Path(path_type=Path), 

148 default="store", 

149 help="Content-addressable store directory", 

150) 

151@click.option( 

152 "--roms-base-dir", 

153 "-b", 

154 type=click.Path(exists=True, path_type=Path), 

155 help="Base directory for resolving relative paths (default: gamelist parent)", 

156) 

157@click.option( 

158 "--update/--no-update", 

159 default=True, 

160 help="Update existing games if found", 

161) 

162def import_arrm( 

163 gamelist_path: Path, 

164 database: Path, 

165 media_storage: Path, 

166 roms_base_dir: Path | None, 

167 update: bool, 

168): 

169 """ 

170 Import ARRM gamelist.xml into metadata database. 

171 

172 This command imports game metadata and media files from ARRM-generated 

173 gamelist.xml files. Media files are deduplicated using content-addressable 

174 storage, so clones share the same media files. 

175 

176 Example: 

177 

178 rom-farmer metadata import-arrm /path/to/roms/vectrex/gamelist.xml 

179 

180 The importer will: 

181 - Parse gamelist.xml 

182 - Import game metadata (name, description, ratings, etc.) 

183 - Import all 9 media types (image, boxart, screenshot, etc.) 

184 - Deduplicate media files by hash 

185 - Store in content-addressable storage 

186 

187 Time: ~30 seconds for 30-game collection, ~5 minutes for 658-game collection 

188 """ 

189 try: 

190 # Create database and importer 

191 db = MetadataDatabase(database) 

192 importer = ARRMImporter(db, media_storage) 

193 

194 # Import gamelist 

195 stats = importer.import_gamelist( 

196 gamelist_path, 

197 roms_base_dir, 

198 update_existing=update, 

199 ) 

200 

201 # Print results 

202 print_import_stats(stats) 

203 

204 if stats.errors: 

205 console.print(f"\n[yellow]⚠ Import completed with {len(stats.errors)} errors[/yellow]") 

206 raise click.Abort() 

207 

208 console.print("\n[green]✓ Import completed successfully![/green]") 

209 

210 except Exception as e: 

211 console.print(f"[red]✗ Error:[/red] {e}") 

212 raise click.Abort() from e 

213 

214 

215@metadata_group.command(name="generate") 

216@click.argument("roms_dir", type=click.Path(exists=True, path_type=Path)) 

217@click.argument("output_dir", type=click.Path(path_type=Path)) 

218@click.option( 

219 "--database", 

220 "-d", 

221 type=click.Path(exists=True, path_type=Path), 

222 default="metadata/database/romfarmer.db", 

223 help="Path to metadata database", 

224) 

225@click.option( 

226 "--media-types", 

227 "-t", 

228 help='Media types to include (comma-separated or "all", "minimal", "standard")', 

229) 

230@click.option( 

231 "--no-copy-media", 

232 is_flag=True, 

233 help="Don't copy media files (gamelist only)", 

234) 

235@click.option( 

236 "--media-subdir", 

237 default="media", 

238 help="Subdirectory name for media files", 

239) 

240def generate( 

241 roms_dir: Path, 

242 output_dir: Path, 

243 database: Path, 

244 media_types: str | None, 

245 no_copy_media: bool, 

246 media_subdir: str, 

247): 

248 """ 

249 Generate gamelist.xml for ROM directory. 

250 

251 This command scans a ROM directory, matches files to the metadata database 

252 by hash, and generates a gamelist.xml with optional media files. 

253 

254 Example: 

255 

256 # Generate with all media types 

257 rom-farmer metadata generate /path/to/roms/nes /path/to/output/nes 

258 

259 # Generate with minimal media (just mix image) 

260 rom-farmer metadata generate /path/to/roms/nes /path/to/output/nes --media-types minimal 

261 

262 # Generate with specific types 

263 rom-farmer metadata generate /path/to/roms/nes /path/to/output/nes --media-types image,boxart,screenshot 

264 

265 # Generate without copying media 

266 rom-farmer metadata generate /path/to/roms/nes /path/to/output/nes --no-copy-media 

267 

268 Media type options: 

269 - "all": All 9 media types (~2.4 GB for 658 games) 

270 - "minimal": Just mix image (~1.3 MB for 658 games) 

271 - "standard": Standard set (image, boxart, screenshot, wheel, mix) 

272 - "no-videos": All except videos 

273 - "no-manuals": All except manuals 

274 - Comma-separated: Specific types (e.g., "image,boxart,screenshot") 

275 

276 Time: ~10 seconds for 658-game collection 

277 """ 

278 try: 

279 # Parse media types 

280 if media_types: 

281 if media_types in ["all", "minimal", "standard", "no-videos", "no-manuals"]: 

282 media_types_list = media_types 

283 else: 

284 media_types_list = [t.strip() for t in media_types.split(",")] 

285 else: 

286 media_types_list = None 

287 

288 # Create database and generator 

289 db = MetadataDatabase(database) 

290 generator = GamelistGenerator(db) 

291 

292 # Generate gamelist 

293 stats = generator.generate_gamelist( 

294 roms_dir, 

295 output_dir, 

296 media_types=media_types_list, 

297 copy_media=not no_copy_media, 

298 media_subdir=media_subdir, 

299 ) 

300 

301 # Print results 

302 print_generation_stats(stats) 

303 

304 if stats.roms_unmatched > 0: 

305 console.print(f"\n[yellow]⚠ {stats.roms_unmatched} ROMs not found in database[/yellow]") 

306 

307 console.print("\n[green]✓ Generation completed successfully![/green]") 

308 

309 except Exception as e: 

310 console.print(f"[red]✗ Error:[/red] {e}") 

311 raise click.Abort() from e 

312 

313 

314@metadata_group.command(name="info") 

315@click.option( 

316 "--database", 

317 "-d", 

318 type=click.Path(exists=True, path_type=Path), 

319 default="metadata/database/romfarmer.db", 

320 help="Path to metadata database", 

321) 

322def info(database: Path): 

323 """ 

324 Show metadata database statistics. 

325 

326 Example: 

327 

328 rom-farmer metadata info 

329 """ 

330 try: 

331 db = MetadataDatabase(database) 

332 stats = db.get_stats() 

333 

334 # Create info table 

335 table = Table(title="Metadata Database Statistics") 

336 table.add_column("Metric", style="cyan") 

337 table.add_column("Value", style="green", justify="right") 

338 

339 table.add_row("Total Games", str(stats["total_games"])) 

340 table.add_row("Total Media Files", str(stats["total_media_files"])) 

341 table.add_row("Total Media Links", str(stats["total_media_links"])) 

342 table.add_row( 

343 "Average References per File", 

344 f"{stats['avg_references_per_file']:.1f}", 

345 ) 

346 table.add_row("", "") # Separator 

347 

348 table.add_row("Total Media Size", f"{stats['total_size_mb']:.1f} MB") 

349 table.add_row("Savings from Deduplication", f"{stats['savings_mb']:.1f} MB") 

350 table.add_row( 

351 "Deduplication Rate", 

352 f"{stats['savings_percent']:.1f}%", 

353 ) 

354 

355 console.print(table) 

356 

357 if stats["savings_percent"] > 0: 

358 console.print( 

359 f"\n[green]✓ Deduplication saved {stats['savings_mb']:.1f} MB " 

360 f"({stats['savings_percent']:.1f}%)[/green]" 

361 ) 

362 

363 except FileNotFoundError: 

364 console.print(f"[red]✗ Database not found:[/red] {database}") 

365 console.print( 

366 "[yellow]Run 'rom-farmer metadata import-arrm' first to create the database[/yellow]" 

367 ) 

368 raise click.Abort() from None 

369 except Exception as e: 

370 console.print(f"[red]✗ Error:[/red] {e}") 

371 raise click.Abort() from e 

372 

373 

374@metadata_group.command(name="list") 

375@click.option( 

376 "--database", 

377 "-d", 

378 type=click.Path(exists=True, path_type=Path), 

379 default="metadata/database/romfarmer.db", 

380 help="Path to metadata database", 

381) 

382@click.option( 

383 "--system", 

384 "-s", 

385 help="Filter by system name", 

386) 

387@click.option( 

388 "--limit", 

389 "-l", 

390 type=int, 

391 default=50, 

392 help="Maximum number of games to show", 

393) 

394def list_games(database: Path, system: str | None, limit: int): 

395 """ 

396 List games in metadata database. 

397 

398 Example: 

399 

400 rom-farmer metadata list 

401 rom-farmer metadata list --system "Nintendo - Nintendo Entertainment System" 

402 rom-farmer metadata list --limit 100 

403 """ 

404 try: 

405 db = MetadataDatabase(database) 

406 

407 with db.get_session() as session: 

408 from ..metadata.database import ScrapedGame 

409 

410 query = session.query(ScrapedGame) 

411 

412 if system: 

413 query = query.filter(ScrapedGame.system == system) 

414 

415 query = query.order_by(ScrapedGame.name) 

416 query = query.limit(limit) 

417 

418 games = query.all() 

419 

420 if not games: 

421 console.print("[yellow]No games found in database[/yellow]") 

422 return 

423 

424 # Create games table 

425 table = Table(title=f"Games in Database (showing {len(games)})") 

426 table.add_column("Name", style="cyan") 

427 table.add_column("System", style="yellow") 

428 table.add_column("Region", style="green") 

429 table.add_column("Media", style="magenta", justify="right") 

430 

431 for game in games: 

432 media_count = len(game.media_links) 

433 table.add_row( 

434 game.name or "Unknown", 

435 game.system or "Unknown", 

436 game.region or "Unknown", 

437 str(media_count), 

438 ) 

439 

440 console.print(table) 

441 

442 # Show total count 

443 total = session.query(ScrapedGame).count() 

444 if total > limit: 

445 console.print( 

446 f"\n[yellow]Showing {len(games)} of {total} games. " 

447 f"Use --limit to show more.[/yellow]" 

448 ) 

449 

450 except FileNotFoundError: 

451 console.print(f"[red]✗ Database not found:[/red] {database}") 

452 raise click.Abort() from None 

453 except Exception as e: 

454 console.print(f"[red]✗ Error:[/red] {e}") 

455 raise click.Abort() from e 

456 

457 

458# Register test commands from separate module 

459metadata_group.add_command(test_dat) 

460metadata_group.add_command(test_transform) 

461 

462 

463@metadata_group.command(name="generate-gamelist") 

464@click.argument("roms_dir", type=click.Path(exists=True, path_type=Path)) 

465@click.option( 

466 "--system", 

467 "-s", 

468 required=True, 

469 help="System name (e.g., ps3, nes, saturn)", 

470) 

471@click.option( 

472 "--output", 

473 "-o", 

474 type=click.Path(path_type=Path), 

475 help="Output path for gamelist.xml (default: <roms_dir>/gamelist.xml)", 

476) 

477@click.option( 

478 "--workers", 

479 "-w", 

480 type=int, 

481 default=None, 

482 help="Number of parallel workers (default: CPU count)", 

483) 

484@click.option( 

485 "--save-interval", 

486 type=int, 

487 default=100, 

488 help="Save progress every N files (default: 100)", 

489) 

490@click.option( 

491 "--incremental/--full", 

492 default=True, 

493 help="Only calculate missing MD5s (default) or recalculate all", 

494) 

495def generate_gamelist( 

496 roms_dir: Path, 

497 system: str, 

498 output: Path | None, 

499 workers: int | None, 

500 save_interval: int, 

501 incremental: bool, 

502): 

503 """ 

504 Generate minimal gamelist.xml with MD5 hashes for ARRM. 

505 

506 This command scans a ROM directory, calculates MD5 hashes for files inside ZIPs, 

507 and generates a minimal gamelist.xml that ARRM can use for faster scraping. 

508 

509 Uses multi-core processing to hash multiple files in parallel. 

510 

511 CRASH RECOVERY: Saves progress periodically. If interrupted, re-run with 

512 --incremental (default) to resume from where it left off. 

513 

514 Example: 

515 

516 # Generate for PS3 ROMs (auto-detect CPU count, save every 100 files) 

517 rom-farmer metadata generate-gamelist /path/to/roms/ps3 --system ps3 

518 

519 # Use 16 workers, save every 50 files 

520 rom-farmer metadata generate-gamelist /path/to/roms/ps3 --system ps3 --workers 16 --save-interval 50 

521 

522 # Force recalculate all MD5s (ignore existing) 

523 rom-farmer metadata generate-gamelist /path/to/roms/ps3 --system ps3 --full 

524 

525 The generated gamelist.xml contains: 

526 - <path>: Relative path to ROM ZIP file 

527 - <md5>: MD5 hash of the first file inside the ZIP (ISO/CUE/BIN) 

528 

529 ARRM will then enrich this file with full metadata using MD5-based matching. 

530 

531 IMPORTANT: This is a MASSIVE operation for large disc systems! 

532 - PS3 (1,246 games, ~20GB avg): ~16-20 HOURS with 16 cores (~7-10 DAYS with 1 core) 

533 - PS2 (2,530 games, ~4GB avg): ~8-10 hours with 16 cores 

534 - Saturn/SegaCD (~600MB avg): ~30-60 minutes with 16 cores 

535 

536 We're decompressing and hashing ~25TB of data for PS3! 

537 

538 Progress auto-saves every 100 files. Safe to Ctrl+C and resume with --incremental. 

539 Recommended: Run in screen/tmux session for overnight processing. 

540 """ 

541 import multiprocessing 

542 import xml.dom.minidom as minidom 

543 import xml.etree.ElementTree as ET 

544 from concurrent.futures import ProcessPoolExecutor, as_completed 

545 

546 from rich.progress import BarColumn, Progress, SpinnerColumn, TaskProgressColumn, TextColumn 

547 

548 def load_existing_gamelist(output_path: Path) -> dict: 

549 """Load existing gamelist.xml and return dict of path -> md5.""" 

550 if not output_path.exists(): 

551 return {} 

552 

553 try: 

554 tree = ET.parse(output_path) 

555 root = tree.getroot() 

556 

557 existing = {} 

558 for game in root.findall("game"): 

559 path_elem = game.find("path") 

560 md5_elem = game.find("md5") 

561 if path_elem is not None and md5_elem is not None: 

562 existing[path_elem.text] = md5_elem.text 

563 

564 return existing 

565 except Exception as e: 

566 console.print(f"[yellow]⚠ Could not load existing gamelist.xml: {e}[/yellow]") 

567 return {} 

568 

569 def save_gamelist(output_path: Path, system: str, games: list): 

570 """Save gamelist.xml to disk.""" 

571 # Create root element 

572 root = ET.Element("gameList") 

573 

574 # Add provider info 

575 provider = ET.SubElement(root, "provider") 

576 ET.SubElement(provider, "system").text = system 

577 ET.SubElement(provider, "software").text = "ROM Farmer" 

578 ET.SubElement(provider, "web").text = "https://github.com/user/rom-farmer-python" 

579 

580 # Add games (sorted) 

581 sorted_games = sorted(games, key=lambda g: g["path"]) 

582 for idx, game_info in enumerate(sorted_games, start=1): 

583 game = ET.SubElement(root, "game") 

584 ET.SubElement(game, "path").text = game_info["path"] 

585 

586 # Extract name from filename (remove ./ prefix and extension) 

587 filename = game_info["path"].replace("./", "") 

588 # Remove common extensions for display name (but keep .cue/.m3u in path) 

589 for ext in [ 

590 ".iso", 

591 ".chd", 

592 ".nds", 

593 ".3ds", 

594 ".gba", 

595 ".gbc", 

596 ".gb", 

597 ".nes", 

598 ".sfc", 

599 ".smd", 

600 ".bin", 

601 ".img", 

602 ]: 

603 if filename.lower().endswith(ext): 

604 filename = filename[: -len(ext)] 

605 break 

606 # Also strip .cue for name display 

607 if filename.lower().endswith(".cue"): 

608 filename = filename[:-4] 

609 ET.SubElement(game, "name").text = filename 

610 

611 # Add sortname with zero-padded index (ARRM format) 

612 sortname = f"{idx:04d} =- {filename}" 

613 ET.SubElement(game, "sortname").text = sortname 

614 

615 # Add genreid (0 = unknown, ARRM will populate) 

616 ET.SubElement(game, "genreid").text = "0" 

617 

618 ET.SubElement(game, "md5").text = game_info["md5"] 

619 

620 # Pretty print XML 

621 xml_str = ET.tostring(root, encoding="unicode") 

622 dom = minidom.parseString(xml_str) 

623 pretty_xml = dom.toprettyxml(indent=" ") 

624 

625 # Remove extra blank lines 

626 lines = [line for line in pretty_xml.split("\n") if line.strip()] 

627 pretty_xml = "\n".join(lines) 

628 

629 # Write to file (with backup) 

630 output_path.parent.mkdir(parents=True, exist_ok=True) 

631 

632 # Create backup if file exists 

633 if output_path.exists(): 

634 backup_path = output_path.with_suffix(output_path.suffix + ".bak") 

635 output_path.rename(backup_path) 

636 

637 with open(output_path, "w", encoding="utf-8") as f: 

638 f.write(pretty_xml) 

639 

640 try: 

641 # Determine output path 

642 if output is None: 

643 output = roms_dir / "gamelist.xml" 

644 

645 # Determine worker count (default to 8, or CPU count if less) 

646 if workers is None: 

647 workers = min(8, multiprocessing.cpu_count()) 

648 

649 # Load existing gamelist (for incremental mode) 

650 existing_md5s = {} 

651 if incremental and output.exists(): 

652 console.print("[cyan]Loading existing gamelist.xml for incremental update...[/cyan]") 

653 existing_md5s = load_existing_gamelist(output) 

654 if existing_md5s: 

655 console.print(f"[green]Found {len(existing_md5s)} existing MD5 hashes[/green]") 

656 

657 # Scan for ROM files (ZIP or ISO/CHD/CUE) 

658 console.print(f"[cyan]Scanning {roms_dir} for ROM files...[/cyan]") 

659 

660 # Try common ROM formats 

661 rom_files = [] 

662 for pattern in ["*.zip", "*.iso", "*.chd", "*.cue"]: 

663 rom_files.extend(roms_dir.glob(pattern)) 

664 rom_files = sorted(set(rom_files)) # Remove duplicates 

665 

666 if not rom_files: 

667 console.print(f"[yellow]⚠ No ROM files found in {roms_dir}[/yellow]") 

668 console.print("[yellow] Supported: .zip, .iso, .chd, .cue[/yellow]") 

669 raise click.Abort() 

670 

671 # Detect file type 

672 is_zipped = rom_files[0].suffix == ".zip" 

673 console.print(f"[green]Found {len(rom_files)} {rom_files[0].suffix} files[/green]") 

674 

675 # Determine which files need processing 

676 files_to_process = [] 

677 games = [] 

678 

679 for rom_file in rom_files: 

680 rel_path = f"./{rom_file.name}" 

681 if incremental and rel_path in existing_md5s: 

682 # Already have MD5, keep it 

683 games.append( 

684 { 

685 "path": rel_path, 

686 "md5": existing_md5s[rel_path], 

687 } 

688 ) 

689 else: 

690 # Need to calculate MD5 

691 files_to_process.append(rom_file) 

692 

693 if incremental and existing_md5s: 

694 console.print( 

695 f"[cyan]Incremental mode: {len(files_to_process)} files need MD5 calculation[/cyan]" 

696 ) 

697 console.print(f"[cyan]Skipping {len(existing_md5s)} files with existing MD5s[/cyan]") 

698 

699 if not files_to_process: 

700 console.print("[green]✓ All files already have MD5 hashes![/green]") 

701 console.print("[green] Use --full to recalculate all MD5s[/green]") 

702 return 

703 

704 console.print(f"[cyan]Using {workers} parallel workers[/cyan]") 

705 console.print(f"[cyan]Auto-saving every {save_interval} files[/cyan]") 

706 

707 # Calculate MD5s with multi-core processing 

708 console.print("\n[cyan]Calculating MD5 hashes (extracting files from ZIPs)...[/cyan]") 

709 console.print("[yellow]⚠ LARGE OPERATION: Decompressing + hashing ISOs[/yellow]") 

710 console.print("[yellow] PS3 games are 5-50GB each (avg ~20GB)[/yellow]") 

711 console.print( 

712 f"[yellow] Estimated: {len(files_to_process) * 50 / workers / 60:.0f}-{len(files_to_process) * 80 / workers / 60:.0f} minutes ({len(files_to_process) * 50 / workers / 3600:.1f}-{len(files_to_process) * 80 / workers / 3600:.1f} hours)[/yellow]" 

713 ) 

714 console.print( 

715 f"[cyan]💾 Auto-saving every {save_interval} files - safe to Ctrl+C and resume![/cyan]\n" 

716 ) 

717 

718 processed_count = 0 

719 import time 

720 

721 start_time = time.time() 

722 last_save_time = start_time 

723 

724 with Progress( 

725 SpinnerColumn(), 

726 TextColumn("[progress.description]{task.description}"), 

727 BarColumn(), 

728 TaskProgressColumn(), 

729 console=console, 

730 ) as progress: 

731 task = progress.add_task("Hashing files...", total=len(files_to_process)) 

732 

733 with ProcessPoolExecutor(max_workers=workers) as executor: 

734 # Submit all tasks (use appropriate hash function based on file type) 

735 hash_function = calculate_md5_from_zip if is_zipped else calculate_md5_from_file 

736 futures = { 

737 executor.submit(hash_function, rom_file): rom_file 

738 for rom_file in files_to_process 

739 } 

740 

741 # Process results as they complete 

742 for future in as_completed(futures): 

743 rom_file = futures[future] 

744 

745 if is_zipped: 

746 filename, md5_hash, data_ext = future.result() 

747 

748 # For .bin files, create zero-byte .cue file to trick ARRM 

749 if md5_hash and data_ext == ".bin": 

750 cue_path = roms_dir / filename 

751 if not cue_path.exists(): 

752 cue_path.touch() # Create zero-byte file 

753 

754 # For .3ds files, create zero-byte .3ds file for ARRM compatibility 

755 # (ZIPs contain full .3ds files but emulators can't load from ZIP due to size) 

756 if md5_hash and data_ext == ".3ds": 

757 tds_path = roms_dir / filename 

758 if not tds_path.exists(): 

759 tds_path.touch() # Create zero-byte file 

760 else: 

761 filename, md5_hash = future.result() 

762 

763 if md5_hash: 

764 games.append( 

765 { 

766 "path": f"./{filename}", 

767 "md5": md5_hash, 

768 } 

769 ) 

770 processed_count += 1 

771 

772 # Show progress every 10 files 

773 if processed_count % 10 == 0: 

774 elapsed = time.time() - start_time 

775 rate = processed_count / (elapsed / 60) if elapsed > 0 else 0 

776 progress.console.print( 

777 f"[dim] ✓ {filename[:60]}... ({processed_count}/{len(files_to_process)}, {rate:.1f}/min)[/dim]" 

778 ) 

779 

780 # Periodic save (every 100 files OR every 5 minutes) 

781 current_time = time.time() 

782 time_since_save = current_time - last_save_time 

783 should_save = (processed_count % save_interval == 0) or ( 

784 time_since_save >= 300 

785 ) # 300 seconds = 5 minutes 

786 

787 if should_save: 

788 elapsed = time.time() - start_time 

789 rate = processed_count / (elapsed / 60) # games per minute 

790 remaining_games = len(files_to_process) - processed_count 

791 eta_minutes = remaining_games / rate if rate > 0 else 0 

792 save_gamelist(output, system, games) 

793 last_save_time = current_time 

794 save_reason = ( 

795 "100 files" if processed_count % save_interval == 0 else "5 min" 

796 ) 

797 progress.console.print( 

798 f"[green]💾 SAVED ({save_reason}): {len(games)} total | " 

799 f"Rate: {rate:.2f}/min | " 

800 f"ETA: {eta_minutes:.0f} min ({eta_minutes / 60:.1f} hrs) | " 

801 f"Elapsed: {elapsed / 3600:.1f} hrs[/green]" 

802 ) 

803 

804 progress.update(task, advance=1) 

805 

806 # Final save 

807 console.print("\n[cyan]Saving final gamelist.xml...[/cyan]") 

808 save_gamelist(output, system, games) 

809 

810 # Success! 

811 console.print(f"\n[green]✓ Generated gamelist.xml with {len(games)} games[/green]") 

812 console.print(f"[green] Output: {output}[/green]") 

813 console.print("\n[cyan]Next steps:[/cyan]") 

814 console.print(f" 1. Run ARRM on {roms_dir}") 

815 console.print(" 2. ARRM will use MD5 hashes for faster/accurate scraping") 

816 console.print(f" 3. Import enriched gamelist: ./romfarmer metadata import-arrm {output}") 

817 

818 except Exception as e: 

819 console.print(f"[red]✗ Error:[/red] {e}") 

820 import traceback 

821 

822 traceback.print_exc() 

823 raise click.Abort() from e