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

115 statements  

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

1""" 

2Wikipedia Search API for Game Information 

3 

4Provides semantic search over Wikipedia game articles using LanceDB 

5for vector similarity and DuckDB for metadata queries. 

6 

7Usage: 

8 from romfarmer.metadata.wiki_search import WikiSearch 

9 

10 search = WikiSearch() 

11 results = search.search("horror game with zombies", limit=5) 

12 

13 # Or get info for a specific game 

14 info = search.get_game_info("Resident Evil") 

15""" 

16 

17import logging 

18from pathlib import Path 

19 

20logger = logging.getLogger(__name__) 

21 

22# Lazy imports for optional dependencies 

23_lancedb = None 

24_duckdb = None 

25_model = None 

26 

27 

28def _get_lancedb(): 

29 global _lancedb 

30 if _lancedb is None: 

31 import lancedb 

32 

33 _lancedb = lancedb 

34 return _lancedb 

35 

36 

37def _get_duckdb(): 

38 global _duckdb 

39 if _duckdb is None: 

40 import duckdb 

41 

42 _duckdb = duckdb 

43 return _duckdb 

44 

45 

46def _get_model(): 

47 global _model 

48 if _model is None: 

49 from sentence_transformers import SentenceTransformer 

50 

51 _model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") 

52 return _model 

53 

54 

55class WikiSearch: 

56 """ 

57 Semantic search over Wikipedia game articles. 

58 

59 Combines: 

60 - LanceDB for vector similarity search 

61 - DuckDB for SQL queries on metadata 

62 - Sentence transformers for query embedding 

63 """ 

64 

65 def __init__(self, data_dir: Path | None = None): 

66 if data_dir is None: 

67 data_dir = ( 

68 Path(__file__).parent.parent.parent.parent / "data" / "wikipedia" / "processed" 

69 ) 

70 

71 self.data_dir = Path(data_dir) 

72 self.lancedb_path = self.data_dir / "lancedb" 

73 self.duckdb_path = self.data_dir / "wikipedia.duckdb" 

74 

75 self._lance_table = None 

76 self._duck_conn = None 

77 

78 @property 

79 def lance_table(self): 

80 """Lazy-load LanceDB table.""" 

81 if self._lance_table is None: 

82 lancedb = _get_lancedb() 

83 db = lancedb.connect(str(self.lancedb_path)) 

84 self._lance_table = db.open_table("wiki_chunks") 

85 return self._lance_table 

86 

87 @property 

88 def duck_conn(self): 

89 """Lazy-load DuckDB connection.""" 

90 if self._duck_conn is None: 

91 duckdb = _get_duckdb() 

92 self._duck_conn = duckdb.connect(str(self.duckdb_path), read_only=True) 

93 return self._duck_conn 

94 

95 def search( 

96 self, 

97 query: str, 

98 limit: int = 10, 

99 section_filter: str | None = None, 

100 game_filter: str | None = None, 

101 ) -> list[dict]: 

102 """ 

103 Semantic search for relevant Wikipedia content. 

104 

105 Args: 

106 query: Natural language search query 

107 limit: Maximum results to return 

108 section_filter: Filter to specific section types (e.g., "Gameplay", "Plot") 

109 game_filter: Filter to specific game title 

110 

111 Returns: 

112 List of matching chunks with metadata and relevance scores 

113 """ 

114 model = _get_model() 

115 embedding = model.encode(query).tolist() 

116 

117 # Build search 

118 search = self.lance_table.search(embedding).limit(limit * 2) # Get extra for filtering 

119 

120 # Apply filters if provided 

121 if section_filter: 

122 search = search.where(f"section_title LIKE '%{section_filter}%'") 

123 if game_filter: 

124 search = search.where(f"game_title LIKE '%{game_filter}%'") 

125 

126 results = search.to_list() 

127 

128 # Format results with deduplication 

129 formatted = [] 

130 seen = set() # Track (article_title, section_title) pairs 

131 

132 for r in results: 

133 if len(formatted) >= limit: 

134 break 

135 

136 # Deduplicate by article + section 

137 key = (r["article_title"], r["section_title"]) 

138 if key in seen: 

139 continue 

140 seen.add(key) 

141 

142 formatted.append( 

143 { 

144 "game_title": r["game_title"], 

145 "article_title": r["article_title"], 

146 "article_url": r["article_url"], 

147 "section": r["section_title"], 

148 "content": r["content"], 

149 "score": 1 - r["_distance"], # Convert distance to similarity 

150 "chunk_id": r["chunk_id"], 

151 } 

152 ) 

153 

154 return formatted 

155 

