Coverage for src/romfarmer/metadata/database.py: 39%

510 statements  

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

1""" 

2Database models for metadata management. 

3 

4This module defines SQLAlchemy models for storing scraped game metadata 

5and media files with content-addressable storage for deduplication. 

6""" 

7 

8from datetime import datetime 

9from enum import Enum 

10from pathlib import Path 

11from typing import Optional 

12 

13from sqlalchemy import ( 

14 Boolean, 

15 Column, 

16 DateTime, 

17 Float, 

18 ForeignKey, 

19 Index, 

20 Integer, 

21 String, 

22 Text, 

23 UniqueConstraint, 

24) 

25from sqlalchemy.orm import declarative_base, relationship 

26 

27Base = declarative_base() 

28 

29 

30class MediaType(str, Enum): 

31 """Supported media types from ScreenScraper/ARRM.""" 

32 

33 IMAGE = "image" # Title screen 

34 BOXART = "boxart" # Box art 

35 SCREENSHOT = "screenshot" # In-game screenshot 

36 CARTRIDGE = "cartridge" # Cartridge/disc art 

37 WHEEL = "wheel" # Logo/wheel art 

38 MARQUEE = "marquee" # Marquee/banner 

39 MIX = "mix" # Composite image (ARRM-generated) 

40 VIDEO = "video" # Video preview 

41 MANUAL = "manual" # PDF manual 

42 

43 @classmethod 

44 def all_types(cls) -> list[str]: 

45 """Return all media types.""" 

46 return [t.value for t in cls] 

47 

48 @classmethod 

49 def standard_types(cls) -> list[str]: 

50 """Return standard media types (excluding manuals and videos).""" 

51 return [ 

52 cls.IMAGE.value, 

53 cls.BOXART.value, 

54 cls.SCREENSHOT.value, 

55 cls.WHEEL.value, 

56 cls.MIX.value, 

57 ] 

58 

59 @classmethod 

60 def minimal_types(cls) -> list[str]: 

61 """Return minimal media types (just mix image).""" 

62 return [cls.MIX.value] 

63 

64 

65class ScrapedGame(Base): 

66 """ 

67 Scraped game metadata from ScreenScraper.fr (via ARRM). 

68 

69 This model stores comprehensive game information including metadata 

70 and links to deduplicated media files. Games are tracked by their 

71 hashes, allowing files to be reorganized without losing metadata. 

72 """ 

73 

74 __tablename__ = "scraped_games" 

75 

76 # Primary key 

77 id = Column(Integer, primary_key=True) 

78 

79 # File identifiers (for matching ROMs) 

80 md5 = Column(String(32), index=True) # Primary matching hash 

81 crc32 = Column(String(8), index=True) 

82 sha1 = Column(String(40)) 

83 filename = Column(String(512)) # Original filename 

84 

85 # ScreenScraper IDs 

86 game_id = Column(Integer) # ScreenScraper game ID 

87 rom_id = Column(Integer) # ScreenScraper ROM ID 

88 

89 # System information 

90 system = Column(String(128), index=True) # System name (e.g., "nes") 

91 

92 # Source tracking (for smart updates) 

93 source_gamelist_path = Column(String(1024)) # Path to source gamelist.xml 

94 source_gamelist_mtime = Column(DateTime) # Modification time of source gamelist 

95 

96 # Game metadata 

97 name = Column(String(512)) # Display name 

98 sortname = Column(String(512)) # Sort name 

99 description = Column(Text) # Game description 

100 rating = Column(Float) # Rating (0.0-1.0) 

101 release_date = Column(String(32)) # Release date (YYYYMMDD format) 

102 developer = Column(String(256)) # Developer 

103 publisher = Column(String(256)) # Publisher 

104 genre = Column(String(256)) # Genre 

105 genre_id = Column(Integer) # ScreenScraper genre ID 

106 players = Column(String(32)) # Player count (e.g., "1-2") 

107 region = Column(String(128)) # Region codes (e.g., "us,wor") 

108 language = Column(String(128)) # Language codes (e.g., "en,ja") 

109 hidden = Column(Boolean, default=False) # EmulationStation hidden flag 

110 favorite = Column(Boolean, default=False) # EmulationStation favorite flag 

111 kidgame = Column(Boolean, default=False) # EmulationStation kid-friendly flag 

112 playcount = Column(Integer, default=0) # Number of times played 

113 lastplayed = Column(DateTime) # Last played timestamp 

114 

115 # Metadata versioning 

116 metadata_version = Column(Integer, default=1) # Version for updates 

117 scraped_at = Column(DateTime, default=datetime.utcnow) # First scraped 

118 updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) 

119 source = Column(String(64), default="arrm") # Metadata source 

120 

121 # Relationships 

122 media_links = relationship( 

123 "GameMediaLink", 

124 back_populates="game", 

125 cascade="all, delete-orphan", 

126 ) 

127 transformations = relationship( 

128 "ROMTransformation", 

129 back_populates="game", 

130 cascade="all, delete-orphan", 

131 ) 

132 

133 # Indexes for fast lookups 

134 __table_args__ = ( 

135 Index("idx_hash_lookup", "md5", "crc32", "sha1"), 

136 Index("idx_system_name", "system", "name"), 

137 ) 

138 

139 def __repr__(self) -> str: 

140 return f"<ScrapedGame(name='{self.name}', system='{self.system}', md5='{self.md5}')>" 

141 

142 

143class MediaFile(Base): 

144 """ 

145 Deduplicated media file storage. 

146 

147 Media files are stored using content-addressable storage (like Git). 

148 Each unique file is stored once based on its hash, and multiple games 

149 can reference the same media file. This provides: 

150 - Deduplication: Clones share the same media 

151 - Integrity: Files verified by hash 

152 - Efficiency: Reduced storage and bandwidth 

153 """ 

154 

155 __tablename__ = "media_files" 

156 

157 # Primary key 

158 id = Column(Integer, primary_key=True) 

159 

160 # Content addressing 

161 file_hash = Column(String(64), unique=True, nullable=False, index=True) 

