cryogenic22 commited on
Commit
b258cb7
·
verified ·
1 Parent(s): 0f519bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -7
app.py CHANGED
@@ -52,7 +52,15 @@ if not os.path.exists('/data'):
52
  except Exception as e:
53
  st.error(f"Setup error: {e}")
54
  st.stop()
55
-
 
 
 
 
 
 
 
 
56
  def verify_database_tables(conn):
57
  """Verify that all required tables exist."""
58
  try:
@@ -128,7 +136,7 @@ def initialize_database():
128
  return False
129
 
130
  def initialize_session_state():
131
- """Initialize all session state variables."""
132
  if 'chat_ready' not in st.session_state:
133
  st.session_state.chat_ready = False
134
  if 'current_collection' not in st.session_state:
@@ -145,6 +153,23 @@ def initialize_session_state():
145
  st.session_state.show_collection_dialog = False
146
  if 'selected_collection' not in st.session_state:
147
  st.session_state.selected_collection = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  def display_top_bar():
150
  """Display the application's top navigation bar."""
@@ -194,6 +219,52 @@ def initialize_chat_from_existing():
194
  st.error(f"Error initializing chat: {e}")
195
  return False
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  def display_collection_sidebar():
198
  """Display the document management sidebar."""
199
  with st.sidebar:
@@ -299,19 +370,46 @@ def display_chat_area():
299
  display_chat_interface()
300
 
301
  def main():
302
- st.set_page_config(layout="wide")
303
 
304
  # Initialize database and session state
305
- initialize_database()
 
 
 
306
  initialize_session_state()
307
 
308
- # Display sidebar
309
- display_collection_sidebar()
 
 
 
 
310
 
311
- # Main content area tabs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  tab1, tab2 = st.tabs(["Chat", "Collections"])
313
 
314
  with tab1:
 
 
 
 
315
  if st.session_state.chat_ready:
316
  display_chat_interface()
317
  else:
@@ -320,6 +418,10 @@ def main():
320
  with tab2:
321
  from components.collection_manager import display_enhanced_collections
322
  display_enhanced_collections()
 
 
 
 
323
 
324
  if __name__ == "__main__":
325
  main()
 
52
  except Exception as e:
53
  st.error(f"Setup error: {e}")
54
  st.stop()
55
+
56
+ def handle_chat_state_change():
57
+ """Handle changes in chat state when switching tabs or collections."""
58
+ if st.session_state.get('chat_ready'):
59
+ # Check if we need to reinitialize with new documents
60
+ if st.session_state.get('reinitialize_chat'):
61
+ initialize_chat_from_collection()
62
+ st.session_state.reinitialize_chat = False
63
+
64
  def verify_database_tables(conn):
65
  """Verify that all required tables exist."""
66
  try:
 
136
  return False
137
 
138
  def initialize_session_state():
139
+ """Initialize all session state variables.
140
  if 'chat_ready' not in st.session_state:
141
  st.session_state.chat_ready = False
142
  if 'current_collection' not in st.session_state:
 
153
  st.session_state.show_collection_dialog = False
154
  if 'selected_collection' not in st.session_state:
155
  st.session_state.selected_collection = None
156
+ """
157
+
158
+ default_states = {
159
+ 'show_collection_dialog': False,
160
+ 'selected_collection': None,
161
+ 'chat_ready': False,
162
+ 'current_collection': None,
163
+ 'vector_store': None,
164
+ 'qa_system': None,
165
+ 'messages': [],
166
+ 'current_chat_id': None,
167
+ 'reinitialize_chat': False
168
+ }
169
+
170
+ for key, default_value in default_states.items():
171
+ if key not in st.session_state:
172
+ st.session_state[key] = default_value
173
 
174
  def display_top_bar():
175
  """Display the application's top navigation bar."""
 
219
  st.error(f"Error initializing chat: {e}")
220
  return False
221
 
222
+ def initialize_chat_from_collection():
223
+ """Initialize chat system from existing collection or documents."""
224
+ try:
225
+ if not st.session_state.chat_ready:
226
+ documents = None
227
+ if st.session_state.get('current_collection'):
228
+ documents = get_collection_documents(st.session_state.db_conn,
229
+ st.session_state.current_collection['id'])
230
+ else:
231
+ documents = get_all_documents(st.session_state.db_conn)
232
+
233
+ if documents:
234
+ embeddings = get_embeddings_model()
235
+ text_splitter = RecursiveCharacterTextSplitter(
236
+ chunk_size=1000,
237
+ chunk_overlap=200,
238
+ length_function=len,
239
+ separators=["\n\n", "\n", " ", ""]
240
+ )
241
+
242
+ # Process documents into chunks
243
+ chunks = []
244
+ for doc in documents:
245
+ doc_chunks = text_splitter.split_text(doc['content'])
246
+ for chunk in doc_chunks:
247
+ chunks.append({
248
+ 'content': chunk,
249
+ 'metadata': {'source': doc['name'], 'document_id': doc['id']}
250
+ })
251
+
252
+ # Initialize vector store
253
+ vector_store = FAISS.from_texts(
254
+ [chunk['content'] for chunk in chunks],
255
+ embeddings,
256
+ [chunk['metadata'] for chunk in chunks]
257
+ )
258
+
259
+ st.session_state.vector_store = vector_store
260
+ st.session_state.qa_system = initialize_qa_system(vector_store)
261
+ st.session_state.chat_ready = True
262
+ return True
263
+ return st.session_state.chat_ready
264
+ except Exception as e:
265
+ st.error(f"Error initializing chat: {e}")
266
+ return False
267
+
268
  def display_collection_sidebar():
269
  """Display the document management sidebar."""
270
  with st.sidebar:
 
370
  display_chat_interface()
371
 
372
  def main():
373
+ st.set_page_config(layout="wide", page_title="SYNAPTYX - RFP Analysis Agent")
374
 
375
  # Initialize database and session state
376
+ if not initialize_database():
377
+ st.error("Failed to initialize database. Please contact support.")
378
+ return
379
+
380
  initialize_session_state()
381
 
382
+ # Top bar with larger logo
383
+ col1, col2, col3 = st.columns([1.5, 4, 1])
384
+ with col1:
385
+ st.image("img/logo.png", width=200) # Increased logo size
386
+ with col2:
387
+ st.title("SYNAPTYX - RFP Analysis Agent")
388
 
389
+ # Sidebar with chat controls
390
+ with st.sidebar:
391
+ st.title("💬 Chat Controls")
392
+
393
+ # New Chat button
394
+ if st.button("🔄 Start New Chat", use_container_width=True):
395
+ st.session_state.messages = []
396
+ st.session_state.current_chat_id = None
397
+ st.rerun()
398
+
399
+ st.divider()
400
+
401
+ # Collection management below
402
+ st.title("📚 Document Manager")
403
+ display_collection_sidebar()
404
+
405
+ # Main content area
406
  tab1, tab2 = st.tabs(["Chat", "Collections"])
407
 
408
  with tab1:
409
+ # Initialize chat if documents exist
410
+ if not st.session_state.chat_ready:
411
+ initialize_chat_from_collection()
412
+
413
  if st.session_state.chat_ready:
414
  display_chat_interface()
415
  else:
 
418
  with tab2:
419
  from components.collection_manager import display_enhanced_collections
420
  display_enhanced_collections()
421
+ # After collection operations, check if we need to reinitialize chat
422
+ if st.session_state.get('reinitialize_chat'):
423
+ initialize_chat_from_collection()
424
+ st.session_state.reinitialize_chat = False
425
 
426
  if __name__ == "__main__":
427
  main()