Pranav0111 commited on
Commit
85fa7cc
Β·
verified Β·
1 Parent(s): 4ce2529

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +453 -438
app.py CHANGED
@@ -1,439 +1,454 @@
 
 
 
1
  import streamlit as st
2
- 2 - import plotly.express as px
3
- 3 - import plotly.graph_objects as go
4
- 4 - import pandas as pd
5
- 5 - import numpy as np
6
- 6 - from datetime import datetime, timedelta
7
- 7 - from typing import Dict, List, Any
8
- 8 - import streamlit as st
9
- 9 - import streamlit.components.v1 as components
10
- 10 -
11
- 11 - # --- Data Processing Class ---
12
- 12 - class DataProcessor:
13
- 13 - def __init__(self):
14
- 14 - self.data = None
15
- 15 - self.numeric_columns = []
16
- 16 - self.categorical_columns = []
17
- 17 -
18
- 18 - self.date_columns = []
19
- 19 -
20
- 20 - def load_data(self, file) -> bool:
21
- 21 - try:
22
- 22 - self.data = pd.read_csv(file)
23
- 23 - self._classify_columns()
24
- 24 - return True
25
- 25 - except Exception as e:
26
- 26 - st.error(f"Error loading data: {str(e)}")
27
- 27 - return False
28
- 28 -
29
- 29 - def _classify_columns(self):
30
- 30 - for col in self.data.columns:
31
- 31 - if pd.api.types.is_numeric_dtype(self.data[col]):
32
- 32 - self.numeric_columns.append(col)
33
- 33 - elif pd.api.types.is_datetime64_any_dtype(self.data[col]):
34
- 34 - self.date_columns.append(col)
35
- 35 - else:
36
- 36 - try:
37
- 37 - pd.to_datetime(self.data[col])
38
- 38 - self.date_columns.append(col)
39
- 39 - except:
40
- 40 - self.categorical_columns.append(col)
41
- 41 -
42
- 42 - def get_basic_stats(self) -> Dict[str, Any]:
43
- 43 - if self.data is None:
44
- 44 - return {}
45
- 45 -
46
- 46 - stats = {
47
- 47 - 'summary': self.data[self.numeric_columns].describe(),
48
- 48 - 'missing_values': self.data.isnull().sum(),
49
- 49 - 'row_count': len(self.data),
50
- 50 - 'column_count': len(self.data.columns)
51
- 51 - }
52
- 52 - return stats
53
- 53 -
54
- 54 - def create_visualization(self, chart_type: str, x_col: str, y_col: str, color_col: str = None) -> go.Figure:
55
- 55 - if chart_type == "Line Plot":
56
- 56 - fig = px.line(self.data, x=x_col, y=y_col, color=color_col)
57
- 57 - elif chart_type == "Bar Plot":
58
- 58 - fig = px.bar(self.data, x=x_col, y=y_col, color=color_col)
59
- 59 - elif chart_type == "Scatter Plot":
60
- 60 - fig = px.scatter(self.data, x=x_col, y=y_col, color=color_col)
61
- 61 - elif chart_type == "Box Plot":
62
- 62 - fig = px.box(self.data, x=x_col, y=y_col, color=color_col)
63
- 63 - else:
64
- 64 - fig = px.histogram(self.data, x=x_col, color=color_col)
65
- 65 -
66
- 66 - return fig
67
- 67 -
68
- 68 - class BrainstormManager:
69
- 69 - def __init__(self):
70
- 70 - if 'products' not in st.session_state:
71
- 71 - st.session_state.products = {}
72
- 72 -
73
- 73 - def generate_product_form(self) -> Dict:
74
- 74 - with st.form("product_form"):
75
- 75 - basic_info = {
76
- 76 - "name": st.text_input("Product Name"),
77
- 77 - "category": st.selectbox("Category", ["Digital", "Physical", "Service"]),
78
- 78 - "description": st.text_area("Description"),
79
- 79 - "target_audience": st.multiselect("Target Audience",
80
- 80 - ["Students", "Professionals", "Businesses", "Seniors", "Youth"]),
81
- 81 - "price_range": st.slider("Price Range ($)", 0, 1000, (50, 200)),
82
- 82 - "launch_date": st.date_input("Expected Launch Date")
83
- 83 - }
84
- 84 -
85
- 85 - st.subheader("Market Analysis")
86
- 86 - market_analysis = {
87
- 87 - "competitors": st.text_area("Main Competitors (one per line)"),
88
- 88 - "unique_features": st.text_area("Unique Selling Points"),
89
- 89 - "market_size": st.selectbox("Market Size",
90
- 90 - ["Small", "Medium", "Large", "Enterprise"]),
91
- 91 - "growth_potential": st.slider("Growth Potential", 1, 10)
92
- 92 - }
93
- 93 -
94
- 94 - submitted = st.form_submit_button("Save Product")
95
- 95 - return basic_info, market_analysis, submitted
96
- 96 -
97
- 97 - def analyze_product(self, product_data: Dict) -> Dict:
98
- 98 - insights = {
99
- 99 - "market_opportunity": self._calculate_opportunity_score(product_data),
100
- 100 - "suggested_price": self._suggest_price(product_data),
101
- 101 - "risk_factors": self._identify_risks(product_data),
102
- 102 - "next_steps": self._generate_next_steps(product_data)
103
- 103 - }
104
- 104 - return insights
105
- 105 -
106
- 106 - def _calculate_opportunity_score(self, data: Dict) -> int:
107
- 107 - score = 0
108
- 108 - if data.get("market_size") == "Large":
109
- 109 - score += 3
110
- 110 - if len(data.get("target_audience", [])) >= 2:
111
- 111 - score += 2
112
- 112 - if data.get("growth_potential", 0) > 7:
113
- 113 - score += 2
114
- 114 - return min(score, 10)
115
- 115 -
116
- 116 - def _suggest_price(self, data: Dict) -> float:
117
- 117 - base_price = sum(data.get("price_range", (0, 0))) / 2
118
- 118 - if data.get("market_size") == "Enterprise":
119
- 119 - base_price *= 1.5
120
- 120 - return round(base_price, 2)
121
- 121 -
122
- 122 - def _identify_risks(self, data: Dict) -> List[str]:
123
- 123 - risks = []
124
- 124 - if data.get("competitors"):
125
- 125 - risks.append("Competitive market - differentiation crucial")
126
- 126 - if len(data.get("target_audience", [])) < 2:
127
- 127 - risks.append("Narrow target audience - consider expansion")
128
- 128 - return risks
129
- 129 -
130
- 130 - def _generate_next_steps(self, data: Dict) -> List[str]:
131
- 131 - steps = [
132
- 132 - "Create detailed product specification",
133
- 133 - "Develop MVP timeline",
134
- 134 - "Plan marketing strategy"
135
- 135 - ]
136
- 136 - if data.get("market_size") == "Enterprise":
137
- 137 - steps.append("Prepare enterprise sales strategy")
138
- 138 - return steps
139
- 139 -
140
- 140 - # --- Sample Data Generation ---
141
- 141 - def generate_sample_data():
142
- 142 - dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
143
- 143 - return pd.DataFrame({
144
- 144 - 'Date': dates,
145
- 145 - 'Revenue': np.random.normal(1000, 100, len(dates)),
146
- 146 - 'Users': np.random.randint(100, 200, len(dates)),
147
- 147 - 'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
148
- 148 - 'Category': np.random.choice(['A', 'B', 'C'], len(dates))
149
- 149 - })
150
- 150 -
151
- 151 - # --- Page Rendering Functions ---
152
- 152 - def render_dashboard():
153
- 153 - st.header("πŸ“Š Comprehensive Business Performance Dashboard")
154
- 154 -
155
- 155 - # Generate sample data with more complex structure
156
- 156 - data = generate_sample_data()
157
- 157 - data['Profit_Margin'] = data['Revenue'] * np.random.uniform(0.1, 0.3, len(data))
158
- 158 -
159
- 159 - # Top-level KPI Section
160
- 160 - col1, col2, col3, col4 = st.columns(4)
161
- 161 - with col1:
162
- 162 - st.metric("Total Revenue",
163
- 163 - f"${data['Revenue'].sum():,.2f}",
164
- 164 - delta=f"{data['Revenue'].pct_change().mean()*100:.2f}%")
165
- 165 - with col2:
166
- 166 - st.metric("Total Users",
167
- 167 - f"{data['Users'].sum():,}",
168
- 168 - delta=f"{data['Users'].pct_change().mean()*100:.2f}%")
169
- 169 - with col3:
170
- 170 - st.metric("Avg Engagement",
171
- 171 - f"{data['Engagement'].mean():.2%}",
172
- 172 - delta=f"{data['Engagement'].pct_change().mean()*100:.2f}%")
173
- 173 - with col4:
174
- 174 - st.metric("Profit Margin",
175
- 175 - f"{data['Profit_Margin'].mean():.2%}",
176
- 176 - delta=f"{data['Profit_Margin'].pct_change().mean()*100:.2f}%")
177
- 177 -
178
- 178 - # Visualization Grid
179
- 179 - col1, col2 = st.columns(2)
180
- 180 -
181
- 181 - with col1:
182
- 182 - st.subheader("Revenue & Profit Trends")
183
- 183 - fig_revenue = go.Figure()
184
- 184 - fig_revenue.add_trace(go.Scatter(
185
- 185 - x=data['Date'],
186
- 186 - y=data['Revenue'],
187
- 187 - mode='lines',
188
- 188 - name='Revenue',
189
- 189 - line=dict(color='blue')
190
- 190 - ))
191
- 191 - fig_revenue.add_trace(go.Scatter(
192
- 192 - x=data['Date'],
193
- 193 - y=data['Profit_Margin'],
194
- 194 - mode='lines',
195
- 195 - name='Profit Margin',
196
- 196 - line=dict(color='green')
197
- 197 - ))
198
- 198 - fig_revenue.update_layout(height=350)
199
- 199 - st.plotly_chart(fig_revenue, use_container_width=True)
200
- 200 -
201
- 201 - with col2:
202
- 202 - st.subheader("User Engagement Analysis")
203
- 203 - fig_engagement = px.scatter(
204
- 204 - data,
205
- 205 - x='Users',
206
- 206 - y='Engagement',
207
- 207 - color='Category',
208
- 208 - size='Revenue',
209
- 209 - hover_data=['Date'],
210
- 210 - title='User Engagement Dynamics'
211
- 211 - )
212
- 212 - fig_engagement.update_layout(height=350)
213
- 213 - st.plotly_chart(fig_engagement, use_container_width=True)
214
- 214 -
215
- 215 - # Category Performance
216
- 216 - st.subheader("Category Performance Breakdown")
217
- 217 - category_performance = data.groupby('Category').agg({
218
- 218 - 'Revenue': 'sum',
219
- 219 - 'Users': 'sum',
220
- 220 - 'Engagement': 'mean'
221
- 221 - }).reset_index()
222
- 222 -
223
- 223 - fig_category = px.bar(
224
- 224 - category_performance,
225
- 225 - x='Category',
226
- 226 - y='Revenue',
227
- 227 - color='Engagement',
228
- 228 - title='Revenue by Category with Engagement Overlay'
229
- 229 - )
230
- 230 - st.plotly_chart(fig_category, use_container_width=True)
231
- 231 -
232
- 232 - # Bottom Summary
233
- 233 - st.subheader("Quick Insights")
234
- 234 - insights_col1, insights_col2 = st.columns(2)
235
- 235 -
236
- 236 - with insights_col1:
237
- 237 - st.metric("Top Performing Category",
238
- 238 - category_performance.loc[category_performance['Revenue'].idxmax(), 'Category'])
239
- 239 -
240
- 240 - with insights_col2:
241
- 241 - st.metric("Highest Engagement Category",
242
- 242 - category_performance.loc[category_performance['Engagement'].idxmax(), 'Category'])
243
- 243 -
244
- 244 - def render_analytics():
245
- 245 - st.header("πŸ” Data Analytics")
246
- 246 -
247
- 247 - processor = DataProcessor()
248
- 248 - uploaded_file = st.file_uploader("Upload your CSV data", type=['csv'])
249
- 249 -
250
- 250 - if uploaded_file is not None:
251
- 251 - if processor.load_data(uploaded_file):
252
- 252 - st.success("Data loaded successfully!")
253
- 253 -
254
- 254 - tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"])
255
- 255 -
256
- 256 - with tabs[0]:
257
- 257 - st.subheader("Data Preview")
258
- 258 - st.dataframe(processor.data.head())
259
- 259 - st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}")
260
- 260 -
261
- 261 - with tabs[1]:
262
- 262 - st.subheader("Basic Statistics")
263
- 263 - stats = processor.get_basic_stats()
264
- 264 - st.write(stats['summary'])
265
- 265 -
266
- 266 - st.subheader("Missing Values")
267
- 267 - st.write(stats['missing_values'])
268
- 268 -
269
- 269 - with tabs[2]:
270
- 270 - st.subheader("Create Visualization")
271
- 271 - col1, col2, col3 = st.columns(3)
272
- 272 -
273
- 273 - with col1:
274
- 274 - chart_type = st.selectbox(
275
- 275 - "Select Chart Type",
276
- 276 - ["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"]
277
- 277 - )
278
- 278 -
279
- 279 - with col2:
280
- 280 - x_col = st.selectbox("Select X-axis", processor.data.columns)
281
- 281 -
282
- 282 - with col3:
283
- 283 - y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None
284
- 284 -
285
- 285 - color_col = st.selectbox("Select Color Variable (optional)",
286
- 286 - ['None'] + processor.categorical_columns)
287
- 287 - color_col = None if color_col == 'None' else color_col
288
- 288 -
289
- 289 - fig = processor.create_visualization(
290
- 290 - chart_type,
291
- 291 - x_col,
292
- 292 - y_col if y_col else x_col,
293
- 293 - color_col
294
- 294 - )
295
- 295 - st.plotly_chart(fig, use_container_width=True)
296
- 296 -
297
- 297 - with tabs[3]:
298
- 298 - st.subheader("Column Metrics")
299
- 299 - selected_col = st.selectbox("Select column", processor.numeric_columns)
300
- 300 -
301
- 301 - metrics = {
302
- 302 - 'Mean': processor.data[selected_col].mean(),
303
- 303 - 'Median': processor.data[selected_col].median(),
304
- 304 - 'Std Dev': processor.data[selected_col].std(),
305
- 305 - 'Min': processor.data[selected_col].min(),
306
- 306 - 'Max': processor.data[selected_col].max()
307
- 307 - }
308
- 308 -
309
- 309 - cols = st.columns(len(metrics))
310
- 310 - for col, (metric, value) in zip(cols, metrics.items()):
311
- 311 - col.metric(metric, f"{value:.2f}")
312
- 312 -
313
- 313 - def render_brainstorm_page():
314
- 314 - st.title("Product Brainstorm Hub")
315
- 315 - manager = BrainstormManager()
316
- 316 -
317
- 317 - action = st.sidebar.radio("Action", ["View Products", "Create New Product"])
318
- 318 -
319
- 319 - if action == "Create New Product":
320
- 320 - basic_info, market_analysis, submitted = manager.generate_product_form()
321
- 321 -
322
- 322 - if submitted:
323
- 323 - product_data = {**basic_info, **market_analysis}
324
- 324 - insights = manager.analyze_product(product_data)
325
- 325 -
326
- 326 - product_id = f"prod_{len(st.session_state.products)}"
327
- 327 - st.session_state.products[product_id] = {
328
- 328 - "data": product_data,
329
- 329 - "insights": insights,
330
- 330 - "created_at": str(datetime.now())
331
- 331 - }
332
- 332 -
333
- 333 - st.success("Product added! View insights in the Products tab.")
334
- 334 -
335
- 335 - else:
336
- 336 - if st.session_state.products:
337
- 337 - for prod_id, product in st.session_state.products.items():
338
- 338 - with st.expander(f"🎯 {product['data']['name']}"):
339
- 339 - col1, col2 = st.columns(2)
340
- 340 -
341
- 341 - with col1:
342
- 342 - st.subheader("Product Details")
343
- 343 - st.write(f"Category: {product['data']['category']}")
344
- 344 - st.write(f"Target: {', '.join(product['data']['target_audience'])}")
345
- 345 - st.write(f"Description: {product['data']['description']}")
346
- 346 -
347
- 347 - with col2:
348
- 348 - st.subheader("Insights")
349
- 349 - st.metric("Opportunity Score", f"{product['insights']['market_opportunity']}/10")
350
- 350 - st.metric("Suggested Price", f"${product['insights']['suggested_price']}")
351
- 351 -
352
- 352 - st.write("**Risk Factors:**")
353
- 353 - for risk in product['insights']['risk_factors']:
354
- 354 - st.write(f"- {risk}")
355
- 355 -
356
- 356 - st.write("**Next Steps:**")
357
- 357 - for step in product['insights']['next_steps']:
358
- 358 - st.write(f"- {step}")
359
- 359 - else:
360
- 360 - st.info("No products yet. Create one to get started!")
361
- 361 -
362
- 362 -
363
- 363 -
364
- 364 Β 
365
- 365 - def generate_response(self, prompt: str, context: list = None) -> str:
366
- 366 - if not self.model or not self.tokenizer:
367
- 367 - return "LLM not initialized. Please check model configuration."
368
- 368 -
369
- 369 - # Prepare conversation context
370
- 370 - if context is None:
371
- 371 - context = []
372
- 372 -
373
- 373 - # Create full prompt with conversation history
374
- 374 - full_prompt = "".join([f"{msg['role']}: {msg['content']}\n" for msg in context])
375
- 375 - full_prompt += f"user: {prompt}\nassistant: "
376
- 376 -
377
- 377 - # Tokenize input
378
- 378 - input_ids = self.tokenizer(full_prompt, return_tensors="pt").input_ids.to(self.model.device)
379
- 379 -
380
- 380 - # Generate response
381
- 381 - try:
382
- 382 - output = self.model.generate(
383
- 383 - input_ids,
384
- 384 - max_length=500,
385
- 385 - num_return_sequences=1,
386
- 386 - no_repeat_ngram_size=2,
387
- 387 - temperature=0.7,
388
- 388 - top_p=0.9
389
- 389 - )
390
- 390 -
391
- 391 - # Decode response
392
- 392 - response = self.tokenizer.decode(output[0], skip_special_tokens=True)
393
- 393 -
394
- 394 - # Extract only the new part of the response
395
- 395 - response = response[len(full_prompt):].strip()
396
- 396 -
397
- 397 - return response
398
- 398 - except Exception as e:
399
- 399 - return f"Response generation error: {e}"
400
- 400 -
401
- 401 - def render_chat():
402
- 402 - st.header("πŸ’¬AI Business Mentor")
403
- 403 - st.title("πŸ€– Prospira AI Business Mentor")
404
- 404 -
405
- 405 - iframe_code = """
406
- 406 - <iframe
407
- 407 - src="https://demoorganisation34-vinay.hf.space"
408
- 408 - frameborder="0"
409
- 409 - width="850"
410
- 410 - height="450"
411
- 411 - ></iframe>
412
- 412 -
413
- 413 -
414
- 414 - """
415
- 415 - components.html(iframe_code, height=600)
416
- 416 -
417
- 417 - def render_home():
418
- 418 - st.title("πŸš€ Welcome to Prospira")
419
- 419 - st.subheader("πŸ“Š Data-Driven Solutions for Businesses and Creators")
420
- 420 - st.markdown("""
421
- 421 - **Prospira** empowers businesses and creators to enhance their content, products, and marketing strategies using AI-driven insights.
422
- 422 -
423
- 423 - ### **✨ Key Features**
424
- 424 - - **πŸ“ˆ Performance Analytics:** Real-time insights into business metrics.
425
- 425 - - **πŸ”Ž Competitive Analysis:** Benchmark your business against competitors.
426
- 426 - - **πŸ’‘ Smart Product Ideas:** AI-generated recommendations for future products and content.
427
- 427 - - **🧠 AI Business Mentor:** Personalized AI guidance for strategy and growth.
428
- 428 - Explore how **Prospira** can help optimize your decision-making and drive success! πŸ’‘πŸš€
429
- 429 - """)
430
- 430 Β 
431
- 431 Β  def main():
432
- 432 Β  st.set_page_config(
433
- @@ -450,5 +30,6 @@ def main():
434
- 450 Β  elif page == "Chat":
435
- 451 Β  render_chat()
436
- 452 Β 
437
- Β 
438
- 453 Β  if __name__ == "__main__":
439
- 454 Β  main()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Here's the code without line numbers:
2
+
3
+ ```python
4
  import streamlit as st
5
+ import plotly.express as px
6
+ import plotly.graph_objects as go
7
+ import pandas as pd
8
+ import numpy as np
9
+ from datetime import datetime, timedelta
10
+ from typing import Dict, List, Any
11
+ import streamlit as st
12
+ import streamlit.components.v1 as components
13
+
14
+ # --- Data Processing Class ---
15
+ class DataProcessor:
16
+ def __init__(self):
17
+ self.data = None
18
+ self.numeric_columns = []
19
+ self.categorical_columns = []
20
+
21
+ self.date_columns = []
22
+
23
+ def load_data(self, file) -> bool:
24
+ try:
25
+ self.data = pd.read_csv(file)
26
+ self._classify_columns()
27
+ return True
28
+ except Exception as e:
29
+ st.error(f"Error loading data: {str(e)}")
30
+ return False
31
+
32
+ def _classify_columns(self):
33
+ for col in self.data.columns:
34
+ if pd.api.types.is_numeric_dtype(self.data[col]):
35
+ self.numeric_columns.append(col)
36
+ elif pd.api.types.is_datetime64_any_dtype(self.data[col]):
37
+ self.date_columns.append(col)
38
+ else:
39
+ try:
40
+ pd.to_datetime(self.data[col])
41
+ self.date_columns.append(col)
42
+ except:
43
+ self.categorical_columns.append(col)
44
+
45
+ def get_basic_stats(self) -> Dict[str, Any]:
46
+ if self.data is None:
47
+ return {}
48
+
49
+ stats = {
50
+ 'summary': self.data[self.numeric_columns].describe(),
51
+ 'missing_values': self.data.isnull().sum(),
52
+ 'row_count': len(self.data),
53
+ 'column_count': len(self.data.columns)
54
+ }
55
+ return stats
56
+
57
+ def create_visualization(self, chart_type: str, x_col: str, y_col: str, color_col: str = None) -> go.Figure:
58
+ if chart_type == "Line Plot":
59
+ fig = px.line(self.data, x=x_col, y=y_col, color=color_col)
60
+ elif chart_type == "Bar Plot":
61
+ fig = px.bar(self.data, x=x_col, y=y_col, color=color_col)
62
+ elif chart_type == "Scatter Plot":
63
+ fig = px.scatter(self.data, x=x_col, y=y_col, color=color_col)
64
+ elif chart_type == "Box Plot":
65
+ fig = px.box(self.data, x=x_col, y=y_col, color=color_col)
66
+ else:
67
+ fig = px.histogram(self.data, x=x_col, color=color_col)
68
+
69
+ return fig
70
+
71
+ class BrainstormManager:
72
+ def __init__(self):
73
+ if 'products' not in st.session_state:
74
+ st.session_state.products = {}
75
+
76
+ def generate_product_form(self) -> Dict:
77
+ with st.form("product_form"):
78
+ basic_info = {
79
+ "name": st.text_input("Product Name"),
80
+ "category": st.selectbox("Category", ["Digital", "Physical", "Service"]),
81
+ "description": st.text_area("Description"),
82
+ "target_audience": st.multiselect("Target Audience",
83
+ ["Students", "Professionals", "Businesses", "Seniors", "Youth"]),
84
+ "price_range": st.slider("Price Range ($)", 0, 1000, (50, 200)),
85
+ "launch_date": st.date_input("Expected Launch Date")
86
+ }
87
+
88
+ st.subheader("Market Analysis")
89
+ market_analysis = {
90
+ "competitors": st.text_area("Main Competitors (one per line)"),
91
+ "unique_features": st.text_area("Unique Selling Points"),
92
+ "market_size": st.selectbox("Market Size",
93
+ ["Small", "Medium", "Large", "Enterprise"]),
94
+ "growth_potential": st.slider("Growth Potential", 1, 10)
95
+ }
96
+
97
+ submitted = st.form_submit_button("Save Product")
98
+ return basic_info, market_analysis, submitted
99
+
100
+ def analyze_product(self, product_data: Dict) -> Dict:
101
+ insights = {
102
+ "market_opportunity": self._calculate_opportunity_score(product_data),
103
+ "suggested_price": self._suggest_price(product_data),
104
+ "risk_factors": self._identify_risks(product_data),
105
+ "next_steps": self._generate_next_steps(product_data)
106
+ }
107
+ return insights
108
+
109
+ def _calculate_opportunity_score(self, data: Dict) -> int:
110
+ score = 0
111
+ if data.get("market_size") == "Large":
112
+ score += 3
113
+ if len(data.get("target_audience", [])) >= 2:
114
+ score += 2
115
+ if data.get("growth_potential", 0) > 7:
116
+ score += 2
117
+ return min(score, 10)
118
+
119
+ def _suggest_price(self, data: Dict) -> float:
120
+ base_price = sum(data.get("price_range", (0, 0))) / 2
121
+ if data.get("market_size") == "Enterprise":
122
+ base_price *= 1.5
123
+ return round(base_price, 2)
124
+
125
+ def _identify_risks(self, data: Dict) -> List[str]:
126
+ risks = []
127
+ if data.get("competitors"):
128
+ risks.append("Competitive market - differentiation crucial")
129
+ if len(data.get("target_audience", [])) < 2:
130
+ risks.append("Narrow target audience - consider expansion")
131
+ return risks
132
+
133
+ def _generate_next_steps(self, data: Dict) -> List[str]:
134
+ steps = [
135
+ "Create detailed product specification",
136
+ "Develop MVP timeline",
137
+ "Plan marketing strategy"
138
+ ]
139
+ if data.get("market_size") == "Enterprise":
140
+ steps.append("Prepare enterprise sales strategy")
141
+ return steps
142
+
143
+ # --- Sample Data Generation ---
144
+ def generate_sample_data():
145
+ dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
146
+ return pd.DataFrame({
147
+ 'Date': dates,
148
+ 'Revenue': np.random.normal(1000, 100, len(dates)),
149
+ 'Users': np.random.randint(100, 200, len(dates)),
150
+ 'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
151
+ 'Category': np.random.choice(['A', 'B', 'C'], len(dates))
152
+ })
153
+
154
+ # --- Page Rendering Functions ---
155
+ def render_dashboard():
156
+ st.header("πŸ“Š Comprehensive Business Performance Dashboard")
157
+
158
+ # Generate sample data with more complex structure
159
+ data = generate_sample_data()
160
+ data['Profit_Margin'] = data['Revenue'] * np.random.uniform(0.1, 0.3, len(data))
161
+
162
+ # Top-level KPI Section
163
+ col1, col2, col3, col4 = st.columns(4)
164
+ with col1:
165
+ st.metric("Total Revenue",
166
+ f"${data['Revenue'].sum():,.2f}",
167
+ delta=f"{data['Revenue'].pct_change().mean()*100:.2f}%")
168
+ with col2:
169
+ st.metric("Total Users",
170
+ f"{data['Users'].sum():,}",
171
+ delta=f"{data['Users'].pct_change().mean()*100:.2f}%")
172
+ with col3:
173
+ st.metric("Avg Engagement",
174
+ f"{data['Engagement'].mean():.2%}",
175
+ delta=f"{data['Engagement'].pct_change().mean()*100:.2f}%")
176
+ with col4:
177
+ st.metric("Profit Margin",
178
+ f"{data['Profit_Margin'].mean():.2%}",
179
+ delta=f"{data['Profit_Margin'].pct_change().mean()*100:.2f}%")
180
+
181
+ # Visualization Grid
182
+ col1, col2 = st.columns(2)
183
+
184
+ with col1:
185
+ st.subheader("Revenue & Profit Trends")
186
+ fig_revenue = go.Figure()
187
+ fig_revenue.add_trace(go.Scatter(
188
+ x=data['Date'],
189
+ y=data['Revenue'],
190
+ mode='lines',
191
+ name='Revenue',
192
+ line=dict(color='blue')
193
+ ))
194
+ fig_revenue.add_trace(go.Scatter(
195
+ x=data['Date'],
196
+ y=data['Profit_Margin'],
197
+ mode='lines',
198
+ name='Profit Margin',
199
+ line=dict(color='green')
200
+ ))
201
+ fig_revenue.update_layout(height=350)
202
+ st.plotly_chart(fig_revenue, use_container_width=True)
203
+
204
+ with col2:
205
+ st.subheader("User Engagement Analysis")
206
+ fig_engagement = px.scatter(
207
+ data,
208
+ x='Users',
209
+ y='Engagement',
210
+ color='Category',
211
+ size='Revenue',
212
+ hover_data=['Date'],
213
+ title='User Engagement Dynamics'
214
+ )
215
+ fig_engagement.update_layout(height=350)
216
+ st.plotly_chart(fig_engagement, use_container_width=True)
217
+
218
+ # Category Performance
219
+ st.subheader("Category Performance Breakdown")
220
+ category_performance = data.groupby('Category').agg({
221
+ 'Revenue': 'sum',
222
+ 'Users': 'sum',
223
+ 'Engagement': 'mean'
224
+ }).reset_index()
225
+
226
+ fig_category = px.bar(
227
+ category_performance,
228
+ x='Category',
229
+ y='Revenue',
230
+ color='Engagement',
231
+ title='Revenue by Category with Engagement Overlay'
232
+ )
233
+ st.plotly_chart(fig_category, use_container_width=True)
234
+
235
+ # Bottom Summary
236
+ st.subheader("Quick Insights")
237
+ insights_col1, insights_col2 = st.columns(2)
238
+
239
+ with insights_col1:
240
+ st.metric("Top Performing Category",
241
+ category_performance.loc[category_performance['Revenue'].idxmax(), 'Category'])
242
+
243
+ with insights_col2:
244
+ st.metric("Highest Engagement Category",
245
+ category_performance.loc[category_performance['Engagement'].idxmax(), 'Category'])
246
+
247
+ def render_analytics():
248
+ st.header("πŸ” Data Analytics")
249
+
250
+ processor = DataProcessor()
251
+ uploaded_file = st.file_uploader("Upload your CSV data", type=['csv'])
252
+
253
+ if uploaded_file is not None:
254
+ if processor.load_data(uploaded_file):
255
+ st.success("Data loaded successfully!")
256
+
257
+ tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"])
258
+
259
+ with tabs[0]:
260
+ st.subheader("Data Preview")
261
+ st.dataframe(processor.data.head())
262
+ st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}")
263
+
264
+ with tabs[1]:
265
+ st.subheader("Basic Statistics")
266
+ stats = processor.get_basic_stats()
267
+ st.write(stats['summary'])
268
+
269
+ st.subheader("Missing Values")
270
+ st.write(stats['missing_values'])
271
+
272
+ with tabs[2]:
273
+ st.subheader("Create Visualization")
274
+ col1, col2, col3 = st.columns(3)
275
+
276
+ with col1:
277
+ chart_type = st.selectbox(
278
+ "Select Chart Type",
279
+ ["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"]
280
+ )
281
+
282
+ with col2:
283
+ x_col = st.selectbox("Select X-axis", processor.data.columns)
284
+
285
+ with col3:
286
+ y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None
287
+
288
+ color_col = st.selectbox("Select Color Variable (optional)",
289
+ ['None'] + processor.categorical_columns)
290
+ color_col = None if color_col == 'None' else color_col
291
+
292
+ fig = processor.create_visualization(
293
+ chart_type,
294
+ x_col,
295
+ y_col if y_col else x_col,
296
+ color_col
297
+ )
298
+ st.plotly_chart(fig, use_container_width=True)
299
+
300
+ with tabs[3]:
301
+ st.subheader("Column Metrics")
302
+ selected_col = st.selectbox("Select column", processor.numeric_columns)
303
+
304
+ metrics = {
305
+ 'Mean': processor.data[selected_col].mean(),
306
+ 'Median': processor.data[selected_col].median(),
307
+ 'Std Dev': processor.data[selected_col].std(),
308
+ 'Min': processor.data[selected_col].min(),
309
+ 'Max': processor.data[selected_col].max()
310
+ }
311
+
312
+ cols = st.columns(len(metrics))
313
+ for col, (metric, value) in zip(cols, metrics.items()):
314
+ col.metric(metric, f"{value:.2f}")
315
+
316
+ def render_brainstorm_page():
317
+ st.title("Product Brainstorm Hub")
318
+ manager = BrainstormManager()
319
+
320
+ action = st.sidebar.radio("Action", ["View Products", "Create New Product"])
321
+
322
+ if action == "Create New Product":
323
+ basic_info, market_analysis, submitted = manager.generate_product_form()
324
+
325
+ if submitted:
326
+ product_data = {**basic_info, **market_analysis}
327
+ insights = manager.analyze_product(product_data)
328
+
329
+ product_id = f"prod_{len(st.session_state.products)}"
330
+ st.session_state.products[product_id] = {
331
+ "data": product_data,
332
+ "insights": insights,
333
+ "created_at": str(datetime.now())
334
+ }
335
+
336
+ st.success("Product added! View insights in the Products tab.")
337
+
338
+ else:
339
+ if st.session_state.products:
340
+ for prod_id, product in st.session_state.products.items():
341
+ with st.expander(f"🎯 {product['data']['name']}"):
342
+ col1, col2 = st.columns(2)
343
+
344
+ with col1:
345
+ st.subheader("Product Details")
346
+ st.write(f"Category: {product['data']['category']}")
347
+ st.write(f"Target: {', '.join(product['data']['target_audience'])}")
348
+ st.write(f"Description: {product['data']['description']}")
349
+
350
+ with col2:
351
+ st.subheader("Insights")
352
+ st.metric("Opportunity Score", f"{product['insights']['market_opportunity']}/10")
353
+ st.metric("Suggested Price", f"${product['insights']['suggested_price']}")
354
+
355
+ st.write("**Risk Factors:**")
356
+ for risk in product['insights']['risk_factors']:
357
+ st.write(f"- {risk}")
358
+
359
+ st.write("**Next Steps:**")
360
+ for step in product['insights']['next_steps']:
361
+ st.write(f"- {step}")
362
+ else:
363
+ st.info("No products yet. Create one to get started!")
364
+
365
+ def generate_response(self, prompt: str, context: list = None) -> str:
366
+ if not self.model or not self.tokenizer:
367
+ return "LLM not initialized. Please check model configuration."
368
+
369
+ # Prepare conversation context
370
+ if context is None:
371
+ context = []
372
+
373
+ # Create full prompt with conversation history
374
+ full_prompt = "".join([f"{msg['role']}: {msg['content']}\n" for msg in context])
375
+ full_prompt += f"user: {prompt}\nassistant: "
376
+
377
+ # Tokenize input
378
+ input_ids = self.tokenizer(full_prompt, return_tensors="pt").input_ids.to(self.model.device)
379
+
380
+ # Generate response
381
+ try:
382
+ output = self.model.generate(
383
+ input_ids,
384
+ max_length=500,
385
+ num_return_sequences=1,
386
+ no_repeat_ngram_size=2,
387
+ temperature=0.7,
388
+ top_p=0.9
389
+ )
390
+
391
+ # Decode response
392
+ response = self.tokenizer.decode(output[0], skip_special_tokens=True)
393
+
394
+ # Extract only the new part of the response
395
+ response = response[len(full_prompt):].strip()
396
+
397
+ return response
398
+ except Exception as e:
399
+ return f"Response generation error: {e}"
400
+
401
+ def render_chat():
402
+ st.header("πŸ’¬AI Business Mentor")
403
+ st.title("πŸ€– Prospira AI Business Mentor")
404
+
405
+ iframe_code = """
406
+ <iframe
407
+ src="https://demoorganisation34-vinay.hf.space"
408
+ frameborder="0"
409
+ width="850"
410
+ height="450"
411
+ ></iframe>
412
+
413
+
414
+ """
415
+ components.html(iframe_code, height=600)
416
+
417
+ def render_home():
418
+ st.title("πŸš€ Welcome to Prospira")
419
+ st.subheader("πŸ“Š Data-Driven Solutions for Businesses and Creators")
420
+ st.markdown("""
421
+ **Prospira** empowers businesses and creators to enhance their content, products, and marketing strategies using AI-driven insights.
422
+
423
+ ### **✨ Key Features**
424
+ - **πŸ“ˆ Performance Analytics:** Real-time insights into business metrics.
425
+ - **πŸ”Ž Competitive Analysis:** Benchmark your business against competitors.
426
+ - **πŸ’‘ Smart Product Ideas:** AI-generated recommendations for future products and content.
427
+ - **🧠 AI Business Mentor:** Personalized AI guidance for strategy and growth.
428
+ Explore how **Prospira** can help optimize your decision-making and drive success! πŸ’‘πŸš€
429
+ """)
430
+
431
+ def main():
432
+ st.set_page_config(
433
+ page_title="Prospira",
434
+ page_icon="πŸš€",
435
+ layout="wide"
436
+ )
437
+
438
+ st.sidebar.title("Navigation")
439
+ page = st.sidebar.radio("Go to", ["Home", "Dashboard", "Analytics", "Brainstorm", "Chat"])
440
+
441
+ if page == "Home":
442
+ render_home()
443
+ elif page == "Dashboard":
444
+ render_dashboard()
445
+ elif page == "Analytics":
446
+ render_analytics()
447
+ elif page == "Brainstorm":
448
+ render_brainstorm_page()
449
+ elif page == "Chat":
450
+ render_chat()
451
+
452
+ if __name__ == "__main__":
453
+ main()
454
+ ```