aaporosh commited on
Commit
60746b2
·
verified ·
1 Parent(s): 7a45022

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -162
app.py CHANGED
@@ -8,13 +8,12 @@ from langchain_community.vectorstores import FAISS
8
  from sentence_transformers import SentenceTransformer
9
  from transformers import pipeline
10
  import re
11
- from collections import defaultdict
12
 
13
- # Setup logging for Hugging Face Spaces
14
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
15
  logger = logging.getLogger(__name__)
16
 
17
- # Lazy load models with Hugging Face compatibility in mind
18
  @st.cache_resource(ttl=1800)
19
  def load_embeddings_model():
20
  logger.info("Loading embeddings model")
@@ -29,8 +28,7 @@ def load_embeddings_model():
29
  def load_qa_pipeline():
30
  logger.info("Loading QA pipeline")
31
  try:
32
- # Using a small but effective model for Spaces resource limits
33
- return pipeline("text2text-generation", model="google/flan-t5-base", max_length=256)
34
  except Exception as e:
35
  logger.error(f"QA model load error: {str(e)}")
36
  st.error(f"QA model error: {str(e)}")
@@ -40,89 +38,67 @@ def load_qa_pipeline():
40
  def load_summary_pipeline():
41
  logger.info("Loading summary pipeline")
42
  try:
43
- return pipeline("summarization", model="sshleifer/distilbart-cnn-12-6", max_length=180)
44
  except Exception as e:
45
  logger.error(f"Summary model load error: {str(e)}")
46
  st.error(f"Summary model error: {str(e)}")
47
  return None
48
 
49
- # Enhanced code extraction: Group by lines, preserve indentation and spaces
50
- def extract_code_from_page(page):
51
- mono_chars = [c for c in page.chars if 'fontname' in c and 'mono' in c['fontname'].lower()]
52
- if not mono_chars:
53
- return ""
54
-
55
- # Group characters by y-coordinate (lines), rounded for precision
56
- lines = defaultdict(list)
57
- for c in mono_chars:
58
- y_key = round(c['y1'], 2) # Use top coordinate
59
- lines[y_key].append(c)
60
-
61
- code_lines = []
62
- # Sort lines top to bottom (PDF y decreases downward)
63
- for y in sorted(lines.keys(), reverse=True):
64
- line_chars = sorted(lines[y], key=lambda c: c['x0'])
65
- line_text = ''
66
- prev_x1 = None
67
- # Calculate average char width for spacing detection
68
- if line_chars:
69
- avg_width = sum(c['width'] for c in line_chars) / len(line_chars)
70
- else:
71
- avg_width = 1
72
- for c in line_chars:
73
- if prev_x1 is not None:
74
- gap = c['x0'] - prev_x1
75
- if gap > avg_width * 0.3: # Threshold for adding spaces
76
- spaces = int(gap / avg_width)
77
- line_text += ' ' * spaces
78
- line_text += c['text']
79
- prev_x1 = c['x1']
80
- code_lines.append(line_text.rstrip()) # Trim trailing spaces but keep leading for indentation
81
-
82
- return '\n'.join(code_lines)
83
-
84
- # Process PDF with improved extraction
85
  def process_pdf(uploaded_file):
86
- logger.info("Processing PDF")
87
  try:
88
- full_text = ""
89
- code_text = ""
90
  with pdfplumber.open(BytesIO(uploaded_file.getvalue())) as pdf:
91
- for page in pdf.pages[:30]: # Increased limit for better coverage, but mindful of resources
92
- # Extract text with layout preservation
93
- extracted_text = page.extract_text(layout=True, x_tolerance=2, y_tolerance=2)
94
- if extracted_text:
95
- full_text += extracted_text + "\n\n"
96
-
97
- # Extract code blocks separately
98
- code_block = extract_code_from_page(page)
99
- if code_block:
100
- code_text += code_block + "\n\n"
101
-
102
- if not full_text:
103
- raise ValueError("No text extracted from PDF. Consider enabling OCR for scanned documents.")
104
-
105
- # Improved splitting: Larger chunks for context, more overlap
106
- text_splitter = CharacterTextSplitter(separator="\n\n", chunk_size=1000, chunk_overlap=200)
107
- text_chunks = text_splitter.split_text(full_text)[:80] # Balanced for performance
108
- code_chunks = text_splitter.split_text(code_text)[:40] if code_text else []
 
 
 
 
 
 
 
 
109
 
