Coverage for src/romfarmer/metadata/external_scores.py: 24%

143 statements  

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

1""" 

2External game score fetcher — MobyGames and RAWG APIs. 

3 

4Fetches professional critic scores and community ratings to supplement 

5ScreenScraper ratings, which have sparse coverage on many platforms. 

6 

7Sources 

8------- 

9MobyGames (https://www.mobygames.com/info/api/) 

10 - moby_score: community-voted score (0-10) 

11 - Excellent retro platform coverage (Saturn, PC Engine, Atari, etc.) 

12 - API key required (free tier: 360 req/day) 

13 - Environment variable: MOBYGAMES_API_KEY 

14 

15RAWG (https://rawg.io/apidocs) [placeholder, not yet implemented] 

16 - metacritic field: actual Metacritic Metascore (0-100) 

17 - Best for modern platforms (PS2-PS5, Xbox, Switch) 

18 - API key required (free tier: 20k req/month) 

19 - Environment variable: RAWG_API_KEY 

20 

21Usage 

22----- 

23 from romfarmer.metadata.external_scores import MobyGamesFetcher 

24 from romfarmer.metadata.database import MetadataDatabase 

25 from pathlib import Path 

26 

27 db = MetadataDatabase(Path("metadata/database/romfarmer.db")) 

28 fetcher = MobyGamesFetcher(api_key="your-key", db=db) 

29 count = fetcher.fetch_platform("ps2") 

30 print(f"Stored {count} PS2 scores") 

31""" 

32 

33import json 

34import logging 

35import os 

36import re 

37import time 

38from datetime import datetime 

39 

40import requests 

41 

42from .database import ExternalScore, MetadataDatabase 

43 

44logger = logging.getLogger(__name__) 

45 

46 

47# --------------------------------------------------------------------------- 

48# Title normalization 

49# --------------------------------------------------------------------------- 

50 

51 

52def normalize_title(title: str) -> str: 

53 """ 

54 Normalize a game title for fuzzy matching against ROM filenames. 

55 

56 ROM filenames carry region/revision noise: 

57 "Castlevania - Symphony of the Night (USA) (v1.1)" 

58 MobyGames stores: 

59 "Castlevania: Symphony of the Night" 

60 

61 This function strips that noise to a bare lowercase token string 

62 that can be compared across sources. 

63 

64 Examples 

65 -------- 

66 >>> normalize_title("Resident Evil 4 (USA)") 

67 'resident evil 4' 

68 >>> normalize_title("The Legend of Zelda: Ocarina of Time") 

69 'legend of zelda ocarina of time' 

70 >>> normalize_title("Gran Turismo 3 - A-spec (Europe) (En,Fr,De,Es,It)") 

71 'gran turismo 3 aspec' 

72 >>> normalize_title("Addams Family, The (USA)") 

73 'addams family' 

74 """ 

75 t = title 

76 

77 # Strip trailing parenthetical content (region, revision, language, etc.) 

78 t = re.sub(r"\s*\([^)]*\)", "", t) 

79 

80 # Strip disc/part suffixes used in multi-disc titles 

81 t = re.sub(r"\s*[-:]\s*(Disc|CD|Part|Vol\.?)\s*\d+.*$", "", t, flags=re.IGNORECASE) 

82 

83 # No-Intro/Redump trailing-article convention ("Legend of Zelda, The") 

84 # must be dropped before the comma is stripped, or "the" would merge 

85 # into the title instead of being removed like a leading article. 

86 t = re.sub(r",\s*(the|a|an)\s*$", "", t, flags=re.IGNORECASE) 

87 

88 # Normalize subtitle separators (colon, dash) to a single space 

89 t = re.sub(r"\s*[:\-]\s*", " ", t) 

90 

91 # Lowercase 

92 t = t.lower() 

93 

94 # Strip punctuation except word characters and spaces 

95 t = re.sub(r"[^\w\s]", "", t) 

96 

97 # Collapse whitespace 

98 t = re.sub(r"\s+", " ", t).strip() 

99 

100 # Strip leading articles (for stable sorting/matching) 

101 t = re.sub(r"^(the|a|an)\s+", "", t) 

102 

103 return t 

104 

105 

106# --------------------------------------------------------------------------- 

107# Platform ID mappings 

108# --------------------------------------------------------------------------- 

