Coverage for src/romfarmer/metadata/transformation_recorder.py: 30%

123 statements  

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

1""" 

2Transformation Recorder for ROM processing. 

3 

4This module records ROM transformations as they happen during processing. 

5It captures: 

6- Source file hashes (from DAT or calculation) 

7- Transformation metadata (tool, version, parameters) 

8- Final file hashes (after processing) 

9 

10Example workflow: 

11 recorder = TransformationRecorder(db, dat_manager) 

12 

13 # Start recording a transformation 

14 with recorder.record_transformation( 

15 source_file=Path("game.iso"), 

16 system="saturn", 

17 tool="chdman", 

18 version="0.251", 

19 params={"compression": "zstd"} 

20 ) as transform: 

21 # Do the actual processing 

22 final_file = process_with_chdman(source_file) 

23 

24 # Record the final file 

25 transform.set_final_file(final_file) 

26 

27 # Transformation automatically saved with timing info! 

28""" 

29 

30import json 

31import time 

32from contextlib import contextmanager 

33from dataclasses import dataclass 

34from datetime import datetime 

35from pathlib import Path 

36from typing import Any 

37 

38from rich.console import Console 

39from sqlalchemy.orm import Session 

40 

41from .dat_manager import DATManager 

42from .database import ScrapedGame 

43from .hash_capture import SmartHashCapture 

44from .transformation import ROMTransformation 

45 

46console = Console() 

47 

48 

49@dataclass 

50class TransformationContext: 

51 """Context for an in-progress transformation.""" 

52 

53 recorder: "TransformationRecorder" 

54 source_file: Path 

55 system: str 

56 tool: str 

57 version: str 

58 params: dict[str, Any] 

59 

60 # Captured at start 

61 source_hashes: Any # SourceHashInfo 

62 start_time: float 

63 

64 # Will be set during processing 

65 final_file: Path | None = None 

66 final_hashes: Any = None 

67 

68 def set_final_file(self, final_file: Path): 

69 """ 

70 Record the final processed file. 

71 

72 This captures the final file's hashes and prepares for storage. 

73 """ 

74 if not final_file.exists(): 

75 raise FileNotFoundError(f"Final file not found: {final_file}") 

76 

77 console.print(f"[cyan]Capturing final file hashes:[/cyan] {final_file.name}") 

78 

79 # Capture final file hashes (no DAT lookup, just calculate/cache) 

80 self.final_file = final_file 

81 self.final_hashes = self.recorder.hash_capture.get_source_hashes( 

82 final_file, 

83 system=None, # Don't look in DAT for final files 

84 force_calculate=False, # Use cache if available 

85 ) 

86 

87 def get_duration(self) -> float: 

88 """Get transformation duration in seconds.""" 

89 return time.time() - self.start_time 

90 

91 

92class TransformationRecorder: 

93 """ 

94 Records ROM transformations during processing. 

95 

96 This class integrates with your ROM processing workflow to automatically 

97 capture and store transformation metadata. 

98 """ 

99 

100 def __init__(self, session: Session, dat_manager: DATManager | None = None): 

101 """ 

102 Initialize transformation recorder. 

103 

104 Args: 

105 session: Database session 

106 dat_manager: Optional DAT manager for source hash lookup 

107 """ 

108 self.session = session 

109 self.dat_manager = dat_manager 

110 self.hash_capture = SmartHashCapture(dat_manager, session) 

111 

112 # Statistics 

113 self.stats = { 

114 "transformations_recorded": 0, 

115 "source_from_dat": 0, 

116 "source_calculated": 0, 

117 "total_duration": 0.0, 

118 } 

119 

120 @contextmanager 

121 def record_transformation( 

122 self, 

123 source_file: Path, 

124 system: str, 

125 tool: str, 

126 version: str, 

127 params: dict[str, Any] | None = None, 

128 ): 

129 """ 

130 Context manager for recording a transformation. 

131 

132 Usage: 

133 with recorder.record_transformation( 

134 source_file=Path("game.iso"), 

135 system="saturn", 

136 tool="chdman", 

137 version="0.251", 

138 params={"compression": "zstd"} 

139 ) as transform: 

140 # Do processing 

141 final_file = process_rom(source_file) 

142 transform.set_final_file(final_file) 

143 

144 Args: 

145 source_file: Source ROM file (before transformation) 

146 system: System name (e.g., "saturn", "xbox360") 

147 tool: Transformation tool (e.g., "chdman", "extract-xiso") 

148 version: Tool version 

149 params: Optional transformation parameters 

150 

151 Yields: 

152 TransformationContext that you call set_final_file() on 

153 """ 

