mrradix commited on
Commit
f99f1ff
·
verified ·
1 Parent(s): 08a78ca

Update pages/dashboard.py

Browse files
Files changed (1) hide show
  1. pages/dashboard.py +35 -97
pages/dashboard.py CHANGED
@@ -7,34 +7,24 @@ import streamlit as st
7
  import pandas as pd
8
  import plotly.express as px
9
  import plotly.graph_objects as go
10
- from datetime import datetime, timedelta
11
  from typing import Dict, List, Optional, Any
12
 
13
  from utils.storage import load_data, save_data, get_cached_data, set_cached_data
14
- from utils.error_handling import handle_data_exceptions, ErrorHandler, ValidationError, DataError
15
  from utils.logging import get_logger, log_info, log_error, log_warning
16
 
17
-
18
  # Initialize logger
19
  logger = get_logger(__name__)
20
 
21
-
22
  @handle_data_exceptions
23
  def load_dashboard_data() -> Dict[str, Any]:
24
- """
25
- Load dashboard data with caching
26
-
27
- Returns:
28
- Dict: Dashboard data including metrics, charts data, etc.
29
- """
30
- # Try to get from cache first
31
  cached_data = get_cached_data("dashboard_data")
32
  if cached_data:
33
  log_info("Using cached dashboard data")
34
  return cached_data
35
-
36
  try:
37
- # Load data from storage
38
  data = {
39
  "metrics": load_data("dashboard_metrics.json", default={}),
40
  "user_activity": load_data("user_activity.json", default=[]),
@@ -42,13 +32,9 @@ def load_dashboard_data() -> Dict[str, Any]:
42
  "recent_events": load_data("recent_events.json", default=[]),
43
  "performance_data": load_data("performance_data.json", default=[])
44
  }
45
-
46
- # Cache the data
47
  set_cached_data("dashboard_data", data)
48
  log_info("Dashboard data loaded and cached successfully")
49
-
50
  return data
51
-
52
  except Exception as e:
53
  log_error("Failed to load dashboard data", error=e)
54
  return {
@@ -59,99 +45,51 @@ def load_dashboard_data() -> Dict[str, Any]:
59
  "performance_data": []
60
  }
61
 
62
-
63
  @handle_data_exceptions
64
  def create_metrics_cards(metrics: Dict[str, Any]) -> None:
65
- """
66
- Create and display metrics cards
67
-
68
- Args:
69
- metrics: Dictionary containing metric values
70
- """
71
  if not metrics:
72
  st.warning("No metrics data available")
73
  return
74
-
75
- # Create columns for metrics
76
  cols = st.columns(4)
77
-
78
- # Total Users
79
  with cols[0]:
80
- total_users = metrics.get("total_users", 0)
81
- st.metric(
82
- label="Total Users",
83
- value=f"{total_users:,}",
84
- delta=metrics.get("users_change", 0)
85
- )
86
-
87
- # Active Sessions
88
  with cols[1]:
89
- active_sessions = metrics.get("active_sessions", 0)
90
- st.metric(
91
- label="Active Sessions",
92
- value=f"{active_sessions:,}",
93
- delta=metrics.get("sessions_change", 0)
94
- )
95
-
96
- # System Health
97
  with cols[2]:
98
- system_health = metrics.get("system_health", 0)
99
- st.metric(
100
- label="System Health",
101
- value=f"{system_health:.1f}%",
102
- delta=f"{metrics.get('health_change', 0):.1f}%"
103
- )
104
-
105
- # Response Time
106
  with cols[3]:
107
- response_time = metrics.get("avg_response_time", 0)
108
- st.metric(
109
- label="Avg Response Time",
110
- value=f"{response_time:.0f}ms",
111
- delta=f"{metrics.get('response_change', 0):.0f}ms",
112
- delta_color="inverse"
113
- )
114
-
115
 
116
  @handle_data_exceptions
117
  def create_activity_chart(activity_data: List[Dict]) -> None:
118
- """
119
- Create user activity chart
120
-
121
- Args:
122
- activity_data: List of activity data points
123
- """
124
  if not activity_data:
125
  st.warning("No activity data available")
126
  return