110
  embeddings_model = load_embeddings_model()
111
  if not embeddings_model:
112
- return None, None, full_text, code_text
113
-
114
- # Use from_texts for simplicity and compatibility
115
- text_vector_store = FAISS.from_texts(text_chunks, embedding=embeddings_model) if text_chunks else None
116
- code_vector_store = FAISS.from_texts(code_chunks, embedding=embeddings_model) if code_chunks else None
117
-
118
- logger.info("PDF processed successfully")
119
- return text_vector_store, code_vector_store, full_text, code_text
 
 
 
 
 
120
  except Exception as e:
121
  logger.error(f"PDF processing error: {str(e)}")
122
  st.error(f"PDF error: {str(e)}")
123
  return None, None, "", ""
124
 
125
- # Improved summarization: More chunks, better concatenation
126
  def summarize_pdf(text):
127
  logger.info("Generating summary")
128
  try:
@@ -130,116 +106,76 @@ def summarize_pdf(text):
130
  if not summary_pipeline:
131
  return "Summary model unavailable."
132
 
133
- text_splitter = CharacterTextSplitter(separator="\n\n", chunk_size=800, chunk_overlap=100)
134
- chunks = text_splitter.split_text(text)[:4] # Balanced for quality and speed
135
- summaries = [summary_pipeline(chunk, max_length=100, min_length=30, do_sample=False)[0]['summary_text'].strip() for chunk in chunks]
136
 
137
- combined_summary = " ".join(summaries)
138
- if len(combined_summary.split()) > 180:
139
- combined_summary = summary_pipeline(combined_summary, max_length=180, min_length=100, do_sample=False)[0]['summary_text']
140
 
 
 
 
141
  logger.info("Summary generated")
142
- return f"Sure, here's a concise summary of the PDF:\n\n{combined_summary}"
143
  except Exception as e:
144
  logger.error(f"Summary error: {str(e)}")
145
  return f"Oops, something went wrong summarizing: {str(e)}"
146
 
147
- # Improved Q&A: Better context, code handling
148
  def answer_question(text_vector_store, code_vector_store, query):
149
  logger.info(f"Processing query: {query}")
150
  try:
151
  if not text_vector_store and not code_vector_store:
152
- return "Please upload and process a PDF first!"
153
 
154
  qa_pipeline = load_qa_pipeline()
155
  if not qa_pipeline:
156
  return "Sorry, the QA model is unavailable right now."
157
 
158
- is_code_query = any(keyword in query.lower() for keyword in ["code", "script", "function", "programming", "give me code", "show code", "extract code"])
 
 
159
 
160
- vector_store = code_vector_store if is_code_query and code_vector_store else text_vector_store
161
  if not vector_store:
162
  return "No relevant content found for your query."
163
 
164
- docs = vector_store.similarity_search(query, k=4) # Increased for better context
165
- context = "\n\n".join(doc.page_content for doc in docs)
166
- prompt = f"Based on this context: {context}\n\nQuestion: {query}\n\nProvide a friendly, concise answer like a helpful assistant:"
167
- response = qa_pipeline(prompt)[0]['generated_text'].strip()
168
-
169
- if is_code_query:
170
- response = f"Here's the relevant code extracted from the PDF:\n```python
171
-
172
  logger.info("Answer generated")
173
- return f"Got it! Here's the answer:\n\n{response}"
174
  except Exception as e:
175
  logger.error(f"Query error: {str(e)}")
176
  return f"Sorry, something went wrong: {str(e)}"
177
 
178
- # Streamlit UI with improved design for Hugging Face Spaces
179
  try:
