-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_cli.py
More file actions
265 lines (212 loc) ยท 8.31 KB
/
Copy pathsimple_cli.py
File metadata and controls
265 lines (212 loc) ยท 8.31 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
#!/usr/bin/env python3
"""
Simple CLI PDF Analyzer - Just ask questions and get answers
"""
import pdfplumber
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer
import ollama
import os
from typing import List, Dict
class SimplePDFAnalyzer:
def __init__(self, model_name: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"):
"""
Initialize the PDF analyzer with embedding model and vector store
"""
print("๐ Initializing PDF Analyzer...")
self.embedding_model = SentenceTransformer(model_name)
self.index = None
self.chunks = []
def extract_text_from_pdf(self, pdf_path: str) -> str:
"""
Extract text from PDF using pdfplumber
"""
text = ""
try:
with pdfplumber.open(pdf_path) as pdf:
for page_num, page in enumerate(pdf.pages):
page_text = page.extract_text()
if page_text:
text += f"\n--- Page {page_num + 1} ---\n"
text += page_text
text += "\n"
except Exception as e:
print(f"โ Error extracting text from PDF: {str(e)}")
return ""
return text
def chunk_text(self, text: str, chunk_size: int = 500, overlap: int = 100) -> List[Dict]:
"""
Split text into overlapping chunks for better retrieval
"""
words = text.split()
chunks = []
for i in range(0, len(words), chunk_size - overlap):
chunk_words = words[i:i + chunk_size]
chunk_text = ' '.join(chunk_words)
# Find page number in chunk
page_num = 1
for word in chunk_words:
if "--- Page" in word:
try:
page_num = int(word.split()[2])
except:
pass
chunks.append({
'text': chunk_text,
'chunk_id': len(chunks),
'page': page_num,
'start_word': i,
'end_word': min(i + chunk_size, len(words))
})
return chunks
def create_embeddings(self, chunks: List[Dict]) -> np.ndarray:
"""
Create embeddings for text chunks
"""
texts = [chunk['text'] for chunk in chunks]
print("๐ Creating embeddings...")
embeddings = self.embedding_model.encode(texts, show_progress_bar=True)
return embeddings
def build_vector_store(self, embeddings: np.ndarray):
"""
Build FAISS vector store for similarity search
"""
dimension = embeddings.shape[1]
self.index = faiss.IndexFlatIP(dimension)
# Normalize embeddings for cosine similarity
faiss.normalize_L2(embeddings)
self.index.add(embeddings.astype('float32'))
def process_pdf(self, pdf_path: str, chunk_size: int = 500, overlap: int = 100):
"""
Complete pipeline to process PDF and build vector store
"""
print(f"๐ Processing PDF: {pdf_path}")
text = self.extract_text_from_pdf(pdf_path)
if not text.strip():
print("โ No text could be extracted from the PDF")
return False
print("โ๏ธ Chunking text...")
self.chunks = self.chunk_text(text, chunk_size, overlap)
embeddings = self.create_embeddings(self.chunks)
print("๐๏ธ Building vector store...")
self.build_vector_store(embeddings)
print(f"โ
Successfully processed PDF! Created {len(self.chunks)} chunks.")
return True
def search_similar_chunks(self, query: str, top_k: int = 5) -> List[Dict]:
"""
Search for similar chunks using vector similarity
"""
if self.index is None:
return []
# Encode query
query_embedding = self.embedding_model.encode([query])
faiss.normalize_L2(query_embedding)
# Search
scores, indices = self.index.search(query_embedding.astype('float32'), top_k)
results = []
for score, idx in zip(scores[0], indices[0]):
if idx < len(self.chunks):
result = self.chunks[idx].copy()
result['similarity_score'] = float(score)
results.append(result)
return results
def get_ollama_response(self, query: str, context: str, model_name: str = "llama3.2") -> str:
"""
Get response from local Ollama model
"""
prompt = f"""
Based ONLY on the following context from the PDF document, answer the question.
Do not use any external knowledge or information not present in the context.
If the answer cannot be found in the context, say "ุงูู
ุนููู
ุฉ ุบูุฑ ู
ุชููุฑุฉ ูู ุงููุต ุงูู
ูุฏู
" (Information not available in the provided text).
Context:
{context}
Question: {query}
Answer (in Arabic if the document is in Arabic, otherwise in the same language as the question):
"""
try:
response = ollama.chat(
model=model_name,
messages=[
{
'role': 'user',
'content': prompt
}
]
)
return response['message']['content']
except Exception as e:
return f"Error connecting to Ollama: {str(e)}"
def answer_question(self, question: str, top_k: int = 5, model_name: str = "llama3.2") -> str:
"""
Answer question using RAG pipeline
"""
if self.index is None:
return 'PDF not processed yet.'
print("๐ Searching for relevant content...")
relevant_chunks = self.search_similar_chunks(question, top_k)
if not relevant_chunks:
return 'No relevant information found in the document.'
# Combine context from relevant chunks
context = "\n\n".join([
f"[Page {chunk['page']}]: {chunk['text']}"
for chunk in relevant_chunks
])
print("๐ค Generating answer...")
answer = self.get_ollama_response(question, context, model_name)
return answer
def main():
print("=" * 60)
print("๐ Simple PDF Analyzer with Local Ollama")
print("=" * 60)
# Find PDF file automatically
pdf_files = [f for f in os.listdir(".") if f.endswith(".pdf")]
if not pdf_files:
print("โ No PDF files found in current directory!")
return
# Use the first PDF found (or the Arabic one if available)
pdf_file = None
for f in pdf_files:
if "ุงููุธุงู
" in f or "ุงูุฃุณุงุณู" in f:
pdf_file = f
break
if not pdf_file:
pdf_file = pdf_files[0]
print(f"๐ Found PDF: {pdf_file}")
# Initialize analyzer
analyzer = SimplePDFAnalyzer()
# Process PDF
success = analyzer.process_pdf(pdf_file)
if not success:
print("โ Failed to process PDF. Exiting.")
return
print("\n" + "=" * 60)
print("โ
PDF processed! You can now ask questions.")
print("๐ก Example questions:")
print(" - ู
ุง ูู ู
ูุถูุน ูุฐุง ุงููุธุงู
ุ")
print(" - ุงุฐูุฑ ุฃูู
ุงูู
ูุงุฏ ูู ุงููุธุงู
")
print(" - ู
ุง ูู ุฃุญูุงู
ุงูุญูู
ุ")
print("Type 'quit' or 'exit' to stop.")
print("=" * 60)
# Interactive Q&A loop
while True:
try:
print()
question = input("โ Question: ").strip()
if question.lower() in ['quit', 'exit', 'q', 'ุฎุฑูุฌ']:
print("๐ Goodbye!")
break
if not question:
continue
answer = analyzer.answer_question(question)
print("\n๐ Answer:")
print("-" * 40)
print(answer)
print("-" * 40)
except KeyboardInterrupt:
print("\n๐ Goodbye!")
break
except Exception as e:
print(f"โ Error: {str(e)}")
if __name__ == "__main__":
main()