Pranav0111 commited on
Commit
db489fb
Β·
verified Β·
1 Parent(s): af686c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -138
app.py CHANGED
@@ -5,9 +5,35 @@ import pandas as pd
5
  import numpy as np
6
  from datetime import datetime, timedelta
7
  from typing import Dict, List, Any
8
- from render_ai_assistant import render_ai_assistant
9
 
10
- # --- Data Processing Class ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  class DataProcessor:
12
  def __init__(self):
13
  self.data = None
@@ -135,110 +161,121 @@ class BrainstormManager:
135
  steps.append("Prepare enterprise sales strategy")
136
  return steps
137
 
138
- # --- Sample Data Generation ---
139
  def generate_sample_data():
140
  dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
141
- return pd.DataFrame({
142
  'Date': dates,
143
  'Revenue': np.random.normal(1000, 100, len(dates)),
144
  'Users': np.random.randint(100, 200, len(dates)),
145
  'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
146
- 'Category': np.random.choice(['A', 'B', 'C'], len(dates))
147
  })
 
 
 
 
 
 
148
 
149
- # --- Page Rendering Functions ---
150
  def render_dashboard():
151
- st.header("πŸ“Š Comprehensive Business Performance Dashboard")
152
 
153
- # Generate sample data with more complex structure
154
  data = generate_sample_data()
155
- data['Profit_Margin'] = data['Revenue'] * np.random.uniform(0.1, 0.3, len(data))
156
 
157
- # Top-level KPI Section
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  col1, col2, col3, col4 = st.columns(4)
159
  with col1:
160
  st.metric("Total Revenue",
161
- f"${data['Revenue'].sum():,.2f}",
162
- delta=f"{data['Revenue'].pct_change().mean()*100:.2f}%")
163
  with col2:
164
  st.metric("Total Users",
165
- f"{data['Users'].sum():,}",
166
- delta=f"{data['Users'].pct_change().mean()*100:.2f}%")
167
  with col3:
168
  st.metric("Avg Engagement",
169
- f"{data['Engagement'].mean():.2%}",
170
- delta=f"{data['Engagement'].pct_change().mean()*100:.2f}%")
171
  with col4:
172
- st.metric("Profit Margin",
173
- f"{data['Profit_Margin'].mean():.2%}",
174
- delta=f"{data['Profit_Margin'].pct_change().mean()*100:.2f}%")
175
 
176
- # Visualization Grid
177
  col1, col2 = st.columns(2)
178
 
179
  with col1:
180
- st.subheader("Revenue & Profit Trends")
181
- fig_revenue = go.Figure()
182
- fig_revenue.add_trace(go.Scatter(
183
- x=data['Date'],
184
- y=data['Revenue'],
185
  mode='lines',
186
- name='Revenue',
187
  line=dict(color='blue')
188
  ))
189
- fig_revenue.add_trace(go.Scatter(
190
- x=data['Date'],
191
- y=data['Profit_Margin'],
192
  mode='lines',
193
- name='Profit Margin',
194
- line=dict(color='green')
195
  ))
196
- fig_revenue.update_layout(height=350)
197
- st.plotly_chart(fig_revenue, use_container_width=True)
198
 
199
  with col2:
200
- st.subheader("User Engagement Analysis")
201
- fig_engagement = px.scatter(
202
- data,
203
- x='Users',
204
- y='Engagement',
205
- color='Category',
206
- size='Revenue',
207
- hover_data=['Date'],
208
- title='User Engagement Dynamics'
 
 
 
 
 
209
  )
210
- fig_engagement.update_layout(height=350)
211
- st.plotly_chart(fig_engagement, use_container_width=True)
212
-
213
- # Category Performance
214
- st.subheader("Category Performance Breakdown")
215
- category_performance = data.groupby('Category').agg({
216
- 'Revenue': 'sum',
217
- 'Users': 'sum',
218
- 'Engagement': 'mean'
219
- }).reset_index()
220
-
221
- fig_category = px.bar(
222
- category_performance,
223
- x='Category',
224
- y='Revenue',
225
- color='Engagement',
226
- title='Revenue by Category with Engagement Overlay'
227
- )
228
- st.plotly_chart(fig_category, use_container_width=True)
229
 