109 

110# Maps rom-farmer platform names → MobyGames platform IDs. 

111# Verify IDs at: https://www.mobygames.com/game/platform/ 

112# To add a platform, find its ID from the MobyGames URL when browsing by platform. 

113MOBYGAMES_PLATFORM_IDS: dict[str, int] = { 

114 # Sony 

115 "psx": 6, # PlayStation 

116 "ps2": 7, # PlayStation 2 

117 "ps3": 81, # PlayStation 3 

118 "psp": 46, # PlayStation Portable 

119 "pspminis": 46, # PSP Minis share the PSP platform 

120 # Microsoft 

121 "xbox": 13, # Xbox 

122 "xbox360": 69, # Xbox 360 

123 # Nintendo home 

124 "gamecube": 14, # GameCube 

125 "wii": 82, # Wii 

126 "wiiu": 132, # Wii U 

127 "n64": 9, # Nintendo 64 

128 "snes": 15, # Super NES 

129 "nes": 22, # NES 

130 "fds": 22, # Famicom Disk System (same platform page on MobyGames) 

131 # Nintendo handheld 

132 "gb": 10, # Game Boy 

133 "gbc": 11, # Game Boy Color 

134 "gba": 12, # Game Boy Advance 

135 "nds": 44, # Nintendo DS 

136 "3ds": 101, # Nintendo 3DS 

137 # Sega home 

138 "dreamcast": 8, # Dreamcast 

139 "saturn": 23, # Saturn 

140 "megadrive": 16, # Genesis / Mega Drive 

141 "megacd": 20, # Sega CD / Mega-CD 

142 "sega32x": 21, # 32X 

143 "mastersystem": 26, # Master System 

144 # Sega handheld 

145 "gamegear": 25, # Game Gear 

146 # NEC 

147 "pcengine": 40, # PC Engine / TurboGrafx-16 

148 # SNK 

149 "neogeo": 36, # Neo Geo 

150 # Atari 

151 "atari2600": 28, # Atari 2600 

152 "atari5200": 33, # Atari 5200 

153 "atari7800": 34, # Atari 7800 

154 "atarijaguar": 17, # Atari Jaguar 

155 "atarilynx": 18, # Atari Lynx 

156 # Other home 

157 "3do": 35, # 3DO 

158 "colecovision": 29, # ColecoVision 

159 "intellivision": 30, # Intellivision 

160 "virtualboy": 38, # Virtual Boy (37 is Vectrex - do not confuse) 

161 # Handheld misc 

162 "wswan": 48, # WonderSwan 

163 "wswanc": 49, # WonderSwan Color 

164 # MSX (same ID for both revisions on MobyGames) 

165 "msx1": 57, 

166 "msx2": 57, 

167 # Computers / added 2026-08-20 for Myrient-sourced platforms not yet built 

168 "dos": 2, # DOS 

169 "c64": 27, # Commodore 64 

170 "amiga": 19, # Amiga 

171 "amigacd32": 56, # Amiga CD32 

172 "atarist": 24, # Atari ST 

173 "atari800": 39, # Atari 8-bit Family 

174 "apple2": 31, # Apple II 

175 "apple2gs": 51, # Apple IIgs 

176 "zxspectrum": 41, # ZX Spectrum 

177 "cpc": 60, # Amstrad CPC 

178 "pc88": 94, # NEC PC-88 

179 "pc98": 95, # NEC PC-98 

180 "pcfx": 59, # NEC PC-FX 

181 "x68000": 106, # Sharp X68000 

182 "fmtowns": 102, # Fujitsu FM Towns 

183 "vectrex": 37, # GCE Vectrex 

184 "odyssey2": 78, # Magnavox Odyssey 2 

185 "channelf": 76, # Fairchild Channel F 

186 "gamecom": 50, # Tiger Game.com 

187 "ngage": 32, # Nokia N-Gage 

188 "neogeocd": 54, # SNK Neo Geo CD 

189 "cdi": 73, # Philips CD-i 

190} 

191 

192# Maps rom-farmer platform names → RAWG platform IDs. 

193# RAWG's 'metacritic' field is the actual Metacritic Metascore. 