154 if not source_file.exists(): 

155 raise FileNotFoundError(f"Source file not found: {source_file}") 

156 

157 console.print("\n[bold cyan]Recording Transformation[/bold cyan]") 

158 console.print(f" Source: {source_file.name}") 

159 console.print(f" System: {system}") 

160 console.print(f" Tool: {tool} v{version}") 

161 

162 # Capture source file hashes 

163 console.print("[cyan]Capturing source file hashes...[/cyan]") 

164 source_hashes = self.hash_capture.get_source_hashes(source_file, system=system) 

165 

166 if source_hashes.from_dat: 

167 console.print(f" [green]✓ Source hashes from DAT: {source_hashes.dat_name}[/green]") 

168 self.stats["source_from_dat"] += 1 

169 else: 

170 console.print( 

171 f" [yellow]⚠ Source hashes calculated ({source_hashes.calculation_time:.1f}s)[/yellow]" 

172 ) 

173 self.stats["source_calculated"] += 1 

174 

175 # Create transformation context 

176 context = TransformationContext( 

177 recorder=self, 

178 source_file=source_file, 

179 system=system, 

180 tool=tool, 

181 version=version, 

182 params=params or {}, 

183 source_hashes=source_hashes, 

184 start_time=time.time(), 

185 ) 

186 

187 try: 

188 # Yield to processing code 

189 yield context 

190 

191 # After processing, save the transformation 

192 if context.final_file is None: 

193 console.print( 

194 "[yellow]⚠ Warning: Final file not set, skipping transformation record[/yellow]" 

195 ) 

196 return 

197 

198 self._save_transformation(context) 

199 

200 except Exception as e: 

201 console.print(f"[red]✗ Error during transformation recording:[/red] {e}") 

202 raise 

203 

204 def _save_transformation(self, context: TransformationContext): 

205 """Save transformation to database.""" 

206 duration = context.get_duration() 

207 

208 console.print("\n[bold green]✓ Transformation Complete[/bold green]") 

209 console.print(f" Duration: {duration:.1f}s") 

210 console.print(f" Source MD5: {context.source_hashes.md5}") 

211 console.print(f" Final MD5: {context.final_hashes.md5}") 

212 

213 # Check if transformation already exists 

214 existing = ( 

215 self.session.query(ROMTransformation) 

216 .filter_by( 

217 source_md5=context.source_hashes.md5, 

218 final_md5=context.final_hashes.md5, 

219 ) 

220 .first() 

221 ) 

222 

223 if existing: 

224 console.print( 

225 f"[yellow] ⚠ Transformation already exists (id={existing.id}), updating...[/yellow]" 

226 ) 

227 # Update existing record 

228 existing.transformation_tool = context.tool 

229 existing.transformation_version = context.version 

230 existing.transformation_params = json.dumps(context.params) 

231 existing.transformation_date = datetime.utcnow() 

232 existing.transformation_duration_seconds = duration 

233 

234 # Update hashes if different 

235 existing.source_sha1 = context.source_hashes.sha1 

236 existing.source_sha256 = context.source_hashes.sha256 

237 existing.source_crc32 = context.source_hashes.crc32 

238 existing.final_sha1 = context.final_hashes.sha1 

239 existing.final_sha256 = context.final_hashes.sha256 

240 existing.final_crc32 = context.final_hashes.crc32 

241 

242 transformation = existing 

243 else: 

244 # Create new transformation record 

245 transformation = ROMTransformation( 

246 # Source file info 

247 source_md5=context.source_hashes.md5, 

248 source_sha1=context.source_hashes.sha1, 

249 source_sha256=context.source_hashes.sha256, 

250 source_crc32=context.source_hashes.crc32, 

251 source_file_size=context.source_hashes.size, 

252 source_file_name=context.source_file.name, 

253 source_format=context.source_file.suffix.lstrip(".").lower(), 

254 source_dat=context.source_hashes.dat_name 

255 if context.source_hashes.from_dat 

256 else None, 

257 source_verified=context.source_hashes.from_dat, 

258 # Transformation metadata 

259 transformation_tool=context.tool, 

260 transformation_version=context.version, 

261 transformation_params=json.dumps(context.params), 

262 transformation_date=datetime.utcnow(), 

263 transformation_duration_seconds=duration, 

264 # Final file info 

265 final_md5=context.final_hashes.md5, 

266 final_sha1=context.final_hashes.sha1, 

267 final_sha256=context.final_hashes.sha256, 

268 final_crc32=context.final_hashes.crc32, 

269 final_file_size=context.final_hashes.size, 

270 final_file_name=context.final_file.name, 

271 final_format=context.final_file.suffix.lstrip(".").lower(), 

272 # Verification 

273 verified=context.source_hashes.from_dat, # Verified if source is from DAT 

274 verification_count=1 if context.source_hashes.from_dat else 0, 

275 community_reported=False, 

276 ) 

