Spaces:
Running on Zero
Running on Zero
File size: 11,973 Bytes
9ef70e8 | 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 | import os
import time
import json
from dotenv import load_dotenv
from google import genai
from lib.config import GEMINI_MODEL
from sentence_transformers import CrossEncoder
def enhance_query_spell(query: str) -> str:
"""Use Gemini to fix spelling errors in a query"""
# Load API key
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in environment")
# Create Gemini client
client = genai.Client(api_key=api_key)
# System prompt for spell correction
prompt = f"""Fix any spelling errors in this movie search query.
Only correct obvious typos. Don't change correctly spelled words.
Query: "{query}"
If no errors, return the original query.
Corrected:"""
# Get response from Gemini
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt
)
# Extract and clean the corrected query
corrected = response.text.strip()
# Remove quotes if Gemini added them
if corrected.startswith('"') and corrected.endswith('"'):
corrected = corrected[1:-1]
if corrected.startswith("'") and corrected.endswith("'"):
corrected = corrected[1:-1]
return corrected
def enhance_query_rewrite(query: str) -> str:
"""Use Gemini to rewrite a vague query to be more specific and searchable"""
# Load API key
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in environment")
# Create Gemini client
client = genai.Client(api_key=api_key)
# System prompt for query rewriting
prompt = f"""Rewrite this movie search query to be more specific and searchable.
Original: "{query}"
Consider:
- Common movie knowledge (famous actors, popular films)
- Genre conventions (horror = scary, animation = cartoon)
- Keep it concise (under 10 words)
- It should be a google style search query that's very specific
- Don't use boolean logic
Examples:
- "that bear movie where leo gets attacked" -> "The Revenant Leonardo DiCaprio bear attack"
- "movie about bear in london with marmalade" -> "Paddington London marmalade"
- "scary movie with bear from few years ago" -> "bear horror movie 2015-2020"
Rewritten query:"""
# Get response from Gemini
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt
)
# Extract and clean the rewritten query
rewritten = response.text.strip()
# Remove quotes if Gemini added them
if rewritten.startswith('"') and rewritten.endswith('"'):
rewritten = rewritten[1:-1]
if rewritten.startswith("'") and rewritten.endswith("'"):
rewritten = rewritten[1:-1]
return rewritten
def enhance_query_expand(query: str) -> str:
"""Use Gemini to expand a query with related terms and synonyms"""
# Load API key
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in environment")
# Create Gemini client
client = genai.Client(api_key=api_key)
# System prompt for query expansion
prompt = f"""Expand this movie search query with related terms.
Add synonyms and related concepts that might appear in movie descriptions.
Keep expansions relevant and focused.
This will be appended to the original query.
Examples:
- "scary bear movie" -> "scary horror grizzly bear movie terrifying film"
- "action movie with bear" -> "action thriller bear chase fight adventure"
- "comedy with bear" -> "comedy funny bear humor lighthearted"
Query: "{query}"
"""
# Get response from Gemini
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt
)
# Extract and clean the expanded query
expanded = response.text.strip()
# Remove quotes if Gemini added them
if expanded.startswith('"') and expanded.endswith('"'):
expanded = expanded[1:-1]
if expanded.startswith("'") and expanded.endswith("'"):
expanded = expanded[1:-1]
return expanded
def rerank_individual(query: str, results: list[dict]) -> list[dict]:
"""Use Gemini to individually re-rank each result"""
# Load API key
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in environment")
# Create Gemini client
client = genai.Client(api_key=api_key)
reranked_results = []
for result in results:
# System prompt for re-ranking
prompt = f"""Rate how well this movie matches the search query.
Query: "{query}"
Movie: {result.get("title", "")} - {result.get("document", "")}
Consider:
- Direct relevance to query
- User intent (what they're looking for)
- Content appropriateness
Rate 0-10 (10 = perfect match).
Give me ONLY the number in your response, no other text or explanation.
Score:"""
try:
# Get response from Gemini
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt
)
# Extract score
score_text = response.text.strip()
# Try to parse the score
try:
rerank_score = float(score_text)
except ValueError:
# If parsing fails, try to extract first number
import re
numbers = re.findall(r'\d+\.?\d*', score_text)
rerank_score = float(numbers[0]) if numbers else 5.0
# Add rerank score to result
result['rerank_score'] = rerank_score
reranked_results.append(result)
# Sleep to avoid rate limits
time.sleep(3)
except Exception as e:
print(f"Warning: Failed to rerank {result.get('title', 'Unknown')}: {e}")
result['rerank_score'] = 5.0 # Default score on error
reranked_results.append(result)
# Sort by rerank score (descending)
reranked_results.sort(key=lambda x: x['rerank_score'], reverse=True)
return reranked_results
def rerank_batch(query: str, results: list[dict]) -> list[dict]:
"""Use Gemini to batch re-rank all results in one call"""
# Load API key
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in environment")
# Create Gemini client
client = genai.Client(api_key=api_key)
# Build the document list string
doc_list_str = ""
for idx, result in enumerate(results):
doc_list_str += f"{result['id']}. {result['title']} - {result.get('document', '')[:200]}...\n"
# System prompt for batch re-ranking
prompt = f"""Rank these movies by relevance to the search query.
Query: "{query}"
Movies:
{doc_list_str}
Return ONLY the IDs in order of relevance (best match first). Return a valid JSON list, nothing else. For example:
[75, 12, 34, 2, 1]
"""
try:
# Get response from Gemini
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt
)
# Extract and parse JSON response
response_text = response.text.strip()
# Clean up response if needed (remove markdown code blocks)
if response_text.startswith("```"):
# Remove ```json or ``` prefix and suffix
lines = response_text.split('\n')
response_text = '\n'.join(lines[1:-1]) if len(lines) > 2 else response_text
# Parse JSON
ranked_ids = json.loads(response_text)
# Create a mapping of ID to result
id_to_result = {result['id']: result for result in results}
# Reorder results based on ranked IDs
reranked_results = []
for rank, doc_id in enumerate(ranked_ids, 1):
if doc_id in id_to_result:
result = id_to_result[doc_id]
result['rerank_rank'] = rank
reranked_results.append(result)
# Add any results that weren't ranked (at the end)
ranked_id_set = set(ranked_ids)
for result in results:
if result['id'] not in ranked_id_set:
result['rerank_rank'] = len(reranked_results) + 1
reranked_results.append(result)
return reranked_results
except Exception as e:
print(f"Warning: Batch reranking failed: {e}")
print(f"Response was: {response_text if 'response_text' in locals() else 'No response'}")
# Return original order with default ranks
for rank, result in enumerate(results, 1):
result['rerank_rank'] = rank
return results
def rerank_cross_encoder(query: str, results: list[dict]) -> list[dict]:
"""Use a cross-encoder model to re-rank results"""
# Create pairs of [query, document]
pairs = []
for result in results:
doc_text = f"{result.get('title', '')} - {result.get('document', '')}"
pairs.append([query, doc_text])
# Initialize cross-encoder model (does this once per query)
cross_encoder = CrossEncoder("cross-encoder/ms-marco-TinyBERT-L-2-v2")
# Compute scores for all pairs
scores = cross_encoder.predict(pairs)
# Add scores to results
for i, result in enumerate(results):
result['cross_encoder_score'] = float(scores[i])
# Sort by cross-encoder score (descending)
results.sort(key=lambda x: x['cross_encoder_score'], reverse=True)
return results
def evaluate_results(query: str, results: list[dict]) -> list[int]:
"""Use Gemini to evaluate search result relevance"""
# Load API key
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY not found in environment")
# Create Gemini client
client = genai.Client(api_key=api_key)
# Format results for the prompt
formatted_results = []
for i, result in enumerate(results, 1):
formatted_results.append(f"{i}. {result['title']} - {result.get('document', '')[:200]}")
# System prompt for evaluation
prompt = f"""Rate how relevant each result is to this query on a 0-3 scale:
Query: "{query}"
Results:
{chr(10).join(formatted_results)}
Scale:
- 3: Highly relevant
- 2: Relevant
- 1: Marginally relevant
- 0: Not relevant
Do NOT give any numbers out than 0, 1, 2, or 3.
Return ONLY the scores in the same order you were given the documents. Return a valid JSON list, nothing else. For example:
[2, 0, 3, 2, 0, 1]"""
try:
# Get response from Gemini
response = client.models.generate_content(
model=GEMINI_MODEL,
contents=prompt
)
# Extract and parse JSON response
response_text = response.text.strip()
# Clean up response if needed (remove markdown code blocks)
if response_text.startswith("```"):
# Remove ```json or ``` prefix and suffix
lines = response_text.split('\n')
response_text = '\n'.join(lines[1:-1]) if len(lines) > 2 else response_text
# Parse JSON
scores = json.loads(response_text)
# Validate scores are 0-3
scores = [max(0, min(3, int(score))) for score in scores]
return scores
except Exception as e:
print(f"Warning: Evaluation failed: {e}")
print(f"Response was: {response_text if 'response_text' in locals() else 'No response'}")
# Return default scores (all 2s - "relevant")
return [2 for _ in results]
|