194RAWG_PLATFORM_IDS: dict[str, int] = { 

195 "psx": 27, # PlayStation 

196 "ps2": 15, # PlayStation 2 

197 "ps3": 16, # PlayStation 3 

198 "psp": 19, # PSP 

199 "xbox": 80, # Xbox 

200 "xbox360": 14, # Xbox 360 

201 "gamecube": 105, # GameCube 

202 "wii": 11, # Wii 

203 "wiiu": 10, # Wii U 

204 "n64": 83, # Nintendo 64 

205 "snes": 79, # SNES 

206 "nes": 18, # NES 

207 "gba": 24, # GBA 

208 "nds": 77, # DS 

209 "3ds": 8, # 3DS 

210 "dreamcast": 106, # Dreamcast 

211 "megadrive": 167, # Genesis 

212} 

213 

214 

215# --------------------------------------------------------------------------- 

216# MobyGames fetcher 

217# --------------------------------------------------------------------------- 

218 

219 

220class MobyGamesFetcher: 

221 """ 

222 Fetches game scores from the MobyGames API v1 and persists them to the DB. 

223 

224 Rate limit 

225 ---------- 

226 The MobyGames Hobbyist tier ($9.99/mo) allows 1 request/second. 

227 The default ``rate_limit_seconds`` of 1.0 uses that full allowance. 

228 Free tier users should set this to 10.0 (360 req/day budget). 

229 

230 Parameters 

231 ---------- 

232 api_key: 

233 MobyGames API key. If not provided, the ``MOBYGAMES_API_KEY`` 

234 environment variable is used. 

235 db: 

236 Initialized MetadataDatabase instance. 

237 rate_limit_seconds: 

238 Minimum seconds between API requests (default 1.0 for Hobbyist tier). 

239 """ 

240 

241 BASE_URL = "https://api.mobygames.com/v1" 

242 

243 def __init__( 

244 self, 

245 db: MetadataDatabase, 

246 api_key: str | None = None, 

247 rate_limit_seconds: float = 1.1, 

248 ): 

249 self.api_key = api_key or os.environ.get("MOBYGAMES_API_KEY", "") 

250 if not self.api_key: 

251 raise ValueError("MobyGames API key required. Pass api_key= or set MOBYGAMES_API_KEY.") 

252 self.db = db 

253 self.rate_limit = rate_limit_seconds 

254 self._session = requests.Session() 

255 self._session.headers.update({"Accept": "application/json"}) 

256 self._last_request_time: float = 0.0 

257 self._request_count: int = 0 

258 

259 # ------------------------------------------------------------------ 

260 # Public interface 

261 # ------------------------------------------------------------------ 

262 

263 def fetch_platform( 

264 self, 

265 platform: str, 

266 progress_callback=None, 

267 resume: bool = True, 

268 ) -> int: 

269 """ 

270 Fetch all scored games for one rom-farmer platform and persist them. 

271 

272 Parameters 

273 ---------- 

274 platform: 

275 rom-farmer platform name (e.g. "ps2", "snes"). 

276 progress_callback: 

277 Optional callable(fetched: int, stored: int, page: int) for UI updates. 

278 resume: 

279 If True (default), skip platforms already fetched today. 

280 

281 Returns 

282 ------- 

283 int 

284 Number of new/updated score records stored. 

285 """ 

286 platform_id = MOBYGAMES_PLATFORM_IDS.get(platform) 

287 if platform_id is None: 

288 raise ValueError( 

289 f"No MobyGames platform ID for '{platform}'. " 

290 f"Add it to MOBYGAMES_PLATFORM_IDS in external_scores.py." 

291 ) 

292 

293 logger.info("Fetching MobyGames scores for platform '%s' (id=%d)", platform, platform_id) 

294 

295 stored = 0 

296 offset = 0 

297 page_size = 100 

298 page = 0 

299 

300 while True: 

301 data = self._get( 

302 "games", 

303 { 

304 "platform": platform_id, 

305 "format": "normal", 

306 "limit": page_size, 

307 "offset": offset, 

308 }, 

309 ) 

310 

311 games = data.get("games", []) 

312 if not games: 

313 break 

314 

315 for game in games: 

316 moby_score = game.get("moby_score") 

317 if moby_score is None: 

318 continue # Skip games with no community score 

319 

320 title = game.get("title", "") 

321 genres = game.get("genres") or [] 

322 cover = game.get("sample_cover") or {} 

323 screenshots = game.get("sample_screenshots") or [] 

