Coverage for src/romfarmer/metadata/dat_parser.py: 0%

231 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1""" 

2DAT file parser for No-Intro, Redump, FBNeo, and MAME DAT files. 

3 

4Extracts: 

5- Parent-clone relationships (cloneof/romof) 

6- Year, manufacturer 

7- Source file (hardware driver) 

8- Video specs (resolution, orientation) 

9- Driver status (emulation quality) 

10- Comments (bootleg, prototype, etc.) 

11""" 

12 

13import logging 

14import re 

15import xml.etree.ElementTree as ET 

16from collections.abc import Iterator 

17from dataclasses import dataclass 

18from pathlib import Path 

19 

20logger = logging.getLogger(__name__) 

21 

22 

23@dataclass 

24class VideoSpec: 

25 """Video hardware specifications.""" 

26 

27 type: str = "raster" # raster or vector 

28 orientation: str = "horizontal" # horizontal or vertical 

29 width: int = 0 

30 height: int = 0 

31 aspect_x: int = 4 

32 aspect_y: int = 3 

33 refresh: float = 60.0 

34 

35 @property 

36 def resolution(self) -> str: 

37 if self.width and self.height: 

38 return f"{self.width}x{self.height}" 

39 return "" 

40 

41 @property 

42 def aspect_ratio(self) -> str: 

43 return f"{self.aspect_x}:{self.aspect_y}" 

44 

45 

46@dataclass 

47class DatGame: 

48 """Represents a game entry from a DAT file.""" 

49 

50 name: str # ROM name (e.g., "sf2ce") 

51 description: str # Full title (e.g., "Street Fighter II': Champion Edition") 

52 year: str | None = None 

53 manufacturer: str | None = None 

54 

55 # Parent-clone relationships 

56 cloneof: str | None = None # Parent game name 

57 romof: str | None = None # ROM parent (for merged sets) 

58 sampleof: str | None = None # Sample parent 

59 

60 # Hardware/driver info 

61 sourcefile: str | None = None # Driver source (e.g., "capcom/d_cps1.cpp") 

62 driver_status: str = "good" # good, imperfect, preliminary 

63 

64 # Video specs 

65 video: VideoSpec | None = None 

66 

67 # Metadata 

68 comment: str | None = None # Bootleg, Prototype, etc. 

69 category: str | None = None 

70 

71 # ROM hashes (first ROM only for identification) 

72 rom_name: str | None = None 

73 rom_crc: str | None = None 

74 rom_size: int | None = None 

75 

76 # Source DAT info 

77 dat_name: str | None = None 

78 dat_type: str | None = None # fbneo, mame, nointro, redump 

79 

80 @property 

81 def hardware(self) -> str | None: 

82 """Extract hardware name from sourcefile.""" 

83 if not self.sourcefile: 

84 return None 

85 # capcom/d_cps1.cpp -> cps1 

86 # sega/d_megadrive.cpp -> megadrive 

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

88 if match: 

89 return match.group(1) 

90 # Also try without d_ prefix 

91 match = re.search(r"/(\w+)\.cpp", self.sourcefile) 

92 if match: 

93 return match.group(1) 

94 return self.sourcefile 

95 

96 @property 

97 def hardware_family(self) -> str | None: 

98 """Extract hardware family from sourcefile path.""" 

99 if not self.sourcefile: 

100 return None 

101 # capcom/d_cps1.cpp -> capcom 

102 parts = self.sourcefile.split("/") 

103 if len(parts) >= 2: 

104 return parts[0] 

105 return None 

106 

107 @property 

108 def is_clone(self) -> bool: 

109 return self.cloneof is not None 

110 

111 @property 

112 def is_bootleg(self) -> bool: 

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

114 return True 

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

116 return True 

117 return False 

118 

119 @property 

120 def is_prototype(self) -> bool: 

121 if self.comment and "proto" in self.comment.lower(): 

122 return True 

123 if self.description and "proto" in self.description.lower(): 

124 return True 

125 return False 

126 

127 

128class DatParser: 

129 """Parser for various DAT file formats.""" 

130 

131 def __init__(self, dat_path: Path): 

132 self.dat_path = Path(dat_path) 

133 self.dat_name: str | None = None 

134 self.dat_description: str | None = None 

