PoroKami commited on
Commit
63f3f0e
·
1 Parent(s): 061eb09

really dodo

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