162 media_type = Column(String(32), nullable=False, index=True) 

163 

164 # File storage 

165 file_path = Column(String(1024), nullable=False) # Path in storage 

166 file_size = Column(Integer, nullable=False) # Size in bytes 

167 file_format = Column(String(32)) # Extension (png, jpg, mp4, pdf) 

168 

169 # Image metadata (for images only) 

170 width = Column(Integer) 

171 height = Column(Integer) 

172 image_mode = Column(String(16)) # Color mode (RGB, RGBA, L, etc.) 

173 has_transparency = Column(Boolean) # True if image has alpha channel 

174 

175 # Video metadata (for videos only) 

176 video_codec = Column(String(32)) # Video codec (h264, vp9, etc.) 

177 video_bitrate = Column(Integer) # Video bitrate in bits/second 

178 video_fps = Column(String(16)) # Frame rate (e.g., "30/1", "59.94") 

179 video_duration = Column(Float) # Duration in seconds 

180 

181 # Source tracking 

182 source_url = Column(String(1024)) # Original URL from ScreenScraper 

183 source_file_mtime = Column(DateTime) # Modification time of source file 

184 uploaded_at = Column(DateTime, default=datetime.utcnow) 

185 

186 # Reference counting (for cleanup) 

187 reference_count = Column(Integer, default=0) 

188 

189 # Relationships 

190 game_links = relationship( 

191 "GameMediaLink", 

192 back_populates="media_file", 

193 cascade="all, delete-orphan", 

194 ) 

195 

196 # Indexes 

197 __table_args__ = (Index("idx_media_type_hash", "media_type", "file_hash"),) 

198 

199 def __repr__(self) -> str: 

200 return f"<MediaFile(type='{self.media_type}', hash='{self.file_hash[:8]}...', refs={self.reference_count})>" 

201 

202 @property 

203 def storage_path(self) -> Path: 

204 """Get the storage path for this media file.""" 

205 return Path(self.file_path) 

206 

207 def increment_references(self) -> None: 

208 """Increment the reference count.""" 

209 self.reference_count += 1 

210 

211 def decrement_references(self) -> None: 

212 """Decrement the reference count.""" 

213 if self.reference_count > 0: 

214 self.reference_count -= 1 

215 

216 

217class GameMediaLink(Base): 

218 """ 

219 Many-to-many relationship between games and media files. 

220 

221 This table links games to their media files, allowing: 

222 - One game to have multiple media types 

223 - Multiple games to share the same media file (deduplication) 

224 - Priority ordering when multiple media of same type exist 

225 """ 

226 

227 __tablename__ = "game_media_links" 

228 

229 # Composite primary key 

230 id = Column(Integer, primary_key=True) 

231 game_id = Column(Integer, ForeignKey("scraped_games.id"), nullable=False) 

232 media_file_id = Column(Integer, ForeignKey("media_files.id"), nullable=False) 

233 

234 # Media role 

235 media_type = Column(String(32), nullable=False) # Type for this link 

236 priority = Column(Integer, default=0) # Priority when multiple exist 

237 

238 # Relationships 

239 game = relationship("ScrapedGame", back_populates="media_links") 

240 media_file = relationship("MediaFile", back_populates="game_links") 

241 

242 # Constraints 

243 # Allow same media file to be used with different media types 

244 # (e.g., mix and image can be the same file) 

245 __table_args__ = ( 

246 UniqueConstraint("game_id", "media_file_id", "media_type", name="uq_game_media_type"), 

247 Index("idx_game_media_type", "game_id", "media_type"), 

248 ) 

249 

250 def __repr__(self) -> str: 

251 return f"<GameMediaLink(game_id={self.game_id}, type='{self.media_type}', priority={self.priority})>" 

252 

253 

254class DatGameEntry(Base): 

255 """ 

256 Game entry from DAT files (No-Intro, Redump, FBNeo, MAME). 

257 

258 Stores parent-clone relationships, hardware info, and video specs 

259 that complement the scraped metadata from ScreenScraper. 

260 """ 

261 

262 __tablename__ = "dat_games" 

263 

264 # Primary key 

265 id = Column(Integer, primary_key=True) 

266 

267 # ROM identification 

268 name = Column(String(256), nullable=False, index=True) # ROM name (e.g., "sf2ce") 

269 description = Column(String(1024)) # Full title 

270 

271 # Parent-clone relationships 

272 cloneof = Column(String(256), index=True) # Parent ROM name 

273 romof = Column(String(256)) # ROM parent (for merged sets) 

274 

275 # Temporal info 

276 year = Column(String(8)) 

277 manufacturer = Column(String(256)) 

278 

279 # Hardware/driver info 

280 sourcefile = Column(String(256), index=True) # Driver source (e.g., "capcom/d_cps1.cpp") 

281 hardware = Column(String(64), index=True) # Extracted hardware name (e.g., "cps1") 

282 hardware_family = Column(String(64), index=True) # Hardware family (e.g., "capcom") 

283 driver_status = Column(String(32), default="good") # good, imperfect, preliminary 

284 

285 # Video specs 

286 video_type = Column(String(16)) # raster, vector 

287 video_orientation = Column(String(16)) # horizontal, vertical 

288 video_width = Column(Integer) 

289 video_height = Column(Integer) 

290 video_aspect_x = Column(Integer) 

291 video_aspect_y = Column(Integer) 

292 video_refresh = Column(Float) 

293 

294 # Metadata 

295 comment = Column(String(256)) # Bootleg, Prototype, etc. 

296 category = Column(String(128)) 

297 

298 # ROM identification (first ROM) 

299 rom_crc = Column(String(8), index=True) 

300 rom_size = Column(Integer) 

301 

302 # Source DAT info 

303 dat_name = Column(String(256)) 

304 dat_type = Column(String(32), index=True) # fbneo, mame, nointro, redump 

305 

306 # Timestamps 

307 imported_at = Column(DateTime, default=datetime.utcnow) 

308 

309 # Indexes for common queries 

