cryogenic22 commited on
Commit
065bacc
Β·
verified Β·
1 Parent(s): cb88b52

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -108
app.py CHANGED
@@ -5,44 +5,124 @@ import os
5
  from pathlib import Path
6
  from components.chat import display_chat_interface
7
  from utils.database import (
8
- display_vector_store_info,
9
- handle_document_upload,
10
  create_connection,
11
  create_tables,
12
- get_collections
 
 
 
 
 
 
 
 
13
  )
14
  import time
15
  from threading import Lock
16
 
17
- # Create a lock for database operations
18
  conn_lock = Lock()
 
19
 
20
  def initialize_database():
21
- """Initialize database connection and tables."""
22
- # [Previous initialize_database code remains the same]
23
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- def display_sidebar():
26
- """Display the document management sidebar."""
27
  with st.sidebar:
28
  st.title("πŸ“š Document Manager")
 
 
 
 
29
 
 
 
 
 
30
  # Collection selector
31
- st.subheader("Select Collection")
32
- collections = get_collections()
33
- collection_names = ["All Documents"] + [c['name'] for c in collections]
34
  selected_collection = st.selectbox(
35
- "Working Collection",
36
- collection_names,
37
  index=0,
38
  key="collection_selector"
39
  )
40
-
41
- # Update session state
42
- st.session_state.current_collection = selected_collection if selected_collection != "All Documents" else None
43
-
 
 
 
 
 
 
44
  # Upload Section
45
- st.header("Upload Documents", anchor=False)
46
  uploaded_files = st.file_uploader(
47
  "Upload PDF documents",
48
  type=['pdf'],
@@ -50,115 +130,112 @@ def display_sidebar():
50
  help="Limit 200MB per file β€’ PDF"
51
  )
52
 
53
- # Process uploads
54
  if uploaded_files:
55
- if 'processed_files' not in st.session_state or uploaded_files != st.session_state.processed_files:
56
  with st.spinner("Processing documents..."):
57
- # Get collection ID if a collection is selected
58
- collection_id = None
59
- if st.session_state.current_collection:
60
- collection_id = next(
61
- (c['id'] for c in collections if c['name'] == st.session_state.current_collection),
62
- None
63
- )
64
-
65
- handle_document_upload(uploaded_files, collection_id)
66
- st.session_state.processed_files = uploaded_files
67
- st.session_state.chat_ready = True
68
- time.sleep(1)
69
- st.rerun()
70
-
71
- # Knowledge Base Status
72
- if st.session_state.get('vector_store'):
73
- st.success("βœ… Documents ready for analysis")
74
- display_vector_store_info()
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- # Document List
77
- if uploaded_files:
78
- st.subheader("πŸ“‘ Uploaded Documents")
79
- for doc in uploaded_files:
80
- st.write(f"β€’ {doc.name}")
81
-
82
- def display_top_navigation():
83
- """Display the top navigation bar."""
84
- with st.container():
85
- cols = st.columns([1, 3, 1])
86
- with cols[0]:
87
- if os.path.exists("img/logo.png"):
88
- st.image("img/logo.png", width=100)
89
- else:
90
- st.error("Logo not found")
91
 
92
- with cols[1]:
93
- st.title("Synaptyx.AI - RFP Analysis Agent")
 
 
 
 
 
 
 
 
94
 
95
- with cols[2]:
96
- if st.session_state.get('current_collection'):
97
- st.write(f"πŸ“ Collection: {st.session_state.current_collection}")
98
-
99
- def display_welcome_screen():
100
- """Display the welcome screen for new users."""
101
- st.title("πŸ€– SYNAPTYX - RFP Analysis Agent")
102
- st.markdown("### Welcome to your AI-powered RFP analysis assistant!")
103
-
104
- col1, col2 = st.columns(2)
105
- with col1:
106
- st.markdown("""
107
- #### Getting Started:
108
- 1. Upload your RFP documents using the sidebar
109
- 2. Wait for the processing to complete
110
- 3. Start chatting with your documents!
111
- """)
112
-
113
- with col2:
114
- st.markdown("#### Example Questions:")
115
- examples = [
116
- "πŸ“Š Summarize the main points of the document",
117
- "πŸ“ Draft a 'Why Us' section based on the document",
118
- "🎯 Extract key success metrics and outcomes",
119
- "πŸ’‘ What are the innovative solutions mentioned?",
120
- "🀝 Analyze the partnership benefits described"
121
- ]
122
- for example in examples:
123
- st.markdown(f"β€’ {example}")
124
 
125
  def main():
126
- # Set up the page configuration
127
  st.set_page_config(
128
  layout="wide",
129
  page_title="SYNAPTYX - RFP Analysis Agent",
130
  initial_sidebar_state="expanded"
131
  )
