File size: 12,081 Bytes
bc0d02b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import streamlit as st
import streamlit.components.v1 as components
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
from datetime import datetime

from data_processor import DataProcessor
from brainstorm_manager import BrainstormManager
from chatbot import ChatbotManager
from utils import generate_sample_data


def render_home():
    st.title("πŸš€ Welcome to Prospira")
    st.subheader("πŸ“Š Data-Driven Solutions for Businesses and Creators")
    st.markdown("""
    **Prospira** empowers businesses and creators to enhance their content, products, and marketing strategies using AI-driven insights.
    
    ### **✨ Key Features**
    - **πŸ“ˆ Performance Analytics:** Real-time insights into business metrics.
    - **πŸ”Ž Competitive Analysis:** Benchmark your business against competitors.
    - **πŸ’‘ Smart Product Ideas:** AI-generated recommendations for future products and content.
    - **🧠 AI Business Mentor:** Personalized AI guidance for strategy and growth.
    Explore how **Prospira** can help optimize your decision-making and drive success! πŸ’‘πŸš€
    """)


def render_dashboard():
    st.header("πŸ“Š Comprehensive Business Performance Dashboard")
    
    # Generate sample data with more complex structure
    data = generate_sample_data()
    data['Profit_Margin'] = data['Revenue'] * np.random.uniform(0.1, 0.3, len(data))
    
    # Top-level KPI Section
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        st.metric("Total Revenue", 
                  f"${data['Revenue'].sum():,.2f}", 
                  delta=f"{data['Revenue'].pct_change().mean()*100:.2f}%")
    with col2:
        st.metric("Total Users", 
                  f"{data['Users'].sum():,}", 
                  delta=f"{data['Users'].pct_change().mean()*100:.2f}%")
    with col3:
        st.metric("Avg Engagement", 
                  f"{data['Engagement'].mean():.2%}", 
                  delta=f"{data['Engagement'].pct_change().mean()*100:.2f}%")
    with col4:
        st.metric("Profit Margin", 
                  f"{data['Profit_Margin'].mean():.2%}", 
                  delta=f"{data['Profit_Margin'].pct_change().mean()*100:.2f}%")
    
    # Visualization Grid
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("Revenue & Profit Trends")
        fig_revenue = go.Figure()
        fig_revenue.add_trace(go.Scatter(
            x=data['Date'], 
            y=data['Revenue'], 
            mode='lines', 
            name='Revenue',
            line=dict(color='blue')
        ))
        fig_revenue.add_trace(go.Scatter(
            x=data['Date'], 
            y=data['Profit_Margin'], 
            mode='lines', 
            name='Profit Margin',
            line=dict(color='green')
        ))
        fig_revenue.update_layout(height=350)
        st.plotly_chart(fig_revenue, use_container_width=True)
    
    with col2:
        st.subheader("User Engagement Analysis")
        fig_engagement = px.scatter(
            data, 
            x='Users', 
            y='Engagement', 
            color='Category', 
            size='Revenue',
            hover_data=['Date'],
            title='User Engagement Dynamics'
        )
        fig_engagement.update_layout(height=350)
        st.plotly_chart(fig_engagement, use_container_width=True)
    
    # Category Performance
    st.subheader("Category Performance Breakdown")
    category_performance = data.groupby('Category').agg({
        'Revenue': 'sum',
        'Users': 'sum',
        'Engagement': 'mean'
    }).reset_index()
    
    fig_category = px.bar(
        category_performance, 
        x='Category', 
        y='Revenue', 
        color='Engagement',
        title='Revenue by Category with Engagement Overlay'
    )
    st.plotly_chart(fig_category, use_container_width=True)
    
    # Bottom Summary
    st.subheader("Quick Insights")
    insights_col1, insights_col2 = st.columns(2)
    
    with insights_col1:
        st.metric("Top Performing Category", 
                  category_performance.loc[category_performance['Revenue'].idxmax(), 'Category'])
    
    with insights_col2:
        st.metric("Highest Engagement Category", 
                  category_performance.loc[category_performance['Engagement'].idxmax(), 'Category'])