310 __table_args__ = ( 

311 Index("idx_dat_hardware", "dat_type", "hardware"), 

312 Index("idx_dat_cloneof", "dat_type", "cloneof"), 

313 UniqueConstraint("dat_type", "name", name="uq_dat_game"), 

314 ) 

315 

316 def __repr__(self) -> str: 

317 return f"<DatGameEntry(name='{self.name}', hardware='{self.hardware}', cloneof='{self.cloneof}')>" 

318 

319 @property 

320 def is_parent(self) -> bool: 

321 return self.cloneof is None 

322 

323 @property 

324 def is_clone(self) -> bool: 

325 return self.cloneof is not None 

326 

327 @property 

328 def is_bootleg(self) -> bool: 

329 if self.comment and "bootleg" in self.comment.lower(): 

330 return True 

331 if self.description and "bootleg" in self.description.lower(): 

332 return True 

333 return False 

334 

335 @property 

336 def resolution(self) -> str: 

337 if self.video_width and self.video_height: 

338 return f"{self.video_width}x{self.video_height}" 

339 return "" 

340 

341 @property 

342 def aspect_ratio(self) -> str: 

343 if self.video_aspect_x and self.video_aspect_y: 

344 return f"{self.video_aspect_x}:{self.video_aspect_y}" 

345 return "" 

346 

347 

348class ExternalScore(Base): 

349 """ 

350 Game scores fetched from external sources (MobyGames, RAWG). 

351 

352 Provides higher-quality, broader coverage than ScreenScraper ratings. 

353 - critic_score: Professional critic aggregate 0-100 (e.g. Metacritic via RAWG) 

354 - user_score: Community score 0-10 (MobyGames moby_score) 

355 

356 Both are stored raw; downstream consumers normalize to 0.0-1.0 as needed. 

357 """ 

358 

359 __tablename__ = "external_scores" 

360 

361 id = Column(Integer, primary_key=True) 

362 

363 # Platform (rom-farmer name, e.g. "ps2", "snes") 

364 platform = Column(String(64), nullable=False, index=True) 

365 

366 # Canonical title from the source 

367 title = Column(String(512), nullable=False) 

368 

369 # Lowercase, punctuation-stripped title for fuzzy matching 

370 normalized_title = Column(String(512), nullable=False, index=True) 

371 

372 # Scores (NULL = not available from this source) 

373 critic_score = Column(Integer) # 0-100, professional critic aggregate 

374 user_score = Column(Float) # 0-10, community/user score 

375 vote_count = Column(Integer) # Number of ratings behind user_score 

376 

377 # Source attribution 

378 source = Column(String(32), nullable=False) # "mobygames" | "rawg" 

379 source_id = Column(String(64)) # Source's internal game ID 

380 url = Column(String(1024)) 

381 

382 # Enrichment (from the same MobyGames "normal" format payload, no extra API cost) 

383 description = Column(Text) # Full HTML game description 

384 genres = Column(String(512)) # Comma-joined genre names 

385 release_date = Column(String(32)) # First release date for this platform (YYYY or YYYY-MM-DD) 

386 official_url = Column(String(1024)) 

387 cover_url = Column(String(1024)) # Box art image URL 

388 screenshot_urls = Column(Text) # JSON-encoded list of screenshot image URLs 

389 

390 fetched_at = Column(DateTime, nullable=False, default=datetime.utcnow) 

391 

392 __table_args__ = ( 

393 UniqueConstraint("platform", "source", "source_id", name="uq_external_score"), 

394 Index("idx_ext_platform_title", "platform", "normalized_title"), 

395 ) 

396 

397 def __repr__(self) -> str: 

398 return ( 

399 f"<ExternalScore(platform='{self.platform}', title='{self.title}', " 

400 f"source='{self.source}', user_score={self.user_score})>" 

401 ) 

402 

403 @property 

404 def best_score_normalized(self) -> float | None: 

405 """Return the best available score normalized to 0.0-1.0.""" 

406 if self.critic_score is not None: 

407 return self.critic_score / 100.0 

408 if self.user_score is not None: 

409 return self.user_score / 10.0 

410 return None 

411 

412 

413class MetadataDatabase: 

414 """ 

415 High-level interface for metadata database operations. 

416 

417 This class provides convenience methods for: 

418 - Importing ARRM gamelist.xml files 

419 - Storing and retrieving game metadata 

420 - Managing deduplicated media files 

421 - Generating gamelist.xml files 

422 - Smart updates (keep old data, replace with better) 

423 """ 

424 

425 def __init__(self, db_path: Path): 

426 """ 

427 Initialize metadata database. 

428 

429 Args: 

430 db_path: Path to SQLite database file 

431 """ 

432 from sqlalchemy import create_engine 

433 from sqlalchemy.orm import sessionmaker 

434 

435 self.db_path = db_path 

436 self.engine = create_engine(f"sqlite:///{db_path}") 

437 Base.metadata.create_all(self.engine) 

438 self.Session = sessionmaker(bind=self.engine) 

439 

440 def get_session(self): 

441 """Get a new database session.""" 

442 return self.Session() 

443 

444 def find_game_by_hash( 

445 self, 

446 md5: str | None = None, 

447 crc32: str | None = None, 

448 sha1: str | None = None, 

449 ) -> ScrapedGame | None: 

450 """ 

451 Find a game by any of its hashes. 

452 

453 Args: 

454 md5: MD5 hash 

455 crc32: CRC32 hash 

456 sha1: SHA1 hash 

457 

458 Returns: 

459 ScrapedGame if found, None otherwise (with relationships loaded) 

460 """ 

461 from sqlalchemy.orm import joinedload 

462 

463 with self.get_session() as session: 

464 query = session.query(ScrapedGame).options( 

465 joinedload(ScrapedGame.media_links).joinedload(GameMediaLink.media_file) 

466 ) 

467 

468 if md5: 

469 result = query.filter(ScrapedGame.md5 == md5).first() 

470 if result: 

471 # Force load relationships before detaching 

472 _ = result.media_links # Trigger lazy load 

473 for link in result.media_links: 

474 _ = link.media_file # Ensure nested relationships loaded 

475 session.expunge(result) # Detach from session but keep data 

