cryogenic22 commited on
Commit
19571e2
·
verified ·
1 Parent(s): f256ef6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -175
app.py CHANGED
@@ -1,200 +1,53 @@
 
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
- if 'processed_files' not in st.session_state:
18
- st.session_state.processed_files = set()
19
-
20
- def handle_doc_select():
21
- st.session_state.current_chat = True
22
- st.session_state.chat_history = []
23
-
24
- def handle_start_chat():
25
- st.session_state.current_chat = True
26
- st.session_state.chat_history = []
27
-
28
- def display_chat_interface():
29
- st.markdown("### 💬 RFP Analysis Chat")
30
-
31
- # Display chat history
32
- for message in st.session_state.chat_history:
33
- if isinstance(message, HumanMessage):
34
- st.markdown(f"🧑‍💼 **You**: {message.content}")
35
- else:
36
- st.markdown(f"🤖 **Assistant**: {message.content}")
37
-
38
- # Chat input
39
- if prompt := st.chat_input("Ask about the RFPs..."):
40
- # Add user message to chat history
41
- st.session_state.chat_history.append(HumanMessage(content=prompt))
42
-
43
- try:
44
- with st.spinner("Analyzing documents..."):
45
- # Convert chat history to the format expected by the QA system
46
- formatted_history = []
47
- for msg in st.session_state.chat_history[:-1]: # Exclude the current message
48
- if isinstance(msg, HumanMessage):
49
- formatted_history.append({"role": "user", "content": msg.content})
50
- else:
51
- formatted_history.append({"role": "assistant", "content": msg.content})
52
-
53
- response = st.session_state.qa_system.invoke({
54
- "input": prompt,
55
- "chat_history": formatted_history
56
- })
57
-
58
- # Add AI response to chat history
59
- st.session_state.chat_history.append(AIMessage(content=response["output"]))
60
-
61
- except Exception as e:
62
- st.error(f"Error generating response: {e}")
63
-
64
- def display_knowledge_base(conn):
65
- st.markdown("### 📚 Knowledge Base")
66
-
67
- if conn is not None:
68
- try:
69
- cursor = conn.cursor()
70
- cursor.execute("SELECT id, name, upload_date FROM documents ORDER BY upload_date DESC")
71
- documents_in_db = cursor.fetchall()
72
-
73
- if documents_in_db:
74
- st.markdown("#### Available Documents")
75
-
76
- for doc_id, name, upload_date in documents_in_db:
77
- col1, col2 = st.columns([3, 1])
78
-
79
- with col1:
80
- selected = st.checkbox(
81
- name,
82
- value=doc_id in st.session_state.selected_docs,
83
- key=f"doc_{doc_id}",
84
- on_change=handle_doc_select
85
- )
86
-
87
- if selected and doc_id not in st.session_state.selected_docs:
88
- st.session_state.selected_docs.append(doc_id)
89
- elif not selected and doc_id in st.session_state.selected_docs:
90
- st.session_state.selected_docs.remove(doc_id)
91
-
92
- with col2:
93
- upload_date = datetime.strptime(upload_date, '%Y-%m-%d %H:%M:%S')
94
- st.text(upload_date.strftime('%Y-%m-%d'))
95
-
96
- if st.session_state.selected_docs and not st.session_state.documents_initialized:
97
- with st.spinner("Initializing document analysis..."):
98
- selected_documents = []
99
- selected_doc_names = []
100
-
101
- for doc_id in st.session_state.selected_docs:
102
- cursor.execute(
103
- "SELECT content, name FROM documents WHERE id = ?",
104
- (doc_id,)
105
- )
106
- result = cursor.fetchone()
107
- if result:
108
- selected_documents.append(result[0])
109
- selected_doc_names.append(result[1])
110
-
111
- embeddings = backend.get_embeddings_model()
112
- if embeddings:
113
- vector_store = backend.initialize_faiss(
114
- embeddings,
115
- selected_documents,
116
- selected_doc_names
117
- )
118
- if vector_store:
119
- st.session_state.qa_system = backend.initialize_qa_system(vector_store)
120
- st.session_state.documents_initialized = True
121
-
122
- if st.session_state.selected_docs:
123
- st.button("🚀 Start New Chat",
124
- on_click=handle_start_chat,
125
- use_container_width=True)
126
- else:
127
- st.info("No documents in the knowledge base. Upload some documents to get started!")
128
-
129
- except Exception as e:
130
- st.error(f"Error accessing knowledge base: {e}")
131
 