132
 
133
- # Initialize database
134
  if not initialize_database():
135
  st.error("Failed to initialize database. Please contact support.")
136
  return
137
 
138
- # Initialize session state
139
- if 'chat_ready' not in st.session_state:
140
- st.session_state.chat_ready = False
141
- if 'current_collection' not in st.session_state:
142
- st.session_state.current_collection = None
143
 
144
- # Display sidebar (maintain existing functionality)
145
- display_sidebar()
146
 
147
- # Main content area
148
- display_top_navigation()
149
 
150
- # Tabs for different sections
151
- tab1, tab2 = st.tabs(["Chat", "Document Store"])
152
-
153
- with tab1:
154
- if not st.session_state.chat_ready:
155
- display_welcome_screen()
156
- else:
157
- display_chat_interface()
158
-
159
- with tab2:
160
- from pages.document_store import display_document_store
161
- display_document_store()
162
 
163
  if __name__ == "__main__":
164
  main()
 
5
  from pathlib import Path
6
  from components.chat import display_chat_interface
7
  from utils.database import (
 
 
8
  create_connection,
9
  create_tables,
10
+ handle_document_upload,
11
+ verify_vector_store
12
+ )
13
+ from utils.collections import (
14
+ create_collection_tables,
15
+ get_collections,
16
+ get_collection_documents,
17
+ create_collection,
18
+ add_document_to_collection
19
  )
20
  import time
21
  from threading import Lock
22
 
23
+ # Create locks for thread-safe operations
24
  conn_lock = Lock()
25
+ vectorstore_lock = Lock()
26
 
27
  def initialize_database():
28
+ """Initialize database connection and create necessary tables."""
29
+ try:
30
+ with conn_lock:
31
+ if 'db_conn' not in st.session_state:
32
+ data_dir = "data"
33
+ if not os.path.exists(data_dir):
34
+ os.makedirs(data_dir)
35
+
36
+ db_path = os.path.join(data_dir, 'rfp_analysis.db')
37
+
38
+ try:
39
+ with open(db_path, 'a') as f:
40
+ pass
41
+ except IOError as e:
42
+ st.error(f"Failed to access database: {e}")
43
+ return False
44
+
45
+ conn = create_connection(db_path)
46
+
47
+ if conn is not None:
48
+ # Create base tables
49
+ create_tables(conn)
50
+ # Create collection-specific tables
51
+ create_collection_tables(conn)
52
+ st.session_state.db_conn = conn
53
+ return True
54
+ else:
55
+ return False
56
+ else:
57
+ return True
58
+
59
+ except Exception as e:
60
+ st.error(f"Database initialization error: {e}")
61
+ return False
62
+
63
+ def initialize_session_state():
64
+ """Initialize all session state variables."""
65
+ if 'chat_ready' not in st.session_state:
66
+ st.session_state.chat_ready = False
67
+ if 'current_collection' not in st.session_state:
68
+ st.session_state.current_collection = None
69
+ if 'processed_files' not in st.session_state:
70
+ st.session_state.processed_files = []
71
+ if 'show_upload_dialog' not in st.session_state:
72
+ st.session_state.show_upload_dialog = False
73
+ if 'vector_stores' not in st.session_state:
74
+ st.session_state.vector_stores = {}
75
+
76
+ def display_top_bar():
77
+ """Display the application's top navigation bar."""
78
+ col1, col2, col3 = st.columns([1, 3, 1])
79
+
80
+ with col1:
81
+ if os.path.exists("img/logo.png"):
82
+ st.image("img/logo.png", width=100)
83
+ else:
84
+ st.warning("Logo not found at img/logo.png")
85
+
86
+ with col2:
87
+ st.title("Synaptyx.AI - RFP Analysis Agent")
88
+
89
+ with col3:
90
+ if st.session_state.current_collection:
91
+ st.info(f"πŸ“ Active Collection: {st.session_state.current_collection['name']}")
92
 
93
+ def display_collection_sidebar():
94
+ """Display the collection management sidebar."""
95
  with st.sidebar:
96
  st.title("πŸ“š Document Manager")
97
+
98
+ # Collection Selection
99
+ st.header("Collections")
100
+ collections = get_collections(st.session_state.db_conn)
101
 
102
+ # Create New Collection button
103
+ if st.button("βž• Create New Collection"):
104
+ st.session_state.show_collection_dialog = True
105
+
106
  # Collection selector
107
+ collection_options = ["All Documents"] + [c['name'] for c in collections]
 
 
108
  selected_collection = st.selectbox(
109
+ "Select Collection",
110
+ collection_options,
111
  index=0,
112
  key="collection_selector"
113
  )
