mrradix commited on
Commit
4f1b3bc
Β·
verified Β·
1 Parent(s): e4111ba

Update pages/dashboard.py

Browse files
Files changed (1) hide show
  1. pages/dashboard.py +160 -108
pages/dashboard.py CHANGED
@@ -1,114 +1,166 @@
1
- """
2
- Dashboard page for the MONA application
3
- Fixed version with proper imports and error handling
4
- """
5
-
6
  import streamlit as st
7
  import pandas as pd
 
 
8
  import plotly.express as px
9
- from datetime import datetime
10
- from typing import Dict, List, Any
11
-
12
- from utils.storage import load_data, save_data, get_cached_data, set_cached_data
13
- from utils.error_handling import handle_data_exceptions, ValidationError, DataError
14
- from utils.logging import get_logger, log_info, log_error, log_warning
15
-
16
- # Initialize logger
17
- logger = get_logger(__name__)
18
-
19
- @handle_data_exceptions
20
- def load_dashboard_data() -> Dict[str, Any]:
21
- cached_data = get_cached_data("dashboard_data")
22
- if cached_data:
23
- log_info("Using cached dashboard data")
24
- return cached_data
25
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  try:
27
- data = {
28
- "metrics": load_data("dashboard_metrics.json", default={}),
29
- "user_activity": load_data("user_activity.json", default=[]),
30
- "system_stats": load_data("system_stats.json", default={}),
31
- "recent_events": load_data("recent_events.json", default=[]),
32
- "performance_data": load_data("performance_data.json", default=[])
33
- }
34
- set_cached_data("dashboard_data", data)
35
- log_info("Dashboard data loaded and cached successfully")
36
- return data
37
  except Exception as e:
38
- log_error("Failed to load dashboard data", error=e)
39
- return {
40
- "metrics": {},
41
- "user_activity": [],
42
- "system_stats": {},
43
- "recent_events": [],
44
- "performance_data": []
45
- }
46
-
47
- @handle_data_exceptions
48
- def create_metrics_cards(metrics: Dict[str, Any]) -> None:
49
- if not metrics:
50
- st.warning("No metrics data available")
51
- return
52
-
53
- cols = st.columns(4)
54
- with cols[0]:
55
- st.metric("Total Users", f"{metrics.get('total_users', 0):,}", delta=metrics.get("users_change", 0))
56
- with cols[1]:
57
- st.metric("Active Sessions", f"{metrics.get('active_sessions', 0):,}", delta=metrics.get("sessions_change", 0))
58
- with cols[2]:
59
- st.metric("System Health", f"{metrics.get('system_health', 0):.1f}%", delta=f"{metrics.get('health_change', 0):.1f}%")
60
- with cols[3]:
61
- st.metric("Avg Response Time", f"{metrics.get('avg_response_time', 0):.0f}ms", delta=f"{metrics.get('response_change', 0):.0f}ms", delta_color="inverse")
62
-
63
- @handle_data_exceptions
64
- def create_activity_chart(activity_data: List[Dict]) -> None:
65
- if not activity_data:
66
- st.warning("No activity data available")
67
- return
68
-
69
- df = pd.DataFrame(activity_data)
70
- if df.empty:
71
- st.warning("Activity data is empty")
72
- return
73
-
74
- if 'timestamp' not in df.columns:
75
- df['timestamp'] = pd.date_range(start='2024-01-01', periods=len(df), freq='H')
76
- if 'users' not in df.columns:
77
- df['users'] = [0] * len(df)
78
-
79
- df['timestamp'] = pd.to_datetime(df['timestamp'])
80
-
81
- fig = px.line(
82
- df,
83
- x='timestamp',
84
- y='users',
85
- title='User Activity Over Time',
86
- labels={'users': 'Active Users', 'timestamp': 'Time'}
87
- )
88
-
89
- fig.update_layout(
90
- xaxis_title="Time",
91
- yaxis_title="Active Users",
92
- )
93
-
94
- st.plotly_chart(fig, use_container_width=True)
95
-
96
- @handle_data_exceptions
97
- def render_dashboard():
98
- """Main function to render the dashboard page."""
99
- st.title("πŸ“Š MONA Dashboard")
100
-
101
- # Load all data
102
- data = load_dashboard_data()
103
-
104
- # Metrics cards
105
- create_metrics_cards(data.get("metrics", {}))
106
- st.markdown("---")
107
-
108
- # Activity chart
109
- st.subheader("User Activity")
110
- create_activity_chart(data.get("user_activity", []))
111
 
112
- # Run page
113
- if __name__ == "__main__" or __name__.endswith(".dashboard"):
114
- render_dashboard()
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import numpy as np
4
+ from datetime import datetime, timedelta
5
  import plotly.express as px