127
-
128
- try:
129
- df = pd.DataFrame(activity_data)
130
-
131
- if df.empty:
132
- st.warning("Activity data is empty")
133
- return
134
-
135
- # Ensure required columns exist
136
- if 'timestamp' not in df.columns:
137
- df['timestamp'] = pd.date_range(start='2024-01-01', periods=len(df), freq='H')
138
-
139
- if 'users' not in df.columns:
140
- df['users'] = [0] * len(df)
141
-
142
- # Convert timestamp to datetime if it's not already
143
- df['timestamp'] = pd.to_datetime(df['timestamp'])
144
-
145
- # Create the chart
146
- fig = px.line(
147
- df,
148
- x='timestamp',
149
- y='users',
150
- title='User Activity Over Time',
151
- labels={'users': 'Active Users', 'timestamp': 'Time'}
152
- )
153
-
154
- fig.update_layout(
155
- xaxis_title="Time",
156
- yaxis_title="Active Users",
157
- )
 
7
  import pandas as pd
8
  import plotly.express as px
9
  import plotly.graph_objects as go
10
+ from datetime import datetime
11
  from typing import Dict, List, Optional, Any
12
 
13
  from utils.storage import load_data, save_data, get_cached_data, set_cached_data
14
+ from utils.error_handling import handle_data_exceptions, ValidationError, DataError
15
  from utils.logging import get_logger, log_info, log_error, log_warning
16
 
 
17
  # Initialize logger
18
  logger = get_logger(__name__)
19
 
 
20
  @handle_data_exceptions
21
  def load_dashboard_data() -> Dict[str, Any]:
 
 
 
 
 
 
 
22
  cached_data = get_cached_data("dashboard_data")
23
  if cached_data:
24
  log_info("Using cached dashboard data")
25
  return cached_data
26
+
27
  try:
 
28
  data = {
29
  "metrics": load_data("dashboard_metrics.json", default={}),
30
  "user_activity": load_data("user_activity.json", default=[]),
 
32
  "recent_events": load_data("recent_events.json", default=[]),
33
  "performance_data": load_data("performance_data.json", default=[])
34
  }
 
 
35
  set_cached_data("dashboard_data", data)
36
  log_info("Dashboard data loaded and cached successfully")
 
37
  return data
 
38
  except Exception as e:
39
  log_error("Failed to load dashboard data", error=e)
40
  return {
 
45
  "performance_data": []
46
  }
47
 
 
48
  @handle_data_exceptions
49
  def create_metrics_cards(metrics: Dict[str, Any]) -> None:
 
 
 
 
 
 
50
  if not metrics:
51
  st.warning("No metrics data available")
52
  return
53
+
 
54
  cols = st.columns(4)
 
 
55
  with cols[0]:
56
+ st.metric("Total Users", f"{metrics.get('total_users', 0):,}", delta=metrics.get("users_change", 0))
 
 
 
 
 
 
 
57
  with cols[1]:
58
+ st.metric("Active Sessions", f"{metrics.get('active_sessions', 0):,}", delta=metrics.get("sessions_change", 0))
 
 
 
 
 
 
 
59
  with cols[2]:
60
+ st.metric("System Health", f"{metrics.get('system_health', 0):.1f}%", delta=f"{metrics.get('health_change', 0):.1f}%")
 
 
 
 
 
 
 
61
  with cols[3]:
62
+ 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")
 
 
 
 
 
 
 
63
 
64
  @handle_data_exceptions
65
  def create_activity_chart(activity_data: List[Dict]) -> None:
 
 
 
 
 
 
66
  if not activity_data:
67
  st.warning("No activity data available")
68
  return
69
+
70
+ df = pd.DataFrame(activity_data)
71
+ if df.empty:
72
+ st.warning("Activity data is empty")
73
+ return
74
+
75
+ if 'timestamp' not in df.columns:
76
+ df['timestamp'] = pd.date_range(start='2024-01-01', periods=len(df), freq='H')
77
+ if 'users' not in df.columns:
78
+ df['users'] = [0] * len(df)
79
+
80
+ df['timestamp'] = pd.to_datetime(df['timestamp'])
81
+
82
+ fig = px.line(
83
+ df,
84
+ x='timestamp',
85
+ y='users',
86
+ title='User Activity Over Time',
87
+ labels={'users': 'Active Users', 'timestamp': 'Time'}
88
+ )
89
+
90
+ fig.update_layout(
91
+ xaxis_title="Time",
92
+ yaxis_title="Active Users",
93
+ )
94
+
95
+ st.plotly_chart(fig, use_container_width=True)