156 def get_game_info(self, game_title: str) -> dict | None: 

157 """ 

158 Get all Wikipedia information about a specific game. 

159 

160 Args: 

161 game_title: The game title to look up 

162 

163 Returns: 

164 Dict with game info organized by section, or None if not found 

165 """ 

166 _get_duckdb() 

167 

168 # Search for the game (fuzzy match) 

169 result = self.duck_conn.execute( 

170 """ 

171 SELECT DISTINCT article_title, article_url, game_title 

172 FROM wiki_chunks 

173 WHERE game_title ILIKE $1 OR article_title ILIKE $1 

174 LIMIT 1 

175 """, 

176 [f"%{game_title}%"], 

177 ).fetchone() 

178 

179 if not result: 

180 return None 

181 

182 article_title, article_url, matched_game = result 

183 

184 # Get all sections for this article 

185 sections = self.duck_conn.execute( 

186 """ 

187 SELECT section_title, content, chunk_index 

188 FROM wiki_chunks 

189 WHERE article_title = $1 

190 ORDER BY chunk_index 

191 """, 

192 [article_title], 

193 ).fetchall() 

194 

195 # Organize by section 

196 organized = {} 

197 for section_title, content, _ in sections: 

198 if section_title not in organized: 

199 organized[section_title] = [] 

200 organized[section_title].append(content) 

201 

202 # Join chunks within each section 

203 for section in organized: 

204 organized[section] = "\n\n".join(organized[section]) 

205 

206 return { 

207 "title": article_title, 

208 "game_title": matched_game, 

209 "url": article_url, 

210 "sections": organized, 

211 } 

212 

213 def get_section(self, game_title: str, section_name: str) -> str | None: 

214 """ 

215 Get a specific section from a game's Wikipedia article. 

216 

217 Args: 

218 game_title: The game to look up 

219 section_name: The section name (e.g., "Gameplay", "Plot", "Reception") 

220 

221 Returns: 

222 The section content or None if not found 

223 """ 

224 result = self.duck_conn.execute( 

225 """ 

226 SELECT content 

227 FROM wiki_chunks 

228 WHERE (game_title ILIKE $1 OR article_title ILIKE $1) 

229 AND section_title ILIKE $2 

230 ORDER BY chunk_index 

231 """, 

232 [f"%{game_title}%", f"%{section_name}%"], 

233 ).fetchall() 

234 

235 if not result: 

236 return None 

237 

238 return "\n\n".join(r[0] for r in result) 

239 

240 def list_games(self, limit: int = 100, offset: int = 0) -> list[dict]: 

241 """List all games with Wikipedia articles.""" 

242 result = self.duck_conn.execute( 

243 """ 

244 SELECT DISTINCT 

245 game_title, 

246 article_title, 

247 article_url, 

248 COUNT(*) as num_chunks, 

249 SUM(token_count) as total_tokens 

250 FROM wiki_chunks 

251 GROUP BY game_title, article_title, article_url 

252 ORDER BY game_title 

253 LIMIT $1 OFFSET $2 

254 """, 

255 [limit, offset], 

256 ).fetchall() 

257 

258 return [ 

259 { 

260 "game_title": r[0], 

261 "article_title": r[1], 

262 "url": r[2], 

263 "chunks": r[3], 

264 "tokens": r[4], 

265 } 

266 for r in result 

267 ] 

268 

269 def stats(self) -> dict: 

270 """Get statistics about the Wikipedia data.""" 

271 result = self.duck_conn.execute("SELECT * FROM wiki_stats").fetchone() 

272 

273 return { 

274 "total_chunks": result[0], 

275 "total_articles": result[1], 

276 "unique_games": result[2], 

277 "avg_tokens_per_chunk": round(result[3], 1), 

278 "total_tokens": result[4], 

279 } 

280 

281 def search_by_section_type(self, query: str, section_type: str, limit: int = 10) -> list[dict]: 

282 """ 

283 Search within a specific type of section. 

284 

285 Useful for targeted queries like: 

286 - "difficult boss" in "Gameplay" sections 

287 - "critical acclaim" in "Reception" sections 

288 - "development history" in "Development" sections 

289 

290 Args: 

291 query: Search query 

292 section_type: Section to search in (Gameplay, Plot, Reception, Development, etc.) 

293 limit: Max results 

294 """ 

295 return self.search(query, limit=limit, section_filter=section_type) 

296 

297 def find_games( 

298 self, 

299 query: str, 

300 limit: int = 10, 

301 threshold: float = 0.5, 

302 ) -> list[dict]: 