def render_analytics():
    st.header("πŸ” Data Analytics")
    
    processor = DataProcessor()
    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"])
            
            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)}")
            
            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'])
            
            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)
            
            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_page():
    st.title("Product Brainstorm Hub")
    manager = BrainstormManager()
    
    action = st.sidebar.radio("Action", ["View Products", "Create New Product"])
    
    if action == "Create New Product":
        basic_info, market_analysis, submitted = manager.generate_product_form()
        
        if submitted:
            product_data = {**basic_info, **market_analysis}
            insights = manager.analyze_product(product_data)
            
            product_id = f"prod_{len(st.session_state.products)}"
            st.session_state.products[product_id] = {
                "data": product_data,
                "insights": insights,
                "created_at": str(datetime.now())
            }
            
            st.success("Product added! View insights in the Products tab.")
    
    else:
        if st.session_state.products:
            for prod_id, product in st.session_state.products.items():
                with st.expander(f"🎯 {product['data']['name']}"):
                    col1, col2 = st.columns(2)
                    
                    with col1:
                        st.subheader("Product Details")
                        st.write(f"Category: {product['data']['category']}")
                        st.write(f"Target: {', '.join(product['data']['target_audience'])}")
                        st.write(f"Description: {product['data']['description']}")
                    
                    with col2:
                        st.subheader("Insights")
                        st.metric("Opportunity Score", f"{product['insights']['market_opportunity']}/10")
                        st.metric("Suggested Price", f"${product['insights']['suggested_price']}")
                        
                        st.write("**Risk Factors:**")
                        for risk in product['insights']['risk_factors']:
                            st.write(f"- {risk}")
                        
                        st.write("**Next Steps:**")
                        for step in product['insights']['next_steps']:
                            st.write(f"- {step}")
        else:
            st.info("No products yet. Create one to get started!")


def render_chat():
    st.header("πŸ’¬ AI Business Mentor")
    
    # Initialize chatbot manager
    chatbot = ChatbotManager()
    chatbot.initialize_chat()
    
    # Sidebar options
    st.sidebar.subheader("Chat Options")
    if st.sidebar.button("Clear Chat History"):
        chatbot.clear_chat()
        st.rerun()
    
    # Display chat history
    st.subheader("πŸ€– Conversation")
    
    # Chat container
    chat_container = st.container()
    
    with chat_container:
        # Display all messages
        for message in chatbot.get_chat_history():
            if message["role"] == "user":
                with st.chat_message("user"):
                    st.write(message["content"])
            else:
                with st.chat_message("assistant"):
                    st.write(message["content"])
    
    # Chat input
    user_input = st.chat_input("Ask me anything about business strategy, marketing, products, or operations...")
    
    if user_input:
        # Add user message
        chatbot.add_message("user", user_input)
        
        # Generate response
        with st.spinner("Thinking..."):
            response = chatbot.generate_business_response(user_input)
        
        # Add assistant response
        chatbot.add_message("assistant", response)
        
        # Rerun to update the display
        st.rerun()
    
    # Additional helpful sections
    st.markdown("---")
    st.subheader("πŸ’‘ Quick Business Topics")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("πŸ“Š Business Strategy"):
            chatbot.add_message("user", "I need help with business strategy")
            response = chatbot.generate_business_response("I need help with business strategy")
            chatbot.add_message("assistant", response)
            st.rerun()
    
    with col2:
        if st.button("πŸ“ˆ Marketing Tips"):
            chatbot.add_message("user", "Give me marketing advice")
            response = chatbot.generate_business_response("Give me marketing advice")
            chatbot.add_message("assistant", response)
            st.rerun()
    
    with col3:
        if st.button("πŸ’° Financial Planning"):
            chatbot.add_message("user", "Help with financial planning")
            response = chatbot.generate_business_response("Help with financial planning")
            chatbot.add_message("assistant", response)
            st.rerun()
    
    # Optional: Keep the iframe as alternative
    st.markdown("---")
    st.subheader("πŸ”— Alternative Chat Interface")
    st.info("You can also use the external chat interface below:")