cryogenic22 commited on
Commit
b3d37d9
ยท
verified ยท
1 Parent(s): 221ee7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -149
app.py CHANGED
@@ -1,114 +1,52 @@
1
  import streamlit as st
2
  import backend
3
  from langchain.schema import HumanMessage, AIMessage
4
- import time
5
  from datetime import datetime
6
 
7
- def initialize_session_state():
8
- """Initialize session state variables"""
9
- if 'chat_history' not in st.session_state:
10
- st.session_state.chat_history = []
11
- if 'current_chat' not in st.session_state:
12
- st.session_state.current_chat = False
13
- if 'selected_docs' not in st.session_state:
14
- st.session_state.selected_docs = []
15
- if 'qa_system' not in st.session_state:
16
- st.session_state.qa_system = None
17
- if 'documents_initialized' not in st.session_state:
18
- st.session_state.documents_initialized = False
19
- if 'should_rerun' not in st.session_state:
20
- st.session_state.should_rerun = False
21
- if 'upload_complete' not in st.session_state:
22
- st.session_state.upload_complete = False
 
 
 
23
 
24
  def display_chat_interface():
25
- """Display the chat interface"""
26
  st.markdown("### ๐Ÿ’ฌ RFP Analysis Chat")
27
 
28
  # Display chat history
29
- chat_container = st.container()
30
- with chat_container:
31
- for message in st.session_state.chat_history:
32
- if isinstance(message, HumanMessage):
33
- st.markdown(f"๐Ÿง‘โ€๐Ÿ’ผ **You**: {message.content}")
34
- else:
35
- st.markdown(f"๐Ÿค– **Assistant**: {message.content}")
36
 
37
  # Chat input
38
- user_query = st.text_input(
39
- "Ask about the RFPs:",
40
- placeholder="e.g., What are the key requirements?",
41
- key="chat_input"
42
- )
43
-
44
- if user_query:
45
- # Add user message to chat history
46
- st.session_state.chat_history.append(HumanMessage(content=user_query))
47
-
48
  try:
49
  with st.spinner("Analyzing documents..."):
50
  response = st.session_state.qa_system.invoke({
51
- "input": user_query,
52
  "chat_history": st.session_state.chat_history
53
  })
54
-
55
- # Add AI message to chat history
56
  st.session_state.chat_history.append(AIMessage(content=response["output"]))
57
-
58
- # Force refresh to show new messages
59
- st.rerun()
60
-
61
  except Exception as e:
62
  st.error(f"Error generating response: {e}")
63
 
64
- def display_document_stats(conn):
65
- """Display document statistics"""
66
- try:
67
- cursor = conn.cursor()
68
- cursor.execute("SELECT COUNT(*) FROM documents")
69
- total_documents = cursor.fetchone()[0]
70
-
71
- cursor.execute("SELECT COUNT(*) FROM queries")
72
- total_queries = cursor.fetchone()[0]
73
-
74
- cursor.execute("SELECT COUNT(*) FROM annotations")
75
- total_annotations = cursor.fetchone()[0]
76
-
77
- # Create three columns for metrics
78
- col1, col2, col3 = st.columns(3)
79
-
80
- with col1:
81
- st.metric("๐Ÿ“š Documents", total_documents)
82
- with col2:
83
- st.metric("โ“ Queries", total_queries)
84
- with col3:
85
- st.metric("๐Ÿ“ Annotations", total_annotations)
86
-
87
- except Exception as e:
88
- st.error(f"Error retrieving statistics: {e}")
89
-
90
- def handle_document_upload(conn, uploaded_documents):
91
- """Handle document upload process"""
92
- if uploaded_documents:
93
- with st.spinner(f"Processing {len(uploaded_documents)} documents..."):
94
- all_texts, document_names, document_pages = backend.upload_and_parse_documents(uploaded_documents)
95
-
96
- if all_texts:
97
- try:
98
- with conn:
99
- for doc, doc_name in zip(all_texts, document_names):
100
- conn.execute(
101
- "INSERT INTO documents (name, content) VALUES (?, ?)",
102
- (doc_name, doc)
103
- )
104
- st.success(f"Successfully uploaded {len(uploaded_documents)} documents!", icon="โœ…")
105
- time.sleep(1) # Give users time to see the success message
106
- st.rerun() # Updated from experimental_rerun
107
- except Exception as e:
108
- st.error(f"Error saving documents to database: {e}")
109
-
110
  def display_knowledge_base(conn):
