-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_analyzer.py
More file actions
387 lines (322 loc) Β· 13.7 KB
/
Copy pathpdf_analyzer.py
File metadata and controls
387 lines (322 loc) Β· 13.7 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import pdfplumber
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer
import ollama
import pickle
import os
from typing import List, Dict, Tuple
import streamlit as st
import tempfile
class PDFAnalyzer:
def __init__(self, model_name: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"):
"""
Initialize the PDF analyzer with embedding model and vector store
"""
self.embedding_model = SentenceTransformer(model_name)
self.index = None
self.chunks = []
self.metadata = []
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:
st.error(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]
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) # Inner product for cosine similarity
# 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
"""
st.info("Extracting text from PDF...")
text = self.extract_text_from_pdf(pdf_path)
if not text.strip():
st.error("No text could be extracted from the PDF")
return False
st.info("Chunking text...")
self.chunks = self.chunk_text(text, chunk_size, overlap)
st.info("Creating embeddings...")
embeddings = self.create_embeddings(self.chunks)
st.info("Building vector store...")
self.build_vector_store(embeddings)
st.success(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") -> Dict:
"""
Answer question using RAG pipeline
"""
if self.index is None:
return {
'answer': 'PDF not processed yet. Please upload and process a PDF first.',
'sources': [],
'context': ''
}
# Search for relevant chunks
relevant_chunks = self.search_similar_chunks(question, top_k)
if not relevant_chunks:
return {
'answer': 'No relevant information found in the document.',
'sources': [],
'context': ''
}
# Combine context from relevant chunks
context = "\n\n".join([
f"[Page {chunk['page']}]: {chunk['text']}"
for chunk in relevant_chunks
])
# Get answer from Ollama
answer = self.get_ollama_response(question, context, model_name)
return {
'answer': answer,
'sources': relevant_chunks,
'context': context
}
def save_index(self, filepath: str):
"""
Save the vector index and chunks to disk
"""
if self.index is not None:
faiss.write_index(self.index, f"{filepath}.faiss")
with open(f"{filepath}.pkl", 'wb') as f:
pickle.dump({
'chunks': self.chunks,
'metadata': self.metadata
}, f)
def load_index(self, filepath: str):
"""
Load the vector index and chunks from disk
"""
try:
self.index = faiss.read_index(f"{filepath}.faiss")
with open(f"{filepath}.pkl", 'rb') as f:
data = pickle.load(f)
self.chunks = data['chunks']
self.metadata = data['metadata']
return True
except Exception as e:
st.error(f"Error loading index: {str(e)}")
return False
def main():
st.set_page_config(
page_title="PDF Analyzer with Local Ollama",
page_icon="π",
layout="wide"
)
st.title("π PDF Analyzer with Local Ollama")
st.markdown("Upload a PDF and ask questions about its content using your local Ollama installation.")
# Initialize the analyzer
if 'analyzer' not in st.session_state:
st.session_state.analyzer = PDFAnalyzer()
# Sidebar for configuration
with st.sidebar:
st.header("Configuration")
# Ollama model selection
model_name = st.text_input(
"Ollama Model Name",
value="llama3.2",
help="Make sure this model is installed in your local Ollama"
)
# Chunk size configuration
chunk_size = st.slider("Chunk Size", 200, 1000, 500)
overlap = st.slider("Chunk Overlap", 50, 200, 100)
top_k = st.slider("Number of relevant chunks to retrieve", 3, 10, 5)
# Test Ollama connection
if st.button("Test Ollama Connection"):
try:
response = ollama.chat(
model=model_name,
messages=[{'role': 'user', 'content': 'Hello'}]
)
st.success("β
Ollama connection successful!")
except Exception as e:
st.error(f"β Ollama connection failed: {str(e)}")
# Main content area
col1, col2 = st.columns([1, 1])
with col1:
st.header("π PDF Selection")
# Check for existing PDFs in workspace
workspace_pdfs = [f for f in os.listdir(".") if f.endswith(".pdf")]
if workspace_pdfs:
st.subheader("π Available PDFs in Workspace")
selected_pdf = st.selectbox(
"Select a PDF from workspace:",
workspace_pdfs,
help="PDFs found in your current workspace"
)
if selected_pdf:
pdf_path = os.path.abspath(selected_pdf)
st.success(f"Selected: {selected_pdf}")
if st.button("Process Selected PDF", type="primary"):
with st.spinner("Processing PDF..."):
success = st.session_state.analyzer.process_pdf(
pdf_path,
chunk_size=chunk_size,
overlap=overlap
)
if success:
st.session_state.pdf_processed = True
st.session_state.current_pdf = selected_pdf
st.subheader("π€ Or Upload New PDF")
uploaded_file = st.file_uploader(
"Choose a PDF file",
type="pdf",
help="Upload a different PDF document to analyze"
)
if uploaded_file is not None:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(uploaded_file.getvalue())
tmp_path = tmp_file.name
st.success(f"File uploaded: {uploaded_file.name}")
if st.button("Process Uploaded PDF", type="primary"):
with st.spinner("Processing PDF..."):
success = st.session_state.analyzer.process_pdf(
tmp_path,
chunk_size=chunk_size,
overlap=overlap
)
# Clean up temporary file
os.unlink(tmp_path)
if success:
st.session_state.pdf_processed = True
st.session_state.current_pdf = uploaded_file.name
with col2:
st.header("β Ask Questions")
if hasattr(st.session_state, 'pdf_processed') and st.session_state.pdf_processed:
# Show current PDF being analyzed
if hasattr(st.session_state, 'current_pdf'):
st.info(f"π Currently analyzing: **{st.session_state.current_pdf}**")
# Question input
question = st.text_area(
"Enter your question about the PDF:",
height=100,
placeholder="Ω
Ψ§ ΩΩ Ω
ΩΨΆΩΨΉ ΩΨ°Ψ§ Ψ§ΩΩΨΈΨ§Ω
Ψ (What is the subject of this system?)"
)
if st.button("Get Answer", type="primary") and question:
with st.spinner("Searching and generating answer..."):
result = st.session_state.analyzer.answer_question(
question,
top_k=top_k,
model_name=model_name
)
# Display answer
st.subheader("π Answer")
st.write(result['answer'])
# Display sources
if result['sources']:
st.subheader("π Sources")
for i, source in enumerate(result['sources']):
with st.expander(f"Source {i+1} (Page {source['page']}) - Similarity: {source['similarity_score']:.3f}"):
st.text(source['text'][:500] + "..." if len(source['text']) > 500 else source['text'])
else:
st.info("Please upload and process a PDF first to start asking questions.")
# Chat history section
st.header("π¬ Chat History")
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Display chat history
for i, (q, a) in enumerate(st.session_state.chat_history):
with st.expander(f"Q{i+1}: {q[:50]}..."):
st.write(f"**Question:** {q}")
st.write(f"**Answer:** {a}")
# Add current Q&A to history
if 'question' in locals() and 'result' in locals() and question:
if (question, result['answer']) not in st.session_state.chat_history:
st.session_state.chat_history.append((question, result['answer']))
if __name__ == "__main__":
main()