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 |
+
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()
|