Coverage for src/romfarmer/metadata/hash_capture.py: 28%

119 statements  

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

1""" 

2Smart Hash Capture with 3-tier strategy. 

3 

4This module provides intelligent hash capture that avoids expensive 

5calculation when possible: 

6 

7Tier 1: DAT file lookup (0.001s - 95% of files) 

8Tier 2: Hash cache (0.1s - 4% of files) 

9Tier 3: Calculate (120s - 1% of files) 

10 

11Expected speedup: 20x-50x for source hash capture. 

12""" 

13 

14import hashlib 

15import time 

16from dataclasses import dataclass 

17from datetime import datetime 

18from pathlib import Path 

19 

20from rich.console import Console 

21from rich.progress import Progress, SpinnerColumn, TextColumn 

22from sqlalchemy.orm import Session 

23 

24from .dat_manager import DATManager 

25from .transformation import HashCache 

26 

27console = Console() 

28 

29 

30@dataclass 

31class SourceHashInfo: 

32 """Complete hash information for a source file.""" 

33 

34 md5: str | None = None 

35 sha1: str | None = None 

36 sha256: str | None = None 

37 crc32: str | None = None 

38 size: int | None = None 

39 

40 # Metadata 

41 from_dat: bool = False # Was this from a DAT file? 

42 dat_name: str | None = None # Which DAT? 

43 from_cache: bool = False # Was this from cache? 

44 calculated: bool = False # Was this calculated? 

45 calculation_time: float = 0.0 # Seconds 

46 

47 def __repr__(self): 

48 source = "DAT" if self.from_dat else "Cache" if self.from_cache else "Calculated" 

49 return f"<SourceHashInfo(md5='{self.md5[:8] if self.md5 else 'None'}...', source={source})>" 

50 

51 

52class SmartHashCapture: 

53 """ 

54 Intelligent hash capture with 3-tier fallback strategy. 

55 

56 This class tries to avoid expensive hash calculation by: 

57 1. Looking up in DAT files (instant) 

58 2. Looking up in hash cache (fast) 

59 3. Calculating only when necessary (slow) 

60 

61 Example: 

62 capture = SmartHashCapture(dat_manager, db_session) 

63 

64 # Try to get hashes for a file 

65 hashes = capture.get_source_hashes( 

66 Path("/path/to/roms/Halo 3 (USA).iso"), 

67 system="xbox360" 

68 ) 

69 

70 if hashes.from_dat: 

71 print("Found in DAT! Instant!") 

72 elif hashes.from_cache: 

73 print("Found in cache! Fast!") 

74 else: 

75 print(f"Had to calculate (took {hashes.calculation_time:.1f}s)") 

76 """ 

77 

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

79 """ 

80 Initialize smart hash capture. 

81 

82 Args: 

83 dat_manager: DAT manager for Tier 1 lookups (optional) 

84 session: Database session for cache operations 

85 """ 

86 self.dat_manager = dat_manager 

87 self.session = session 

88 

89 # Statistics 

90 self.stats = { 

91 "dat_hits": 0, 

92 "cache_hits": 0, 

93 "calculated": 0, 

94 "total_calculation_time": 0.0, 

95 } 

96 

97 def get_source_hashes( 

98 self, file_path: Path, system: str | None = None, force_calculate: bool = False 

99 ) -> SourceHashInfo: 

100 """ 

101 Get hashes for a source file using 3-tier strategy. 

102 

103 Args: 

104 file_path: Path to file to hash 

105 system: System name (e.g., "xbox360") for DAT lookup 

106 force_calculate: Skip DAT/cache and force calculation 

107 

108 Returns: 

109 SourceHashInfo with hashes and metadata 

110 """ 

111 if not file_path.exists(): 

112 raise FileNotFoundError(f"File not found: {file_path}") 

113 

114 file_size = file_path.stat().st_size 

115 

116 # Tier 1: Try DAT lookup 

117 if not force_calculate and self.dat_manager and system: 