324 release_date = None 

325 for p in game.get("platforms") or []: 

326 if p.get("platform_id") == platform_id: 

327 release_date = p.get("first_release_date") 

328 break 

329 score = ExternalScore( 

330 platform=platform, 

331 title=title, 

332 normalized_title=normalize_title(title), 

333 critic_score=None, # MobyGames list endpoint doesn't include critic aggregate 

334 user_score=float(moby_score), 

335 vote_count=game.get("num_votes"), 

336 source="mobygames", 

337 source_id=str(game.get("game_id", "")), 

338 url=game.get("moby_url"), 

339 description=game.get("description"), 

340 genres=", ".join(g["genre_name"] for g in genres) or None, 

341 release_date=release_date, 

342 official_url=game.get("official_url"), 

343 cover_url=cover.get("image"), 

344 screenshot_urls=json.dumps([s["image"] for s in screenshots]) 

345 if screenshots 

346 else None, 

347 fetched_at=datetime.utcnow(), 

348 ) 

349 self.db.upsert_external_score(score) 

350 stored += 1 

351 

352 page += 1 

353 offset += len(games) 

354 

355 if progress_callback: 

356 progress_callback(offset, stored, page) 

357 

358 logger.debug( 

359 " page %d: fetched %d games total, %d scored, offset=%d", 

360 page, 

361 offset, 

362 stored, 

363 offset, 

364 ) 

365 

366 if len(games) < page_size: 

367 break # Last page 

368 

369 logger.info("Stored %d scored games for platform '%s'", stored, platform) 

370 return stored 

371 

372 def fetch_all_platforms( 

373 self, 

374 platforms: list[str] | None = None, 

375 progress_callback=None, 

376 ) -> dict[str, int]: 

377 """ 

378 Fetch scores for multiple platforms sequentially. 

379 

380 Parameters 

381 ---------- 

382 platforms: 

383 List of rom-farmer platform names to fetch. Defaults to all 

384 platforms in MOBYGAMES_PLATFORM_IDS. 

385 progress_callback: 

386 Optional callable(platform: str, fetched: int, stored: int). 

387 

388 Returns 

389 ------- 

390 dict mapping platform name → stored count. 

391 """ 

392 target_platforms = platforms or list(MOBYGAMES_PLATFORM_IDS.keys()) 

393 # Deduplicate while preserving order (e.g. msx1/msx2 share same ID) 

394 seen_ids: set[int] = set() 

395 deduped: list[str] = [] 

396 for p in target_platforms: 

397 pid = MOBYGAMES_PLATFORM_IDS.get(p) 

398 if pid is not None and pid not in seen_ids: 

399 seen_ids.add(pid) 

400 deduped.append(p) 

401 

402 results: dict[str, int] = {} 

403 for platform in deduped: 

404 try: 

405 count = self.fetch_platform(platform, progress_callback=progress_callback) 

406 results[platform] = count 

407 except Exception as exc: 

408 logger.error("Error fetching platform '%s': %s", platform, exc) 

409 results[platform] = -1 

410 

411 return results 

412 

413 def lookup_game(self, title: str, platform: str) -> dict | None: 

414 """ 

415 Search MobyGames for a single game by title and platform. 

416 

417 Useful for spot-checks or filling gaps. Returns the first result 

418 dict from the API, or None if not found. 

419 """ 

420 platform_id = MOBYGAMES_PLATFORM_IDS.get(platform) 

421 data = self._get( 

422 "games", 

423 { 

424 "title": title, 

425 "platform": platform_id, 

426 "format": "normal", 

427 "limit": 5, 

428 }, 

429 ) 

430 games = data.get("games", []) 

431 return games[0] if games else None 

432 

433 # ------------------------------------------------------------------ 

434 # Internal helpers 

435 # ------------------------------------------------------------------ 

436 

437 @staticmethod 

438 def _seconds_until_next_utc_hour() -> float: 

439 """Return seconds until the next UTC :00:00 boundary.""" 

440 import datetime as _dt 

441 

442 now = _dt.datetime.utcnow() 

443 next_hour = now.replace(minute=0, second=0, microsecond=0) + _dt.timedelta(hours=1) 

444 return max((next_hour - now).total_seconds(), 1.0) 

445 

446 def _get(self, endpoint: str, params: dict, _retry: int = 0) -> dict: 