132
  def main():
 
133
  st.set_page_config(
134
- page_title="SYNAPTYX - RFP Analysis Agent",
135
- page_icon="🤖",
136
- layout="wide"
137
  )
138
 
139
- st.title("🤖 SYNAPTYX - RFP Analysis Agent")
 
 
 
 
140
  st.markdown(
141
- """
142
  <p style='color: #1E3A8A;'>
143
- Upload RFP documents, analyze requirements, and get intelligent answers powered by AI.
144
  </p>
145
  """,
146
  unsafe_allow_html=True
147
  )
148
 
149
- database = "rfp_agent.db"
150
- conn = backend.create_connection(database)
151
- if conn is not None:
152
- backend.create_tables(conn)
153
- else:
154
  st.error("Error! Cannot create the database connection.")
155
  return
156
 
 
 
 
157
  col1, col2 = st.columns([1, 2])
158
 
159
  with col1:
160
- st.markdown("### 📤 Upload Documents")
161
- uploaded_files = st.file_uploader(
162
- "Upload PDF documents",
163
- type="pdf",
164
- accept_multiple_files=True
165
- )
166
-
167
- if uploaded_files:
168
- # Filter out already processed files
169
- new_files = [f for f in uploaded_files if f.name not in st.session_state.processed_files]
170
-
171
- if new_files:
172
- with st.spinner("Processing documents..."):
173
- all_texts, document_names, document_pages = backend.upload_and_parse_documents(new_files)
174
- if all_texts:
175
- try:
176
- with conn:
177
- for doc, doc_name in zip(all_texts, document_names):
178
- # Check if document already exists in database
179
- cursor = conn.cursor()
180
- cursor.execute("SELECT id FROM documents WHERE name = ?", (doc_name,))
181
- existing_doc = cursor.fetchone()
182
-
183
- if not existing_doc:
184
- conn.execute(
185
- "INSERT INTO documents (name, content) VALUES (?, ?)",
186
- (doc_name, doc)
187
- )
188
- # Add to processed files set
189
- st.session_state.processed_files.add(doc_name)
190
-
191
- st.success(f"Successfully uploaded {len(new_files)} new documents!")
192
- except Exception as e:
193
- st.error(f"Error saving documents to database: {e}")
194
-
195
- display_knowledge_base(conn)
196
 
197
  with col2:
 
198
  if st.session_state.current_chat and st.session_state.qa_system:
199
  display_chat_interface()
200
  else:
 
1
+ #src/app.py
2
  import streamlit as st
3
  import backend
4
+ from utils.session_state import initialize_session_state
5
+ from utils.database import get_documents
6
+ from components.chat import display_chat_interface
7
+ from components.knowledge_base import display_knowledge_base
8
+ from components.upload import handle_document_upload
9
+ from config.settings import APP_SETTINGS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  def main():
12
+ # Page configuration
13
  st.set_page_config(
14
+ page_title=APP_SETTINGS['title'],
15
+ page_icon=APP_SETTINGS['icon'],
16
+ layout=APP_SETTINGS['layout']
17
  )
18
 
19
+ # Initialize session state
20
+ initialize_session_state()
21
+
22
+ # Main title and description
23
+ st.title(APP_SETTINGS['title'])
24
  st.markdown(
25
+ f"""
26
  <p style='color: #1E3A8A;'>
27
+ {APP_SETTINGS['description']}
28
  </p>
29
  """,
30
  unsafe_allow_html=True
31
  )
32
 
33
+ # Database initialization
34
+ conn = backend.create_connection(APP_SETTINGS['database'])
35
+ if conn is None:
 
 
36
  st.error("Error! Cannot create the database connection.")
37
  return
38
 
39
+ backend.create_tables(conn)
40
+
41
+ # Create two columns for layout
42
  col1, col2 = st.columns([1, 2])
43
 
44
  with col1:
45
+ # Document upload and knowledge base
46
+ handle_document_upload(conn, backend)
47
+ display_knowledge_base(conn, backend)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  with col2:
50
+ # Chat interface or welcome message
51
  if st.session_state.current_chat and st.session_state.qa_system:
52
  display_chat_interface()
53
  else: