File size: 7,691 Bytes
81cbae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197d07f
 
 
 
81cbae0
 
 
 
 
 
197d07f
81cbae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7987d3
 
 
81cbae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from streamlit_folium import st_folium
import folium
from backend_route import get_route_fatalities

FEATURE_MEANING = {
    # --- REST_USE ---
    "REST_USE_1": "Shoulder Belt Only",
    "REST_USE_2": "Lap Belt Only",
    "REST_USE_3": "Shoulder and Lap Belt",
    "REST_USE_4": "Child Restraint",
    "REST_USE_6": "Racing Harness",
    "REST_USE_7": "No Restraint (MV Occupant)",
    "REST_USE_8": "No Restraint Used",
    "REST_USE_10": "Child Restraint (Forward)",
    "REST_USE_11": "Child Restraint (Rear)",
    "REST_USE_12": "Booster Seat",
    "REST_USE_16": "Helmet",
    "REST_USE_20": "Not Applicable",
    "REST_USE_96": "Not MV Occupant",
    "REST_USE_99": "Unknown",

    # --- ROLLOVER ---
    "ROLLOVER_0.0": "No Rollover",
    "ROLLOVER_3.0": "Rollover",
    "ROLLOVER_8.0": "Not Applicable",

    # --- BODY_TYP ---
    **{f"BODY_TYP_{k}": v for k, v in {
        '1.0':'Convertible','2.0':'2-Door Sedan','3.0':'2-Door Hatchback',
        '4.0':'4-Door Sedan','5.0':'4-Door Hatchback','6.0':'Station Wagon',
        '14.0':'Compact Utility','15.0':'Large Utility','20.0':'Minivan',
        '21.0':'Large Van','34.0':'Light Pickup','50.0':'School Bus',
        '52.0':'Transit Bus','61.0':'Single-Unit Truck (10–19.5k)',
        '62.0':'Single-Unit Truck (19.5–26k)','63.0':'Single-Unit Truck (>26k)',
        '64.0':'Single-Unit Truck (Unknown)','66.0':'Truck Tractor',
        '67.0':'Heavy Pickup','80.0':'Motorcycle','81.0':'Moped',
        '82.0':'3-Wheel Motorcycle','83.0':'Off-Road Motorcycle',
        '84.0':'Motor Scooter','88.0':'Other Motored Cycle','90.0':'ATV',
        '92.0':'Farm Equipment','95.0':'Golf Cart'
    }.items()},

    # --- IMPACT1 ---
    **{f"IMPACT1_{k}": v for k, v in {
        '0.0': 'Non-Collision','1.0':'12-O’clock','2.0':'1-O’clock','3.0':'2-O’clock',
        '4.0':'3-O’clock','5.0':'4-O’clock','6.0':'5-O’clock','7.0':'6-O’clock',
        '8.0':'7-O’clock','9.0':'8-O’clock','10.0':'9-O’clock','11.0':'10-O’clock',
        '12.0':'11-O’clock','13.0':'Top','14.0':'Undercarriage',
        '61.0':'Left','62.0':'Left-Front','63.0':'Left-Back',
        '81.0':'Right','82.0':'Right-Front','83.0':'Right-Back'
    }.items()},

    # --- HARM_EV ---
    **{f"HARM_EV_{k}": v for k, v in {
        '1':'Rollover','8':'Pedestrian','9':'Pedalcyclist','10':'Railway Vehicle',
        '11':'Animal','12':'Motor Vehicle','14':'Parked Vehicle',
        '15':'Personal Conveyance','16':'Thrown Object','21':'Bridge Pier',
        '23':'Bridge Rail','24':'Guardrail','25':'Concrete Barrier','30':'Utility Pole',
        '32':'Culvert','33':'Curb','34':'Ditch','35':'Embankment','38':'Fence',
        '39':'Wall','40':'Fire Hydrant','41':'Shrubbery','42':'Tree',
        '43':'Fixed Object','49':'Animal-Drawn Conveyance'
    }.items()}
}

# ---------------------------------------------------
# Streamlit Page Setup
# ---------------------------------------------------
st.set_page_config(page_title="Route Fatality Explorer", layout="wide")
st.title("🚗 Route Fatality Explorer")

