File size: 18,711 Bytes
0028613
31c794f
0028613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31c794f
0028613
3926bca
 
 
0028613
 
31c794f
0028613
 
31c794f
0028613
31c794f
0028613
 
 
 
 
 
 
 
 
 
 
1b42a5c
67c39b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0028613
31c794f
0028613
 
31c794f
 
 
 
0028613
 
 
 
31c794f
 
0028613
 
 
 
 
 
 
 
 
 
 
 
 
 
31c794f
0028613
 
 
31c794f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d458254
 
 
 
0aa7446
31c794f
0028613
d458254
434892d
0aa7446
0028613
 
 
31c794f
0028613
 
31c794f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0028613
 
31c794f
 
 
 
 
0028613
 
 
 
 
 
 
 
 
 
 
 
31c794f
0028613
 
 
31c794f
0028613
31c794f
0028613
31c794f
 
0028613
 
 
 
 
 
 
31c794f
0028613
 
 
 
 
 
 
 
 
31c794f
 
 
 
 
 
0028613
 
31c794f
 
 
0028613
 
31c794f
 
 
 
 
 
0028613
 
 
 
 
 
67c39b3
0028613
 
 
31c794f
 
0028613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31c794f
 
 
0028613
 
31c794f
 
 
 
 
 
0028613
31c794f
 
0028613
 
31c794f
0028613
31c794f
0028613
 
 
31c794f
 
0028613
 
 
 
31c794f
0028613
 
 
31c794f
0028613
 
 
 
 
 
 
 
 
31c794f
0028613
 
 
 
31c794f
 
 
 
0028613
 
31c794f
 
 
 
0028613
 
 
 
31c794f
0028613
 
 
 
 
31c794f
0028613
3813419
 
 
0028613
 
 
 
3813419
 
31c794f
 
 
 
 
3813419
31c794f
 
 
 
0028613
3813419
31c794f
3813419
 
0028613
 
3813419
31c794f
 
3813419
 
 
fbae698
0028613
3813419
 
0028613
 
3813419
0028613
 
31c794f
0028613
31c794f
 
 
 
 
 
0028613
 
 
 
 
 
31c794f
0028613
 
 
 
31c794f
0028613
 
3813419
0028613
 
 
 
525f494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# =========================
#  App Streamlit - GeoDéchet (patched)
# =========================
import os
os.environ.setdefault("MPLCONFIGDIR", "/tmp/mpl")
os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false")

import re
import unicodedata
from io import StringIO
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pickle
import shap
import streamlit as st
from sklearn.linear_model import LinearRegression
from dotenv import load_dotenv

from langchain_core.output_parsers import StrOutputParser
from langchain_mistralai import ChatMistralAI

# ========== Helpers robustes ==========
def _norm(s: str) -> str:
    """Normalise une chaîne (BOM/accents/espaces/casse) pour matching 'humain'."""
    if s is None:
        return ""
    s = str(s).replace("\ufeff", "")
    s = unicodedata.normalize("NFKD", s)
    s = s.encode("ascii", "ignore").decode("ascii")
    s = re.sub(r"\s+", " ", s)
    return s.strip().lower()

def find_col(df: pd.DataFrame, *aliases: str) -> str:
    """Trouve le nom réel d'une colonne à partir d'alias ('Département'/'Departement', 'année'/'annee')."""
    targets = {_norm(a) for a in aliases}
    for c in df.columns:
        if _norm(c) in targets:
            return c
    return ""

def to_float(x, default=0.0):
    """Convertit '72,7', ' 1 234,56', etc. en float."""
    if x is None:
        return float(default)
    if isinstance(x, (int, float, np.number)):
        return float(x)
    s = str(x).strip()
    s = s.replace("\u00A0", " ").replace("\u202F", " ")  # espaces insécables
    s = s.replace(" ", "")          # milliers
    s = s.replace(",", ".")         # virgule -> point
    try:
        return float(s)
    except Exception:
        return float(default)


