Pranav0111 commited on
Commit
bc0d02b
Β·
verified Β·
1 Parent(s): 1a7de55

Create pages.py

Browse files
Files changed (1) hide show
  1. pages.py +328 -0
pages.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import streamlit.components.v1 as components
3
+ import plotly.express as px
4
+ import plotly.graph_objects as go
5
+ import numpy as np
6
+ from datetime import datetime
7
+
8
+ from data_processor import DataProcessor
9
+ from brainstorm_manager import BrainstormManager
10
+ from chatbot import ChatbotManager
11
+ from utils import generate_sample_data
12
+
13
+
14
+ def render_home():
15
+ st.title("πŸš€ Welcome to Prospira")
16
+ st.subheader("πŸ“Š Data-Driven Solutions for Businesses and Creators")
17
+ st.markdown("""
18
+ **Prospira** empowers businesses and creators to enhance their content, products, and marketing strategies using AI-driven insights.
19
+
20
+ ### **✨ Key Features**
21
+ - **πŸ“ˆ Performance Analytics:** Real-time insights into business metrics.
22
+ - **πŸ”Ž Competitive Analysis:** Benchmark your business against competitors.
23
+ - **πŸ’‘ Smart Product Ideas:** AI-generated recommendations for future products and content.
24
+ - **🧠 AI Business Mentor:** Personalized AI guidance for strategy and growth.
25
+ Explore how **Prospira** can help optimize your decision-making and drive success! πŸ’‘πŸš€
26
+ """)
27
+
28
+
29
+ def render_dashboard():
30
+ st.header("πŸ“Š Comprehensive Business Performance Dashboard")
31
+
32
+ # Generate sample data with more complex structure
33
+ data = generate_sample_data()
34
+ data['Profit_Margin'] = data['Revenue'] * np.random.uniform(0.1, 0.3, len(data))
35
+
36
+ # Top-level KPI Section
37
+ col1, col2, col3, col4 = st.columns(4)
38
+ with col1:
39
+ st.metric("Total Revenue",
40
+ f"${data['Revenue'].sum():,.2f}",
41
+ delta=f"{data['Revenue'].pct_change().mean()*100:.2f}%")
42
+ with col2:
43
+ st.metric("Total Users",
44
+ f"{data['Users'].sum():,}",
45
+ delta=f"{data['Users'].pct_change().mean()*100:.2f}%")
46
+ with col3:
47
+ st.metric("Avg Engagement",
48
+ f"{data['Engagement'].mean():.2%}",
49
+ delta=f"{data['Engagement'].pct_change().mean()*100:.2f}%")
50
+ with col4:
51
+ st.metric("Profit Margin",
52
+ f"{data['Profit_Margin'].mean():.2%}",
53
+ delta=f"{data['Profit_Margin'].pct_change().mean()*100:.2f}%")
54
+
55
+ # Visualization Grid
56
+ col1, col2 = st.columns(2)
57
+
58
+ with col1:
59
+ st.subheader("Revenue & Profit Trends")
60
+ fig_revenue = go.Figure()
61
+ fig_revenue.add_trace(go.Scatter(
62
+ x=data['Date'],
63
+ y=data['Revenue'],
64
+ mode='lines',
65
+ name='Revenue',
66
+ line=dict(color='blue')
67
+ ))
68
+ fig_revenue.add_trace(go.Scatter(
69
+ x=data['Date'],
70
+ y=data['Profit_Margin'],
71
+ mode='lines',
72
+ name='Profit Margin',
73
+ line=dict(color='green')
74
+ ))
75
+ fig_revenue.update_layout(height=350)
76
+ st.plotly_chart(fig_revenue, use_container_width=True)
77
+
78
+ with col2:
79
+ st.subheader("User Engagement Analysis")
80
+ fig_engagement = px.scatter(
81
+ data,
82
+ x='Users',
83
+ y='Engagement',
84
+ color='Category',
85
+ size='Revenue',
86
+ hover_data=['Date'],
87
+ title='User Engagement Dynamics'
88
+ )
89
+ fig_engagement.update_layout(height=350)
90
+ st.plotly_chart(fig_engagement, use_container_width=True)
91
+
92
+ # Category Performance
93
+ st.subheader("Category Performance Breakdown")
94
+ category_performance = data.groupby('Category').agg({
95
+ 'Revenue': 'sum',
96
+ 'Users': 'sum',
97
+ 'Engagement': 'mean'
98
+ }).reset_index()
99
+
100
+ fig_category = px.bar(
101
+ category_performance,
102
+ x='Category',
103
+ y='Revenue',
104
+ color='Engagement',
105
+ title='Revenue by Category with Engagement Overlay'
106
+ )
107
+ st.plotly_chart(fig_category, use_container_width=True)
108
+
109
+ # Bottom Summary
110
+ st.subheader("Quick Insights")
111
+ insights_col1, insights_col2 = st.columns(2)
112
+
113
+ with insights_col1:
114
+ st.metric("Top Performing Category",
115
+ category_performance.loc[category_performance['Revenue'].idxmax(), 'Category'])
116
+
117
+ with insights_col2:
118
+ st.metric("Highest Engagement Category",
119
+ category_performance.loc[category_performance['Engagement'].idxmax(), 'Category'])
120
+
121
+
122
+ def render_analytics():
123
+ st.header("πŸ” Data Analytics")
124
+
125
+ processor = DataProcessor()
126
+ uploaded_file = st.file_uploader("Upload your CSV data", type=['csv'])
127
+
128
+ if uploaded_file is not None:
129
+ if processor.load_data(uploaded_file):
130
+ st.success("Data loaded successfully!")
131
+
132
+ tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"])
133
+
134
+ with tabs[0]:
135
+ st.subheader("Data Preview")
136
+ st.dataframe(processor.data.head())
137
+ st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}")
138
+
139
+ with tabs[1]:
140
+ st.subheader("Basic Statistics")
141
+ stats = processor.get_basic_stats()
142
+ st.write(stats['summary'])
143
+
144
+ st.subheader("Missing Values")
145
+ st.write(stats['missing_values'])
146
+
147
+ with tabs[2]:
148
+ st.subheader("Create Visualization")
149
+ col1, col2, col3 = st.columns(3)
150
+
151
+ with col1:
152
+ chart_type = st.selectbox(
153
+ "Select Chart Type",
154
+ ["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"]
155
+ )
156
+
157
+ with col2:
158
+ x_col = st.selectbox("Select X-axis", processor.data.columns)
159
+
160
+ with col3:
161
+ y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None
162
+
163
+ color_col = st.selectbox("Select Color Variable (optional)",
164
+ ['None'] + processor.categorical_columns)
165
+ color_col = None if color_col == 'None' else color_col
166
+
167
+ fig = processor.create_visualization(
168
+ chart_type,
169
+ x_col,
170
+ y_col if y_col else x_col,
171
+ color_col
172
+ )
173
+ st.plotly_chart(fig, use_container_width=True)
174
+
175
+ with tabs[3]:
176
+ st.subheader("Column Metrics")
177
+ selected_col = st.selectbox("Select column", processor.numeric_columns)
178
+
179
+ metrics = {
180
+ 'Mean': processor.data[selected_col].mean(),
181
+ 'Median': processor.data[selected_col].median(),
182
+ 'Std Dev': processor.data[selected_col].std(),
183
+ 'Min': processor.data[selected_col].min(),
184
+ 'Max': processor.data[selected_col].max()
185
+ }
186
+
187
+ cols = st.columns(len(metrics))
188
+ for col, (metric, value) in zip(cols, metrics.items()):
189
+ col.metric(metric, f"{value:.2f}")
190
+
191
+
192
+ def render_brainstorm_page():
193
+ st.title("Product Brainstorm Hub")
194
+ manager = BrainstormManager()
195
+
196
+ action = st.sidebar.radio("Action", ["View Products", "Create New Product"])
197
+
198
+ if action == "Create New Product":
199
+ basic_info, market_analysis, submitted = manager.generate_product_form()
200
+
201
+ if submitted:
202
+ product_data = {**basic_info, **market_analysis}
203
+ insights = manager.analyze_product(product_data)
204
+
205
+ product_id = f"prod_{len(st.session_state.products)}"
206
+ st.session_state.products[product_id] = {
207
+ "data": product_data,
208
+ "insights": insights,
209
+ "created_at": str(datetime.now())
210
+ }
211
+
212
+ st.success("Product added! View insights in the Products tab.")
213
+
214
+ else:
215
+ if st.session_state.products:
216
+ for prod_id, product in st.session_state.products.items():
217
+ with st.expander(f"🎯 {product['data']['name']}"):
218
+ col1, col2 = st.columns(2)
219
+
220
+ with col1:
221
+ st.subheader("Product Details")
222
+ st.write(f"Category: {product['data']['category']}")
223
+ st.write(f"Target: {', '.join(product['data']['target_audience'])}")
224
+ st.write(f"Description: {product['data']['description']}")
225
+
226
+ with col2:
227
+ st.subheader("Insights")
228
+ st.metric("Opportunity Score", f"{product['insights']['market_opportunity']}/10")
229
+ st.metric("Suggested Price", f"${product['insights']['suggested_price']}")
230
+
231
+ st.write("**Risk Factors:**")
232
+ for risk in product['insights']['risk_factors']:
233
+ st.write(f"- {risk}")
234
+
235
+ st.write("**Next Steps:**")
236
+ for step in product['insights']['next_steps']:
237
+ st.write(f"- {step}")
238
+ else:
239
+ st.info("No products yet. Create one to get started!")
240
+
241
+
242
+ def render_chat():
243
+ st.header("πŸ’¬ AI Business Mentor")
244
+
245
+ # Initialize chatbot manager
246
+ chatbot = ChatbotManager()
247
+ chatbot.initialize_chat()
248
+
249
+ # Sidebar options
250
+ st.sidebar.subheader("Chat Options")
251
+ if st.sidebar.button("Clear Chat History"):
252
+ chatbot.clear_chat()
253
+ st.rerun()
254
+
255
+ # Display chat history
256
+ st.subheader("πŸ€– Conversation")
257
+
258
+ # Chat container
259
+ chat_container = st.container()
260
+
261
+ with chat_container:
262
+ # Display all messages
263
+ for message in chatbot.get_chat_history():
264
+ if message["role"] == "user":
265
+ with st.chat_message("user"):
266
+ st.write(message["content"])
267
+ else:
268
+ with st.chat_message("assistant"):
269
+ st.write(message["content"])
270
+
271
+ # Chat input
272
+ user_input = st.chat_input("Ask me anything about business strategy, marketing, products, or operations...")
273
+
274
+ if user_input:
275
+ # Add user message
276
+ chatbot.add_message("user", user_input)
277
+
278
+ # Generate response
279
+ with st.spinner("Thinking..."):
280
+ response = chatbot.generate_business_response(user_input)
281
+
282
+ # Add assistant response
283
+ chatbot.add_message("assistant", response)
284
+
285
+ # Rerun to update the display
286
+ st.rerun()
287
+
288
+ # Additional helpful sections
289
+ st.markdown("---")
290
+ st.subheader("πŸ’‘ Quick Business Topics")
291
+
292
+ col1, col2, col3 = st.columns(3)
293
+
294
+ with col1:
295
+ if st.button("πŸ“Š Business Strategy"):
296
+ chatbot.add_message("user", "I need help with business strategy")
297
+ response = chatbot.generate_business_response("I need help with business strategy")
298
+ chatbot.add_message("assistant", response)
299
+ st.rerun()
300
+
301
+ with col2:
302
+ if st.button("πŸ“ˆ Marketing Tips"):
303
+ chatbot.add_message("user", "Give me marketing advice")
304
+ response = chatbot.generate_business_response("Give me marketing advice")
305
+ chatbot.add_message("assistant", response)
306
+ st.rerun()
307
+
308
+ with col3:
309
+ if st.button("πŸ’° Financial Planning"):
310
+ chatbot.add_message("user", "Help with financial planning")
311
+ response = chatbot.generate_business_response("Help with financial planning")
312
+ chatbot.add_message("assistant", response)
313
+ st.rerun()
314
+
315
+ # Optional: Keep the iframe as alternative
316
+ st.markdown("---")
317
+ st.subheader("πŸ”— Alternative Chat Interface")
318
+ st.info("You can also use the external chat interface below:")
319
+
320
+ iframe_code = """
321
+ <iframe
322
+ src="https://demoorganisation34-vinay.hf.space"
323
+ frameborder="0"
324
+ width="850"
325
+ height="450"
326
+ ></iframe>
327
+ """
328
+ components.html(iframe_code, height=500)