st.markdown("""
<div style="
    background-color:#f0f2f6;
    padding:15px;
    border-radius:8px;
    font-size:16px;
">
<b>About This Tool</b><br>
This dashboard identifies all fatal crashes that occurred within 50 meters of a selected driving route and displays the primary contributing factor for each fatality.  
Contributing factors come from a machine-learning model trained on nationwide crash data (2016–2023).
</div>
""", unsafe_allow_html=True)

# ---------------------------------------------------
# Initialize session state
# ---------------------------------------------------
if "results" not in st.session_state:
    st.session_state.results = None


# ---------------------------------------------------
# Input fields
# ---------------------------------------------------
st.subheader("Enter Route Information")

col1, col2 = st.columns(2)

with col1:
    origin = st.text_input("Origin Address", placeholder="e.g., New York, NY")

with col2:
    destination = st.text_input("Destination Address", placeholder="e.g., Washington, DC")

# ---------------------------------------------------
# Button – run backend
# ---------------------------------------------------
if st.button("Find Fatalities Along Route"):
    if origin.strip() == "" or destination.strip() == "":
        st.error("Please enter BOTH origin and destination.")
        st.stop()

    with st.spinner("Calculating route and filtering fatalities..."):
        st.session_state.results = get_route_fatalities(origin, destination)


# ---------------------------------------------------
# Render results if available
# ---------------------------------------------------
results = st.session_state.results

if results is None:
    st.info("Enter a route to begin.")
    st.stop()

if not isinstance(results, dict):
    st.error("Unexpected backend response.")
    st.stop()

if "error" in results:
    st.error(results["error"])
    if "details" in results:
        st.code(results["details"])
    st.stop()


# ---------------------------------------------------
# Map Rendering + Summary Side-by-Side
# ---------------------------------------------------
st.subheader("Fatalities Along the Route")

route_coords = results["route_coords"]
fatalities = results["fatalities"]   # list of dicts

if len(route_coords) == 0:
    st.warning("Route geometry missing.")
    st.stop()

# Create columns: big map (left), summary (right)
col_map, col_table = st.columns([2.2, 1])

with col_map:

    # --- Create Map Centered on First Route Point ---
    center_lat = route_coords[0][1]
    center_lon = route_coords[0][0]

    m = folium.Map(location=[center_lat, center_lon], zoom_start=10)

    # --- Draw Route Line ---
    folium.PolyLine(
        [(latlon[1], latlon[0]) for latlon in results["route_coords"]],
        color="blue",
        weight=4,
        opacity=0.8,
    ).add_to(m)

    # --- Add Fatality Markers ---
    for item in fatalities:
        lat = item["LATITUDE"]
        lon = item["LONGITUDE"]
        year = item["YEAR"]
        contrib = item["top_contributor"]
        color = item["top_contributor_color"]

        popup_html = f"""
        <b>Crash Year:</b> {year}<br>
        <b>Top Contributor:</b> {contrib}
        """

        folium.CircleMarker(
            location=[lat, lon],
            radius=6,
            color=color,
            fill=True,
            fill_opacity=0.9,
            popup=popup_html,
            tooltip=f"{contrib} ({year})"
        ).add_to(m)

    from streamlit.components.v1 import html

    html(m.get_root().render(), height=600)



with col_table:

    import pandas as pd

    st.subheader(f"Fatalities Found: {len(fatalities)}")

    if len(fatalities) > 0:
        # Convert list → DataFrame
        df = pd.DataFrame(fatalities)

        # Create human-readable explanation column
        df["explanation"] = df["top_contributor"].apply(
            lambda x: FEATURE_MEANING.get(x, "")
        )

        # Group by raw feature & explanation together
        summary = (
            df.groupby(["top_contributor", "explanation"])
              .size()
              .reset_index(name="count")
              .sort_values("count", ascending=False)
        )

        # Rename columns for display
        summary = summary.rename(columns={
            "top_contributor": "Feature",
            "explanation": "Explanation",
            "count": "Count"
        })

        st.subheader("Top Contributors Summary")
        st.dataframe(summary, use_container_width=True)

    else:
        st.info("No fatalities found within 50 meters of the route.")