cryogenic22 commited on
Commit
94dc3dd
·
verified ·
1 Parent(s): b5ab699

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -19
app.py CHANGED
@@ -212,33 +212,210 @@ def display_chat_area():
212
  else:
213
  display_chat_interface()
214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  def main():
216
- # Configure the page
217
- st.set_page_config(
218
- layout="wide",
219
- page_title="SYNAPTYX - RFP Analysis Agent",
220
- initial_sidebar_state="expanded"
221
- )
222
-
223
- # Initialize database and session state
224
  if not initialize_database():
225
  st.error("Failed to initialize database. Please contact support.")
226
  return
227
 
228
  initialize_session_state()
229
-
230
- # Display the top navigation bar
231
  display_top_bar()
232
 
233
- # Display the collection sidebar
234
- display_collection_sidebar()
235
-
236
- # Show collection creation dialog if triggered
237
- if st.session_state.get('show_collection_dialog', False):
238
- display_collection_dialog()
239
-
240
- # Main chat area
241
- display_chat_area()
242
 
 
 
 
 
 
 
 
 
243
  if __name__ == "__main__":
244
  main()
 
212
  else:
213
  display_chat_interface()
214
 
215
+ # app.py
216
+
217
+
218
+
219
+ def display_collections_tab():
220
+ """Display the collections management interface."""
221
+ col1, col2 = st.columns([1, 2])
222
+
223
+ with col1:
224
+ st.header("Collections")
225
+
226
+ # New collection button
227
+ if st.button("+ New Collection", use_container_width=True):
228
+ st.session_state.show_collection_dialog = True
229
+
230
+ # Collections list
231
+ collections = get_collections(st.session_state.db_conn)
232
+ for collection in collections:
233
+ collection_button = st.button(
234
+ f"📁 {collection['name']} ({collection['doc_count']})",
235
+ key=f"col_{collection['id']}",
236
+ use_container_width=True
237
+ )
238
+ if collection_button:
239
+ st.session_state.selected_collection = collection
240
+ st.rerun()
241
+
242
+ with col2:
243
+ if st.session_state.get('selected_collection'):
244
+ display_collection_details(st.session_state.selected_collection)
245
+
246
+ def display_collection_details(collection):
247
+ """Display details and documents for a selected collection."""
248
+ st.header(collection['name'])
249
+ st.write(f"Created: {collection['created_at']}")
250
+ st.write(f"Description: {collection.get('description', 'No description')}")
251
+
252
+ # Documents in collection
253
+ st.subheader("Documents")
254
+ documents = get_collection_documents(st.session_state.db_conn, collection['id'])
255
+
256
+ for doc in documents:
257
+ with st.expander(f"📄 {doc['name']}", expanded=False):
258
+ col1, col2 = st.columns([3, 1])
259
+ with col1:
260
+ st.write(f"Uploaded: {doc['upload_date']}")
261
+ st.write(f"Size: {len(doc['content'])/1024:.1f} KB")
262
+ with col2:
263
+ st.button("Preview", key=f"preview_{doc['id']}",
264
+ on_click=lambda: preview_document(doc))
265
+ st.button("Remove", key=f"remove_{doc['id']}",
266
+ on_click=lambda: remove_from_collection(doc['id'], collection['id']))
267
+
268
+ def display_documents_tab():
269
+ """Display all documents with metadata and collection management."""
270
+ st.header("Document Library")
271
+
272
+ # Upload section
273
+ with st.expander("Upload New Documents", expanded=False):
274
+ uploaded_files = st.file_uploader(
275
+ "Upload PDF documents",
276
+ type=['pdf'],
277
+ accept_multiple_files=True,
278
+ help="Limit 200MB per file • PDF"
279
+ )
280
+
281
+ if uploaded_files:
282
+ st.subheader("Add to Collection")
283
+ collections = get_collections(st.session_state.db_conn)
284
+ collection_options = ["Create New Collection"] + [c['name'] for c in collections]
285
+ selected_option = st.selectbox("Select Collection", collection_options)
286
+
287
+ if selected_option == "Create New Collection":
288
+ col1, col2 = st.columns([2, 1])
289
+ with col1:
290
+ new_collection_name = st.text_input("Collection Name")
291
+ new_collection_desc = st.text_area("Description")
292
+ with col2:
293
+ if st.button("Create & Upload") and new_collection_name:
294
+ collection_id = create_collection(
295
+ st.session_state.db_conn,
296
+ new_collection_name,
297
+ new_collection_desc
298
+ )
299
+ if collection_id:
300
+ handle_document_upload(uploaded_files, collection_id=collection_id)
301
+ else:
302
+ if st.button("Upload to Collection"):
303
+ collection_id = next(
304
+ c['id'] for c in collections if c['name'] == selected_option
305
+ )
306
+ handle_document_upload(uploaded_files, collection_id=collection_id)
307
+
308
+ # Document list
309
+ documents = get_all_documents(st.session_state.db_conn)
310
+ for doc in documents:
311
+ with st.expander(f"📄 {doc['name']}", expanded=False):
312
+ col1, col2, col3 = st.columns([2, 1, 1])
313
+
314
+ with col1:
315
+ st.write("**Metadata:**")
316
+ st.write(f"• Upload Date: {doc['upload_date']}")
317
+ st.write(f"• Size: {len(doc['content'])/1024:.1f} KB")
318
+ st.write(f"• Collections: {', '.join(doc['collections'])}")
319
+
320
+ with col2:
321
+ st.write("**Actions:**")
322
+ st.button("Preview", key=f"doc_preview_{doc['id']}")
323
+ collections = get_collections(st.session_state.db_conn)
324
+ collection_options = [c['name'] for c in collections]
325
+ selected_collection = st.selectbox(
326
+ "Add to Collection",
327
+ collection_options,
328
+ key=f"add_to_col_{doc['id']}"
329
+ )
330
+ if st.button("Add", key=f"add_btn_{doc['id']}"):
331
+ collection_id = next(
332
+ c['id'] for c in collections if c['name'] == selected_collection
333
+ )
334
+ add_document_to_collection(
335
+ st.session_state.db_conn,
336
+ doc['id'],
337
+ collection_id
338
+ )
339
+
340
+ with col3:
341
+ st.write("**Preview:**")
342
+ if st.button("Show Content", key=f"show_{doc['id']}"):
343
+ st.text_area("Content Preview",
344
+ doc['content'][:500] + "...",
345
+ height=200)
346
+
347
+ def display_chat_interface_with_sources():
348
+ """Display chat interface with source references."""
349
+ if not st.session_state.chat_ready:
350
+ display_welcome_screen()
351
+ return
352
+
353
+ # Display chat history with sources
354
+ for message in st.session_state.messages:
355
+ if isinstance(message, HumanMessage):
356
+ st.chat_message("user").write(message.content)
357
+ elif isinstance(message, AIMessage):
358
+ with st.chat_message("assistant"):
359
+ st.write(message.content)
360
+ if hasattr(message, 'metadata') and message.metadata.get('sources'):
361
+ st.divider()
362
+ st.caption("**Sources:**")
363
+ for source in message.metadata['sources']:
364
+ st.caption(f"• {source}")
365
+
366
+ # Chat input
367
+ if prompt := st.chat_input("Ask about your documents..."):
368
+ with st.spinner("Analyzing..."):
369
+ sources, response = get_response_with_sources(
370
+ prompt,
371
+ st.session_state.qa_system
372
+ )
373
+
374
+ # Add messages to history with metadata
375
+ human_msg = HumanMessage(content=prompt)
376
+ ai_msg = AIMessage(
377
+ content=response,
378
+ metadata={'sources': sources}
379
+ )
380
+
381
+ st.session_state.messages.extend([human_msg, ai_msg])
382
+ st.rerun()
383
+
384
+ def get_response_with_sources(prompt, qa_system):
385
+ """Get response from QA system with source documents."""
386
+ response = qa_system.invoke({
387
+ "input": prompt,
388
+ "chat_history": st.session_state.messages
389
+ })
390
+
391
+ # Extract sources from the chunks used
392
+ sources = set()
393
+ if hasattr(response, 'metadata'):
394
+ for source in response.metadata.get('source_documents', []):
395
+ sources.add(source.metadata.get('source', 'Unknown source'))
396
+
397
+ return list(sources), response.content
398
+
399
  def main():
400
+ st.set_page_config(layout="wide", page_title="SYNAPTYX - RFP Analysis Agent")
401
+
 
 
 
 
 
 
402
  if not initialize_database():
403
  st.error("Failed to initialize database. Please contact support.")
404
  return
405
 
406
  initialize_session_state()
 
 
407
  display_top_bar()
408
 
409
+ # Main navigation tabs
410
+ tab1, tab2, tab3 = st.tabs(["Chat", "Collections", "Documents"])
 
 
 
 
 
 
 
411
 
412
+ with tab1:
413
+ display_chat_interface_with_sources()
414
+
415
+ with tab2:
416
+ display_collections_tab()
417
+
418
+ with tab3:
419
+ display_documents_tab()
420
  if __name__ == "__main__":
421
  main()