135 self.dat_version: str | None = None 

136 self.dat_type: str | None = None 

137 

138 def _detect_dat_type(self, root: ET.Element) -> str: 

139 """Detect DAT type from content.""" 

140 header = root.find("header") 

141 if header is not None: 

142 name = header.findtext("name", "").lower() 

143 if "fbneo" in name or "finalburn" in name: 

144 return "fbneo" 

145 elif "mame" in name: 

146 return "mame" 

147 elif "no-intro" in name or "nointro" in name: 

148 return "nointro" 

149 elif "redump" in name: 

150 return "redump" 

151 

152 # Check for machine vs game elements (MAME uses machine) 

153 if root.find("machine") is not None: 

154 return "mame" 

155 

156 return "unknown" 

157 

158 def _parse_header(self, root: ET.Element) -> None: 

159 """Parse DAT header information.""" 

160 header = root.find("header") 

161 if header is not None: 

162 self.dat_name = header.findtext("name") 

163 self.dat_description = header.findtext("description") 

164 self.dat_version = header.findtext("version") 

165 self.dat_type = self._detect_dat_type(root) 

166 

167 def _parse_video(self, game_elem: ET.Element) -> VideoSpec | None: 

168 """Parse video element.""" 

169 video_elem = game_elem.find("video") 

170 if video_elem is None: 

171 return None 

172 

173 video = VideoSpec() 

174 video.type = video_elem.get("type", "raster") 

175 video.orientation = video_elem.get("orientation", "horizontal") 

176 

177 width = video_elem.get("width") 

178 if width: 

179 video.width = int(width) 

180 

181 height = video_elem.get("height") 

182 if height: 

183 video.height = int(height) 

184 

185 aspect_x = video_elem.get("aspectx") 

186 if aspect_x: 

187 video.aspect_x = int(aspect_x) 

188 

189 aspect_y = video_elem.get("aspecty") 

190 if aspect_y: 

191 video.aspect_y = int(aspect_y) 

192 

193 refresh = video_elem.get("refresh") 

194 if refresh: 

195 video.refresh = float(refresh) 

196 

197 return video 

198 

199 def _parse_game(self, game_elem: ET.Element) -> DatGame: 

200 """Parse a single game/machine element.""" 

201 # Get basic attributes 

202 name = game_elem.get("name", "") 

203 

204 game = DatGame( 

205 name=name, 

206 description=game_elem.findtext("description", name), 

207 year=game_elem.findtext("year"), 

208 manufacturer=game_elem.findtext("manufacturer"), 

209 cloneof=game_elem.get("cloneof"), 

210 romof=game_elem.get("romof"), 

211 sampleof=game_elem.get("sampleof"), 

212 sourcefile=game_elem.get("sourcefile"), 

213 comment=game_elem.findtext("comment"), 

214 category=game_elem.findtext("category"), 

215 dat_name=self.dat_name, 

216 dat_type=self.dat_type, 

217 ) 

218 

219 # Parse video specs 

220 game.video = self._parse_video(game_elem) 

221 

222 # Parse driver status 

223 driver_elem = game_elem.find("driver") 

224 if driver_elem is not None: 

225 game.driver_status = driver_elem.get("status", "good") 

226 

227 # Get first ROM for identification 

228 rom_elem = game_elem.find("rom") 

229 if rom_elem is not None: 

230 game.rom_name = rom_elem.get("name") 

231 game.rom_crc = rom_elem.get("crc") 

232 size = rom_elem.get("size") 

233 if size: 

234 game.rom_size = int(size) 

235 

236 return game 

237 

238 def parse(self) -> Iterator[DatGame]: 

239 """Parse DAT file and yield game entries.""" 

240 logger.info(f"Parsing DAT file: {self.dat_path}") 

241 

242 try: 

243 tree = ET.parse(self.dat_path) 

244 root = tree.getroot() 

245 except ET.ParseError as e: 

246 logger.error(f"Failed to parse DAT file: {e}") 

247 return 

248 

249 self._parse_header(root) 

250 logger.info(f"DAT: {self.dat_name} ({self.dat_type}), version: {self.dat_version}") 

251 

252 # Find all game/machine elements 

253 game_tag = "machine" if self.dat_type == "mame" else "game" 

254 

255 count = 0 