476 return result 

477 

478 if crc32: 

479 result = query.filter(ScrapedGame.crc32 == crc32).first() 

480 if result: 

481 # Force load relationships before detaching 

482 _ = result.media_links 

483 for link in result.media_links: 

484 _ = link.media_file 

485 session.expunge(result) 

486 return result 

487 

488 if sha1: 

489 result = query.filter(ScrapedGame.sha1 == sha1).first() 

490 if result: 

491 # Force load relationships before detaching 

492 _ = result.media_links 

493 for link in result.media_links: 

494 _ = link.media_file 

495 session.expunge(result) 

496 return result 

497 

498 return None 

499 

500 def find_or_create_media( 

501 self, 

502 file_hash: str, 

503 media_type: str, 

504 file_path: Path, 

505 file_size: int, 

506 **kwargs, 

507 ) -> MediaFile: 

508 """ 

509 Find existing media file or create new one. 

510 

511 This implements content-addressable storage - if a file with 

512 the same hash already exists, we reuse it (deduplication). 

513 

514 Args: 

515 file_hash: Content hash of the file 

516 media_type: Type of media (image, boxart, etc.) 

517 file_path: Path where file is stored 

518 file_size: Size in bytes 

519 **kwargs: Additional metadata (width, height, etc.) 

520 

521 Returns: 

522 MediaFile (existing or newly created) 

523 """ 

524 with self.get_session() as session: 

525 # Try to find existing media 

526 media = session.query(MediaFile).filter(MediaFile.file_hash == file_hash).first() 

527 

528 if media: 

529 # Existing media found - increment references 

530 media.increment_references() 

531 session.commit() 

532 return media 

533 

534 # Create new media file 

535 media = MediaFile( 

536 file_hash=file_hash, 

537 media_type=media_type, 

538 file_path=str(file_path), 

539 file_size=file_size, 

540 file_format=file_path.suffix.lstrip("."), 

541 **kwargs, 

542 ) 

543 session.add(media) 

544 session.commit() 

545 return media 

546 

547 def get_game_media( 

548 self, 

549 game: ScrapedGame, 

550 media_types: list[str] | None = None, 

551 ) -> dict[str, MediaFile]: 

552 """ 

553 Get media files for a game, optionally filtered by type. 

554 

555 Args: 

556 game: Game to get media for (should have media_links loaded) 

557 media_types: List of media types to include (None = all) 

558 

559 Returns: 

560 Dictionary mapping media type to MediaFile 

561 """ 

562 result = {} 

563 

564 for link in game.media_links: 

565 if media_types is None or link.media_type in media_types: 

566 result[link.media_type] = link.media_file 

567 

568 return result 

569 

570 def compression_ratio_samples( 

571 self, platform: str, tool: str, max_ratio: float = 1.5 

572 ) -> tuple[float, int] | None: 

573 """``(sum(final)/sum(source), n)`` from ``rom_transformations`` for a platform/tool. 

574 

575 Joins ``scraped_games.system`` for the platform and filters out corrupt 

576 rows (``ratio > max_ratio`` — the table holds xbox360 rows at 13×). 

577 Only formats the legacy pipeline recorded exist (chd, xiso). 

578 """ 

579 from sqlalchemy import func 

580 

581 from .transformation import ROMTransformation 

582 

583 fmt = {"chd": "chd", "xiso": "xiso"}.get(tool) 

584 if fmt is None: 

585 return None 

586 with self.get_session() as session: 

587 q = ( 

588 session.query( 

589 func.sum(ROMTransformation.final_file_size), 

590 func.sum(ROMTransformation.source_file_size), 

591 func.count(ROMTransformation.id), 

592 ) 

593 .join(ScrapedGame, ROMTransformation.game_id == ScrapedGame.id) 

594 .filter( 

595 ScrapedGame.system == platform, 

596 ROMTransformation.final_format == fmt, 

597 ROMTransformation.source_file_size > 0, 

598 ROMTransformation.final_file_size > 0, 

599 ROMTransformation.final_file_size 

600 <= ROMTransformation.source_file_size * max_ratio, 

601 ) 

602 ) 

603 out_b, in_b, n = q.first() or (None, None, 0) 

604 if not n or not in_b: 

605 return None 

606 return float(out_b) / float(in_b), int(n) 

607 

608 def get_average_compression_ratio( 

609 self, platform: str | None = None, output_format: str | None = None, min_samples: int = 5 

610 ) -> float | None: 

611 """ 

612 Calculate average compression ratio from historical transformations. 

613 

614 Queries the rom_transformations table to find the average ratio of 

615 final_file_size / source_file_size for a given platform and format. 

616 

617 Args: 

618 platform: Platform name to filter by (e.g., "saturn", "psx") 

619 output_format: Output format to filter by (e.g., "chd", "cso") 

620 min_samples: Minimum number of samples required for reliable average 

621 

622 Returns: 

623 Average compression ratio (0.0-1.0), or None if insufficient data 

624 

625 Example: 

626 ratio = db.get_average_compression_ratio("saturn", "chd") 

627 # Returns 0.68 meaning CHD is 68% of source ISO size 

628 """ 

629 from sqlalchemy import func 

630 

631 from .transformation import ROMTransformation 

632 

633 with self.get_session() as session: 

634 query = session.query( 

635 func.avg( 

636 ROMTransformation.final_file_size * 1.0 / ROMTransformation.source_file_size 

637 ).label("avg_ratio"), 

638 func.count(ROMTransformation.id).label("sample_count"), 

639 ) 

640 

641 # Filter out transformations with missing size data 

642 query = query.filter( 

643 ROMTransformation.source_file_size > 0, ROMTransformation.final_file_size > 0 

644 ) 

645 

646 # Apply platform filter (if specified) 

647 if platform: 

648 # Join with ScrapedGame to filter by system 

649 query = query.join(ScrapedGame, ROMTransformation.game_id == ScrapedGame.id).filter( 

650 ScrapedGame.system == platform 

651 ) 

652 

653 # Apply format filter (if specified) 

654 if output_format: 