118 dat_entry = self.dat_manager.lookup_by_filename(file_path.name, system) 

119 if dat_entry: 

120 self.stats["dat_hits"] += 1 

121 return SourceHashInfo( 

122 md5=dat_entry.md5, 

123 sha1=dat_entry.sha1, 

124 sha256=dat_entry.sha256, 

125 crc32=dat_entry.crc32, 

126 size=dat_entry.size, 

127 from_dat=True, 

128 dat_name=dat_entry.dat_name, 

129 ) 

130 

131 # Tier 2: Try cache lookup 

132 if not force_calculate: 

133 cached = self._lookup_cache(file_path, file_size) 

134 if cached: 

135 self.stats["cache_hits"] += 1 

136 return cached 

137 

138 # Tier 3: Calculate 

139 calculated = self._calculate_hashes(file_path, file_size) 

140 self.stats["calculated"] += 1 

141 self.stats["total_calculation_time"] += calculated.calculation_time 

142 

143 # Store in cache for future lookups 

144 self._store_cache(file_path, file_size, calculated) 

145 

146 return calculated 

147 

148 def _lookup_cache(self, file_path: Path, file_size: int) -> SourceHashInfo | None: 

149 """ 

150 Look up hashes in cache. 

151 

152 Cache is valid if file path, size, and mtime match. 

153 """ 

154 file_mtime = datetime.fromtimestamp(file_path.stat().st_mtime) 

155 

156 cached = ( 

157 self.session.query(HashCache) 

158 .filter_by( 

159 file_path=str(file_path), 

160 file_size=file_size, 

161 file_mtime=file_mtime, 

162 ) 

163 .first() 

164 ) 

165 

166 if cached: 

167 return SourceHashInfo( 

168 md5=cached.md5, 

169 sha1=cached.sha1, 

170 sha256=cached.sha256, 

171 crc32=cached.crc32, 

172 size=file_size, 

173 from_cache=True, 

174 ) 

175 

176 return None 

177 

178 def _calculate_hashes(self, file_path: Path, file_size: int) -> SourceHashInfo: 

179 """ 

180 Calculate all hashes for a file. 

181 

182 This is the slow path - only used for files not in DAT or cache. 

183 Shows progress for large files (>100MB). 

184 """ 

185 start_time = time.time() 

186 

187 # Initialize hashers 

188 md5 = hashlib.md5() 

189 sha1 = hashlib.sha1() 

190 sha256 = hashlib.sha256() 

191 crc32 = 0 

192 

193 # Read file in chunks 

194 chunk_size = 8192 * 1024 # 8MB chunks 

195 show_progress = file_size > 100 * 1024 * 1024 # Show for files >100MB 

196 

197 if show_progress: 

198 with Progress( 

199 SpinnerColumn(), 

200 TextColumn("[progress.description]{task.description}"), 

201 console=console, 

202 ) as progress: 

203 progress.add_task(f"Calculating hashes for {file_path.name}...", total=None) 

204 

205 with open(file_path, "rb") as f: 

206 while chunk := f.read(chunk_size): 

207 md5.update(chunk) 

208 sha1.update(chunk) 

209 sha256.update(chunk) 

210 crc32 = self._update_crc32(crc32, chunk) 

211 else: 

212 with open(file_path, "rb") as f: 

213 while chunk := f.read(chunk_size): 

214 md5.update(chunk) 

215 sha1.update(chunk) 

216 sha256.update(chunk) 

217 crc32 = self._update_crc32(crc32, chunk) 

218 

219 calculation_time = time.time() - start_time 

220 

221 return SourceHashInfo( 

222 md5=md5.hexdigest(), 

223 sha1=sha1.hexdigest(), 

224 sha256=sha256.hexdigest(), 

225 crc32=f"{crc32:08x}", 

226 size=file_size, 

227 calculated=True, 

228 calculation_time=calculation_time, 

229 ) 

230 

231 def _update_crc32(self, crc: int, data: bytes) -> int: 

