Prospea / app.py
Pranav0111's picture
Update app.py
b6425ec verified
raw
history blame
19.2 kB
import streamlit as st
2 - import plotly.express as px
3 - import plotly.graph_objects as go
4 - import pandas as pd
5 - import numpy as np
6 - from datetime import datetime, timedelta
7 - from typing import Dict, List, Any
8 - import streamlit as st
9 - import streamlit.components.v1 as components
10 -
11 - # --- Data Processing Class ---
12 - class DataProcessor:
13 - def __init__(self):
14 - self.data = None
15 - self.numeric_columns = []
16 - self.categorical_columns = []
17 -
18 - self.date_columns = []
19 -
20 - def load_data(self, file) -> bool:
21 - try:
22 - self.data = pd.read_csv(file)
23 - self._classify_columns()
24 - return True
25 - except Exception as e:
26 - st.error(f"Error loading data: {str(e)}")
27 - return False
28 -
29 - def _classify_columns(self):
30 - for col in self.data.columns:
31 - if pd.api.types.is_numeric_dtype(self.data[col]):
32 - self.numeric_columns.append(col)
33 - elif pd.api.types.is_datetime64_any_dtype(self.data[col]):
34 - self.date_columns.append(col)
35 - else:
36 - try:
37 - pd.to_datetime(self.data[col])
38 - self.date_columns.append(col)
39 - except:
40 - self.categorical_columns.append(col)
41 -
42 - def get_basic_stats(self) -> Dict[str, Any]:
43 - if self.data is None:
44 - return {}
45 -
46 - stats = {
47 - 'summary': self.data[self.numeric_columns].describe(),
48 - 'missing_values': self.data.isnull().sum(),
49 - 'row_count': len(self.data),
50 - 'column_count': len(self.data.columns)
51 - }
52 - return stats
53 -
54 - def create_visualization(self, chart_type: str, x_col: str, y_col: str, color_col: str = None) -> go.Figure:
55 - if chart_type == "Line Plot":
56 - fig = px.line(self.data, x=x_col, y=y_col, color=color_col)
57 - elif chart_type == "Bar Plot":
58 - fig = px.bar(self.data, x=x_col, y=y_col, color=color_col)
59 - elif chart_type == "Scatter Plot":
60 - fig = px.scatter(self.data, x=x_col, y=y_col, color=color_col)
61 - elif chart_type == "Box Plot":
62 - fig = px.box(self.data, x=x_col, y=y_col, color=color_col)
63 - else:
64 - fig = px.histogram(self.data, x=x_col, color=color_col)
65 -
66 - return fig
67 -
68 - class BrainstormManager:
69 - def __init__(self):
70 - if 'products' not in st.session_state:
71 - st.session_state.products = {}
72 -
73 - def generate_product_form(self) -> Dict:
74 - with st.form("product_form"):
75 - basic_info = {
76 - "name": st.text_input("Product Name"),
77 - "category": st.selectbox("Category", ["Digital", "Physical", "Service"]),
78 - "description": st.text_area("Description"),
79 - "target_audience": st.multiselect("Target Audience",
80 - ["Students", "Professionals", "Businesses", "Seniors", "Youth"]),
81 - "price_range": st.slider("Price Range ($)", 0, 1000, (50, 200)),
82 - "launch_date": st.date_input("Expected Launch Date")
83 - }
84 -
85 - st.subheader("Market Analysis")
86 - market_analysis = {
87 - "competitors": st.text_area("Main Competitors (one per line)"),
88 - "unique_features": st.text_area("Unique Selling Points"),
89 - "market_size": st.selectbox("Market Size",
90 - ["Small", "Medium", "Large", "Enterprise"]),
91 - "growth_potential": st.slider("Growth Potential", 1, 10)
92 - }
93 -
94 - submitted = st.form_submit_button("Save Product")
95 - return basic_info, market_analysis, submitted
96 -
97 - def analyze_product(self, product_data: Dict) -> Dict:
98 - insights = {
99 - "market_opportunity": self._calculate_opportunity_score(product_data),
100 - "suggested_price": self._suggest_price(product_data),
101 - "risk_factors": self._identify_risks(product_data),
102 - "next_steps": self._generate_next_steps(product_data)
103 - }
104 - return insights
105 -
106 - def _calculate_opportunity_score(self, data: Dict) -> int:
107 - score = 0
108 - if data.get("market_size") == "Large":
109 - score += 3
110 - if len(data.get("target_audience", [])) >= 2:
111 - score += 2
112 - if data.get("growth_potential", 0) > 7:
113 - score += 2
114 - return min(score, 10)
115 -
116 - def _suggest_price(self, data: Dict) -> float:
117 - base_price = sum(data.get("price_range", (0, 0))) / 2
118 - if data.get("market_size") == "Enterprise":
119 - base_price *= 1.5
120 - return round(base_price, 2)
121 -
122 - def _identify_risks(self, data: Dict) -> List[str]:
123 - risks = []
124 - if data.get("competitors"):
125 - risks.append("Competitive market - differentiation crucial")
126 - if len(data.get("target_audience", [])) < 2:
127 - risks.append("Narrow target audience - consider expansion")
128 - return risks
129 -
130 - def _generate_next_steps(self, data: Dict) -> List[str]:
131 - steps = [
132 - "Create detailed product specification",
133 - "Develop MVP timeline",
134 - "Plan marketing strategy"
135 - ]
136 - if data.get("market_size") == "Enterprise":
137 - steps.append("Prepare enterprise sales strategy")
138 - return steps
139 -
140 - # --- Sample Data Generation ---
141 - def generate_sample_data():
142 - dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
143 - return pd.DataFrame({
144 - 'Date': dates,
145 - 'Revenue': np.random.normal(1000, 100, len(dates)),
146 - 'Users': np.random.randint(100, 200, len(dates)),
147 - 'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
148 - 'Category': np.random.choice(['A', 'B', 'C'], len(dates))
149 - })
150 -
151 - # --- Page Rendering Functions ---
152 - def render_dashboard():
153 - st.header("πŸ“Š Comprehensive Business Performance Dashboard")
154 -
155 - # Generate sample data with more complex structure
156 - data = generate_sample_data()
157 - data['Profit_Margin'] = data['Revenue'] * np.random.uniform(0.1, 0.3, len(data))
158 -
159 - # Top-level KPI Section
160 - col1, col2, col3, col4 = st.columns(4)
161 - with col1:
162 - st.metric("Total Revenue",
163 - f"${data['Revenue'].sum():,.2f}",
164 - delta=f"{data['Revenue'].pct_change().mean()*100:.2f}%")
165 - with col2:
166 - st.metric("Total Users",
167 - f"{data['Users'].sum():,}",
168 - delta=f"{data['Users'].pct_change().mean()*100:.2f}%")
169 - with col3:
170 - st.metric("Avg Engagement",
171 - f"{data['Engagement'].mean():.2%}",
172 - delta=f"{data['Engagement'].pct_change().mean()*100:.2f}%")
173 - with col4:
174 - st.metric("Profit Margin",
175 - f"{data['Profit_Margin'].mean():.2%}",
176 - delta=f"{data['Profit_Margin'].pct_change().mean()*100:.2f}%")
177 -
178 - # Visualization Grid
179 - col1, col2 = st.columns(2)
180 -
181 - with col1:
182 - st.subheader("Revenue & Profit Trends")
183 - fig_revenue = go.Figure()
184 - fig_revenue.add_trace(go.Scatter(
185 - x=data['Date'],
186 - y=data['Revenue'],
187 - mode='lines',
188 - name='Revenue',
189 - line=dict(color='blue')
190 - ))
191 - fig_revenue.add_trace(go.Scatter(
192 - x=data['Date'],
193 - y=data['Profit_Margin'],
194 - mode='lines',
195 - name='Profit Margin',
196 - line=dict(color='green')
197 - ))
198 - fig_revenue.update_layout(height=350)
199 - st.plotly_chart(fig_revenue, use_container_width=True)
200 -
201 - with col2:
202 - st.subheader("User Engagement Analysis")
203 - fig_engagement = px.scatter(
204 - data,
205 - x='Users',
206 - y='Engagement',
207 - color='Category',
208 - size='Revenue',
209 - hover_data=['Date'],
210 - title='User Engagement Dynamics'
211 - )
212 - fig_engagement.update_layout(height=350)
213 - st.plotly_chart(fig_engagement, use_container_width=True)
214 -
215 - # Category Performance
216 - st.subheader("Category Performance Breakdown")
217 - category_performance = data.groupby('Category').agg({
218 - 'Revenue': 'sum',
219 - 'Users': 'sum',
220 - 'Engagement': 'mean'
221 - }).reset_index()
222 -
223 - fig_category = px.bar(
224 - category_performance,
225 - x='Category',
226 - y='Revenue',
227 - color='Engagement',
228 - title='Revenue by Category with Engagement Overlay'
229 - )
230 - st.plotly_chart(fig_category, use_container_width=True)
231 -
232 - # Bottom Summary
233 - st.subheader("Quick Insights")
234 - insights_col1, insights_col2 = st.columns(2)
235 -
236 - with insights_col1:
237 - st.metric("Top Performing Category",
238 - category_performance.loc[category_performance['Revenue'].idxmax(), 'Category'])
239 -
240 - with insights_col2:
241 - st.metric("Highest Engagement Category",
242 - category_performance.loc[category_performance['Engagement'].idxmax(), 'Category'])
243 -
244 - def render_analytics():
245 - st.header("πŸ” Data Analytics")
246 -
247 - processor = DataProcessor()
248 - uploaded_file = st.file_uploader("Upload your CSV data", type=['csv'])
249 -
250 - if uploaded_file is not None:
251 - if processor.load_data(uploaded_file):
252 - st.success("Data loaded successfully!")
253 -
254 - tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"])
255 -
256 - with tabs[0]:
257 - st.subheader("Data Preview")
258 - st.dataframe(processor.data.head())
259 - st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}")
260 -
261 - with tabs[1]:
262 - st.subheader("Basic Statistics")
263 - stats = processor.get_basic_stats()
264 - st.write(stats['summary'])
265 -
266 - st.subheader("Missing Values")
267 - st.write(stats['missing_values'])
268 -
269 - with tabs[2]:
270 - st.subheader("Create Visualization")
271 - col1, col2, col3 = st.columns(3)
272 -
273 - with col1:
274 - chart_type = st.selectbox(
275 - "Select Chart Type",
276 - ["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"]
277 - )
278 -
279 - with col2:
280 - x_col = st.selectbox("Select X-axis", processor.data.columns)
281 -
282 - with col3:
283 - y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None
284 -
285 - color_col = st.selectbox("Select Color Variable (optional)",
286 - ['None'] + processor.categorical_columns)
287 - color_col = None if color_col == 'None' else color_col
288 -
289 - fig = processor.create_visualization(
290 - chart_type,
291 - x_col,
292 - y_col if y_col else x_col,
293 - color_col
294 - )
295 - st.plotly_chart(fig, use_container_width=True)
296 -
297 - with tabs[3]:
298 - st.subheader("Column Metrics")
299 - selected_col = st.selectbox("Select column", processor.numeric_columns)
300 -
301 - metrics = {
302 - 'Mean': processor.data[selected_col].mean(),
303 - 'Median': processor.data[selected_col].median(),
304 - 'Std Dev': processor.data[selected_col].std(),
305 - 'Min': processor.data[selected_col].min(),
306 - 'Max': processor.data[selected_col].max()
307 - }
308 -
309 - cols = st.columns(len(metrics))
310 - for col, (metric, value) in zip(cols, metrics.items()):
311 - col.metric(metric, f"{value:.2f}")
312 -
313 - def render_brainstorm_page():
314 - st.title("Product Brainstorm Hub")
315 - manager = BrainstormManager()
316 -
317 - action = st.sidebar.radio("Action", ["View Products", "Create New Product"])
318 -
319 - if action == "Create New Product":
320 - basic_info, market_analysis, submitted = manager.generate_product_form()
321 -
322 - if submitted:
323 - product_data = {**basic_info, **market_analysis}
324 - insights = manager.analyze_product(product_data)
325 -
326 - product_id = f"prod_{len(st.session_state.products)}"
327 - st.session_state.products[product_id] = {
328 - "data": product_data,
329 - "insights": insights,
330 - "created_at": str(datetime.now())
331 - }
332 -
333 - st.success("Product added! View insights in the Products tab.")
334 -
335 - else:
336 - if st.session_state.products:
337 - for prod_id, product in st.session_state.products.items():
338 - with st.expander(f"🎯 {product['data']['name']}"):
339 - col1, col2 = st.columns(2)
340 -
341 - with col1:
342 - st.subheader("Product Details")
343 - st.write(f"Category: {product['data']['category']}")
344 - st.write(f"Target: {', '.join(product['data']['target_audience'])}")
345 - st.write(f"Description: {product['data']['description']}")
346 -
347 - with col2:
348 - st.subheader("Insights")
349 - st.metric("Opportunity Score", f"{product['insights']['market_opportunity']}/10")
350 - st.metric("Suggested Price", f"${product['insights']['suggested_price']}")
351 -
352 - st.write("**Risk Factors:**")
353 - for risk in product['insights']['risk_factors']:
354 - st.write(f"- {risk}")
355 -
356 - st.write("**Next Steps:**")
357 - for step in product['insights']['next_steps']:
358 - st.write(f"- {step}")
359 - else:
360 - st.info("No products yet. Create one to get started!")
361 -
362 -
363 -
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(
@@ -450,5 +30,6 @@ def main():
450 Β  elif page == "Chat":
451 Β  render_chat()
452 Β 
Β 
453 Β  if __name__ == "__main__":
454 Β  main()