303 """ 

304 Fuzzy search for game titles using Jaro-Winkler similarity. 

305 

306 Handles: 

307 - Typos and misspellings 

308 - Partial titles ("sonic 2" -> "Sonic the Hedgehog 2") 

309 - Word variations 

310 

311 Scoring: 

312 - Base: Jaro-Winkler similarity (0-1) 

313 - Containment bonus (+0.15): Query is substring of title 

314 - All words bonus (+0.25): All query words appear in title 

315 

316 Args: 

317 query: Game title to search for (fuzzy) 

318 limit: Maximum results to return 

319 threshold: Minimum similarity score (0-1) to include 

320 

321 Returns: 

322 List of matching games with similarity scores, sorted by relevance 

323 """ 

324 query_lower = query.lower().strip() 

325 # Keep all words, including single chars like "2" in "sonic 2" 

326 words = query_lower.split() 

327 

328 if not words: 

329 return [] 

330 

331 # Build SQL conditions dynamically (escaping words for safety) 

332 def escape_like(s: str) -> str: 

333 """Escape special LIKE characters.""" 

334 return s.replace("%", "\\%").replace("_", "\\_") 

335 

336 escaped_words = [escape_like(w) for w in words] 

337 

338 # ILIKE any word match (pre-filter for speed) 

339 ilike_any = " OR ".join([f"LOWER(game_title) LIKE '%{w}%'" for w in escaped_words]) 

340 

341 # ILIKE all words match (for bonus) 

342 ilike_all = " AND ".join([f"LOWER(game_title) LIKE '%{w}%'" for w in escaped_words]) 

343 

344 # Containment check (full query as substring) 

345 escaped_query = escape_like(query_lower) 

346 

347 # Hybrid search with multiple bonuses 

348 # - Jaro-Winkler for fuzzy matching 

349 # - Containment bonus if query is substring of title 

350 # - All-words bonus if all query words appear in title 

351 results = self.duck_conn.execute( 

352 f""" 

353 SELECT * FROM ( 

354 SELECT DISTINCT 

355 game_title, 

356 article_title, 

357 article_url, 

358 jaro_winkler_similarity(LOWER(game_title), ?) as jw_sim, 

359 CASE WHEN LOWER(game_title) LIKE '%{escaped_query}%' 

360 THEN 0.15 ELSE 0.0 END as containment_bonus, 

361 CASE WHEN {ilike_all} 

362 THEN 0.25 ELSE 0.0 END as all_words_bonus 

363 FROM wiki_chunks 

364 WHERE {ilike_any} 

365 ) sub 

366 WHERE jw_sim >= ? 

367 ORDER BY (jw_sim + containment_bonus + all_words_bonus) DESC, jw_sim DESC 

368 LIMIT ? 

369 """, 

370 [query_lower, threshold, limit * 3], 

371 ).fetchall() 

372 

373 # If no word matches, fall back to pure similarity search (slower) 

374 if not results: 

375 results = self.duck_conn.execute( 

376 f""" 

377 SELECT * FROM ( 

378 SELECT DISTINCT 

379 game_title, 

380 article_title, 

381 article_url, 

382 jaro_winkler_similarity(LOWER(game_title), ?) as jw_sim, 

383 CASE WHEN LOWER(game_title) LIKE '%{escaped_query}%' 

384 THEN 0.15 ELSE 0.0 END as containment_bonus, 

385 0.0 as all_words_bonus 

386 FROM wiki_chunks 

387 ) sub 

388 WHERE jw_sim >= ? 

389 ORDER BY (jw_sim + containment_bonus) DESC, jw_sim DESC 

390 LIMIT ? 

391 """, 

392 [query_lower, threshold, limit * 3], 

393 ).fetchall() 

394 

395 # Return combined score (capped at 1.0), limited to requested count 

396 return [ 

397 { 

398 "game_title": r[0], 

399 "article_title": r[1], 

400 "url": r[2], 

401 "similarity": round(min(float(r[3]) + float(r[4]) + float(r[5]), 1.0), 3), 

402 } 

403 for r in results[:limit] 

404 ] 

405 

406 

407# Convenience functions for quick access 

408_search_instance = None 

409 

410 

411def get_search() -> WikiSearch: 

412 """Get or create a WikiSearch instance.""" 

413 global _search_instance 

414 if _search_instance is None: 

415 _search_instance = WikiSearch() 

416 return _search_instance 

417 

418 

419def search(query: str, limit: int = 10) -> list[dict]: 

420 """Quick semantic search.""" 

421 return get_search().search(query, limit=limit) 

422 

423 

424def get_game_info(game_title: str) -> dict | None: 

425 """Quick game lookup.""" 

426 return get_search().get_game_info(game_title)