114
+
115
+ # Update current collection in session state
116
+ if selected_collection != "All Documents":
117
+ st.session_state.current_collection = next(
118
+ (c for c in collections if c['name'] == selected_collection),
119
+ None
120
+ )
121
+ else:
122
+ st.session_state.current_collection = None
123
+
124
  # Upload Section
125
+ st.header("Upload Documents")
126
  uploaded_files = st.file_uploader(
127
  "Upload PDF documents",
128
  type=['pdf'],
 
130
  help="Limit 200MB per file β€’ PDF"
131
  )
132
 
 
133
  if uploaded_files:
134
+ if st.button("Process Documents"):
135
  with st.spinner("Processing documents..."):
136
+ collection_id = st.session_state.current_collection['id'] if st.session_state.current_collection else None
137
+ success = handle_document_upload(uploaded_files, collection_id)
138
+ if success:
139
+ st.success("Documents processed successfully!")
140
+ st.session_state.chat_ready = True
141
+ st.rerun()
142
+
143
+ # Display current collection info
144
+ if st.session_state.current_collection:
145
+ st.header("Collection Info")
146
+ collection = st.session_state.current_collection
147
+ documents = get_collection_documents(st.session_state.db_conn, collection['id'])
148
+
149
+ st.markdown(f"""
150
+ **Collection:** {collection['name']}
151
+ **Documents:** {len(documents)}
152
+ **Created:** {collection['created_at']}
153
+ """)
154
+
155
+ if documents:
156
+ st.subheader("Documents in Collection")
157
+ for doc in documents:
158
+ st.write(f"πŸ“„ {doc['name']}")
159
+
160
+ def display_collection_dialog():
161
+ """Display the create collection dialog."""
162
+ with st.sidebar:
163
+ st.subheader("Create New Collection")
164
+ name = st.text_input("Collection Name")
165
+ description = st.text_area("Description")
166
 
167
+ col1, col2 = st.columns(2)
168
+ with col1:
169
+ if st.button("Create"):
170
+ if name:
171
+ if create_collection(st.session_state.db_conn, name, description):
172
+ st.success(f"Collection '{name}' created!")
173
+ st.session_state.show_collection_dialog = False
174
+ st.rerun()
175
+ else:
176
+ st.error("Please enter a collection name")
 
 
 
 
 
177
 
178
+ with col2:
179
+ if st.button("Cancel"):
180
+ st.session_state.show_collection_dialog = False
181
+ st.rerun()
182
+
183
+ def display_chat_area():
184
+ """Display the main chat interface."""
185
+ if not st.session_state.chat_ready:
186
+ st.title("πŸ€– Welcome to SYNAPTYX")
187
+ st.markdown("### Your AI-powered RFP Analysis Assistant")
188
 
189
+ col1, col2 = st.columns(2)
190
+ with col1:
191
+ st.markdown("""
192
+ #### Getting Started:
193
+ 1. Select or create a collection in the sidebar
194
+ 2. Upload your RFP documents
195
+ 3. Start analyzing with AI!
196
+ """)
197
+
198
+ with col2:
199
+ st.markdown("#### Example Questions:")
200
+ examples = [
201
+ "πŸ“Š Summarize the main points of the document",
202
+ "πŸ“ Draft a 'Why Us' section based on the document",
203
+ "🎯 Extract key success metrics and outcomes",
204
+ "πŸ’‘ What are the innovative solutions mentioned?",
205
+ "🀝 Analyze the partnership benefits described"
206
+ ]
207
+ for example in examples:
208
+ st.markdown(f"β€’ {example}")
209
+ else:
210
+ display_chat_interface()
 
 
 
 
 
 
 
211
 
212
  def main():
213
+ # Configure the page
214
  st.set_page_config(
215
  layout="wide",
216
  page_title="SYNAPTYX - RFP Analysis Agent",
217
  initial_sidebar_state="expanded"
218
  )
219
 
220
+ # Initialize database and session state
221
  if not initialize_database():
222
  st.error("Failed to initialize database. Please contact support.")
223
  return
224
 
225
+ initialize_session_state()
 
 
 
 
226
 
227
+ # Display the top navigation bar
228
+ display_top_bar()
229
 
230
+ # Display the collection sidebar
231
+ display_collection_sidebar()
232
 
233
+ # Show collection creation dialog if triggered
234
+ if st.session_state.get('show_collection_dialog', False):
235
+ display_collection_dialog()
236
+
237
+ # Main chat area
238
+ display_chat_area()
 
 
 
 
 
 
239
 
240
  if __name__ == "__main__":
241
  main()