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
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
import os

st.set_page_config(
    page_title="Urban Traffic Flow Dashboard",
    page_icon="πŸš—",
    layout="wide",
    initial_sidebar_state="expanded",
)


@st.cache_data
def load_data():
    script_dir = os.path.dirname(os.path.abspath(__file__))
    csv_path = os.path.join(script_dir, "urban_traffic_flow_with_target.csv")
    df = pd.read_csv(csv_path)
    df["Timestamp"] = pd.to_datetime(df["Timestamp"])
    df["Hour"] = df["Timestamp"].dt.hour
    df["DayOfWeek"] = df["Timestamp"].dt.day_name()
    df["Date"] = df["Timestamp"].dt.date
    df["IsWeekend"] = df["DayOfWeek"].isin(["Saturday", "Sunday"])
    return df


def main():
    st.title("πŸš— Urban Traffic Flow Dashboard")
    st.markdown(
        "Explore urban traffic patterns, congestion levels, and temporal trends"
    )

    df = load_data()

    with st.sidebar:
        st.header("πŸ” Filters")

        min_date = df["Timestamp"].min().date()
        max_date = df["Timestamp"].max().date()

        date_range = st.date_input(
            "Date Range",
            value=(min_date, max_date),
            min_value=min_date,
            max_value=max_date,
        )

        selected_locations = st.multiselect(
            "Select Locations",
            options=sorted(df["Location"].unique()),
            default=sorted(df["Location"].unique()),
        )

        peak_filter = st.multiselect(
            "Peak/Off-Peak",
            options=sorted(df["Peak_Off_Peak"].unique()),
            default=sorted(df["Peak_Off_Peak"].unique()),
        )

        day_filter = st.multiselect(
            "Day of Week",
            options=sorted(df["DayOfWeek"].unique()),
            default=sorted(df["DayOfWeek"].unique()),
        )

        congestion_filter = st.slider(
            "Min Congestion Level", min_value=0, max_value=5, value=0, step=1
        )

    filtered_df = df.copy()

    if len(date_range) == 2:
        start_date, end_date = date_range
        filtered_df = filtered_df[
            (filtered_df["Timestamp"].dt.date >= start_date)
            & (filtered_df["Timestamp"].dt.date <= end_date)
        ]

    if selected_locations:
        filtered_df = filtered_df[filtered_df["Location"].isin(selected_locations)]

    if peak_filter:
        filtered_df = filtered_df[filtered_df["Peak_Off_Peak"].isin(peak_filter)]

    if day_filter:
        filtered_df = filtered_df[filtered_df["DayOfWeek"].isin(day_filter)]

    filtered_df = filtered_df[filtered_df["Congestion_Level"] >= congestion_filter]

    st.subheader("πŸ“Š Key Performance Indicators")

    kpi_col1, kpi_col2, kpi_col3, kpi_col4 = st.columns(4)

    with kpi_col1:
        st.metric(
            "Total Vehicle Count",
            f"{filtered_df['Vehicle_Count'].sum():,.0f}",
            help="Total number of vehicles recorded",
        )

    with kpi_col2:
        st.metric(
            "Avg Vehicle Speed",
            f"{filtered_df['Vehicle_Speed'].mean():.1f} km/h",
            help="Average speed across all locations",
        )

    with kpi_col3:
        st.metric(
            "Avg Congestion Level",
            f"{filtered_df['Congestion_Level'].mean():.1f}",
            help="Average congestion level (0-5 scale)",
        )

    with kpi_col4:
        st.metric(
            "Peak Hours Ratio",
            f"{(filtered_df['Peak_Off_Peak'] == 'Peak').sum() / len(filtered_df) * 100:.1f}%",
            help="Percentage of peak hour observations",
        )

    st.markdown("---")

    tab1, tab2, tab3, tab4 = st.tabs(
        [
            "πŸ“ˆ Temporal Trends",
            "πŸ“ Location Analysis",
            "πŸ“Š Distribution",
            "πŸ† Top Zones",
        ]
    )

    with tab1:
        st.subheader("Hourly Traffic Patterns")

        hourly_avg = (
            filtered_df.groupby("Hour")
            .agg(
                {
                    "Vehicle_Count": "mean",
                    "Vehicle_Speed": "mean",
                    "Congestion_Level": "mean",
                }
            )
            .reset_index()
        )

        fig_hourly = go.Figure()

        fig_hourly.add_trace(
            go.Scatter(
                x=hourly_avg["Hour"],
                y=hourly_avg["Vehicle_Count"],
                mode="lines+markers",
                name="Avg Vehicle Count",
                line=dict(color="#1f77b4", width=3),
                yaxis="y",
            )
        )

        fig_hourly.add_trace(
            go.Scatter(
                x=hourly_avg["Hour"],
                y=hourly_avg["Vehicle_Speed"],
                mode="lines+markers",
                name="Avg Speed (km/h)",
                line=dict(color="#2ca02c", width=3),
                yaxis="y2",
            )
        )

        fig_hourly.update_layout(
            title="Average Traffic by Hour of Day",
            xaxis_title="Hour",
            yaxis_title="Vehicle Count",
            yaxis2=dict(title="Speed (km/h)", overlaying="y", side="right"),
            hovermode="x unified",
            template="plotly_white",
            height=500,
        )

        st.plotly_chart(fig_hourly, use_container_width=True)

        st.subheader("Traffic Evolution Over Time")

        time_series = (
            filtered_df.groupby(["Timestamp", "Location"])
            .agg({"Vehicle_Count": "sum", "Congestion_Level": "mean"})
            .reset_index()
        )

        fig_ts = px.line(
            time_series,
            x="Timestamp",
            y="Vehicle_Count",
            color="Location",
            title="Traffic Volume Over Time by Location",
            labels={"Vehicle_Count": "Vehicle Count", "Timestamp": "Time"},
        )

        fig_ts.update_layout(hovermode="x unified", template="plotly_white", height=500)

        st.plotly_chart(fig_ts, use_container_width=True)

    with tab2:
        col1, col2 = st.columns(2)

        with col1:
            st.subheader("Traffic by Location")

            location_stats = (
                filtered_df.groupby("Location")
                .agg(
                    {
                        "Vehicle_Count": "sum",
                        "Vehicle_Speed": "mean",
                        "Congestion_Level": "mean",
                    }
                )
                .reset_index()
            )

            fig_loc = px.bar(
                location_stats,
                x="Location",
                y="Vehicle_Count",
                title="Total Vehicle Count by Location",
                color="Vehicle_Count",
                color_continuous_scale="Blues",
                labels={"Vehicle_Count": "Total Count"},
            )

            fig_loc.update_layout(template="plotly_white", height=400)

            st.plotly_chart(fig_loc, use_container_width=True)

        with col2:
            st.subheader("Avg Speed by Location")

            fig_speed = px.bar(
                location_stats,
                x="Location",
                y="Vehicle_Speed",
                title="Average Speed by Location",
                color="Vehicle_Speed",
                color_continuous_scale="RdYlGn",
                labels={"Vehicle_Speed": "Speed (km/h)"},
            )

            fig_speed.update_layout(template="plotly_white", height=400)

            st.plotly_chart(fig_speed, use_container_width=True)

        st.subheader("Congestion Heatmap: Hour vs Location")

        heatmap_data = filtered_df.pivot_table(
            values="Congestion_Level", index="Hour", columns="Location", aggfunc="mean"
        )

        fig_heatmap = px.imshow(
            heatmap_data,
            labels=dict(x="Location", y="Hour", color="Avg Congestion Level"),
            title="Average Congestion Level by Hour and Location",
            color_continuous_scale="RdYlGn_r",
            aspect="auto",
        )

        fig_heatmap.update_layout(template="plotly_white", height=500)

        st.plotly_chart(fig_heatmap, use_container_width=True)

    with tab3:
        col1, col2 = st.columns(2)

        with col1:
            st.subheader("Vehicle Count Distribution")

            fig_count_box = px.box(
                filtered_df,
                x="Location",
                y="Vehicle_Count",
                title="Vehicle Count Distribution by Location",
                color="Location",
            )

            fig_count_box.update_layout(
                template="plotly_white", height=400, showlegend=False
            )

            st.plotly_chart(fig_count_box, use_container_width=True)

        with col2:
            st.subheader("Speed Distribution")

            fig_speed_box = px.box(
                filtered_df,
                x="Location",
                y="Vehicle_Speed",
                title="Speed Distribution by Location",
                color="Location",
            )

            fig_speed_box.update_layout(
                template="plotly_white", height=400, showlegend=False
            )

            st.plotly_chart(fig_speed_box, use_container_width=True)

        st.subheader("Congestion Level Distribution")

        congestion_dist = (
            filtered_df["Congestion_Level"].value_counts().sort_index().reset_index()
        )
        congestion_dist.columns = ["Congestion_Level", "Count"]

        fig_congestion = px.bar(
            congestion_dist,
            x="Congestion_Level",
            y="Count",
            title="Distribution of Congestion Levels",
            color="Congestion_Level",
            color_continuous_scale="Reds",
            labels={
                "Count": "Number of Records",
                "Congestion_Level": "Congestion Level",
            },
        )

        fig_congestion.update_layout(template="plotly_white", height=400)

        st.plotly_chart(fig_congestion, use_container_width=True)

        st.subheader("Congestion by Peak/Off-Peak")

        fig_peak = px.box(
            filtered_df,
            x="Peak_Off_Peak",
            y="Congestion_Level",
            title="Congestion Level: Peak vs Off-Peak",
            color="Peak_Off_Peak",
        )

        fig_peak.update_layout(template="plotly_white", height=400, showlegend=False)

        st.plotly_chart(fig_peak, use_container_width=True)

    with tab4:
        st.subheader("Most Congested Locations")

        location_congestion = (
            filtered_df.groupby("Location")
            .agg(
                {
                    "Congestion_Level": "mean",
                    "Vehicle_Count": "mean",
                    "Vehicle_Speed": "mean",
                }
            )
            .round(2)
            .reset_index()
        )

        location_congestion = location_congestion.sort_values(
            "Congestion_Level", ascending=True
        )

        st.dataframe(location_congestion, use_container_width=True, hide_index=True)

        st.subheader("Top 5 Busiest Locations")

        top_locations = (
            filtered_df.groupby("Location")["Vehicle_Count"]
            .sum()
            .sort_values(ascending=False)
            .head(5)
            .reset_index()
        )

        fig_top = px.bar(
            top_locations,
            x="Vehicle_Count",
            y="Location",
            orientation="h",
            title="Top 5 Locations by Total Traffic Volume",
            color="Vehicle_Count",
            color_continuous_scale="Blues",
        )

        fig_top.update_layout(
            template="plotly_white",
            height=400,
            yaxis={"categoryorder": "total ascending"},
        )

        st.plotly_chart(fig_top, use_container_width=True)

        st.subheader("Slowest Locations (Lowest Avg Speed)")

        slowest_locations = (
            filtered_df.groupby("Location")["Vehicle_Speed"]
            .mean()
            .sort_values()
            .head(5)
            .reset_index()
        )

        fig_slow = px.bar(
            slowest_locations,
            x="Vehicle_Speed",
            y="Location",
            orientation="h",
            title="Top 5 Slowest Locations",
            color="Vehicle_Speed",
            color_continuous_scale="Reds_r",
        )

        fig_slow.update_layout(
            template="plotly_white",
            height=400,
            yaxis={"categoryorder": "total ascending"},
        )

        st.plotly_chart(fig_slow, use_container_width=True)

    st.markdown("---")
    st.subheader("πŸ’‘ Automatic Insights")

    insights = []

    if len(filtered_df) > 0:
        peak_hour = filtered_df.groupby("Hour")["Vehicle_Count"].mean().idxmax()
        insights.append(
            f"πŸ• **Peak traffic hour**: {peak_hour}:00 - {peak_hour + 1}:00 with avg {filtered_df.groupby('Hour')['Vehicle_Count'].mean().max():.0f} vehicles"
        )

        busiest_loc = filtered_df.groupby("Location")["Vehicle_Count"].sum().idxmax()
        busiest_count = filtered_df.groupby("Location")["Vehicle_Count"].sum().max()
        insights.append(
            f"πŸ“ **Busiest location**: {busiest_loc} with {busiest_count:,.0f} total vehicles"
        )

        avg_congestion = filtered_df["Congestion_Level"].mean()
        if avg_congestion < 2:
            congestion_status = "Low"
        elif avg_congestion < 4:
            congestion_status = "Moderate"
        else:
            congestion_status = "High"
        insights.append(
            f"🚦 **Overall congestion**: {congestion_status} (avg level: {avg_congestion:.1f}/5)"
        )

        weekday_avg = filtered_df[~filtered_df["IsWeekend"]]["Vehicle_Count"].mean()
        weekend_avg = filtered_df[filtered_df["IsWeekend"]]["Vehicle_Count"].mean()
        diff_pct = (
            ((weekday_avg - weekend_avg) / weekend_avg * 100) if weekend_avg > 0 else 0
        )
        insights.append(
            f"πŸ“… **Weekday vs Weekend**: Weekdays have {abs(diff_pct):.1f}% {'more' if diff_pct > 0 else 'less'} traffic on average"
        )

        peak_vs_offpeak_peak = filtered_df[filtered_df["Peak_Off_Peak"] == "Peak"][
            "Congestion_Level"
        ].mean()
        peak_vs_offpeak_off = filtered_df[filtered_df["Peak_Off_Peak"] == "Off-Peak"][
            "Congestion_Level"
        ].mean()
        insights.append(
            f"⏰ **Peak hours**: Congestion is {(peak_vs_offpeak_peak - peak_vs_offpeak_off):.1f} levels higher during peak hours"
        )

    for insight in insights:
        st.markdown(f"- {insight}")


if __name__ == "__main__":
    main()