232 """Update CRC32 checksum.""" 

233 import zlib 

234 

235 return zlib.crc32(data, crc) & 0xFFFFFFFF 

236 

237 def _store_cache(self, file_path: Path, file_size: int, hashes: SourceHashInfo): 

238 """Store calculated hashes in cache.""" 

239 file_mtime = datetime.fromtimestamp(file_path.stat().st_mtime) 

240 

241 # Check if cache entry exists 

242 cached = self.session.query(HashCache).filter_by(file_path=str(file_path)).first() 

243 

244 if cached: 

245 # Update existing 

246 cached.file_size = file_size 

247 cached.file_mtime = file_mtime 

248 cached.md5 = hashes.md5 

249 cached.sha1 = hashes.sha1 

250 cached.sha256 = hashes.sha256 

251 cached.crc32 = hashes.crc32 

252 cached.calculation_time_seconds = hashes.calculation_time 

253 else: 

254 # Create new 

255 cached = HashCache( 

256 file_path=str(file_path), 

257 file_size=file_size, 

258 file_mtime=file_mtime, 

259 md5=hashes.md5, 

260 sha1=hashes.sha1, 

261 sha256=hashes.sha256, 

262 crc32=hashes.crc32, 

263 calculation_time_seconds=hashes.calculation_time, 

264 ) 

265 self.session.add(cached) 

266 

267 self.session.commit() 

268 

269 def get_stats(self) -> dict: 

270 """Get statistics on cache performance.""" 

271 total = sum([self.stats["dat_hits"], self.stats["cache_hits"], self.stats["calculated"]]) 

272 

273 if total == 0: 

274 return { 

275 "total_lookups": 0, 

276 "dat_hit_rate": 0.0, 

277 "cache_hit_rate": 0.0, 

278 "calculation_rate": 0.0, 

279 "avg_calculation_time": 0.0, 

280 } 

281 

282 return { 

283 "total_lookups": total, 

284 "dat_hits": self.stats["dat_hits"], 

285 "cache_hits": self.stats["cache_hits"], 

286 "calculated": self.stats["calculated"], 

287 "dat_hit_rate": self.stats["dat_hits"] / total * 100, 

288 "cache_hit_rate": self.stats["cache_hits"] / total * 100, 

289 "calculation_rate": self.stats["calculated"] / total * 100, 

290 "avg_calculation_time": ( 

291 self.stats["total_calculation_time"] / self.stats["calculated"] 

292 if self.stats["calculated"] > 0 

293 else 0.0 

294 ), 

295 "total_calculation_time": self.stats["total_calculation_time"], 

296 } 

297 

298 def print_stats(self): 

299 """Print cache performance statistics.""" 

300 stats = self.get_stats() 

301 

302 if stats["total_lookups"] == 0: 

303 console.print("[yellow]No hash lookups performed yet[/yellow]") 

304 return 

305 

306 console.print("\n[bold cyan]Hash Capture Performance:[/bold cyan]") 

307 console.print(f" Total Lookups: {stats['total_lookups']}") 

308 console.print(f" DAT Hits: {stats['dat_hits']} ({stats['dat_hit_rate']:.1f}%)") 

309 console.print(f" Cache Hits: {stats['cache_hits']} ({stats['cache_hit_rate']:.1f}%)") 

310 console.print(f" Calculated: {stats['calculated']} ({stats['calculation_rate']:.1f}%)") 

311 

312 if stats["calculated"] > 0: 

313 console.print(f" Avg Calculation Time: {stats['avg_calculation_time']:.1f}s") 

314 console.print(f" Total Calculation Time: {stats['total_calculation_time']:.1f}s") 

315 

316 # Show estimated speedup 

317 if stats["dat_hit_rate"] > 0: 

318 speedup = 100 / stats["calculation_rate"] if stats["calculation_rate"] > 0 else 0 

319 console.print(f" [green]Estimated Speedup: {speedup:.1f}x[/green]")