walaa2022 commited on
Commit
e8ab00f
·
verified ·
1 Parent(s): 288a22c

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +811 -0
app.py ADDED
@@ -0,0 +1,811 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ import plotly.graph_objects as go
6
+ from datetime import datetime, timedelta, date
7
+ import requests
8
+ import google.generativeai as genai
9
+
10
+ # Constants
11
+ ENGINEER_SALARY = 10000 # Monthly cost per engineer ($120K/year)
12
+
13
+ # Initialize session state variables
14
+ if 'startups' not in st.session_state:
15
+ st.session_state.startups = {} # Dictionary to store startup data
16
+ if 'current_startup' not in st.session_state:
17
+ st.session_state.current_startup = None # Currently selected startup
18
+ if 'current_page' not in st.session_state:
19
+ st.session_state.current_page = 'upload' # Default page
20
+ if 'insights_cache' not in st.session_state:
21
+ st.session_state.insights_cache = {}
22
+ if 'chat_history' not in st.session_state:
23
+ st.session_state.chat_history = [
24
+ {"role": "assistant", "content": "Hi! I'm your AI financial advisor. How can I help with your startup's finances?"}
25
+ ]
26
+
27
+ # Setup page config and styling
28
+ st.set_page_config(page_title="StartupFinancePilot", page_icon="💰", layout="wide")
29
+
30
+ # Apply custom styling
31
+ st.markdown("""
32
+ <style>
33
+ .main-header {font-size: 2.5rem; color: #0066cc; margin-bottom: 0.5rem;}
34
+ .sub-header {font-size: 1.5rem; color: #5c5c5c; margin-bottom: 1.5rem;}
35
+ .metric-card {background-color: #f8f9fa; border-radius: 10px; padding: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);}
36
+ .metric-label {font-size: 1rem; color: #5c5c5c;}
37
+ .metric-value {font-size: 1.8rem; color: #0066cc; font-weight: bold;}
38
+ .good-metric {color: #28a745;}
39
+ .warning-metric {color: #ffc107;}
40
+ .danger-metric {color: #dc3545;}
41
+ .title-box {background: linear-gradient(45deg, #0066cc, #66b3ff); padding: 20px; border-radius: 10px;
42
+ margin-bottom: 20px; text-align: center; color: white;}
43
+ .ai-badge {display: inline-block; background-color: #0066cc; color: white; border-radius: 4px;
44
+ padding: 2px 6px; font-size: 0.7rem; font-weight: bold; margin-bottom: 8px;}
45
+ .insight-card, .advisor-card {background-color: #f8f9fa; border-radius: 10px; padding: 15px;
46
+ margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);}
47
+ div.stButton > button {width: 100%; padding: 10px; border: none; background-color: #E6F3FF;
48
+ color: #0066cc; border-radius: 10px; text-align: left; font-weight: bold;}
49
+ div.stButton > button:hover {background-color: #CCE5FF; color: #004080;}
50
+ </style>
51
+ """, unsafe_allow_html=True)
52
+
53
+ # AI Integration Functions
54
+ def initialize_gemini():
55
+ """Initialize Google's Gemini AI with API key"""
56
+ try:
57
+ api_key = st.secrets.get("GEMINI_API_KEY", None)
58
+ if api_key:
59
+ genai.configure(api_key=api_key)
60
+ return True
61
+ else:
62
+ st.warning("Gemini API key not found. Using simulated responses.")
63
+ return False
64
+ except Exception as e:
65
+ st.error(f"Failed to initialize Gemini AI: {e}")
66
+ return False
67
+
68
+ def generate_ai_response(prompt, simulate=True):
69
+ """Generate text using Google's Gemini AI"""
70
+ if simulate:
71
+ return "AI response simulation: Based on your financial data, I recommend focusing on extending runway, accelerating revenue growth, and preparing for your next funding round."
72
+ else:
73
+ try:
74
+ model = genai.GenerativeModel('gemini-pro')
75
+ response = model.generate_content(prompt)
76
+ return response.text
77
+ except Exception as e:
78
+ st.error(f"Error generating AI response: {e}")
79
+ return "Sorry, I couldn't generate a response at this time."
80
+
81
+ def generate_voice_response(text, simulate=True):
82
+ """Generate voice response using ElevenLabs API"""
83
+ if simulate:
84
+ return None
85
+ else:
86
+ try:
87
+ api_key = st.secrets.get("ELEVENLABS_API_KEY", None)
88
+ if not api_key:
89
+ return None
90
+
91
+ url = "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM" # Rachel voice
92
+
93
+ headers = {
94
+ "Accept": "audio/mpeg",
95
+ "Content-Type": "application/json",
96
+ "xi-api-key": api_key
97
+ }
98
+
99
+ data = {
100
+ "text": text,
101
+ "model_id": "eleven_monolingual_v1",
102
+ "voice_settings": {
103
+ "stability": 0.5,
104
+ "similarity_boost": 0.5
105
+ }
106
+ }
107
+
108
+ response = requests.post(url, json=data, headers=headers)
109
+
110
+ if response.status_code == 200:
111
+ return response.content
112
+ else:
113
+ st.error(f"Error with ElevenLabs API: {response.status_code}")
114
+ return None
115
+
116
+ except Exception as e:
117
+ st.error(f"Error generating voice response: {e}")
118
+ return None
119
+
120
+ # Utility Functions
121
+ def switch_page(page_name):
122
+ """Function to switch between pages"""
123
+ st.session_state.current_page = page_name
124
+ st.rerun()
125
+
126
+ def calculate_runway(cash, burn_rate, revenue, growth_rate, months=24):
127
+ """Calculate runway based on cash, burn, revenue and growth"""
128
+ current_date = datetime.now()
129
+ date_range = [current_date + timedelta(days=30*i) for i in range(months)]
130
+
131
+ cash_flow = []
132
+ monthly_revenue = revenue
133
+
134
+ for i in range(months):
135
+ net_burn = burn_rate - monthly_revenue
136
+ cash_flow.append(net_burn)
137
+ monthly_revenue *= (1 + growth_rate)
138
+
139
+ df = pd.DataFrame({
140
+ 'Net_Burn': cash_flow,
141
+ 'Cumulative_Cash': [cash - sum(cash_flow[:i+1]) for i in range(len(cash_flow))]
142
+ }, index=date_range)
143
+
144
+ negative_cash = df[df['Cumulative_Cash'] < 0]
145
+ runway_months = (negative_cash.index[0] - current_date).days // 30 if len(negative_cash) > 0 else months
146
+
147
+ return runway_months, df
148
+
149
+ def simulate_decision(cash, burn_rate, revenue, growth_rate,
150
+ additional_expenses, new_hires, marketing_increase, growth_impact):
151
+ """Simulate the financial impact of a business decision"""
152
+ current_runway, current_df = calculate_runway(cash, burn_rate, revenue, growth_rate)
153
+
154
+ new_burn_rate = burn_rate + additional_expenses + (new_hires * ENGINEER_SALARY) + marketing_increase
155
+ new_growth_rate = growth_rate + growth_impact
156
+
157
+ new_runway, new_df = calculate_runway(cash, new_burn_rate, revenue, new_growth_rate)
158
+
159
+ return current_runway, new_runway, current_df, new_df
160
+
161
+ def detect_suspicious_transactions(transactions_df):
162
+ """AI-enhanced suspicious transaction detection"""
163
+ df = transactions_df.copy()
164
+
165
+ # Define thresholds for each category
166
+ category_thresholds = {
167
+ "Travel": 3000, "Marketing": 10000, "Office": 7000,
168
+ "Software": 6000, "Consulting": 5000, "Legal": 6000
169
+ }
170
+
171
+ suspicious_terms = ['luxury', 'cruise', 'premium', 'personal', 'gift']
172
+
173
+ # Add analysis columns
174
+ df['Suspicious'] = False
175
+ df['Reason'] = ""
176
+ df['Risk_Score'] = 0
177
+
178
+ for idx, row in df.iterrows():
179
+ reasons = []
180
+ risk_score = 0
181
+
182
+ # Check category thresholds
183
+ if row['Category'] in category_thresholds and row['Amount'] > category_thresholds[row['Category']]:
184
+ reasons.append(f"Amount exceeds typical spending for {row['Category']}")
185
+ risk_score += 30
186
+
187
+ # Check for suspicious terms
188
+ for field in ['Vendor', 'Description']:
189
+ if any(term in str(row[field]).lower() for term in suspicious_terms):
190
+ reasons.append(f"{field} contains suspicious term")
191
+ risk_score += 20
192
+
193
+ # Check for round amounts
194
+ if row['Amount'] % 1000 == 0 and row['Amount'] > 3000:
195
+ reasons.append(f"Suspiciously round amount")
196
+ risk_score += 15
197
+
198
+ # Mark as suspicious if risk score is high enough
199
+ if risk_score >= 30:
200
+ df.at[idx, 'Suspicious'] = True
201
+ df.at[idx, 'Reason'] = "; ".join(reasons)
202
+ df.at[idx, 'Risk_Score'] = risk_score
203
+
204
+ return df.sort_values(by='Risk_Score', ascending=False)
205
+
206
+ def parse_csv_to_df(file):
207
+ """Parse uploaded CSV file to DataFrame"""
208
+ try:
209
+ df = pd.read_csv(file)
210
+ return df, None
211
+ except Exception as e:
212
+ return None, f"Error parsing CSV: {e}"
213
+
214
+ # Navigation
215
+ def create_sidebar():
216
+ with st.sidebar:
217
+ st.markdown("""
218
+ <div class="title-box">
219
+ <h1>💰 StartupFinancePilot</h1>
220
+ <p>AI-powered financial assistant for startups</p>
221
+ </div>
222
+ """, unsafe_allow_html=True)
223
+
224
+ # Startup selector
225
+ if st.session_state.startups:
226
+ st.subheader("Selected Startup")
227
+ startup_names = list(st.session_state.startups.keys())
228
+ selected_startup = st.selectbox(
229
+ "Choose Startup",
230
+ startup_names,
231
+ index=startup_names.index(st.session_state.current_startup) if st.session_state.current_startup in startup_names else 0
232
+ )
233
+ st.session_state.current_startup = selected_startup
234
+
235
+ # Show basic startup info
236
+ if selected_startup in st.session_state.startups:
237
+ startup_data = st.session_state.startups[selected_startup]['profile']
238
+ st.markdown(f"""
239
+ **Stage:** {startup_data['stage']}
240
+ **Cash:** ${startup_data['cash']:,}
241
+ **Monthly Burn:** ${startup_data['burn_rate']:,}
242
+ **Monthly Revenue:** ${startup_data['revenue']:,}
243
+ """)
244
+
245
+ st.markdown("<hr>", unsafe_allow_html=True)
246
+
247
+ # Navigation buttons
248
+ if st.button("📤 Upload Startup Data", use_container_width=True):
249
+ switch_page('upload')
250
+ if st.button("📊 Financial Dashboard", use_container_width=True):
251
+ switch_page('dashboard')
252
+ if st.button("🔮 Decision Simulator", use_container_width=True):
253
+ switch_page('simulator')
254
+ if st.button("🕵️ Fund Monitoring", use_container_width=True):
255
+ switch_page('monitoring')
256
+ if st.button("🤖 AI Financial Advisor", use_container_width=True):
257
+ switch_page('advisor')
258
+
259
+ # Page Renderers
260
+ def render_upload_page():
261
+ """Render the upload page for startup data"""
262
+ st.markdown("<h1 class='main-header'>Upload Your Startup Data</h1>", unsafe_allow_html=True)
263
+ st.markdown("<p class='sub-header'>Upload CSV files to get started</p>", unsafe_allow_html=True)
264
+
265
+ with st.expander("Upload Instructions", expanded=False):
266
+ st.markdown("""
267
+ ### How to Upload Your Startup Data
268
+
269
+ You can upload three types of files:
270
+
271
+ 1. **Company Profile** - A CSV with basic information about your startup including:
272
+ - name, stage, founded, employees, last_funding, cash, burn_rate, revenue, growth_rate
273
+
274
+ 2. **Cash Flow Data** - A CSV with monthly cash flow data with columns:
275
+ - Month, Revenue, Payroll, Marketing, Office, Software, Travel, Legal, Misc
276
+
277
+ 3. **Transaction Data** - A CSV with transaction details:
278
+ - Date, Category, Vendor, Amount, Description, Flag
279
+ """)
280
+
281
+ startup_name = st.text_input("Startup Name", value="My Startup")
282
+
283
+ col1, col2, col3 = st.columns(3)
284
+
285
+ with col1:
286
+ profile_file = st.file_uploader("Upload Company Profile (CSV)", type=['csv'])
287
+ with col2:
288
+ cash_flow_file = st.file_uploader("Upload Cash Flow Data (CSV)", type=['csv'])
289
+ with col3:
290
+ transactions_file = st.file_uploader("Upload Transactions Data (CSV)", type=['csv'])
291
+
292
+ # Process the files if uploaded
293
+ if st.button("Process Data"):
294
+ # Initialize with default values
295
+ startup_data = {
296
+ "name": startup_name,
297
+ "stage": "Seed",
298
+ "founded": "12 months ago",
299
+ "employees": 5,
300
+ "last_funding": "Not specified",
301
+ "cash": 100000,
302
+ "burn_rate": 20000,
303
+ "revenue": 5000,
304
+ "growth_rate": 0.05
305
+ }
306
+
307
+ cash_flow_df = None
308
+ transactions_df = None
309
+
310
+ # Parse company profile
311
+ if profile_file:
312
+ profile_df, error = parse_csv_to_df(profile_file)
313
+ if error:
314
+ st.error(error)
315
+ elif len(profile_df) > 0:
316
+ startup_data.update(profile_df.iloc[0].to_dict())
317
+ st.success(f"Successfully loaded company profile")
318
+
319
+ # Parse cash flow data
320
+ if cash_flow_file:
321
+ cash_flow_df, error = parse_csv_to_df(cash_flow_file)
322
+ if error:
323
+ st.error(error)
324
+ else:
325
+ if "Total_Expenses" not in cash_flow_df.columns:
326
+ expense_columns = [col for col in cash_flow_df.columns if col not in ["Month", "Revenue", "Total_Expenses", "Net_Burn"]]
327
+ cash_flow_df["Total_Expenses"] = cash_flow_df[expense_columns].sum(axis=1)
328
+
329
+ if "Net_Burn" not in cash_flow_df.columns:
330
+ cash_flow_df["Net_Burn"] = cash_flow_df["Total_Expenses"] - cash_flow_df["Revenue"]
331
+
332
+ st.success("Successfully loaded cash flow data")
333
+
334
+ # Parse transactions data
335
+ if transactions_file:
336
+ transactions_df, error = parse_csv_to_df(transactions_file)
337
+ if error:
338
+ st.error(error)
339
+ else:
340
+ # Ensure transactions data has required columns
341
+ required_columns = ["Date", "Category", "Vendor", "Amount", "Description"]
342
+ if all(col in transactions_df.columns for col in required_columns):
343
+ if "Flag" not in transactions_df.columns:
344
+ transactions_df["Flag"] = "Normal"
345
+ st.success("Successfully loaded transactions data")
346
+ else:
347
+ st.error("Transactions file is missing required columns")
348
+
349
+ # Save to session state if we have at least some data
350
+ if profile_file:
351
+ # Store in session state
352
+ st.session_state.startups[startup_data['name']] = {
353
+ 'profile': startup_data,
354
+ 'cash_flow': cash_flow_df,
355
+ 'transactions': transactions_df
356
+ }
357
+
358
+ # Set as current startup
359
+ st.session_state.current_startup = startup_data['name']
360
+
361
+ st.success(f"Successfully added {startup_data['name']} to your startups")
362
+ switch_page('dashboard')
363
+ else:
364
+ st.error("Please upload at least a company profile file")
365
+
366
+ def render_financial_dashboard():
367
+ """Render the AI-powered financial dashboard page"""
368
+ if not st.session_state.current_startup or st.session_state.current_startup not in st.session_state.startups:
369
+ st.warning("No startup selected. Please upload data first.")
370
+ render_upload_page()
371
+ return
372
+
373
+ # Get the selected startup data
374
+ startup_data = st.session_state.startups[st.session_state.current_startup]['profile']
375
+ cash_flow_df = st.session_state.startups[st.session_state.current_startup]['cash_flow']
376
+
377
+ st.markdown("<h1 class='main-header'>Financial Dashboard</h1>", unsafe_allow_html=True)
378
+
379
+ # AI Insights
380
+ insights_key = f"dashboard_{date.today().isoformat()}"
381
+ if insights_key not in st.session_state.insights_cache:
382
+ insights = generate_ai_response(f"""
383
+ You are a financial advisor for startups. Based on this startup's data:
384
+ - Current cash: ${startup_data['cash']}
385
+ - Monthly burn rate: ${startup_data['burn_rate']}
386
+ - Monthly revenue: ${startup_data['revenue']}
387
+ - Monthly growth rate: {startup_data['growth_rate'] * 100}%
388
+
389
+ Provide the top 3 most important financial insights that the founder should know today.
390
+ Format each insight as a brief, action-oriented bullet point.
391
+ """)
392
+ st.session_state.insights_cache[insights_key] = insights
393
+
394
+ with st.expander("📊 AI Financial Insights", expanded=True):
395
+ st.markdown("<span class='ai-badge'>AI-Generated Insights</span>", unsafe_allow_html=True)
396
+ st.markdown(st.session_state.insights_cache[insights_key])
397
+
398
+ # Key metrics
399
+ col1, col2, col3, col4 = st.columns(4)
400
+
401
+ # Calculate runway
402
+ runway_months, runway_df = calculate_runway(
403
+ startup_data['cash'],
404
+ startup_data['burn_rate'],
405
+ startup_data['revenue'],
406
+ startup_data['growth_rate']
407
+ )
408
+
409
+ # Determine status colors
410
+ runway_status = "danger-metric" if runway_months < 6 else ("warning-metric" if runway_months < 9 else "good-metric")
411
+ burn_status = "danger-metric" if startup_data['burn_rate'] > 100000 else ("warning-metric" if startup_data['burn_rate'] > 80000 else "good-metric")
412
+ revenue_status = "good-metric" if startup_data['revenue'] > 20000 else ("warning-metric" if startup_data['revenue'] > 10000 else "danger-metric")
413
+
414
+ with col1:
415
+ st.markdown(f"""
416
+ <div class='metric-card'>
417
+ <p class='metric-label'>Current Cash</p>
418
+ <p class='metric-value'>${startup_data['cash']:,}</p>
419
+ </div>
420
+ """, unsafe_allow_html=True)
421
+
422
+ with col2:
423
+ st.markdown(f"""
424
+ <div class='metric-card'>
425
+ <p class='metric-label'>Monthly Burn</p>
426
+ <p class='metric-value {burn_status}'>${startup_data['burn_rate']:,}</p>
427
+ </div>
428
+ """, unsafe_allow_html=True)
429
+
430
+ with col3:
431
+ st.markdown(f"""
432
+ <div class='metric-card'>
433
+ <p class='metric-label'>Monthly Revenue</p>
434
+ <p class='metric-value {revenue_status}'>${startup_data['revenue']:,}</p>
435
+ </div>
436
+ """, unsafe_allow_html=True)
437
+
438
+ with col4:
439
+ st.markdown(f"""
440
+ <div class='metric-card'>
441
+ <p class='metric-label'>Runway</p>
442
+ <p class='metric-value {runway_status}'>{runway_months} months</p>
443
+ </div>
444
+ """, unsafe_allow_html=True)
445
+
446
+ # Financial charts
447
+ st.subheader("Financial Overview")
448
+
449
+ # Display only if we have cash flow data
450
+ if cash_flow_df is not None:
451
+ # Runway chart
452
+ fig = px.line(runway_df.reset_index(), x='index', y='Cumulative_Cash',
453
+ title="Cash Runway Projection",
454
+ labels={'index': 'Date', 'Cumulative_Cash': 'Remaining Cash ($)'},
455
+ color_discrete_sequence=['#0066cc'])
456
+ fig.add_hline(y=0, line_dash="dash", line_color="red", annotation_text="Out of Cash")
457
+ fig.update_layout(height=400)
458
+ st.plotly_chart(fig, use_container_width=True)
459
+
460
+ # Revenue vs Expenses
461
+ fig = px.bar(cash_flow_df, x='Month', y=['Revenue', 'Total_Expenses'],
462
+ title="Revenue vs. Expenses",
463
+ barmode='group',
464
+ color_discrete_sequence=['#28a745', '#dc3545'])
465
+ st.plotly_chart(fig, use_container_width=True)
466
+ else:
467
+ st.info("Upload cash flow data to see detailed financial charts")
468
+
469
+ def render_decision_simulator():
470
+ """Render the decision simulator page"""
471
+ if not st.session_state.current_startup or st.session_state.current_startup not in st.session_state.startups:
472
+ st.warning("No startup selected. Please upload data first.")
473
+ render_upload_page()
474
+ return
475
+
476
+ startup_data = st.session_state.startups[st.session_state.current_startup]['profile']
477
+
478
+ st.markdown("<h1 class='main-header'>Decision Simulator</h1>", unsafe_allow_html=True)
479
+ st.markdown("<p class='sub-header'>Test the financial impact of business decisions</p>", unsafe_allow_html=True)
480
+
481
+ # Decision input form
482
+ with st.form("decision_form"):
483
+ st.subheader("Scenario Parameters")
484
+
485
+ col1, col2 = st.columns(2)
486
+
487
+ with col1:
488
+ new_hires = st.number_input("New Engineering Hires", min_value=0, max_value=10, value=0)
489
+ st.caption(f"Monthly Cost: ${new_hires * ENGINEER_SALARY:,}")
490
+
491
+ new_marketing = st.number_input("Additional Monthly Marketing Budget",
492
+ min_value=0, max_value=50000, value=0, step=1000)
493
+
494
+ with col2:
495
+ other_expenses = st.number_input("Other Additional Monthly Expenses",
496
+ min_value=0, max_value=50000, value=0, step=1000)
497
+
498
+ growth_impact = st.slider("Estimated Impact on Monthly Growth Rate",
499
+ min_value=0.0, max_value=0.10, value=0.0, step=0.01,
500
+ format="%.2f")
501
+
502
+ question = st.text_area("Describe your decision scenario", height=100)
503
+
504
+ decision_summary = f"""
505
+ - {new_hires} new engineers: ${new_hires * ENGINEER_SALARY:,}/month
506
+ - Marketing increase: ${new_marketing:,}/month
507
+ - Other expenses: ${other_expenses:,}/month
508
+ - Total additional burn: ${new_hires * ENGINEER_SALARY + new_marketing + other_expenses:,}/month
509
+ - Growth impact: +{growth_impact * 100:.1f}% monthly growth
510
+ """
511
+
512
+ st.markdown(f"**Decision Summary:**\n{decision_summary}")
513
+
514
+ submitted = st.form_submit_button("Simulate Decision")
515
+
516
+ if submitted:
517
+ # Calculate current and new runway
518
+ current_runway, new_runway, current_df, new_df = simulate_decision(
519
+ startup_data['cash'],
520
+ startup_data['burn_rate'],
521
+ startup_data['revenue'],
522
+ startup_data['growth_rate'],
523
+ other_expenses,
524
+ new_hires,
525
+ new_marketing,
526
+ growth_impact
527
+ )
528
+
529
+ # Display results
530
+ st.markdown("<h3>Decision Impact Analysis</h3>", unsafe_allow_html=True)
531
+
532
+ # Summary metrics
533
+ col1, col2, col3 = st.columns(3)
534
+
535
+ with col1:
536
+ st.metric("Current Runway", f"{current_runway} months")
537
+ with col2:
538
+ runway_change = new_runway - current_runway
539
+ st.metric("New Runway", f"{new_runway} months",
540
+ delta=f"{runway_change} months",
541
+ delta_color="off" if runway_change == 0 else ("normal" if runway_change > 0 else "inverse"))
542
+ with col3:
543
+ new_burn = startup_data['burn_rate'] + other_expenses + (new_hires * ENGINEER_SALARY) + new_marketing
544
+ burn_change = new_burn - startup_data['burn_rate']
545
+ burn_percentage = burn_change / startup_data['burn_rate'] * 100
546
+ st.metric("New Monthly Burn", f"${new_burn:,}",
547
+ delta=f"${burn_change:,} ({burn_percentage:.1f}%)",
548
+ delta_color="inverse")
549
+
550
+ # Cash projection comparison
551
+ st.subheader("Cash Projection Comparison")
552
+
553
+ # Combine dataframes for comparison
554
+ current_df['Scenario'] = 'Current'
555
+ new_df['Scenario'] = 'After Decision'
556
+
557
+ combined_df = pd.concat([current_df, new_df])
558
+ combined_df = combined_df.reset_index()
559
+ combined_df = combined_df.rename(columns={'index': 'Date'})
560
+
561
+ # Plot comparison
562
+ fig = px.line(combined_df, x='Date', y='Cumulative_Cash', color='Scenario',
563
+ title="Cash Runway Comparison",
564
+ labels={'Cumulative_Cash': 'Remaining Cash'},
565
+ color_discrete_sequence=['#4c78a8', '#f58518'])
566
+
567
+ fig.add_hline(y=0, line_dash="dash", line_color="red", annotation_text="Out of Cash")
568
+ fig.update_layout(height=400)
569
+
570
+ st.plotly_chart(fig, use_container_width=True)
571
+
572
+ # Get AI analysis
573
+ if question:
574
+ analysis_key = f"decision_analysis_{new_hires}_{new_marketing}_{other_expenses}_{growth_impact}"
575
+ if analysis_key not in st.session_state.insights_cache:
576
+ analysis = generate_ai_response(f"""
577
+ You are a financial advisor for startups. A founder asks:
578
+ "{question}"
579
+
580
+ Here's their current financial situation:
581
+ - Current cash: ${startup_data['cash']}
582
+ - Monthly burn rate: ${startup_data['burn_rate']}
583
+ - Monthly revenue: ${startup_data['revenue']}
584
+ - Monthly growth rate: {startup_data['growth_rate'] * 100}%
585
+
586
+ They're considering these changes:
587
+ - Adding {new_hires} new engineers (${ENGINEER_SALARY}/month each)
588
+ - Increasing marketing budget by ${new_marketing}/month
589
+ - Adding ${other_expenses}/month in other expenses
590
+ - Expecting {growth_impact * 100}% additional monthly growth
591
+
592
+ Analyze this decision thoroughly:
593
+ 1. Quantify the impact on runway
594
+ 2. Assess the risk level (low, medium, high)
595
+ 3. Compare the ROI potential
596
+ 4. Provide recommendations
597
+
598
+ Be direct and specific with numbers and timeframes.
599
+ """)
600
+ st.session_state.insights_cache[analysis_key] = analysis
601
+
602
+ st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
603
+ st.markdown("<span class='ai-badge'>AI Decision Analysis</span>", unsafe_allow_html=True)
604
+ st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[analysis_key]}</p>", unsafe_allow_html=True)
605
+ st.markdown("</div>", unsafe_allow_html=True)
606
+
607
+ def render_fund_monitoring():
608
+ """Render the fund monitoring page"""
609
+ if not st.session_state.current_startup or st.session_state.current_startup not in st.session_state.startups:
610
+ st.warning("No startup selected. Please upload data first.")
611
+ render_upload_page()
612
+ return
613
+
614
+ # Get the selected startup data
615
+ transactions_df = st.session_state.startups[st.session_state.current_startup]['transactions']
616
+
617
+ st.markdown("<h1 class='main-header'>Fund Monitoring</h1>", unsafe_allow_html=True)
618
+ st.markdown("<p class='sub-header'>AI-powered fraud detection and spending analysis</p>", unsafe_allow_html=True)
619
+
620
+ if transactions_df is None:
621
+ st.warning("No transaction data available. Please upload transaction data.")
622
+ return
623
+
624
+ # Process transactions to detect suspicious ones
625
+ processed_df = detect_suspicious_transactions(transactions_df)
626
+
627
+ # Summary metrics
628
+ total_transactions = len(processed_df)
629
+ suspicious_transactions = processed_df[processed_df['Suspicious']].copy()
630
+ suspicious_count = len(suspicious_transactions)
631
+ suspicious_amount = suspicious_transactions['Amount'].sum() if not suspicious_transactions.empty else 0
632
+ total_amount = processed_df['Amount'].sum()
633
+
634
+ col1, col2 = st.columns(2)
635
+
636
+ with col1:
637
+ st.markdown(f"""
638
+ <div class='metric-card'>
639
+ <p class='metric-label'>Total Transactions</p>
640
+ <p class='metric-value'>{total_transactions}</p>
641
+ </div>
642
+ """, unsafe_allow_html=True)
643
+
644
+ with col2:
645
+ flagged_percent = suspicious_count/total_transactions*100 if total_transactions > 0 else 0
646
+ status = "danger-metric" if flagged_percent > 10 else ("warning-metric" if flagged_percent > 5 else "good-metric")
647
+ st.markdown(f"""
648
+ <div class='metric-card'>
649
+ <p class='metric-label'>Flagged Transactions</p>
650
+ <p class='metric-value {status}'>{suspicious_count} ({flagged_percent:.1f}%)</p>
651
+ </div>
652
+ """, unsafe_allow_html=True)
653
+
654
+ # Tabs for different views
655
+ tab1, tab2 = st.tabs(["Flagged Transactions", "All Transactions"])
656
+
657
+ with tab1:
658
+ if suspicious_count > 0:
659
+ st.dataframe(
660
+ suspicious_transactions[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Risk_Score', 'Reason']],
661
+ use_container_width=True
662
+ )
663
+
664
+ # Get AI analysis of suspicious transactions
665
+ fraud_key = f"fraud_{date.today().isoformat()}"
666
+ if fraud_key not in st.session_state.insights_cache:
667
+ suspicious_text = "\n".join([
668
+ f"- {row['Vendor']} (${row['Amount']:.2f}): {row['Description']}"
669
+ for _, row in suspicious_transactions.head(5).iterrows()
670
+ ])
671
+
672
+ fraud_analysis = generate_ai_response(f"""
673
+ You are a financial fraud detection expert. Review these flagged suspicious transactions:
674
+
675
+ {suspicious_text}
676
+
677
+ Provide a brief analysis and recommendations.
678
+ """)
679
+ st.session_state.insights_cache[fraud_key] = fraud_analysis
680
+
681
+ st.markdown("<div class='advisor-card'>", unsafe_allow_html=True)
682
+ st.markdown("<span class='ai-badge'>AI Fraud Analysis</span>", unsafe_allow_html=True)
683
+ st.markdown(f"<p class='advice-text'>{st.session_state.insights_cache[fraud_key]}</p>", unsafe_allow_html=True)
684
+ st.markdown("</div>", unsafe_allow_html=True)
685
+ else:
686
+ st.success("No suspicious transactions detected.")
687
+
688
+ with tab2:
689
+ st.dataframe(processed_df[['Date', 'Category', 'Vendor', 'Amount', 'Description', 'Suspicious', 'Risk_Score']],
690
+ use_container_width=True)
691
+
692
+ # Category spending
693
+ if not processed_df.empty:
694
+ st.subheader("Spending by Category")
695
+ category_spending = processed_df.groupby('Category')['Amount'].sum().reset_index()
696
+
697
+ fig = px.bar(category_spending, x='Category', y='Amount',
698
+ title="Spending by Category",
699
+ color='Amount',
700
+ color_continuous_scale='Blues')
701
+ st.plotly_chart(fig, use_container_width=True)
702
+
703
+ def render_ai_financial_advisor():
704
+ """Render the AI financial advisor page with voice chat"""
705
+ if not st.session_state.current_startup or st.session_state.current_startup not in st.session_state.startups:
706
+ st.warning("No startup selected. Please upload data first.")
707
+ render_upload_page()
708
+ return
709
+
710
+ startup_data = st.session_state.startups[st.session_state.current_startup]['profile']
711
+
712
+ st.markdown("<h1 class='main-header'>AI Financial Advisor</h1>", unsafe_allow_html=True)
713
+
714
+ # Chat container
715
+ st.markdown("<div style='background-color: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;'>", unsafe_allow_html=True)
716
+
717
+ # Display chat history
718
+ for message in st.session_state.chat_history:
719
+ if message["role"] == "user":
720
+ st.markdown(f"<div style='background-color: #e6f7ff; padding: 10px; border-radius: 10px; margin-bottom: 10px;'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
721
+ else:
722
+ st.markdown(f"<div style='background-color: #f0f7ff; padding: 10px; border-radius: 10px; margin-bottom: 10px;'><strong>Financial Advisor:</strong> {message['content']}</div>", unsafe_allow_html=True)
723
+
724
+ # Show play button for voice if it exists
725
+ if 'audio' in message and message['audio']:
726
+ st.audio(message['audio'], format='audio/mp3')
727
+
728
+ # Input for new message
729
+ col1, col2 = st.columns([5, 1])
730
+
731
+ with col1:
732
+ user_input = st.text_input("Ask a financial question", key="user_question")
733
+
734
+ with col2:
735
+ use_voice = st.checkbox("Enable voice", value=True)
736
+
737
+ # Common financial questions
738
+ st.markdown("### Common Questions")
739
+ question_cols = st.columns(3)
740
+
741
+ common_questions = [
742
+ "How much runway do we have?",
743
+ "When should we start fundraising?",
744
+ "How can we optimize our burn rate?"
745
+ ]
746
+
747
+ for i, question in enumerate(common_questions):
748
+ with question_cols[i % 3]:
749
+ if st.button(question, key=f"q_{i}"):
750
+ user_input = question
751
+
752
+ # Process user input
753
+ if user_input:
754
+ # Add user message to chat history
755
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
756
+
757
+ # Get AI response
758
+ response = generate_ai_response(f"""
759
+ You are a strategic financial advisor for startups. A founder asks:
760
+ "{user_input}"
761
+
762
+ Here's their current financial situation:
763
+ - Stage: {startup_data['stage']}
764
+ - Current cash: ${startup_data['cash']}
765
+ - Monthly burn rate: ${startup_data['burn_rate']}
766
+ - Monthly revenue: ${startup_data['revenue']}
767
+ - Monthly growth rate: {startup_data['growth_rate'] * 100}%
768
+ - Last funding: {startup_data['last_funding']}
769
+
770
+ Provide concise, actionable advice.
771
+ """)
772
+
773
+ # Generate voice response if enabled
774
+ audio_data = None
775
+ if use_voice:
776
+ audio_data = generate_voice_response(response)
777
+
778
+ # Add AI response to chat history
779
+ st.session_state.chat_history.append({
780
+ "role": "assistant",
781
+ "content": response,
782
+ "audio": audio_data
783
+ })
784
+
785
+ # Rerun to display updated chat
786
+ st.rerun()
787
+
788
+ st.markdown("</div>", unsafe_allow_html=True)
789
+
790
+ # Main function
791
+ def main():
792
+ # Initialize AI
793
+ initialize_gemini()
794
+
795
+ # Create sidebar navigation
796
+ create_sidebar()
797
+
798
+ # Render the correct page based on session state
799
+ if st.session_state.current_page == 'upload':
800
+ render_upload_page()
801
+ elif st.session_state.current_page == 'dashboard':
802
+ render_financial_dashboard()
803
+ elif st.session_state.current_page == 'simulator':
804
+ render_decision_simulator()
805
+ elif st.session_state.current_page == 'monitoring':
806
+ render_fund_monitoring()
807
+ elif st.session_state.current_page == 'advisor':
808
+ render_ai_financial_advisor()
809
+
810
+ if __name__ == "__main__":
811
+ main()