Spaces:
Runtime error
Runtime error
Download src/streamlit_app.py from mcshoja/FoodInsecurityDashboard: direct link, hf CLI and curl.
- Browser
- Download file 32.6 kB
-
https://huggingface.co/spaces/mcshoja/FoodInsecurityDashboard/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/mcshoja/FoodInsecurityDashboard/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/mcshoja/FoodInsecurityDashboard/resolve/main/src/streamlit_app.py
32.6 kB
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import json | |
| import joblib | |
| import re | |
| from pathlib import Path | |
| from datetime import datetime | |
| from dateutil.relativedelta import relativedelta | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| # ------------------------------------------------------- | |
| # PATHS | |
| # ------------------------------------------------------- | |
| BASE_DIR = Path(__file__).resolve().parent | |
| def p(name: str) -> Path: | |
| return BASE_DIR / name | |
| # ------------------------------------------------------- | |
| # PAGE CONFIG | |
| # ------------------------------------------------------- | |
| st.set_page_config(page_title="Kenya IPC Phase Dashboard", layout="wide") | |
| # ------------------------------------------------------- | |
| # APP HEADER | |
| # ------------------------------------------------------- | |
| st.markdown( | |
| """ | |
| <h1 style="margin-bottom:0.2rem;">County-Level Food Insecurity Risk Prediction Dashboard (Kenya)</h1> | |
| <div class="small-note" style="margin-top:0;"> | |
| Predicting IPC Phase 3+ (Crisis and above) risk to support monitoring, planning, and targeted response. | |
| </div> | |
| <hr/> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| # ------------------------------------------------------- | |
| # CSS | |
| # ------------------------------------------------------- | |
| st.markdown( | |
| """ | |
| <style> | |
| .block-container {padding-top:2rem;padding-bottom:2rem;} | |
| [data-testid="stSidebar"] {background: rgba(255,255,255,0.02);} | |
| .card {background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06); | |
| border-radius:16px;padding:14px;margin-bottom:10px;} | |
| .small-note {opacity:0.78;font-size:0.92rem;} | |
| .legend-dot {display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:8px;} | |
| div[data-testid="stMetricValue"] {font-size: 2rem;} | |
| hr {border:none;border-top:1px solid rgba(255,255,255,0.08); margin:0.6rem 0;} | |
| .band-pill {display:inline-block;padding:2px 10px;border-radius:999px;font-weight:700;} | |
| </style> | |
| """, | |
| unsafe_allow_html=True, | |
| ) | |
| # ------------------------------------------------------- | |
| # LOADERS | |
| # ------------------------------------------------------- | |
| def load_csv(filename: str) -> pd.DataFrame: | |
| return pd.read_csv(p(filename)) | |
| def load_geojson(filename: str) -> dict: | |
| with open(p(filename), "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| def load_model(filename: str): | |
| return joblib.load(p(filename)) | |
| def load_json(filename: str): | |
| with open(p(filename), "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| def load_optional_csv(filename: str) -> pd.DataFrame | None: | |
| fp = p(filename) | |
| if not fp.exists(): | |
| return None | |
| try: | |
| return pd.read_csv(fp) | |
| except Exception: | |
| return None | |
| # ------------------------------------------------------- | |
| # STANDARDIZATION | |
| # ------------------------------------------------------- | |
| def normalize_county_name(x) -> str: | |
| if pd.isna(x): | |
| return "" | |
| s = str(x).strip() | |
| s = " ".join(s.split()) | |
| s = s.replace("&", "and") | |
| s = s.title() | |
| s = s.replace("Elgeyo Marakwet", "Elgeyo-Marakwet") | |
| s = s.replace("Taita Taveta", "Taita-Taveta") | |
| s = s.replace("Tharaka Nithi", "Tharaka-Nithi") | |
| return s | |
| def county_key(x) -> str: | |
| if pd.isna(x): | |
| return "" | |
| s = str(x).strip().lower() | |
| s = s.replace("&", "and") | |
| return re.sub(r"[^a-z0-9]+", "", s) | |
| def detect_month_col(df: pd.DataFrame) -> str | None: | |
| candidates = ["month", "Month", "date", "Date", "TIME_PERIOD", "time_period", "assessment_month", "Assessment_Month"] | |
| for c in candidates: | |
| if c in df.columns: | |
| return c | |
| for c in df.columns: | |
| if "month" in c.lower(): | |
| return c | |
| return None | |
| def detect_county_col(df: pd.DataFrame) -> str | None: | |
| candidates = ["county", "County", "admin1", "Admin1", "Admin 1", "Admin_1"] | |
| for c in candidates: | |
| if c in df.columns: | |
| return c | |
| for c in df.columns: | |
| if "county" in c.lower(): | |
| return c | |
| return None | |
| def detect_risk_col(df: pd.DataFrame) -> str | None: | |
| candidates = ["risk_proba", "risk_probability", "Risk_Probability", "risk_prob", "probability", "proba"] | |
| for c in candidates: | |
| if c in df.columns: | |
| return c | |
| for c in df.columns: | |
| lc = c.lower() | |
| if ("risk" in lc and "prob" in lc) or (lc in ["risk", "proba", "probability"]): | |
| return c | |
| return None | |
| def coerce_month(df: pd.DataFrame) -> pd.DataFrame: | |
| mcol = detect_month_col(df) | |
| if mcol is not None and mcol != "month": | |
| df = df.rename(columns={mcol: "month"}) | |
| if "month" in df.columns: | |
| df["month"] = pd.to_datetime(df["month"], errors="coerce") | |
| df["month"] = df["month"].dt.to_period("M").dt.to_timestamp() | |
| return df | |
| def coerce_county(df: pd.DataFrame) -> pd.DataFrame: | |
| ccol = detect_county_col(df) | |
| if ccol is not None and ccol != "county": | |
| df = df.rename(columns={ccol: "county"}) | |
| if "county" in df.columns: | |
| df["county"] = df["county"].map(normalize_county_name) | |
| df["county_key"] = df["county"].map(county_key) | |
| return df | |
| def coerce_risk(df: pd.DataFrame) -> pd.DataFrame: | |
| rcol = detect_risk_col(df) | |
| if rcol is not None and rcol != "risk_proba": | |
| df = df.rename(columns={rcol: "risk_proba"}) | |
| if "risk_proba" in df.columns: | |
| df["risk_proba"] = pd.to_numeric(df["risk_proba"], errors="coerce").clip(0, 1) | |
| return df | |
| # ------------------------------------------------------- | |
| # GEOJSON HELPERS (BORROWED IDEA: USE RAW PROPERTY VALUES) | |
| # ------------------------------------------------------- | |
| def geojson_detect_county_key(gj: dict) -> str: | |
| features = gj.get("features", []) | |
| if not features: | |
| return "properties.shapeName" | |
| props = features[0].get("properties", {}) | |
| keys = list(props.keys()) | |
| preferred = [] | |
| for k in keys: | |
| lk = k.lower() | |
| if "shapename" in lk or (("county" in lk or "name" in lk) and "code" not in lk and "id" not in lk): | |
| preferred.append(k) | |
| if preferred: | |
| return f"properties.{preferred[0]}" | |
| for k in keys: | |
| if isinstance(props.get(k), str): | |
| return f"properties.{k}" | |
| return "properties.shapeName" | |
| def build_geo_base(gj: dict) -> tuple[str, pd.DataFrame, dict]: | |
| """ | |
| Returns: | |
| - featureidkey string | |
| - base dataframe with all polygons (47 rows): county, county_key, geo_value | |
| - lookup dict: normalized county -> raw geo_value | |
| """ | |
| featureidkey = geojson_detect_county_key(gj) | |
| prop = featureidkey.split(".", 1)[1] if featureidkey.startswith("properties.") else featureidkey | |
| rows = [] | |
| lookup = {} | |
| for ft in gj.get("features", []): | |
| props = ft.get("properties", {}) | |
| raw = props.get(prop, "") | |
| pretty = normalize_county_name(raw) | |
| key = county_key(raw) | |
| if raw and key: | |
| rows.append({"county": pretty, "county_key": key, "geo_value": raw}) | |
| lookup[pretty] = raw | |
| base = pd.DataFrame(rows).drop_duplicates(subset=["county_key"]).sort_values("county") | |
| return featureidkey, base, lookup | |
| # ------------------------------------------------------- | |
| # RISK + IPC | |
| # ------------------------------------------------------- | |
| def risk_band(p: float, thr: float) -> str: | |
| if pd.isna(p): | |
| return "Unknown" | |
| if p < thr: | |
| return "Secure" | |
| if p < min(thr + 0.15, 1.0): | |
| return "Watch" | |
| if p < min(thr + 0.35, 1.0): | |
| return "High" | |
| return "Extreme" | |
| RISK_COLORS = { | |
| "Secure": "#16a34a", | |
| "Watch": "#facc15", | |
| "High": "#f97316", | |
| "Extreme": "#dc2626", | |
| "Unknown": "#6b7280", | |
| } | |
| RISK_ORDER = ["Secure", "Watch", "High", "Extreme", "Unknown"] | |
| def band_badge_html(band: str) -> str: | |
| c = RISK_COLORS.get(band, "#6b7280") | |
| return f"<span class='band-pill' style='background:{c}22;border:1px solid {c}66;color:{c};'>{band}</span>" | |
| # ------------------------------------------------------- | |
| # HUMAN-FRIENDLY NAMES FOR FEATURES (Scenario inputs + Drivers) | |
| # ------------------------------------------------------- | |
| FEATURE_LABELS = { | |
| "is_ASAL": "Arid/Semi-Arid county (ASAL)", | |
| "vim": "Vegetation health (greenness)", | |
| "r3q": "Rainfall (3-month total)", | |
| "r1q": "Rainfall (1-month total)", | |
| "r1h": "Rainfall intensity (1-month)", | |
| "r3h": "Rainfall intensity (3-month)", | |
| "maize_price_per_kg": "Maize price (KES per kg)", | |
| "price_pct_change": "Food price change (%)", | |
| } | |
| FEATURE_HELP = { | |
| "is_ASAL": "1 means the county is classified as ASAL; 0 means non-ASAL.", | |
| "vim": "Higher usually means greener vegetation; lower can indicate drought stress.", | |
| "r3q": "Total rainfall over the recent 3-month window.", | |
| "r1q": "Total rainfall for the most recent month.", | |
| "maize_price_per_kg": "Market price of maize per kilogram (KES).", | |
| "price_pct_change": "Percent change in a food price index compared to the previous period.", | |
| } | |
| def humanize_feature_name(f: str) -> str: | |
| if f in FEATURE_LABELS: | |
| return FEATURE_LABELS[f] | |
| m = re.match(r"^(.*)_lag_(\d+)$", str(f)) | |
| if m: | |
| base = m.group(1) | |
| n = int(m.group(2)) | |
| base_label = FEATURE_LABELS.get(base, base.replace("_", " ").title()) | |
| # Simple phrasing a normal user understands | |
| if n == 1: | |
| return f"{base_label} (1 month ago)" | |
| return f"{base_label} ({n} months ago)" | |
| return str(f).replace("_", " ").title() | |
| def feature_help_text(f: str) -> str: | |
| if f in FEATURE_HELP: | |
| return FEATURE_HELP[f] | |
| m = re.match(r"^(.*)_lag_(\d+)$", str(f)) | |
| if m: | |
| base = m.group(1) | |
| return FEATURE_HELP.get(base, "A past (lagged) value of this factor.") | |
| return "Model input used to estimate IPC Phase 3+ risk." | |
| # IPC Phase reference (definition + colors) | |
| ipc_table = pd.DataFrame( | |
| [ | |
| [1, "Minimal", "Households meet basic food needs without atypical coping."], | |
| [2, "Stressed", "Basic food needs met, but cannot afford essential non-food needs."], | |
| [3, "Crisis", "Food gaps and/or high coping; requires urgent action."], | |
| [4, "Emergency", "Large food gaps; very high malnutrition; excess mortality risk."], | |
| [5, "Famine", "Extreme lack of food; starvation, death, destitution."], | |
| ], | |
| columns=["IPC Phase", "Label", "Interpretation"], | |
| ) | |
| IPC_PHASE_COLORS = {1: "#16a34a", 2: "#84cc16", 3: "#facc15", 4: "#f97316", 5: "#dc2626"} | |
| def style_ipc_table(df: pd.DataFrame): | |
| d = df.copy() | |
| def row_style(row): | |
| c = IPC_PHASE_COLORS.get(int(row["IPC Phase"]), "#6b7280") | |
| return [f"background-color: {c}22; border-left: 6px solid {c};"] * len(row) | |
| sty = d.style.apply(row_style, axis=1) | |
| try: | |
| sty = sty.hide(axis="index") | |
| except Exception: | |
| pass | |
| return sty | |
| def styled_df_for_display(df: pd.DataFrame, thr: float): | |
| d = df.copy() | |
| if "risk_proba" in d.columns: | |
| d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce").clip(0, 1) | |
| d["band"] = d["risk_proba"].apply(lambda x: risk_band(x, thr)) | |
| d["class"] = np.where(d["risk_proba"] >= thr, "At Risk", "Secure") | |
| else: | |
| d["band"] = "Unknown" | |
| d["class"] = "Unknown" | |
| def row_style(row): | |
| band = row.get("band", "Unknown") | |
| color = RISK_COLORS.get(band, "#6b7280") | |
| return [f"background-color: {color}22; border-left: 6px solid {color};"] * len(row) | |
| sty = d.style.apply(row_style, axis=1) | |
| if "risk_proba" in d.columns: | |
| sty = sty.format({"risk_proba": "{:.3f}"}) | |
| try: | |
| sty = sty.hide(axis="index") | |
| except Exception: | |
| pass | |
| return d, sty | |
| # ------------------------------------------------------- | |
| # LOAD DATA | |
| # ------------------------------------------------------- | |
| hist = coerce_month(coerce_risk(coerce_county(load_csv("predictions_historical.csv")))) | |
| forecast = coerce_month(coerce_risk(coerce_county(load_csv("predictions_forecast_next_month.csv")))) | |
| national = coerce_month(load_csv("national_trend.csv")) | |
| top10 = coerce_month(coerce_risk(coerce_county(load_csv("top10_by_month.csv")))) | |
| baseline = coerce_county(load_csv("baseline_latest_features.csv")) | |
| feature_importance = load_csv("feature_importance.csv") | |
| geojson = load_geojson("kenya_counties.geojson") | |
| model = load_model("model.joblib") | |
| FEATURES = load_json("features.json") | |
| # Optional observed IPC phases file (exact phase 1–5). This is the only way to show "exact phase". | |
| # File name expected: ipc_phases_county_month.csv with columns: county, month, ipc_phase (1–5) | |
| ipc_obs = load_optional_csv("ipc_phases_county_month.csv") | |
| if ipc_obs is not None: | |
| ipc_obs = coerce_month(coerce_county(ipc_obs)) | |
| if "ipc_phase" in ipc_obs.columns: | |
| ipc_obs["ipc_phase"] = pd.to_numeric(ipc_obs["ipc_phase"], errors="coerce").astype("Int64") | |
| # National trend robustness | |
| if "national_avg_risk" not in national.columns: | |
| rc = detect_risk_col(national) | |
| if rc and rc != "national_avg_risk": | |
| national = national.rename(columns={rc: "national_avg_risk"}) | |
| national["national_avg_risk"] = pd.to_numeric(national.get("national_avg_risk", np.nan), errors="coerce") | |
| # Feature importance robustness | |
| if "feature" not in feature_importance.columns: | |
| for c in feature_importance.columns: | |
| if "feature" in c.lower(): | |
| feature_importance = feature_importance.rename(columns={c: "feature"}) | |
| if "importance" not in feature_importance.columns: | |
| for c in feature_importance.columns: | |
| if "import" in c.lower(): | |
| feature_importance = feature_importance.rename(columns={c: "importance"}) | |
| if "importance" in feature_importance.columns: | |
| feature_importance["importance"] = pd.to_numeric(feature_importance["importance"], errors="coerce") | |
| # Month anchors | |
| if "month" not in hist.columns or hist["month"].isna().all(): | |
| st.error("Historical predictions file is missing a usable month column.") | |
| st.stop() | |
| latest_hist_month = hist["month"].max() | |
| # Forecast month (use file if present; else next month) | |
| if "month" in forecast.columns and not forecast["month"].isna().all(): | |
| forecast_month = forecast["month"].max() | |
| else: | |
| forecast_month = datetime.today().replace(day=1) + relativedelta(months=1) | |
| forecast_month = pd.to_datetime(forecast_month).to_period("M").to_timestamp() | |
| def get_county_forecast_probability(county_name: str) -> float | None: | |
| """Return forecast probability for the selected county (for forecast_month when available).""" | |
| if forecast is None or forecast.empty or "risk_proba" not in forecast.columns: | |
| return None | |
| ck = county_key(county_name) | |
| d = forecast.copy() | |
| if "county_key" not in d.columns: | |
| d = coerce_county(d) | |
| # Prefer the explicit forecast_month if the forecast file contains month | |
| if "month" in d.columns and not d["month"].isna().all(): | |
| m = pd.to_datetime(forecast_month).to_period("M").to_timestamp() | |
| tmp = d[(d["county_key"] == ck) & (d["month"] == m)].copy() | |
| if tmp.empty: | |
| # fallback: latest forecast available for that county | |
| tmp = d[d["county_key"] == ck].sort_values("month", ascending=False).head(1) | |
| else: | |
| tmp = d[d["county_key"] == ck].head(1) | |
| if tmp.empty: | |
| return None | |
| return float(pd.to_numeric(tmp["risk_proba"], errors="coerce").clip(0, 1).iloc[0]) | |
| # Geo base (this is what ensures all 47 polygons can render) | |
| featureidkey, GEO_BASE, GEO_LOOKUP = build_geo_base(geojson) | |
| if GEO_BASE.empty or GEO_BASE.shape[0] < 40: | |
| st.error("GeoJSON county extraction failed. Your GeoJSON may not contain county names in the detected properties.") | |
| st.stop() | |
| # ------------------------------------------------------- | |
| # CACHED PREP (ALL 47 ALWAYS) | |
| # ------------------------------------------------------- | |
| def prepare_month_all47(pred_df: pd.DataFrame, month_value: pd.Timestamp | None, thr: float) -> pd.DataFrame: | |
| base = GEO_BASE.copy() | |
| d = pred_df.copy() | |
| if "month" in d.columns and month_value is not None: | |
| d = d[d["month"] == month_value].copy() | |
| # If predictions have duplicates per county-month, keep max risk (conservative) | |
| if "risk_proba" in d.columns: | |
| d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce").clip(0, 1) | |
| d = d.sort_values("risk_proba", ascending=False) | |
| d = d.drop_duplicates(subset=["county_key"], keep="first") | |
| merged = base.merge( | |
| d[["county_key", "risk_proba"]] if "risk_proba" in d.columns else d[["county_key"]], | |
| on="county_key", | |
| how="left", | |
| ) | |
| merged["risk_proba"] = pd.to_numeric(merged.get("risk_proba", np.nan), errors="coerce").clip(0, 1) | |
| merged["band"] = merged["risk_proba"].apply(lambda x: risk_band(x, thr)) | |
| merged["class"] = np.where(merged["risk_proba"] >= thr, "At Risk", "Secure") | |
| return merged | |
| def attach_ipc_phase(df47: pd.DataFrame, month_value: pd.Timestamp) -> pd.DataFrame: | |
| out = df47.copy() | |
| out["ipc_phase"] = pd.NA | |
| if ipc_obs is None: | |
| return out | |
| if "month" not in ipc_obs.columns or "ipc_phase" not in ipc_obs.columns: | |
| return out | |
| m = pd.to_datetime(month_value).to_period("M").to_timestamp() | |
| tmp = ipc_obs[ipc_obs["month"] == m].copy() | |
| if tmp.empty: | |
| return out | |
| tmp = tmp.sort_values("ipc_phase", ascending=False).drop_duplicates(subset=["county_key"], keep="first") | |
| out = out.merge(tmp[["county_key", "ipc_phase"]], on="county_key", how="left", suffixes=("", "_obs")) | |
| if "ipc_phase_obs" in out.columns: | |
| out["ipc_phase"] = out["ipc_phase_obs"] | |
| out = out.drop(columns=["ipc_phase_obs"]) | |
| return out | |
| # ------------------------------------------------------- | |
| # SIDEBAR | |
| # ------------------------------------------------------- | |
| st.sidebar.markdown("## System Controls") | |
| threshold = st.sidebar.slider("Risk Threshold", 0.10, 0.90, 0.45, 0.01) | |
| page = st.sidebar.radio( | |
| "Navigation", | |
| ["National Situation", "Risk Map", "Scenario Simulator", "County Profile"], | |
| ) | |
| st.sidebar.markdown("### Risk Bands") | |
| for k in ["Secure", "Watch", "High", "Extreme"]: | |
| st.sidebar.markdown( | |
| f"<span class='legend-dot' style='background:{RISK_COLORS[k]}'></span>{k}", | |
| unsafe_allow_html=True, | |
| ) | |
| st.sidebar.markdown("<div class='small-note'>Bands adapt when you move the threshold slider.</div>", unsafe_allow_html=True) | |
| # ======================================================= | |
| # NATIONAL SITUATION | |
| # ======================================================= | |
| if page == "National Situation": | |
| st.title("National Risk Situation") | |
| latest_data = hist[hist["month"] == latest_hist_month].copy() | |
| latest_data["risk_proba"] = pd.to_numeric(latest_data["risk_proba"], errors="coerce").clip(0, 1) | |
| col1, col2, col3, col4 = st.columns(4) | |
| col1.metric("Observed Month (Latest)", latest_hist_month.strftime("%B %Y")) | |
| col2.metric("National Risk Index (Observed)", f"{latest_data['risk_proba'].mean():.2f}") | |
| col3.metric("Counties Above Threshold (Observed)", int((latest_data["risk_proba"] >= threshold).sum())) | |
| col4.metric("Projection Month", forecast_month.strftime("%B %Y")) | |
| fig = go.Figure() | |
| nat = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month") | |
| fig.add_trace(go.Scatter(x=nat["month"], y=nat["national_avg_risk"], mode="lines", name="Observed")) | |
| if not forecast.empty and "risk_proba" in forecast.columns: | |
| proj_y = float(pd.to_numeric(forecast["risk_proba"], errors="coerce").clip(0, 1).mean()) | |
| fig.add_trace(go.Scatter(x=[forecast_month], y=[proj_y], mode="markers", name="Projection")) | |
| if len(nat) > 0: | |
| fig.add_trace(go.Scatter( | |
| x=[nat["month"].iloc[-1], forecast_month], | |
| y=[nat["national_avg_risk"].iloc[-1], proj_y], | |
| mode="lines", | |
| line=dict(dash="dot"), | |
| showlegend=False | |
| )) | |
| fig.add_hline(y=threshold, line_dash="dot") | |
| fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10)) | |
| st.plotly_chart(fig, use_container_width=True) | |
| st.subheader("Top Counties Above Threshold (Predicted IPC Phase 3+ Risk)") | |
| top_risk = ( | |
| latest_data[latest_data["risk_proba"] >= threshold] | |
| .sort_values("risk_proba", ascending=False) | |
| .head(20)[["county", "risk_proba"]] | |
| .copy() | |
| ) | |
| if top_risk.empty: | |
| st.info("No counties are above the current threshold in the latest observed month.") | |
| else: | |
| top_risk["band"] = top_risk["risk_proba"].apply(lambda x: risk_band(x, threshold)) | |
| _, top_sty = styled_df_for_display(top_risk, threshold) | |
| st.dataframe(top_sty, use_container_width=True) | |
| with st.expander("IPC Phase Reference", expanded=False): | |
| st.dataframe(style_ipc_table(ipc_table), use_container_width=True) | |
| # ======================================================= | |
| # RISK MAP | |
| # ======================================================= | |
| elif page == "Risk Map": | |
| st.title("County Risk Map") | |
| view = st.radio("View", ["Historical", "Forecast"], horizontal=True) | |
| filt = st.radio( | |
| "Filter", | |
| ["All", "At Risk (>= threshold)", "Secure (< threshold)"], | |
| horizontal=True, | |
| ) | |
| layer_options = ["Predicted IPC Phase 3+ Risk"] | |
| if ipc_obs is not None and view == "Historical": | |
| layer_options.append("Observed IPC Phase (Exact 1–5)") | |
| layer = st.radio("Map Layer", layer_options, horizontal=True) | |
| if view == "Historical": | |
| months = sorted(hist["month"].dropna().unique()) | |
| selected_month = st.selectbox("Month", months, index=len(months) - 1) | |
| display_month = pd.to_datetime(selected_month).to_period("M").to_timestamp() | |
| df47 = prepare_month_all47(hist, display_month, threshold) | |
| else: | |
| if "month" in forecast.columns and not forecast["month"].isna().all(): | |
| display_month = forecast["month"].max() | |
| df47 = prepare_month_all47(forecast, display_month, threshold) | |
| else: | |
| display_month = forecast_month | |
| df47 = prepare_month_all47(forecast, None, threshold) | |
| if layer == "Observed IPC Phase (Exact 1–5)": | |
| df47 = attach_ipc_phase(df47, display_month) | |
| st.markdown(f"**Displaying:** {display_month.strftime('%B %Y')}") | |
| st.markdown(f"<div class='small-note'>Map always renders all counties. Filter affects emphasis and the ranked list.</div>", unsafe_allow_html=True) | |
| df_map = df47.copy() | |
| df_list = df47.copy() | |
| if layer == "Predicted IPC Phase 3+ Risk": | |
| if filt == "At Risk (>= threshold)": | |
| keep = df47["risk_proba"] >= threshold | |
| df_list = df47[keep].copy() | |
| df_map.loc[~keep, "band"] = "Unknown" | |
| elif filt == "Secure (< threshold)": | |
| keep = df47["risk_proba"] < threshold | |
| df_list = df47[keep].copy() | |
| df_map.loc[~keep, "band"] = "Unknown" | |
| else: | |
| phase = pd.to_numeric(df47["ipc_phase"], errors="coerce") | |
| if filt == "At Risk (>= threshold)": | |
| keep = phase >= 3 | |
| df_list = df47[keep].copy() | |
| df_map.loc[~keep, "ipc_phase"] = pd.NA | |
| elif filt == "Secure (< threshold)": | |
| keep = phase <= 2 | |
| df_list = df47[keep].copy() | |
| df_map.loc[~keep, "ipc_phase"] = pd.NA | |
| left, right = st.columns([2.2, 1.0], gap="large") | |
| with left: | |
| if layer == "Predicted IPC Phase 3+ Risk": | |
| fig = px.choropleth_mapbox( | |
| df_map, | |
| geojson=geojson, | |
| locations="geo_value", | |
| featureidkey=featureidkey, | |
| color="band", | |
| category_orders={"band": RISK_ORDER}, | |
| color_discrete_map=RISK_COLORS, | |
| hover_name="county", | |
| hover_data={"risk_proba": ":.3f", "band": True}, | |
| mapbox_style="carto-positron", | |
| zoom=5.2, | |
| center={"lat": 0.2, "lon": 37.8}, | |
| opacity=0.85, | |
| height=650, | |
| ) | |
| fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, showlegend=False) | |
| st.plotly_chart(fig, use_container_width=True) | |
| else: | |
| df_map["_ipc_phase_str"] = df_map["ipc_phase"].astype("Int64").astype(str) | |
| df_map.loc[df_map["ipc_phase"].isna(), "_ipc_phase_str"] = "Unknown" | |
| ipc_color_map = { | |
| "1": IPC_PHASE_COLORS[1], | |
| "2": IPC_PHASE_COLORS[2], | |
| "3": IPC_PHASE_COLORS[3], | |
| "4": IPC_PHASE_COLORS[4], | |
| "5": IPC_PHASE_COLORS[5], | |
| "Unknown": "#6b7280", | |
| } | |
| fig = px.choropleth_mapbox( | |
| df_map, | |
| geojson=geojson, | |
| locations="geo_value", | |
| featureidkey=featureidkey, | |
| color="_ipc_phase_str", | |
| category_orders={"_ipc_phase_str": ["1", "2", "3", "4", "5", "Unknown"]}, | |
| color_discrete_map=ipc_color_map, | |
| hover_name="county", | |
| hover_data={"ipc_phase": True}, | |
| mapbox_style="carto-positron", | |
| zoom=5.2, | |
| center={"lat": 0.2, "lon": 37.8}, | |
| opacity=0.85, | |
| height=650, | |
| ) | |
| fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, showlegend=False) | |
| st.plotly_chart(fig, use_container_width=True) | |
| with st.expander("IPC Phase Reference", expanded=False): | |
| st.dataframe(style_ipc_table(ipc_table), use_container_width=True) | |
| with right: | |
| if layer == "Predicted IPC Phase 3+ Risk": | |
| st.subheader("Counties Sorted by Risk") | |
| ranked = df_list.sort_values("risk_proba", ascending=False)[["county", "risk_proba"]].copy() | |
| ranked["band"] = ranked["risk_proba"].apply(lambda x: risk_band(x, threshold)) | |
| _, ranked_sty = styled_df_for_display(ranked, threshold) | |
| st.dataframe(ranked_sty, use_container_width=True, height=650) | |
| else: | |
| st.subheader("Counties by Observed IPC Phase") | |
| ranked = df_list[["county", "ipc_phase"]].copy() | |
| ranked = ranked.sort_values(["ipc_phase", "county"], ascending=[False, True]) | |
| st.dataframe(ranked, use_container_width=True, height=650) | |
| # ======================================================= | |
| # SCENARIO SIMULATOR | |
| # ======================================================= | |
| elif page == "Scenario Simulator": | |
| st.title("Scenario Simulation") | |
| counties = sorted([c for c in baseline["county"].dropna().unique() if c]) | |
| county = st.selectbox("Select County", counties) | |
| base_row = baseline[baseline["county"] == county].copy() | |
| if base_row.empty: | |
| st.error("No baseline row found for this county.") | |
| st.stop() | |
| for f in FEATURES: | |
| if f not in base_row.columns: | |
| base_row[f] = np.nan | |
| x_base = base_row.iloc[[0]][FEATURES].copy() | |
| x_edit = x_base.copy() | |
| st.markdown("<div class='small-note'>Adjust inputs, then run prediction.</div>", unsafe_allow_html=True) | |
| # Common features if present (renamed to user-friendly labels) | |
| if "r3q_lag_1" in x_edit.columns: | |
| x_edit["r3q_lag_1"] = st.number_input( | |
| humanize_feature_name("r3q_lag_1"), | |
| value=float(x_edit["r3q_lag_1"].iloc[0]) if pd.notna(x_edit["r3q_lag_1"].iloc[0]) else 0.0, | |
| help=feature_help_text("r3q_lag_1"), | |
| ) | |
| if "price_pct_change" in x_edit.columns: | |
| x_edit["price_pct_change"] = st.number_input( | |
| humanize_feature_name("price_pct_change"), | |
| value=float(x_edit["price_pct_change"].iloc[0]) if pd.notna(x_edit["price_pct_change"].iloc[0]) else 0.0, | |
| help=feature_help_text("price_pct_change"), | |
| ) | |
| with st.expander("Advanced inputs", expanded=False): | |
| for f in FEATURES: | |
| cur = x_edit[f].iloc[0] | |
| x_edit[f] = st.number_input( | |
| humanize_feature_name(f), | |
| value=float(cur) if pd.notna(cur) else 0.0, | |
| key=f"{county}_{f}", | |
| help=feature_help_text(f), | |
| ) | |
| if st.button("Run Prediction", use_container_width=True): | |
| try: | |
| base_prob = float(model.predict_proba(x_base)[0][1]) | |
| new_prob = float(model.predict_proba(x_edit)[0][1]) | |
| delta = new_prob - base_prob | |
| c1, c2, c3 = st.columns(3) | |
| c1.metric("Baseline Probability (IPC Phase 3+)", f"{base_prob:.4f}") | |
| c2.metric("Scenario Probability (IPC Phase 3+)", f"{new_prob:.4f}") | |
| c3.metric("Change (Δ)", f"{delta:.4f}") | |
| band = risk_band(new_prob, threshold) | |
| st.markdown( | |
| f"**Risk Band:** {band_badge_html(band)}", | |
| unsafe_allow_html=True, | |
| ) | |
| st.markdown("<div class='small-note'>This model outputs IPC Phase 3+ probability. It does not output exact IPC Phase (1–5).</div>", unsafe_allow_html=True) | |
| except Exception as e: | |
| st.error(f"Prediction failed: {e}") | |
| # ======================================================= | |
| # COUNTY PROFILE | |
| # ======================================================= | |
| elif page == "County Profile": | |
| st.title("County Profile") | |
| counties = sorted(hist["county"].dropna().unique()) | |
| county = st.selectbox("Select County", counties) | |
| county_data = hist[hist["county"] == county].sort_values("month").copy() | |
| county_data = county_data.dropna(subset=["month", "risk_proba"]) | |
| if county_data.empty: | |
| st.warning("No historical data available for this county.") | |
| st.stop() | |
| latest = float(pd.to_numeric(county_data["risk_proba"], errors="coerce").clip(0, 1).iloc[-1]) | |
| latest_band = risk_band(latest, threshold) | |
| next_prob = get_county_forecast_probability(county) | |
| next_band = risk_band(next_prob, threshold) if next_prob is not None else "Unknown" | |
| m1, m2 = st.columns(2) | |
| with m1: | |
| st.metric("Latest Risk Probability (IPC Phase 3+)", f"{latest:.2f}") | |
| st.markdown(f"{band_badge_html(latest_band)}", unsafe_allow_html=True) | |
| with m2: | |
| # Next month forecast (e.g., Nov) | |
| if next_prob is None: | |
| st.metric(f"Next Month Forecast ({forecast_month.strftime('%B %Y')})", "N/A") | |
| st.markdown(f"{band_badge_html('Unknown')}", unsafe_allow_html=True) | |
| else: | |
| st.metric(f"Next Month Forecast ({forecast_month.strftime('%B %Y')})", f"{float(next_prob):.2f}") | |
| st.markdown(f"{band_badge_html(next_band)}", unsafe_allow_html=True) | |
| # Optional: exact observed IPC phase (if file exists) | |
| if ipc_obs is not None: | |
| m = county_data["month"].iloc[-1] | |
| tmp = ipc_obs[(ipc_obs["county"] == county) & (ipc_obs["month"] == m)] | |
| if not tmp.empty and "ipc_phase" in tmp.columns and pd.notna(tmp["ipc_phase"].iloc[0]): | |
| st.metric("Observed IPC Phase (Exact)", int(tmp["ipc_phase"].iloc[0])) | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter(x=county_data["month"], y=county_data["risk_proba"], mode="lines+markers", name="Risk")) | |
| fig.add_hline(y=threshold, line_dash="dot") | |
| fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10)) | |
| st.plotly_chart(fig, use_container_width=True) | |
| st.subheader("Historical Levels") | |
| tbl = county_data[["month", "risk_proba"]].copy() | |
| tbl["band"] = tbl["risk_proba"].apply(lambda x: risk_band(x, threshold)) | |
| tbl = tbl.sort_values("month", ascending=False) | |
| _, tbl_sty = styled_df_for_display(tbl, threshold) | |
| st.dataframe(tbl_sty, use_container_width=True) | |
| # Rename drivers for normal users + human-friendly feature names | |
| st.subheader("Key Factors Behind the Risk (Model Drivers)") | |
| st.markdown("<div class='small-note'>These are the strongest overall factors the model learned from data (global drivers).</div>", unsafe_allow_html=True) | |
| if "feature" in feature_importance.columns and "importance" in feature_importance.columns: | |
| top_drivers = ( | |
| feature_importance.dropna(subset=["feature", "importance"]) | |
| .sort_values("importance", ascending=False) | |
| .head(6) | |
| ) | |
| for _, r in top_drivers.iterrows(): | |
| f = str(r["feature"]) | |
| st.markdown(f"- **{humanize_feature_name(f)}**") | |
| else: | |
| st.info("feature_importance.csv is missing expected columns (feature, importance).") |