655 query = query.filter(ROMTransformation.final_format == output_format) 

656 

657 result = query.first() 

658 

659 if result and result.sample_count >= min_samples: 

660 return result.avg_ratio 

661 

662 return None 

663 

664 def get_stats(self) -> dict: 

665 """ 

666 Get database statistics. 

667 

668 Returns: 

669 Dictionary with counts and sizes 

670 """ 

671 with self.get_session() as session: 

672 total_games = session.query(ScrapedGame).count() 

673 total_media = session.query(MediaFile).count() 

674 total_links = session.query(GameMediaLink).count() 

675 

676 # Calculate total media size 

677 total_size = session.query(MediaFile).with_entities(MediaFile.file_size).all() 

678 total_bytes = sum(row[0] for row in total_size if row[0]) 

679 

680 # Calculate deduplication savings 

681 # If we had no deduplication, each link would need a separate file 

682 potential_size = total_links * (total_bytes / max(total_media, 1)) 

683 savings = potential_size - total_bytes if total_media > 0 else 0 

684 savings_percent = (savings / potential_size * 100) if potential_size > 0 else 0 

685 

686 return { 

687 "total_games": total_games, 

688 "total_media_files": total_media, 

689 "total_media_links": total_links, 

690 "total_size_bytes": total_bytes, 

691 "total_size_mb": total_bytes / (1024 * 1024), 

692 "potential_size_bytes": potential_size, 

693 "savings_bytes": savings, 

694 "savings_mb": savings / (1024 * 1024), 

695 "savings_percent": savings_percent, 

696 "avg_references_per_file": (total_links / total_media if total_media > 0 else 0), 

697 } 

698 

699 def get_games_for_platform(self, platform: str) -> list[ScrapedGame]: 

700 """ 

701 Get all games for a specific platform/system. 

702 

703 Args: 

704 platform: System name (e.g., "megadrive", "psx", "snes") 

705 

706 Returns: 

707 List of ScrapedGame objects for that platform 

708 """ 

709 with self.get_session() as session: 

710 games = session.query(ScrapedGame).filter(ScrapedGame.system == platform).all() 

711 

712 # Detach from session 

713 for g in games: 

714 session.expunge(g) 

715 

716 return games 

717 

718 def search_games( 

719 self, 

720 platform: str | None = None, 

721 query: str | None = None, 

722 genre: str | None = None, 

723 developer: str | None = None, 

724 publisher: str | None = None, 

725 min_rating: float | None = None, 

726 limit: int = 50, 

727 deduplicate: bool = True, 

728 title_only: bool = False, 

729 ) -> list[ScrapedGame]: 

730 """ 

731 Search for games with flexible filtering. 

732 

733 Args: 

734 platform: Filter by system (e.g., "megadrive", "psx") 

735 query: Search in name/description (fuzzy) 

736 genre: Filter by genre (partial match) 

737 developer: Filter by developer (partial match) 

738 publisher: Filter by publisher (partial match) 

739 min_rating: Minimum rating (0.0-1.0) 

740 limit: Maximum results to return 

741 deduplicate: If True, show only one entry per game_id (default True) 

742 title_only: If True, only search in title, not description (default False) 

743 

744 Returns: 

745 List of matching ScrapedGame objects 

746 """ 

747 with self.get_session() as session: 

748 q = session.query(ScrapedGame) 

749 

750 if platform: 

751 q = q.filter(ScrapedGame.system == platform) 

752 

753 if query: 

754 search_pattern = f"%{query}%" 

755 if title_only: 

756 # Only search in name - more precise 

757 q = q.filter(ScrapedGame.name.ilike(search_pattern)) 

758 else: 

759 # Search in name and description 

760 q = q.filter( 

761 (ScrapedGame.name.ilike(search_pattern)) 

762 | (ScrapedGame.description.ilike(search_pattern)) 

763 ) 

764 

765 if genre: 

766 q = q.filter(ScrapedGame.genre.ilike(f"%{genre}%")) 

767 

768 if developer: 

769 q = q.filter(ScrapedGame.developer.ilike(f"%{developer}%")) 

770 

771 if publisher: 

772 q = q.filter(ScrapedGame.publisher.ilike(f"%{publisher}%")) 

773 

774 if min_rating is not None: 

775 q = q.filter(ScrapedGame.rating >= min_rating) 

776 

777 # Order by rating (best first), then name 

778 q = q.order_by(ScrapedGame.rating.desc().nullslast(), ScrapedGame.name) 

779 

780 # Get more results if deduplicating (we'll filter down) 

781 fetch_limit = limit * 5 if deduplicate else limit 

782 all_games = q.limit(fetch_limit).all() 

783 

784 if deduplicate: 

785 # Keep only one entry per game_id (preferring US/World regions) 

786 games = [] 

787 region_priority = ["us", "wor", "eu", "jp"] # Preference order 

788 

789 # First pass: group by game_id 

790 by_game_id = {} 

791 for g in all_games: 

792 gid = g.game_id or g.name # Fallback to name if no game_id 

793 if gid not in by_game_id: 

794 by_game_id[gid] = [] 

795 by_game_id[gid].append(g) 

796 

797 # Second pass: pick best variant per game_id 

798 for _gid, variants in by_game_id.items(): 

799 if len(games) >= limit: 

800 break 

801 

802 # Sort variants by region priority 

803 def region_sort_key(game): 

804 region = (game.region or "").lower() 

805 for i, r in enumerate(region_priority): 

806 if r in region: 

807 return i 

808 return len(region_priority) # Unknown regions last 

809 

810 variants.sort(key=region_sort_key) 

811 best = variants[0] 

812 session.expunge(best) 

813 games.append(best) 

814 else: 

815 games = all_games[:limit] 

816 for g in games: 

817 session.expunge(g) 

818 

819 return games 

820 

821 def get_game_variants( 

822 self, 

823 game_id: int, 

824 platform: str | None = None, 

825 ) -> list[ScrapedGame]: 

826 """ 

827 Get all regional/revision variants of a game by its game_id. 

828 

829 Args: 

830 game_id: ScreenScraper game ID 

831 platform: Optional system filter 

832 

833 Returns: 

834 List of all variants (different regions, revisions) 

835 """ 

