Coverage for src/romfarmer/metadata/arrm.py: 17%

277 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1""" 

2ARRM (Advanced ROM Repository Manager) gamelist.xml importer. 

3 

4This module imports metadata from ARRM-generated gamelist.xml files into 

5the ROM Farmer database. It handles all 9 media types and implements 

6content-addressable storage for deduplication. 

7""" 

8 

9import re 

10import xml.etree.ElementTree as ET 

11from dataclasses import dataclass 

12from datetime import datetime 

13from pathlib import Path 

14 

15from rich.console import Console 

16from rich.progress import ( 

17 BarColumn, 

18 Progress, 

19 SpinnerColumn, 

20 TaskProgressColumn, 

21 TextColumn, 

22 TimeRemainingColumn, 

23) 

24 

25from ..cas import ContentStore 

26from .database import ( 

27 GameMediaLink, 

28 MediaFile, 

29 MediaType, 

30 MetadataDatabase, 

31 ScrapedGame, 

32) 

33 

34console = Console() 

35 

36# ARRM embeds a numeric sort key as a prefix: "3595 =- Game Name" 

37# Strip it on import so the database stores clean sortnames. 

38_ARRM_SORTNAME_RE = re.compile(r"^\d+\s+=-\s+") 

39 

40 

41def _clean_arrm_sortname(value: str | None, name: str | None = None) -> str | None: 

42 """Strip ARRM numeric sort prefix from sortname; return None if result equals name.""" 

43 if not value: 

44 return value 

45 cleaned = _ARRM_SORTNAME_RE.sub("", value).strip() 

46 if name and cleaned == name: 

47 return None 

48 return cleaned or None 

49 

50 

51@dataclass 

52class ImportStats: 

53 """Statistics from an import operation.""" 

54 

55 games_processed: int = 0 

56 games_imported: int = 0 

57 games_updated: int = 0 

58 games_skipped: int = 0 

59 media_files_total: int = 0 

60 media_files_new: int = 0 

61 media_files_deduplicated: int = 0 

62 media_bytes_total: int = 0 

63 media_bytes_saved: int = 0 

64 errors: list[str] = None 

65 

66 def __post_init__(self): 

67 if self.errors is None: 

68 self.errors = [] 

69 

70 

71class ARRMImporter: 

72 """ 

73 Import ARRM gamelist.xml files into ROM Farmer database. 

74 

75 This importer: 

76 - Parses ARRM gamelist.xml format 

77 - Imports game metadata (all fields) 

78 - Imports all 9 media types 

79 - Implements content-addressable storage 

80 - Deduplicates media files by hash 

81 - Supports smart updates (keep old data, replace with better) 

82 """ 

83 

84 def __init__( 

85 self, 

86 database: MetadataDatabase, 

87 store_dir: Path = Path("store"), 

88 ): 

89 """ 

90 Initialize ARRM importer. 

91 

92 Args: 

93 database: MetadataDatabase instance 

94 store_dir: Content-addressable store directory 

95 """ 

96 self.database = database 

97 self.store = ContentStore(store_dir) 

98 

99 def import_gamelist( 

100 self, 

101 gamelist_path: Path, 

102 roms_base_dir: Path | None = None, 

103 update_existing: bool = True, 

104 ) -> ImportStats: 

105 """ 

106 Import an ARRM gamelist.xml file. 

107 

108 Args: 

109 gamelist_path: Path to gamelist.xml 

110 roms_base_dir: Base directory for resolving relative paths 

111 (defaults to gamelist.xml parent directory) 

112 update_existing: Update existing games if found 

113 

114 Returns: 

115 ImportStats with import results 

116 """ 

117 if not gamelist_path.exists(): 

118 raise FileNotFoundError(f"Gamelist not found: {gamelist_path}") 

119 

120 if roms_base_dir is None: 

121 roms_base_dir = gamelist_path.parent 

122 

123 console.print(f"[cyan]Importing:[/cyan] {gamelist_path}") 