256 for game_elem in root.findall(game_tag): 

257 yield self._parse_game(game_elem) 

258 count += 1 

259 

260 logger.info(f"Parsed {count} games from {self.dat_path.name}") 

261 

262 def parse_all(self) -> list[DatGame]: 

263 """Parse DAT file and return all games as a list.""" 

264 return list(self.parse()) 

265 

266 

267def get_hardware_games(dat_path: Path, hardware: str) -> list[DatGame]: 

268 """Get all games for a specific hardware/driver.""" 

269 parser = DatParser(dat_path) 

270 games = [] 

271 

272 hardware_lower = hardware.lower() 

273 

274 for game in parser.parse(): 

275 if game.hardware and hardware_lower in game.hardware.lower(): 

276 games.append(game) 

277 elif game.sourcefile and hardware_lower in game.sourcefile.lower(): 

278 games.append(game) 

279 

280 return games 

281 

282 

283def get_game_variants(dat_path: Path, game_name: str) -> dict: 

284 """Get a game and all its variants/clones.""" 

285 parser = DatParser(dat_path) 

286 all_games = {g.name: g for g in parser.parse()} 

287 

288 # Find the target game 

289 target = all_games.get(game_name) 

290 if not target: 

291 # Try to find by partial match 

292 for name, game in all_games.items(): 

293 if game_name.lower() in name.lower(): 

294 target = game 

295 break 

296 

297 if not target: 

298 return {"parent": None, "clones": []} 

299 

300 # Find the root parent 

301 parent = target 

302 while parent.cloneof and parent.cloneof in all_games: 

303 parent = all_games[parent.cloneof] 

304 

305 # Find all clones of the parent 

306 clones = [g for g in all_games.values() if g.cloneof == parent.name] 

307 

308 return { 

309 "parent": parent, 

310 "clones": sorted(clones, key=lambda g: g.name), 

311 "target": target, 

312 } 

313 

314 

315# Quick test 

316if __name__ == "__main__": 

317 import sys 

318 

319 if len(sys.argv) < 2: 

320 print("Usage: python dat_parser.py <dat_file> [hardware|game_name]") 

321 sys.exit(1) 

322 

323 dat_path = Path(sys.argv[1]) 

324 

325 if len(sys.argv) >= 3: 

326 query = sys.argv[2] 

327 

328 # Try hardware search first 

329 games = get_hardware_games(dat_path, query) 

330 if games: 

331 print(f"\n=== {query.upper()} Games ({len(games)}) ===\n") 

332 for g in sorted(games, key=lambda x: x.description): 

333 status = f"[{g.driver_status}]" if g.driver_status != "good" else "" 

334 clone = f" (clone of {g.cloneof})" if g.cloneof else "" 

335 print(f" {g.name}: {g.description}{clone} {status}") 

336 else: 

337 # Try game variant search 

338 result = get_game_variants(dat_path, query) 

339 if result["parent"]: 

340 p = result["parent"] 

341 print(f"\n=== {p.description} ({p.name}) ===") 

342 print(f"Year: {p.year}") 

343 print(f"Manufacturer: {p.manufacturer}") 

344 print(f"Hardware: {p.hardware}") 

345 if p.video: 

346 print(f"Video: {p.video.resolution} {p.video.orientation}") 

347 print(f"\nClones ({len(result['clones'])}):") 

348 for c in result["clones"]: 

349 print(f" - {c.name}: {c.description}") 

350 else: 

351 # Just parse and show stats 

352 parser = DatParser(dat_path) 

353 games = parser.parse_all() 

354 

355 print(f"\nDAT: {parser.dat_name}") 

356 print(f"Type: {parser.dat_type}") 

357 print(f"Total games: {len(games)}") 

358 print(f"Parents: {len([g for g in games if not g.cloneof])}") 

359 print(f"Clones: {len([g for g in games if g.cloneof])}") 

360 

361 # Hardware breakdown 

362 hw_counts = {} 

363 for g in games: 

364 hw = g.hardware or "unknown" 

365 hw_counts[hw] = hw_counts.get(hw, 0) + 1 

366 

367 print("\nTop hardware:") 

368 for hw, count in sorted(hw_counts.items(), key=lambda x: -x[1])[:20]: 

369 print(f" {hw}: {count}")