Coverage for src/romfarmer/dat/filter.py: 0%

120 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-03 11:31 -0700

1""" 

21G1R (One Game One ROM) filtering for ROM collections. 

3 

4Filters DAT game entries to select the best version of each game based on: 

5- Region priorities (USA > Europe > Japan > World, etc.) 

6- Language preferences 

7- Parent vs Clone relationships 

8- Version/revision preferences 

9""" 

10 

11from collections import defaultdict 

12from dataclasses import dataclass 

13 

14from romfarmer.catalog.database import DatGame 

15 

16 

17@dataclass 

18class FilterStats: 

19 """Statistics from 1G1R filtering.""" 

20 

21 total_games: int = 0 

22 unique_games: int = 0 

23 filtered_games: int = 0 

24 parents_selected: int = 0 

25 clones_selected: int = 0 

26 duplicates_removed: int = 0 

27 

28 

29class OneGameOneRomFilter: 

30 """ 

31 Filter DAT games to select one ROM per game based on preferences. 

32 

33 This implements the "1G1R" (One Game One ROM) concept popular in ROM 

34 collecting communities, reducing collections to one version of each game. 

35 """ 

36 

37 # Default region priority (higher score = higher priority) 

38 DEFAULT_REGION_PRIORITY = { 

39 "USA": 100, 

40 "World": 95, 

41 "Europe": 90, 

42 "Japan": 85, 

43 "Asia": 80, 

44 "Korea": 75, 

45 "China": 70, 

46 "Brazil": 65, 

47 "Australia": 60, 

48 "Germany": 55, 

49 "France": 54, 

50 "Spain": 53, 

51 "Italy": 52, 

52 "Netherlands": 51, 

53 "Sweden": 50, 

54 "Canada": 45, 

55 "Unknown": 0, 

56 } 

57 

58 # Default language priority 

59 DEFAULT_LANGUAGE_PRIORITY = { 

60 "En": 100, # English 

61 "Ja": 85, # Japanese 

62 "Fr": 80, # French 

63 "De": 75, # German 

64 "Es": 70, # Spanish 

65 "It": 65, # Italian 

66 "Pt": 60, # Portuguese 

67 "Nl": 55, # Dutch 

68 "Sv": 50, # Swedish 

69 "No": 45, # Norwegian 

70 "Da": 40, # Danish 

71 "Fi": 35, # Finnish 

72 "Zh": 30, # Chinese 

73 "Ko": 25, # Korean 

74 } 

75 

76 def __init__( 

77 self, 

78 region_priority: list[str] | None = None, 

79 language_priority: list[str] | None = None, 

80 prefer_parents: bool = True, 

81 prefer_later_revisions: bool = True, 

82 ): 

83 """ 

84 Initialize the 1G1R filter. 

85 

86 Args: 

87 region_priority: Ordered list of preferred regions (highest first) 

88 language_priority: Ordered list of preferred languages (highest first) 

89 prefer_parents: If True, prefer parent ROMs over clones when scores tie 

90 prefer_later_revisions: If True, prefer later revisions (Rev 2 > Rev 1) 

91 """ 

92 self.prefer_parents = prefer_parents 

93 self.prefer_later_revisions = prefer_later_revisions 

94 

95 # Build region priority map 

96 if region_priority: 

97 self.region_priority = {region: 100 - i * 5 for i, region in enumerate(region_priority)} 

98 else: 

99 self.region_priority = self.DEFAULT_REGION_PRIORITY.copy() 

100 

101 # Build language priority map 

102 if language_priority: 

103 self.language_priority = {lang: 100 - i * 5 for i, lang in enumerate(language_priority)} 

104 else: 

105 self.language_priority = self.DEFAULT_LANGUAGE_PRIORITY.copy() 

106 

107 def filter_games(self, games: list[DatGame]) -> tuple[list[DatGame], FilterStats]: 

108 """ 

109 Filter games to one ROM per unique game. 

110 

111 Args: 

112 games: List of DatGame entries to filter 

113 

114 Returns: 

115 Tuple of (filtered games list, statistics) 

116 """ 

117 stats = FilterStats(total_games=len(games)) 

118 

119 # Group games by base name (removing region/language/version tags) 

120 game_groups = self._group_games_by_base_name(games) 

121 stats.unique_games = len(game_groups) 

122 

123 # Select best game from each group 

124 filtered = [] 

125 for _base_name, group in game_groups.items(): 

126 best_game = self._select_best_game(group) 

127 filtered.append(best_game) 

128 

129 # Update stats 

130 if self._is_parent(best_game): 

131 stats.parents_selected += 1 

132 else: 

133 stats.clones_selected += 1 

134 

135 stats.filtered_games = len(filtered) 

136 stats.duplicates_removed = stats.total_games - stats.filtered_games 

137 

138 return filtered, stats 

139 

140 def _group_games_by_base_name(self, games: list[DatGame]) -> dict[str, list[DatGame]]: 

141 """ 

142 Group games by their base name (without region/language/version tags). 

143 

144 For example: 

145 - "Super Mario Bros. (USA)" -> "Super Mario Bros." 

146 - "Super Mario Bros. (Europe)" -> "Super Mario Bros." 

147 - "Super Mario Bros. (Japan)" -> "Super Mario Bros." 

148 """ 

149 groups = defaultdict(list) 

150 

151 for game in games: 

152 base_name = self._extract_base_name(game.name or "") 

153 groups[base_name].append(game) 

154 

155 return dict(groups) 

156 

157 def _extract_base_name(self, name: str) -> str: 

158 """ 

159 Extract the base game name without region/language/version tags. 

160 

161 Removes patterns like: 

162 - (USA), (Europe), (Japan), etc. 

163 - (En), (En,Fr), etc. 

164 - (Rev 1), (Rev A), (Beta), (Proto), etc. 

165 - [!], [a], [b], etc. 

166 """ 

167 # Remove parenthetical tags 

168 import re 

169 

170 # Common patterns to remove 

171 patterns = [ 

172 r"\([^)]*\)", # Anything in parentheses 

173 r"\[[^\]]*\]", # Anything in brackets 

174 r"\{[^}]*\}", # Anything in braces 

175 ] 

176 

177 result = name 

178 for pattern in patterns: 

179 result = re.sub(pattern, "", result) 

180 

181 # Clean up extra whitespace 

182 result = " ".join(result.split()) 

183 result = result.strip(" -,") 

184 

185 return result 

186 

187 def _select_best_game(self, games: list[DatGame]) -> DatGame: 

188 """ 

189 Select the best game from a group based on scoring criteria. 

190 

191 Scoring factors (in order of importance): 

192 1. Region priority 

193 2. Language priority 

194 3. Parent vs Clone (if prefer_parents=True) 

195 4. Revision number (if prefer_later_revisions=True) 

196 5. Alphabetical (for ties) 

197 """ 

198 if len(games) == 1: 

199 return games[0] 

200 

201 # Score each game 

202 scored_games = [(self._score_game(game), game) for game in games] 

203 

204 # Sort by score (descending), then by name (ascending) for ties 

205 scored_games.sort(key=lambda x: (-x[0], x[1].name or "")) 

206 

207 return scored_games[0][1] 

208 

209 def _score_game(self, game: DatGame) -> int: 

210 """ 

211 Calculate a score for a game based on preferences. 

212 

213 Higher score = more preferred. 

214 """ 

215 score = 0 

216 name = game.name or "" 

217 

218 # Region score (most important, weight: 1000) 

219 region_score = self._get_region_score(name) 

220 score += region_score * 1000 

221 

222 # Language score (weight: 100) 

223 language_score = self._get_language_score(name) 

224 score += language_score * 100 

225 

226 # Parent vs Clone score (weight: 10) 

227 if self.prefer_parents and self._is_parent(game): 

228 score += 10 

