idiouf's picture
Upload 19 files
419e4fd verified
Raw History Blame Contribute Delete
71.8 kB
"""Africa Conservation & Human Development — an exploratory dashboard. Built around the question Liesbet Steer put after Li et al. (2024): do the human conditions around protected areas explain whether conservation and local development pull together or against each other? """ from __future__ import annotations import inspect import os from string import Template import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go import streamlit as st import streamlit.components.v1 as components import analysis as an import methods import sources as src st.set_page_config( page_title="Africa Conservation & Human Development", page_icon="🌍", layout="wide", initial_sidebar_state="auto", menu_items={ "About": ( "Exploratory dashboard on protected areas and the human conditions " "around them in Africa. Framed on Li et al. (2024), *The synergy " "between protected area effectiveness and economic growth*, " "Current Biology 34." ) }, ) AUTHOR = { "name": "Dr. Ibrahima Diouf", "affiliation": "UCAD–ESP/LPAO-SF · Université de Labé–FST", "links": [ ("🌐", "Website", "https://scientific-hub-lab.github.io/Dr-Ibrahima-Diouf/"), ("🤗", "Hugging Face", "https://huggingface.co/idiouf"), ("🆔", "ORCID", "https://orcid.org/0000-0002-3157-0925"), ("in", "LinkedIn", "https://www.linkedin.com/in/dr-ibrahima-diouf-610872108/"), ("🎓", "Google Scholar", "https://scholar.google.com/citations?user=phsMm7sAAAAJ&hl=fr"), ("🔗", "This Space", "https://huggingface.co/spaces/idiouf/" "African-Conservation-Human-Development-Observatory"), ], } SEQ_BLUE = ["#EEF4FB", "#D2E3F4", "#AACBE9", "#7FB0DC", "#5493CB", "#2F76B4", "#1B5B95", "#114374", "#0A2C51"] SEQ_GREEN = ["#F0F7F2", "#D3E9DA", "#A9D5BA", "#7CBE99", "#51A57A", "#33885E", "#216A48", "#154E34", "#0C3322"] DIVERGING = ["#8C2D3F", "#C05B5F", "#E39A88", "#F5D0BC", "#F2F2EF", "#C4DCE4", "#8CBCD1", "#4E90B5", "#1F5F8F"] CATEGORICAL = ["#2F6FED", "#0E9F9B", "#E8873D", "#A64CB0", "#3FA34D", "#D6455D", "#7B6FE8", "#B08A24", "#3FA3D9", "#7A8896"] PALETTES = { "Dark": { "bg": "#070F1A", "panel": "#0D1E30", "panel2": "#122840", "border": "#1D3A55", "border_soft": "#162E45", "text": "#F2F7FC", "muted": "#9AB0C6", "accent": "#4A9BFF", "accent_soft": "rgba(74,155,255,.15)", "positive": "#3FBF8F", "negative": "#F2778D", "shadow": "0 10px 30px rgba(0,0,0,.35)", "hero1": "#0B2C52", "hero2": "#14503C", "hero3": "#5C2350", "map_style": "carto-darkmatter", }, "Light": { "bg": "#F2F6FA", "panel": "#FFFFFF", "panel2": "#F6F9FD", "border": "#D8E3EF", "border_soft": "#E6EDF5", "text": "#0F2439", "muted": "#54687E", "accent": "#1668CE", "accent_soft": "rgba(22,104,206,.10)", "positive": "#12805C", "negative": "#B93049", "shadow": "0 8px 24px rgba(15,36,57,.08)", "hero1": "#0B3A69", "hero2": "#1B6B4F", "hero3": "#7A2359", "map_style": "carto-positron", }, } # --------------------------------------------------------------------------- # Translations # --------------------------------------------------------------------------- TEXT = { "English": { "title": "Conservation & Human Development in Africa", "subtitle": ("Where protected areas sit, what human conditions surround them, " "and whether the two move together."), "framing": ("Framed on Li et al. (2024), Current Biology — protected areas and " "neighbouring communities fall into four relationships: synergy, " "economy impaired, conservation impaired, retreat."), "nav": "Sections", "overview": "Overview", "areas": "Protected areas", "conditions": "Human conditions", "relationships": "Relationships", "trajectories": "Trajectories", "data": "Data & method", "filters": "Filters", "language": "Language / Langue", "appearance": "Appearance", "theme_hint": "dark by default · switch to light in ⋮ → Settings → Appearance.", "country": "Country", "countries": "Countries", "all_countries": "All of Africa", "indicator": "Human development indicator", "year": "Reference year", "kpi_pas": "Protected areas mapped", "kpi_countries": "Countries covered", "kpi_area": "Total reported area", "kpi_pressure": "Median pressure index", "map_title": "Protected areas on human development", "map_hint": "Colour is the country indicator; each dot is a protected area.", "no_data": "No data available for this selection.", "loading": "Loading data from the open sources…", "loading_map": "Downloading country boundaries…", "sources_ok": "sources loaded", "sources_failed": "source(s) unavailable", "select_pa": "Select a protected area", "search": "Search by name", "iucn": "IUCN category", "min_area": "Minimum area (km²)", "pressure": "Human pressure index", "pressure_help": ( "Rank-based 0–100 screening index: it says which parks sit in busier " "settings, not how many people live within 10 km of a boundary."), "pressure_built": "Built from:", "neighbours": "protected areas within 50 km", "profile": "Profile", "context": "Country context", "nearby": "Nearest protected areas", "education": "Education", "health": "Health", "income": "Income & poverty", "typology": "The four relationships", "quadrant": "Where each country falls", "cons_axis": "Conservation outcome", "dev_axis": "Human development outcome", "period": "Period", "vs_li": "Compared with Li et al. (2024), global", "this_dashboard": "This dashboard, Africa", "upload_title": "Add protected area effectiveness scores", "upload_help": ("Upload a CSV with a 'name' column and a 'score' column — " "for example Canopy PACE scores — to unlock the " "protected-area level analysis."), "upload_matched": "matched to mapped protected areas", "counterfactual_note": ("Li et al. compare each protected area with matched " "counterfactual sites. That is not possible from the open " "country series used here, so the reference point is the " "African median change over the same period. Read this as " "description, not causal attribution."), "status": "Connector status", "licence": "Licence", "rows": "Rows", "trend_title": "Trajectories, 1990–2024", "pick_countries": "Pick countries to compare", "conservation_ind": "Conservation indicator", "no_overlap": "These two indicators have no period in common", "typology_hint": ("Each country is placed by how its conservation and " "human development changes compare with the African median."), "coverage": "Coverage", "coverage_hint": "What each series actually contains", "first_year": "From", "last_year": "To", "observations": "Observations", "detailed": "Data, methods and analyses in detail", "detailed_hint": "Provenance, every computation, and what each analysis supports", "assoc_title": "Do the two axes move together?", "assoc_pos": "Conservation and human development gains went together:", "assoc_neg": "Conservation and human development gains pulled against each other:", "assoc_none": "The two moved close to independently:", "odds": "odds ratio", "assoc_note": ("The median split fixes each margin at 50/50, so the four shares " "are near-arithmetic; this association is the part the split does " "not force. See Data & method."), "demography": "Demography", "dependency": "Dependency", "projection": "Projection", "unit_col": "Unit", "source_col": "Source", }, "Français": { "title": "Conservation et développement humain en Afrique", "subtitle": ("Où se trouvent les aires protégées, quelles conditions humaines les " "entourent, et si les deux évoluent ensemble."), "framing": ("D'après Li et al. (2024), Current Biology — aires protégées et " "communautés voisines relèvent de quatre relations : synergie, " "économie entravée, conservation entravée, repli."), "nav": "Sections", "overview": "Vue d'ensemble", "areas": "Aires protégées", "conditions": "Conditions humaines", "relationships": "Relations", "trajectories": "Trajectoires", "data": "Données et méthode", "filters": "Filtres", "language": "Language / Langue", "appearance": "Apparence", "theme_hint": "sombre par défaut · passez en clair via ⋮ → Settings → Appearance.", "country": "Pays", "countries": "Pays", "all_countries": "Toute l'Afrique", "indicator": "Indicateur de développement humain", "year": "Année de référence", "kpi_pas": "Aires protégées cartographiées", "kpi_countries": "Pays couverts", "kpi_area": "Superficie totale déclarée", "kpi_pressure": "Indice de pression médian", "map_title": "Aires protégées et développement humain", "map_hint": "La couleur est l'indicateur national ; chaque point est une aire protégée.", "no_data": "Aucune donnée disponible pour cette sélection.", "loading": "Chargement des données depuis les sources ouvertes…", "loading_map": "Téléchargement des frontières nationales…", "sources_ok": "sources chargées", "sources_failed": "source(s) indisponible(s)", "select_pa": "Sélectionner une aire protégée", "search": "Rechercher par nom", "iucn": "Catégorie UICN", "min_area": "Superficie minimale (km²)", "pressure": "Indice de pression humaine", "pressure_help": ( "Indice de criblage 0–100 fondé sur les rangs : il indique quelles aires se " "trouvent dans les contextes les plus peuplés, non combien de personnes vivent " "à moins de 10 km d'une limite."), "pressure_built": "Construit à partir de :", "neighbours": "aires protégées à moins de 50 km", "profile": "Profil", "context": "Contexte national", "nearby": "Aires protégées les plus proches", "education": "Éducation", "health": "Santé", "income": "Revenu et pauvreté", "typology": "Les quatre relations", "quadrant": "Position de chaque pays", "cons_axis": "Résultat de conservation", "dev_axis": "Résultat de développement humain", "period": "Période", "vs_li": "Comparaison avec Li et al. (2024), monde", "this_dashboard": "Ce tableau de bord, Afrique", "upload_title": "Ajouter des scores d'efficacité des aires protégées", "upload_help": ("Déposez un CSV avec une colonne 'name' et une colonne 'score' — " "par exemple les scores PACE de Canopy — pour activer l'analyse " "au niveau des aires protégées."), "upload_matched": "appariées aux aires protégées cartographiées", "counterfactual_note": ("Li et al. comparent chaque aire protégée à des sites " "contrefactuels appariés. Ce n'est pas possible à partir des " "séries nationales ouvertes utilisées ici : la référence est " "donc la variation médiane africaine sur la même période. " "À lire comme une description, non comme une attribution causale."), "status": "État des connecteurs", "licence": "Licence", "rows": "Lignes", "trend_title": "Trajectoires, 1990–2024", "pick_countries": "Choisir des pays à comparer", "conservation_ind": "Indicateur de conservation", "no_overlap": "Ces deux indicateurs n'ont aucune période commune", "typology_hint": ("Chaque pays est situé selon la comparaison de ses variations " "de conservation et de développement humain à la médiane africaine."), "coverage": "Couverture", "coverage_hint": "Ce que contient réellement chaque série", "first_year": "De", "last_year": "À", "observations": "Observations", "detailed": "Données, méthodes et analyses en détail", "detailed_hint": "Provenance, chaque calcul, et ce que permet chaque analyse", "assoc_title": "Les deux axes évoluent-ils ensemble ?", "assoc_pos": "Conservation et développement humain ont progressé de concert :", "assoc_neg": "Conservation et développement humain se sont opposés :", "assoc_none": "Les deux ont évolué de façon quasi indépendante :", "odds": "rapport de cotes", "assoc_note": ("La coupe médiane fixe chaque marge à 50/50 : les quatre parts sont " "donc surtout arithmétiques ; cette association est ce que la coupe " "n'impose pas. Voir Données et méthode."), "demography": "Démographie", "dependency": "Dépendance", "projection": "Projection", "unit_col": "Unité", "source_col": "Source", }, } # --------------------------------------------------------------------------- # Streamlit compatibility + styling # --------------------------------------------------------------------------- _WIDTH_CACHE: dict[str, dict] = {} def stretch(fn) -> dict: key = getattr(fn, "__name__", str(fn)) if key not in _WIDTH_CACHE: try: supported = "width" in inspect.signature(fn).parameters except (TypeError, ValueError): supported = False _WIDTH_CACHE[key] = {"width": "stretch"} if supported else {"use_container_width": True} return _WIDTH_CACHE[key] # Both palettes ship (see the Dockerfile), so light and dark both render # correctly — native widgets, data grids and pop-overs included — and the reader # can switch at any time from ⋮ → Settings → Appearance. # # Streamlit has no API to choose which one a first-time reader gets: with two # palettes it follows the browser. DEFAULT_THEME closes that gap by writing the # reader's preference key once, on a first visit only, and never touching it # again. Set CONSERVATION_HD_THEME=auto to follow the browser instead. DEFAULT_THEME = os.environ.get("CONSERVATION_HD_THEME", "dark").strip().lower() def apply_default_theme(preference: str) -> None: """Seed the reader's theme choice on their very first visit. Streamlit writes its own preference key eagerly, with the value "System", before any component runs — so the mere presence of a key means nothing. Only "System" counts as 'no choice made'; an explicit "Light" or "Dark" is the reader's and is never touched. A sessionStorage flag makes the single reload idempotent, so this can never loop. """ if preference not in ("dark", "light"): return name = preference.capitalize() components.html( f""" <script> (function () {{ try {{ const store = window.parent.localStorage; if (window.parent.sessionStorage.getItem('themeSeeded')) return; const keys = Object.keys(store).filter(k => k.startsWith('stActiveTheme-')); const chosen = keys.some(k => {{ const v = (store.getItem(k) || '').replace(/"/g, ''); return v === 'Light' || v === 'Dark'; }}); window.parent.sessionStorage.setItem('themeSeeded', '1'); if (chosen) return; // the reader decided; leave it const path = window.parent.location.pathname || '/'; store.setItem('stActiveTheme-' + path + '-v2', JSON.stringify('{name}')); store.setItem('stActiveTheme-/-v2', JSON.stringify('{name}')); window.parent.location.reload(); }} catch (e) {{ /* a sandboxed frame just means the browser default wins */ }} }})(); </script> """, height=0, ) def active_theme() -> str: try: return "Light" if st.context.theme.type == "light" else "Dark" except Exception: return "Dark" if DEFAULT_THEME != "light" else "Light" CSS = Template(""" <style> @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap'); :root { --bg:$bg; --panel:$panel; --panel2:$panel2; --border:$border; --border-soft:$border_soft; --text:$text; --muted:$muted; --accent:$accent; --accent-soft:$accent_soft; --positive:$positive; --negative:$negative; --shadow:$shadow; --radius:16px; --radius-sm:10px; } html, body, [data-testid="stAppViewContainer"] { background:var(--bg); color:var(--text); font-family:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; -webkit-text-size-adjust:100%; } [data-testid="stHeader"] { background:transparent; } .block-container { max-width:1560px; padding:1.1rem 1.5rem 2.2rem; } h1,h2,h3,h4,p,span,label,li,div { color:var(--text); } [data-testid="stSidebar"] { background:var(--panel); border-right:1px solid var(--border-soft); } .side-brand { display:flex; align-items:center; gap:11px; padding:4px 2px 12px; } .side-brand .glyph { width:40px; height:40px; flex:0 0 40px; border-radius:12px; display:grid; place-items:center; font-size:1.25rem; background:linear-gradient(140deg,$hero1,var(--accent)); box-shadow:var(--shadow); } .side-brand .txt strong { font-size:.94rem; font-weight:800; line-height:1.15; display:block; } .side-brand .txt span { font-size:.72rem; color:var(--muted); } .side-label { font-size:.68rem; font-weight:800; letter-spacing:.09em; text-transform:uppercase; color:var(--muted); margin:14px 2px 6px; } .hero { position:relative; background:linear-gradient(118deg,$hero1 0%,$hero2 55%,$hero3 100%); border:1px solid rgba(255,255,255,.14); border-radius:20px; padding:26px 28px; margin-bottom:14px; box-shadow:var(--shadow); overflow:hidden; } .hero::after { content:""; position:absolute; inset:0; background:radial-gradient(circle at 85% -20%,rgba(255,255,255,.18),transparent 55%); pointer-events:none; } .hero h1, .hero h1 span, .hero h1 [data-heading-text] { color:#fff !important; } .hero h1 { font-size:clamp(1.55rem,3.4vw,2.7rem); line-height:1.06; margin:0 0 10px; letter-spacing:-.035em; font-weight:800 !important; } .hero h1 [data-testid="stHeaderActionElements"] { display:none; } .hero p, .hero p span { color:rgba(255,255,255,.92) !important; font-size:clamp(.88rem,1.4vw,1rem); margin:0; max-width:66ch; line-height:1.5; } .hero-tags { display:flex; flex-wrap:wrap; gap:8px; margin-top:14px; } .hero-tag { display:inline-flex; align-items:center; gap:6px; background:rgba(255,255,255,.14); border:1px solid rgba(255,255,255,.20); color:#fff !important; border-radius:999px; padding:4px 11px; font-size:.73rem; font-weight:600; white-space:nowrap; } .source-line { color:var(--muted); font-size:.8rem; margin:0 2px 16px; line-height:1.5; } .section-head { display:flex; align-items:baseline; justify-content:space-between; flex-wrap:wrap; gap:6px; margin:18px 2px 10px; } .section-head h2 { margin:0; font-size:clamp(1.12rem,2.2vw,1.42rem); font-weight:700; letter-spacing:-.02em; } .section-head .hint { color:var(--muted); font-size:.8rem; } .kpi-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(215px,1fr)); gap:12px; margin-bottom:6px; } .kpi { border:1px solid var(--border); border-radius:var(--radius); background:linear-gradient(150deg,var(--panel),var(--panel2)); box-shadow:var(--shadow); padding:15px 16px 14px; display:flex; gap:12px; align-items:flex-start; transition:transform .15s ease,border-color .15s ease; } .kpi:hover { transform:translateY(-2px); border-color:var(--accent); } .kpi .ic { width:36px; height:36px; flex:0 0 36px; border-radius:10px; display:grid; place-items:center; font-size:1.05rem; background:var(--accent-soft); border:1px solid var(--border-soft); } .kpi .lab { color:var(--muted); font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; } .kpi .val { font-size:clamp(1.25rem,3vw,1.6rem); font-weight:800; letter-spacing:-.02em; line-height:1.18; margin-top:4px; } .kpi .note { color:var(--muted); font-size:.74rem; margin-top:3px; } .card { border:1px solid var(--border); border-radius:var(--radius); background:var(--panel); padding:18px 20px; margin-bottom:12px; box-shadow:var(--shadow); } .card h3 { margin-top:0; font-size:1.05rem; } .small-muted { color:var(--muted); font-size:.82rem; line-height:1.6; } .rel-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(210px,1fr)); gap:10px; } .rel { border-radius:var(--radius); padding:14px 15px; border:1px solid var(--border); background:var(--panel); } .rel .nm { font-weight:800; font-size:.9rem; } .rel .pc { font-size:1.5rem; font-weight:800; margin:4px 0 2px; } .rel .ds { color:var(--muted); font-size:.76rem; line-height:1.5; } .status-row { display:flex; align-items:center; gap:10px; padding:9px 12px; border:1px solid var(--border); border-radius:var(--radius-sm); margin-bottom:7px; background:var(--panel); flex-wrap:wrap; } .dot { width:9px; height:9px; border-radius:50%; flex:0 0 9px; } .dot.ok { background:var(--positive); } .dot.cache { background:var(--accent); } .dot.bad { background:var(--negative); } .status-row .nm { font-weight:700; font-size:.85rem; min-width:180px; } .status-row .dt { color:var(--muted); font-size:.78rem; } div[data-testid="stPlotlyChart"] { background:var(--panel); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; box-shadow:var(--shadow); } [data-testid="stDataFrame"] { border:1px solid var(--border); border-radius:var(--radius-sm); overflow:hidden; } .stButton > button, .stDownloadButton > button { border-radius:var(--radius-sm); border:1px solid var(--border); font-weight:650; min-height:42px; } .stButton > button:hover, .stDownloadButton > button:hover { border-color:var(--accent); background:var(--accent); color:#fff; } div[role="radiogroup"] { display:flex; flex-wrap:wrap; gap:6px; } div[role="radiogroup"] > label { background:var(--panel2); border:1px solid var(--border); padding:7px 13px; border-radius:999px; margin:0; } div[role="radiogroup"] > label:has(input:checked) { border-color:var(--accent); background:var(--accent-soft); box-shadow:inset 0 0 0 1px var(--accent); } [data-testid="stSidebar"] div[role="radiogroup"] { flex-direction:column; gap:4px; } [data-testid="stSidebar"] div[role="radiogroup"] > label { width:100%; border-radius:var(--radius-sm); } div[data-testid="stSegmentedControl"] button, div[data-testid="stButtonGroup"] button { border-radius:999px !important; min-height:40px; font-weight:650 !important; } [data-testid="stSelectbox"] > div > div, [data-testid="stMultiSelect"] > div > div, [data-testid="stTextInput"] > div > div { border-radius:var(--radius-sm) !important; min-height:42px; } .stTabs [data-baseweb="tab-list"] { gap:4px; border-bottom:1px solid var(--border-soft); overflow-x:auto; scrollbar-width:none; } .stTabs [data-baseweb="tab"] { border-radius:var(--radius-sm) var(--radius-sm) 0 0; padding:8px 14px; white-space:nowrap; font-weight:600; } .stTabs [aria-selected="true"] { background:var(--accent-soft); } div[data-testid="stExpander"] { border:1px solid var(--border) !important; border-radius:var(--radius) !important; background:var(--panel); overflow:hidden; } [data-testid="stHorizontalBlock"] { flex-wrap:wrap; gap:12px; } [data-testid="stColumn"] { min-width:min(100%,320px); } .signature { margin-top:34px; padding:22px 18px 18px; text-align:center; border-top:1px solid var(--border); border-radius:var(--radius) var(--radius) 0 0; background:linear-gradient(180deg,transparent,var(--panel2)); } .sig-name { font-weight:800; font-size:1rem; } .sig-affil { color:var(--muted); font-size:.82rem; margin-top:3px; } .sig-links { display:flex; flex-wrap:wrap; justify-content:center; gap:8px; margin:14px 0 12px; } .sig-links a { display:inline-flex; align-items:center; padding:7px 14px; border-radius:999px; border:1px solid var(--border); background:var(--panel); color:var(--text) !important; text-decoration:none; font-size:.8rem; font-weight:650; min-height:38px; } .sig-links a { gap:8px; } .sig-links a .ic, .side-links a .ic { font-size:.9em; opacity:.85; font-style:normal; font-weight:700; line-height:1; } .sig-links a span:not(.ic) { text-decoration:underline; text-underline-offset:3px; } .sig-links a:hover { border-color:var(--accent); background:var(--accent); color:#fff !important; } .sig-links a:hover .ic { opacity:1; } .side-links a { display:inline-flex; align-items:center; gap:5px; } .sig-meta { color:var(--muted); font-size:.76rem; line-height:1.7; } .side-links { display:flex; flex-wrap:wrap; gap:6px; margin-top:4px; } .side-links a { font-size:.72rem; font-weight:650; padding:5px 10px; border-radius:999px; border:1px solid var(--border); background:var(--panel2); color:var(--text) !important; text-decoration:none; } @media (max-width:900px) { .block-container { padding:.7rem .8rem 1.6rem; } .hero { padding:20px 18px; border-radius:16px; } .kpi-grid { grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:9px; } .kpi .lab { font-size:.63rem; } .kpi .val { font-size:1.24rem; } } @media (max-width:700px) { div[data-testid="stPlotlyChart"] .modebar { display:none !important; } } @media (max-width:560px) { .kpi-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } .sig-links a { flex:1 1 calc(50% - 8px); justify-content:center; } } </style> """) def kpi(label: str, value: str, note: str = "", icon: str = "") -> str: return ('<div class="kpi">' f'<div class="ic">{icon}</div><div class="body">' f'<div class="lab">{label}</div><div class="val">{value}</div>' f'<div class="note">{note}</div></div></div>') def kpi_grid(cards: list[str]) -> None: st.markdown(f'<div class="kpi-grid">{"".join(cards)}</div>', unsafe_allow_html=True) def section(title: str, hint: str = "") -> None: st.markdown(f'<div class="section-head"><h2>{title}</h2><span class="hint">{hint}</span></div>', unsafe_allow_html=True) def fmt(value, decimals: int = 1) -> str: if value is None or pd.isna(value): return "—" value = float(value) if abs(value) >= 1_000_000_000: return f"{value / 1_000_000_000:.2f} B" if abs(value) >= 1_000_000: return f"{value / 1_000_000:.1f} M" if abs(value) >= 10_000: return f"{value / 1_000:.0f} K" return f"{value:,.{decimals}f}" def style_figure(fig: go.Figure, height: int = 420, theme: str = "Dark", legend_top: bool = True) -> go.Figure: p = PALETTES[theme] grid = "#1E3A54" if theme == "Dark" else "#E8EFF6" fig.update_layout( height=height, autosize=True, paper_bgcolor=p["panel"], plot_bgcolor=p["panel"], font=dict(family="Inter, -apple-system, Segoe UI, sans-serif", color=p["text"], size=13), margin=dict(l=14, r=14, t=54, b=14), title=dict(font=dict(size=16, color=p["text"]), x=0.01, xanchor="left", y=0.965), hoverlabel=dict(bgcolor=p["panel2"], font_color=p["text"], bordercolor=p["border"]), xaxis=dict(gridcolor=grid, zerolinecolor=grid, linecolor=grid, title_font=dict(color=p["muted"], size=12), tickfont=dict(color=p["muted"], size=11), automargin=True), yaxis=dict(gridcolor=grid, zerolinecolor=grid, linecolor=grid, title_font=dict(color=p["muted"], size=12), tickfont=dict(color=p["muted"], size=11), automargin=True), colorway=CATEGORICAL, modebar=dict(bgcolor="rgba(0,0,0,0)", color=p["muted"], activecolor=p["accent"]), ) if legend_top: fig.update_layout(legend=dict(orientation="h", yanchor="bottom", y=1.005, xanchor="right", x=1, bgcolor="rgba(0,0,0,0)", font=dict(size=11, color=p["muted"]), title_text="")) return fig PLOT_CONFIG = {"displaylogo": False, "responsive": True, "modeBarButtonsToRemove": ["select2d", "lasso2d", "autoScale2d", "toggleSpikelines"]} def show(fig: go.Figure, filename: str = "conservation_hd") -> None: cfg = dict(PLOT_CONFIG) cfg["toImageButtonOptions"] = {"format": "png", "filename": filename, "scale": 2} st.plotly_chart(fig, config=cfg, theme=None, **stretch(st.plotly_chart)) # --------------------------------------------------------------------------- # Continental map: country choropleth + protected area points # --------------------------------------------------------------------------- def _rings(geometry: dict) -> list[list]: """Exterior rings of a (Multi)Polygon geometry.""" kind, coords = geometry.get("type"), geometry.get("coordinates") if kind == "Polygon": return [coords[0]] if coords else [] if kind == "MultiPolygon": return [poly[0] for poly in coords if poly] return [] def _sample(scale: list[str], frac: float) -> str: frac = min(max(float(frac), 0.0), 1.0) try: return px.colors.sample_colorscale(px.colors.make_colorscale(scale), [frac])[0] except Exception: return scale[int(frac * (len(scale) - 1))] def continent_map(boundaries: dict, values: pd.DataFrame, points: pd.DataFrame, value_label: str, unit: str, theme: str, height: int = 620) -> go.Figure: """Self-contained map: no tile server, no remote topojson. Country polygons come from geoBoundaries and are drawn as filled paths on a plain cartesian canvas, so the view renders identically online and offline. """ p = PALETTES[theme] lookup = dict(zip(values["iso3"], values["value"])) if not values.empty else {} finite = [v for v in lookup.values() if pd.notna(v)] vmin, vmax = (min(finite), max(finite)) if finite else (0.0, 1.0) span = (vmax - vmin) or 1.0 missing = "#22374D" if theme == "Dark" else "#E4EBF2" fig = go.Figure() for feature in boundaries.get("features", []): rings = _rings(feature.get("geometry", {})) if not rings: continue props = feature.get("properties", {}) iso3 = props.get("iso3", "") value = lookup.get(iso3) known = value is not None and pd.notna(value) xs: list = [] ys: list = [] for ring in rings: xs.extend([c[0] for c in ring] + [None]) ys.extend([c[1] for c in ring] + [None]) label = (f"<b>{props.get('name', iso3)}</b><br>{value:,.1f} {unit}" if known else f"<b>{props.get('name', iso3)}</b><br>no data") fig.add_trace(go.Scatter( x=xs, y=ys, mode="lines", fill="toself", fillcolor=_sample(SEQ_GREEN, (value - vmin) / span) if known else missing, line=dict(color=p["border"], width=0.6), hoveron="fills", hoverinfo="text", text=label, showlegend=False, name=props.get("name", iso3), )) fig.add_trace(go.Scatter( x=[None], y=[None], mode="markers", hoverinfo="skip", showlegend=False, marker=dict(colorscale=px.colors.make_colorscale(SEQ_GREEN), cmin=vmin, cmax=vmax, color=[vmin], size=0.1, showscale=True, colorbar=dict(title=dict(text=f"{value_label} ({unit})", font=dict(color=p["muted"], size=11), side="top"), orientation="h", thickness=12, len=0.62, x=0.5, xanchor="center", y=-0.02, yanchor="top", outlinewidth=0, bgcolor="rgba(0,0,0,0)", tickfont=dict(color=p["muted"], size=10))), )) if not points.empty: sizes = points["area_km2"].fillna(points["area_km2"].median()) sizes = (sizes.clip(lower=1) ** 0.22) sizes = 5 + 13 * (sizes - sizes.min()) / ((sizes.max() - sizes.min()) or 1) custom = points[["country", "area_km2", "pressure"]].to_numpy() fig.add_trace(go.Scatter( x=points["lon"], y=points["lat"], mode="markers", name="Protected areas", marker=dict(size=sizes, color=points["pressure"], colorscale=SEQ_BLUE, line=dict(width=0.7, color=p["panel"]), opacity=0.92, showscale=False), text=points["name"], customdata=custom, hovertemplate=("<b>%{text}</b><br>%{customdata[0]}" "<br>%{customdata[1]:,.0f} km²" "<br>pressure %{customdata[2]:.0f}<extra></extra>"), showlegend=False, )) fig = style_figure(fig, height, theme, legend_top=False) fig.update_layout( margin=dict(l=6, r=6, t=16, b=58), xaxis=dict(visible=False, showgrid=False, zeroline=False), yaxis=dict(visible=False, showgrid=False, zeroline=False, scaleanchor="x", scaleratio=1), plot_bgcolor=p["panel"], dragmode="pan", ) return fig # --------------------------------------------------------------------------- # Cached data loading # --------------------------------------------------------------------------- @st.cache_data(show_spinner=False, ttl=60 * 60 * 12) def load_protected_areas(): ds = src.fetch_protected_areas() return ds.frame, ds.status @st.cache_data(show_spinner=False, ttl=60 * 60 * 12) def load_indicators(): ds = src.fetch_indicators() return ds.frame, ds.status @st.cache_data(show_spinner=False, ttl=60 * 60 * 12) def load_un_population(): ds = src.fetch_un_population() return ds.frame, ds.status @st.cache_data(show_spinner=False, ttl=60 * 60 * 12) def load_subnational(): ds = src.fetch_subnational_hdi() return ds.frame, ds.status @st.cache_data(show_spinner=False, ttl=60 * 60 * 24) def load_boundaries(level: int = 0): return src.fetch_boundaries(level) @st.cache_data(show_spinner=False) def enrich(pas: pd.DataFrame, indicators: pd.DataFrame) -> pd.DataFrame: """Attach country context, neighbour counts and the pressure index.""" if pas.empty: return pas codes = ["EN.POP.DNST", "SP.RUR.TOTL.ZS", "SP.POP.TOTL", "SP.DYN.LE00.IN", "SE.SEC.ENRR", "NY.GNP.PCAP.PP.CD", "SI.POV.DDAY", "SH.DYN.MORT", "ER.LND.PTLD.ZS", "AG.LND.FRST.ZS", "EG.ELC.ACCS.ZS"] + list(src.UN_INDICATORS) out = an.attach_country_context(pas, indicators, codes) out["neighbours_50km"] = an.neighbour_counts(out).values out["pressure"] = an.pressure_index(out).values return out # --------------------------------------------------------------------------- # Sidebar # --------------------------------------------------------------------------- apply_default_theme(DEFAULT_THEME) theme = active_theme() palette = PALETTES[theme] with st.sidebar: st.markdown( '<div class="side-brand"><div class="glyph">🌍</div><div class="txt">' "<strong>Conservation &amp; Human Development</strong>" "<span>Africa · protected areas &amp; people</span></div></div>", unsafe_allow_html=True, ) language = st.radio(TEXT["English"]["language"], ["English", "Français"], horizontal=True, key="lang") t = TEXT[language] st.caption(f"{t['appearance']} · {t['theme_hint']}") st.markdown(CSS.substitute(**{k: v for k, v in palette.items() if k != "map_style"}), unsafe_allow_html=True) with st.spinner(t["loading"]): pas_raw, pa_status = load_protected_areas() wb_indicators, ind_status = load_indicators() un_indicators, un_status = load_un_population() shdi, shdi_status = load_subnational() statuses = [pa_status, ind_status, un_status, shdi_status] # `indicators_all` keeps the UN median-variant projections for the trajectory # charts; `indicators` is observations only and is what every analytic view uses. indicators_all = pd.concat([f for f in (wb_indicators, un_indicators) if not f.empty], ignore_index=True) if (not wb_indicators.empty or not un_indicators.empty) else pd.DataFrame() indicators = an.observations_only(indicators_all) pas = enrich(pas_raw, indicators) if not pas_raw.empty else pas_raw COUNTRIES = sorted(pas["country"].dropna().unique().tolist()) if not pas.empty else [] if not COUNTRIES and not indicators.empty: COUNTRIES = sorted(indicators["country"].dropna().unique().tolist()) # Welfare outcomes usable as the development axis of the typology. Demographic # structure is context, not a welfare outcome, so only the two standard markers # of the demographic transition join them. HD_CODES = [c for c, m in src.INDICATORS.items() if m["group"] in ("Education", "Health", "Income")] HD_CODES += [c for c in ("UN:67", "UN:86") if c in src.UN_INDICATORS] CONS_CODES = [c for c, m in src.INDICATORS.items() if m["group"] == "Conservation"] CONTEXT_CODES = src.DEMOGRAPHY_CODES + src.DEPENDENCY_CODES MAP_CODES = HD_CODES + [c for c in CONTEXT_CODES if c not in HD_CODES] def label_of(code: str) -> str: meta = src.ALL_INDICATORS.get(code, {}) return meta.get("label", code) SOURCE_TAG = {"World Bank": "WB", "UN WPP 2024": "UN WPP"} def label_with_source(code: str) -> str: """Selector label. Provenance is always visible, never inferred.""" meta = src.ALL_INDICATORS.get(code, {}) tag = SOURCE_TAG.get(meta.get("source", ""), meta.get("source", "?")) return f"{meta.get('label', code)} · {tag}" def unit_of(code: str) -> str: return src.ALL_INDICATORS.get(code, {}).get("unit", "") with st.sidebar: st.markdown(f'<div class="side-label">{t["nav"]}</div>', unsafe_allow_html=True) NAV = { t["overview"]: f"🗺️ {t['overview']}", t["areas"]: f"🌳 {t['areas']}", t["conditions"]: f"👥 {t['conditions']}", t["relationships"]: f"⚖️ {t['relationships']}", t["trajectories"]: f"📈 {t['trajectories']}", t["data"]: f"📚 {t['data']}", } nav_label = st.radio("Navigation", list(NAV.values()), index=0, label_visibility="collapsed", key="nav") page = next(k for k, v in NAV.items() if v == nav_label) st.markdown(f'<div class="side-label">{t["filters"]}</div>', unsafe_allow_html=True) hd_code = st.selectbox(t["indicator"], MAP_CODES, index=0, format_func=label_with_source, key="hd_code") country_filter = st.multiselect(t["countries"], COUNTRIES, default=[], key="country_filter", placeholder=t["all_countries"]) st.markdown(f'<div class="side-label">{t["upload_title"]}</div>', unsafe_allow_html=True) upload = st.file_uploader("PACE / effectiveness CSV", type=["csv"], label_visibility="collapsed", key="pace_upload") st.caption(t["upload_help"]) ok_count = sum(1 for s in statuses if s.ok) bad = [s for s in statuses if not s.ok] st.markdown(f'<div class="side-label">{t["status"]}</div>', unsafe_allow_html=True) st.caption(f"{ok_count}/{len(statuses)} {t['sources_ok']}" + (f" · {len(bad)} {t['sources_failed']}" if bad else "")) st.markdown(f'<div class="side-label">{AUTHOR["name"]}</div>', unsafe_allow_html=True) st.markdown('<div class="side-links">' + "".join( f'<a href="{u}" target="_blank" rel="noopener">' f'<span class="ic">{i}</span>{n}</a>' for i, n, u in AUTHOR["links"] ) + "</div>", unsafe_allow_html=True) effectiveness = pd.DataFrame() match_report: dict = {} if upload is not None: ds = src.read_effectiveness_upload(upload) statuses.append(ds.status) if ds.ok: pas, match_report = an.match_effectiveness(pas, ds.frame) effectiveness = ds.frame view = pas if not country_filter else pas[pas["country"].isin(country_filter)] ind_view = (indicators if not country_filter else indicators[indicators["country"].isin(country_filter)]) # --------------------------------------------------------------------------- # Header # --------------------------------------------------------------------------- st.markdown( f""" <div class="hero"> <h1>{t['title']}</h1> <p>{t['subtitle']}</p> <div class="hero-tags"> <span class="hero-tag">🌳 {len(pas):,} {t['areas'].lower()}</span> <span class="hero-tag">🌍 {len(COUNTRIES)} {t['countries'].lower()}</span> <span class="hero-tag">📅 1990–2024</span> <span class="hero-tag">📄 Li et al. 2024</span> </div> </div> <div class="source-line">{t['framing']}</div> """, unsafe_allow_html=True, ) if not pa_status.ok or not ind_status.ok: failed = ", ".join(s.name for s in statuses if not s.ok) st.error( f"**{t['sources_failed'].capitalize()}: {failed}.** " + (" · ".join(f"{s.name}: {s.detail}" for s in statuses if not s.ok)) + f" \n→ {t['data']}" ) def map_style() -> str: return palette["map_style"] # --------------------------------------------------------------------------- # Page: Overview # --------------------------------------------------------------------------- if page == t["overview"]: total_area = view["area_km2"].sum() if "area_km2" in view else np.nan kpi_grid([ kpi(t["kpi_pas"], f"{len(view):,}", "Wikidata / WDPA", "🌳"), kpi(t["kpi_countries"], str(view["country"].nunique() if not view.empty else 0), "Africa", "🌍"), kpi(t["kpi_area"], f"{fmt(total_area)} km²", "reported", "📐"), kpi(t["kpi_pressure"], fmt(view["pressure"].median()) if "pressure" in view and not view.empty else "—", "0–100", "👥"), ]) if "UN:83" in view.columns and view["UN:83"].notna().any(): kpi_grid([ kpi(label_of("UN:54"), fmt(view["UN:54"].median()), unit_of("UN:54"), "🏘️"), kpi(label_of("UN:83"), fmt(view["UN:83"].median()), unit_of("UN:83"), "🧒"), kpi(label_of("UN:67"), fmt(view["UN:67"].median()), unit_of("UN:67"), "🎂"), kpi(label_of("UN:51"), fmt(view["UN:51"].median()), unit_of("UN:51"), "📈"), ]) st.caption("UN World Population Prospects 2024, median variant · " "median across the countries in view, latest estimate year." if language == "English" else "Nations Unies, World Population Prospects 2024, variante médiane · " "médiane des pays affichés, dernière année d'estimation.") section(t["map_title"], t["map_hint"]) if view.empty: st.info(t["no_data"]) else: with st.spinner(t["loading_map"]): boundaries, bnd_status = load_boundaries(0) if not bnd_status.ok: st.warning(f"{bnd_status.name}: {bnd_status.detail}") latest = an.latest_values(ind_view, hd_code) points = view.dropna(subset=["lat", "lon"]).copy() show( continent_map(boundaries, latest, points, label_of(hd_code), src.ALL_INDICATORS[hd_code]["unit"], theme), "africa_conservation_hd_map", ) used = an.pressure_components(view) st.caption(t["pressure_help"] + " " + t["pressure_built"] + " " + ", ".join(label_with_source(c) if c in src.ALL_INDICATORS else t["neighbours"] for c in used) + ".") left, right = st.columns([1, 1], gap="medium") with left: if latest.empty: st.info(t["no_data"]) else: top = latest.nlargest(15, "value").sort_values("value") bar = px.bar(top, x="value", y="country", orientation="h", color="value", color_continuous_scale=SEQ_GREEN, title=label_of(hd_code), labels={"value": src.ALL_INDICATORS[hd_code]["unit"], "country": ""}) bar.update_coloraxes(showscale=False) bar.update_traces(hovertemplate="<b>%{y}</b><br>%{x:,.1f}<extra></extra>", marker_line_width=0) show(style_figure(bar, 470, theme, legend_top=False), "top_indicator") with right: counts = an.summarise_by_country(view).head(15).sort_values("n_pas") if counts.empty: st.info(t["no_data"]) else: bar = px.bar(counts, x="n_pas", y="country", orientation="h", color="n_pas", color_continuous_scale=SEQ_BLUE, title=t["kpi_pas"], labels={"n_pas": "", "country": ""}) bar.update_coloraxes(showscale=False) bar.update_traces(hovertemplate="<b>%{y}</b><br>%{x:,.0f}<extra></extra>", marker_line_width=0) show(style_figure(bar, 470, theme, legend_top=False), "pa_counts") # --------------------------------------------------------------------------- # Page: Protected areas # --------------------------------------------------------------------------- elif page == t["areas"]: section(t["areas"], f"{len(view):,}") if view.empty: st.info(t["no_data"]) else: c1, c2, c3 = st.columns([1.4, 1, 1], gap="medium") with c1: query = st.text_input(t["search"], "", key="pa_search", placeholder=t["search"]) with c2: cats = sorted([c for c in view["iucn_category"].dropna().unique() if c]) cat = st.multiselect(t["iucn"], cats, default=[], key="pa_iucn") with c3: max_area = float(view["area_km2"].max()) if view["area_km2"].notna().any() else 0.0 min_area = st.slider(t["min_area"], 0.0, max(max_area, 1.0), 0.0, key="pa_area") if max_area > 0 else 0.0 filtered = view.copy() if query: filtered = filtered[filtered["name"].str.contains(query, case=False, na=False)] if cat: filtered = filtered[filtered["iucn_category"].isin(cat)] if min_area: filtered = filtered[filtered["area_km2"].fillna(0) >= min_area] if filtered.empty: st.info(t["no_data"]) else: cols = ["name", "country", "iucn_category", "area_km2", "established", "pressure", "neighbours_50km"] if "effectiveness" in filtered.columns and filtered["effectiveness"].notna().any(): cols.append("effectiveness") table = filtered[cols].sort_values("area_km2", ascending=False) st.dataframe(table.round(1), hide_index=True, height=340, **stretch(st.dataframe)) st.download_button( "⬇ CSV", data=filtered.to_csv(index=False).encode("utf-8"), file_name="african_protected_areas_with_context.csv", mime="text/csv", **stretch(st.download_button), ) section(t["profile"]) names = filtered.sort_values("name")["name"].tolist() chosen = st.selectbox(t["select_pa"], names, key="pa_choice") row = filtered[filtered["name"] == chosen].iloc[0] kpi_grid([ kpi(t["country"], str(row.get("country", "—")), str(row.get("iucn_category") or "—"), "🌍"), kpi("Area", f"{fmt(row.get('area_km2'))} km²", f"est. {int(row['established'])}" if pd.notna(row.get("established")) else "", "📐"), kpi(t["pressure"], fmt(row.get("pressure")), f"{int(row.get('neighbours_50km', 0))} PAs < 50 km", "👥"), kpi(label_of(hd_code), fmt(row.get(hd_code)), src.ALL_INDICATORS[hd_code]["unit"], "📊"), ]) pcol, mcol = st.columns([1, 1], gap="medium") with pcol: context_rows = [] for code in ["SE.SEC.ENRR", "SP.DYN.LE00.IN", "SH.DYN.MORT", "NY.GNP.PCAP.PP.CD", "SI.POV.DDAY", "EG.ELC.ACCS.ZS", "AG.LND.FRST.ZS", "UN:54", "UN:67", "UN:83", "UN:86", "UN:46"]: if code in row.index: context_rows.append({ t["context"]: label_of(code), "": round(float(row[code]), 1) if pd.notna(row[code]) else None, t["unit_col"]: unit_of(code), t["source_col"]: src.ALL_INDICATORS[code].get("source", ""), }) st.dataframe(pd.DataFrame(context_rows), hide_index=True, **stretch(st.dataframe)) with mcol: same = filtered[filtered["country"] == row["country"]] d = np.sqrt((same["lat"] - row["lat"]) ** 2 + (same["lon"] - row["lon"]) ** 2) near = same.assign(deg=d).nsmallest(8, "deg") near = near[near["name"] != chosen] st.markdown(f'<div class="small-muted"><b>{t["nearby"]}</b></div>', unsafe_allow_html=True) st.dataframe(near[["name", "area_km2", "pressure"]].round(1), hide_index=True, **stretch(st.dataframe)) # --------------------------------------------------------------------------- # Page: Human conditions # --------------------------------------------------------------------------- elif page == t["conditions"]: section(t["conditions"], "World Bank Open Data · UN World Population Prospects 2024") if ind_view.empty: st.info(t["no_data"]) else: tabs = st.tabs([f"🎓 {t['education']}", f"🩺 {t['health']}", f"💶 {t['income']}", f"🏘️ {t['demography']}", f"⚖️ {t['dependency']}"]) groups = [("Education", src.EDUCATION_CODES), ("Health", src.HEALTH_CODES), ("Income", src.INCOME_CODES), ("Demography", src.DEMOGRAPHY_CODES), ("Dependency", src.DEPENDENCY_CODES)] for tab, (_, codes) in zip(tabs, groups): with tab: for code in codes: latest = an.latest_values(ind_view, code) if latest.empty: continue ranked = latest.sort_values("value", ascending=src.ALL_INDICATORS[code]["good"] == "low") top = ranked.head(20).sort_values( "value", ascending=src.ALL_INDICATORS[code]["good"] != "low") scale = (DIVERGING if src.ALL_INDICATORS[code]["good"] == "low" else SEQ_GREEN) bar = px.bar(top, x="value", y="country", orientation="h", color="value", color_continuous_scale=scale, title=(f"{label_of(code)} ({unit_of(code)}) · " f"{src.ALL_INDICATORS[code].get('source', '')}"), labels={"value": "", "country": ""}) bar.update_coloraxes(showscale=False) bar.update_traces( hovertemplate="<b>%{y}</b><br>%{x:,.1f}<extra></extra>", marker_line_width=0) show(style_figure(bar, 520, theme, legend_top=False), f"cond_{code}") if not shdi.empty: section("Subnational HDI", shdi_status.detail) st.dataframe(shdi.head(300), hide_index=True, **stretch(st.dataframe)) else: st.info( "Subnational HDI is not loaded, so this page shows country averages. " f"Set `SHDI_CSV_URL` to switch to regions — {shdi_status.detail}" if language == "English" else "L'IDH infranational n'est pas chargé : cette page montre des moyennes " f"nationales. Définissez `SHDI_CSV_URL` pour passer aux régions — {shdi_status.detail}" ) # --------------------------------------------------------------------------- # Page: Relationships # --------------------------------------------------------------------------- elif page == t["relationships"]: section(t["typology"], t["typology_hint"]) st.markdown(f'<div class="card small-muted">{t["counterfactual_note"]}</div>', unsafe_allow_html=True) if ind_view.empty: st.info(t["no_data"]) else: c1, c2, c3 = st.columns([1, 1, 1], gap="medium") with c1: cons_code = st.selectbox(t["conservation_ind"], CONS_CODES, index=min(1, len(CONS_CODES) - 1), format_func=label_with_source, key="rel_cons") with c2: dev_code = st.selectbox( t["indicator"], HD_CODES, index=HD_CODES.index(hd_code) if hd_code in HD_CODES else 0, format_func=label_with_source, key="rel_dev") span_ok = an.overlapping_span(ind_view, [cons_code, dev_code]) with c3: if span_ok is None: st.caption(t["no_overlap"]) span = None else: lo, hi = span_ok years = [y for y in sorted(ind_view["year"].unique()) if lo <= y <= hi] # Keyed on the pair so switching indicators resets the window to # one where both series actually have observations. span = st.select_slider( t["period"], options=years, value=(years[0], years[-1]), key=f"rel_span_{cons_code}_{dev_code}") if span is None: st.info( f"{t['no_overlap']} — {label_of(cons_code)}: " f"{an.year_span(ind_view, cons_code) or t['no_data']} · " f"{label_of(dev_code)}: {an.year_span(ind_view, dev_code) or t['no_data']}" ) else: result = an.build_typology( ind_view, cons_code, dev_code, int(span[0]), int(span[1]), development_good=src.ALL_INDICATORS[dev_code]["good"], conservation_good=src.ALL_INDICATORS[cons_code]["good"], ) if result.frame.empty: st.info(t["no_data"]) else: shares = result.shares cards = [] for rel in an.RELATIONSHIPS: color = an.RELATIONSHIP_COLORS[rel] cards.append( f'<div class="rel" style="border-left:4px solid {color}">' f'<div class="nm" style="color:{color}">{rel}</div>' f'<div class="pc">{shares.get(rel, 0):.0f}%</div>' f'<div class="ds">{an.RELATIONSHIP_MEANING[rel]}<br>' f'{t["vs_li"]}: <b>{an.LI_GLOBAL_SHARES[rel]:.1f}%</b></div></div>' ) st.markdown(f'<div class="rel-grid">{"".join(cards)}</div>', unsafe_allow_html=True) assoc = an.association(result) if assoc["n"] and not pd.isna(assoc["phi"]): phi = assoc["phi"] direction = (t["assoc_pos"] if phi > 0.08 else t["assoc_neg"] if phi < -0.08 else t["assoc_none"]) st.markdown( f'<div class="card small-muted"><b>{t["assoc_title"]}</b> — ' f'{direction} <b>φ = {phi:+.2f}</b>, ' f'{t["odds"]} {assoc["odds_ratio"]:.2f}, n = {assoc["n"]}.<br>' f'{t["assoc_note"]}</div>', unsafe_allow_html=True, ) section(t["quadrant"], f"{label_of(cons_code)} × {label_of(dev_code)}, " f"{result.start}–{result.end}") frame = result.frame fig = px.scatter( frame, x="cons_oriented", y="dev_oriented", color="relationship", hover_name="country", color_discrete_map=an.RELATIONSHIP_COLORS, labels={"cons_oriented": f"{t['cons_axis']}: Δ {label_of(cons_code)}", "dev_oriented": f"{t['dev_axis']}: Δ {label_of(dev_code)}"}, ) fig.update_traces(marker=dict(size=11, line=dict(width=1, color=palette["panel"])), hovertemplate="<b>%{hovertext}</b><br>" "Δ cons: %{x:,.2f}<br>Δ dev: %{y:,.2f}<extra></extra>") fig.add_vline(x=result.conservation_reference, line_dash="dot", line_color=palette["muted"]) fig.add_hline(y=result.development_reference, line_dash="dot", line_color=palette["muted"]) # Name the quadrants in place: the 2x2 should read without the legend. corners = [ (0.99, 0.98, "right", "top", an.SYNERGY), (0.01, 0.98, "left", "top", an.CONSERVATION_IMPAIRED), (0.99, 0.02, "right", "bottom", an.ECONOMY_IMPAIRED), (0.01, 0.02, "left", "bottom", an.RETREAT), ] for x, y, xa, ya, name in corners: fig.add_annotation( x=x, y=y, xref="paper", yref="paper", xanchor=xa, yanchor=ya, text=name.upper(), showarrow=False, font=dict(size=10, color=an.RELATIONSHIP_COLORS[name]), opacity=0.85, ) fig.update_layout(showlegend=False) show(style_figure(fig, 560, theme), "typology_quadrant") st.dataframe( frame[["country", "relationship", "change_cons", "change_dev", "start_year_cons", "end_year_cons"]] .rename(columns={"change_cons": f"Δ {label_of(cons_code)}", "change_dev": f"Δ {label_of(dev_code)}", "start_year_cons": "from", "end_year_cons": "to"}) .sort_values("relationship").round(2), hide_index=True, height=320, **stretch(st.dataframe), ) # --- Protected-area level, unlocked by an upload ----------------------- section(t["upload_title"]) if "effectiveness" in pas.columns and pas["effectiveness"].notna().any(): matched = pas[pas["effectiveness"].notna()] st.success(f"{match_report.get('matched', len(matched))} / " f"{match_report.get('uploaded', len(matched))} {t['upload_matched']}") x_code = st.selectbox( t["indicator"], MAP_CODES, index=MAP_CODES.index(hd_code) if hd_code in MAP_CODES else 0, format_func=label_with_source, key="pa_rel_x") plot = matched.dropna(subset=[x_code, "effectiveness"]) if plot.empty: st.info(t["no_data"]) else: fig = px.scatter( plot, x=x_code, y="effectiveness", hover_name="name", color="country", size=plot["area_km2"].fillna(plot["area_km2"].median()).clip(lower=1) ** 0.3, size_max=20, labels={x_code: f"{label_of(x_code)} ({src.ALL_INDICATORS[x_code]['unit']})", "effectiveness": "Effectiveness score"}, ) corr = plot[[x_code, "effectiveness"]].corr().iloc[0, 1] fig.update_layout(title=f"r = {corr:.2f} (n = {len(plot)})") show(style_figure(fig, 520, theme), "pa_effectiveness_vs_hd") if match_report.get("unmatched"): with st.expander(f"Unmatched ({len(match_report['unmatched'])})"): st.write(", ".join(match_report["unmatched"])) else: st.info(t["upload_help"]) st.dataframe( pd.DataFrame([{"column": k, "meaning": v} for k, v in src.EFFECTIVENESS_SCHEMA.items()]), hide_index=True, **stretch(st.dataframe), ) # --------------------------------------------------------------------------- # Page: Trajectories # --------------------------------------------------------------------------- elif page == t["trajectories"]: section(t["trend_title"], t["framing"]) if indicators_all.empty: st.info(t["no_data"]) else: default = [c for c in ["Kenya", "Tanzania", "Ethiopia", "Senegal", "Zambia"] if c in COUNTRIES][:5] picked = st.multiselect(t["pick_countries"], COUNTRIES, default=default or COUNTRIES[:4], key="traj_countries") codes = st.multiselect(t["indicator"], MAP_CODES + CONS_CODES, default=[hd_code, "ER.LND.PTLD.ZS"], format_func=label_with_source, key="traj_codes") if not picked or not codes: st.info(t["no_data"]) else: for code in codes: d = indicators_all[(indicators_all["indicator"] == code) & (indicators_all["country"].isin(picked))] if d.empty: continue d = d.sort_values("year") has_projection = ("series" in d.columns and (d["series"] == "Projection").any()) fig = go.Figure() for i, c in enumerate(picked): sub = d[d["country"] == c] if sub.empty: continue colour = CATEGORICAL[i % len(CATEGORICAL)] if has_projection: obs = sub[sub["series"] != "Projection"] proj = sub[sub["series"] == "Projection"] else: obs, proj = sub, sub.iloc[0:0] if not obs.empty: fig.add_trace(go.Scatter( x=obs["year"], y=obs["value"], mode="lines", name=c, legendgroup=c, line=dict(color=colour, width=2.6), hovertemplate=f"<b>{c}</b><br>%{{x}} · %{{y:,.1f}}<extra></extra>")) if not proj.empty: bridge = pd.concat([obs.tail(1), proj]) if not obs.empty else proj fig.add_trace(go.Scatter( x=bridge["year"], y=bridge["value"], mode="lines", name=c, legendgroup=c, showlegend=obs.empty, line=dict(color=colour, width=2.2, dash="dash"), hovertemplate=(f"<b>{c}</b> ({t['projection']})" "<br>%{x} · %{y:,.1f}<extra></extra>"))) fig.update_layout( title=f"{label_of(code)} ({unit_of(code)}) · " f"{src.ALL_INDICATORS[code].get('source', '')}", hovermode="x unified", xaxis_title="", yaxis_title="") fig = style_figure(fig, 420, theme) if has_projection: fig.add_vline(x=src.UN_LAST_ESTIMATE_YEAR + 0.5, line_dash="dot", line_color=palette["muted"], line_width=1.4) fig.add_annotation(x=src.UN_LAST_ESTIMATE_YEAR + 1, y=1.0, yref="paper", yanchor="bottom", xanchor="left", text=t["projection"], showarrow=False, font=dict(color=palette["muted"], size=10)) show(fig, f"traj_{code}") # --------------------------------------------------------------------------- # Page: Data & method # --------------------------------------------------------------------------- elif page == t["data"]: section(t["status"]) with st.spinner(t["loading_map"]): _, bnd_status = load_boundaries(0) for s in statuses + [bnd_status]: dot = "ok" if (s.ok and not s.from_cache) else ("cache" if s.ok else "bad") st.markdown( f'<div class="status-row"><span class="dot {dot}"></span>' f'<span class="nm">{s.name}</span>' f'<span class="dt">{s.badge} · {s.rows:,} {t["rows"].lower()} · {s.detail}</span>' f'<span class="dt">{s.licence}</span></div>', unsafe_allow_html=True, ) section(t["coverage"], t["coverage_hint"]) cov = an.coverage(indicators_all) if cov.empty: st.info(t["no_data"]) else: cov = cov.assign( Indicator=[label_of(c) for c in cov["indicator"]], Source=[src.ALL_INDICATORS.get(c, {}).get("source", "") for c in cov["indicator"]], )[["indicator", "Indicator", "Source", "countries", "first", "last", "points"]] st.dataframe( cov.rename(columns={"indicator": "Code", "countries": t["countries"], "first": t["first_year"], "last": t["last_year"], "points": t["observations"]}), hide_index=True, height=300, **stretch(st.dataframe), ) section("Method") with st.expander("Sources and licences", expanded=True): rows = [] for code, meta in src.ALL_INDICATORS.items(): rows.append({"Code": code, "Indicator": meta["label"], "Unit": meta["unit"], "Group": meta["group"], "Source": meta.get("source", ""), "Direction": {"high": "higher is better", "low": "lower is better"}.get(meta.get("good"), "context")}) st.dataframe(pd.DataFrame(rows), hide_index=True, height=330, **stretch(st.dataframe)) st.markdown( """ - **Protected areas** — Wikidata (CC0) by default: name, country, coordinates, reported area, year established, IUCN category. Set `PROTECTED_PLANET_TOKEN` in the Space secrets to pull the authoritative WDPA from Protected Planet instead. - **Education, health, income, conservation cover** — World Bank Open Data (CC BY 4.0), 1990–2024. - **Demography and dependency** — UN Population Division, *World Population Prospects 2024*, median variant. Read from `unpopulation_data*.csv` committed at the repo root: the same file, the same indicator ids and therefore the same numbers as the Africa Population Atlas. Set `UN_WPP_CSV` to point elsewhere. - **Subnational HDI** — Global Data Lab. No stable open endpoint; set `SHDI_CSV_URL` to a direct link or a file in the repo to move from country averages to regions. - **Boundaries** — geoBoundaries (CC BY 4.0). - **Effectiveness scores** — supplied by you, e.g. Canopy PACE. """ ) with st.expander("Rules this dashboard keeps", expanded=True): st.markdown( f""" 1. **Provenance is never inferred.** Every indicator carries its source, and every selector prints it, so a World Bank series and a UN series are never mistaken for one another in the same chart. 2. **Projections never enter an analysis.** WPP 2024 runs to 2100; everything after **{src.UN_LAST_ESTIMATE_YEAR}** is a median-variant projection. Those rows are filtered out of the relationship typology, the change calculations, the map and the protected-area profiles. They appear only on *Trajectories*, drawn dashed and behind a marked line. 3. **One variant only.** Only the WPP median variant is loaded; high, low and probabilistic variants are dropped at read time. 4. **The reference is stated, not hidden.** The 2×2 uses the African median change over the selected period, because matched counterfactuals are not reconstructible from open country series. That is a benchmark, not a causal claim. 5. **Missing is missing.** A connector that fails leaves its features disabled and says so on this page. Nothing is filled in with modelled or invented values. """ ) with st.expander("Known limits"): st.markdown( """ - The pressure index is built from **national** density, child dependency, rural share and protected-area clustering. It is a screening proxy, not a count of people living within 10 km of a park. Doing that properly needs gridded population (WorldPop or GHSL) clipped to a buffer around each boundary polygon — the natural next step, and the reason synthetic or modelled population surfaces are worth looking at. - Country averages hide exactly the subnational variation the question is about. The subnational HDI connector is the single highest-value thing to switch on. - Wikidata coverage of protected areas is uneven between countries; WDPA via a Protected Planet token is the authoritative alternative. - No nightlight or land-cover change series is used here, so this dashboard describes **conditions and co-movement**, not the causal park effect Li et al. estimate. """ ) section(t["detailed"], t["detailed_hint"]) for block in methods.sections(language): with st.expander(f"{block['icon']} {block['title']}", expanded=False): st.markdown(block["body"]) with st.expander("Citation"): st.markdown( """ Li, B.V., Wu, S., Pimm, S.L. & Cui, J. (2024). The synergy between protected area effectiveness and economic growth. *Current Biology* 34, 1–14. https://doi.org/10.1016/j.cub.2024.05.044 Dashboard: Diouf, I. (2026). *Conservation & Human Development in Africa*. """ ) # --------------------------------------------------------------------------- # Signature # --------------------------------------------------------------------------- st.markdown( f""" <div class="signature"> <div class="sig-name">{AUTHOR['name']}</div> <div class="sig-affil">{AUTHOR['affiliation']}</div> <div class="sig-links"> {''.join(f'<a href="{u}" target="_blank" rel="noopener">' f'<span class="ic">{i}</span>{n}</a>' for i, n, u in AUTHOR['links'])} </div> <div class="sig-meta"> © 2026 · <b>Conservation &amp; Human Development in Africa</b><br> Wikidata · World Bank Open Data · geoBoundaries · framed on Li et al. (2024) </div> </div> """, unsafe_allow_html=True, )
"""Africa Conservation & Human Development — an exploratory dashboard.
Built around the question Liesbet Steer put after Li et al. (2024): do the human
conditions around protected areas explain whether conservation and local
development pull together or against each other?
"""
from __future__ import annotations
import inspect
import os
from string import Template
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import streamlit as st
import streamlit.components.v1 as components
import analysis as an
import methods
import sources as src
st.set_page_config(
page_title="Africa Conservation & Human Development",
page_icon="🌍",
layout="wide",
initial_sidebar_state="auto",
menu_items={
"About": (
"Exploratory dashboard on protected areas and the human conditions "
"around them in Africa. Framed on Li et al. (2024), *The synergy "
"between protected area effectiveness and economic growth*, "
"Current Biology 34."
)
},
)
AUTHOR = {
"name": "Dr. Ibrahima Diouf",
"affiliation": "UCAD–ESP/LPAO-SF · Université de Labé–FST",
"links": [
("🌐", "Website", "https://scientific-hub-lab.github.io/Dr-Ibrahima-Diouf/"),
("🤗", "Hugging Face", "https://huggingface.co/idiouf"),
("🆔", "ORCID", "https://orcid.org/0000-0002-3157-0925"),
("in", "LinkedIn", "https://www.linkedin.com/in/dr-ibrahima-diouf-610872108/"),
("🎓", "Google Scholar",
"https://scholar.google.com/citations?user=phsMm7sAAAAJ&hl=fr"),
("🔗", "This Space",
"https://huggingface.co/spaces/idiouf/"
"African-Conservation-Human-Development-Observatory"),
],
}
SEQ_BLUE = ["#EEF4FB", "#D2E3F4", "#AACBE9", "#7FB0DC", "#5493CB",
"#2F76B4", "#1B5B95", "#114374", "#0A2C51"]
SEQ_GREEN = ["#F0F7F2", "#D3E9DA", "#A9D5BA", "#7CBE99", "#51A57A",
"#33885E", "#216A48", "#154E34", "#0C3322"]
DIVERGING = ["#8C2D3F", "#C05B5F", "#E39A88", "#F5D0BC", "#F2F2EF",
"#C4DCE4", "#8CBCD1", "#4E90B5", "#1F5F8F"]
CATEGORICAL = ["#2F6FED", "#0E9F9B", "#E8873D", "#A64CB0", "#3FA34D",
"#D6455D", "#7B6FE8", "#B08A24", "#3FA3D9", "#7A8896"]
PALETTES = {
"Dark": {
"bg": "#070F1A", "panel": "#0D1E30", "panel2": "#122840", "border": "#1D3A55",
"border_soft": "#162E45", "text": "#F2F7FC", "muted": "#9AB0C6",
"accent": "#4A9BFF", "accent_soft": "rgba(74,155,255,.15)",
"positive": "#3FBF8F", "negative": "#F2778D",
"shadow": "0 10px 30px rgba(0,0,0,.35)",
"hero1": "#0B2C52", "hero2": "#14503C", "hero3": "#5C2350",
"map_style": "carto-darkmatter",
},
"Light": {
"bg": "#F2F6FA", "panel": "#FFFFFF", "panel2": "#F6F9FD", "border": "#D8E3EF",
"border_soft": "#E6EDF5", "text": "#0F2439", "muted": "#54687E",
"accent": "#1668CE", "accent_soft": "rgba(22,104,206,.10)",
"positive": "#12805C", "negative": "#B93049",
"shadow": "0 8px 24px rgba(15,36,57,.08)",
"hero1": "#0B3A69", "hero2": "#1B6B4F", "hero3": "#7A2359",
"map_style": "carto-positron",
},
}
# ---------------------------------------------------------------------------
# Translations
# ---------------------------------------------------------------------------
TEXT = {
"English": {
"title": "Conservation & Human Development in Africa",
"subtitle": ("Where protected areas sit, what human conditions surround them, "
"and whether the two move together."),
"framing": ("Framed on Li et al. (2024), Current Biology — protected areas and "
"neighbouring communities fall into four relationships: synergy, "
"economy impaired, conservation impaired, retreat."),
"nav": "Sections",
"overview": "Overview", "areas": "Protected areas", "conditions": "Human conditions",