180
- st.set_page_config(page_title="Smart PDF Q&A", page_icon="📄", layout="wide", initial_sidebar_state="expanded")
181
-
182
- # Enhanced CSS for modern, dark-theme friendly design (matching the screenshot's dark mode)
183
  st.markdown("""
184
  <style>
185
- /* General styling */
186
- .stApp { background-color: #1e1e1e; color: #ffffff; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
187
- .stSidebar { background-color: #2a2a2a; }
188
- .stButton > button { background-color: #4a90e2; color: white; border: none; border-radius: 6px; padding: 8px 16px; font-weight: bold; }
189
- .stButton > button:hover { background-color: #357abd; }
190
- .stFileUploader { background-color: #333333; border: 1px solid #444444; border-radius: 6px; padding: 10px; }
191
- .stSpinner > div { color: #4a90e2; }
192
- .stSuccess, .stError { border-radius: 6px; padding: 10px; }
193
-
194
- /* Chat messages */
195
- .stChatMessage { border-radius: 12px; padding: 12px; margin: 8px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
196
- .stChatMessage.user { background-color: #3a3a3a; color: #ffffff; }
197
- .stChatMessage.assistant { background-color: #2a2a2a; color: #ffffff; }
198
-
199
- /* Code blocks */
200
- pre { background-color: #252525; color: #d4d4d4; padding: 12px; border-radius: 6px; overflow: auto; font-family: 'Consolas', 'Monaco', monospace; }
201
-
202
- /* Title and markdown */
203
- h1 { color: #ffffff; }
204
- .stMarkdown { color: #d4d4d4; }
205
  </style>
206
  """, unsafe_allow_html=True)
207
 
208
- # Sidebar for controls
209
- with st.sidebar:
210
- st.title("📄 PDF Controls")
211
- st.markdown("Upload your PDF (up to 200MB) and process it.")
212
- uploaded_file = st.file_uploader("Upload a PDF", type=["pdf"], help="Drag and drop or browse to upload.")
213
-
214
- if uploaded_file:
215
- if st.button("Process PDF", key="process_btn"):
216
- with st.spinner("Processing PDF... This may take a moment."):
217
- st.session_state.text_vector_store, st.session_state.code_vector_store, st.session_state.pdf_text, st.session_state.code_text = process_pdf(uploaded_file)
218
- if st.session_state.text_vector_store or st.session_state.code_vector_store:
219
- st.success("PDF processed successfully! You can now ask questions or summarize.")
220
- st.session_state.messages = []
221
- else:
222
- st.error("Failed to process PDF. Please try another file.")
223
-
224
- if "pdf_text" in st.session_state and st.session_state.pdf_text:
225
- if st.button("Summarize PDF", key="summarize_btn"):
226
- with st.spinner("Generating summary..."):
227
- summary = summarize_pdf(st.session_state.pdf_text)
228
- st.session_state.messages.append({"role": "assistant", "content": summary})
229
-
230
- st.markdown("---")
231
- if st.session_state.get("messages"):
232
- chat_text = "\n\n".join(f"**{m['role'].capitalize()}:** {m['content']}" for m in st.session_state.messages)
233
- st.download_button("Download Chat History", chat_text, "chat_history.txt", use_container_width=True)
234
-
235
- # Main content
236
- st.title("Smart PDF Q&A")
237
- st.markdown("""
238
- Upload a PDF using the sidebar to ask questions, get summaries (~180 words), or extract code.
239
- For code, try queries like "give me code for [topic]". Responses are designed to be quick, accurate, and user-friendly!
240
- """)
241
 
242
- # Session state initialization
243
  if "messages" not in st.session_state:
244
  st.session_state.messages = []
245
  if "text_vector_store" not in st.session_state:
@@ -251,26 +187,57 @@ try:
251
  if "code_text" not in st.session_state:
252
  st.session_state.code_text = ""
253
 
