Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,123 +1,264 @@
|
|
1 |
import streamlit as st
|
2 |
import plotly.express as px
|
|
|
3 |
import pandas as pd
|
4 |
import numpy as np
|
5 |
from datetime import datetime, timedelta
|
6 |
-
from
|
7 |
|
8 |
-
#
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
st.title("Prospira π")
|
24 |
-
st.subheader("Navigation")
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
-
|
34 |
-
if st.button(f"{emoji} {page}"):
|
35 |
-
st.session_state['current_page'] = page
|
36 |
|
37 |
-
#
|
38 |
def generate_sample_data():
|
39 |
dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
|
40 |
return pd.DataFrame({
|
41 |
'Date': dates,
|
42 |
'Revenue': np.random.normal(1000, 100, len(dates)),
|
43 |
'Users': np.random.randint(100, 200, len(dates)),
|
44 |
-
'Engagement': np.random.uniform(0.5, 0.9, len(dates))
|
|
|
45 |
})
|
46 |
|
47 |
-
# Page
|
48 |
-
def
|
49 |
-
st.header("Dashboard")
|
50 |
-
col1, col2 = st.columns(2)
|
51 |
-
|
52 |
data = generate_sample_data()
|
53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
with col1:
|
55 |
st.subheader("Revenue Trend")
|
56 |
fig = px.line(data, x='Date', y='Revenue')
|
57 |
st.plotly_chart(fig, use_container_width=True)
|
58 |
|
59 |
with col2:
|
60 |
-
st.subheader("User Engagement")
|
61 |
-
fig = px.scatter(data, x='Date', y='Engagement',
|
|
|
62 |
st.plotly_chart(fig, use_container_width=True)
|
63 |
|
64 |
-
def
|
65 |
-
st.header("Analytics")
|
66 |
-
st.info("Select data for analysis:")
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
-
def
|
77 |
-
st.header("Brainstorm")
|
78 |
|
79 |
-
|
|
|
80 |
selected_product = st.selectbox("Select Product", products)
|
81 |
|
82 |
-
if selected_product:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
st.subheader(f"Analysis for {selected_product}")
|
84 |
-
st.write("Product performance metrics will appear here")
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
st.
|
|
|
|
|
|
|
|
|
90 |
|
91 |
-
def
|
92 |
-
st.header("
|
93 |
|
94 |
-
|
95 |
-
if
|
96 |
-
st.
|
97 |
-
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
|
|
100 |
def main():
|
101 |
-
st.set_page_config(
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
-
# Sidebar
|
104 |
-
st.sidebar
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
|
|
107 |
if page == "Dashboard":
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
elif page == "Data Analytics":
|
112 |
-
render_analytics_page()
|
113 |
-
|
114 |
elif page == "Brainstorm":
|
115 |
-
|
116 |
-
st.write("Brainstorm feature coming soon")
|
117 |
-
|
118 |
elif page == "Chat":
|
119 |
-
|
120 |
-
st.write("Chat feature coming soon")
|
121 |
|
122 |
if __name__ == "__main__":
|
123 |
main()
|
|
|
1 |
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 |
|
9 |
+
# --- Data Processing Class ---
|
10 |
+
class DataProcessor:
|
11 |
+
def __init__(self):
|
12 |
+
self.data = None
|
13 |
+
self.numeric_columns = []
|
14 |
+
self.categorical_columns = []
|
15 |
+
self.date_columns = []
|
16 |
+
|
17 |
+
def load_data(self, file) -> bool:
|
18 |
+
try:
|
19 |
+
self.data = pd.read_csv(file)
|
20 |
+
self._classify_columns()
|
21 |
+
return True
|
22 |
+
except Exception as e:
|
23 |
+
st.error(f"Error loading data: {str(e)}")
|
24 |
+
return False
|
25 |
+
|
26 |
+
def _classify_columns(self):
|
27 |
+
for col in self.data.columns:
|
28 |
+
if pd.api.types.is_numeric_dtype(self.data[col]):
|
29 |
+
self.numeric_columns.append(col)
|
30 |
+
elif pd.api.types.is_datetime64_any_dtype(self.data[col]):
|
31 |
+
self.date_columns.append(col)
|
32 |
+
else:
|
33 |
+
try:
|
34 |
+
pd.to_datetime(self.data[col])
|
35 |
+
self.date_columns.append(col)
|
36 |
+
except:
|
37 |
+
self.categorical_columns.append(col)
|
38 |
|
39 |
+
def get_basic_stats(self) -> Dict[str, Any]:
|
40 |
+
if self.data is None:
|
41 |
+
return {}
|
|
|
|
|
42 |
|
43 |
+
stats = {
|
44 |
+
'summary': self.data[self.numeric_columns].describe(),
|
45 |
+
'missing_values': self.data.isnull().sum(),
|
46 |
+
'row_count': len(self.data),
|
47 |
+
'column_count': len(self.data.columns)
|
48 |
}
|
49 |
+
return stats
|
50 |
+
|
51 |
+
def create_visualization(self, chart_type: str, x_col: str, y_col: str, color_col: str = None) -> go.Figure:
|
52 |
+
if chart_type == "Line Plot":
|
53 |
+
fig = px.line(self.data, x=x_col, y=y_col, color=color_col)
|
54 |
+
elif chart_type == "Bar Plot":
|
55 |
+
fig = px.bar(self.data, x=x_col, y=y_col, color=color_col)
|
56 |
+
elif chart_type == "Scatter Plot":
|
57 |
+
fig = px.scatter(self.data, x=x_col, y=y_col, color=color_col)
|
58 |
+
elif chart_type == "Box Plot":
|
59 |
+
fig = px.box(self.data, x=x_col, y=y_col, color=color_col)
|
60 |
+
else:
|
61 |
+
fig = px.histogram(self.data, x=x_col, color=color_col)
|
62 |
|
63 |
+
return fig
|
|
|
|
|
64 |
|
65 |
+
# --- Sample Data Generation ---
|
66 |
def generate_sample_data():
|
67 |
dates = pd.date_range(start='2024-01-01', end='2024-01-31', freq='D')
|
68 |
return pd.DataFrame({
|
69 |
'Date': dates,
|
70 |
'Revenue': np.random.normal(1000, 100, len(dates)),
|
71 |
'Users': np.random.randint(100, 200, len(dates)),
|
72 |
+
'Engagement': np.random.uniform(0.5, 0.9, len(dates)),
|
73 |
+
'Category': np.random.choice(['A', 'B', 'C'], len(dates))
|
74 |
})
|
75 |
|
76 |
+
# --- Page Rendering Functions ---
|
77 |
+
def render_dashboard():
|
78 |
+
st.header("π Performance Dashboard")
|
|
|
|
|
79 |
data = generate_sample_data()
|
80 |
|
81 |
+
# KPI Metrics
|
82 |
+
col1, col2, col3, col4 = st.columns(4)
|
83 |
+
with col1:
|
84 |
+
st.metric("Total Revenue", f"${data['Revenue'].sum():,.2f}")
|
85 |
+
with col2:
|
86 |
+
st.metric("Total Users", f"{data['Users'].sum():,}")
|
87 |
+
with col3:
|
88 |
+
st.metric("Avg Engagement", f"{data['Engagement'].mean():.2%}")
|
89 |
+
with col4:
|
90 |
+
st.metric("Active Days", len(data))
|
91 |
+
|
92 |
+
# Charts
|
93 |
+
col1, col2 = st.columns(2)
|
94 |
with col1:
|
95 |
st.subheader("Revenue Trend")
|
96 |
fig = px.line(data, x='Date', y='Revenue')
|
97 |
st.plotly_chart(fig, use_container_width=True)
|
98 |
|
99 |
with col2:
|
100 |
+
st.subheader("User Engagement by Category")
|
101 |
+
fig = px.scatter(data, x='Date', y='Engagement',
|
102 |
+
size='Users', color='Category')
|
103 |
st.plotly_chart(fig, use_container_width=True)
|
104 |
|
105 |
+
def render_analytics():
|
106 |
+
st.header("π Data Analytics")
|
|
|
107 |
|
108 |
+
processor = DataProcessor()
|
109 |
+
|
110 |
+
# File upload
|
111 |
+
uploaded_file = st.file_uploader("Upload your CSV data", type=['csv'])
|
112 |
+
|
113 |
+
if uploaded_file is not None:
|
114 |
+
if processor.load_data(uploaded_file):
|
115 |
+
st.success("Data loaded successfully!")
|
116 |
+
|
117 |
+
tabs = st.tabs(["Data Preview", "Statistics", "Visualization", "Metrics"])
|
118 |
+
|
119 |
+
# Data Preview Tab
|
120 |
+
with tabs[0]:
|
121 |
+
st.subheader("Data Preview")
|
122 |
+
st.dataframe(processor.data.head())
|
123 |
+
st.info(f"Total rows: {len(processor.data)}, Total columns: {len(processor.data.columns)}")
|
124 |
+
|
125 |
+
# Statistics Tab
|
126 |
+
with tabs[1]:
|
127 |
+
st.subheader("Basic Statistics")
|
128 |
+
stats = processor.get_basic_stats()
|
129 |
+
st.write(stats['summary'])
|
130 |
+
|
131 |
+
st.subheader("Missing Values")
|
132 |
+
st.write(stats['missing_values'])
|
133 |
+
|
134 |
+
# Visualization Tab
|
135 |
+
with tabs[2]:
|
136 |
+
st.subheader("Create Visualization")
|
137 |
+
col1, col2, col3 = st.columns(3)
|
138 |
+
|
139 |
+
with col1:
|
140 |
+
chart_type = st.selectbox(
|
141 |
+
"Select Chart Type",
|
142 |
+
["Line Plot", "Bar Plot", "Scatter Plot", "Box Plot", "Histogram"]
|
143 |
+
)
|
144 |
+
|
145 |
+
with col2:
|
146 |
+
x_col = st.selectbox("Select X-axis", processor.data.columns)
|
147 |
+
|
148 |
+
with col3:
|
149 |
+
y_col = st.selectbox("Select Y-axis", processor.numeric_columns) if chart_type != "Histogram" else None
|
150 |
+
|
151 |
+
color_col = st.selectbox("Select Color Variable (optional)",
|
152 |
+
['None'] + processor.categorical_columns)
|
153 |
+
color_col = None if color_col == 'None' else color_col
|
154 |
+
|
155 |
+
fig = processor.create_visualization(
|
156 |
+
chart_type,
|
157 |
+
x_col,
|
158 |
+
y_col if y_col else x_col,
|
159 |
+
color_col
|
160 |
+
)
|
161 |
+
st.plotly_chart(fig, use_container_width=True)
|
162 |
+
|
163 |
+
# Metrics Tab
|
164 |
+
with tabs[3]:
|
165 |
+
st.subheader("Column Metrics")
|
166 |
+
selected_col = st.selectbox("Select column", processor.numeric_columns)
|
167 |
+
|
168 |
+
metrics = {
|
169 |
+
'Mean': processor.data[selected_col].mean(),
|
170 |
+
'Median': processor.data[selected_col].median(),
|
171 |
+
'Std Dev': processor.data[selected_col].std(),
|
172 |
+
'Min': processor.data[selected_col].min(),
|
173 |
+
'Max': processor.data[selected_col].max()
|
174 |
+
}
|
175 |
+
|
176 |
+
cols = st.columns(len(metrics))
|
177 |
+
for col, (metric, value) in zip(cols, metrics.items()):
|
178 |
+
col.metric(metric, f"{value:.2f}")
|
179 |
|
180 |
+
def render_brainstorm():
|
181 |
+
st.header("π§ Product Brainstorm")
|
182 |
|
183 |
+
# Product selection
|
184 |
+
products = ["Product A", "Product B", "Product C", "Add New Product"]
|
185 |
selected_product = st.selectbox("Select Product", products)
|
186 |
|
187 |
+
if selected_product == "Add New Product":
|
188 |
+
with st.form("new_product"):
|
189 |
+
st.subheader("Add New Product")
|
190 |
+
product_name = st.text_input("Product Name")
|
191 |
+
product_desc = st.text_area("Product Description")
|
192 |
+
product_category = st.selectbox("Category", ["Category A", "Category B", "Category C"])
|
193 |
+
|
194 |
+
if st.form_submit_button("Add Product"):
|
195 |
+
st.success(f"Product '{product_name}' added successfully!")
|
196 |
+
else:
|
197 |
st.subheader(f"Analysis for {selected_product}")
|
|
|
198 |
|
199 |
+
# Sample metrics
|
200 |
+
col1, col2, col3 = st.columns(3)
|
201 |
+
with col1:
|
202 |
+
st.metric("Sales", "$12,345", "+10%")
|
203 |
+
with col2:
|
204 |
+
st.metric("Reviews", "4.5/5", "+0.2")
|
205 |
+
with col3:
|
206 |
+
st.metric("Engagement", "89%", "-2%")
|
207 |
|
208 |
+
def render_chat():
|
209 |
+
st.header("π¬ Business Assistant")
|
210 |
|
211 |
+
# Initialize chat history
|
212 |
+
if "messages" not in st.session_state:
|
213 |
+
st.session_state.messages = []
|
214 |
+
|
215 |
+
# Display chat history
|
216 |
+
for message in st.session_state.messages:
|
217 |
+
with st.chat_message(message["role"]):
|
218 |
+
st.markdown(message["content"])
|
219 |
+
|
220 |
+
# Chat input
|
221 |
+
if prompt := st.chat_input("Ask about your business..."):
|
222 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
223 |
+
with st.chat_message("user"):
|
224 |
+
st.markdown(prompt)
|
225 |
+
|
226 |
+
# Simple response (placeholder for LLM integration)
|
227 |
+
response = f"Thank you for your question about '{prompt}'. The LLM integration will be implemented soon."
|
228 |
+
|
229 |
+
with st.chat_message("assistant"):
|
230 |
+
st.markdown(response)
|
231 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
232 |
|
233 |
+
# --- Main App ---
|
234 |
def main():
|
235 |
+
st.set_page_config(
|
236 |
+
page_title="Prospira",
|
237 |
+
page_icon="π",
|
238 |
+
layout="wide",
|
239 |
+
initial_sidebar_state="expanded"
|
240 |
+
)
|
241 |
|
242 |
+
# Sidebar
|
243 |
+
with st.sidebar:
|
244 |
+
st.title("Prospira")
|
245 |
+
st.subheader("Data-Driven Solutions")
|
246 |
+
|
247 |
+
# Navigation
|
248 |
+
page = st.radio(
|
249 |
+
"Navigation",
|
250 |
+
["Dashboard", "Analytics", "Brainstorm", "Chat"]
|
251 |
+
)
|
252 |
|
253 |
+
# Page routing
|
254 |
if page == "Dashboard":
|
255 |
+
render_dashboard()
|
256 |
+
elif page == "Analytics":
|
257 |
+
render_analytics()
|
|
|
|
|
|
|
258 |
elif page == "Brainstorm":
|
259 |
+
render_brainstorm()
|
|
|
|
|
260 |
elif page == "Chat":
|
261 |
+
render_chat()
|
|
|
262 |
|
263 |
if __name__ == "__main__":
|
264 |
main()
|