124 console.print(f"[cyan]Base directory:[/cyan] {roms_base_dir}") 

125 

126 stats = ImportStats() 

127 

128 # Get gamelist modification time for timestamp tracking 

129 gamelist_mtime = datetime.fromtimestamp(gamelist_path.stat().st_mtime) 

130 

131 # Parse XML 

132 try: 

133 tree = ET.parse(gamelist_path) 

134 root = tree.getroot() 

135 except ET.ParseError as e: 

136 stats.errors.append(f"XML parse error: {e}") 

137 return stats 

138 

139 # Extract system name from provider section 

140 system_name = None 

141 provider = root.find("provider") 

142 if provider is not None: 

143 system_name = provider.findtext("system") 

144 

145 # Fallback: extract from directory name if no provider section 

146 if not system_name: 

147 system_name = roms_base_dir.name 

148 

149 if system_name: 

150 console.print(f"[cyan]System:[/cyan] {system_name}") 

151 

152 # Get all game elements 

153 games = root.findall("game") 

154 console.print(f"[cyan]Found {len(games)} games in gamelist[/cyan]") 

155 

156 # Import games with progress bar 

157 with Progress( 

158 SpinnerColumn(), 

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

160 BarColumn(), 

161 TaskProgressColumn(), 

162 TimeRemainingColumn(), 

163 ) as progress: 

164 task = progress.add_task("Importing games...", total=len(games)) 

165 

166 for game_elem in games: 

167 try: 

168 self._import_game( 

169 game_elem, 

170 roms_base_dir, 

171 stats, 

172 update_existing, 

173 system_name=system_name, 

174 gamelist_path=str(gamelist_path), 

175 gamelist_mtime=gamelist_mtime, 

176 ) 

177 except Exception as e: 

178 game_name = game_elem.findtext("name", "Unknown") 

179 error_msg = f"Error importing '{game_name}': {e}" 

180 stats.errors.append(error_msg) 

181 console.print(f"[yellow]⚠ {error_msg}[/yellow]") 

182 

183 progress.update(task, advance=1) 

184 

185 return stats 

186 

187 def _import_game( 

188 self, 

189 game_elem: ET.Element, 

190 roms_base_dir: Path, 

191 stats: ImportStats, 

192 update_existing: bool, 

193 system_name: str | None = None, 

194 gamelist_path: str | None = None, 

195 gamelist_mtime: datetime | None = None, 

196 ) -> None: 

197 """Import a single game from XML element.""" 

198 stats.games_processed += 1 

199 

200 # Extract metadata 

201 game_data = self._extract_game_metadata(game_elem, system_name) 

202 

203 # Add source tracking 

204 game_data["source_gamelist_path"] = gamelist_path 

205 game_data["source_gamelist_mtime"] = gamelist_mtime 

206 

207 if not game_data.get("md5"): 

208 stats.games_skipped += 1 

209 stats.errors.append(f"Skipping '{game_data.get('name')}': No MD5 hash") 

210 return 

211 

212 # Check if game exists 

213 with self.database.get_session() as session: 

214 existing_game = self.database.find_game_by_hash( 

215 md5=game_data.get("md5"), 

216 crc32=game_data.get("crc32"), 

217 sha1=game_data.get("sha1"), 

218 ) 

219 

220 if existing_game and not update_existing: 

221 stats.games_skipped += 1 

222 return 

223 

224 if existing_game: 

225 # Smart update: only update if new source is newer or more complete 

226 if self._should_update_game(existing_game, game_data, gamelist_mtime): 

227 game = session.merge(existing_game) 

228 self._update_game_metadata(game, game_data) 

229 stats.games_updated += 1 

230 else: 

231 # Skip update - existing data is newer or better 

232 stats.games_skipped += 1 

233 # Merge to attach to this session 

234 game = session.merge(existing_game) 

235 else: 

236 # Create new game 

237 game = ScrapedGame(**game_data) 

238 session.add(game) 

239 stats.games_imported += 1 

240 

241 session.commit() 

242 session.refresh(game) 

243 

244 # Import media files 

245 media_elements = self._extract_media_elements(game_elem) 

246 for media_type, media_path in media_elements.items(): 

247 try: 

248 self._import_media( 

249 game, 

250 media_type, 

251 media_path, 

252 roms_base_dir, 

253 stats, 

254 ) 

255 except Exception as e: 

256 error_msg = f"Error importing media '{media_type}' for '{game.name}': {e}" 

257 stats.errors.append(error_msg) 

258 

259 session.commit() 

260 

261 def _extract_game_metadata(self, game_elem: ET.Element, system_name: str | None = None) -> dict: 

262 """Extract game metadata from XML element.""" 

263 return { 

264 "md5": game_elem.findtext("md5"), 

265 "crc32": game_elem.findtext("crc32"), 

266 "sha1": game_elem.findtext("sha1"), 

267 "filename": game_elem.findtext("path"), 

268 "game_id": self._parse_int(game_elem.get("id")), 

269 "system": system_name, # Use system from provider section 

270 "name": game_elem.findtext("name"), 

271 "sortname": _clean_arrm_sortname( 

272 game_elem.findtext("sortname"), 

273 game_elem.findtext("name"), 

274 ), 

275 "description": game_elem.findtext("desc"), 

276 "rating": self._parse_float(game_elem.findtext("rating")), 

277 "release_date": game_elem.findtext("releasedate"), 

278 "developer": game_elem.findtext("developer"), 

279 "publisher": game_elem.findtext("publisher"), 

280 "genre": game_elem.findtext("genre"), 

281 "genre_id": self._parse_int(game_elem.findtext("genreid")), 

282 "players": game_elem.findtext("players"), 

283 "region": game_elem.findtext("region"), 

284 "language": game_elem.findtext("lang"), 

285 "hidden": self._parse_bool(game_elem.findtext("hidden")), 

286 "favorite": self._parse_bool(game_elem.findtext("favorite")), 

287 "kidgame": self._parse_bool(game_elem.findtext("kidgame")), 

288 "playcount": self._parse_int(game_elem.findtext("playcount")), 

289 "lastplayed": self._parse_datetime(game_elem.findtext("lastplayed")), 

290 } 

291 

292 def _parse_bool(self, value: str | None) -> bool: 

293 """Parse boolean value from string.""" 

294 if not value: 

295 return False 

296 return value.lower() in ("true", "yes", "1", "on") 

297 

298 def _parse_datetime(self, value: str | None) -> datetime | None: 

299 """Parse datetime from gamelist format (YYYYMMDDTHHMMSS).""" 

300 if not value: 

301 return None 

302 try: 

303 return datetime.strptime(value, "%Y%m%dT%H%M%S") 

304 except ValueError: 

305 return None 

306 

307 def _extract_media_elements(self, game_elem: ET.Element) -> dict[str, str]: 

308 """Extract all media elements from game XML.""" 

309 media_elements = {} 

310 

311 for media_type in MediaType.all_types(): 

312 media_path = game_elem.findtext(media_type) 

313 if media_path: 

314 media_elements[media_type] = media_path 

315 

316 return media_elements 

317 

318 def _import_media( 

319 self, 

320 game: ScrapedGame, 

321 media_type: str, 

322 media_path: str, 

323 roms_base_dir: Path, 

324 stats: ImportStats, 

325 ) -> None: 

326 """Import a media file with content-addressable storage.""" 

327 # Resolve path 

328 if media_path.startswith("./"): 

329 media_path = media_path[2:] 

330 

331 source_path = roms_base_dir / media_path 

332 

333 if not source_path.exists(): 

334 stats.errors.append(f"Media file not found: {source_path} (game: {game.name})") 

335 return 

336 

337 # Calculate file hash for content addressing 

338 file_hash = self.store.hash_file(source_path) 

339 file_size = source_path.stat().st_size 

340 file_mtime = datetime.fromtimestamp(source_path.stat().st_mtime) 

341 

