Wall06 commited on
Commit
9f3cdd5
Β·
verified Β·
1 Parent(s): 4d9dea7

Create rag_engine.py

Browse files
Files changed (1) hide show
  1. rag_engine.py +146 -0
rag_engine.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import re
3
+ import textwrap
4
+ from pathlib import Path
5
+ from typing import Any
6
+ import faiss
7
+ import numpy as np
8
+ import requests
9
+ import spacy
10
+ from bs4 import BeautifulSoup
11
+ from huggingface_hub import InferenceClient
12
+ from pypdf import PdfReader
13
+ from sentence_transformers import SentenceTransformer
14
+
15
+ # ── Config ────────────────────────────────────────────────────────────────────
16
+ EMBED_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
17
+ LLM_MODEL = "HuggingFaceH4/zephyr-7b-beta"
18
+ CHUNK_SIZE = 400
19
+ CHUNK_OVERLAP = 80
20
+ TOP_K = 4
21
+
22
+ INTENT_MAP = {
23
+ "summarise": ["summarise", "summarize", "summary", "overview", "brief", "key points"],
24
+ "explain": ["explain", "what is", "what are", "define", "describe", "tell me about"],
25
+ "list": ["list", "enumerate", "give me a list", "what are the types"],
26
+ }
27
+
28
+ class RAGEngine:
29
+ def __init__(self):
30
+ self.embed_model = SentenceTransformer(EMBED_MODEL)
31
+ self.hf_client = InferenceClient()
32
+ try:
33
+ self.nlp = spacy.load("en_core_web_sm")
34
+ except:
35
+ # Fallback if model not downloaded
36
+ import os
37
+ os.system("python -m spacy download en_core_web_sm")
38
+ self.nlp = spacy.load("en_core_web_sm")
39
+
40
+ self.reset()
41
+
42
+ def reset(self):
43
+ self.chunks: list[str] = []
44
+ self.index: faiss.IndexFlatL2 | None = None
45
+ self.ready = False
46
+
47
+ def _process_text_into_chunks(self, text: str):
48
+ text = re.sub(r'\s+', ' ', text).strip()
49
+ new_chunks = []
50
+ for i in range(0, len(text), CHUNK_SIZE - CHUNK_OVERLAP):
51
+ chunk = text[i : i + CHUNK_SIZE]
52
+ if len(chunk) > 20:
53
+ new_chunks.append(chunk)
54
+
55
+ self.chunks = new_chunks
56
+ embeddings = self.embed_model.encode(self.chunks)
57
+ self.index = faiss.IndexFlatL2(embeddings.shape[1])
58
+ self.index.add(np.array(embeddings).astype("float32"))
59
+ self.ready = True
60
+
61
+ def load_pdf(self, path: str) -> str:
62
+ reader = PdfReader(path)
63
+ text = "".join([page.extract_text() for page in reader.pages])
64
+ self._process_text_into_chunks(text)
65
+ return f"βœ… Loaded PDF: {len(self.chunks)} chunks indexed."
66
+
67
+ def load_url(self, url: str) -> str:
68
+ res = requests.get(url, timeout=10)
69
+ soup = BeautifulSoup(res.text, "html.parser")
70
+ for script in soup(["script", "style"]):
71
+ script.decompose()
72
+ self._process_text_into_chunks(soup.get_text())
73
+ return f"βœ… Loaded URL: {len(self.chunks)} chunks indexed."
74
+
75
+ def load_text(self, text: str) -> str:
76
+ self._process_text_into_chunks(text)
77
+ return f"βœ… Loaded Text: {len(self.chunks)} chunks indexed."
78
+
79
+ def detect_intent(self, query: str) -> str:
80
+ query_lower = query.lower()
81
+ for intent, keywords in INTENT_MAP.items():
82
+ if any(k in query_lower for k in keywords):
83
+ return intent
84
+ return "general_query"
85
+
86
+ def extract_entities(self, text: str) -> dict[str, list[str]]:
87
+ doc = self.nlp(text)
88
+ entities = {}
89
+ for ent in doc.ents:
90
+ if ent.label_ not in entities:
91
+ entities[ent.label_] = []
92
+ if ent.text not in entities[ent.label_]:
93
+ entities[ent.label_].append(ent.text)
94
+ return entities
95
+
96
+ def _retrieve(self, query: str) -> list[str]:
97
+ query_vec = self.embed_model.encode([query]).astype("float32")
98
+ _, indices = self.index.search(query_vec, TOP_K)
99
+ return [self.chunks[i] for i in indices[0]]
100
+
101
+ def _build_prompt(self, query: str, chunks: list[str]) -> str:
102
+ context = "\n".join([f"- {c}" for c in chunks])
103
+ return textwrap.dedent(f"""
104
+ <|system|>
105
+ You are a helpful assistant. Use the following context to answer the user's question.
106
+ If the answer is not in the context, say you don't know based on the provided data.
107
+ </s>
108
+ <|user|>
109
+ Context:
110
+ {context}
111
+
112
+ Question: {query}
113
+ </s>
114
+ <|assistant|>
115
+ """).strip()
116
+
117
+ def answer(self, query: str) -> str:
118
+ if not self.ready:
119
+ return "⚠️ No knowledge source loaded. Please load a PDF, URL, or text first."
120
+ chunks = self._retrieve(query)
121
+ prompt = self._build_prompt(query, chunks)
122
+ try:
123
+ response = self.hf_client.text_generation(
124
+ prompt,
125
+ model=LLM_MODEL,
126
+ max_new_tokens=512,
127
+ temperature=0.3,
128
+ repetition_penalty=1.1,
129
+ stop_sequences=["</s>", "<|user|>"],
130
+ )
131
+ answer_text = response.strip()
132
+ except Exception as e:
133
+ answer_text = f"⚠️ LLM API unavailable ({e}).\n\n**Most relevant passage found:**\n\n{chunks[0]}"
134
+ return answer_text
135
+
136
+ def answer_with_nlp(self, query: str) -> tuple[str, dict[str, Any]]:
137
+ answer_text = self.answer(query)
138
+ intent = self.detect_intent(query)
139
+ entities_in_query = self.extract_entities(query)
140
+ entities_in_answer = self.extract_entities(answer_text)
141
+ nlp_info = {
142
+ "detected_intent": intent,
143
+ "entities_in_query": entities_in_query,
144
+ "entities_in_answer": entities_in_answer,
145
+ }
146
+ return answer_text, nlp_info