Chris4K commited on
Commit
e904f34
·
verified ·
1 Parent(s): 68a1536

Create faq_service.py

Browse files
Files changed (1) hide show
  1. services/faq_service.py +91 -0
services/faq_service.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # services/faq_service.py
2
+ from typing import List, Dict, Any, Optional
3
+ import aiohttp
4
+ from bs4 import BeautifulSoup
5
+ import faiss
6
+ import logging
7
+ from config.config import settings
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ class FAQService:
12
+ def __init__(self, model_service):
13
+ self.embedder = model_service.embedder
14
+ self.faiss_index = None
15
+ self.faq_data = []
16
+
17
+ async def fetch_faq_pages(self) -> List[Dict[str, Any]]:
18
+ async with aiohttp.ClientSession() as session:
19
+ try:
20
+ async with session.get(f"{settings.FAQ_ROOT_URL}sitemap.xml", timeout=settings.TIMEOUT) as response:
21
+ if response.status == 200:
22
+ sitemap = await response.text()
23
+ soup = BeautifulSoup(sitemap, 'xml')
24
+ faq_urls = [loc.text for loc in soup.find_all('loc') if "/faq/" in loc.text]
25
+
26
+ tasks = [self.fetch_faq_content(url, session) for url in faq_urls]
27
+ return await asyncio.gather(*tasks)
28
+ except Exception as e:
29
+ logger.error(f"Error fetching FAQ sitemap: {e}")
30
+ return []
31
+
32
+ async def fetch_faq_content(self, url: str, session: aiohttp.ClientSession) -> Optional[Dict[str, Any]]:
33
+ try:
34
+ async with session.get(url, timeout=settings.TIMEOUT) as response:
35
+ if response.status == 200:
36
+ content = await response.text()
37
+ soup = BeautifulSoup(content, 'html.parser')
38
+
39
+ faq_title = soup.find('h1').text.strip() if soup.find('h1') else "Unknown Title"
40
+ faqs = []
41
+ sections = soup.find_all(['div', 'section'], class_=['faq-item', 'faq-section'])
42
+
43
+ for section in sections:
44
+ question = section.find(['h2', 'h3']).text.strip() if section.find(['h2', 'h3']) else None
45
+ answer = section.find(['p']).text.strip() if section.find(['p']) else None
46
+
47
+ if question and answer:
48
+ faqs.append({"question": question, "answer": answer})
49
+
50
+ return {"url": url, "title": faq_title, "faqs": faqs}
51
+ except Exception as e:
52
+ logger.error(f"Error fetching FAQ content from {url}: {e}")
53
+ return None
54
+
55
+ async def index_faqs(self):
56
+ faq_pages = await self.fetch_faq_pages()
57
+ faq_pages = [page for page in faq_pages if page]
58
+
59
+ self.faq_data = []
60
+ all_texts = []
61
+
62
+ for faq_page in faq_pages:
63
+ for item in faq_page['faqs']:
64
+ combined_text = f"{item['question']} {item['answer']}"
65
+ all_texts.append(combined_text)
66
+ self.faq_data.append({
67
+ "question": item['question'],
68
+ "answer": item['answer'],
69
+ "source": faq_page['url']
70
+ })
71
+
72
+ embeddings = self.embedder.encode(all_texts, convert_to_tensor=True).cpu().detach().numpy()
73
+ dimension = embeddings.shape[1]
74
+ self.faiss_index = faiss.IndexFlatL2(dimension)
75
+ self.faiss_index.add(embeddings)
76
+
77
+ async def search_faqs(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
78
+ if not self.faiss_index:
79
+ await self.index_faqs()
80
+
81
+ query_embedding = self.embedder.encode([query], convert_to_tensor=True).cpu().detach().numpy()
82
+ distances, indices = self.faiss_index.search(query_embedding, top_k)
83
+
84
+ results = []
85
+ for i, idx in enumerate(indices[0]):
86
+ if idx < len(self.faq_data):
87
+ result = self.faq_data[idx].copy()
88
+ result["score"] = float(distances[0][i])
89
+ results.append(result)
90
+
91
+ return results