VADITYA307 commited on
Commit
c01aef7
Β·
verified Β·
1 Parent(s): b7da533

Update services/search.py

Browse files
Files changed (1) hide show
  1. services/search.py +74 -94
services/search.py CHANGED
@@ -25,7 +25,10 @@ from qdrant_client.models import (
25
  Modifier
26
  )
27
  from sentence_transformers import SentenceTransformer
28
- from fastembed import SparseTextEmbedding, TextReranker
 
 
 
29
  import uuid
30
 
31
  load_dotenv()
@@ -57,7 +60,7 @@ class LiveWebSearcher:
57
  self.sparse_encoder = SparseTextEmbedding(model_name="Qdrant/bm25")
58
 
59
  print("🧠 Loading Cross-Encoder Reranking Engine...")
60
- self.reranker = TextReranker(model_name="Xenova/ms-marco-MiniLM-L-6-v2")
61
 
62
  # Collection names
63
  self.cache_collection = "web_cache_hybrid"
@@ -87,12 +90,10 @@ class LiveWebSearcher:
87
 
88
  # --- PERSONAL CLOUD INDEXING METHODS ---
89
  def chunk_text(self, text: str, max_words: int = 150) -> list:
90
- """Breaks large documents into small, searchable vector blocks."""
91
  words = text.split()
92
  return [" ".join(words[i:i + max_words]) for i in range(0, len(words), max_words)]
93
 
94
  def ingest_personal_file(self, filename: str, content: str):
95
- """Embeds and saves personal document chunks into Qdrant using Hybrid fields."""
96
  print(f"πŸ“‚ Indexing personal file with Hybrid vectors: {filename}")
97
  chunks = self.chunk_text(content)
98
  points = []
@@ -106,23 +107,14 @@ class LiveWebSearcher:
106
 
107
  points.append(PointStruct(
108
  id=str(uuid.uuid4()),
109
- vector={
110
- "dense": vector_dense,
111
- "sparse": vector_sparse
112
- },
113
- payload={
114
- "title": filename,
115
- "url": "Local File",
116
- "snippet": chunk,
117
- "source": "Personal Cloud"
118
- }
119
  ))
120
  if points:
121
  self.qdrant.upsert(collection_name=self.files_collection, points=points)
122
  print(f"βœ… Indexed {len(points)} hybrid vectors for {filename}")
123
 
124
  def search_personal_files(self, query: str, limit: int = 5) -> list:
125
- """Retrieves candidates via Hybrid Search, then applies a deep Cross-Encoder Rerank."""
126
  print(f"πŸ” Searching Personal Cloud (Hybrid Search) for: '{query}'")
127
  try:
128
  query_dense = self.encoder.encode(query).tolist()
@@ -147,32 +139,35 @@ class LiveWebSearcher:
147
  return []
148
 
149
  documents = [res.payload.get("snippet", "") for res in search_results]
150
-
151
  print(f"βš–οΈ Reranking {len(documents)} candidates via Cross-Encoder...")
152
- rerank_results = list(self.reranker.rerank(query, documents))
 
 
 
 
 
 
 
 
 
153
 
154
  final_contexts = []
155
- for reranked in rerank_results[:limit]:
156
- original_match = search_results[reranked.result_index]
157
  final_contexts.append({
158
- "title": original_match.payload.get("title"),
159
- "url": original_match.payload.get("url"),
160
- "snippet": reranked.text,
161
- "score": round(float(reranked.score), 4),
162
  "source": "Personal File (Reranked)"
163
  })
164
 
165
- if final_contexts:
166
- print(f"🎯 Personal File Hit! Retrieved {len(final_contexts)} highly relevant chunks.")
167
  return final_contexts
168
-
169
  except Exception as e:
170
  print(f"❌ Personal search failed: {str(e)}")
171
  return []
172
 
173
  # --- WEB SEARCH & CACHE METHODS ---
174
  def check_cache(self, query: str, limit: int = 3, threshold: float = -2.0) -> list:
175
- """Scans local cache with hybrid retrieval and cross-encoder sorting."""
176
  try:
177
  query_dense = self.encoder.encode(query).tolist()
