# app.py import numpy as np import pandas as pd import streamlit as st import joblib from pathlib import Path # ------------------------- # Page config # ------------------------- st.set_page_config(page_title='Road Accident Risk Predictor', page_icon='🚗', layout='centered') st.title('🚗 Road Accident Risk Predictor') st.write('Predicts **accident_risk (0–1)** using a trained **LightGBM** regression model.') BASE_DIR = Path(__file__).resolve().parent MODEL_PATH = BASE_DIR / 'lgbm_model.pkl' FEATURE_NAMES_PATH = BASE_DIR / 'feature_names.pkl' # ------------------------- # Load artifacts # ------------------------- @st.cache_resource def load_artifacts(): if not MODEL_PATH.exists(): raise FileNotFoundError(f'Missing model file: {MODEL_PATH.name} (put it in the repo root).') if not FEATURE_NAMES_PATH.exists(): raise FileNotFoundError(f'Missing feature file: {FEATURE_NAMES_PATH.name} (put it in the repo root).') model = joblib.load(MODEL_PATH) feature_names = joblib.load(FEATURE_NAMES_PATH) return model, feature_names model, FEATURE_NAMES = load_artifacts() # ------------------------- # Feature engineering + encoding (must match notebook logic) # ------------------------- def build_features(raw_df: pd.DataFrame) -> pd.DataFrame: df = raw_df.copy() # Ensure expected base columns exist required = [ 'road_type', 'num_lanes', 'curvature', 'speed_limit', 'lighting', 'weather', 'road_signs_present', 'public_road', 'time_of_day', 'holiday', 'school_season', 'num_reported_accidents' ] missing = [c for c in required if c not in df.columns] if missing: raise ValueError(f'Missing columns: {missing}') # Force numeric/bool-friendly types num_cols = ['num_lanes', 'curvature', 'speed_limit', 'num_reported_accidents'] for c in num_cols: df[c] = pd.to_numeric(df[c], errors='coerce') bool_cols = ['road_signs_present', 'public_road', 'holiday', 'school_season'] for c in bool_cols: # accept True/False, 0/1, 'true'/'false' df[c] = df[c].astype(str).str.lower().map({'true': 1, 'false': 0}) df[c] = df[c].fillna(0).astype(int) # Fill any numeric NaNs defensively (even if your dataset had none) df['curvature'] = df['curvature'].fillna(df['curvature'].median()) df['speed_limit'] = df['speed_limit'].fillna(df['speed_limit'].median()) df['num_lanes'] = df['num_lanes'].fillna(df['num_lanes'].median()) df['num_reported_accidents'] = df['num_reported_accidents'].fillna(df['num_reported_accidents'].median()) # ---- Feature engineering you used ---- df['curvature_speed'] = df['curvature'] * df['speed_limit'] df['lanes_speed'] = df['num_lanes'] * df['speed_limit'] df['accidents_lane'] = df['num_reported_accidents'] / (df['num_lanes'] + 1) df['holiday_school'] = (df['holiday'].astype(int) & df['school_season'].astype(int)).astype(int) df['signs_public'] = (df['road_signs_present'].astype(int) & df['public_road'].astype(int)).astype(int) # ---- One-hot encoding (same style as notebook) ---- df_encoded = pd.get_dummies(df, drop_first=True) # Align to training feature order (critical for Streamlit / deployment) df_encoded = df_encoded.reindex(columns=FEATURE_NAMES, fill_value=0) return df_encoded def predict_one(raw_row: dict) -> float: raw_df = pd.DataFrame([raw_row]) X = build_features(raw_df) pred = float(model.predict(X)[0]) pred = float(np.clip(pred, 0, 1)) return pred # ------------------------- # UI # ------------------------- st.subheader('Input') tab1, tab2 = st.tabs(['Manual input', 'Upload CSV']) with tab1: col1, col2 = st.columns(2) with col1: road_type = st.selectbox('Road type', ['highway', 'urban', 'rural'], index=0) lighting = st.selectbox('Lighting', ['daylight', 'dim', 'night'], index=0) weather = st.selectbox('Weather', ['clear', 'foggy', 'rainy'], index=0) time_of_day = st.selectbox('Time of day', ['morning', 'afternoon', 'evening'], index=0) with col2: num_lanes = st.slider('Number of lanes', min_value=1, max_value=6, value=2, step=1) curvature = st.slider('Curvature (0–1)', min_value=0.0, max_value=1.0, value=0.30, step=0.01) speed_limit = st.slider('Speed limit', min_value=10, max_value=130, value=50, step=5) num_reported_accidents = st.slider('Reported accidents', min_value=0, max_value=10, value=1, step=1) st.markdown('**Flags**') c1, c2, c3, c4 = st.columns(4) road_signs_present = c1.checkbox('Road signs present', value=True) public_road = c2.checkbox('Public road', value=True) holiday = c3.checkbox('Holiday', value=False) school_season = c4.checkbox('School season', value=False) raw_row = { 'road_type': road_type, 'num_lanes': num_lanes, 'curvature': curvature, 'speed_limit': speed_limit, 'lighting': lighting, 'weather': weather, 'road_signs_present': int(road_signs_present), 'public_road': int(public_road), 'time_of_day': time_of_day, 'holiday': int(holiday), 'school_season': int(school_season), 'num_reported_accidents': num_reported_accidents } if st.button('Predict'): try: pred = predict_one(raw_row) st.success(f'Predicted accident_risk: **{pred:.6f}**') st.progress(min(max(pred, 0.0), 1.0)) except Exception as e: st.error(str(e)) with tab2: st.write('Upload a CSV with the raw columns (same as Kaggle test.csv, without `accident_risk`).') up = st.file_uploader('Upload CSV', type=['csv']) if up is not None: try: raw_df = pd.read_csv(up) # If user accidentally includes id or target, drop safely for col in ['id', 'accident_risk']: if col in raw_df.columns: raw_df = raw_df.drop(columns=[col]) X = build_features(raw_df) preds = model.predict(X) preds = np.clip(preds, 0, 1) out = raw_df.copy() out['accident_risk_pred'] = preds st.write('Preview:') st.dataframe(out.head(20), use_container_width=True) csv_bytes = out.to_csv(index=False).encode('utf-8') st.download_button( label='Download predictions CSV', data=csv_bytes, file_name='predictions.csv', mime='text/csv' ) except Exception as e: st.error(str(e)) st.caption('Note: This app reproduces the same feature engineering + one-hot encoding logic as the notebook and then aligns features using feature_names.pkl.')