def get_numeric_value(series: pd.Series) -> float:
    """Convertit proprement une série (str possiblement avec espaces, virgule décimale) en float."""
    s = series.astype(str)
    s = (
        s.str.replace("\u00A0", " ", regex=False)  # nbsp
         .str.replace("\u202F", " ", regex=False)  # thin space
         .str.replace(" ", "", regex=False)        # supprime milliers
         .str.replace(",", ".", regex=False)       # virgule -> point
    )
    val = pd.to_numeric(s, errors="coerce")
    return float(val.iloc[0]) if len(val) and pd.notna(val.iloc[0]) else 0.0

def read_csv_robust(body_bytes: bytes, default_sep: str = ",", try_utf8sig_first: bool = True) -> pd.DataFrame:
    """Lecture robuste : utf-8-sig puis latin-1, fallback utf-8, et réparation des en-têtes si mojibake."""
    df = None
    if try_utf8sig_first:
        try:
            df = pd.read_csv(StringIO(body_bytes.decode("utf-8-sig")), sep=default_sep)
        except Exception:
            pass
    if df is None:
        try:
            df = pd.read_csv(StringIO(body_bytes.decode("latin-1")), sep=default_sep)
        except Exception:
            df = pd.read_csv(StringIO(body_bytes.decode("utf-8")), sep=default_sep)

    cols = [c.replace("\ufeff", "") for c in df.columns]
    if any(("Ã" in c) or ("" in c) or ("Â" in c) for c in cols):
        cols = [c.encode("latin-1", "ignore").decode("utf-8", "ignore").replace("\ufeff", "") for c in cols]
    df.columns = cols
    return df

# --- Normalisation de noms de colonnes pour matcher modèle <-> DF ---
def _ascii_key(name: str) -> str:
    """Normalise un nom: accents→ASCII, ’`→', espaces→_, garde -/_/'."""
    if name is None:
        return ""
    s = str(name)
    s = s.replace("’", "'").replace("`", "'")
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode("ascii")
    s = s.replace(" ", "_")
    s = re.sub(r"[^0-9a-zA-Z_\-']", "_", s)
    return s

def reindex_like_expected(X: pd.DataFrame, expected_cols: list[str]) -> tuple[pd.DataFrame, list[str]]:
    """Construit un DF avec exactement les colonnes attendues (dans le même ordre).
    - mappe via _ascii_key
    - crée à 0.0 les colonnes manquantes
    """
    present = {_ascii_key(c): c for c in X.columns}
    out = {}
    missing = []
    for col in expected_cols:
        key = _ascii_key(col)
        if key in present:
            out[col] = X[present[key]]
        else:
            out[col] = 0.0
            missing.append(col)
    return pd.DataFrame(out, index=X.index), missing

# ========== Chargement données locales ==========
ROOT = Path(__file__).resolve().parent
DATA_DIR = ROOT / "data"

with open(DATA_DIR / "df_dummies_2019.csv", "rb") as f:
    df = read_csv_robust(f.read(), default_sep=",", try_utf8sig_first=True)
df = df.drop(columns=["Unnamed: 0"], errors="ignore")

with open(DATA_DIR / "data_wip_v5.csv", "rb") as f:
    observed_df = read_csv_robust(f.read(), default_sep=",", try_utf8sig_first=True)

DEPT_COL = find_col(observed_df, "Département", "Departement")
YEAR_COL = find_col(observed_df, "année", "annee")

# ========== Chargement centralisé des modèles (robuste aux fichiers '(1).pkl') ==========
MODELS_DIR = ROOT / "models"

def load_model_smart(*candidates: str):
    """Charge le premier fichier existant parmi les candidats.
    Si un nom sans extension est donné, on essaie '*.pkl' qui 'commence par' ce nom.
    """
    for cand in candidates:
        p = Path(cand)
        if not p.suffix:
            # chercher dans models/ un fichier qui commence par ce stem
            matches = sorted(MODELS_DIR.glob(f"{cand}*.pkl"))
            if matches:
                with open(matches[0], "rb") as f:
                    return pickle.load(f)
        full = MODELS_DIR / cand
        if full.exists():
            with open(full, "rb") as f:
                return pickle.load(f)
    raise FileNotFoundError(f"Aucun des fichiers modèles trouvés: {candidates}")