178
  sparse_output = list(self.sparse_encoder.embed([query]))[0]
@@ -196,18 +191,25 @@ class LiveWebSearcher:
196
  return []
197
 
198
  documents = [res.payload.get("snippet", "") for res in search_results]
199
- rerank_results = list(self.reranker.rerank(query, documents))
 
 
 
 
 
 
 
 
200
 
201
  cached_contexts = []
202
- for reranked in rerank_results[:limit]:
203
- if reranked.score >= threshold:
204
- original_match = search_results[reranked.result_index]
205
  cached_contexts.append({
206
- "title": original_match.payload.get("title"),
207
- "url": original_match.payload.get("url"),
208
- "snippet": reranked.text,
209
- "score": round(float(reranked.score), 4),
210
- "source": f"Cache Reranked ({original_match.payload.get('source', 'Unknown')})"
211
  })
212
  return cached_contexts
213
  except Exception:
@@ -219,7 +221,6 @@ class LiveWebSearcher:
219
  points = []
220
  for r in results:
221
  text_to_embed = f"Query: {query} | Content: {r.get('snippet', '')}"
222
-
223
  vector_dense = self.encoder.encode(text_to_embed).tolist()
224
  sparse_output = list(self.sparse_encoder.embed([text_to_embed]))[0]
225
  vector_sparse = SparseVector(
@@ -229,15 +230,10 @@ class LiveWebSearcher:
229
 
230
  points.append(PointStruct(
231
  id=str(uuid.uuid4()),
232
- vector={
233
- "dense": vector_dense,
234
- "sparse": vector_sparse
235
- },
236
  payload={
237
- "original_query": query,
238
- "title": r.get("title"),
239
- "url": r.get("url"),
240
- "snippet": r.get("snippet"),
241
  "source": r.get("source", "Web")
242
  }
243
  ))
@@ -253,32 +249,22 @@ class LiveWebSearcher:
253
  current_date_str = datetime.now().strftime("%B %d %Y")
254
  expanded_query = f"{query} {current_date_str}" if is_news else query
255
 
256
- # 1. --- SERP API ROUTE (Google Search Engine Engine) ---
257
  if self.serp_key:
258
  try:
259
  print("πŸ” [SERP API] Querying premium Google Index engine...")
260
- serp_url = "https://serpapi.com/search"
261
- params = {
262
- "engine": "google",
263
- "q": expanded_query,
264
- "api_key": self.serp_key,
265
- "num": limit * 2,
266
- "gl": "in",
267
- "hl": "en"
268
- }
269
- response = requests.get(serp_url, params=params, timeout=7)
270
  if response.status_code == 200:
271
- results = response.json().get("organic_results", [])
272
- for r in results:
273
  res_url = r.get("link", "")
274
  if res_url and res_url not in processed_urls:
275
- if is_news and not any(dom in res_url for dom in TRUSTED_DOMAINS):
276
- continue
277
  raw_candidates.append({
278
  "title": r.get("title", "Google Sourced Context"),
279
- "url": res_url,
280
- "snippet": r.get("snippet", ""),
281
- "source": "SerpApi (Google)"
282
  })
283
  processed_urls.add(res_url)
284
  except Exception as e:
@@ -289,11 +275,9 @@ class LiveWebSearcher:
289
  try:
290
  print(f"🌍 [TAVILY] Executing concurrent context pull...")
291
  payload = {
292
- "api_key": self.tavily_key,
293
- "query": expanded_query,
294
  "search_depth": "advanced" if is_news else "basic",
295
- "max_results": limit * 2,
296
- "topic": "news" if is_news else "general",
297
  }
298
  if is_news:
299
  payload["days"] = 1
@@ -301,62 +285,58 @@ class LiveWebSearcher:
301
 
302
  response = requests.post("https://api.tavily.com/search", json=payload, timeout=7)
303
  if response.status_code not in [403, 429]:
304
- response.raise_for_status()
305
- results = response.json().get("results", [])
306
- for r in results:
307
  res_url = r.get("url", "")
308
  if res_url and res_url not in processed_urls:
309
  raw_candidates.append({
310
  "title": r.get("title", "Verified News Output"),
311
- "url": res_url,
312
- "snippet": r.get("content", ""),
313
- "source": "Tavily"
314
  })
315
  processed_urls.add(res_url)
316
  except Exception as e:
317
  print(f"⚠️ Tavily failed: {str(e)}")
318
 
319
- # 3. --- DUCKDUCKGO BACKEND FALLBACK (Triggered if active routes yielded insufficient content) ---
320
  if len(raw_candidates) < limit:
321
  print(f"πŸ” [DDG FALLBACK] Augmenting search pool...")
322
  try:
323
- ddgs = DDGS()
324
- timelimit = "d" if is_news else None
325
- ddg_results = list(ddgs.text(expanded_query, max_results=limit * 2, backend="lite", timelimit=timelimit))
326
- for r in ddg_results:
327
  res_url = r.get("href", "")
328
  if res_url and res_url not in processed_urls:
329
- if is_news and not any(dom in res_url for dom in TRUSTED_DOMAINS):
330
- continue
331
  raw_candidates.append({
332
  "title": r.get("title", "DDG Verified Source"),
333
- "url": res_url,
334
- "snippet": r.get("body", ""),
335
- "source": "DDG"
336
  })
337
  processed_urls.add(res_url)
338
  except Exception as e:
339
  print(f"❌ DuckDuckGo fallback failed: {str(e)}")
340
 
341
- # 4. --- CROSS-ENCODER DEEP RERANKING & FILTERING SYSTEM ---
342
  if raw_candidates:
343
  try:
344
  documents = [c["snippet"] for c in raw_candidates if c["snippet"].strip()]
345
- if not documents:
346
- return raw_candidates[:limit]
347
 
348
  print(f"βš–οΈ Reranking {len(documents)} pooled Web candidates via Cross-Encoder...")
349
- rerank_results = list(self.reranker.rerank(query, documents))
 
 
 
 
 
 
 
 
350
 
351
  final_web_results = []
352
- for reranked in rerank_results[:limit]:
353
- original_match = raw_candidates[reranked.result_index]
354
  final_web_results.append({
355
- "title": original_match["title"],
356
- "url": original_match["url"],
357
- "snippet": reranked.text,
358
- "score": round(float(reranked.score), 4),
359
- "source": f"{original_match['source']} (Reranked)"
360
  })
361
 
362
  self.save_to_cache(query, final_web_results)
 
25
  Modifier
26
  )
27
  from sentence_transformers import SentenceTransformer
28
+
29
+ # --- UPDATED FASTEMBED IMPORTS ---
30
+ from fastembed import SparseTextEmbedding
31
+ from fastembed.rerank.cross_encoder import TextCrossEncoder
32
  import uuid
33
 
34
  load_dotenv()
 
60
  self.sparse_encoder = SparseTextEmbedding(model_name="Qdrant/bm25")
61
 
62
  print("🧠 Loading Cross-Encoder Reranking Engine...")
63
+ self.reranker = TextCrossEncoder(model_name="Xenova/ms-marco-MiniLM-L-6-v2")
64
 
65
  # Collection names
66
  self.cache_collection = "web_cache_hybrid"
 
90
 
91
  # --- PERSONAL CLOUD INDEXING METHODS ---
92
  def chunk_text(self, text: str, max_words: int = 150) -> list:
 
93
  words = text.split()
94
  return [" ".join(words[i:i + max_words]) for i in range(0, len(words), max_words)]
95
 
96
  def ingest_personal_file(self, filename: str, content: str):
 
97
  print(f"πŸ“‚ Indexing personal file with Hybrid vectors: {filename}")
98
  chunks = self.chunk_text(content)
99
  points = []
 
107
 
108
  points.append(PointStruct(
109
  id=str(uuid.uuid4()),
110
+ vector={"dense": vector_dense, "sparse": vector_sparse},
111
+ payload={"title": filename, "url": "Local File", "snippet": chunk, "source": "Personal Cloud"}
 
 
 
 
 
 
 
 
112
  ))
113
  if points:
114
  self.qdrant.upsert(collection_name=self.files_collection, points=points)
115
  print(f"βœ… Indexed {len(points)} hybrid vectors for {filename}")
116
 
117
  def search_personal_files(self, query: str, limit: int = 5) -> list:
 
118
  print(f"πŸ” Searching Personal Cloud (Hybrid Search) for: '{query}'")
119
  try:
120
  query_dense = self.encoder.encode(query).tolist()
 
139
  return []
140
 
141
  documents = [res.payload.get("snippet", "") for res in search_results]
 
142
  print(f"βš–οΈ Reranking {len(documents)} candidates via Cross-Encoder...")
143
+
144
+ # Universal scoring wrapper resilient to version changes
145
+ raw_scores = list(self.reranker.rerank(query, documents))
146
+ scored_candidates = []
147
+ for i, res in enumerate(raw_scores):
148
+ score_val = getattr(res, 'score', res)
149
+ idx_val = getattr(res, 'result_index', i)
150
+ scored_candidates.append((search_results[idx_val], score_val))
151
+
152
+ scored_candidates.sort(key=lambda x: x[1], reverse=True)
153
 
154
  final_contexts = []
155
+ for match, score in scored_candidates[:limit]:
 
156
  final_contexts.append({
157
+ "title": match.payload.get("title"),
158
+ "url": match.payload.get("url"),
159
+ "snippet": match.payload.get("snippet"),
160
+ "score": round(float(score), 4),
161
  "source": "Personal File (Reranked)"
162
  })
163
 
 
 
164
  return final_contexts
 
165
  except Exception as e:
166
  print(f"❌ Personal search failed: {str(e)}")
167
  return []
168
 
169
  # --- WEB SEARCH & CACHE METHODS ---
170
  def check_cache(self, query: str, limit: int = 3, threshold: float = -2.0) -> list:
 
171
  try:
172
  query_dense = self.encoder.encode(query).tolist()
173
  sparse_output = list(self.sparse_encoder.embed([query]))[0]
 
191
  return []
192
 
193
  documents = [res.payload.get("snippet", "") for res in search_results]
194
+ raw_scores = list(self.reranker.rerank(query, documents))
195
+
196
+ scored_candidates = []
197
+ for i, res in enumerate(raw_scores):
198
+ score_val = getattr(res, 'score', res)
199
+ idx_val = getattr(res, 'result_index', i)
200
+ scored_candidates.append((search_results[idx_val], score_val))
201
+
202
+ scored_candidates.sort(key=lambda x: x[1], reverse=True)
203
 
204
  cached_contexts = []
205
+ for match, score in scored_candidates[:limit]:
206
+ if float(score) >= threshold:
 
207
  cached_contexts.append({
208
+ "title": match.payload.get("title"),
209
+ "url": match.payload.get("url"),
210
+ "snippet": match.payload.get("snippet"),
211
+ "score": round(float(score), 4),
212
+ "source": f"Cache Reranked ({match.payload.get('source', 'Unknown')})"
213
  })
214
  return cached_contexts
215
  except Exception:
 
221
  points = []
222
  for r in results:
223
  text_to_embed = f"Query: {query} | Content: {r.get('snippet', '')}"
 
224
  vector_dense = self.encoder.encode(text_to_embed).tolist()
225
  sparse_output = list(self.sparse_encoder.embed([text_to_embed]))[0]
