Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
400 lines (333 loc) · 14.5 KB
/
Copy pathapp.py
File metadata and controls
400 lines (333 loc) · 14.5 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from models.database import DatabaseConnection
from models.serving_layer import ServingLayer
from models.visualization import VisualizationService
from datetime import timezone, timedelta
# Konfigurasi Halaman
st.set_page_config(layout="wide", page_title="Heatmap Traffic & Polusi")
st.title("🚦 Heatmap Traffic & Polusi Jakarta (Real-Time)")
# Timezone UTC+7 (WIB)
WIB = timezone(timedelta(hours=7))
def convert_to_wib(dt):
"""Convert datetime to WIB (UTC+7) for display purposes only."""
if pd.isna(dt):
return dt
# If datetime is naive (no timezone), assume it's UTC
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
# Convert to WIB
return dt.astimezone(WIB)
def format_wib_time(dt):
"""Format datetime as WIB string."""
if pd.isna(dt):
return "N/A"
wib_dt = convert_to_wib(dt)
return wib_dt.strftime('%Y-%m-%d %H:%M:%S WIB')
@st.cache_data(ttl=10)
def get_heatmap_data():
"""Get heatmap data from Serving Layer (Lambda Architecture)."""
db_connection = DatabaseConnection()
serving_layer = ServingLayer(db_connection)
# Get combined data from Speed + Batch layers
df, last_update = serving_layer.get_combined_heatmap_data()
if not df.empty:
df['latitude'] = pd.to_numeric(df['latitude'], errors='coerce')
df['longitude'] = pd.to_numeric(df['longitude'], errors='coerce')
df['aqi_clean'] = pd.to_numeric(df.get('aqi_value', df.get('aqi_clean', 0)), errors='coerce')
df['aqi_value'] = df['aqi_clean'] # Ensure both columns exist
df['traffic_level'] = pd.to_numeric(df['traffic_level'], errors='coerce')
df = df.dropna(subset=['latitude', 'longitude'])
# Convert timestamp to WIB for display
df['timestamp_wib'] = df['timestamp'].apply(convert_to_wib)
df['formatted_time'] = df['timestamp_wib'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S WIB') if pd.notna(x) else 'N/A')
# Ensure aqi_category exists (if not, compute it)
if 'aqi_category' not in df.columns:
from models.stream_processor import StreamProcessor
df['aqi_category'] = df['aqi_value'].apply(
lambda x: StreamProcessor.get_aqi_category(int(x)) if pd.notna(x) else "Unknown"
)
# Ensure is_peak_hour exists (if not, set to False or compute it)
if 'is_peak_hour' not in df.columns:
df['is_peak_hour'] = False
# Format is_peak_hour for display
df['is_peak_hour_display'] = df['is_peak_hour'].apply(lambda x: "Yes" if x else "No")
return df, last_update
@st.cache_data(ttl=60)
def get_peak_hours_data():
"""Get peak hours analysis from Serving Layer."""
db_connection = DatabaseConnection()
serving_layer = ServingLayer(db_connection)
# Get peak hours analysis (last 7 days)
df = serving_layer.get_peak_hours_analysis(days=7)
return df
# Load data
df_main, last_update = get_heatmap_data()
df_peak_hours = get_peak_hours_data()
# Initialize visualization service
visualization = VisualizationService()
# Display last update time and data source
if not df_main.empty:
# Determine data source
now = pd.Timestamp.now(tz='UTC')
max_timestamp = df_main['timestamp'].max()
if max_timestamp.tz is None:
max_timestamp = pd.Timestamp(max_timestamp, tz='UTC')
time_diff = (now - max_timestamp).total_seconds() / 60
if time_diff < 60:
data_source = "📡 Speed Layer (Real-time)"
badge_color = "green"
else:
data_source = "📊 Batch Layer (Historical)"
badge_color = "orange"
# Format timestamp in WIB
if isinstance(last_update, str):
display_time = last_update
else:
display_time = format_wib_time(last_update) if last_update else "N/A"
col1, col2 = st.columns([3, 1])
with col1:
st.info(f"**Update Terakhir:** {display_time} | **Total Records:** {len(df_main)}")
with col2:
st.markdown(f":{badge_color}[{data_source}]")
# Sidebar - Peak Hours Info
with st.sidebar:
st.header("⏰ Peak Hours Info")
st.markdown("""
**Morning Peak:** 06:00 - 10:00
**Evening Peak:** 16:00 - 20:00
""")
if not df_main.empty and 'is_peak_hour' in df_main.columns:
try:
current_peak = df_main.sort_values('timestamp', ascending=False)['is_peak_hour'].iloc[0]
if current_peak:
st.error("🔴 Currently in PEAK HOURS")
else:
st.success("🟢 Currently OFF-PEAK")
except:
st.info("Peak hour status unavailable")
st.markdown("---")
st.markdown("### 🏗️ Architecture")
st.markdown("""
**Lambda Architecture:**
- **Speed Layer:** Real-time data
- **Batch Layer:** Historical aggregations
- **Serving Layer:** Unified access
""")
# Main content - Tabs
tab1, tab2, tab3, tab4 = st.tabs(["🗺️ Heatmaps", "📊 Peak Hours Analysis", "📈 Statistics", "📋 Raw Data"])
with tab1:
st.markdown("## Traffic & Pollution Maps")
if not df_main.empty:
# TRAFFIC MAP (using VisualizationService with Carto Dark)
st.subheader("1️⃣ Peta Kemacetan Lalu Lintas")
st.caption("Hover pada pinpoint untuk melihat detail")
traffic_deck = visualization.create_traffic_heatmap(df_main)
st.pydeck_chart(traffic_deck, use_container_width=True)
# Traffic Legend
st.markdown("**Legenda Traffic Level:**")
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
st.markdown("🟢 **1** - Lancar")
with col2:
st.markdown("🟢 **2** - Agak Lancar")
with col3:
st.markdown("🟡 **3** - Sedang")
with col4:
st.markdown("🟠 **4** - Padat")
with col5:
st.markdown("🔴 **5** - Macet Total")
st.markdown("---")
# AQI MAP (using VisualizationService with Carto Dark)
st.subheader("2️⃣ Peta Kualitas Udara (AQI)")
st.caption("Hover pada pinpoint untuk melihat detail")
aqi_deck = visualization.create_aqi_heatmap(df_main)
st.pydeck_chart(aqi_deck, use_container_width=True)
# AQI Legend - matching reference image
st.markdown("**Legenda AQI:**")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("😊 **0-50** - Good")
st.markdown("😐 **50-100** - Moderate")
with col2:
st.markdown("😷 **100-150** - Unhealthy for Sensitive Groups")
st.markdown("😨 **150-200** - Unhealthy")
with col3:
st.markdown("😱 **200-300** - Very Unhealthy")
st.markdown("☠️ **300-500** - Hazardous")
else:
st.warning("⏳ Menunggu data... Pastikan semua services berjalan.")
with tab2:
st.header("📊 Peak Hours Analysis (Last 7 Days)")
if not df_peak_hours.empty:
col1, col2 = st.columns(2)
with col1:
# Traffic by hour
fig_traffic = go.Figure()
fig_traffic.add_trace(go.Bar(
x=df_peak_hours['hour'],
y=df_peak_hours['avg_traffic'],
name='Avg Traffic Level',
marker_color=['#F44336' if is_peak else '#42A5F5' for is_peak in df_peak_hours['is_peak']]
))
fig_traffic.update_layout(
title="Average Traffic Level by Hour",
xaxis_title="Hour of Day",
yaxis_title="Average Traffic Level",
height=400
)
st.plotly_chart(fig_traffic, use_container_width=True)
with col2:
# AQI by hour
fig_aqi = go.Figure()
fig_aqi.add_trace(go.Bar(
x=df_peak_hours['hour'],
y=df_peak_hours['avg_aqi'],
name='Avg AQI',
marker_color=['#FF9800' if is_peak else '#66BB6A' for is_peak in df_peak_hours['is_peak']]
))
fig_aqi.update_layout(
title="Average AQI by Hour",
xaxis_title="Hour of Day",
yaxis_title="Average AQI",
height=400
)
st.plotly_chart(fig_aqi, use_container_width=True)
# Combined view
st.subheader("Combined View - Traffic vs AQI")
fig_combined = go.Figure()
fig_combined.add_trace(go.Scatter(
x=df_peak_hours['hour'],
y=df_peak_hours['avg_traffic'],
name='Traffic Level',
line=dict(color='#2196F3', width=3),
mode='lines+markers'
))
fig_combined.add_trace(go.Scatter(
x=df_peak_hours['hour'],
y=df_peak_hours['avg_aqi']/50, # Scale AQI to fit
name='AQI (scaled /50)',
line=dict(color='#FF5722', width=3),
mode='lines+markers',
yaxis='y2'
))
# Add peak hour backgrounds
morning_peak = [6, 7, 8, 9]
evening_peak = [16, 17, 18, 19]
for hour in morning_peak:
fig_combined.add_vrect(x0=hour-0.5, x1=hour+0.5, fillcolor="yellow", opacity=0.2, line_width=0)
for hour in evening_peak:
fig_combined.add_vrect(x0=hour-0.5, x1=hour+0.5, fillcolor="orange", opacity=0.2, line_width=0)
fig_combined.update_layout(
title="Traffic Level and AQI Throughout the Day",
xaxis_title="Hour of Day",
yaxis_title="Traffic Level",
yaxis2=dict(title="AQI (scaled)", overlaying='y', side='right'),
height=500
)
st.plotly_chart(fig_combined, use_container_width=True)
st.info("💡 Yellow = Morning Peak (6-10 AM) | Orange = Evening Peak (4-8 PM)")
else:
st.warning("⏳ No peak hours data available yet. Wait for data to accumulate.")
with tab3:
st.header("📈 Real-Time Statistics")
if not df_main.empty:
col1, col2 = st.columns(2)
with col1:
st.subheader("🚗 Traffic Statistics")
avg_traffic = df_main['traffic_level'].mean()
max_traffic = df_main['traffic_level'].max()
st.metric("Average Traffic Level", f"{avg_traffic:.2f}")
st.metric("Max Traffic Level", int(max_traffic))
if 'is_peak_hour' in df_main.columns:
peak_count = df_main['is_peak_hour'].sum()
st.metric("Peak Hour Records", f"{peak_count} / {len(df_main)}")
# Traffic level distribution
traffic_dist = df_main['traffic_level'].value_counts().sort_index()
fig_traffic_dist = px.bar(
x=traffic_dist.index,
y=traffic_dist.values,
labels={'x': 'Traffic Level', 'y': 'Count'},
title='Traffic Level Distribution',
color=traffic_dist.values,
color_continuous_scale='Reds'
)
st.plotly_chart(fig_traffic_dist, use_container_width=True)
with col2:
st.subheader("🌫️ AQI Statistics")
avg_aqi = df_main['aqi_value'].mean()
max_aqi = df_main['aqi_value'].max()
st.metric("Average AQI", f"{avg_aqi:.1f}")
st.metric("Max AQI", int(max_aqi))
# AQI category distribution
if 'aqi_category' in df_main.columns:
category_dist = df_main['aqi_category'].value_counts()
fig_category = px.pie(
values=category_dist.values,
names=category_dist.index,
title='AQI Category Distribution'
)
st.plotly_chart(fig_category, use_container_width=True)
else:
# If no category, show AQI distribution
st.info("AQI categories will be available once data is processed through Speed Layer")
else:
st.warning("⏳ No data available for statistics")
with tab4:
st.header("📋 Real-Time Data Table")
st.caption("Menampilkan data terbaru dari Speed Layer dan Batch Layer")
if not df_main.empty:
# Prepare display dataframe with WIB timestamps
display_df = df_main.copy()
# Select and rename columns for display
display_columns = {
'timestamp_wib': 'Timestamp (WIB)',
'location': 'Location',
'aqi_value': 'AQI Value',
'aqi_category': 'AQI Category',
'traffic_level': 'Traffic Level',
'is_peak_hour_display': 'Peak Hour',
'latitude': 'Latitude',
'longitude': 'Longitude'
}
# Filter to only existing columns
available_columns = {k: v for k, v in display_columns.items() if k in display_df.columns}
# Create display dataframe
df_display = display_df[list(available_columns.keys())].copy()
df_display = df_display.rename(columns=available_columns)
# Sort by timestamp (most recent first)
df_display = df_display.sort_values('Timestamp (WIB)', ascending=False)
# Display info
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Total Records", len(df_display))
with col2:
if 'AQI Value' in df_display.columns:
avg_aqi = df_display['AQI Value'].mean()
st.metric("Average AQI", f"{avg_aqi:.1f}")
with col3:
if 'Traffic Level' in df_display.columns:
avg_traffic = df_display['Traffic Level'].mean()
st.metric("Average Traffic", f"{avg_traffic:.1f}")
st.markdown("---")
# Display table
st.dataframe(
df_display.head(100),
use_container_width=True,
hide_index=True
)
# Download button
csv = df_display.to_csv(index=False)
st.download_button(
label="💾 Download CSV (Top 100 Records)",
data=csv,
file_name=f"traffic_pollution_realtime_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv"
)
else:
st.warning("⏳ No data available")
# Auto-refresh info
st.sidebar.markdown("---")
st.sidebar.info("🔄 Dashboard auto-refreshes every 10 seconds (cached)")