JanviMl commited on
Commit
1af090e
·
verified ·
1 Parent(s): 3adb913

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +249 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,251 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ import sys
5
+ from typing import Dict, List, Optional
6
+ from datetime import datetime
7
+
8
+ # Add the src directory to Python path for imports
9
+ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
10
+
11
+ # Import our custom modules
12
+ from rag_system import RAGSystem
13
+ from auth_system import AuthSystem
14
+ from document_processor import DocumentProcessor
15
+
16
+ # Page config
17
+ st.set_page_config(
18
+ page_title="FinSolve AI Assistant",
19
+ page_icon="🤖",
20
+ layout="wide",
21
+ initial_sidebar_state="expanded"
22
+ )
23
+
24
+ # Custom CSS
25
+ st.markdown("""
26
+ <style>
27
+ .main-header {
28
+ background: linear-gradient(90deg, #1f4e79 0%, #2d5aa0 100%);
29
+ padding: 1rem;
30
+ border-radius: 10px;
31
+ margin-bottom: 2rem;
32
+ color: white;
33
+ text-align: center;
34
+ }
35
+ .role-badge {
36
+ background-color: #28a745;
37
+ color: white;
38
+ padding: 0.25rem 0.5rem;
39
+ border-radius: 15px;
40
+ font-size: 0.8rem;
41
+ font-weight: bold;
42
+ }
43
+ .chat-message {
44
+ padding: 1rem;
45
+ border-radius: 10px;
46
+ margin-bottom: 1rem;
47
+ border-left: 4px solid #1f4e79;
48
+ background-color: #f8f9fa;
49
+ }
50
+ .source-info {
51
+ background-color: #e9ecef;
52
+ padding: 0.5rem;
53
+ border-radius: 5px;
54
+ margin-top: 0.5rem;
55
+ font-size: 0.8rem;
56
+ color: #6c757d;
57
+ }
58
+ </style>
59
+ """, unsafe_allow_html=True)
60
+
61
+ def initialize_session_state():
62
+ """Initialize session state variables"""
63
+ if 'authenticated' not in st.session_state:
64
+ st.session_state.authenticated = False
65
+ if 'user_role' not in st.session_state:
66
+ st.session_state.user_role = None
67
+ if 'username' not in st.session_state:
68
+ st.session_state.username = None
69
+ if 'chat_history' not in st.session_state:
70
+ st.session_state.chat_history = []
71
+ if 'rag_system' not in st.session_state:
72
+ st.session_state.rag_system = None
73
+
74
+ def login_page():
75
+ """Display login page"""
76
+ st.markdown('<div class="main-header"><h1>🤖 FinSolve AI Assistant</h1><p>Please login to access role-specific insights</p></div>', unsafe_allow_html=True)
77
+
78
+ col1, col2, col3 = st.columns([1, 2, 1])
79
+
80
+ with col2:
81
+ st.subheader("🔐 Login")
82
+
83
+ with st.form("login_form"):
84
+ username = st.text_input("Username", placeholder="Enter your username")
85
+ password = st.text_input("Password", type="password", placeholder="Enter your password")
86
+ submit_button = st.form_submit_button("Login", use_container_width=True)
87
+
88
+ if submit_button:
89
+ auth_system = AuthSystem()
90
+ if auth_system.authenticate(username, password):
91
+ st.session_state.authenticated = True
92
+ st.session_state.username = username
93
+ st.session_state.user_role = auth_system.get_user_role(username)
94
+ st.success(f"Welcome {username}! Your role: {st.session_state.user_role}")
95
+ st.rerun()
96
+ else:
97
+ st.error("Invalid credentials. Please try again.")
98
+
99
+ # Demo credentials info
100
+ st.info("""
101
+ **Demo Credentials:**
102
+ - **Finance**: tony.finance / password123
103
+ - **Marketing**: sarah.marketing / password123
104
+ - **HR**: mike.hr / password123
105
+ - **Engineering**: peter.engineering / password123
106
+ - **C-Level**: ceo.admin / password123
107
+ - **Employee**: john.employee / password123
108
+ """)
109
+
110
+ def main_app():
111
+ """Main application interface"""
112
+ # Initialize RAG system if not done
113
+ if st.session_state.rag_system is None:
114
+ with st.spinner("Initializing AI system..."):
115
+ st.session_state.rag_system = RAGSystem()
116
+ st.session_state.rag_system.initialize_system()
117
+
118
+ # Header
119
+ col1, col2, col3 = st.columns([2, 1, 1])
120
+ with col1:
121
+ st.markdown('<div class="main-header"><h1>🤖 FinSolve AI Assistant</h1></div>', unsafe_allow_html=True)
122
+ with col2:
123
+ st.markdown(f"""
124
+ <div style="text-align: center; margin-top: 1rem;">
125
+ <strong>Welcome, {st.session_state.username}</strong><br>
126
+ <span class="role-badge">{st.session_state.user_role}</span>
127
+ </div>
128
+ """, unsafe_allow_html=True)
129
+ with col3:
130
+ if st.button("Logout", use_container_width=True):
131
+ for key in list(st.session_state.keys()):
132
+ del st.session_state[key]
133
+ st.rerun()
134
+
135
+ # Sidebar with role info and capabilities
136
+ with st.sidebar:
137
+ st.header("📋 Your Access Level")
138
+
139
+ role_permissions = {
140
+ "Finance": ["Financial reports", "Marketing expenses", "Equipment costs", "Reimbursements"],
141
+ "Marketing": ["Campaign performance", "Customer feedback", "Sales metrics"],
142
+ "HR": ["Employee data", "Attendance records", "Payroll", "Performance reviews"],
143
+ "Engineering": ["Technical architecture", "Development processes", "Operational guidelines"],
144
+ "C-Level": ["Full access to all company data"],
145
+ "Employee": ["General company information", "Policies", "Events", "FAQs"]
146
+ }
147
+
148
+ permissions = role_permissions.get(st.session_state.user_role, [])
149
+ for perm in permissions:
150
+ st.markdown(f"✅ {perm}")
151
+
152
+ st.markdown("---")
153
+ st.header("💡 Sample Questions")
154
+
155
+ sample_questions = {
156
+ "Finance": [
157
+ "What was our Q4 2024 revenue?",
158
+ "Show me marketing expenses breakdown",
159
+ "What are the major cost drivers?"
160
+ ],
161
+ "Marketing": [
162
+ "How did our Q4 campaigns perform?",
163
+ "What was our customer acquisition cost?",
164
+ "Show me ROI for digital marketing"
165
+ ],
166
+ "HR": [
167
+ "How many employees do we have?",
168
+ "What are the leave policies?",
169
+ "Show me attendance statistics"
170
+ ],
171
+ "Engineering": [
172
+ "What is our system architecture?",
173
+ "What technologies do we use?",
174
+ "Show me our deployment process"
175
+ ],
176
+ "C-Level": [
177
+ "Give me a company overview",
178
+ "What are our growth metrics?",
179
+ "Show me all department performance"
180
+ ],
181
+ "Employee": [
182
+ "What are the company policies?",
183
+ "How do I apply for leave?",
184
+ "What benefits do we have?"
185
+ ]
186
+ }
187
+
188
+ questions = sample_questions.get(st.session_state.user_role, [])
189
+ for q in questions:
190
+ if st.button(q, key=f"sample_{q}", use_container_width=True):
191
+ st.session_state.current_query = q
192
+
193
+ # Main chat interface
194
+ st.header("💬 Ask Me Anything")
195
+
196
+ # Display chat history
197
+ for i, (query, response, sources) in enumerate(st.session_state.chat_history):
198
+ st.markdown(f"""
199
+ <div class="chat-message">
200
+ <strong>You:</strong> {query}
201
+ </div>
202
+ """, unsafe_allow_html=True)
203
+
204
+ st.markdown(f"""
205
+ <div class="chat-message">
206
+ <strong>AI Assistant:</strong> {response}
207
+ {f'<div class="source-info"><strong>Sources:</strong> {", ".join(sources)}</div>' if sources else ""}
208
+ </div>
209
+ """, unsafe_allow_html=True)
210
+
211
+ # Query input
212
+ query = st.text_input("Ask your question:",
213
+ value=st.session_state.get('current_query', ''),
214
+ placeholder="Type your question here...",
215
+ key="query_input")
216
+
217
+ col1, col2 = st.columns([1, 4])
218
+ with col1:
219
+ ask_button = st.button("Ask", use_container_width=True)
220
+
221
+ if ask_button and query:
222
+ with st.spinner("Thinking..."):
223
+ try:
224
+ response, sources = st.session_state.rag_system.query(
225
+ query,
226
+ st.session_state.user_role
227
+ )
228
+
229
+ # Add to chat history
230
+ st.session_state.chat_history.append((query, response, sources))
231
+
232
+ # Clear the current query
233
+ if 'current_query' in st.session_state:
234
+ del st.session_state.current_query
235
+
236
+ st.rerun()
237
+
238
+ except Exception as e:
239
+ st.error(f"Error processing query: {str(e)}")
240
+
241
+ def main():
242
+ """Main application entry point"""
243
+ initialize_session_state()
244
+
245
+ if not st.session_state.authenticated:
246
+ login_page()
247
+ else:
248
+ main_app()
249
 
250
+ if __name__ == "__main__":
251
+ main()