111
- """Display and manage knowledge base"""
112
  st.markdown("### ๐Ÿ“š Knowledge Base")
113
 
114
  if conn is not None:
@@ -120,34 +58,26 @@ def display_knowledge_base(conn):
120
  if documents_in_db:
121
  st.markdown("#### Available Documents")
122
 
123
- # Create a container for the document list
124
- doc_container = st.container()
125
- with doc_container:
126
- for doc_id, name, upload_date in documents_in_db:
127
- col1, col2, col3 = st.columns([3, 2, 1])
 
 
 
 
 
128
 
129
- # Document name and checkbox
130
- with col1:
131
- selected = st.checkbox(
132
- name,
133
- value=doc_id in st.session_state.selected_docs,
134
- key=f"doc_{doc_id}"
135
- )
136
- if selected and doc_id not in st.session_state.selected_docs:
137
- st.session_state.selected_docs.append(doc_id)
138
- elif not selected and doc_id in st.session_state.selected_docs:
139
- st.session_state.selected_docs.remove(doc_id)
140
-
141
- # Upload date
142
- with col2:
143
- upload_date = datetime.strptime(upload_date, '%Y-%m-%d %H:%M:%S')
144
- st.text(upload_date.strftime('%Y-%m-%d %H:%M'))
145
-
146
- # Document actions
147
- with col3:
148
- st.button("๐Ÿ“", key=f"annotate_{doc_id}", help="Add annotations")
149
 
150
- # Initialize selected documents
151
  if st.session_state.selected_docs and not st.session_state.documents_initialized:
152
  with st.spinner("Initializing document analysis..."):
153
  selected_documents = []
@@ -159,10 +89,10 @@ def display_knowledge_base(conn):
159
  (doc_id,)
160
  )
161
  result = cursor.fetchone()
162
- selected_documents.append(result[0])
163
- selected_doc_names.append(result[1])
 
164
 
165
- # Initialize FAISS and QA system
166
  embeddings = backend.get_embeddings_model()
167
  if embeddings:
168
  vector_store = backend.initialize_faiss(
@@ -173,14 +103,11 @@ def display_knowledge_base(conn):
173
  if vector_store:
174
  st.session_state.qa_system = backend.initialize_qa_system(vector_store)
175
  st.session_state.documents_initialized = True
176
- st.success("Documents initialized successfully!")
177
-
178
- # Start Chat button
179
  if st.session_state.selected_docs:
180
- if st.button("๐Ÿš€ Start New Chat", use_container_width=True):
181
- st.session_state.current_chat = True
182
- st.session_state.chat_history = []
183
- st.rerun() # Updated from experimental_rerun
184
  else:
185
  st.info("No documents in the knowledge base. Upload some documents to get started!")
186
 
@@ -188,17 +115,12 @@ def display_knowledge_base(conn):
188
  st.error(f"Error accessing knowledge base: {e}")
189
 
190
  def main():
191
- # Page configuration
192
  st.set_page_config(
193
  page_title="SYNAPTYX - RFP Analysis Agent",
194
  page_icon="๐Ÿค–",
195
  layout="wide"
196
  )
197
 
198
- # Initialize session state
199
- initialize_session_state()
200
-
201
- # Main title and description
202
  st.title("๐Ÿค– SYNAPTYX - RFP Analysis Agent")
203
  st.markdown(
204
  """
@@ -209,7 +131,6 @@ def main():
209
  unsafe_allow_html=True
210
  )
211
 
212
- # Database initialization
213
  database = "rfp_agent.db"
214
  conn = backend.create_connection(database)
215
  if conn is not None:
@@ -218,29 +139,34 @@ def main():
218
  st.error("Error! Cannot create the database connection.")
219
  return
220
 
221
- # Create two columns for layout
222
  col1, col2 = st.columns([1, 2])
223
 
224
  with col1:
225
- # Document upload section
226
  st.markdown("### ๐Ÿ“ค Upload Documents")
227
- uploaded_documents = st.file_uploader(
228
  "Upload PDF documents",
229
  type="pdf",
230
- accept_multiple_files=True,
231
- help="Select one or more PDF files to upload"
232
  )
233
- handle_document_upload(conn, uploaded_documents)
234
 
235
- # Display document statistics
236
- st.markdown("### ๐Ÿ“Š Statistics")
237
- display_document_stats(conn)
 
 
 
 
 
 
 
 
 
 
 
238
 
239
- # Knowledge base management
240
  display_knowledge_base(conn)
241
 
242
  with col2:
243
- # Chat interface
244
  if st.session_state.current_chat and st.session_state.qa_system:
245
  display_chat_interface()
246
  else:
@@ -252,13 +178,6 @@ def main():
252
  1. Upload your RFP documents using the upload section
253
  2. Select the documents you want to analyze from the knowledge base
254
  3. Click "Start New Chat" to begin asking questions
255
-
256
- Features:
257
- - ๐Ÿ“š Document Management
258
- - ๐Ÿ’ฌ Intelligent Chat Interface
259
- - ๐Ÿ“ Document Annotations
260
- - ๐Ÿ“Š Analytics Dashboard
261
- - ๐Ÿ” Advanced Search Capabilities
262
  """
263
  )
264
 
 
1
  import streamlit as st
2
  import backend
3
  from langchain.schema import HumanMessage, AIMessage
 
4
  from datetime import datetime
5
 
6
+ # Initialize session state
7
+ if 'chat_history' not in st.session_state:
8
+ st.session_state.chat_history = []
9
+ if 'current_chat' not in st.session_state:
10
+ st.session_state.current_chat = False
11
+ if 'selected_docs' not in st.session_state:
12
+ st.session_state.selected_docs = []
13
+ if 'qa_system' not in st.session_state:
14
+ st.session_state.qa_system = None
15
+ if 'documents_initialized' not in st.session_state:
16
+ st.session_state.documents_initialized = False
17
+
18
+ def handle_doc_select():
19
+ st.session_state.current_chat = True
20
+ st.session_state.chat_history = []
21
+
22
+ def handle_start_chat():
23
+ st.session_state.current_chat = True
24
+ st.session_state.chat_history = []
25
 
26
  def display_chat_interface():
 
27
  st.markdown("### ๐Ÿ’ฌ RFP Analysis Chat")
28
 
29
  # Display chat history
30
+ for message in st.session_state.chat_history:
31
+ if isinstance(message, HumanMessage):
32
+ st.markdown(f"๐Ÿง‘โ€๐Ÿ’ผ **You**: {message.content}")
33
+ else:
34
+ st.markdown(f"๐Ÿค– **Assistant**: {message.content}")
 
 
35
 
36
  # Chat input
37
+ if prompt := st.chat_input("Ask about the RFPs..."):
38
+ st.session_state.chat_history.append(HumanMessage(content=prompt))
 
 
 
 
 
 
 
 
39
  try:
40
  with st.spinner("Analyzing documents..."):
41
  response = st.session_state.qa_system.invoke({
42
+ "input": prompt,
43
  "chat_history": st.session_state.chat_history
44
  })
 
 
45
  st.session_state.chat_history.append(AIMessage(content=response["output"]))
 
 
 
 
46
  except Exception as e:
47
  st.error(f"Error generating response: {e}")
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  def display_knowledge_base(conn):
 
50
  st.markdown("### ๐Ÿ“š Knowledge Base")
51
 
52
  if conn is not None:
 
58
  if documents_in_db:
59
  st.markdown("#### Available Documents")
60
 
61
+ for doc_id, name, upload_date in documents_in_db:
62
+ col1, col2 = st.columns([3, 1])
63
+
64
+ with col1:
65
+ selected = st.checkbox(
66
+ name,
67
+ value=doc_id in st.session_state.selected_docs,
68
+ key=f"doc_{doc_id}",
69
+ on_change=handle_doc_select
70
+ )
71
 
72
+ if selected and doc_id not in st.session_state.selected_docs:
73
+ st.session_state.selected_docs.append(doc_id)
74
+ elif not selected and doc_id in st.session_state.selected_docs:
75
+ st.session_state.selected_docs.remove(doc_id)
76
+
77
+ with col2:
78
+ upload_date = datetime.strptime(upload_date, '%Y-%m-%d %H:%M:%S')
79
+ st.text(upload_date.strftime('%Y-%m-%d'))
 
 
 
 
 
 
 
 
 
 
 
 
80
 
 
81
  if st.session_state.selected_docs and not st.session_state.documents_initialized:
82
  with st.spinner("Initializing document analysis..."):
83
  selected_documents = []
 
89
  (doc_id,)
90
  )
91
  result = cursor.fetchone()
92
+ if result:
93
+ selected_documents.append(result[0])
94
+ selected_doc_names.append(result[1])
95
 
 
96
  embeddings = backend.get_embeddings_model()
97
  if embeddings:
98
  vector_store = backend.initialize_faiss(
 
103
  if vector_store:
104
  st.session_state.qa_system = backend.initialize_qa_system(vector_store)
105
  st.session_state.documents_initialized = True
106
+
 
 
107
  if st.session_state.selected_docs:
108
+ st.button("๐Ÿš€ Start New Chat",
109
+ on_click=handle_start_chat,
110
+ use_container_width=True)
 
111
  else:
112
  st.info("No documents in the knowledge base. Upload some documents to get started!")
113
 
 
115
  st.error(f"Error accessing knowledge base: {e}")
116
 
117
  def main():
 
118
  st.set_page_config(
119
  page_title="SYNAPTYX - RFP Analysis Agent",
120
  page_icon="๐Ÿค–",
121
  layout="wide"
122
  )
123
 
 
 
 
 
124
  st.title("๐Ÿค– SYNAPTYX - RFP Analysis Agent")
125
  st.markdown(
126
  """
 
131
  unsafe_allow_html=True
132
  )
133
 
 
134
  database = "rfp_agent.db"
135
  conn = backend.create_connection(database)
136
  if conn is not None:
 
139
  st.error("Error! Cannot create the database connection.")
140
  return
141
 
 
142
  col1, col2 = st.columns([1, 2])
143
 
144
  with col1:
 
145
  st.markdown("### ๐Ÿ“ค Upload Documents")
146
+ uploaded_files = st.file_uploader(
147
  "Upload PDF documents",
148
  type="pdf",
149
+ accept_multiple_files=True
 
150
  )
 
151
 
152
+ if uploaded_files:
153
+ with st.spinner("Processing documents..."):
154
+ all_texts, document_names, document_pages = backend.upload_and_parse_documents(uploaded_files)
155
+ if all_texts:
156
+ try:
157
+ with conn:
158
+ for doc, doc_name in zip(all_texts, document_names):
159
+ conn.execute(
160
+ "INSERT INTO documents (name, content) VALUES (?, ?)",
161
+ (doc_name, doc)
162
+ )
163
+ st.success(f"Successfully uploaded {len(uploaded_files)} documents!")
164
+ except Exception as e:
165
+ st.error(f"Error saving documents to database: {e}")
166
 
 
167
  display_knowledge_base(conn)
168
 
169
  with col2:
 
170
  if st.session_state.current_chat and st.session_state.qa_system:
171
  display_chat_interface()
172
  else:
 
178
  1. Upload your RFP documents using the upload section
179
  2. Select the documents you want to analyze from the knowledge base
180
  3. Click "Start New Chat" to begin asking questions
 
 
 
 
 
 
 
181
  """
182
  )
183