MODELS = {
    "Déblais et Gravats": load_model_smart("deblais_gravats.pkl", "deblais_gravats"),
    "Déchets verts":      load_model_smart("dechets_verts.pkl", "dechets_verts"),
    "Encombrants":        load_model_smart("encombrants.pkl", "encombrants"),
    "Matériaux recyclables": load_model_smart("materiaux_recyclables.pkl", "materiaux_recyclables"),
    "Total autres déchets":  load_model_smart("total_autres_dechets.pkl", "total_autres_dechets"),
}

col_mapping = {
    "Déblais et Gravats": "Déblais_gravats",
    "Déchets verts": "Déchets_verts",
    "Encombrants": "Encombrants",
    "Matériaux recyclables": "Matériaux_recyclables",
    "Total autres déchets": "Total_autres_dechets",
}

# ========== UI ==========
st.set_page_config(layout="wide")
st.markdown("<h1 style='text-align: center;'>♻️ Simulateur de production de déchets par département</h1>", unsafe_allow_html=True)

top_col1, top_col2 = st.columns([1, 2])
with top_col1:
    st.markdown("<h3 style='text-align: center;'>📍 Choix du département</h3>", unsafe_allow_html=True)
with top_col2:
    st.markdown("<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>", unsafe_allow_html=True)

# Liste des départements depuis df_dummies (garanti aligné avec les colonnes)
departements = [c.replace("Département_", "") for c in df.columns if c.startswith("Département_")]

top_input_col, chart_col = st.columns([1, 2])

with top_input_col:
    selected_dept = st.selectbox(
        "Sélectionner un département",
        sorted(departements),
        index=sorted(departements).index("Ain") if "Ain" in departements else 0
    )
    row_default = df[df[f"Département_{selected_dept}"] == 1].iloc[0]
    default_dict = row_default.to_dict()

    st.subheader("⚙️ Paramètres modifiables")
    form_input = {}

    categories = {
        "📊 Population": [
            "pop_globale_n-2", "pop_globale",
            "tranche_age_0-24", "tranche_age_25-59", "tranche_age_60+",
            "csp1_agriculteurs", "csp2_artisans_commerçant_chef_entreprises",
            "csp3_cadres_professions_intellectuelles", "csp4_professions_intermédiaires",
            "csp5_employés", "csp6_ouvriers", "csp7_retraités", "csp8_sans_activité",
            "densité_n-2", "densité"
        ],
        "🏭 Activité économique": [
            "nbre_entreprises", "nbre_entreprises_agricole", "nb_salaries_secteur_agricole",
            "nbre_entreprises_industrie", "nb_salaries_secteur_industrie",
            "nb_salaries_secteur_service", "nbre_entreprises_service"
        ],
        "🗑️ Déchets": [
            "tonnage_dechet_produit", "Matériaux_recyclables", "Déblais_gravats",
            "Déchets_verts", "Encombrants", "Total_autres_dechets",
            "tonnage_dechet_produit_n-2", "Matériaux_recyclables_n-2",
            "Déblais_gravats_n-2", "Déchets_verts_n-2",
            "Encombrants_n-2", "Total_autres_dechets_n-2",
        ]
    }

    for category_name, variables in categories.items():
        with st.expander(category_name, expanded=True):
            for var in variables:
                if var in default_dict:
                    default_value = int(round(to_float(default_dict[var])))
                    max_value = int(max(1, default_value * 1.5))
                    val = st.slider(
                        f"🔧 {var}",
                        min_value=0, max_value=max_value, value=default_value, step=1,
                        key=f"slider_{var}"
                    )
                    form_input[var] = int(val)

    # Build input row pour la prédiction
    input_df = pd.DataFrame([form_input])
    input_df_complete = row_default.to_frame().T.copy()
    for col in input_df.columns:
        if col in input_df_complete.columns:
            input_df_complete.at[input_df_complete.index[0], col] = input_df.at[0, col]