229 

230 # Revision score (weight: 1) 

231 if self.prefer_later_revisions: 

232 revision_score = self._get_revision_score(name) 

233 score += revision_score 

234 

235 return score 

236 

237 def _get_region_score(self, name: str) -> int: 

238 """Extract region from name and return priority score.""" 

239 import re 

240 

241 # Look for region tags like (USA), (Europe), etc. 

242 region_match = re.search(r"\(([^)]+)\)", name) 

243 if not region_match: 

244 return self.region_priority.get("Unknown", 0) 

245 

246 region_tag = region_match.group(1) 

247 

248 # Handle multi-region (e.g., "USA, Europe") 

249 regions = [r.strip() for r in region_tag.split(",")] 

250 

251 # Return highest priority region 

252 max_score = 0 

253 for region in regions: 

254 score = self.region_priority.get(region, 0) 

255 max_score = max(max_score, score) 

256 

257 return max_score 

258 

259 def _get_language_score(self, name: str) -> int: 

260 """Extract language from name and return priority score.""" 

261 import re 

262 

263 # Look for language tags like (En), (En,Fr), etc. 

264 lang_match = re.search(r"\(([A-Z][a-z](?:,[A-Z][a-z])*)\)", name) 

265 if not lang_match: 

266 return 0 

267 

268 lang_tag = lang_match.group(1) 

269 languages = [lang.strip() for lang in lang_tag.split(",")] 

270 

271 # Return highest priority language 

272 max_score = 0 

273 for lang in languages: 

274 score = self.language_priority.get(lang, 0) 

275 max_score = max(max_score, score) 

276 

277 return max_score 

278 

279 def _get_revision_score(self, name: str) -> int: 

280 """Extract revision number and return score.""" 

281 import re 

282 

283 # Look for revision patterns like (Rev 1), (Rev A), (v1.1), etc. 

284 patterns = [ 

285 r"Rev\s+(\d+)", 

286 r"Rev\s+([A-Z])", 

287 r"v(\d+)\.(\d+)", 

288 r"v(\d+)", 

289 ] 

290 

291 for pattern in patterns: 

292 match = re.search(pattern, name, re.IGNORECASE) 

293 if match: 

294 # Convert to numeric score 

295 if pattern.startswith("Rev\\s+([A-Z])"): 

296 # Rev A=1, Rev B=2, etc. 

297 return ord(match.group(1).upper()) - ord("A") + 1 

298 elif "\\." in pattern: 

299 # v1.1 = 11, v2.3 = 23 

300 major = int(match.group(1)) 

301 minor = int(match.group(2)) 

302 return major * 10 + minor 

303 else: 

304 # Simple number 

305 return int(match.group(1)) 

306 

307 return 0 

308 

309 def _is_parent(self, game: DatGame) -> bool: 

310 """ 

311 Check if a game is a parent (not a clone). 

312 

313 Parent games typically don't have tags like [a], [b], [!], etc. 

314 """ 

315 name = game.name or "" 

316 

317 # Check for clone indicators 

318 clone_indicators = ["[a]", "[b]", "[c]", "[!]", "[h]", "[t]", "[f]", "[p]", "[o]"] 

319 for indicator in clone_indicators: 

320 if indicator.lower() in name.lower(): 

321 return False 

322 

323 return True 

324 

325 def get_filtered_by_dat( 

326 self, 

327 games: list[DatGame], 

328 dat_name: str | None = None, 

329 ) -> tuple[list[DatGame], FilterStats]: 

330 """ 

331 Filter games from a specific DAT or all DATs. 

332 

333 Args: 

334 games: List of games to filter 

335 dat_name: Optional DAT name to filter within 

336 

337 Returns: 

338 Tuple of (filtered games, statistics) 

339 """ 

340 # Filter by DAT if specified 

341 if dat_name: 

342 games = [g for g in games if g.dat_file and g.dat_file.name == dat_name] 

343 

344 return self.filter_games(games)