import streamlit as st import plotly.express as px import plotly.graph_objects as go import pandas as pd import numpy as np from datetime import datetime, timedelta from typing import Dict, List, Any # --- Data Processing Class --- class DataProcessor: def __init__(self): self.data = None self.numeric_columns = [] self.categorical_columns = [] self.date_columns = [] def load_data(self, file) -> bool: try: self.data = pd.read_csv(file) self._classify_columns() return True except Exception as e: st.error(f"Error loading data: {str(e)}") return False def _classify_columns(self): for col in self.data.columns: if pd.api.types.is_numeric_dtype(self.data[col]): self.numeric_columns.append(col) elif pd.api.types.is_datetime64_any_dtype(self.data[col]): self.date_columns.append(col) else: try: pd.to_datetime(self.data[col]) self.date_columns.append(col) except: self.categorical_columns.append(col) def get_basic_stats(self) -> Dict[str, Any]: if self.data is None: return {} stats = { 'summary': self.data[self.numeric_columns].describe(), 'missing_values': self.data.isnull().sum(), 'row_count': len(self.data), 'column_count': len(self.data.columns) } return stats def create_visualization(self, chart_type: str, x_col: str, y_col: str, color_col: str = None) -> go.Figure: if chart_type == "Line Plot": fig = px.line(self.data, x=x_col, y=y_col, color=color_col) elif chart_type == "Bar Plot": fig = px.bar(self.data, x=x_col, y=y_col, color=color_col) elif chart_type == "Scatter Plot": fig = px.scatter(self.data, x=x_col, y=y_col, color=color_col) elif chart_type == "Box Plot": fig = px.box(self.data, x=x_col, y=y_col, color=color_col) else: fig = px.histogram(self.data, x=x_col, color=color_col) return fig # --- Sample Data Generation --- def generate_sample_data(): dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D') return pd.DataFrame({ 'Date': dates, 'Revenue': np.random.normal(1000, 100, len(dates)), 'Users': np.random.randint(100, 200, len(dates)), 'Engagement': np.random.uniform(0.5, 0.9, len(dates)), 'Category': np.random.choice(['A', 'B', 'C'], len(dates)) }) # --- Page Rendering Functions --- def render_dashboard(): st.header("📊 Performance Dashboard") data = generate_sample_data() # KPI Metrics col1, col2, col3, col4 = st.columns(4) with col1: st.metric("Total Revenue", f"${data['Revenue'].sum():,.2f}") with col2: st.metric("Total Users", f"{data['Users'].sum():,}") with col3: st.metric("Avg Engagement", f"{data['Engagement'].mean():.2%}") with col4: st.metric("Active Days", len(data)) # Charts col1, col2 = st.columns(2) with col1: st.subheader("Revenue Trend") fig = px.line(data, x='Date', y='Revenue') st.plotly_chart(fig, use_container_width=True) with col2: st.subheader("User Engagement by Category") fig = px.scatter(data, x='Date', y='Engagement', size='Users', color='Category') st.plotly_chart(fig, use_container_width=True) def render_analytics(): st.header("🔍 Data Analytics") processor = DataProcessor() # File upload uploaded_file = st.file_uploader("Upload your CSV data", type=['csv']) if uploaded_file is not None: if processor.load_data(uploaded_file): st.success("Data loaded successfully!") tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"]) # Data Preview Tab with tabs[0]: st.subheader("Data Preview") st.dataframe(processor.data.head()) st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}") # Statistics Tab with tabs[1]: st.subheader("Basic Statistics") stats = processor.get_basic_stats() st.write(stats['summary']) st.subheader("Missing Values") st.write(stats['missing_values']) # Visualization Tab with tabs[2]: st.subheader("Create Visualization") col1, col2, col3 = st.columns(3) with col1: chart_type = st.selectbox( "Select Chart Type", ["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"] ) with col2: x_col = st.selectbox("Select X-axis", processor.data.columns) with col3: y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None color_col = st.selectbox("Select Color Variable (optional)", ['None'] + processor.categorical_columns) color_col = None if color_col == 'None' else color_col fig = processor.create_visualization( chart_type, x_col, y_col if y_col else x_col, color_col ) st.plotly_chart(fig, use_container_width=True) # Metrics Tab with tabs[3]: st.subheader("Column Metrics") selected_col = st.selectbox("Select column", processor.numeric_columns) metrics = { 'Mean': processor.data[selected_col].mean(), 'Median': processor.data[selected_col].median(), 'Std Dev': processor.data[selected_col].std(), 'Min': processor.data[selected_col].min(), 'Max': processor.data[selected_col].max() } cols = st.columns(len(metrics)) for col, (metric, value) in zip(cols, metrics.items()): col.metric(metric, f"{value:.2f}") def render_brainstorm(): st.header("🧠 Product Brainstorm") # Product selection products = ["Product A", "Product B", "Product C", "Add New Product"] selected_product = st.selectbox("Select Product", products) if selected_product == "Add New Product": with st.form("new_product"): st.subheader("Add New Product") product_name = st.text_input("Product Name") product_desc = st.text_area("Product Description") product_category = st.selectbox("Category", ["Category A", "Category B", "Category C"]) if st.form_submit_button("Add Product"): st.success(f"Product '{product_name}' added successfully!") else: st.subheader(f"Analysis for {selected_product}") # Sample metrics col1, col2, col3 = st.columns(3) with col1: st.metric("Sales", "$12,345", "+10%") with col2: st.metric("Reviews", "4.5/5", "+0.2") with col3: st.metric("Engagement", "89%", "-2%") def render_chat(): st.header("💬 Business Assistant") # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Display chat history for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Chat input if prompt := st.chat_input("Ask about your business..."): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # Simple response (placeholder for LLM integration) response = f"Thank you for your question about '{prompt}'. The LLM integration will be implemented soon." with st.chat_message("assistant"): st.markdown(response) st.session_state.messages.append({"role": "assistant", "content": response}) # --- Main App --- def main(): st.set_page_config( page_title="Prospira", page_icon="📊", layout="wide", initial_sidebar_state="expanded" ) # Sidebar with st.sidebar: st.title("Prospira") st.subheader("Data-Driven Solutions") # Navigation page = st.radio( "Navigation", ["Dashboard", "Analytics", "Brainstorm", "Chat"] ) # Page routing if page == "Dashboard": render_dashboard() elif page == "Analytics": render_analytics() elif page == "Brainstorm": render_brainstorm() elif page == "Chat": render_chat() if __name__ == "__main__": main()