226
  vector_sparse = SparseVector(
 
230
 
231
  points.append(PointStruct(
232
  id=str(uuid.uuid4()),
233
+ vector={"dense": vector_dense, "sparse": vector_sparse},
 
 
 
234
  payload={
235
+ "original_query": query, "title": r.get("title"),
236
+ "url": r.get("url"), "snippet": r.get("snippet"),
 
 
237
  "source": r.get("source", "Web")
238
  }
239
  ))
 
249
  current_date_str = datetime.now().strftime("%B %d %Y")
250
  expanded_query = f"{query} {current_date_str}" if is_news else query
251
 
252
+ # 1. --- SERP API ROUTE ---
253
  if self.serp_key:
254
  try:
255
  print("πŸ” [SERP API] Querying premium Google Index engine...")
256
+ response = requests.get("https://serpapi.com/search", params={
257
+ "engine": "google", "q": expanded_query, "api_key": self.serp_key,
258
+ "num": limit * 2, "gl": "in", "hl": "en"
259
+ }, timeout=7)
 
 
 
 
 
 
260
  if response.status_code == 200:
261
+ for r in response.json().get("organic_results", []):
 
262
  res_url = r.get("link", "")
263
  if res_url and res_url not in processed_urls:
264
+ if is_news and not any(dom in res_url for dom in TRUSTED_DOMAINS): continue
 
265
  raw_candidates.append({
266
  "title": r.get("title", "Google Sourced Context"),
267
+ "url": res_url, "snippet": r.get("snippet", ""), "source": "SerpApi (Google)"
 
 
268
  })
269
  processed_urls.add(res_url)
270
  except Exception as e:
 
275
  try:
276
  print(f"🌍 [TAVILY] Executing concurrent context pull...")
277
  payload = {
278
+ "api_key": self.tavily_key, "query": expanded_query,
 
279
  "search_depth": "advanced" if is_news else "basic",
280
+ "max_results": limit * 2, "topic": "news" if is_news else "general",
 
281
  }
282
  if is_news:
283
  payload["days"] = 1
 
285
 
286
  response = requests.post("https://api.tavily.com/search", json=payload, timeout=7)
287
  if response.status_code not in [403, 429]:
288
+ for r in response.json().get("results", []):
 
 
289
  res_url = r.get("url", "")
290
  if res_url and res_url not in processed_urls:
291
  raw_candidates.append({
292
  "title": r.get("title", "Verified News Output"),
293
+ "url": res_url, "snippet": r.get("content", ""), "source": "Tavily"
 
 
294
  })
295
  processed_urls.add(res_url)
296
  except Exception as e:
297
  print(f"⚠️ Tavily failed: {str(e)}")
298
 
299
+ # 3. --- DUCKDUCKGO FALLBACK ---
300
  if len(raw_candidates) < limit:
301
  print(f"πŸ” [DDG FALLBACK] Augmenting search pool...")
302
  try:
303
+ for r in list(DDGS().text(expanded_query, max_results=limit * 2, backend="lite", timelimit="d" if is_news else None)):
 
 
 
304
  res_url = r.get("href", "")
305
  if res_url and res_url not in processed_urls:
306
+ if is_news and not any(dom in res_url for dom in TRUSTED_DOMAINS): continue
 
307
  raw_candidates.append({
308
  "title": r.get("title", "DDG Verified Source"),
309
+ "url": res_url, "snippet": r.get("body", ""), "source": "DDG"
 
 
310
  })
311
  processed_urls.add(res_url)
312
  except Exception as e:
313
  print(f"❌ DuckDuckGo fallback failed: {str(e)}")
314
 
315
+ # 4. --- CROSS-ENCODER DEEP RERANKING ---
316
  if raw_candidates:
317
  try:
318
  documents = [c["snippet"] for c in raw_candidates if c["snippet"].strip()]
319
+ if not documents: return raw_candidates[:limit]
 
320
 
321
  print(f"βš–οΈ Reranking {len(documents)} pooled Web candidates via Cross-Encoder...")
322
+ raw_scores = list(self.reranker.rerank(query, documents))
323
+
324
+ scored_candidates = []
325
+ for i, res in enumerate(raw_scores):
326
+ score_val = getattr(res, 'score', res)
327
+ idx_val = getattr(res, 'result_index', i)
328
+ scored_candidates.append((raw_candidates[idx_val], score_val))
329
+
330
+ scored_candidates.sort(key=lambda x: x[1], reverse=True)
331
 
332
  final_web_results = []
333
+ for match, score in scored_candidates[:limit]:
 
334
  final_web_results.append({
335
+ "title": match["title"],
336
+ "url": match["url"],
337
+ "snippet": match["snippet"],
338
+ "score": round(float(score), 4),
339
+ "source": f"{match['source']} (Reranked)"
340
  })
341
 
342
  self.save_to_cache(query, final_web_results)