Update src/app.py
Browse files- src/app.py +516 -417
src/app.py
CHANGED
|
@@ -1,417 +1,516 @@
|
|
| 1 |
-
# =========================
|
| 2 |
-
# App Streamlit - GeoDéchet
|
| 3 |
-
# =========================
|
| 4 |
-
|
| 5 |
-
# -- Evite les erreurs de permissions sur Hugging Face Spaces --
|
| 6 |
-
import os
|
| 7 |
-
|
| 8 |
-
os.environ.setdefault("
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
-
from
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
import
|
| 17 |
-
import
|
| 18 |
-
import
|
| 19 |
-
import
|
| 20 |
-
import
|
| 21 |
-
import
|
| 22 |
-
|
| 23 |
-
from
|
| 24 |
-
from
|
| 25 |
-
from
|
| 26 |
-
from
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
"
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
#
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =========================
|
| 2 |
+
# App Streamlit - GeoDéchet
|
| 3 |
+
# =========================
|
| 4 |
+
|
| 5 |
+
# -- Evite les erreurs de permissions sur Hugging Face Spaces --
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
|
| 9 |
+
os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false")
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
import unicodedata
|
| 13 |
+
from io import StringIO
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import boto3
|
| 17 |
+
import matplotlib.pyplot as plt
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import pickle
|
| 21 |
+
import shap
|
| 22 |
+
import streamlit as st
|
| 23 |
+
from botocore.config import Config
|
| 24 |
+
from dotenv import load_dotenv
|
| 25 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 26 |
+
from langchain_mistralai import ChatMistralAI
|
| 27 |
+
from sklearn.linear_model import LinearRegression
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ========== Helpers robustes ==========
|
| 31 |
+
def _norm(s: str) -> str:
|
| 32 |
+
"""Normalise une chaîne (BOM/accents/espaces/casse)."""
|
| 33 |
+
if s is None:
|
| 34 |
+
return ""
|
| 35 |
+
s = str(s).replace("\ufeff", "") # BOM éventuel
|
| 36 |
+
s = unicodedata.normalize("NFKD", s)
|
| 37 |
+
s = s.encode("ascii", "ignore").decode("ascii") # enlève accents
|
| 38 |
+
s = re.sub(r"\s+", " ", s)
|
| 39 |
+
return s.strip().lower()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def find_col(df: pd.DataFrame, *aliases: str) -> str:
|
| 43 |
+
"""Trouve le nom réel d'une colonne à partir d'alias ('Département'/'Departement', 'année'/'annee')."""
|
| 44 |
+
targets = {_norm(a) for a in aliases}
|
| 45 |
+
for c in df.columns:
|
| 46 |
+
if _norm(c) in targets:
|
| 47 |
+
return c
|
| 48 |
+
return ""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_numeric_value(series: pd.Series) -> float:
|
| 52 |
+
"""Convertit proprement une série (potentiellement str avec espaces, virgule décimale) en float."""
|
| 53 |
+
s = series.astype(str)
|
| 54 |
+
s = (
|
| 55 |
+
s.str.replace("\u00a0", " ", regex=False) # nbsp
|
| 56 |
+
.str.replace("\u202f", " ", regex=False) # thin space
|
| 57 |
+
.str.replace(" ", "", regex=False) # supprime espaces milliers
|
| 58 |
+
.str.replace(",", ".", regex=False) # virgule -> point
|
| 59 |
+
)
|
| 60 |
+
val = pd.to_numeric(s, errors="coerce")
|
| 61 |
+
return float(val.iloc[0]) if len(val) and pd.notna(val.iloc[0]) else 0.0
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def read_csv_robust(
|
| 65 |
+
body_bytes: bytes, default_sep: str = ",", try_utf8sig_first: bool = True
|
| 66 |
+
) -> pd.DataFrame:
|
| 67 |
+
"""Lecture robuste : essaie utf-8-sig puis latin-1, set sep, et répare la mojibake si besoin."""
|
| 68 |
+
df = None
|
| 69 |
+
if try_utf8sig_first:
|
| 70 |
+
try:
|
| 71 |
+
df = pd.read_csv(StringIO(body_bytes.decode("utf-8-sig")), sep=default_sep)
|
| 72 |
+
except Exception:
|
| 73 |
+
pass
|
| 74 |
+
if df is None:
|
| 75 |
+
try:
|
| 76 |
+
df = pd.read_csv(StringIO(body_bytes.decode("latin-1")), sep=default_sep)
|
| 77 |
+
except Exception:
|
| 78 |
+
# dernier fallback: utf-8 simple
|
| 79 |
+
df = pd.read_csv(StringIO(body_bytes.decode("utf-8")), sep=default_sep)
|
| 80 |
+
|
| 81 |
+
# Nettoyage BOM dans colonnes
|
| 82 |
+
cols = [c.replace("\ufeff", "") for c in df.columns]
|
| 83 |
+
# Répare si mojibake du style Département, année, Code, etc.
|
| 84 |
+
if any(("Ã" in c) or ("" in c) or ("Â" in c) for c in cols):
|
| 85 |
+
cols = [
|
| 86 |
+
c.encode("latin-1", "ignore")
|
| 87 |
+
.decode("utf-8", "ignore")
|
| 88 |
+
.replace("\ufeff", "")
|
| 89 |
+
for c in cols
|
| 90 |
+
]
|
| 91 |
+
df.columns = cols
|
| 92 |
+
return df
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ========== Connexion S3 ==========
|
| 96 |
+
def clean(s):
|
| 97 |
+
return (s or "").strip().replace("\r", "").replace("\n", "")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
session = boto3.Session(
|
| 101 |
+
aws_access_key_id=clean(os.getenv("AWS_ACCESS_KEY_ID")),
|
| 102 |
+
aws_secret_access_key=clean(os.getenv("AWS_SECRET_ACCESS_KEY")),
|
| 103 |
+
region_name="eu-west-3",
|
| 104 |
+
)
|
| 105 |
+
s3 = session.client("s3", config=Config(signature_version="s3v4"))
|
| 106 |
+
BUCKET = "mygeodechetbuckets3"
|
| 107 |
+
|
| 108 |
+
# ========== Choix source données ==========
|
| 109 |
+
st.sidebar.header("📂 Source des données")
|
| 110 |
+
data_source = st.sidebar.radio("Charger les données depuis :", ["S3", "Local"], index=0)
|
| 111 |
+
|
| 112 |
+
LOCAL_DATA_DIR = Path(__file__).resolve().parent / "data" # crée un dossier data/ à côté du script
|
| 113 |
+
|
| 114 |
+
def load_data(filename: str, default_sep: str = ",", try_utf8sig_first=True) -> pd.DataFrame:
|
| 115 |
+
"""Charge un CSV soit localement (data/), soit depuis S3."""
|
| 116 |
+
local_path = LOCAL_DATA_DIR / filename
|
| 117 |
+
if data_source == "Local" and local_path.exists():
|
| 118 |
+
st.info(f"Lecture locale : {local_path}")
|
| 119 |
+
with open(local_path, "rb") as f:
|
| 120 |
+
return read_csv_robust(f.read(), default_sep=default_sep, try_utf8sig_first=try_utf8sig_first)
|
| 121 |
+
else:
|
| 122 |
+
st.info(f"Lecture depuis S3 : {filename}")
|
| 123 |
+
obj = s3.get_object(Bucket=BUCKET, Key=filename)
|
| 124 |
+
return read_csv_robust(obj["Body"].read(), default_sep=default_sep, try_utf8sig_first=try_utf8sig_first)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# ========== Lecture des données ==========
|
| 128 |
+
# df_dummies_2019.csv
|
| 129 |
+
df = load_data("df_dummies_2019.csv", default_sep=",", try_utf8sig_first=True)
|
| 130 |
+
df = df.drop(columns=["Unnamed: 0"], errors="ignore")
|
| 131 |
+
|
| 132 |
+
# data_wip_v5.csv
|
| 133 |
+
observed_df = load_data("data_wip_v5.csv", default_sep=";", try_utf8sig_first=True)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Debug léger (commenter quand tout est ok)
|
| 137 |
+
# st.write("Colonnes observed_df:", list(observed_df.columns))
|
| 138 |
+
# st.write("Colonnes df:", list(df.columns)[:15])
|
| 139 |
+
|
| 140 |
+
# Colonnes robustes pour département/année
|
| 141 |
+
DEPT_COL = find_col(observed_df, "Département", "Departement")
|
| 142 |
+
YEAR_COL = find_col(observed_df, "année", "annee")
|
| 143 |
+
|
| 144 |
+
# ========== Chargement centralisé des modèles ==========
|
| 145 |
+
ROOT = Path(__file__).resolve().parent
|
| 146 |
+
MODELS_DIR = ROOT / "models"
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def load_model(filename: str):
|
| 150 |
+
path = MODELS_DIR / filename
|
| 151 |
+
if not path.exists():
|
| 152 |
+
raise FileNotFoundError(f"Introuvable: {path}")
|
| 153 |
+
with open(path, "rb") as f:
|
| 154 |
+
return pickle.load(f)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
MODELS = {
|
| 158 |
+
"Déblais et Gravats": load_model("deblais_gravats.pkl"),
|
| 159 |
+
"Déchets verts": load_model("dechets_verts.pkl"),
|
| 160 |
+
"Encombrants": load_model("encombrants.pkl"),
|
| 161 |
+
"Matériaux recyclables": load_model("materiaux_recyclables.pkl"),
|
| 162 |
+
"Total autres déchets": load_model("total_autres_dechets.pkl"),
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
col_mapping = {
|
| 166 |
+
"Déblais et Gravats": "Déblais_gravats",
|
| 167 |
+
"Déchets verts": "Déchets_verts",
|
| 168 |
+
"Encombrants": "Encombrants",
|
| 169 |
+
"Matériaux recyclables": "Matériaux_recyclables",
|
| 170 |
+
"Total autres déchets": "Total_autres_dechets",
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# ========== UI ==========
|
| 174 |
+
st.set_page_config(layout="wide")
|
| 175 |
+
st.markdown(
|
| 176 |
+
"<h1 style='text-align: center;'>♻️ Simulateur de production de déchets par département</h1>",
|
| 177 |
+
unsafe_allow_html=True,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
top_col1, top_col2 = st.columns([1, 2])
|
| 181 |
+
with top_col1:
|
| 182 |
+
st.markdown(
|
| 183 |
+
"<h3 style='text-align: center;'>📍 Choix du département</h3>",
|
| 184 |
+
unsafe_allow_html=True,
|
| 185 |
+
)
|
| 186 |
+
with top_col2:
|
| 187 |
+
st.markdown(
|
| 188 |
+
"<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>",
|
| 189 |
+
unsafe_allow_html=True,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# Liste des départements depuis df_dummies
|
| 193 |
+
departements = [
|
| 194 |
+
c.replace("Département_", "") for c in df.columns if c.startswith("Département_")
|
| 195 |
+
]
|
| 196 |
+
|
| 197 |
+
top_input_col, chart_col = st.columns([1, 2])
|
| 198 |
+
|
| 199 |
+
with top_input_col:
|
| 200 |
+
selected_dept = st.selectbox(
|
| 201 |
+
"Sélectionner un département",
|
| 202 |
+
sorted(departements),
|
| 203 |
+
index=sorted(departements).index("Ain") if "Ain" in departements else 0,
|
| 204 |
+
)
|
| 205 |
+
row_default = df[df[f"Département_{selected_dept}"] == 1].iloc[0]
|
| 206 |
+
default_dict = row_default.to_dict()
|
| 207 |
+
|
| 208 |
+
st.subheader("⚙️ Paramètres modifiables")
|
| 209 |
+
form_input = {}
|
| 210 |
+
|
| 211 |
+
categories = {
|
| 212 |
+
"📊 Population": [
|
| 213 |
+
"pop_globale_n-2",
|
| 214 |
+
"pop_globale",
|
| 215 |
+
"tranche_age_0-24",
|
| 216 |
+
"tranche_age_25-59",
|
| 217 |
+
"tranche_age_60+",
|
| 218 |
+
"csp1_agriculteurs",
|
| 219 |
+
"csp2_artisans_commerçant_chef_entreprises",
|
| 220 |
+
"csp3_cadres_professions_intellectuelles",
|
| 221 |
+
"csp4_professions_intermédiaires",
|
| 222 |
+
"csp5_employés",
|
| 223 |
+
"csp6_ouvriers",
|
| 224 |
+
"csp7_retraités",
|
| 225 |
+
"csp8_sans_activité",
|
| 226 |
+
"densité_n-2",
|
| 227 |
+
"densité",
|
| 228 |
+
],
|
| 229 |
+
"🏭 Activité économique": [
|
| 230 |
+
"nbre_entreprises",
|
| 231 |
+
"nbre_entreprises_agricole",
|
| 232 |
+
"nb_salaries_secteur_agricole",
|
| 233 |
+
"nbre_entreprises_industrie",
|
| 234 |
+
"nb_salaries_secteur_industrie",
|
| 235 |
+
"nb_salaries_secteur_service",
|
| 236 |
+
"nbre_entreprises_service",
|
| 237 |
+
],
|
| 238 |
+
"🗑️ Déchets": [
|
| 239 |
+
"tonnage_dechet_produit",
|
| 240 |
+
"Matériaux_recyclables",
|
| 241 |
+
"Déblais_gravats",
|
| 242 |
+
"Déchets_verts",
|
| 243 |
+
"Encombrants",
|
| 244 |
+
"Total_autres_dechets",
|
| 245 |
+
"tonnage_dechet_produit_n-2",
|
| 246 |
+
"Matériaux_recyclables_n-2",
|
| 247 |
+
"Déblais_gravats_n-2",
|
| 248 |
+
"Déchets_verts_n-2",
|
| 249 |
+
"Encombrants_n-2",
|
| 250 |
+
"Total_autres_dechets_n-2",
|
| 251 |
+
],
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
for category_name, variables in categories.items():
|
| 255 |
+
with st.expander(category_name, expanded=True):
|
| 256 |
+
for var in variables:
|
| 257 |
+
if var in default_dict:
|
| 258 |
+
default_value = int(round(float(default_dict[var])))
|
| 259 |
+
max_value = int(max(1, default_value * 1.5))
|
| 260 |
+
val = st.slider(
|
| 261 |
+
f"🔧 {var}",
|
| 262 |
+
min_value=0,
|
| 263 |
+
max_value=max_value,
|
| 264 |
+
value=default_value,
|
| 265 |
+
step=1,
|
| 266 |
+
key=f"slider_{var}",
|
| 267 |
+
)
|
| 268 |
+
form_input[var] = int(val)
|
| 269 |
+
|
| 270 |
+
# Build input row pour la prédiction
|
| 271 |
+
input_df = pd.DataFrame([form_input])
|
| 272 |
+
input_df_complete = row_default.to_frame().T.copy()
|
| 273 |
+
for col in input_df.columns:
|
| 274 |
+
if col in input_df_complete.columns:
|
| 275 |
+
input_df_complete.at[input_df_complete.index[0], col] = input_df.at[0, col]
|
| 276 |
+
|
| 277 |
+
with chart_col:
|
| 278 |
+
st.markdown("<div style='margin-top: 30px;'></div>", unsafe_allow_html=True)
|
| 279 |
+
btn_col = st.columns([3, 2, 3])[1]
|
| 280 |
+
with btn_col:
|
| 281 |
+
run_eval = st.button("🔍 Lancer l'évaluation")
|
| 282 |
+
|
| 283 |
+
st.markdown("<div style='margin-top: 40px;'></div>", unsafe_allow_html=True)
|
| 284 |
+
|
| 285 |
+
valeurs_observees, valeurs_predites, labels = [], [], []
|
| 286 |
+
|
| 287 |
+
if run_eval:
|
| 288 |
+
run_eval = False
|
| 289 |
+
for typologie, model in MODELS.items():
|
| 290 |
+
try:
|
| 291 |
+
expected_cols = model.model.exog_names
|
| 292 |
+
if (
|
| 293 |
+
"const" in expected_cols
|
| 294 |
+
and "const" not in input_df_complete.columns
|
| 295 |
+
):
|
| 296 |
+
input_df_complete["const"] = 1.0
|
| 297 |
+
|
| 298 |
+
# Prédiction
|
| 299 |
+
pred = max(0, model.predict(input_df_complete[expected_cols]).iloc[0])
|
| 300 |
+
valeurs_predites.append(float(pred))
|
| 301 |
+
labels.append(typologie)
|
| 302 |
+
|
| 303 |
+
# Observé (2019) — robustesse sur département/année + nom de typologie
|
| 304 |
+
if not DEPT_COL or not YEAR_COL:
|
| 305 |
+
st.error(
|
| 306 |
+
f"Colonnes 'Département/année' introuvables. Colonnes: {list(observed_df.columns)}"
|
| 307 |
+
)
|
| 308 |
+
valeurs_observees.append(0.0)
|
| 309 |
+
else:
|
| 310 |
+
sel_norm = _norm(selected_dept)
|
| 311 |
+
mask = (
|
| 312 |
+
observed_df[DEPT_COL].astype(str).map(_norm) == sel_norm
|
| 313 |
+
) & (pd.to_numeric(observed_df[YEAR_COL], errors="coerce") == 2019)
|
| 314 |
+
filtered = observed_df[mask]
|
| 315 |
+
|
| 316 |
+
excel_col_raw = col_mapping.get(typologie) # ex: "Déblais_gravats"
|
| 317 |
+
excel_col_norm = _norm(excel_col_raw)
|
| 318 |
+
cand_cols = [
|
| 319 |
+
c for c in observed_df.columns if _norm(c) == excel_col_norm
|
| 320 |
+
]
|
| 321 |
+
target_col = cand_cols[0] if cand_cols else ""
|
| 322 |
+
|
| 323 |
+
if not filtered.empty and target_col:
|
| 324 |
+
valeurs_observees.append(
|
| 325 |
+
get_numeric_value(filtered[target_col].iloc[:1])
|
| 326 |
+
)
|
| 327 |
+
else:
|
| 328 |
+
valeurs_observees.append(0.0)
|
| 329 |
+
|
| 330 |
+
except Exception as e:
|
| 331 |
+
st.error(f"Erreur avec le modèle {typologie}")
|
| 332 |
+
st.exception(e)
|
| 333 |
+
|
| 334 |
+
if valeurs_observees and valeurs_predites:
|
| 335 |
+
# Force float
|
| 336 |
+
valeurs_observees = [float(v) for v in valeurs_observees]
|
| 337 |
+
valeurs_predites = [float(v) for v in valeurs_predites]
|
| 338 |
+
|
| 339 |
+
x = np.arange(len(labels))
|
| 340 |
+
width = 0.4
|
| 341 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 342 |
+
|
| 343 |
+
ax.bar(
|
| 344 |
+
x - width / 2,
|
| 345 |
+
valeurs_observees,
|
| 346 |
+
width,
|
| 347 |
+
label="Observé (2019)",
|
| 348 |
+
color="steelblue",
|
| 349 |
+
)
|
| 350 |
+
bar_colors = [
|
| 351 |
+
(1, 0, 0, 0.6) if pred > obs else (0, 0.6, 0, 0.6)
|
| 352 |
+
for pred, obs in zip(valeurs_predites, valeurs_observees)
|
| 353 |
+
]
|
| 354 |
+
ax.bar(
|
| 355 |
+
x + width / 2, valeurs_predites, width, label="Prévision", color=bar_colors
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
for i in range(len(labels)):
|
| 359 |
+
ax.text(
|
| 360 |
+
x[i] - width / 2,
|
| 361 |
+
valeurs_observees[i] + max(valeurs_observees) * 0.01,
|
| 362 |
+
f"{valeurs_observees[i]:,.0f}",
|
| 363 |
+
ha="center",
|
| 364 |
+
va="bottom",
|
| 365 |
+
fontsize=9,
|
| 366 |
+
)
|
| 367 |
+
ax.text(
|
| 368 |
+
x[i] + width / 2,
|
| 369 |
+
valeurs_predites[i] + max(valeurs_predites) * 0.01,
|
| 370 |
+
f"{valeurs_predites[i]:,.0f}",
|
| 371 |
+
ha="center",
|
| 372 |
+
va="bottom",
|
| 373 |
+
fontsize=9,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
ax.set_ylabel("Tonnes")
|
| 377 |
+
ax.set_title("Comparaison Observé vs Prédit")
|
| 378 |
+
ax.set_xticks(x)
|
| 379 |
+
ax.set_xticklabels(labels, rotation=45, ha="right")
|
| 380 |
+
ax.legend()
|
| 381 |
+
st.pyplot(fig)
|
| 382 |
+
|
| 383 |
+
st.markdown("---")
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
# ========== SHAP ==========
|
| 387 |
+
st.subheader(
|
| 388 |
+
f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
selected_typologie = st.selectbox(
|
| 392 |
+
"Choisissez une typologie de déchets à analyser avec SHAP :", list(MODELS.keys())
|
| 393 |
+
)
|
| 394 |
+
typologie = selected_typologie
|
| 395 |
+
model_sm = MODELS[typologie]
|
| 396 |
+
|
| 397 |
+
try:
|
| 398 |
+
used_features = model_sm.model.exog_names
|
| 399 |
+
used_features_no_const = [f for f in used_features if f != "const"]
|
| 400 |
+
X_used = df[used_features_no_const].copy()
|
| 401 |
+
|
| 402 |
+
if "const" in used_features:
|
| 403 |
+
X_used["const"] = 1.0
|
| 404 |
+
|
| 405 |
+
intercept = model_sm.params["const"] if "const" in model_sm.params else 0
|
| 406 |
+
coefs = model_sm.params[used_features_no_const].values
|
| 407 |
+
|
| 408 |
+
lr = LinearRegression()
|
| 409 |
+
lr.intercept_ = float(intercept)
|
| 410 |
+
lr.coef_ = np.array(coefs, dtype=float)
|
| 411 |
+
lr.feature_names_in_ = np.array(used_features_no_const)
|
| 412 |
+
|
| 413 |
+
X_used_corrected = X_used.reindex(columns=lr.feature_names_in_, fill_value=0)
|
| 414 |
+
|
| 415 |
+
explainer = shap.Explainer(lr, X_used_corrected)
|
| 416 |
+
shap_values = explainer(X_used_corrected)
|
| 417 |
+
|
| 418 |
+
selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]
|
| 419 |
+
|
| 420 |
+
# On exclut les cibles (observées et n-2) des graphes SHAP (mais pas de la prédiction)
|
| 421 |
+
exclude_vars = [
|
| 422 |
+
"tonnage_dechet_produit_n-2",
|
| 423 |
+
"tonnage_dechet_produit",
|
| 424 |
+
"Total_autres_dechets_n-2",
|
| 425 |
+
"Total_autres_dechets",
|
| 426 |
+
"Déblais_gravats_n-2",
|
| 427 |
+
"Déblais_gravats",
|
| 428 |
+
"Déchets_verts_n-2",
|
| 429 |
+
"Déchets_verts",
|
| 430 |
+
"Encombrants_n-2",
|
| 431 |
+
"Encombrants",
|
| 432 |
+
"Matériaux_recyclables_n-2",
|
| 433 |
+
"Matériaux_recyclables",
|
| 434 |
+
]
|
| 435 |
+
mask = np.array([name not in exclude_vars for name in shap_values.feature_names])
|
| 436 |
+
filtered_shap = shap.Explanation(
|
| 437 |
+
values=shap_values.values[:, mask],
|
| 438 |
+
base_values=shap_values.base_values,
|
| 439 |
+
data=shap_values.data[:, mask],
|
| 440 |
+
feature_names=[
|
| 441 |
+
name for name in shap_values.feature_names if name not in exclude_vars
|
| 442 |
+
],
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
col1 = st.columns(1)[0]
|
| 446 |
+
with col1:
|
| 447 |
+
st.markdown(
|
| 448 |
+
"<h6 style='text-align: center;'> Waterfall</h6>", unsafe_allow_html=True
|
| 449 |
+
)
|
| 450 |
+
fig = plt.figure(figsize=(3, 2))
|
| 451 |
+
shap.plots.waterfall(filtered_shap[selected_index], max_display=10, show=False)
|
| 452 |
+
st.pyplot(fig, bbox_inches="tight", dpi=200, clear_figure=True)
|
| 453 |
+
|
| 454 |
+
except Exception as e:
|
| 455 |
+
st.error(f"Erreur dans le SHAP pour {typologie}")
|
| 456 |
+
st.exception(e)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
# ========== Interprétation LLM (Mistral) ==========
|
| 460 |
+
try:
|
| 461 |
+
mean_shap_values = shap_values.abs.mean(0).values
|
| 462 |
+
feature_names = lr.feature_names_in_
|
| 463 |
+
sorted_indices = mean_shap_values.argsort()[::-1]
|
| 464 |
+
top_n = 10
|
| 465 |
+
list_coef = "\n".join(
|
| 466 |
+
[
|
| 467 |
+
f"{feature_names[i]}: {float(mean_shap_values[i]):.4f}"
|
| 468 |
+
for i in sorted_indices[:top_n]
|
| 469 |
+
]
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
prompt_template = f"""
|
| 473 |
+
Tu es un expert en data science et en statistique, spécialisé dans l'interprétation de modèles explicatifs avec des coefficients de Shapley.
|
| 474 |
+
|
| 475 |
+
Je te fournis les contributions SHAP moyennes des variables d'un modèle linéaire.
|
| 476 |
+
|
| 477 |
+
Ta mission :
|
| 478 |
+
- Identifie les variables qui ont le plus d’impact (positif/négatif) sur la variable cible.
|
| 479 |
+
- Mets en évidence les tendances démographiques/économiques.
|
| 480 |
+
- Reste clair pour un public non expert, tout en étant rigoureux.
|
| 481 |
+
|
| 482 |
+
Coefficients (SHAP mean abs) :
|
| 483 |
+
{list_coef}
|
| 484 |
+
|
| 485 |
+
Contexte :
|
| 486 |
+
- Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des déchets.
|
| 487 |
+
- Variable cible : {typologie}
|
| 488 |
+
- Modèle : OLS (Statsmodels) interprété via SHAP (approx. linéaire).
|
| 489 |
+
- Variables explicatives (exemples) :
|
| 490 |
+
secteurs (salariés agricole/industrie/service), CSP (1..8), tranches d’âge (0-24/25-59/60+),
|
| 491 |
+
population/densité, historiques à n-2.
|
| 492 |
+
- Ne commente pas les variables cibles/exclues suivantes : {exclude_vars}.
|
| 493 |
+
"""
|
| 494 |
+
|
| 495 |
+
load_dotenv()
|
| 496 |
+
api_key = os.getenv("MISTRAL_API_KEY")
|
| 497 |
+
|
| 498 |
+
if api_key:
|
| 499 |
+
with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
|
| 500 |
+
model_llm = ChatMistralAI(
|
| 501 |
+
model="mistral-small-latest", mistral_api_key=api_key
|
| 502 |
+
)
|
| 503 |
+
parser = StrOutputParser()
|
| 504 |
+
response = model_llm.invoke(prompt_template)
|
| 505 |
+
explanation_text = parser.invoke(response)
|
| 506 |
+
|
| 507 |
+
st.markdown("#### 🤖 Interprétation automatique (LLM)")
|
| 508 |
+
st.success(explanation_text)
|
| 509 |
+
else:
|
| 510 |
+
st.info(
|
| 511 |
+
"ℹ️ MISTRAL_API_KEY manquant dans l'environnement. Ajoute ta clé pour activer l'interprétation automatique."
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
except Exception as e:
|
| 515 |
+
st.error("Erreur lors de l'analyse SHAP / appel au LLM.")
|
| 516 |
+
st.exception(e)
|