447 """Make a rate-limited, authenticated GET request with 429 backoff. 

448 

449 Retry strategy: 

450 Retries 0-2: short exponential backoff (5s, 10s, 20s) — handles burst limiting. 

451 Retry 3+: wait until the next UTC :00 boundary + 5s buffer, then retry. 

452 This survives the ~47-minute hourly quota dead window. 

453 _MAX_RETRIES: give up after this many retries (covers multiple dead windows). 

454 """ 

455 _MAX_RETRIES = 12 

456 _SHORT_RETRIES = 3 # below this index, use short exponential backoff 

457 

458 # Enforce minimum gap between requests 

459 elapsed = time.monotonic() - self._last_request_time 

460 if elapsed < self.rate_limit: 

461 time.sleep(self.rate_limit - elapsed) 

462 

463 call_params = dict(params) # copy so we never mutate caller's dict 

464 call_params["api_key"] = self.api_key 

465 

466 url = f"{self.BASE_URL}/{endpoint}" 

467 try: 

468 resp = self._session.get(url, params=call_params, timeout=60) 

469 resp.raise_for_status() 

470 except requests.HTTPError as exc: 

471 if exc.response is not None and exc.response.status_code == 429: 

472 if _retry >= _MAX_RETRIES: 

473 raise RuntimeError( 

474 f"MobyGames API rate limit exceeded (429) after " 

475 f"{_MAX_RETRIES} retries on {endpoint}. " 

476 f"Consider --rate-limit 5.0 to stay within 720 req/hour." 

477 ) from exc 

478 if _retry < _SHORT_RETRIES: 

479 backoff = 5.0 * (2**_retry) # 5s, 10s, 20s 

480 logger.warning( 

481 "429 burst limit hit — backing off %.0fs (retry %d/%d)", 

482 backoff, 

483 _retry + 1, 

484 _MAX_RETRIES, 

485 ) 

486 else: 

487 # Likely hourly quota exhausted — wait until next UTC :00 

488 wait = self._seconds_until_next_utc_hour() + 5.0 

489 logger.warning( 

490 "429 hourly quota exhausted — waiting %.0fs for UTC :00 reset " 

491 "(retry %d/%d, ~%.0f min)", 

492 wait, 

493 _retry + 1, 

494 _MAX_RETRIES, 

495 wait / 60, 

496 ) 

497 backoff = wait 

498 time.sleep(backoff) 

499 self._last_request_time = time.monotonic() 

500 return self._get(endpoint, params, _retry + 1) 

501 raise 

502 finally: 

503 self._last_request_time = time.monotonic() 

504 self._request_count += 1 

505 

506 return resp.json() 

507 

508 

509# --------------------------------------------------------------------------- 

510# RAWG fetcher (Metacritic scores) 

511# --------------------------------------------------------------------------- 

512 

513 

514class RawgFetcher: 

515 """ 

516 Fetches Metacritic scores via the RAWG API. 

517 

518 RAWG's ``metacritic`` field is the actual Metacritic Metascore (0-100). 

519 It provides the best coverage for PS2-PS5, Xbox, Switch, and other 

520 modern platforms. 

521 

522 Status: placeholder — not yet implemented. 

523 Register at https://rawg.io/apidocs for a free API key (20k req/month). 

524 Set environment variable: RAWG_API_KEY 

525 """ 

526 

527 BASE_URL = "https://api.rawg.io/api" 

528 

529 def __init__( 

530 self, 

531 db: MetadataDatabase, 

532 api_key: str | None = None, 

533 rate_limit_seconds: float = 1.0, 

534 ): 

535 self.api_key = api_key or os.environ.get("RAWG_API_KEY", "") 

536 if not self.api_key: 

537 raise ValueError("RAWG API key required. Pass api_key= or set RAWG_API_KEY.") 

538 self.db = db 

539 self.rate_limit = rate_limit_seconds 

540 self._session = requests.Session() 

541 self._last_request_time: float = 0.0 

542 

543 def fetch_platform(self, platform: str) -> int: 

544 """Fetch Metacritic scores for one platform from RAWG. Not yet implemented.""" 

545 raise NotImplementedError( 

546 "RawgFetcher.fetch_platform() is not yet implemented. Use MobyGamesFetcher for now." 

547 )