836 with self.get_session() as session: 

837 q = session.query(ScrapedGame).filter(ScrapedGame.game_id == game_id) 

838 

839 if platform: 

840 q = q.filter(ScrapedGame.system == platform) 

841 

842 q = q.order_by(ScrapedGame.region, ScrapedGame.name) 

843 

844 games = q.all() 

845 for g in games: 

846 session.expunge(g) 

847 

848 return games 

849 

850 def get_game_by_name( 

851 self, 

852 name: str, 

853 platform: str | None = None, 

854 ) -> ScrapedGame | None: 

855 """ 

856 Find a game by exact or close name match. 

857 

858 Args: 

859 name: Game name to search for 

860 platform: Optional system filter 

861 

862 Returns: 

863 Best matching ScrapedGame, or None 

864 """ 

865 with self.get_session() as session: 

866 q = session.query(ScrapedGame) 

867 

868 # Try exact match first 

869 if platform: 

870 q = q.filter(ScrapedGame.system == platform) 

871 

872 exact = q.filter(ScrapedGame.name == name).first() 

873 if exact: 

874 session.expunge(exact) 

875 return exact 

876 

877 # Try case-insensitive 

878 result = q.filter(ScrapedGame.name.ilike(name)).first() 

879 if result: 

880 session.expunge(result) 

881 return result 

882 

883 # Try partial match 

884 result = q.filter(ScrapedGame.name.ilike(f"%{name}%")).first() 

885 if result: 

886 session.expunge(result) 

887 return result 

888 

889 return None 

890 

891 def get_platforms(self) -> list[dict]: 

892 """ 

893 Get all platforms with game counts. 

894 

895 Returns: 

896 List of dicts with platform name and count 

897 """ 

898 from sqlalchemy import func 

899 

900 with self.get_session() as session: 

901 results = ( 

902 session.query(ScrapedGame.system, func.count(ScrapedGame.id).label("count")) 

903 .group_by(ScrapedGame.system) 

904 .order_by(func.count(ScrapedGame.id).desc()) 

905 .all() 

906 ) 

907 

908 return [{"platform": r[0], "game_count": r[1]} for r in results] 

909 

910 def get_genres(self, platform: str | None = None) -> list[dict]: 

911 """ 

912 Get all genres with game counts. 

913 

914 Args: 

915 platform: Optional platform filter 

916 

917 Returns: 

918 List of dicts with genre and count 

919 """ 

920 from sqlalchemy import func 

921 

922 with self.get_session() as session: 

923 q = session.query(ScrapedGame.genre, func.count(ScrapedGame.id).label("count")) 

924 

925 if platform: 

926 q = q.filter(ScrapedGame.system == platform) 

927 

928 results = ( 

929 q.filter(ScrapedGame.genre.isnot(None), ScrapedGame.genre != "") 

930 .group_by(ScrapedGame.genre) 

931 .order_by(func.count(ScrapedGame.id).desc()) 

932 .all() 

933 ) 

934 

935 return [{"genre": r[0], "game_count": r[1]} for r in results] 

936 

937 # ==================== DAT FILE METHODS ==================== 

938 

939 def import_dat_file(self, dat_path: Path, replace: bool = False) -> dict: 

940 """ 

941 Import games from a DAT file into the database. 

942 

943 Args: 

944 dat_path: Path to DAT file 

945 replace: If True, replace existing entries for this DAT 

946 

947 Returns: 

948 Dict with import statistics 

949 """ 

950 import re 

951 

952 from .dat_parser import DatParser 

953 

954 parser = DatParser(dat_path) 

955 

956 stats = { 

957 "dat_name": None, 

958 "dat_type": None, 

959 "total": 0, 

960 "imported": 0, 

961 "updated": 0, 

962 "skipped": 0, 

963 } 

964 

965 with self.get_session() as session: 

966 # Delete existing entries if replacing 

967 if replace and parser.dat_name: 

968 deleted = ( 

969 session.query(DatGameEntry) 

970 .filter(DatGameEntry.dat_name == parser.dat_name) 

971 .delete() 

972 ) 

973 session.commit() 

974 stats["deleted"] = deleted 

975 

976 for game in parser.parse(): 

977 stats["total"] += 1 

978 stats["dat_name"] = parser.dat_name 

979 stats["dat_type"] = parser.dat_type 

980 

981 # Check if entry already exists 

982 existing = ( 

983 session.query(DatGameEntry) 

984 .filter( 

985 DatGameEntry.dat_type == parser.dat_type, DatGameEntry.name == game.name 

986 ) 

987 .first() 

988 ) 

989 

990 if existing and not replace: 

991 stats["skipped"] += 1 

992 continue 

993 

994 # Extract hardware from sourcefile 

995 hardware = None 

996 hardware_family = None 

997 if game.sourcefile: 

998 match = re.search(r"d_(\w+)\.cpp", game.sourcefile) 

999 if match: 

1000 hardware = match.group(1) 

1001 parts = game.sourcefile.split("/") 

1002 if len(parts) >= 2: 

1003 hardware_family = parts[0] 

1004 

1005 entry = DatGameEntry( 

1006 name=game.name, 

1007 description=game.description, 

1008 cloneof=game.cloneof, 

1009 romof=game.romof, 

1010 year=game.year, 

1011 manufacturer=game.manufacturer, 

1012 sourcefile=game.sourcefile, 

1013 hardware=hardware, 

1014 hardware_family=hardware_family, 

1015 driver_status=game.driver_status, 

1016 comment=game.comment, 

1017 category=game.category, 

1018 rom_crc=game.rom_crc, 

1019 rom_size=game.rom_size, 

1020 dat_name=parser.dat_name, 

1021 dat_type=parser.dat_type, 

1022 ) 

1023 

1024 # Add video specs if present 

1025 if game.video: 

1026 entry.video_type = game.video.type 

1027 entry.video_orientation = game.video.orientation 

1028 entry.video_width = game.video.width 

1029 entry.video_height = game.video.height 

