-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag_system.py
More file actions
278 lines (230 loc) · 8.99 KB
/
rag_system.py
File metadata and controls
278 lines (230 loc) · 8.99 KB
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
"""
RAG (Retrieval Augmented Generation) System for Math Tutor Bot
Allows the tutor to answer questions based on uploaded documents
"""
import os
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss
from PyPDF2 import PdfReader
from typing import List, Dict
import pickle
class RAGSystem:
def __init__(self, documents_dir='uploaded_docs', index_dir='rag_index'):
"""
Initialize RAG system with document and index directories
"""
self.documents_dir = documents_dir
self.index_dir = index_dir
# Create directories if they don't exist
os.makedirs(documents_dir, exist_ok=True)
os.makedirs(index_dir, exist_ok=True)
# Load embedding model (lightweight, runs on CPU)
print("Loading embedding model...")
self.embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
print("✓ Embedding model loaded!")
# Initialize or load FAISS index
self.index = None
self.chunks = []
self.chunk_metadata = []
self.load_index()
def chunk_text(self, text: str, chunk_size=500, overlap=50) -> List[str]:
"""
Split text into overlapping chunks
"""
words = text.split()
chunks = []
for i in range(0, len(words), chunk_size - overlap):
chunk = ' '.join(words[i:i + chunk_size])
chunks.append(chunk)
return chunks
def process_pdf(self, pdf_path: str) -> str:
"""
Extract text from PDF file
"""
try:
reader = PdfReader(pdf_path)
text = ""
for page in reader.pages:
text += page.extract_text() + "\n"
return text
except Exception as e:
print(f"Error reading PDF {pdf_path}: {e}")
return ""
def process_txt(self, txt_path: str) -> str:
"""
Read text from TXT file
"""
try:
with open(txt_path, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
print(f"Error reading TXT {txt_path}: {e}")
return ""
def add_document(self, file_path: str, filename: str):
"""
Add a document to the RAG system
"""
print(f"Processing document: {filename}")
# Check if document already exists
existing_filenames = [m['filename'] for m in self.chunk_metadata]
if filename in existing_filenames:
print(f"⚠️ Document '{filename}' already exists in the system!")
print(f"Skipping upload to prevent duplicates.")
return False
# Extract text based on file type
if filename.lower().endswith('.pdf'):
text = self.process_pdf(file_path)
elif filename.lower().endswith('.txt'):
text = self.process_txt(file_path)
else:
print(f"Unsupported file type: {filename}")
return False
if not text.strip():
print(f"No text extracted from {filename}")
return False
# Chunk the text
new_chunks = self.chunk_text(text)
print(f"Created {len(new_chunks)} chunks from {filename}")
# Create embeddings
print("Creating embeddings...")
embeddings = self.embedding_model.encode(new_chunks, show_progress_bar=True)
# Add to index
if self.index is None:
# Create new index
dimension = embeddings.shape[1]
self.index = faiss.IndexFlatL2(dimension)
self.index.add(embeddings.astype('float32'))
# Store chunks and metadata
for i, chunk in enumerate(new_chunks):
self.chunks.append(chunk)
self.chunk_metadata.append({
'filename': filename,
'chunk_id': i,
'total_chunks': len(new_chunks)
})
# Save index
self.save_index()
print(f"✓ Document {filename} added successfully!")
return True
def retrieve(self, query: str, top_k=3, relevance_threshold=1.5) -> List[Dict]:
"""
Retrieve most relevant chunks for a query
Args:
query: The query string
top_k: Number of chunks to retrieve
relevance_threshold: Maximum L2 distance to consider relevant (default: 1.5)
Lower = more strict, higher = more lenient
"""
if self.index is None or self.index.ntotal == 0:
return []
# Encode query
query_embedding = self.embedding_model.encode([query])
# Search in FAISS index
distances, indices = self.index.search(query_embedding.astype('float32'), top_k)
# Prepare results - only include if below relevance threshold
results = []
for i, idx in enumerate(indices[0]):
distance = float(distances[0][i])
if idx < len(self.chunks) and distance < relevance_threshold:
results.append({
'text': self.chunks[idx],
'metadata': self.chunk_metadata[idx],
'score': distance
})
print(f"[RAG Retrieval] Chunk {idx} - distance: {distance:.3f} (relevant)")
elif idx < len(self.chunks):
print(f"[RAG Retrieval] Chunk {idx} - distance: {distance:.3f} (skipped - not relevant)")
return results
def get_context_for_query(self, query: str, top_k=3, relevance_threshold=1.5) -> str:
"""
Get formatted context string for LLM from retrieved chunks
Args:
query: The query string
top_k: Number of chunks to retrieve
relevance_threshold: Maximum L2 distance (default: 1.5, use 999 to get all chunks)
"""
results = self.retrieve(query, top_k, relevance_threshold)
if not results:
print("[RAG] No relevant context found - using base knowledge only")
return ""
print(f"[RAG] Found {len(results)} relevant chunk(s) - injecting context")
context = "**Relevant information from uploaded documents:**\n\n"
for i, result in enumerate(results, 1):
filename = result['metadata']['filename']
text = result['text']
context += f"[Source: {filename}]\n{text}\n\n"
return context
def save_index(self):
"""
Save FAISS index and metadata to disk
"""
if self.index is not None:
faiss.write_index(self.index, os.path.join(self.index_dir, 'faiss.index'))
# Save chunks and metadata
with open(os.path.join(self.index_dir, 'chunks.pkl'), 'wb') as f:
pickle.dump({
'chunks': self.chunks,
'metadata': self.chunk_metadata
}, f)
print("✓ Index saved successfully!")
def load_index(self):
"""
Load existing FAISS index and metadata from disk
"""
index_path = os.path.join(self.index_dir, 'faiss.index')
chunks_path = os.path.join(self.index_dir, 'chunks.pkl')
if os.path.exists(index_path) and os.path.exists(chunks_path):
print("Loading existing RAG index...")
self.index = faiss.read_index(index_path)
with open(chunks_path, 'rb') as f:
data = pickle.load(f)
self.chunks = data['chunks']
self.chunk_metadata = data['metadata']
print(f"✓ Loaded {len(self.chunks)} chunks from {len(set(m['filename'] for m in self.chunk_metadata))} documents")
else:
print("No existing index found. Starting fresh.")
def get_stats(self) -> Dict:
"""
Get statistics about the RAG system
"""
if not self.chunks:
return {
'total_chunks': 0,
'total_documents': 0,
'documents': []
}
documents = {}
for metadata in self.chunk_metadata:
filename = metadata['filename']
if filename not in documents:
documents[filename] = 0
documents[filename] += 1
return {
'total_chunks': len(self.chunks),
'total_documents': len(documents),
'documents': [{'name': k, 'chunks': v} for k, v in documents.items()]
}
def clear_all(self):
"""
Clear all documents and reset the index
"""
self.index = None
self.chunks = []
self.chunk_metadata = []
# Remove saved files
index_path = os.path.join(self.index_dir, 'faiss.index')
chunks_path = os.path.join(self.index_dir, 'chunks.pkl')
if os.path.exists(index_path):
os.remove(index_path)
if os.path.exists(chunks_path):
os.remove(chunks_path)
print("✓ All documents cleared!")
if __name__ == "__main__":
# Test the RAG system
print("RAG System Test")
print("=" * 60)
rag = RAGSystem()
print("\n" + "=" * 60)
print("RAG System ready!")
print("=" * 60)