254
- # Chat interface
255
- chat_container = st.container()
256
- with chat_container:
257
- for message in st.session_state.messages:
258
- with st.chat_message(message["role"]):
259
- st.markdown(message["content"], unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
 
 
 
261
  if st.session_state.text_vector_store or st.session_state.code_vector_store:
262
- prompt = st.chat_input("Ask a question (e.g., 'What's the main idea?' or 'Give me code for algorithm')")
263
  if prompt:
264
  st.session_state.messages.append({"role": "user", "content": prompt})
265
- with chat_container.chat_message("user"):
266
  st.markdown(prompt)
267
- with chat_container.chat_message("assistant"):
268
- with st.spinner("Thinking..."):
269
  answer = answer_question(st.session_state.text_vector_store, st.session_state.code_vector_store, prompt)
270
  st.markdown(answer, unsafe_allow_html=True)
271
  st.session_state.messages.append({"role": "assistant", "content": answer})
272
- st.rerun() # Rerun to update chat display
 
 
 
 
 
 
 
 
 
 
 
273
 
274
  except Exception as e:
275
  logger.error(f"App initialization failed: {str(e)}")
276
- st.error(f"App failed to start: {str(e)}. Please check the logs or contact support.")
 
8
  from sentence_transformers import SentenceTransformer
9
  from transformers import pipeline
10
  import re
 
11
 
12
+ # Setup logging for Spaces
13
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
14
  logger = logging.getLogger(__name__)
15
 
16
+ # Lazy load models
17
  @st.cache_resource(ttl=1800)
18
  def load_embeddings_model():
19
  logger.info("Loading embeddings model")
 
28
  def load_qa_pipeline():
29
  logger.info("Loading QA pipeline")
30
  try:
31
+ return pipeline("text2text-generation", model="google/flan-t5-small", max_length=300)
 
32
  except Exception as e:
33
  logger.error(f"QA model load error: {str(e)}")
34
  st.error(f"QA model error: {str(e)}")
 
38
  def load_summary_pipeline():
39
  logger.info("Loading summary pipeline")
40
  try:
41
+ return pipeline("summarization", model="sshleifer/distilbart-cnn-6-6", max_length=150)
42
  except Exception as e:
43
  logger.error(f"Summary model load error: {str(e)}")
44
  st.error(f"Summary model error: {str(e)}")
45
  return None
46
 
47
+ # Process PDF with enhanced extraction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def process_pdf(uploaded_file):
49
+ logger.info("Processing PDF with enhanced extraction")
50
  try:
51
+ text = ""
52
+ code_blocks = []
53
  with pdfplumber.open(BytesIO(uploaded_file.getvalue())) as pdf:
54
+ for page in pdf.pages[:20]:
55
+ extracted = page.extract_text(layout=False)
56
+ if extracted:
57
+ text += extracted + "\n"
58
+ for char in page.chars:
59
+ if 'fontname' in char and 'mono' in char['fontname'].lower():
60
+ code_blocks.append(char['text'])
61
+ code_text = page.extract_text()
62
+ code_matches = re.finditer(r'(^\s{2,}.*?(?:\n\s{2,}.*?)*)', code_text, re.MULTILINE)
63
+ for match in code_matches:
64
+ code_blocks.append(match.group().strip())
65
+ tables = page.extract_tables()
66
+ if tables:
67
+ for table in tables:
68
+ text += "\n".join([" | ".join(map(str, row)) for row in table if row]) + "\n"
69
+ for obj in page.extract_words():
70
+ if obj.get('size', 0) > 12:
71
+ text += f"\n{obj['text']}\n"
72
+
73
+ code_text = "\n".join(code_blocks).strip()
74
+ if not text:
75
+ raise ValueError("No text extracted from PDF")
76
+
77
+ text_splitter = CharacterTextSplitter(separator="\n\n", chunk_size=500, chunk_overlap=100, keep_separator=True)
78
+ text_chunks = text_splitter.split_text(text)[:50]
79
+ code_chunks = text_splitter.split_text(code_text)[:25] if code_text else []
80
 
81
  embeddings_model = load_embeddings_model()
82
  if not embeddings_model:
83
+ return None, None, text, code_text
84
+
85
+ text_vector_store = FAISS.from_embeddings(
86
+ zip(text_chunks, [embeddings_model.encode(chunk) for chunk in text_chunks]),
87
+ embeddings_model.encode
88
+ ) if text_chunks else None
89
+ code_vector_store = FAISS.from_embeddings(
90
+ zip(code_chunks, [embeddings_model.encode(chunk) for chunk in code_chunks]),
91
+ embeddings_model.encode
92
+ ) if code_chunks else None
93
+
94
+ logger.info("PDF processed successfully with enhanced extraction")
95
+ return text_vector_store, code_vector_store, text, code_text
96
  except Exception as e:
97
  logger.error(f"PDF processing error: {str(e)}")
98
  st.error(f"PDF error: {str(e)}")
99
  return None, None, "", ""
100
 
101
+ # Summarize PDF
102
  def summarize_pdf(text):
103
  logger.info("Generating summary")
104
  try:
 
106
  if not summary_pipeline:
107
  return "Summary model unavailable."
108
 
109
+ text_splitter = CharacterTextSplitter(separator="\n\n", chunk_size=500, chunk_overlap=50)
110
+ chunks = text_splitter.split_text(text)[:2]
111
+ summaries = []
112
 
113
+ for chunk in chunks:
114
+ summary = summary_pipeline(chunk[:500], max_length=100, min_length=30, do_sample=False)[0]['summary_text']
115
+ summaries.append(summary.strip())
116
 
117
+ combined_summary = " ".join(summaries)
118
+ if len(combined_summary.split()) > 150:
119
+ combined_summary = " ".join(combined_summary.split()[:150])
120
  logger.info("Summary generated")
121
+ return f"Sure, here's a concise summary of the PDF:\n{combined_summary}"
122
  except Exception as e:
123
  logger.error(f"Summary error: {str(e)}")
124
  return f"Oops, something went wrong summarizing: {str(e)}"
125
 
126
+ # Answer question with improved response
127
  def answer_question(text_vector_store, code_vector_store, query):
128
  logger.info(f"Processing query: {query}")
129
  try:
130
  if not text_vector_store and not code_vector_store:
131
+ return "Please upload a PDF first!"
132
 
133
  qa_pipeline = load_qa_pipeline()
134
  if not qa_pipeline:
135
  return "Sorry, the QA model is unavailable right now."
136
 
137
+ is_code_query = any(keyword in query.lower() for keyword in ["code", "script", "function", "programming", "give me code", "show code"])
138
+ if is_code_query and code_vector_store:
139
+ return f"Here's the code from the PDF:\n```python\n{st.session_state.code_text}\n```"
140
 
141
+ vector_store = text_vector_store
142
  if not vector_store:
143
  return "No relevant content found for your query."
144
 
145
+ docs = vector_store.similarity_search(query, k=5) # Increased to 5 for more context
146
+ context = "\n".join(doc.page_content for doc in docs)
147
+ prompt = f"Context: {context}\nQuestion: {query}\nProvide a detailed, accurate answer based on the context, prioritizing relevant information. Respond as a helpful assistant:"
148
+ response = qa_pipeline(prompt)[0]['generated_text']
 
 
 
 
149
  logger.info("Answer generated")
150
+ return f"Got it! Here's a detailed answer:\n{response.strip()}"
151
  except Exception as e:
152
  logger.error(f"Query error: {str(e)}")
153
  return f"Sorry, something went wrong: {str(e)}"
154
 
155
+ # Streamlit UI
156
  try:
157
+ st.set_page_config(page_title="Smart PDF Q&A", page_icon="📄", layout="wide")
 
 
158
  st.markdown("""
159
  <style>
160
+ .main { max-width: 900px; margin: 0 auto; padding: 20px; }
161
+ .sidebar { background-color: #f8f9fa; padding: 10px; border-radius: 5px; }
162
+ .chat-container { border: 1px solid #ddd; border-radius: 10px; padding: 10px; height: 60vh; overflow-y: auto; margin-top: 20px; }
163
+ .stChatMessage { border-radius: 10px; padding: 10px; margin: 5px; max-width: 70%; }
164
+ .user { background-color: #e6f3ff; align-self: flex-end; }
165
+ .assistant { background-color: #f0f0f0; }
166
+ .dark .user { background-color: #2a2a72; color: #fff; }
167
+ .dark .assistant { background-color: #2e2e2e; color: #fff; }
168
+ .stButton>button { background-color: #4CAF50; color: white; border: none; padding: 8px 16px; border-radius: 5px; }
169
+ .stButton>button:hover { background-color: #45a049; }
170
+ pre { background-color: #f8f8f8; padding: 10px; border-radius: 5px; overflow-x: auto; }
171
+ .header { background: linear-gradient(90deg, #4CAF50, #81C784); color: white; padding: 10px; border-radius: 5px; text-align: center; }
 
 
 
 
 
 
 
 
172
  </style>
173
  """, unsafe_allow_html=True)
174
 
175
+ st.markdown('<div class="header"><h1>Smart PDF Q&A</h1></div>', unsafe_allow_html=True)
176
+ st.markdown("Upload a PDF to ask questions, summarize (~150 words), or extract code with 'give me code'. Fast and friendly responses!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
+ # Initialize session state
179
  if "messages" not in st.session_state:
180
  st.session_state.messages = []
181
  if "text_vector_store" not in st.session_state:
 
187
  if "code_text" not in st.session_state:
188
  st.session_state.code_text = ""
189
 
190
+ # Sidebar with toggle
191
+ with st.sidebar:
192
+ st.markdown('<div class="sidebar">', unsafe_allow_html=True)
193
+ theme = st.radio("Theme", ["Light", "Dark"], index=0)
194
+ st.markdown('</div>', unsafe_allow_html=True)
195
+
196
+ # PDF upload and processing
197
+ uploaded_file = st.file_uploader("Upload a PDF", type=["pdf"])
198
+ col1, col2 = st.columns([1, 1])
199
+ with col1:
200
+ if st.button("Process PDF"):
201
+ with st.spinner("Processing PDF..."):
202
+ st.session_state.text_vector_store, st.session_state.code_vector_store, st.session_state.pdf_text, st.session_state.code_text = process_pdf(uploaded_file)
203
+ if st.session_state.text_vector_store or st.session_state.code_vector_store:
204
+ st.success("PDF processed! Ask away or summarize.")
205
+ st.session_state.messages = []
206
+ else:
207
+ st.error("Failed to process PDF.")
208
+ with col2:
209
+ if st.button("Summarize PDF") and st.session_state.pdf_text:
210
+ with st.spinner("Summarizing..."):
211
+ summary = summarize_pdf(st.session_state.pdf_text)
212
+ st.session_state.messages.append({"role": "assistant", "content": summary})
213
+ st.markdown(summary, unsafe_allow_html=True)
214
 
215
+ # Chat interface
216
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
217
  if st.session_state.text_vector_store or st.session_state.code_vector_store:
218
+ prompt = st.chat_input("Ask a question (e.g., 'Give me code' or 'What’s the main idea?'):")
219
  if prompt:
220
  st.session_state.messages.append({"role": "user", "content": prompt})
221
+ with st.chat_message("user"):
222
  st.markdown(prompt)
223
+ with st.chat_message("assistant"):
224
+ with st.spinner('<div class="spinner">⏳</div>'):
225
  answer = answer_question(st.session_state.text_vector_store, st.session_state.code_vector_store, prompt)
226
  st.markdown(answer, unsafe_allow_html=True)
227
  st.session_state.messages.append({"role": "assistant", "content": answer})
228
+
229
+ # Display chat history
230
+ for message in st.session_state.messages:
231
+ with st.chat_message(message["role"]):
232
+ st.markdown(message["content"], unsafe_allow_html=True)
233
+
234
+ st.markdown('</div>', unsafe_allow_html=True)
235
+
236
+ # Download chat history
237
+ if st.session_state.messages:
238
+ chat_text = "\n".join(f"{m['role'].capitalize()}: {m['content']}" for m in st.session_state.messages)
239
+ st.download_button("Download Chat History", chat_text, "chat_history.txt")
240
 
241
  except Exception as e:
242
  logger.error(f"App initialization failed: {str(e)}")
243
+ st.error(f"App failed to start: {str(e)}. Check Spaces logs or contact support.")