1030 entry.video_aspect_x = game.video.aspect_x 

1031 entry.video_aspect_y = game.video.aspect_y 

1032 entry.video_refresh = game.video.refresh 

1033 

1034 if existing: 

1035 # Update existing 

1036 for key, value in entry.__dict__.items(): 

1037 if not key.startswith("_") and key != "id": 

1038 setattr(existing, key, value) 

1039 stats["updated"] += 1 

1040 else: 

1041 session.add(entry) 

1042 stats["imported"] += 1 

1043 

1044 # Commit in batches 

1045 if stats["total"] % 1000 == 0: 

1046 session.commit() 

1047 

1048 session.commit() 

1049 

1050 return stats 

1051 

1052 def get_hardware_games( 

1053 self, 

1054 hardware: str, 

1055 dat_type: str = "fbneo", 

1056 parents_only: bool = False, 

1057 ) -> list[DatGameEntry]: 

1058 """ 

1059 Get all games for a specific hardware/driver. 

1060 

1061 Args: 

1062 hardware: Hardware name (e.g., "cps1", "neogeo") 

1063 dat_type: DAT type to search 

1064 parents_only: If True, only return parent games (no clones) 

1065 

1066 Returns: 

1067 List of DatGameEntry objects 

1068 """ 

1069 with self.get_session() as session: 

1070 q = session.query(DatGameEntry).filter( 

1071 DatGameEntry.dat_type == dat_type, DatGameEntry.hardware == hardware 

1072 ) 

1073 

1074 if parents_only: 

1075 q = q.filter(DatGameEntry.cloneof.is_(None)) 

1076 

1077 return q.order_by(DatGameEntry.description).all() 

1078 

1079 def get_dat_game_variants( 

1080 self, 

1081 game_name: str, 

1082 dat_type: str = "fbneo", 

1083 ) -> dict: 

1084 """ 

1085 Get a game and all its variants/clones from DAT data. 

1086 

1087 Args: 

1088 game_name: ROM name to search for 

1089 dat_type: DAT type to search 

1090 

1091 Returns: 

1092 Dict with parent and clones 

1093 """ 

1094 with self.get_session() as session: 

1095 # Find the game 

1096 target = ( 

1097 session.query(DatGameEntry) 

1098 .filter(DatGameEntry.dat_type == dat_type, DatGameEntry.name == game_name) 

1099 .first() 

1100 ) 

1101 

1102 if not target: 

1103 # Try partial match 

1104 target = ( 

1105 session.query(DatGameEntry) 

1106 .filter( 

1107 DatGameEntry.dat_type == dat_type, DatGameEntry.name.ilike(f"%{game_name}%") 

1108 ) 

1109 .first() 

1110 ) 

1111 

1112 if not target: 

1113 return {"parent": None, "clones": [], "target": None} 

1114 

1115 # Find root parent 

1116 parent = target 

1117 while parent.cloneof: 

1118 parent_game = ( 

1119 session.query(DatGameEntry) 

1120 .filter(DatGameEntry.dat_type == dat_type, DatGameEntry.name == parent.cloneof) 

1121 .first() 

1122 ) 

1123 if parent_game: 

1124 parent = parent_game 

1125 else: 

1126 break 

1127 

1128 # Find all clones 

1129 clones = ( 

1130 session.query(DatGameEntry) 

1131 .filter(DatGameEntry.dat_type == dat_type, DatGameEntry.cloneof == parent.name) 

1132 .order_by(DatGameEntry.name) 

1133 .all() 

1134 ) 

1135 

1136 # Convert to dicts to avoid detached instance issues 

1137 def to_dict(g): 

1138 return { 

1139 "name": g.name, 

1140 "description": g.description, 

1141 "year": g.year, 

1142 "manufacturer": g.manufacturer, 

1143 "hardware": g.hardware, 

1144 "hardware_family": g.hardware_family, 

1145 "driver_status": g.driver_status, 

1146 "cloneof": g.cloneof, 

1147 "video_width": g.video_width, 

1148 "video_height": g.video_height, 

1149 "video_orientation": g.video_orientation, 

1150 "is_bootleg": g.is_bootleg, 

1151 "comment": g.comment, 

1152 } 

1153 

1154 return { 

1155 "parent": to_dict(parent), 

1156 "clones": [to_dict(c) for c in clones], 

1157 "target": to_dict(target), 

1158 "clone_count": len(clones), 

1159 } 

1160 

1161 def get_hardware_list(self, dat_type: str = "fbneo") -> list[dict]: 

1162 """ 

1163 Get all hardware types with game counts. 

1164 

1165 Args: 

1166 dat_type: DAT type to query 

1167 

1168 Returns: 

1169 List of dicts with hardware name and counts 

1170 """ 

1171 from sqlalchemy import case, func 

1172 

1173 with self.get_session() as session: 

1174 results = ( 

1175 session.query( 

1176 DatGameEntry.hardware, 

1177 DatGameEntry.hardware_family, 

1178 func.count(DatGameEntry.id).label("total"), 

1179 func.sum(case((DatGameEntry.cloneof.is_(None), 1), else_=0)).label("parents"), 

1180 ) 

1181 .filter(DatGameEntry.dat_type == dat_type, DatGameEntry.hardware.isnot(None)) 

1182 .group_by(DatGameEntry.hardware, DatGameEntry.hardware_family) 

1183 .order_by(func.count(DatGameEntry.id).desc()) 

1184 .all() 

1185 ) 

1186 

1187 return [ 

1188 { 

1189 "hardware": r[0], 

1190 "family": r[1], 

1191 "total_games": r[2], 

1192 "parent_games": r[3], 

1193 "clone_games": r[2] - r[3], 

1194 } 

1195 for r in results 

1196 ] 

1197 

1198 def search_dat_games( 

1199 self, 

1200 query: str, 

1201 dat_type: str = "fbneo", 

1202 hardware: str | None = None, 

1203 parents_only: bool = False, 

1204 limit: int = 50, 

1205 ) -> list[dict]: 