277 

278 self.session.add(transformation) 

279 console.print("[green] ✓ Created new transformation record[/green]") 

280 

281 self.session.commit() 

282 

283 # Update statistics 

284 self.stats["transformations_recorded"] += 1 

285 self.stats["total_duration"] += duration 

286 

287 console.print( 

288 f"[green] ✓ Transformation saved to database (id={transformation.id})[/green]" 

289 ) 

290 

291 def find_source_hash(self, final_file: Path) -> ROMTransformation | None: 

292 """ 

293 Reverse lookup: Given a final file, find the source hash. 

294 

295 This is useful for ScreenScraper lookups - you can find the original 

296 ISO/ROM hash even though you only have the CHD/XISO/CSO file. 

297 

298 Args: 

299 final_file: The final processed file 

300 

301 Returns: 

302 ROMTransformation if found, None otherwise 

303 """ 

304 console.print(f"[cyan]Looking up source hash for:[/cyan] {final_file.name}") 

305 

306 # First, get the final file's hash 

307 final_hashes = self.hash_capture.get_source_hashes( 

308 final_file, system=None, force_calculate=False 

309 ) 

310 

311 # Look up transformation by final hash 

312 transformation = ( 

313 self.session.query(ROMTransformation).filter_by(final_md5=final_hashes.md5).first() 

314 ) 

315 

316 if transformation: 

317 console.print(f"[green] ✓ Found source hash:[/green] {transformation.source_md5}") 

318 return transformation 

319 else: 

320 console.print("[yellow] ⚠ No transformation found for this file[/yellow]") 

321 return None 

322 

323 def link_to_game(self, transformation: ROMTransformation, game_name: str, system: str): 

324 """ 

325 Link a transformation to a scraped game. 

326 

327 This creates the connection between the transformation and the game metadata. 

328 """ 

329 # Find game by name and system 

330 game = self.session.query(ScrapedGame).filter_by(name=game_name, system=system).first() 

331 

332 if game: 

333 transformation.game_id = game.id 

334 self.session.commit() 

335 console.print(f"[green]✓ Linked transformation to game:[/green] {game_name}") 

336 else: 

337 console.print(f"[yellow]⚠ Game not found in database:[/yellow] {game_name}") 

338 

339 def get_stats(self) -> dict[str, Any]: 

340 """Get transformation recording statistics.""" 

341 return { 

342 "transformations_recorded": self.stats["transformations_recorded"], 

343 "source_from_dat": self.stats["source_from_dat"], 

344 "source_calculated": self.stats["source_calculated"], 

345 "avg_duration": ( 

346 self.stats["total_duration"] / self.stats["transformations_recorded"] 

347 if self.stats["transformations_recorded"] > 0 

348 else 0.0 

349 ), 

350 "total_duration": self.stats["total_duration"], 

351 } 

352 

353 def print_stats(self): 

354 """Print transformation recording statistics.""" 

355 stats = self.get_stats() 

356 

357 if stats["transformations_recorded"] == 0: 

358 console.print("[yellow]No transformations recorded yet[/yellow]") 

359 return 

360 

361 console.print("\n[bold cyan]Transformation Recording Statistics:[/bold cyan]") 

362 console.print(f" Transformations Recorded: {stats['transformations_recorded']}") 

363 console.print(f" Source from DAT: {stats['source_from_dat']}") 

364 console.print(f" Source Calculated: {stats['source_calculated']}") 

365 console.print(f" Avg Duration: {stats['avg_duration']:.1f}s") 

366 console.print(f" Total Duration: {stats['total_duration']:.1f}s") 

367 

368 # Show hash capture stats too 

369 self.hash_capture.print_stats()