-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhanced_search.py
More file actions
430 lines (351 loc) · 15.4 KB
/
enhanced_search.py
File metadata and controls
430 lines (351 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
Enhanced search capabilities for Overtalkerr.
Features:
- Fuzzy matching for typos and speech recognition errors
- Actor/director/cast search
- Genre filtering
- Natural language date parsing
- Trending/popular content discovery
- Smart query parsing
"""
import re
from typing import List, Dict, Any, Optional, Tuple
from rapidfuzz import fuzz, process
import dateparser
from logger import logger
class SearchEnhancer:
"""Enhances search queries with fuzzy matching and NLP"""
# Common speech recognition errors
COMMON_SUBSTITUTIONS = {
'jurrasic': 'jurassic',
'harry potter': 'harry potter',
'lord of the rings': 'lord of the rings',
'game of thrones': 'game of thrones',
'breaking bad': 'breaking bad',
'the office': 'the office',
'stranger things': 'stranger things',
'the mandalorian': 'the mandalorian',
'wandavision': 'wandavision',
'the witcher': 'the witcher',
}
# Genre keywords
GENRE_KEYWORDS = {
'action': ['action', 'adventure', 'thriller'],
'comedy': ['comedy', 'funny', 'humor'],
'drama': ['drama', 'dramatic'],
'horror': ['horror', 'scary', 'frightening'],
'scifi': ['sci-fi', 'science fiction', 'scifi', 'sci fi'],
'fantasy': ['fantasy', 'magical'],
'romance': ['romance', 'romantic', 'love story'],
'documentary': ['documentary', 'docuseries'],
'animation': ['animated', 'animation', 'cartoon'],
'crime': ['crime', 'detective', 'mystery'],
'superhero': ['superhero', 'marvel', 'dc', 'comic'],
}
# Actor/director indicators
CAST_INDICATORS = [
'with', 'starring', 'by', 'directed by',
'featuring', 'actor', 'actress', 'director'
]
# Temporal keywords
TEMPORAL_KEYWORDS = {
'recent': 90, # Last 90 days
'new': 180, # Last 6 months
'latest': 90,
'upcoming': -90, # Next 90 days
'coming soon': -60,
'this year': 'current_year',
'last year': 'last_year',
}
@staticmethod
def correct_common_typos(query: str) -> str:
"""Correct common typos and speech recognition errors"""
query_lower = query.lower()
for wrong, correct in SearchEnhancer.COMMON_SUBSTITUTIONS.items():
if wrong in query_lower:
query = re.sub(re.escape(wrong), correct, query, flags=re.IGNORECASE)
logger.debug(f"Corrected typo: '{wrong}' -> '{correct}'")
return query
@staticmethod
def extract_cast_info(query: str) -> Tuple[str, Optional[str]]:
"""
Extract actor/director info from query.
Returns:
(cleaned_query, cast_member_name)
"""
for indicator in SearchEnhancer.CAST_INDICATORS:
pattern = rf'\b{re.escape(indicator)}\s+([a-zA-Z\s]+?)(?:\s|$)'
match = re.search(pattern, query, re.IGNORECASE)
if match:
cast_name = match.group(1).strip()
cleaned_query = re.sub(pattern, '', query, flags=re.IGNORECASE).strip()
logger.info(f"Extracted cast: '{cast_name}' from query")
return cleaned_query, cast_name
return query, None
@staticmethod
def extract_genre(query: str) -> Tuple[str, Optional[str]]:
"""
Extract genre from query.
Returns:
(cleaned_query, genre)
"""
query_lower = query.lower()
for genre, keywords in SearchEnhancer.GENRE_KEYWORDS.items():
for keyword in keywords:
if keyword in query_lower:
# Remove genre keyword from query
cleaned = re.sub(rf'\b{re.escape(keyword)}\b', '', query, flags=re.IGNORECASE)
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
logger.info(f"Extracted genre: '{genre}' from keyword '{keyword}'")
return cleaned, genre
return query, None
@staticmethod
def extract_temporal_info(query: str) -> Tuple[str, Optional[Dict[str, Any]]]:
"""
Extract temporal information from query.
Returns:
(cleaned_query, temporal_filter)
temporal_filter: {'type': 'relative', 'days': 90} or {'type': 'year', 'year': 2023}
"""
query_lower = query.lower()
# Check for temporal keywords
for keyword, value in SearchEnhancer.TEMPORAL_KEYWORDS.items():
if keyword in query_lower:
cleaned = re.sub(rf'\b{re.escape(keyword)}\b', '', query, flags=re.IGNORECASE)
cleaned = re.sub(r'\s+', ' ', cleaned).strip()
if isinstance(value, int):
temporal_filter = {'type': 'relative', 'days': value}
elif value == 'current_year':
from datetime import datetime
temporal_filter = {'type': 'year', 'year': datetime.now().year}
elif value == 'last_year':
from datetime import datetime
temporal_filter = {'type': 'year', 'year': datetime.now().year - 1}
logger.info(f"Extracted temporal filter: {temporal_filter}")
return cleaned, temporal_filter
# Try natural language date parsing
date_match = re.search(r'from\s+(\d{4})', query, re.IGNORECASE)
if date_match:
year = int(date_match.group(1))
cleaned = re.sub(r'from\s+\d{4}', '', query, flags=re.IGNORECASE).strip()
temporal_filter = {'type': 'year', 'year': year}
logger.info(f"Extracted year filter: {year}")
return cleaned, temporal_filter
return query, None
@staticmethod
def parse_enhanced_query(query: str) -> Dict[str, Any]:
"""
Parse query with all enhancements.
Returns dict with:
- cleaned_query: The search term
- cast: Actor/director name if found
- genre: Genre if found
- temporal: Temporal filter if found
- original: Original query
"""
original = query
# Step 1: Correct typos
query = SearchEnhancer.correct_common_typos(query)
# Step 2: Extract cast
query, cast = SearchEnhancer.extract_cast_info(query)
# Step 3: Extract genre
query, genre = SearchEnhancer.extract_genre(query)
# Step 4: Extract temporal info
query, temporal = SearchEnhancer.extract_temporal_info(query)
# Clean up extra whitespace
query = re.sub(r'\s+', ' ', query).strip()
result = {
'cleaned_query': query,
'cast': cast,
'genre': genre,
'temporal': temporal,
'original': original
}
logger.info(f"Enhanced query parsing: {result}")
return result
@staticmethod
def is_low_quality_result(result: Dict[str, Any]) -> bool:
"""
Detect low-quality results that should be filtered out.
Filters based on:
- No votes (voteCount = 0)
- Very low popularity (< 1.0)
- Missing poster
- Short/weird overviews
"""
vote_count = result.get('voteCount', 0)
popularity = result.get('popularity', 0)
poster = result.get('posterPath')
overview = result.get('overview', '')
# Filter if: no votes AND low popularity AND no poster
if vote_count == 0 and popularity < 1.0 and not poster:
return True
# Filter if overview is suspiciously short or weird
if overview and len(overview) < 30:
# Allow short overviews if the item has some popularity/votes
if vote_count == 0 and popularity < 1.0:
return True
return False
@staticmethod
def is_allowed_language(result: Dict[str, Any]) -> bool:
"""
Check if result is in an allowed language based on configuration.
Returns:
True if language is allowed or no language filter is set, False otherwise
"""
from config import Config
# If no language filter configured, allow all
if not Config.LANGUAGE_FILTER:
return True
# Get original language from result (ISO 639-1 code)
original_language = result.get('originalLanguage', '').lower()
# If no language specified in result, allow it (benefit of doubt)
if not original_language:
return True
# Check if language is in allowed list
return original_language in Config.LANGUAGE_FILTER
@staticmethod
def fuzzy_match_results(query: str, results: List[Dict[str, Any]], threshold: int = 70) -> List[Dict[str, Any]]:
"""
Re-rank results using intelligent matching with priority tiers:
1. Exact matches
2. Titles starting with the query
3. Titles containing the query
4. Fuzzy matches
Also filters out low-quality results.
Args:
query: Search query
results: List of search results from Overseerr
threshold: Minimum similarity score (0-100)
Returns:
Re-ranked results with match tier and similarity scores
"""
if not results:
return results
query_lower = query.lower().strip()
scored_results = []
for result in results:
# Skip low-quality results
if SearchEnhancer.is_low_quality_result(result):
logger.debug(f"Filtering low-quality result: {result.get('title', 'unknown')} ({result.get('releaseDate', 'no date')})")
continue
# Skip results not in allowed languages
if not SearchEnhancer.is_allowed_language(result):
original_lang = result.get('originalLanguage', 'unknown')
logger.debug(f"Filtering non-allowed language: {result.get('title', 'unknown')} (language: {original_lang})")
continue
title = result.get('_title', result.get('title', result.get('name', '')))
title_lower = title.lower().strip()
# Determine match tier
match_tier = 4 # Default: fuzzy match
bonus = 0
# Tier 1: Exact match (highest priority)
if title_lower == query_lower:
match_tier = 1
bonus = 1000
# Tier 2: Starts with query
elif title_lower.startswith(query_lower):
match_tier = 2
bonus = 500
# Tier 3: Contains query as whole word
elif f" {query_lower} " in f" {title_lower} ":
match_tier = 3
bonus = 250
# Tier 3.5: Contains query anywhere (but not as whole word)
elif query_lower in title_lower:
match_tier = 3
bonus = 100
# Calculate multiple similarity scores
ratio = fuzz.ratio(query_lower, title_lower)
partial = fuzz.partial_ratio(query_lower, title_lower)
token_sort = fuzz.token_sort_ratio(query_lower, title_lower)
token_set = fuzz.token_set_ratio(query_lower, title_lower)
# Use the best score
best_score = max(ratio, partial, token_sort, token_set)
# For exact/starts/contains matches, always include regardless of threshold
# For fuzzy matches, apply threshold
if match_tier <= 3 or best_score >= threshold:
result_copy = result.copy()
result_copy['_fuzzy_score'] = best_score
result_copy['_match_tier'] = match_tier
# Combined score for sorting: tier matters most, then fuzzy score
result_copy['_combined_score'] = bonus + best_score
scored_results.append(result_copy)
# Sort by match tier (ascending), then by fuzzy score (descending)
scored_results.sort(key=lambda x: (-x.get('_combined_score', 0)))
logger.info(f"Intelligent matching: {len(scored_results)} results (Tier 1: {sum(1 for r in scored_results if r.get('_match_tier') == 1)}, Tier 2: {sum(1 for r in scored_results if r.get('_match_tier') == 2)}, Tier 3: {sum(1 for r in scored_results if r.get('_match_tier') == 3)}, Fuzzy: {sum(1 for r in scored_results if r.get('_match_tier') == 4)})")
return scored_results
@staticmethod
def suggest_alternatives(query: str, known_titles: List[str], limit: int = 5) -> List[Tuple[str, int]]:
"""
Suggest alternative titles based on fuzzy matching.
Args:
query: User's search query
known_titles: List of known titles to match against
limit: Maximum number of suggestions
Returns:
List of (title, score) tuples
"""
if not known_titles:
return []
# Use rapidfuzz to find best matches
matches = process.extract(
query,
known_titles,
scorer=fuzz.WRatio,
limit=limit
)
# Filter out low scores
suggestions = [(match[0], match[1]) for match in matches if match[1] >= 60]
logger.info(f"Generated {len(suggestions)} suggestions for query '{query}'")
return suggestions
@staticmethod
def filter_by_genre(results: List[Dict[str, Any]], genre: str) -> List[Dict[str, Any]]:
"""
Filter results by genre.
Note: This requires Overseerr API to return genre information.
If not available, this returns all results.
"""
# Check if results have genre info
if not results or 'genres' not in results[0] and 'genre_ids' not in results[0]:
logger.warning("Genre filtering requested but genre data not available in results")
return results
# TODO: Implement genre ID mapping when Overseerr provides genre data
logger.info(f"Genre filtering for '{genre}' - implementation pending genre data from API")
return results
@staticmethod
def filter_by_cast(results: List[Dict[str, Any]], cast_name: str) -> List[Dict[str, Any]]:
"""
Filter results by actor/director.
Note: This would require additional API calls to TMDB for cast info.
Consider implementing if needed.
"""
logger.info(f"Cast filtering for '{cast_name}' - requires TMDB API integration")
return results
@staticmethod
def build_smart_query_explanation(parsed: Dict[str, Any]) -> str:
"""Build a human-readable explanation of what was understood"""
parts = []
if parsed['cleaned_query']:
parts.append(f"searching for '{parsed['cleaned_query']}'")
if parsed['cast']:
parts.append(f"with {parsed['cast']}")
if parsed['genre']:
parts.append(f"in the {parsed['genre']} genre")
if parsed['temporal']:
if parsed['temporal']['type'] == 'year':
parts.append(f"from {parsed['temporal']['year']}")
elif parsed['temporal']['type'] == 'relative':
days = abs(parsed['temporal']['days'])
if parsed['temporal']['days'] > 0:
parts.append(f"from the last {days} days")
else:
parts.append(f"coming in the next {days} days")
if len(parts) > 1:
return "I'm " + ", ".join(parts[:-1]) + " and " + parts[-1]
elif parts:
return "I'm " + parts[0]
else:
return "I'm searching for that"
# Singleton instance
search_enhancer = SearchEnhancer()