1206 """ 

1207 Search DAT games by name or description. 

1208 

1209 Args: 

1210 query: Search query 

1211 dat_type: DAT type to search 

1212 hardware: Optional hardware filter 

1213 parents_only: If True, only return parents 

1214 limit: Max results 

1215 

1216 Returns: 

1217 List of matching games as dicts 

1218 """ 

1219 with self.get_session() as session: 

1220 q = session.query(DatGameEntry).filter( 

1221 DatGameEntry.dat_type == dat_type, 

1222 (DatGameEntry.name.ilike(f"%{query}%")) 

1223 | (DatGameEntry.description.ilike(f"%{query}%")), 

1224 ) 

1225 

1226 if hardware: 

1227 q = q.filter(DatGameEntry.hardware == hardware) 

1228 

1229 if parents_only: 

1230 q = q.filter(DatGameEntry.cloneof.is_(None)) 

1231 

1232 results = q.order_by(DatGameEntry.description).limit(limit).all() 

1233 

1234 return [ 

1235 { 

1236 "name": g.name, 

1237 "description": g.description, 

1238 "year": g.year, 

1239 "manufacturer": g.manufacturer, 

1240 "hardware": g.hardware, 

1241 "cloneof": g.cloneof, 

1242 "is_parent": g.is_parent, 

1243 "driver_status": g.driver_status, 

1244 "resolution": g.resolution, 

1245 "orientation": g.video_orientation, 

1246 } 

1247 for g in results 

1248 ] 

1249 

1250 # ------------------------------------------------------------------ 

1251 # External scores (MobyGames, RAWG) 

1252 # ------------------------------------------------------------------ 

1253 

1254 def upsert_external_score(self, score: "ExternalScore") -> None: 

1255 """Insert or update an external score record.""" 

1256 with self.get_session() as session: 

1257 existing = ( 

1258 session.query(ExternalScore) 

1259 .filter_by( 

1260 platform=score.platform, 

1261 source=score.source, 

1262 source_id=score.source_id, 

1263 ) 

1264 .first() 

1265 ) 

1266 if existing: 

1267 existing.title = score.title 

1268 existing.normalized_title = score.normalized_title 

1269 existing.critic_score = score.critic_score 

1270 existing.user_score = score.user_score 

1271 existing.vote_count = score.vote_count 

1272 existing.url = score.url 

1273 existing.description = score.description 

1274 existing.genres = score.genres 

1275 existing.release_date = score.release_date 

1276 existing.official_url = score.official_url 

1277 existing.cover_url = score.cover_url 

1278 existing.screenshot_urls = score.screenshot_urls 

1279 existing.fetched_at = score.fetched_at 

1280 else: 

1281 session.add(score) 

1282 session.commit() 

1283 

1284 def get_external_scores_for_platform( 

1285 self, 

1286 platform: str, 

1287 source: str | None = None, 

1288 min_user_score: float | None = None, 

1289 min_critic_score: int | None = None, 

1290 ) -> list["ExternalScore"]: 

1291 """Return external scores for a platform, optionally filtered.""" 

1292 with self.get_session() as session: 

1293 q = session.query(ExternalScore).filter(ExternalScore.platform == platform) 

1294 if source: 

1295 q = q.filter(ExternalScore.source == source) 

1296 if min_user_score is not None: 

1297 q = q.filter(ExternalScore.user_score >= min_user_score) 

1298 if min_critic_score is not None: 

1299 q = q.filter(ExternalScore.critic_score >= min_critic_score) 

1300 q = q.order_by(ExternalScore.user_score.desc().nullslast(), ExternalScore.title) 

1301 results = q.all() 

1302 session.expunge_all() 

1303 return results 

1304 

1305 def lookup_external_score( 

1306 self, 

1307 platform: str, 

1308 normalized_title: str, 

1309 ) -> Optional["ExternalScore"]: 

1310 """ 

1311 Find the best external score for a game by normalized title. 

1312 

1313 Tries exact match first, then falls back to prefix/contains match. 

1314 Prefers critic_score over user_score when both are available. 

1315 """ 

1316 with self.get_session() as session: 

1317 q = session.query(ExternalScore).filter(ExternalScore.platform == platform) 

1318 # Exact normalized title match 

1319 exact = q.filter(ExternalScore.normalized_title == normalized_title).first() 

1320 if exact: 

1321 session.expunge(exact) 

1322 return exact 

1323 # Prefix match (handles subtitle truncation) 

1324 prefix = ( 

1325 q.filter(ExternalScore.normalized_title.like(f"{normalized_title}%")) 

1326 .order_by( 

1327 ExternalScore.critic_score.desc().nullslast(), 

1328 ExternalScore.user_score.desc().nullslast(), 

1329 ) 

1330 .first() 

1331 ) 

1332 if prefix: 

1333 session.expunge(prefix) 

1334 return prefix 

1335 return None 

1336 

1337 def get_external_scores_stats(self) -> list[dict]: 

1338 """Return per-platform/source coverage statistics.""" 

1339 from sqlalchemy import func 

1340 

1341 with self.get_session() as session: 

1342 rows = ( 

1343 session.query( 

1344 ExternalScore.platform, 

1345 ExternalScore.source, 

1346 func.count(ExternalScore.id).label("count"), 

1347 func.count(ExternalScore.critic_score).label("with_critic"), 

1348 func.count(ExternalScore.user_score).label("with_user"), 

1349 func.avg(ExternalScore.user_score).label("avg_user"), 

1350 func.max(ExternalScore.fetched_at).label("last_fetch"), 

1351 ) 

1352 .group_by(ExternalScore.platform, ExternalScore.source) 

1353 .order_by(ExternalScore.platform, ExternalScore.source) 

1354 .all() 

1355 ) 

1356 return [ 

1357 { 

1358 "platform": r.platform, 

1359 "source": r.source, 

1360 "count": r.count, 

1361 "with_critic": r.with_critic, 

1362 "with_user": r.with_user, 

1363 "avg_user_score": round(r.avg_user, 2) if r.avg_user else None, 

1364 "last_fetch": r.last_fetch, 

1365 } 

1366 for r in rows 

1367 ]