with chart_col:
    st.markdown("<div style='margin-top: 30px;'></div>", unsafe_allow_html=True)
    btn_col = st.columns([3, 2, 3])[1]
    with btn_col:
        run_eval = st.button("🔍 Lancer l'évaluation")

    st.markdown("<div style='margin-top: 40px;'></div>", unsafe_allow_html=True)

    valeurs_observees, valeurs_predites, labels = [], [], []

    if run_eval:
        run_eval = False
        for typologie, model in MODELS.items():
            try:
                expected_cols = model.model.exog_names  # ordre et noms attendus
                # constante si attendue
                if "const" in expected_cols and "const" not in input_df_complete.columns:
                    input_df_complete["const"] = 1.0

                # réaligner les colonnes (accents/apostrophes/espaces) + créer manquantes à 0
                X_in, missing_cols = reindex_like_expected(input_df_complete, expected_cols)
                if missing_cols:
                    with st.expander(f"Colonnes manquantes (créées à 0) — {typologie}"):
                        st.write(missing_cols)

                # Prédiction
                pred = float(model.predict(X_in).iloc[0])
                valeurs_predites.append(max(0.0, pred))
                labels.append(typologie)

                # Observé (2019)
                if not DEPT_COL or not YEAR_COL:
                    st.error(f"Colonnes 'Département/année' introuvables. Colonnes: {list(observed_df.columns)}")
                    valeurs_observees.append(0.0)
                else:
                    sel_norm = _norm(selected_dept)
                    mask = (observed_df[DEPT_COL].astype(str).map(_norm) == sel_norm) & \
                           (pd.to_numeric(observed_df[YEAR_COL], errors="coerce") == 2019)
                    filtered = observed_df[mask]

                    excel_col_raw = col_mapping.get(typologie)  # ex: "Déblais_gravats"
                    excel_col_norm = _norm(excel_col_raw)
                    cand_cols = [c for c in observed_df.columns if _norm(c) == excel_col_norm]
                    target_col = cand_cols[0] if cand_cols else ""

                    if not filtered.empty and target_col:
                        valeurs_observees.append(get_numeric_value(filtered[target_col].iloc[:1]))
                    else:
                        valeurs_observees.append(0.0)

            except Exception as e:
                st.error(f"Erreur avec le modèle {typologie}")
                st.exception(e)

    if valeurs_observees and valeurs_predites:
        valeurs_observees = [float(v) for v in valeurs_observees]
        valeurs_predites  = [float(v) for v in valeurs_predites]

        x = np.arange(len(labels))
        width = 0.4
        fig, ax = plt.subplots(figsize=(10, 6))
        ax.bar(x - width/2, valeurs_observees, width, label='Observé (2019)', color='steelblue')
        bar_colors = [(1, 0, 0, 0.6) if pred > obs else (0, 0.6, 0, 0.6)
                      for pred, obs in zip(valeurs_predites, valeurs_observees)]
        ax.bar(x + width/2, valeurs_predites, width, label='Prévision', color=bar_colors)

        for i in range(len(labels)):
            ax.text(x[i] - width/2, valeurs_observees[i] + max(valeurs_observees)*0.01,
                    f"{valeurs_observees[i]:,.0f}", ha='center', va='bottom', fontsize=9)
            ax.text(x[i] + width/2, valeurs_predites[i] + max(valeurs_predites)*0.01,
                    f"{valeurs_predites[i]:,.0f}", ha='center', va='bottom', fontsize=9)

        ax.set_ylabel("Tonnes")
        ax.set_title("Comparaison Observé vs Prédit")
        ax.set_xticks(x)
        ax.set_xticklabels(labels, rotation=45, ha='right')
        ax.legend()
        st.pyplot(fig)
        st.markdown("---")

# ========== SHAP ==========
st.subheader(f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}")

selected_typologie = st.selectbox(
    "Choisissez une typologie de déchets à analyser avec SHAP :", list(MODELS.keys())
)
typologie = selected_typologie
model_sm = MODELS[typologie]