6
+ import plotly.graph_objects as go
7
+ from utils.storage import load_data, save_data, get_session_data, set_session_data
8
+ from utils.error_handling import handle_ui_exceptions
9
+ from utils.logging import log_info, log_error
10
+
11
+ @handle_ui_exceptions
12
+ def create_dashboard_page():
13
+ """Create the main dashboard page with enhanced features"""
14
+
15
+ st.title("🏠 Dashboard")
16
+ st.markdown("---")
17
+
18
+ # Key metrics section
19
+ create_metrics_section()
20
+
21
+ # Charts section
22
+ create_charts_section()
23
+
24
+ # Recent activity
25
+ create_activity_section()
26
+
27
+ # Quick actions
28
+ create_quick_actions()
29
+
30
+ @handle_ui_exceptions
31
+ def create_metrics_section():
32
+ """Create the key metrics display"""
33
+ st.subheader("πŸ“Š Key Metrics")
34
+
35
+ # Sample metrics - in a real app, these would come from your data
36
+ col1, col2, col3, col4 = st.columns(4)
37
+
38
+ with col1:
39
+ st.metric(
40
+ label="Total Users",
41
+ value="2,847",
42
+ delta="12%",
43
+ help="Total registered users"
44
+ )
45
+
46
+ with col2:
47
+ st.metric(
48
+ label="Active Sessions",
49
+ value="456",
50
+ delta="8%",
51
+ help="Currently active user sessions"
52
+ )
53
+
54
+ with col3:
55
+ st.metric(
56
+ label="Messages Today",
57
+ value="1,234",
58
+ delta="-3%",
59
+ help="Messages sent today"
60
+ )
61
+
62
+ with col4:
63
+ st.metric(
64
+ label="System Uptime",
65
+ value="99.9%",
66
+ delta="0.1%",
67
+ help="System availability"
68
+ )
69
+
70
+ @handle_ui_exceptions
71
+ def create_charts_section():
72
+ """Create charts and visualizations"""
73
+ st.subheader("πŸ“ˆ Analytics")
74
+
75
+ col1, col2 = st.columns(2)
76
+
77
+ with col1:
78
+ # Line chart for usage over time
79
+ st.write("**Usage Trend (Last 30 Days)**")
80
+
81
+ # Generate sample data
82
+ dates = pd.date_range(start=datetime.now() - timedelta(days=30),
83
+ end=datetime.now(),
84
+ freq='D')
85
+
86
+ usage_data = pd.DataFrame({
87
+ 'Date': dates,
88
+ 'Users': np.random.randint(50, 200, len(dates)),
89
+ 'Messages': np.random.randint(100, 500, len(dates))
90
+ })
91
+
92
+ fig = px.line(usage_data, x='Date', y=['Users', 'Messages'],
93
+ title="Daily Usage Statistics")
94
+ st.plotly_chart(fig, use_container_width=True)
95
+
96
+ with col2:
97
+ # Pie chart for user distribution
98
+ st.write("**User Distribution**")
99
+
100
+ user_types = ['Free Users', 'Premium Users', 'Enterprise']
101
+ user_counts = [1200, 800, 400]
102
+
103
+ fig = px.pie(values=user_counts, names=user_types,
104
+ title="User Type Distribution")
105
+ st.plotly_chart(fig, use_container_width=True)
106
+
107
+ @handle_ui_exceptions
108
+ def create_activity_section():
109
+ """Create recent activity feed"""
110
+ st.subheader("πŸ”” Recent Activity")
111
+
112
+ # Sample activity data
113
+ activities = [
114
+ {"time": "2 minutes ago", "action": "New user registered", "user": "[email protected]"},
115
+ {"time": "5 minutes ago", "action": "Message sent", "user": "[email protected]"},
116
+ {"time": "10 minutes ago", "action": "File uploaded", "user": "[email protected]"},
117
+ {"time": "15 minutes ago", "action": "Settings updated", "user": "[email protected]"},
118
+ {"time": "20 minutes ago", "action": "Login", "user": "[email protected]"}
119
+ ]
120
+
121
+ for activity in activities:
122
+ with st.container():
123
+ col1, col2, col3 = st.columns([2, 4, 2])
124
+ with col1:
125
+ st.write(activity["time"])
126
+ with col2:
127
+ st.write(f"**{activity['action']}** - {activity['user']}")
128
+ with col3:
129
+ st.write("βœ“")
130
+ st.markdown("---")
131
+
132
+ @handle_ui_exceptions
133
+ def create_quick_actions():
134
+ """Create quick action buttons"""
135
+ st.subheader("⚑ Quick Actions")
136
+
137
+ col1, col2, col3, col4 = st.columns(4)
138
+
139
+ with col1:
140
+ if st.button("πŸ’¬ Start Chat", use_container_width=True):
141
+ st.switch_page("pages/chat.py")
142
+
143
+ with col2:
144
+ if st.button("πŸ“Š View Analytics", use_container_width=True):
145
+ st.switch_page("pages/analytics.py")
146
+
147
+ with col3:
148
+ if st.button("βš™οΈ Settings", use_container_width=True):
149
+ st.switch_page("pages/settings.py")
150
+
151
+ with col4:
152
+ if st.button("πŸ“ File Manager", use_container_width=True):
153
+ st.switch_page("pages/files.py")
154
+
155
+ # Export the main function
156
+ def main():
157
+ """Main function for the dashboard page"""
158
  try:
159
+ create_dashboard_page()
160
+ log_info("Dashboard page loaded successfully")
 
 
 
 
 
 
 
 
161
  except Exception as e:
162
+ log_error("Error loading dashboard page", error=e)
163
+ st.error("Failed to load dashboard. Please try refreshing the page.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
+ if __name__ == "__main__":
166
+ main()