Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,12 @@
|
|
| 1 |
import time
|
| 2 |
import fitz
|
| 3 |
import numpy as np
|
| 4 |
-
import pickle
|
| 5 |
-
import os
|
| 6 |
import dill
|
|
|
|
| 7 |
import logging
|
| 8 |
import asyncio
|
| 9 |
import networkx as nx
|
| 10 |
-
from mistralai import Mistral
|
| 11 |
from annoy import AnnoyIndex
|
| 12 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 13 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 14 |
from rank_bm25 import BM25Okapi
|
| 15 |
from gensim.models import Word2Vec
|
|
@@ -17,12 +14,14 @@ from typing import List, Optional, Tuple
|
|
| 17 |
import gradio as gr
|
| 18 |
from openai import OpenAI
|
| 19 |
|
| 20 |
-
logger = logging.getLogger(__name__)
|
| 21 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 22 |
|
| 23 |
-
api_key = os.getenv("MISTRAL_API_KEY")
|
| 24 |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
def get_text_embedding_with_rate_limit(text_list, initial_delay=2, max_retries=10, max_delay=60):
|
| 28 |
embeddings = []
|
|
@@ -34,12 +33,11 @@ def get_text_embedding_with_rate_limit(text_list, initial_delay=2, max_retries=1
|
|
| 34 |
if len(text) > 8192:
|
| 35 |
logging.warning("Text chunk exceeds the token limit. Truncating the text.")
|
| 36 |
text = text[:8192]
|
| 37 |
-
|
| 38 |
response = client.embeddings.create(
|
| 39 |
model="text-embedding-3-small",
|
| 40 |
input=[text]
|
| 41 |
)
|
| 42 |
-
embeddings.append(response.data[0].embedding)
|
| 43 |
time.sleep(delay)
|
| 44 |
break
|
| 45 |
except Exception as e:
|
|
@@ -51,177 +49,109 @@ def get_text_embedding_with_rate_limit(text_list, initial_delay=2, max_retries=1
|
|
| 51 |
logging.error("Max retries reached. Skipping this chunk.")
|
| 52 |
return embeddings
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
def store_embeddings_in_vector_db(
|
| 56 |
-
pdf_path: str,
|
| 57 |
-
vector_db_path: str,
|
| 58 |
-
annoy_index_path: str,
|
| 59 |
-
chunk_size: int = 2048,
|
| 60 |
-
overlap: int = 200,
|
| 61 |
-
num_trees: int = 10
|
| 62 |
-
):
|
| 63 |
doc = fitz.open(pdf_path)
|
| 64 |
all_embeddings = []
|
| 65 |
all_texts = []
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
for page_num in range(total_pages):
|
| 70 |
-
page = doc.load_page(page_num)
|
| 71 |
-
text = page.get_text()
|
| 72 |
if text.strip():
|
| 73 |
chunks = split_text_into_chunks(text, chunk_size, overlap)
|
| 74 |
embeddings = get_text_embedding_with_rate_limit(chunks)
|
| 75 |
all_embeddings.extend(embeddings)
|
| 76 |
all_texts.extend(chunks)
|
| 77 |
-
logging.info(f"Processed page {page_num + 1}/{total_pages}, extracted {len(chunks)} chunks.")
|
| 78 |
-
else:
|
| 79 |
-
logging.warning(f"No text found on page {page_num + 1}.")
|
| 80 |
-
|
| 81 |
embeddings_np = np.array(all_embeddings).astype('float32')
|
| 82 |
with open(vector_db_path, "wb") as f:
|
| 83 |
dill.dump({'embeddings': embeddings_np, 'texts': all_texts}, f)
|
| 84 |
-
logging.info(f"Stored embeddings and texts to {vector_db_path}.")
|
| 85 |
-
|
| 86 |
if os.path.exists(annoy_index_path):
|
| 87 |
os.remove(annoy_index_path)
|
| 88 |
-
logging.info(f"Existing Annoy index at {annoy_index_path} removed.")
|
| 89 |
-
|
| 90 |
embedding_dim = embeddings_np.shape[1]
|
| 91 |
annoy_index = AnnoyIndex(embedding_dim, 'angular')
|
| 92 |
for i, embedding in enumerate(embeddings_np):
|
| 93 |
annoy_index.add_item(i, embedding)
|
| 94 |
annoy_index.build(num_trees)
|
| 95 |
annoy_index.save(annoy_index_path)
|
| 96 |
-
logging.info(f"Annoy index built with {len(all_embeddings)} items and saved to {annoy_index_path}.")
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
chunks = []
|
| 101 |
-
start = 0
|
| 102 |
-
while start < len(tokens):
|
| 103 |
-
end = start + chunk_size
|
| 104 |
-
chunk = " ".join(tokens[start:end])
|
| 105 |
-
chunks.append(chunk)
|
| 106 |
-
start += chunk_size - overlap
|
| 107 |
-
return chunks
|
| 108 |
|
| 109 |
class MistralRAGChatbot:
|
| 110 |
def __init__(self, vector_db_path: str, annoy_index_path: str):
|
| 111 |
-
self.embeddings, self.texts = self.load_vector_db(vector_db_path)
|
| 112 |
-
self.annoy_index = self.load_annoy_index(annoy_index_path, self.embeddings.shape[1])
|
| 113 |
-
self.bm25 = BM25Okapi([text.split() for text in self.texts])
|
| 114 |
-
self.word2vec_model = self.train_word2vec(self.texts)
|
| 115 |
-
self.reranking_methods = {
|
| 116 |
-
'advanced_fusion': self.advanced_fusion_retrieval
|
| 117 |
-
}
|
| 118 |
-
logging.info("MistralRAGChatbot initialized successfully.")
|
| 119 |
-
|
| 120 |
-
def load_vector_db(self, vector_db_path: str) -> Tuple[np.ndarray, List[str]]:
|
| 121 |
with open(vector_db_path, "rb") as f:
|
| 122 |
data = dill.load(f)
|
| 123 |
-
embeddings = np.array(data['embeddings'], dtype='float32')
|
| 124 |
-
texts = data['texts']
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
if not os.path.exists(annoy_index_path):
|
| 130 |
-
raise FileNotFoundError(f"Annoy index file {annoy_index_path} not found.")
|
| 131 |
-
annoy_index = AnnoyIndex(embedding_dim, 'angular')
|
| 132 |
-
annoy_index.load(annoy_index_path)
|
| 133 |
-
logging.info(f"Loaded Annoy index from {annoy_index_path}.")
|
| 134 |
-
return annoy_index
|
| 135 |
-
|
| 136 |
-
def train_word2vec(self, texts: List[str]) -> Word2Vec:
|
| 137 |
-
tokenized_texts = [text.split() for text in texts]
|
| 138 |
-
model = Word2Vec(sentences=tokenized_texts, vector_size=100, window=5, min_count=1, workers=4)
|
| 139 |
-
logging.info("Word2Vec model trained.")
|
| 140 |
-
return model
|
| 141 |
|
| 142 |
-
def get_text_embedding(self, text: str
|
| 143 |
try:
|
| 144 |
response = client.embeddings.create(
|
| 145 |
model="text-embedding-3-small",
|
| 146 |
input=[text]
|
| 147 |
)
|
| 148 |
-
return np.array(response.data[0].embedding, dtype=np.float32)
|
| 149 |
except Exception as e:
|
| 150 |
-
logging.error(f"Error fetching
|
| 151 |
return np.zeros((1536,), dtype=np.float32)
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
sim_graph = nx.Graph()
|
| 161 |
sim_matrix = cosine_similarity(self.embeddings)
|
| 162 |
for i in range(len(self.embeddings)):
|
| 163 |
for j in range(i + 1, len(self.embeddings)):
|
| 164 |
if sim_matrix[i, j] > 0.5:
|
| 165 |
sim_graph.add_edge(i, j, weight=sim_matrix[i, j])
|
| 166 |
-
|
| 167 |
pagerank_scores = np.array(list(nx.pagerank(sim_graph, weight='weight').values()))
|
| 168 |
-
|
| 169 |
-
combined_scores = {}
|
| 170 |
for doc in docs:
|
| 171 |
idx = doc['index']
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
0.3 * bm25_scores.get(idx, 0) +
|
| 175 |
-
0.2 * pagerank_scores[idx] if idx < len(pagerank_scores) else 0
|
| 176 |
-
)
|
| 177 |
-
|
| 178 |
-
min_score = min(combined_scores.values())
|
| 179 |
-
max_score = max(combined_scores.values())
|
| 180 |
-
|
| 181 |
-
if min_score == max_score:
|
| 182 |
-
normalized_scores = {idx: 0.5 for idx in combined_scores}
|
| 183 |
-
else:
|
| 184 |
-
normalized_scores = {idx: (score - min_score) / (max_score - min_score) for idx, score in combined_scores.items()}
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
async def generate_response_with_rag(
|
| 205 |
-
self,
|
| 206 |
-
user_query: str,
|
| 207 |
-
model: str = "gpt-4o-mini",
|
| 208 |
-
top_k: int = 10,
|
| 209 |
-
response_style: str = "Detailed",
|
| 210 |
-
selected_retrieval_methods: Optional[List[str]] = None,
|
| 211 |
-
selected_reranking_methods: Optional[List[str]] = None
|
| 212 |
-
) -> Tuple[str, List[str], List[dict]]:
|
| 213 |
-
if not selected_retrieval_methods:
|
| 214 |
-
selected_retrieval_methods = ['annoy', 'bm25']
|
| 215 |
-
if not selected_reranking_methods:
|
| 216 |
-
selected_reranking_methods = ['advanced_fusion']
|
| 217 |
-
|
| 218 |
-
query_embedding = self.get_text_embedding(user_query)
|
| 219 |
-
retrieved_docs = self.retrieve_documents(user_query, query_embedding, top_k, selected_retrieval_methods)
|
| 220 |
-
reranked_docs = self.rerank_documents(user_query, retrieved_docs, selected_reranking_methods)
|
| 221 |
-
|
| 222 |
-
context = "\n\n".join([doc['text'] for doc in reranked_docs[:5]])
|
| 223 |
-
prompt = self.build_prompt(context, user_query, response_style)
|
| 224 |
-
|
| 225 |
try:
|
| 226 |
response = ""
|
| 227 |
stream = client.chat.completions.create(
|
|
@@ -232,132 +162,14 @@ class MistralRAGChatbot:
|
|
| 232 |
for chunk in stream:
|
| 233 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 234 |
response += chunk.choices[0].delta.content
|
| 235 |
-
|
| 236 |
except Exception as e:
|
| 237 |
logging.error(f"Error generating response: {e}")
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
return response, [doc['text'] for doc in reranked_docs[:5]], reranked_docs[:5]
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
def retrieve_documents(
|
| 245 |
-
self,
|
| 246 |
-
user_query: str,
|
| 247 |
-
query_embedding: np.ndarray,
|
| 248 |
-
top_k: int,
|
| 249 |
-
selected_methods: List[str]
|
| 250 |
-
) -> List[dict]:
|
| 251 |
-
all_docs = []
|
| 252 |
-
for method in selected_methods:
|
| 253 |
-
indices, scores = getattr(self, f"retrieve_with_{method}")(user_query, query_embedding, top_k)
|
| 254 |
-
for idx, score in zip(indices, scores):
|
| 255 |
-
all_docs.append({
|
| 256 |
-
'text': self.texts[idx],
|
| 257 |
-
'method': method,
|
| 258 |
-
'score': score,
|
| 259 |
-
'index': idx
|
| 260 |
-
})
|
| 261 |
-
return all_docs
|
| 262 |
-
|
| 263 |
-
def retrieve_with_annoy(self, user_query: str, query_embedding: np.ndarray, top_k: int) -> Tuple[List[int], List[float]]:
|
| 264 |
-
n_results = min(top_k, len(self.texts))
|
| 265 |
-
indices, distances = self.annoy_index.get_nns_by_vector(query_embedding, n_results, include_distances=True)
|
| 266 |
-
scores = [1.0 - (dist / max(distances)) for dist in distances] if distances else []
|
| 267 |
-
logging.debug(f"Annoy retrieval returned {len(indices)} documents.")
|
| 268 |
-
return indices, scores
|
| 269 |
-
|
| 270 |
-
def retrieve_with_bm25(self, user_query: str, query_embedding: np.ndarray, top_k: int) -> Tuple[List[int], List[float]]:
|
| 271 |
-
tokenized_query = user_query.split()
|
| 272 |
-
scores = self.bm25.get_scores(tokenized_query)
|
| 273 |
-
indices = np.argsort(-scores)[:top_k]
|
| 274 |
-
logging.debug(f"BM25 retrieval returned {len(indices)} documents.")
|
| 275 |
-
return indices, scores[indices].tolist()
|
| 276 |
-
|
| 277 |
-
def rerank_documents(
|
| 278 |
-
self,
|
| 279 |
-
user_query: str,
|
| 280 |
-
retrieved_docs: List[dict],
|
| 281 |
-
selected_methods: List[str]
|
| 282 |
-
) -> List[dict]:
|
| 283 |
-
reranked_docs = retrieved_docs
|
| 284 |
-
for method in selected_methods:
|
| 285 |
-
if method == 'advanced_fusion':
|
| 286 |
-
reranked_docs = self.advanced_fusion_retrieval(user_query, reranked_docs)
|
| 287 |
-
else:
|
| 288 |
-
reranked_docs = self.reranking_methods[method](user_query, reranked_docs)
|
| 289 |
-
|
| 290 |
-
return reranked_docs
|
| 291 |
-
|
| 292 |
-
def build_prompt(self, context: str, user_query: str, response_style: str) -> str:
|
| 293 |
-
styles = {
|
| 294 |
-
"detailed": "Provide a comprehensive and detailed answer based on the provided context.",
|
| 295 |
-
"concise": "Provide a brief and concise answer based on the provided context.",
|
| 296 |
-
"creative": "Provide a creative and engaging answer based on the provided context.",
|
| 297 |
-
"technical": "Provide a technical and in-depth answer based on the provided context."
|
| 298 |
-
}
|
| 299 |
-
|
| 300 |
-
style_instruction = styles.get(response_style.lower(), styles["detailed"])
|
| 301 |
-
|
| 302 |
-
if not context or not self.is_context_relevant(context, user_query):
|
| 303 |
-
prompt = f"""You are an intelligent assistant.
|
| 304 |
-
User Question:
|
| 305 |
-
{user_query}
|
| 306 |
-
Instruction:
|
| 307 |
-
The document database does not contain relevant information to answer the question. Please inform the user that no relevant documents were found and refrain from generating an imaginative or unrelated response."""
|
| 308 |
-
else:
|
| 309 |
-
prompt = f"""You are an intelligent assistant.
|
| 310 |
-
Context:
|
| 311 |
-
{context}
|
| 312 |
-
User Question:
|
| 313 |
-
{user_query}
|
| 314 |
-
Instruction:
|
| 315 |
-
{style_instruction}"""
|
| 316 |
-
|
| 317 |
-
logging.debug("Prompt constructed for response generation.")
|
| 318 |
-
return prompt
|
| 319 |
-
|
| 320 |
-
def is_context_relevant(self, context: str, user_query: str) -> bool:
|
| 321 |
-
context_lower = context.lower()
|
| 322 |
-
user_query_lower = user_query.lower()
|
| 323 |
-
query_terms = set(user_query_lower.split())
|
| 324 |
-
context_terms = set(context_lower.split())
|
| 325 |
-
common_terms = query_terms.intersection(context_terms)
|
| 326 |
-
return len(common_terms) > len(query_terms) * 0.2
|
| 327 |
-
|
| 328 |
-
def create_vector_db_and_annoy_index(pdf_path, vector_db_path, annoy_index_path):
|
| 329 |
-
store_embeddings_in_vector_db(pdf_path, vector_db_path, annoy_index_path)
|
| 330 |
-
print("Vector database and Annoy index creation completed.")
|
| 331 |
-
|
| 332 |
-
def chatbot_interface(file, user_query, response_style):
|
| 333 |
-
vector_db_path = "vector_db.pkl"
|
| 334 |
-
annoy_index_path = "vector_index.ann"
|
| 335 |
-
chunk_size = 2048
|
| 336 |
-
overlap = 200
|
| 337 |
-
store_embeddings_in_vector_db(file.name, vector_db_path, annoy_index_path, chunk_size, overlap)
|
| 338 |
-
|
| 339 |
-
chatbot = MistralRAGChatbot(vector_db_path, annoy_index_path)
|
| 340 |
-
|
| 341 |
-
selected_retrieval_methods_list = ['annoy', 'bm25']
|
| 342 |
-
selected_reranking_methods_list = ["advanced_fusion"]
|
| 343 |
-
|
| 344 |
-
response, retrieved_docs, source_info = asyncio.run(chatbot.generate_response_with_rag(
|
| 345 |
-
user_query=user_query,
|
| 346 |
-
response_style=response_style,
|
| 347 |
-
selected_retrieval_methods=selected_retrieval_methods_list,
|
| 348 |
-
selected_reranking_methods=selected_reranking_methods_list
|
| 349 |
-
))
|
| 350 |
-
|
| 351 |
-
formatted_response = f"Response:\n{response}\n\n"
|
| 352 |
-
formatted_response += "Retrieved and Reranked Documents:\n"
|
| 353 |
-
for idx, doc_info in enumerate(source_info, start=1):
|
| 354 |
-
formatted_response += f"\nDocument {idx}:\n"
|
| 355 |
-
formatted_response += f"Content Preview: {doc_info['text'][:200]}...\n"
|
| 356 |
-
formatted_response += f"Retrieval Method: {doc_info['method']}\n"
|
| 357 |
-
if 'score' in doc_info:
|
| 358 |
-
formatted_response += f"Precision Score: {doc_info['score']:.4f}\n"
|
| 359 |
|
| 360 |
-
|
|
|
|
|
|
|
| 361 |
|
| 362 |
iface = gr.Blocks(theme="Rabbitt-AI/ChanceRAG")
|
| 363 |
with iface:
|
|
@@ -366,13 +178,10 @@ with iface:
|
|
| 366 |
fn=chatbot_interface,
|
| 367 |
theme="Rabbitt-AI/ChanceRAG",
|
| 368 |
inputs=[
|
| 369 |
-
gr.File(label="Upload a File"),
|
| 370 |
gr.Textbox(lines=5, label="User Query"),
|
| 371 |
-
gr.Dropdown([
|
| 372 |
-
"Detailed", "Concise", "Creative", "Technical"], label="Response Style"
|
| 373 |
-
),
|
| 374 |
],
|
| 375 |
-
outputs=
|
| 376 |
)
|
| 377 |
|
| 378 |
-
iface.launch(share=True)
|
|
|
|
| 1 |
import time
|
| 2 |
import fitz
|
| 3 |
import numpy as np
|
|
|
|
|
|
|
| 4 |
import dill
|
| 5 |
+
import os
|
| 6 |
import logging
|
| 7 |
import asyncio
|
| 8 |
import networkx as nx
|
|
|
|
| 9 |
from annoy import AnnoyIndex
|
|
|
|
| 10 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 11 |
from rank_bm25 import BM25Okapi
|
| 12 |
from gensim.models import Word2Vec
|
|
|
|
| 14 |
import gradio as gr
|
| 15 |
from openai import OpenAI
|
| 16 |
|
|
|
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
|
|
|
|
| 20 |
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 21 |
+
|
| 22 |
+
PDF_PATH = "input.pdf"
|
| 23 |
+
VECTOR_DB_PATH = "vector_db.pkl"
|
| 24 |
+
ANNOY_INDEX_PATH = "vector_index.ann"
|
| 25 |
|
| 26 |
def get_text_embedding_with_rate_limit(text_list, initial_delay=2, max_retries=10, max_delay=60):
|
| 27 |
embeddings = []
|
|
|
|
| 33 |
if len(text) > 8192:
|
| 34 |
logging.warning("Text chunk exceeds the token limit. Truncating the text.")
|
| 35 |
text = text[:8192]
|
|
|
|
| 36 |
response = client.embeddings.create(
|
| 37 |
model="text-embedding-3-small",
|
| 38 |
input=[text]
|
| 39 |
)
|
| 40 |
+
embeddings.append(response.data[0].embedding)
|
| 41 |
time.sleep(delay)
|
| 42 |
break
|
| 43 |
except Exception as e:
|
|
|
|
| 49 |
logging.error("Max retries reached. Skipping this chunk.")
|
| 50 |
return embeddings
|
| 51 |
|
| 52 |
+
def split_text_into_chunks(text: str, chunk_size: int = 2048, overlap: int = 200) -> List[str]:
|
| 53 |
+
tokens = text.split()
|
| 54 |
+
chunks = []
|
| 55 |
+
start = 0
|
| 56 |
+
while start < len(tokens):
|
| 57 |
+
end = start + chunk_size
|
| 58 |
+
chunk = " ".join(tokens[start:end])
|
| 59 |
+
chunks.append(chunk)
|
| 60 |
+
start += chunk_size - overlap
|
| 61 |
+
return chunks
|
| 62 |
|
| 63 |
+
def store_embeddings_in_vector_db(pdf_path, vector_db_path, annoy_index_path, chunk_size=2048, overlap=200, num_trees=10):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
doc = fitz.open(pdf_path)
|
| 65 |
all_embeddings = []
|
| 66 |
all_texts = []
|
| 67 |
+
for page_num in range(doc.page_count):
|
| 68 |
+
text = doc.load_page(page_num).get_text()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
if text.strip():
|
| 70 |
chunks = split_text_into_chunks(text, chunk_size, overlap)
|
| 71 |
embeddings = get_text_embedding_with_rate_limit(chunks)
|
| 72 |
all_embeddings.extend(embeddings)
|
| 73 |
all_texts.extend(chunks)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
embeddings_np = np.array(all_embeddings).astype('float32')
|
| 75 |
with open(vector_db_path, "wb") as f:
|
| 76 |
dill.dump({'embeddings': embeddings_np, 'texts': all_texts}, f)
|
|
|
|
|
|
|
| 77 |
if os.path.exists(annoy_index_path):
|
| 78 |
os.remove(annoy_index_path)
|
|
|
|
|
|
|
| 79 |
embedding_dim = embeddings_np.shape[1]
|
| 80 |
annoy_index = AnnoyIndex(embedding_dim, 'angular')
|
| 81 |
for i, embedding in enumerate(embeddings_np):
|
| 82 |
annoy_index.add_item(i, embedding)
|
| 83 |
annoy_index.build(num_trees)
|
| 84 |
annoy_index.save(annoy_index_path)
|
|
|
|
| 85 |
|
| 86 |
+
if not os.path.exists(VECTOR_DB_PATH) or not os.path.exists(ANNOY_INDEX_PATH):
|
| 87 |
+
store_embeddings_in_vector_db(PDF_PATH, VECTOR_DB_PATH, ANNOY_INDEX_PATH)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
class MistralRAGChatbot:
|
| 90 |
def __init__(self, vector_db_path: str, annoy_index_path: str):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
with open(vector_db_path, "rb") as f:
|
| 92 |
data = dill.load(f)
|
| 93 |
+
self.embeddings = np.array(data['embeddings'], dtype='float32')
|
| 94 |
+
self.texts = data['texts']
|
| 95 |
+
self.annoy_index = AnnoyIndex(self.embeddings.shape[1], 'angular')
|
| 96 |
+
self.annoy_index.load(annoy_index_path)
|
| 97 |
+
self.bm25 = BM25Okapi([text.split() for text in self.texts])
|
| 98 |
+
self.word2vec_model = Word2Vec([text.split() for text in self.texts], vector_size=100, window=5, min_count=1, workers=4)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
def get_text_embedding(self, text: str) -> np.ndarray:
|
| 101 |
try:
|
| 102 |
response = client.embeddings.create(
|
| 103 |
model="text-embedding-3-small",
|
| 104 |
input=[text]
|
| 105 |
)
|
| 106 |
+
return np.array(response.data[0].embedding, dtype=np.float32)
|
| 107 |
except Exception as e:
|
| 108 |
+
logging.error(f"Error fetching embedding: {e}")
|
| 109 |
return np.zeros((1536,), dtype=np.float32)
|
| 110 |
|
| 111 |
+
def retrieve_documents(self, query: str, embedding: np.ndarray, top_k=10):
|
| 112 |
+
indices, distances = self.annoy_index.get_nns_by_vector(embedding, top_k, include_distances=True)
|
| 113 |
+
bm25_scores = self.bm25.get_scores(query.split())
|
| 114 |
+
combined_docs = []
|
| 115 |
+
for idx in indices:
|
| 116 |
+
combined_docs.append({
|
| 117 |
+
'text': self.texts[idx],
|
| 118 |
+
'method': 'hybrid',
|
| 119 |
+
'score': float(bm25_scores[idx]),
|
| 120 |
+
'index': idx
|
| 121 |
+
})
|
| 122 |
+
return combined_docs
|
| 123 |
+
|
| 124 |
+
def rerank_documents(self, query: str, docs: List[dict]) -> List[dict]:
|
| 125 |
+
query_embedding = self.get_text_embedding(query)
|
| 126 |
+
vector_scores = {doc['index']: doc['score'] for doc in docs}
|
| 127 |
sim_graph = nx.Graph()
|
| 128 |
sim_matrix = cosine_similarity(self.embeddings)
|
| 129 |
for i in range(len(self.embeddings)):
|
| 130 |
for j in range(i + 1, len(self.embeddings)):
|
| 131 |
if sim_matrix[i, j] > 0.5:
|
| 132 |
sim_graph.add_edge(i, j, weight=sim_matrix[i, j])
|
|
|
|
| 133 |
pagerank_scores = np.array(list(nx.pagerank(sim_graph, weight='weight').values()))
|
|
|
|
|
|
|
| 134 |
for doc in docs:
|
| 135 |
idx = doc['index']
|
| 136 |
+
doc['score'] = 0.7 * vector_scores.get(idx, 0) + 0.3 * pagerank_scores[idx]
|
| 137 |
+
return sorted(docs, key=lambda x: x['score'], reverse=True)[:5]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
def build_prompt(self, context: str, query: str, style: str) -> str:
|
| 140 |
+
styles = {
|
| 141 |
+
"detailed": "Provide a detailed answer.",
|
| 142 |
+
"concise": "Provide a concise answer.",
|
| 143 |
+
"creative": "Be creative in your response.",
|
| 144 |
+
"technical": "Provide a technically sound answer."
|
| 145 |
+
}
|
| 146 |
+
instruction = styles.get(style.lower(), styles["detailed"])
|
| 147 |
+
return f"""You are a helpful assistant.\nContext:\n{context}\nQuestion:\n{query}\nInstruction:\n{instruction}"""
|
| 148 |
+
|
| 149 |
+
def generate_response(self, query: str, style: str) -> str:
|
| 150 |
+
query_embedding = self.get_text_embedding(query)
|
| 151 |
+
docs = self.retrieve_documents(query, query_embedding)
|
| 152 |
+
reranked_docs = self.rerank_documents(query, docs)
|
| 153 |
+
context = "\n\n".join([doc['text'] for doc in reranked_docs])
|
| 154 |
+
prompt = self.build_prompt(context, query, style)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
try:
|
| 156 |
response = ""
|
| 157 |
stream = client.chat.completions.create(
|
|
|
|
| 162 |
for chunk in stream:
|
| 163 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 164 |
response += chunk.choices[0].delta.content
|
| 165 |
+
return response
|
| 166 |
except Exception as e:
|
| 167 |
logging.error(f"Error generating response: {e}")
|
| 168 |
+
return "Sorry, I couldn't generate a response."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
def chatbot_interface(user_query, response_style):
|
| 171 |
+
bot = MistralRAGChatbot(VECTOR_DB_PATH, ANNOY_INDEX_PATH)
|
| 172 |
+
return bot.generate_response(user_query, response_style)
|
| 173 |
|
| 174 |
iface = gr.Blocks(theme="Rabbitt-AI/ChanceRAG")
|
| 175 |
with iface:
|
|
|
|
| 178 |
fn=chatbot_interface,
|
| 179 |
theme="Rabbitt-AI/ChanceRAG",
|
| 180 |
inputs=[
|
|
|
|
| 181 |
gr.Textbox(lines=5, label="User Query"),
|
| 182 |
+
gr.Dropdown(["Detailed", "Concise", "Creative", "Technical"], label="Response Style"),
|
|
|
|
|
|
|
| 183 |
],
|
| 184 |
+
outputs=gr.Textbox(label="ChanceRAG Response"),
|
| 185 |
)
|
| 186 |
|
| 187 |
+
iface.launch(share=True)
|