try:
    used_features = model_sm.model.exog_names  # peut contenir 'const'
    # 1) Construire X avec exactement ces colonnes (on crée les manquantes à 0)
    X_used_all, miss_shap = reindex_like_expected(df, used_features)
    if miss_shap:
        with st.expander(f"Colonnes SHAP manquantes (créées à 0) — {typologie}"):
            st.write(miss_shap)

    # 2) Retirer 'const' pour le modèle scikit-learn
    if "const" in X_used_all.columns:
        X_used_no_const = X_used_all.drop(columns=["const"])
    else:
        X_used_no_const = X_used_all

    # 3) Recréer un modèle linéaire sklearn équivalent
    coef_names = [c for c in used_features if c != "const"]
    coefs = model_sm.params.reindex(coef_names).fillna(0).values
    intercept = float(model_sm.params.get("const", 0.0))

    lr = LinearRegression()
    lr.coef_ = np.asarray(coefs, dtype=float)
    lr.intercept_ = intercept
    lr.feature_names_in_ = np.array(coef_names)

    # 4) Aligner la matrice d'entrée ET forcer le type numérique
    X_used_corrected = X_used_no_const.reindex(columns=coef_names, fill_value=0)
    X_used_corrected = X_used_corrected.apply(pd.to_numeric, errors="coerce").fillna(0)

    # 5) Explainer + valeurs SHAP
    explainer = shap.Explainer(lr, X_used_corrected, feature_names=coef_names)
    shap_values = explainer(X_used_corrected)

    # Index du département sélectionné (dans df_dummies)
    selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]

    # Exclure certaines cibles des visus SHAP
    exclude_vars = [
        "tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
        "Total_autres_dechets_n-2", "Total_autres_dechets",
        "Déblais_gravats_n-2", "Déblais_gravats",
        "Déchets_verts_n-2", "Déchets_verts",
        "Encombrants_n-2", "Encombrants",
        "Matériaux_recyclables_n-2", "Matériaux_recyclables"
    ]
    mask = np.array([name not in exclude_vars for name in shap_values.feature_names])
    filtered_shap = shap.Explanation(
        values=shap_values.values[:, mask],
        base_values=shap_values.base_values,
        data=shap_values.data[:, mask],
        feature_names=[name for name in shap_values.feature_names if name not in exclude_vars]
    )

    col1 = st.columns(1)[0]
    with col1:
        st.markdown("<h6 style='text-align: center;'>🩜 Waterfall</h6>", unsafe_allow_html=True)
        fig = plt.figure(figsize=(3, 2))
        shap.plots.waterfall(filtered_shap[selected_index], max_display=10, show=False)
        st.pyplot(fig, bbox_inches="tight", dpi=200, clear_figure=True)

except Exception as e:
    st.error(f"Erreur dans le SHAP pour {typologie}")
    st.exception(e)



# ========== Interprétation LLM (Mistral) ==========
try:
    mean_shap_values = shap_values.abs.mean(0).values
    feature_names = lr.feature_names_in_
    sorted_indices = mean_shap_values.argsort()[::-1]
    top_n = 10
    list_coef = "\n".join(
        [
            f"{feature_names[i]}: {float(mean_shap_values[i]):.4f}"
            for i in sorted_indices[:top_n]
        ]
    )

    prompt_template = f"""
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.

Je te fournis les contributions SHAP moyennes des variables d'un modèle linéaire.

Ta mission :
- Identifie les variables qui ont le plus d’impact (positif/négatif) sur la variable cible.
- Mets en évidence les tendances démographiques/économiques.
- Reste clair pour un public non expert, tout en étant rigoureux.

Coefficients (SHAP mean abs) :
{list_coef}

Contexte :
- Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des déchets.
- Variable cible : {typologie}
- Modèle : OLS (Statsmodels) interprété via SHAP (approx. linéaire).
- Variables explicatives (exemples) :
  secteurs (salariés agricole/industrie/service), CSP (1..8), tranches d’âge (0-24/25-59/60+),
  population/densité, historiques à n-2.
- Ne commente pas les variables cibles/exclues suivantes : {exclude_vars}.
"""

    load_dotenv()
    api_key = os.getenv("MISTRAL_API_KEY")

    if api_key:
        with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
            model_llm = ChatMistralAI(
                model="mistral-small-latest", mistral_api_key=api_key
            )
            parser = StrOutputParser()
            response = model_llm.invoke(prompt_template)
            explanation_text = parser.invoke(response)

        st.markdown("#### 🤖 Interprétation automatique (LLM)")
        st.success(explanation_text)
    else:
        st.info(
            "ℹ️ MISTRAL_API_KEY manquant dans l'environnement. Ajoute ta clé pour activer l'interprétation automatique."
        )

except Exception as e:
    st.error("Erreur lors de l'analyse SHAP / appel au LLM.")
    st.exception(e)