Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,19 +6,19 @@ import faiss
|
|
| 6 |
import numpy as np
|
| 7 |
import os
|
| 8 |
import time
|
|
|
|
| 9 |
from typing import List, Tuple, Optional
|
| 10 |
|
| 11 |
# Initialize models with error handling
|
| 12 |
try:
|
| 13 |
-
|
|
|
|
| 14 |
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 15 |
-
qa_pipeline = pipeline("question-answering",
|
| 16 |
-
model="distilbert-base-uncased-distilled-squad")
|
| 17 |
except Exception as e:
|
| 18 |
print(f"Error loading models: {e}")
|
| 19 |
raise
|
| 20 |
|
| 21 |
-
|
| 22 |
def extract_text_from_pdf(file_path: str) -> Tuple[str, int, bool]:
|
| 23 |
"""Extract text from PDF with metadata and error handling."""
|
| 24 |
try:
|
|
@@ -39,7 +39,6 @@ def extract_text_from_pdf(file_path: str) -> Tuple[str, int, bool]:
|
|
| 39 |
except Exception as e:
|
| 40 |
return f"Error extracting text: {str(e)}", 0, False
|
| 41 |
|
| 42 |
-
|
| 43 |
def chunk_text(text: str, max_chunk_size: int = 500, overlap: int = 50) -> List[str]:
|
| 44 |
"""Improved text chunking with overlap for better context preservation."""
|
| 45 |
words = text.split()
|
|
@@ -59,7 +58,6 @@ def chunk_text(text: str, max_chunk_size: int = 500, overlap: int = 50) -> List[
|
|
| 59 |
|
| 60 |
return chunks
|
| 61 |
|
| 62 |
-
|
| 63 |
def build_faiss_index(chunks: List[str]) -> Tuple[faiss.IndexFlatL2, np.ndarray]:
|
| 64 |
"""Build FAISS index with error handling."""
|
| 65 |
try:
|
|
@@ -71,20 +69,17 @@ def build_faiss_index(chunks: List[str]) -> Tuple[faiss.IndexFlatL2, np.ndarray]
|
|
| 71 |
except Exception as e:
|
| 72 |
raise Exception(f"Error building FAISS index: {str(e)}")
|
| 73 |
|
| 74 |
-
|
| 75 |
def retrieve_relevant_chunks(query: str, chunks: List[str], index: faiss.IndexFlatL2,
|
| 76 |
embeddings: np.ndarray, top_k: int = 5) -> List[str]:
|
| 77 |
"""Retrieve most relevant chunks for the query."""
|
| 78 |
try:
|
| 79 |
query_embedding = embedding_model.encode([query]).astype('float32')
|
| 80 |
-
distances, indices = index.search(
|
| 81 |
-
query_embedding, min(top_k, len(chunks)))
|
| 82 |
retrieved_chunks = [chunks[i] for i in indices[0] if i < len(chunks)]
|
| 83 |
return retrieved_chunks
|
| 84 |
except Exception as e:
|
| 85 |
return [f"Error retrieving chunks: {str(e)}"]
|
| 86 |
|
| 87 |
-
|
| 88 |
def summarize_pdf(file_path: Optional[str]) -> str:
|
| 89 |
"""Enhanced PDF summarization with progress tracking."""
|
| 90 |
if not file_path:
|
|
@@ -104,9 +99,8 @@ def summarize_pdf(file_path: Optional[str]) -> str:
|
|
| 104 |
try:
|
| 105 |
# Improved chunking for summarization
|
| 106 |
max_chunk = 1000 # Slightly larger chunks for better context
|
| 107 |
-
chunks = [raw_text[i:i+max_chunk]
|
| 108 |
-
|
| 109 |
-
for i in range(0, len(raw_text), max_chunk//2)]
|
| 110 |
|
| 111 |
summary_parts = []
|
| 112 |
total_chunks = len(chunks)
|
|
@@ -116,17 +110,16 @@ def summarize_pdf(file_path: Optional[str]) -> str:
|
|
| 116 |
continue
|
| 117 |
|
| 118 |
try:
|
| 119 |
-
|
| 120 |
max_len = min(150, len(chunk.split()) // 3)
|
| 121 |
min_len = min(30, max_len // 3)
|
| 122 |
|
| 123 |
-
result = summarizer(chunk, max_length=max_len,
|
| 124 |
-
min_length=min_len, do_sample=False)
|
| 125 |
summary_parts.append(result[0]['summary_text'])
|
| 126 |
|
| 127 |
except Exception as chunk_error:
|
| 128 |
-
|
| 129 |
-
|
| 130 |
|
| 131 |
processing_time = time.time() - start_time
|
| 132 |
|
|
@@ -134,8 +127,7 @@ def summarize_pdf(file_path: Optional[str]) -> str:
|
|
| 134 |
final_summary = " ".join(summary_parts)
|
| 135 |
|
| 136 |
# Meta information
|
| 137 |
-
meta_info = f"π Document Summary ({page_count} pages, processed in {processing_time:.1f}s)\n" + \
|
| 138 |
-
"="*60 + "\n\n"
|
| 139 |
|
| 140 |
return meta_info + final_summary
|
| 141 |
else:
|
|
@@ -144,7 +136,6 @@ def summarize_pdf(file_path: Optional[str]) -> str:
|
|
| 144 |
except Exception as e:
|
| 145 |
return f"Error during summarization: {str(e)}"
|
| 146 |
|
| 147 |
-
|
| 148 |
def answer_question(file_path: Optional[str], question: str) -> str:
|
| 149 |
"""Enhanced Q&A with better error handling and context."""
|
| 150 |
if not file_path:
|
|
@@ -167,6 +158,7 @@ def answer_question(file_path: Optional[str], question: str) -> str:
|
|
| 167 |
|
| 168 |
# Create chunks with overlap for better context
|
| 169 |
chunks = chunk_text(raw_text, max_chunk_size=400, overlap=50)
|
|
|
|
| 170 |
|
| 171 |
if not chunks:
|
| 172 |
return "No processable text found in the document."
|
|
@@ -175,8 +167,7 @@ def answer_question(file_path: Optional[str], question: str) -> str:
|
|
| 175 |
index, embeddings = build_faiss_index(chunks)
|
| 176 |
|
| 177 |
# Retrieve relevant chunks
|
| 178 |
-
relevant_chunks = retrieve_relevant_chunks(
|
| 179 |
-
question, chunks, index, embeddings, top_k=5)
|
| 180 |
|
| 181 |
if not relevant_chunks:
|
| 182 |
return "No relevant information found for your question."
|
|
@@ -207,18 +198,12 @@ def answer_question(file_path: Optional[str], question: str) -> str:
|
|
| 207 |
except Exception as e:
|
| 208 |
return f"Error processing question: {str(e)}"
|
| 209 |
|
| 210 |
-
|
| 211 |
-
def clear_inputs():
|
| 212 |
-
"""Helper function to clear inputs."""
|
| 213 |
-
return None, ""
|
| 214 |
-
|
| 215 |
-
|
| 216 |
# Enhanced Gradio UI
|
| 217 |
with gr.Blocks(title="PDF Analyzer", theme=gr.themes.Soft()) as demo:
|
| 218 |
gr.Markdown("""
|
| 219 |
# π Advanced PDF Analyzer
|
| 220 |
Upload a PDF document to generate summaries or ask questions about its content.
|
| 221 |
-
|
| 222 |
**Features:**
|
| 223 |
- π Intelligent text extraction and processing
|
| 224 |
- π AI-powered document summarization
|
|
@@ -237,7 +222,8 @@ with gr.Blocks(title="PDF Analyzer", theme=gr.themes.Soft()) as demo:
|
|
| 237 |
type="filepath"
|
| 238 |
)
|
| 239 |
summarize_button = gr.Button(
|
| 240 |
-
"π Generate Summary", variant="primary"
|
|
|
|
| 241 |
clear_summary_btn = gr.Button("ποΈ Clear", variant="secondary")
|
| 242 |
|
| 243 |
with gr.Column(scale=2):
|
|
@@ -248,6 +234,15 @@ with gr.Blocks(title="PDF Analyzer", theme=gr.themes.Soft()) as demo:
|
|
| 248 |
show_copy_button=True
|
| 249 |
)
|
| 250 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
summarize_button.click(
|
| 252 |
fn=summarize_pdf,
|
| 253 |
inputs=pdf_input,
|
|
@@ -255,8 +250,8 @@ with gr.Blocks(title="PDF Analyzer", theme=gr.themes.Soft()) as demo:
|
|
| 255 |
)
|
| 256 |
|
| 257 |
clear_summary_btn.click(
|
| 258 |
-
fn=lambda: (None, ""),
|
| 259 |
-
outputs=[pdf_input, summary_output]
|
| 260 |
)
|
| 261 |
|
| 262 |
with gr.Tab("β Question & Answer"):
|
|
@@ -265,67 +260,6 @@ with gr.Blocks(title="PDF Analyzer", theme=gr.themes.Soft()) as demo:
|
|
| 265 |
with gr.Row():
|
| 266 |
with gr.Column(scale=1):
|
| 267 |
pdf_input_qa = gr.File(
|
| 268 |
-
label="Upload PDF
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
)
|
| 272 |
-
question_input = gr.Textbox(
|
| 273 |
-
label="Your Question",
|
| 274 |
-
placeholder="e.g., What is the main topic of this document?",
|
| 275 |
-
lines=2
|
| 276 |
-
)
|
| 277 |
-
answer_button = gr.Button("π― Get Answer", variant="primary")
|
| 278 |
-
clear_qa_btn = gr.Button("ποΈ Clear", variant="secondary")
|
| 279 |
-
|
| 280 |
-
with gr.Column(scale=2):
|
| 281 |
-
answer_output = gr.Textbox(
|
| 282 |
-
label="Answer",
|
| 283 |
-
lines=10,
|
| 284 |
-
placeholder="Upload a PDF, enter your question, and click 'Get Answer'...",
|
| 285 |
-
show_copy_button=True
|
| 286 |
-
)
|
| 287 |
-
|
| 288 |
-
# Example questions
|
| 289 |
-
gr.Markdown("**Example questions:**")
|
| 290 |
-
example_questions = [
|
| 291 |
-
"What is the main topic of this document?",
|
| 292 |
-
"Who are the key people mentioned?",
|
| 293 |
-
"What are the main conclusions?",
|
| 294 |
-
"Can you explain the methodology used?"
|
| 295 |
-
]
|
| 296 |
-
|
| 297 |
-
with gr.Row():
|
| 298 |
-
for i, eq in enumerate(example_questions):
|
| 299 |
-
gr.Button(eq, size="sm").click(
|
| 300 |
-
fn=lambda q=eq: q,
|
| 301 |
-
outputs=question_input
|
| 302 |
-
)
|
| 303 |
-
|
| 304 |
-
answer_button.click(
|
| 305 |
-
fn=answer_question,
|
| 306 |
-
inputs=[pdf_input_qa, question_input],
|
| 307 |
-
outputs=answer_output
|
| 308 |
-
)
|
| 309 |
-
|
| 310 |
-
clear_qa_btn.click(
|
| 311 |
-
fn=lambda: (None, "", ""),
|
| 312 |
-
outputs=[pdf_input_qa, question_input, answer_output]
|
| 313 |
-
)
|
| 314 |
-
|
| 315 |
-
# Footer with tips
|
| 316 |
-
gr.Markdown("""
|
| 317 |
-
---
|
| 318 |
-
### π‘ Tips for better results:
|
| 319 |
-
- **For summarization**: Works best with text-heavy documents (research papers, reports, articles)
|
| 320 |
-
- **For Q&A**: Ask specific questions and ensure your PDF contains searchable text
|
| 321 |
-
- **File size**: Larger documents may take longer to process
|
| 322 |
-
- **Quality**: Scanned PDFs without OCR may have limited text extraction
|
| 323 |
-
""")
|
| 324 |
-
|
| 325 |
-
if __name__ == "__main__":
|
| 326 |
-
demo.launch(
|
| 327 |
-
share=False,
|
| 328 |
-
server_name="0.0.0.0",
|
| 329 |
-
server_port=7860,
|
| 330 |
-
show_error=True
|
| 331 |
-
)
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
import os
|
| 8 |
import time
|
| 9 |
+
import torch
|
| 10 |
from typing import List, Tuple, Optional
|
| 11 |
|
| 12 |
# Initialize models with error handling
|
| 13 |
try:
|
| 14 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 15 |
+
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6", device=device)
|
| 16 |
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 17 |
+
qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad", device=device)
|
|
|
|
| 18 |
except Exception as e:
|
| 19 |
print(f"Error loading models: {e}")
|
| 20 |
raise
|
| 21 |
|
|
|
|
| 22 |
def extract_text_from_pdf(file_path: str) -> Tuple[str, int, bool]:
|
| 23 |
"""Extract text from PDF with metadata and error handling."""
|
| 24 |
try:
|
|
|
|
| 39 |
except Exception as e:
|
| 40 |
return f"Error extracting text: {str(e)}", 0, False
|
| 41 |
|
|
|
|
| 42 |
def chunk_text(text: str, max_chunk_size: int = 500, overlap: int = 50) -> List[str]:
|
| 43 |
"""Improved text chunking with overlap for better context preservation."""
|
| 44 |
words = text.split()
|
|
|
|
| 58 |
|
| 59 |
return chunks
|
| 60 |
|
|
|
|
| 61 |
def build_faiss_index(chunks: List[str]) -> Tuple[faiss.IndexFlatL2, np.ndarray]:
|
| 62 |
"""Build FAISS index with error handling."""
|
| 63 |
try:
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
raise Exception(f"Error building FAISS index: {str(e)}")
|
| 71 |
|
|
|
|
| 72 |
def retrieve_relevant_chunks(query: str, chunks: List[str], index: faiss.IndexFlatL2,
|
| 73 |
embeddings: np.ndarray, top_k: int = 5) -> List[str]:
|
| 74 |
"""Retrieve most relevant chunks for the query."""
|
| 75 |
try:
|
| 76 |
query_embedding = embedding_model.encode([query]).astype('float32')
|
| 77 |
+
distances, indices = index.search(query_embedding, min(top_k, len(chunks)))
|
|
|
|
| 78 |
retrieved_chunks = [chunks[i] for i in indices[0] if i < len(chunks)]
|
| 79 |
return retrieved_chunks
|
| 80 |
except Exception as e:
|
| 81 |
return [f"Error retrieving chunks: {str(e)}"]
|
| 82 |
|
|
|
|
| 83 |
def summarize_pdf(file_path: Optional[str]) -> str:
|
| 84 |
"""Enhanced PDF summarization with progress tracking."""
|
| 85 |
if not file_path:
|
|
|
|
| 99 |
try:
|
| 100 |
# Improved chunking for summarization
|
| 101 |
max_chunk = 1000 # Slightly larger chunks for better context
|
| 102 |
+
chunks = [raw_text[i:i+max_chunk] for i in range(0, len(raw_text), max_chunk//2)]
|
| 103 |
+
chunks = chunks[:5] # Limit to first 5 chunks to prevent long processing
|
|
|
|
| 104 |
|
| 105 |
summary_parts = []
|
| 106 |
total_chunks = len(chunks)
|
|
|
|
| 110 |
continue
|
| 111 |
|
| 112 |
try:
|
| 113 |
+
print(f"Summarizing chunk {i+1}/{total_chunks}...")
|
| 114 |
max_len = min(150, len(chunk.split()) // 3)
|
| 115 |
min_len = min(30, max_len // 3)
|
| 116 |
|
| 117 |
+
result = summarizer(chunk, max_length=max_len, min_length=min_len, do_sample=False)
|
|
|
|
| 118 |
summary_parts.append(result[0]['summary_text'])
|
| 119 |
|
| 120 |
except Exception as chunk_error:
|
| 121 |
+
print(f"Error in chunk {i+1}: {str(chunk_error)}")
|
| 122 |
+
summary_parts.append(f"[Error summarizing chunk {i+1}: {str(chunk_error)}]")
|
| 123 |
|
| 124 |
processing_time = time.time() - start_time
|
| 125 |
|
|
|
|
| 127 |
final_summary = " ".join(summary_parts)
|
| 128 |
|
| 129 |
# Meta information
|
| 130 |
+
meta_info = f"π Document Summary ({page_count} pages, processed in {processing_time:.1f}s)\n" + "="*60 + "\n\n"
|
|
|
|
| 131 |
|
| 132 |
return meta_info + final_summary
|
| 133 |
else:
|
|
|
|
| 136 |
except Exception as e:
|
| 137 |
return f"Error during summarization: {str(e)}"
|
| 138 |
|
|
|
|
| 139 |
def answer_question(file_path: Optional[str], question: str) -> str:
|
| 140 |
"""Enhanced Q&A with better error handling and context."""
|
| 141 |
if not file_path:
|
|
|
|
| 158 |
|
| 159 |
# Create chunks with overlap for better context
|
| 160 |
chunks = chunk_text(raw_text, max_chunk_size=400, overlap=50)
|
| 161 |
+
chunks = chunks[:5] # Limit to first 5 chunks to prevent long processing
|
| 162 |
|
| 163 |
if not chunks:
|
| 164 |
return "No processable text found in the document."
|
|
|
|
| 167 |
index, embeddings = build_faiss_index(chunks)
|
| 168 |
|
| 169 |
# Retrieve relevant chunks
|
| 170 |
+
relevant_chunks = retrieve_relevant_chunks(question, chunks, index, embeddings, top_k=5)
|
|
|
|
| 171 |
|
| 172 |
if not relevant_chunks:
|
| 173 |
return "No relevant information found for your question."
|
|
|
|
| 198 |
except Exception as e:
|
| 199 |
return f"Error processing question: {str(e)}"
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
# Enhanced Gradio UI
|
| 202 |
with gr.Blocks(title="PDF Analyzer", theme=gr.themes.Soft()) as demo:
|
| 203 |
gr.Markdown("""
|
| 204 |
# π Advanced PDF Analyzer
|
| 205 |
Upload a PDF document to generate summaries or ask questions about its content.
|
| 206 |
+
|
| 207 |
**Features:**
|
| 208 |
- π Intelligent text extraction and processing
|
| 209 |
- π AI-powered document summarization
|
|
|
|
| 222 |
type="filepath"
|
| 223 |
)
|
| 224 |
summarize_button = gr.Button(
|
| 225 |
+
"π Generate Summary", variant="primary", interactive=False
|
| 226 |
+
)
|
| 227 |
clear_summary_btn = gr.Button("ποΈ Clear", variant="secondary")
|
| 228 |
|
| 229 |
with gr.Column(scale=2):
|
|
|
|
| 234 |
show_copy_button=True
|
| 235 |
)
|
| 236 |
|
| 237 |
+
def enable_summarize_button(file):
|
| 238 |
+
return gr.update(interactive=bool(file))
|
| 239 |
+
|
| 240 |
+
pdf_input.change(
|
| 241 |
+
fn=enable_summarize_button,
|
| 242 |
+
inputs=pdf_input,
|
| 243 |
+
outputs=summarize_button
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
summarize_button.click(
|
| 247 |
fn=summarize_pdf,
|
| 248 |
inputs=pdf_input,
|
|
|
|
| 250 |
)
|
| 251 |
|
| 252 |
clear_summary_btn.click(
|
| 253 |
+
fn=lambda: (None, "", gr.update(interactive=False)),
|
| 254 |
+
outputs=[pdf_input, summary_output, summarize_button]
|
| 255 |
)
|
| 256 |
|
| 257 |
with gr.Tab("β Question & Answer"):
|
|
|
|
| 260 |
with gr.Row():
|
| 261 |
with gr.Column(scale=1):
|
| 262 |
pdf_input_qa = gr.File(
|
| 263 |
+
label="Upload PDF
|
| 264 |
+
::contentReference[oaicite:0]{index=0}
|
| 265 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|