230
- # Bottom Summary
231
- st.subheader("Quick Insights")
232
- insights_col1, insights_col2 = st.columns(2)
233
 
234
- with insights_col1:
235
- st.metric("Top Performing Category",
236
- category_performance.loc[category_performance['Revenue'].idxmax(), 'Category'])
 
 
237
 
238
- with insights_col2:
239
- st.metric("Highest Engagement Category",
240
- category_performance.loc[category_performance['Engagement'].idxmax(), 'Category'])
 
241
 
 
242
  def render_analytics():
243
  st.header("πŸ” Data Analytics")
244
 
@@ -308,6 +345,7 @@ def render_analytics():
308
  for col, (metric, value) in zip(cols, metrics.items()):
309
  col.metric(metric, f"{value:.2f}")
310
 
 
311
  def render_brainstorm_page():
312
  st.title("Product Brainstorm Hub")
313
  manager = BrainstormManager()
@@ -357,71 +395,7 @@ def render_brainstorm_page():
357
  else:
358
  st.info("No products yet. Create one to get started!")
359
 
360
- def render_chat():
361
- st.header("πŸ’¬ Business Assistant")
362
-
363
- if "messages" not in st.session_state:
364
- st.session_state.messages = []
365
-
366
- for message in st.session_state.messages:
367
- with st.chat_message(message["role"]):
368
- st.markdown(message["content"])
369
-
370
- if prompt := st.chat_input("Ask about your business..."):
371
- st.session_state.messages.append({"role": "user", "content": prompt})
372
- with st.chat_message("user"):
373
- st.markdown(prompt)
374
-
375
- response = f"Thank you for your question about '{prompt}'. The LLM integration will be implemented soon."
376
-
377
- with st.chat_message("assistant"):
378
- st.markdown(response)
379
- st.session_state.messages.append({"role": "assistant", "content": response})
380
-
381
- def load_huggingface_model(model_name="google/flan-t5-base"):
382
- """
383
- Load a pre-trained model from Hugging Face
384
-
385
- Args:
386
- model_name (str): Hugging Face model identifier
387
-
388
- Returns:
389
- tuple: Loaded model and tokenizer
390
- """
391
- try:
392
- tokenizer = AutoTokenizer.from_pretrained(model_name)
393
- model = AutoModelForCausalLM.from_pretrained(model_name)
394
- return model, tokenizer
395
- except Exception as e:
396
- st.error(f"Error loading model: {e}")
397
- return None, None
398
-
399
- def generate_text(model, tokenizer, prompt, max_length=200):
400
- """
401
- Generate text based on input prompt
402
-
403
- Args:
404
- model: Loaded Hugging Face model
405
- tokenizer: Model's tokenizer
406
- prompt (str): Input text prompt
407
- max_length (int): Maximum generated text length
408
-
409
- Returns:
410
- str: Generated text
411
- """
412
- inputs = tokenizer(prompt, return_tensors="pt")
413
-
414
- with torch.no_grad():
415
- outputs = model.generate(
416
- **inputs,
417
- max_length=max_length,
418
- num_return_sequences=1,
419
- do_sample=True,
420
- temperature=0.7
421
- )
422
-
423
- return tokenizer.decode(outputs[0], skip_special_tokens=True)
424
-
425
  def render_ai_assistant():
426
  st.title("πŸ€– Business AI Assistant")
427
 
@@ -456,6 +430,29 @@ def render_ai_assistant():
456
  else:
457
  st.error("Failed to load model")
