Coverage for src/romfarmer/cross_platform/game_normalizer.py: 0%
80 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""
2Cross-platform game name normalization for 1G1Gen matching.
4This module provides utilities for normalizing game names across different platforms
5to identify the same game released on multiple systems. It strips platform-specific
6metadata, normalizes title variations, and extracts key identifying information.
8Example:
9 >>> normalizer = GameNameNormalizer()
10 >>> psx_game = normalizer.normalize("Grand Theft Auto (USA)", "psx")
11 >>> ps2_game = normalizer.normalize("Grand Theft Auto (USA)", "ps2")
12 >>> psx_game.match_key() == ps2_game.match_key()
13 True # Same game across platforms!
14"""
16import logging
17import re
18from dataclasses import dataclass
20logger = logging.getLogger(__name__)
23@dataclass
24class NormalizedGame:
25 """Normalized game for cross-platform matching.
27 Attributes:
28 original_name: Original game name from DAT file
29 normalized_name: Cleaned name for matching
30 platform: Platform identifier (psx, ps2, saturn, etc.)
31 region: Detected region code (USA, Europe, Japan, World)
32 year: Release year if present in name
33 revision: Revision number (0 if none)
34 file_path: Path to the actual game file
35 """
37 original_name: str
38 normalized_name: str
39 platform: str
40 region: str | None = None
41 year: str | None = None
42 revision: int = 0
43 file_path: str | None = None
45 def match_key(self) -> str:
46 """Get key for matching across platforms.
48 Games with the same match_key are considered the same game
49 on different platforms.
51 Returns:
52 Lowercase string: "normalized_name|region"
53 """
54 key = self.normalized_name
55 # Include region in match key to avoid matching different regional releases
56 # "Final Fantasy VII (USA)" should match across platforms
57 # but not match "Final Fantasy VII (Japan)"
58 if self.region:
59 key = f"{key}|{self.region}"
60 return key.lower()
62 def __repr__(self) -> str:
63 return f"NormalizedGame({self.platform}: {self.normalized_name} [{self.region}])"
66class GameNameNormalizer:
67 """Normalize game names for cross-platform matching.
69 This class handles the complex task of identifying the same game across
70 different platforms. It:
71 - Strips region/language markers
72 - Normalizes punctuation and whitespace
73 - Handles title variations (III vs 3, The vs no The)
74 - Extracts metadata (region, year, revision)
75 """
77 # Regex patterns for metadata extraction and stripping
78 REGION_PATTERN = re.compile(
79 r"\((USA?|Europe|Japan|World|Asia|Korea|En|Fr|De|Es|It|Pt|Nl|Sv|No|Da|Fi|Zh|Ja|Ko|Ru|Pl|Tr)\)",
80 re.IGNORECASE,
81 )
82 LANGUAGE_PATTERN = re.compile(r"\(([A-Z][a-z](,[A-Z][a-z])*)\)")
83 REVISION_PATTERN = re.compile(r"\((Rev|Version|v)[\s\.]?(\d+|[A-Z])\)", re.IGNORECASE)
84 DISC_PATTERN = re.compile(r"\(Disc\s+\d+(\s+of\s+\d+)?\)", re.IGNORECASE)
85 PLATFORM_HINTS = re.compile(
86 r"\((?:PS2|Xbox|GC|GameCube|PSX|PlayStation|Saturn)\s+(?:Exclusive|Only|Version)\)",
87 re.IGNORECASE,
88 )
89 YEAR_PATTERN = re.compile(r"\b(19\d{2}|20\d{2})\b")
91 # Additional patterns for cleaning
92 SUBTITLE_SEPARATOR = re.compile(r"[:\-–—]") # Various dash types
93 QUOTES_PATTERN = re.compile(r'[\'"`]')
94 BRACKETS_PATTERN = re.compile(r"\[[^\]]*\]") # [!], [b], [T+Eng], etc.
95 PARENS_CLEANUP = re.compile(r"\(\s*\)") # Empty parentheses
97 # Roman numeral to arabic conversion
98 ROMAN_NUMERALS = {
99 r"\bI\b": "1",
100 r"\bII\b": "2",
101 r"\bIII\b": "3",
102 r"\bIV\b": "4",
103 r"\bV\b": "5",
104 r"\bVI\b": "6",
105 r"\bVII\b": "7",
106 r"\bVIII\b": "8",
107 r"\bIX\b": "9",
108 r"\bX\b": "10",
109 r"\bXI\b": "11",
110 r"\bXII\b": "12",
111 }
113 # Common title variations to normalize
114 TITLE_NORMALIZATIONS = {
115 r"\bThe\s+": "", # "The Legend" -> "Legend"
116 r"\bA\s+": "", # "A Bug's Life" -> "Bug's Life"
117 r"\bAn\s+": "", # "An American Tail" -> "American Tail"
118 r"&": "and", # "Tom & Jerry" -> "Tom and Jerry"
119 }
121 @classmethod
122 def normalize(
123 cls, game_name: str, platform: str, file_path: str | None = None
124 ) -> NormalizedGame:
125 """Normalize a game name for cross-platform matching.
127 Args:
128 game_name: Original game name from DAT file
129 platform: Platform identifier (psx, ps2, saturn, gamecube, xbox, etc.)
130 file_path: Optional path to the actual game file
132 Returns:
133 NormalizedGame with extracted metadata and cleaned name
134 """
135 original = game_name
136 normalized = game_name
138 # Extract metadata BEFORE stripping
139 region = cls._extract_region(game_name)
140 year = cls._extract_year(game_name)
141 revision = cls._extract_revision(game_name)
143 logger.debug(f"Normalizing: {game_name} ({platform})")
145 # Strip brackets (Good Dump markers, translations, etc.)
146 # [!], [b], [T+Eng], [h], [f], etc.
147 normalized = cls.BRACKETS_PATTERN.sub("", normalized)
149 # Strip region markers
150 normalized = cls.REGION_PATTERN.sub("", normalized)
152 # Strip language markers
153 normalized = cls.LANGUAGE_PATTERN.sub("", normalized)
155 # Strip revision markers
156 normalized = cls.REVISION_PATTERN.sub("", normalized)
158 # Strip disc markers (multi-disc games)
159 normalized = cls.DISC_PATTERN.sub("", normalized)
161 # Strip platform hints
162 normalized = cls.PLATFORM_HINTS.sub("", normalized)
164 # Normalize Roman numerals to Arabic numbers
165 # "Final Fantasy VII" -> "Final Fantasy 7"
166 for roman, arabic in cls.ROMAN_NUMERALS.items():
167 normalized = re.sub(roman, arabic, normalized)
169 # Apply title normalizations
170 for pattern, replacement in cls.TITLE_NORMALIZATIONS.items():
171 normalized = re.sub(pattern, replacement, normalized, flags=re.IGNORECASE)
173 # Normalize punctuation (colons, dashes, quotes)
174 normalized = cls.SUBTITLE_SEPARATOR.sub(" ", normalized)
175 normalized = cls.QUOTES_PATTERN.sub("", normalized)
177 # Clean up empty parentheses
178 normalized = cls.PARENS_CLEANUP.sub("", normalized)
180 # Normalize whitespace
181 normalized = re.sub(r"\s+", " ", normalized).strip()
183 # Final cleanup - remove trailing/leading punctuation
184 normalized = normalized.strip(" .-,")
186 result = NormalizedGame(
187 original_name=original,
188 normalized_name=normalized,
189 platform=platform,
190 region=region,
191 year=year,
192 revision=revision,
193 file_path=file_path,
194 )
196 logger.debug(f" -> {result.normalized_name} | {result.region} | key={result.match_key()}")
198 return result
200 @staticmethod
201 def _extract_region(name: str) -> str | None:
202 """Extract region code from game name.
204 Returns:
205 Region code (USA, Europe, Japan, World) or None
206 """
207 # Look for common region patterns
208 patterns = [
209 (r"\(USA?\)", "USA"),
210 (r"\(U\)", "USA"),
211 (r"\(Europe\)", "Europe"),
212 (r"\(E\)", "Europe"),
213 (r"\(Japan\)", "Japan"),
214 (r"\(J\)", "Japan"),
215 (r"\(World\)", "World"),
216 (r"\(W\)", "World"),
217 ]
219 for pattern, region in patterns:
220 if re.search(pattern, name, re.IGNORECASE):
221 return region
223 return None
225 @staticmethod
226 def _extract_year(name: str) -> str | None:
227 """Extract year if present in game name.
229 Returns:
230 Year as string (e.g., "2001") or None
231 """
232 match = re.search(r"\b(19\d{2}|20\d{2})\b", name)
233 return match.group(1) if match else None
235 @staticmethod
236 def _extract_revision(name: str) -> int:
237 """Extract revision number from game name.
239 Handles:
240 - (Rev 1), (Rev A)
241 - (Version 1.1)
242 - (v1.2)
244 Returns:
245 Revision number (0 if none, 1 for Rev A, 2 for Rev B, etc.)
246 """
247 match = re.search(r"\((Rev|Version|v)[\s\.]?(\d+|[A-Z])\)", name, re.IGNORECASE)
248 if match:
249 rev_str = match.group(2)
250 if rev_str.isdigit():
251 return int(rev_str)
252 elif rev_str.isalpha():
253 # Rev A = 1, Rev B = 2, etc.
254 return ord(rev_str.upper()) - ord("A") + 1
255 return 0