PoroKami commited on
Commit
0028613
·
verified ·
1 Parent(s): b78f528

Update src/app.py

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