458
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  def main():
460
  st.set_page_config(
461
  page_title="Prospira",
@@ -470,7 +467,7 @@ def main():
470
 
471
  page = st.radio(
472
  "Navigation",
473
- ["Dashboard", "Analytics", "Brainstorm", "AI Assistant", "Chat"] # Added AI Assistant
474
  )
475
 
476
  if page == "Dashboard":
@@ -479,7 +476,10 @@ def main():
479
  render_analytics()
480
  elif page == "Brainstorm":
481
  render_brainstorm_page()
482
- elif page == "AI Assistant": # New condition
483
  render_ai_assistant()
484
  elif page == "Chat":
485
- render_chat()
 
 
 
 
5
  import numpy as np
6
  from datetime import datetime, timedelta
7
  from typing import Dict, List, Any
 
8
 
9
+ # Hugging Face Model Integration
10
+ import torch
11
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
12
+
13
+ def load_huggingface_model(model_name="google/flan-t5-base"):
14
+ try:
15
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
16
+ model = AutoModelForCausalLM.from_pretrained(model_name)
17
+ return model, tokenizer
18
+ except Exception as e:
19
+ st.error(f"Error loading model: {e}")
20
+ return None, None
21
+
22
+ def generate_text(model, tokenizer, prompt, max_length=200):
23
+ inputs = tokenizer(prompt, return_tensors="pt")
24
+
25
+ with torch.no_grad():
26
+ outputs = model.generate(
27
+ **inputs,
28
+ max_length=max_length,
29
+ num_return_sequences=1,
30
+ do_sample=True,
31
+ temperature=0.7
32
+ )
33
+
34
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
35
+
36
+ # Data Processing Class
37
  class DataProcessor:
38
  def __init__(self):
39
  self.data = None
 
161
  steps.append("Prepare enterprise sales strategy")
162
  return steps
163
 
164
+ # Sample Data Generation
165
  def generate_sample_data():
166
  dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
167
+ base_data = pd.DataFrame({
168
  'Date': dates,
169
  'Revenue': np.random.normal(1000, 100, len(dates)),
170
  'Users': np.random.randint(100, 200, len(dates)),
171
  'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
172
+ 'Category': np.random.choice(['Digital', 'Physical', 'Service'], len(dates))
173
  })
174
+
175
+ # Add predictive elements
176
+ base_data['Predicted_Revenue'] = base_data['Revenue'] * np.linspace(1, 1.2, len(dates))
177
+ base_data['Revenue_Trend'] = np.where(base_data['Predicted_Revenue'] > base_data['Revenue'], 'Positive', 'Negative')
178
+
179
+ return base_data
180
 
181
+ # Dashboard Rendering
182
  def render_dashboard():
183
+ st.header("πŸ“Š Advanced Business Intelligence Dashboard")
184
 
 
185
  data = generate_sample_data()
 
186
 
187
+ # Sidebar Filters
188
+ st.sidebar.header("Dashboard Filters")
189
+ selected_categories = st.sidebar.multiselect(
190
+ "Select Categories",
191
+ options=data['Category'].unique(),
192
+ default=data['Category'].unique()
193
+ )
194
+
195
+ date_range = st.sidebar.date_input(
196
+ "Select Date Range",
197
+ [data['Date'].min(), data['Date'].max()]
198
+ )
199
+
200
+ # Filter Data
201
+ filtered_data = data[
202
+ (data['Category'].isin(selected_categories)) &
203
+ (data['Date'].between(date_range[0], date_range[1]))
204
+ ]
205
+
206
+ # KPI Metrics
207
  col1, col2, col3, col4 = st.columns(4)
208
  with col1:
209
  st.metric("Total Revenue",
210
+ f"${filtered_data['Revenue'].sum():,.2f}",
211
+ delta=f"{filtered_data['Revenue'].pct_change().mean()*100:.2f}%")
212
  with col2:
213
  st.metric("Total Users",
214
+ f"{filtered_data['Users'].sum():,}",
215
+ delta=f"{filtered_data['Users'].pct_change().mean()*100:.2f}%")
216
  with col3:
217
  st.metric("Avg Engagement",
218
+ f"{filtered_data['Engagement'].mean():.2%}")
 
219
  with col4:
220
+ st.metric("Predicted Trend",
221
+ filtered_data['Revenue_Trend'].mode()[0])
 
222
 
223
+ # Advanced Visualizations
224
  col1, col2 = st.columns(2)
225
 
226
  with col1:
227
+ st.subheader("Revenue Forecast")
228
+ forecast_fig = go.Figure()
229
+ forecast_fig.add_trace(go.Scatter(
230
+ x=filtered_data['Date'],
231
+ y=filtered_data['Revenue'],
232
  mode='lines',
233
+ name='Actual Revenue',
234
  line=dict(color='blue')
235
  ))
236
+ forecast_fig.add_trace(go.Scatter(
237
+ x=filtered_data['Date'],
238
+ y=filtered_data['Predicted_Revenue'],
239
  mode='lines',
240
+ name='Predicted Revenue',
241
+ line=dict(color='red', dash='dot')
242
  ))
243
+ st.plotly_chart(forecast_fig, use_container_width=True)
 
244
 
245
  with col2:
246
+ st.subheader("Category Performance")
247
+ category_performance = filtered_data.groupby('Category').agg({
248
+ 'Revenue': ['sum', 'mean'],
249
+ 'Users': 'sum',
250
+ 'Engagement': 'mean'
251
+ }).reset_index()
252
+ category_performance.columns = ['Category', 'Total_Revenue', 'Avg_Revenue', 'Total_Users', 'Avg_Engagement']
253
+
254
+ perf_fig = px.bar(
255
+ category_performance,
256
+ x='Category',
257
+ y='Total_Revenue',
258
+ color='Avg_Engagement',
259
+ hover_data=['Total_Users', 'Avg_Revenue']
260
  )
261
+ st.plotly_chart(perf_fig, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
+ # Predictive Insights
264
+ st.subheader("Predictive Insights")
265
+ col1, col2 = st.columns(2)
266
 
267
+ with col1:
268
+ top_category = category_performance.loc[category_performance['Total_Revenue'].idxmax()]
269
+ st.metric("Top Revenue Category",
270
+ top_category['Category'],
271
+ delta=f"${top_category['Total_Revenue']:,.2f}")
272
 
273
+ with col2:
274
+ growth_prediction = filtered_data['Predicted_Revenue'].mean() / filtered_data['Revenue'].mean() - 1
275
+ st.metric("Revenue Growth Prediction",
276
+ f"{growth_prediction:.2%}")
277
 
278
+ # Analytics Rendering (from previous implementation)
279
  def render_analytics():
280
  st.header("πŸ” Data Analytics")
281
 
 
345
  for col, (metric, value) in zip(cols, metrics.items()):
346
  col.metric(metric, f"{value:.2f}")
347
 
348
+ # Brainstorm Rendering
349
  def render_brainstorm_page():
350
  st.title("Product Brainstorm Hub")
351
  manager = BrainstormManager()
 
395
  else:
396
  st.info("No products yet. Create one to get started!")
397
 
398
+ # AI Assistant Rendering
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
  def render_ai_assistant():
400
  st.title("πŸ€– Business AI Assistant")
401
 
 
430
  else:
431
  st.error("Failed to load model")
432
 
433
+ # Chat Rendering (simplified)
434
+ def render_chat():
435
+ st.header("πŸ’¬ Business Assistant")
436
+
437
+ if "messages" not in st.session_state:
438
+ st.session_state.messages = []
439
+
440
+ for message in st.session_state.messages:
441
+ with st.chat_message(message["role"]):
442
+ st.markdown(message["content"])
443
+
444
+ if prompt := st.chat_input("Ask about your business..."):
445
+ st.session_state.messages.append({"role": "user", "content": prompt})
446
+ with st.chat_message("user"):
447
+ st.markdown(prompt)
448
+
449
+ response = f"Thank you for your question about '{prompt}'. The LLM integration will be implemented soon."
450
+
451
+ with st.chat_message("assistant"):
452
+ st.markdown(response)
453
+ st.session_state.messages.append({"role": "assistant", "content": response})
454
+
455
+ # Main Application Function
456
  def main():
457
  st.set_page_config(
458
  page_title="Prospira",
 
467
 
468
  page = st.radio(
469
  "Navigation",
470
+ ["Dashboard", "Analytics", "Brainstorm", "AI Assistant", "Chat"]
471
  )
472
 
473
  if page == "Dashboard":
 
476
  render_analytics()
477
  elif page == "Brainstorm":
478
  render_brainstorm_page()
479
+ elif page == "AI Assistant":
480
  render_ai_assistant()
481
  elif page == "Chat":
482
+ render_chat()
483
+
484
+ if __name__ == "__main__":
485
+ main()