342 stats.media_files_total += 1 

343 stats.media_bytes_total += file_size 

344 

345 # Check if media already exists 

346 with self.database.get_session() as session: 

347 # Reload game in this session 

348 game_in_session = session.query(ScrapedGame).filter(ScrapedGame.id == game.id).first() 

349 if not game_in_session: 

350 stats.errors.append(f"Game not found in session: {game.name}") 

351 return 

352 

353 existing_media = ( 

354 session.query(MediaFile).filter(MediaFile.file_hash == file_hash).first() 

355 ) 

356 

357 if existing_media: 

358 # Media already exists - deduplication! 

359 media_file = existing_media 

360 stats.media_files_deduplicated += 1 

361 stats.media_bytes_saved += file_size 

362 else: 

363 # Store in content-addressable store 

364 _, storage_path = self.store.put(source_path, file_hash=file_hash) 

365 

366 # Get media metadata based on type 

367 if media_type == "video": 

368 # Get comprehensive video metadata 

369 video_meta = self._get_video_metadata(storage_path) 

370 width = video_meta["width"] 

371 height = video_meta["height"] 

372 video_codec = video_meta["codec"] 

373 video_bitrate = video_meta["bitrate"] 

374 video_fps = video_meta["fps"] 

375 video_duration = video_meta["duration"] 

376 image_mode = None 

377 has_transparency = None 

378 else: 

379 # Get comprehensive image metadata 

380 image_meta = self._get_image_metadata(storage_path) 

381 width = image_meta["width"] 

382 height = image_meta["height"] 

383 image_mode = image_meta["mode"] 

384 has_transparency = image_meta["has_transparency"] 

385 video_codec = None 

386 video_bitrate = None 

387 video_fps = None 

388 video_duration = None 

389 

390 # Create media file record 

391 media_file = MediaFile( 

392 file_hash=file_hash, 

393 media_type=media_type, 

394 file_path=str(storage_path), 

395 file_size=file_size, 

396 file_format=source_path.suffix.lstrip("."), 

397 width=width, 

398 height=height, 

399 image_mode=image_mode, 

400 has_transparency=has_transparency, 

401 video_codec=video_codec, 

402 video_bitrate=video_bitrate, 

403 video_fps=video_fps, 

404 video_duration=video_duration, 

405 source_url=None, # ARRM doesn't provide URL 

406 source_file_mtime=file_mtime, # Track source file modification time 

407 ) 

408 session.add(media_file) 

409 session.flush() # Assign ID to media_file 

410 stats.media_files_new += 1 

411 

412 # Create link between game and media 

413 # Check if link already exists for THIS media type 

414 # Note: The same file can be linked with different media types 

415 # (e.g., mix and image might be the same file, wheel and marquee, etc.) 

416 existing_link = ( 

417 session.query(GameMediaLink) 

418 .filter( 

419 GameMediaLink.game_id == game_in_session.id, 

420 GameMediaLink.media_type == media_type, 

421 ) 

422 .first() 

423 ) 

424 

425 if not existing_link: 

426 link = GameMediaLink( 

427 game_id=game_in_session.id, 

428 media_file_id=media_file.id, 

429 media_type=media_type, 

430 priority=0, 

431 ) 

432 session.add(link) 

433 media_file.increment_references() 

434 

435 session.commit() 

436 

437 def _get_storage_path(self, file_hash: str, media_type: str, extension: str) -> Path: 

438 """Get storage path for a media file (delegates to ContentStore).""" 

439 return self.store.blob_path(file_hash, extension) 

440 

441 def _get_image_metadata(self, image_path: Path) -> dict: 

442 """Get comprehensive image metadata.""" 

443 try: 

444 from PIL import Image 

445 

446 with Image.open(image_path) as img: 

447 has_transparency = img.mode in ("RGBA", "LA", "PA", "P") 

448 # For P mode, check if there's actually transparency in the palette 

449 if img.mode == "P" and "transparency" not in img.info: 

450 has_transparency = False 

451 

452 return { 

453 "width": img.width, 

454 "height": img.height, 

455 "mode": img.mode, 

456 "has_transparency": has_transparency, 

457 } 

458 except (ImportError, Exception): 

459 return { 

460 "width": None, 

461 "height": None, 

462 "mode": None, 

463 "has_transparency": None, 

464 } 

465 

466 def _get_image_dimensions(self, image_path: Path) -> tuple[int | None, int | None]: 

467 """Get image dimensions (legacy method - use _get_image_metadata instead).""" 

468 metadata = self._get_image_metadata(image_path) 

469 return metadata["width"], metadata["height"] 

470 

471 def _get_video_metadata(self, video_path: Path) -> dict: 

472 """Get comprehensive video metadata using ffprobe.""" 

473 try: 

474 import json 

475 import subprocess 

476 

477 result = subprocess.run( 

478 [ 

479 "ffprobe", 

480 "-v", 

481 "quiet", 

482 "-print_format", 

483 "json", 

484 "-show_streams", 

485 "-select_streams", 

486 "v:0", 

487 str(video_path), 

488 ], 

489 capture_output=True, 

490 text=True, 

491 timeout=5, 

492 ) 

493 

494 if result.returncode == 0: 

495 data = json.loads(result.stdout) 

496 if "streams" in data and len(data["streams"]) > 0: 

497 stream = data["streams"][0] 

498 return { 

499 "width": stream.get("width"), 

500 "height": stream.get("height"), 

501 "codec": stream.get("codec_name"), 

502 "bitrate": int(stream["bit_rate"]) if stream.get("bit_rate") else None, 

503 "fps": stream.get("r_frame_rate"), 

504 "duration": float(stream["duration"]) if stream.get("duration") else None, 

505 } 

506 except Exception: 

507 pass 

508 

509 return { 

510 "width": None, 

511 "height": None, 

512 "codec": None, 

513 "bitrate": None, 

514 "fps": None, 

515 "duration": None, 

516 } 

517 

518 def _get_video_dimensions(self, video_path: Path) -> tuple[int | None, int | None]: 

519 """Get video dimensions using ffprobe (legacy method - use _get_video_metadata instead).""" 

520 metadata = self._get_video_metadata(video_path) 

521 return metadata["width"], metadata["height"] 

522 

523 def _get_media_dimensions( 

524 self, media_path: Path, media_type: str 

525 ) -> tuple[int | None, int | None]: 

526 """Get dimensions for image or video files.""" 

527 if media_type == "video": 

528 return self._get_video_dimensions(media_path) 

529 else: 

530 # For images (boxart, cartridge, image, screenshot, wheel, marquee, manual covers) 

531 return self._get_image_dimensions(media_path) 

532 

533 def _update_game_metadata(self, game: ScrapedGame, new_data: dict) -> None: 

534 """Update existing game with new metadata (smart update).""" 

535 # Update all fields, but only if new data is not None 

536 for key, value in new_data.items(): 

537 if value is not None: 

538 setattr(game, key, value) 

539 

540 def _should_update_game( 

541 self, existing_game: ScrapedGame, new_game_data: dict, new_source_mtime: datetime | None 

542 ) -> bool: 

543 """ 

544 Decide if we should update existing game with new data. 

545 

546 Strategy: 

547 1. If no timestamp on existing game -> always update (legacy data) 

548 2. If new source is newer -> update 

549 3. If new source is older but more complete -> update 

550 4. Otherwise -> skip (keep existing) 

551 """ 

552 # No existing timestamp? Always update (legacy import) 

553 if not existing_game.source_gamelist_mtime: 

554 return True 

555 

556 # New source is newer? Update 

557 if new_source_mtime and new_source_mtime > existing_game.source_gamelist_mtime: 

558 return True 

559 

560 # New source is same age or older, but has more complete data? 

561 if self._is_more_complete(new_game_data, existing_game): 

562 return True 

563 

564 # Otherwise, keep existing (it's newer or equally complete) 

565 return False 

566 

567 def _is_more_complete(self, new_data: dict, existing_game: ScrapedGame) -> bool: 

568 """ 

569 Check if new data is more complete than existing. 

570 

571 Counts non-null fields in both and compares. 

572 """ 

573 important_fields = [ 

574 "name", 

575 "description", 

576 "rating", 

577 "release_date", 

578 "developer", 

579 "publisher", 

580 "genre", 

581 "players", 

582 "region", 

583 "favorite", 

584 "hidden", 

585 "kidgame", 

586 "playcount", 

587 "lastplayed", 

588 "sortname", 

589 ] 

590 

591 new_filled = sum( 

592 1 for field in important_fields if new_data.get(field) and str(new_data[field]).strip() 

593 ) 

594 

595 existing_filled = sum( 

596 1 

597 for field in important_fields 

598 if getattr(existing_game, field, None) and str(getattr(existing_game, field)).strip() 

599 ) 

600 

601 # Consider "more complete" if at least 2 more fields are filled 

602 return new_filled > existing_filled + 1 

603 

604 def _extract_system_from_path(self, path: str) -> str | None: 

605 """Extract system name from file path (if possible).""" 

606 # This is a simple heuristic - you might want to make this configurable 

607 # For now, we'll leave it None and let the user specify 

608 return None 

609 

610 def _parse_int(self, value: str | None) -> int | None: 

611 """Safely parse integer.""" 

612 if value is None: 

613 return None 

614 try: 

615 return int(value) 

616 except (ValueError, TypeError): 

617 return None 

618 

619 def _parse_float(self, value: str | None) -> float | None: 

620 """Safely parse float.""" 

621 if value is None: 

622 return None 

623 try: 

624 return float(value) 

625 except (ValueError, TypeError): 

626 return None 

627 

628 

629def print_import_stats(stats: ImportStats) -> None: 

630 """Print import statistics in a nice format.""" 

631 from rich.panel import Panel 

632 from rich.table import Table 

633 

634 # Games table 

635 games_table = Table(title="Games") 

636 games_table.add_column("Metric", style="cyan") 

637 games_table.add_column("Count", style="green", justify="right") 

638 

639 games_table.add_row("Processed", str(stats.games_processed)) 

640 games_table.add_row("Imported", str(stats.games_imported)) 

641 games_table.add_row("Updated", str(stats.games_updated)) 

642 games_table.add_row("Skipped", str(stats.games_skipped)) 

643 

644 console.print(games_table) 

645 

646 # Media table 

647 media_table = Table(title="Media Files") 

648 media_table.add_column("Metric", style="cyan") 

649 media_table.add_column("Count", style="green", justify="right") 

650 

651 media_table.add_row("Total Media Links", str(stats.media_files_total)) 

652 media_table.add_row("New Files", str(stats.media_files_new)) 

653 media_table.add_row("Deduplicated", str(stats.media_files_deduplicated)) 

654 

655 console.print(media_table) 

656 

657 # Storage savings 

658 if stats.media_bytes_saved > 0: 

659 savings_mb = stats.media_bytes_saved / (1024 * 1024) 

660 total_mb = stats.media_bytes_total / (1024 * 1024) 

661 savings_pct = stats.media_bytes_saved / stats.media_bytes_total * 100 

662 

663 console.print( 

664 Panel( 

665 f"[green]Storage Savings:[/green]\n" 

666 f" Saved: {savings_mb:.1f} MB\n" 

667 f" Total: {total_mb:.1f} MB\n" 

668 f" Deduplication: {savings_pct:.1f}%", 

669 title="💾 Deduplication", 

670 ) 

671 ) 

672 

673 # Errors 

674 if stats.errors: 

675 console.print(f"\n[yellow]⚠ {len(stats.errors)} errors occurred:[/yellow]") 

676 for error in stats.errors[:10]: # Show first 10 

677 console.print(f" • {error}") 

678 if len(stats.errors) > 10: 

679 console.print(f" ... and {len(stats.errors) - 10} more")