Coverage for src/romfarmer/arcade/filter.py: 0%
195 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""Arcade-aware 1G1R filter.
3Provides filtering modes for arcade systems:
4- Strict 1G1R: Only parents, best regional variant per game
5- Relaxed 1G1R: Parents + essential hacks + best regional variants
6- Working Only: Filter out non-working games (preliminary drivers)
7"""
9from dataclasses import dataclass
10from enum import Enum
12from ..dat_parser.models import ArcadeCloneType, DATFile, DATGame
13from .classifier import ArcadeClassification, ArcadeClassifier, CloneImportance
16class ArcadeFilterMode(str, Enum):
17 """Filtering mode for arcade games."""
19 STRICT = "strict" # Parents only, one per game
20 RELAXED = "relaxed" # Parents + essential/recommended clones
21 COMPLETE = "complete" # All working games
22 ALL = "all" # Everything including non-working
25@dataclass
26class ArcadeFilterConfig:
27 """Configuration for arcade filtering."""
29 mode: ArcadeFilterMode = ArcadeFilterMode.RELAXED
30 include_working_only: bool = True
31 include_bootlegs: bool = False
32 include_hacks: bool = True # Include culturally important hacks
33 include_prototypes: bool = True
34 include_homebrew: bool = False
35 include_demos: bool = False
36 preferred_regions: list[str] = None # Order of preference
37 filter_driver: str = None # Filter by driver/sourcefile (e.g., 'neogeo')
38 filter_romof: str = None # Filter by romof/BIOS (e.g., 'naomi2' for Naomi 2 games)
39 exclude_romof: list[str] = None # Exclude games with these BIOS dependencies
41 def __post_init__(self):
42 if self.preferred_regions is None:
43 self.preferred_regions = ["World", "USA", "Europe", "Asia", "Japan"]
46@dataclass
47class FilteredGame:
48 """Result of filtering a game."""
50 game: DATGame
51 classification: ArcadeClassification
52 selected: bool
53 reason: str
56class ArcadeFilter:
57 """Filter arcade games based on 1G1R rules and preferences."""
59 def __init__(
60 self,
61 config: ArcadeFilterConfig | None = None,
62 classifier: ArcadeClassifier | None = None,
63 ):
64 """Initialize arcade filter.
66 Args:
67 config: Filter configuration
68 classifier: Arcade classifier instance
69 """
70 self.config = config or ArcadeFilterConfig()
71 self.classifier = classifier or ArcadeClassifier()
73 def filter_dat(self, dat: DATFile) -> list[FilteredGame]:
74 """Filter all games in a DAT file.
76 Args:
77 dat: Parsed DAT file
79 Returns:
80 List of FilteredGame results
81 """
82 # Pre-filter: exclude device entries (not actual games)
83 games_to_filter = [
84 g
85 for g in dat.games
86 if not g.is_device and not (g.sourcefile and g.sourcefile.startswith("devices/"))
87 ]
89 # Pre-filter by driver if specified
90 if self.config.filter_driver:
91 driver_pattern = self.config.filter_driver.lower()
92 games_to_filter = [
93 g
94 for g in games_to_filter
95 if g.sourcefile and driver_pattern in g.sourcefile.lower()
96 ]
98 # Pre-filter by romof (BIOS dependency) if specified
99 if self.config.filter_romof:
100 romof_pattern = self.config.filter_romof.lower()
101 games_to_filter = [
102 g for g in games_to_filter if g.romof and g.romof.lower() == romof_pattern
103 ]
105 # Exclude games with specific BIOS dependencies
106 if self.config.exclude_romof:
107 exclude_patterns = [p.lower() for p in self.config.exclude_romof]
108 games_to_filter = [
109 g for g in games_to_filter if not g.romof or g.romof.lower() not in exclude_patterns
110 ]
112 # Classify all games
113 classified = [(game, self.classifier.classify(game)) for game in games_to_filter]
115 # Group by parent
116 parent_groups: dict[str, list[tuple[DATGame, ArcadeClassification]]] = {}
118 for game, classification in classified:
119 parent_name = game.cloneof or game.name
120 if parent_name not in parent_groups:
121 parent_groups[parent_name] = []
122 parent_groups[parent_name].append((game, classification))
124 # Filter each group
125 results = []
126 for parent_name, group in parent_groups.items():
127 group_results = self._filter_group(parent_name, group)
128 results.extend(group_results)
130 return results
132 def _filter_group(
133 self,
134 parent_name: str,
135 group: list[tuple[DATGame, ArcadeClassification]],
136 ) -> list[FilteredGame]:
137 """Filter a group of games (parent + clones).
139 Args:
140 parent_name: Name of parent ROM
141 group: List of (game, classification) tuples
143 Returns:
144 List of FilteredGame results
145 """
146 results = []
148 # Separate by clone type
149 parent = None
150 regionals = []
151 revisions = []
152 hacks = []
153 bootlegs = []
154 prototypes = []
155 homebrew = []
156 demos = []
157 bios = []
159 for game, classification in group:
160 if classification.clone_type == ArcadeCloneType.PARENT:
161 parent = (game, classification)
162 elif classification.clone_type == ArcadeCloneType.REGIONAL:
163 regionals.append((game, classification))
164 elif classification.clone_type == ArcadeCloneType.REVISION:
165 revisions.append((game, classification))
166 elif classification.clone_type == ArcadeCloneType.HACK:
167 hacks.append((game, classification))
168 elif classification.clone_type == ArcadeCloneType.BOOTLEG:
169 bootlegs.append((game, classification))
170 elif classification.clone_type == ArcadeCloneType.PROTOTYPE:
171 prototypes.append((game, classification))
172 elif classification.clone_type == ArcadeCloneType.HOMEBREW:
173 homebrew.append((game, classification))
174 elif classification.clone_type == ArcadeCloneType.DEMO:
175 demos.append((game, classification))
176 elif classification.clone_type == ArcadeCloneType.BIOS:
177 bios.append((game, classification))
179 # Always include BIOS
180 for game, classification in bios:
181 results.append(
182 FilteredGame(
183 game=game,
184 classification=classification,
185 selected=True,
186 reason="BIOS required",
187 )
188 )
190 # Select parent or best regional variant
191 selected_main = self._select_best_main(parent, regionals, revisions)
192 if selected_main:
193 game, classification = selected_main
194 # Check if working
195 if self.config.include_working_only and not classification.is_working:
196 results.append(
197 FilteredGame(
198 game=game,
199 classification=classification,
200 selected=False,
201 reason="Non-working (preliminary driver)",
202 )
203 )
204 else:
205 results.append(
206 FilteredGame(
207 game=game,
208 classification=classification,
209 selected=True,
210 reason="Best version selected",
211 )
212 )
214 # Add rejected main variants
215 all_main = [parent] if parent else []
216 all_main.extend(regionals)
217 all_main.extend(revisions)
218 for game, classification in all_main:
219 if selected_main and game.name == selected_main[0].name:
220 continue # Already added
221 results.append(
222 FilteredGame(
223 game=game,
224 classification=classification,
225 selected=False,
226 reason=f"Alternative {classification.clone_type.value} variant",
227 )
228 )
230 # Handle hacks based on config
231 for game, classification in hacks:
232 if self.config.mode == ArcadeFilterMode.ALL:
233 selected = True
234 reason = "All mode - including all"
235 elif self.config.mode == ArcadeFilterMode.COMPLETE:
236 selected = classification.is_working
237 reason = "Working hack" if selected else "Non-working hack"
238 elif self.config.include_hacks:
239 # When include_hacks=True, include ALL hacks (not just essential/recommended)
240 # This gives users all variations so they can see what's available
241 selected = classification.is_working if self.config.include_working_only else True
242 if classification.importance in (
243 CloneImportance.ESSENTIAL,
244 CloneImportance.RECOMMENDED,
245 ):
246 reason = f"Important hack ({classification.importance.value})"
247 else:
248 reason = "Hack included (include_hacks=True)"
249 else:
250 selected = False
251 reason = "Hack filtered out"
253 results.append(
254 FilteredGame(
255 game=game,
256 classification=classification,
257 selected=selected,
258 reason=reason,
259 )
260 )
262 # Handle bootlegs
263 for game, classification in bootlegs:
264 # Essential/recommended bootlegs (like Rainbow Edition) included with hacks
265 if classification.importance in (
266 CloneImportance.ESSENTIAL,
267 CloneImportance.RECOMMENDED,
268 ):
269 if self.config.include_hacks or self.config.mode in (
270 ArcadeFilterMode.COMPLETE,
271 ArcadeFilterMode.ALL,
272 ):
273 selected = (
274 classification.is_working if self.config.include_working_only else True
275 )
276 reason = f"Important bootleg ({classification.importance.value})"
277 else:
278 selected = False
279 reason = "Important bootleg but hacks disabled"
280 elif self.config.include_bootlegs or self.config.mode == ArcadeFilterMode.ALL:
281 selected = classification.is_working if self.config.include_working_only else True
282 reason = "Bootleg included"
283 else:
284 selected = False
285 reason = "Bootleg filtered out"
287 results.append(
288 FilteredGame(
289 game=game,
290 classification=classification,
291 selected=selected,
292 reason=reason,
293 )
294 )
296 # Handle prototypes
297 for game, classification in prototypes:
298 if self.config.include_prototypes or self.config.mode in (
299 ArcadeFilterMode.COMPLETE,
300 ArcadeFilterMode.ALL,
301 ):
302 selected = classification.is_working if self.config.include_working_only else True
303 reason = "Prototype included"
304 else:
305 selected = False
306 reason = "Prototype filtered out"
308 results.append(
309 FilteredGame(
310 game=game,
311 classification=classification,
312 selected=selected,
313 reason=reason,
314 )
315 )
317 # Handle homebrew
318 for game, classification in homebrew:
319 # Quality homebrew (RECOMMENDED) included when include_homebrew=True
320 if classification.importance == CloneImportance.RECOMMENDED:
321 if self.config.include_homebrew or self.config.mode in (
322 ArcadeFilterMode.COMPLETE,
323 ArcadeFilterMode.ALL,
324 ):
325 selected = (
326 classification.is_working if self.config.include_working_only else True
327 )
328 reason = "Quality homebrew included"
329 else:
330 selected = False
331 reason = "Quality homebrew filtered (enable include_homebrew)"
332 elif self.config.mode == ArcadeFilterMode.ALL:
333 selected = classification.is_working if self.config.include_working_only else True
334 reason = "All homebrew included (ALL mode)"
335 else:
336 selected = False
337 reason = "Homebrew filtered out"
339 results.append(
340 FilteredGame(
341 game=game,
342 classification=classification,
343 selected=selected,
344 reason=reason,
345 )
346 )
348 # Handle demos
349 for game, classification in demos:
350 if self.config.include_demos or self.config.mode == ArcadeFilterMode.ALL:
351 selected = classification.is_working if self.config.include_working_only else True
352 reason = "Demo included"
353 else:
354 selected = False
355 reason = "Demo filtered out"
357 results.append(
358 FilteredGame(
359 game=game,
360 classification=classification,
361 selected=selected,
362 reason=reason,
363 )
364 )
366 return results
368 def _select_best_main(
369 self,
370 parent: tuple[DATGame, ArcadeClassification] | None,
371 regionals: list[tuple[DATGame, ArcadeClassification]],
372 revisions: list[tuple[DATGame, ArcadeClassification]],
373 ) -> tuple[DATGame, ArcadeClassification] | None:
374 """Select the best main version of a game.
376 Priority:
377 1. Preferred region (World > USA > Europe > Asia > Japan)
378 2. Latest revision
379 3. Working status
380 4. Parent if no better option
382 Args:
383 parent: Parent game tuple or None
384 regionals: List of regional variant tuples
385 revisions: List of revision tuples
387 Returns:
388 Best game tuple or None
389 """
390 candidates = []
392 if parent:
393 candidates.append(parent)
394 candidates.extend(regionals)
395 candidates.extend(revisions)
397 if not candidates:
398 return None
400 # Score each candidate
401 def score_candidate(item: tuple[DATGame, ArcadeClassification]) -> tuple:
402 game, classification = item
404 # Working status is most important
405 working_score = 1 if classification.is_working else 0
407 # Region priority
408 region_score = self.classifier.get_region_priority(classification.region)
410 # Prefer latest revision
411 revision_score = 0
412 if classification.revision:
413 # Extract number from revision
414 import re
416 match = re.search(r"\d+", classification.revision)
417 if match:
418 revision_score = int(match.group())
420 # Parent gets slight bonus (it's the "official" version)
421 parent_score = 1 if classification.clone_type == ArcadeCloneType.PARENT else 0
423 return (working_score, region_score, revision_score, parent_score)
425 # Sort by score (highest first)
426 candidates.sort(key=score_candidate, reverse=True)
428 return candidates[0]
430 def get_statistics(self, results: list[FilteredGame]) -> dict:
431 """Get filtering statistics.
433 Args:
434 results: List of FilteredGame results
436 Returns:
437 Statistics dictionary
438 """
439 total = len(results)
440 selected = sum(1 for r in results if r.selected)
441 rejected = total - selected
443 # Count by clone type
444 by_type = {}
445 for r in results:
446 ct = r.classification.clone_type.value
447 if ct not in by_type:
448 by_type[ct] = {"total": 0, "selected": 0}
449 by_type[ct]["total"] += 1
450 if r.selected:
451 by_type[ct]["selected"] += 1
453 # Count non-working
454 non_working = sum(1 for r in results if not r.classification.is_working)
456 return {
457 "total_games": total,
458 "selected": selected,
459 "rejected": rejected,
460 "non_working": non_working,
461 "by_clone_type": by_type,
462 }