PoroKami commited on
Commit
061eb09
·
1 Parent(s): 4be7993
Files changed (1) hide show
  1. src/app.py +64 -140
src/app.py CHANGED
@@ -1,21 +1,52 @@
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import pickle
4
  import matplotlib.pyplot as plt
5
  from dotenv import load_dotenv
6
- import os
7
  import boto3
8
  from pathlib import Path
9
  from io import StringIO
10
  import numpy as np
11
  from botocore.config import Config
12
- from botocore import UNSIGNED
13
  import shap
14
  from sklearn.linear_model import LinearRegression
15
  from langchain_mistralai import ChatMistralAI
16
  from langchain_core.output_parsers import StrOutputParser
17
-
18
- # --- Chargement des données depuis S3 ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def clean(s):
20
  return (s or "").strip().replace("\r", "").replace("\n", "")
21
 
@@ -26,16 +57,20 @@ session = boto3.Session(
26
  )
27
  s3 = session.client("s3", config=Config(signature_version="s3v4"))
28
 
29
- # Lire df_dummies_2019.csv (UTF-8-SIG)
30
  obj = s3.get_object(Bucket="mygeodechetbuckets3", Key="df_dummies_2019.csv")
31
  df = pd.read_csv(StringIO(obj["Body"].read().decode("utf-8-sig")), sep=",")
32
  df = df.drop(columns=["Unnamed: 0"], errors="ignore")
33
 
34
- # Lire data_wip_v5.csv (latin-1 avec ;)
35
  obj2 = s3.get_object(Bucket="mygeodechetbuckets3", Key="data_wip_v5.csv")
36
  observed_df = pd.read_csv(StringIO(obj2["Body"].read().decode("latin-1")), sep=";")
37
 
38
- # --- Chargement centralisé des modèles ---
 
 
 
 
39
  ROOT = Path(__file__).resolve().parent
40
  MODELS_DIR = ROOT / "models"
41
 
@@ -62,21 +97,20 @@ col_mapping = {
62
  "Total autres déchets": "Total_autres_dechets"
63
  }
64
 
65
- # === Liste des départements
66
  departements = [col.replace("Département_", "") for col in df.columns if col.startswith("Département_")]
67
 
68
- # === Mise en page
69
  st.set_page_config(layout="wide")
70
  st.markdown("<h1 style='text-align: center;'>♻️ Simulateur de production de déchets par département</h1>", unsafe_allow_html=True)
71
 
72
- # === Titre + Choix département alignés
73
  top_col1, top_col2 = st.columns([1, 2])
74
  with top_col1:
75
  st.markdown("<h3 style='text-align: center;'>📍 Choix du département</h3>", unsafe_allow_html=True)
76
  with top_col2:
77
  st.markdown("<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>", unsafe_allow_html=True)
78
 
79
- # === Séparation en colonnes
80
  top_input_col, chart_col = st.columns([1, 2])
81
 
82
  with top_input_col:
@@ -156,25 +190,32 @@ with chart_col:
156
  valeurs_predites.append(float(prediction))
157
  labels.append(typologie)
158
 
159
- filtered = observed_df[
160
- (observed_df["Département"] == selected_dept) & (observed_df["année"] == 2019)
161
- ]
162
- excel_col = col_mapping.get(typologie)
163
- if not filtered.empty and excel_col in filtered.columns:
164
- try:
165
- valeurs_observees.append(float(filtered[excel_col].values[0]))
166
- except Exception:
167
- valeurs_observees.append(0.0)
168
- else:
169
  valeurs_observees.append(0.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  except Exception as e:
171
  st.error(f"Erreur avec le modèle {typologie}")
172
  st.exception(e)
173
 
174
  if valeurs_observees and valeurs_predites:
175
- # forcer en float
176
  valeurs_observees = [float(v) for v in valeurs_observees]
177
- valeurs_predites = [float(v) for v in valeurs_predites]
178
 
179
  x = np.arange(len(labels))
180
  width = 0.4
@@ -199,120 +240,3 @@ with chart_col:
199
  st.pyplot(fig)
200
 
201
  st.markdown("---")
202
-
203
- # === Suite SHAP et Mistral (inchangée, mais garde tes float casts)...
204
-
205
-
206
- st.subheader(f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}")
207
-
208
- selected_typologie = st.selectbox("Choisissez une typologie de déchets à analyser avec SHAP :", list(MODELS.keys()))
209
- typologie = selected_typologie
210
- model_sm = MODELS[typologie]
211
-
212
- try:
213
- used_features = model_sm.model.exog_names
214
- used_features_no_const = [f for f in used_features if f != "const"]
215
- X_used = df[used_features_no_const].copy()
216
-
217
- if "const" in used_features:
218
- X_used["const"] = 1.0
219
-
220
- intercept = model_sm.params['const'] if 'const' in model_sm.params else 0
221
- coefs = model_sm.params[used_features_no_const].values
222
-
223
- lr = LinearRegression()
224
- lr.intercept_ = intercept
225
- lr.coef_ = coefs
226
- lr.feature_names_in_ = np.array(used_features_no_const)
227
-
228
- X_used_corrected = X_used.reindex(columns=lr.feature_names_in_, fill_value=0)
229
-
230
- explainer = shap.Explainer(lr, X_used_corrected)
231
- shap_values = explainer(X_used_corrected)
232
-
233
- selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]
234
-
235
- exclude_vars = [
236
- "tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
237
- "Total_autres_dechets_n-2", "Total_autres_dechets",
238
- "Déblais_gravats_n-2", "Déblais_gravats",
239
- "Déchets_verts_n-2", "Déchets_verts",
240
- "Encombrants_n-2", "Encombrants",
241
- "Matériaux_recyclables_n-2", "Matériaux_recyclables"
242
- ]
243
- mask = np.array([name not in exclude_vars for name in shap_values.feature_names])
244
- filtered_shap = shap.Explanation(
245
- values=shap_values.values[:, mask],
246
- base_values=shap_values.base_values,
247
- data=shap_values.data[:, mask],
248
- feature_names=[name for name in shap_values.feature_names if name not in exclude_vars]
249
- )
250
-
251
- col1 = st.columns(1)[0]
252
- with col1:
253
- st.markdown("<h6 style='text-align: center;'>🩜 Waterfall</h6>", unsafe_allow_html=True)
254
- fig = plt.figure(figsize=(3, 2))
255
- shap.plots.waterfall(filtered_shap[selected_index], max_display=10, show=False)
256
- st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
257
-
258
- except Exception as e:
259
- st.error(f"Erreur dans le SHAP pour {typologie}")
260
- st.exception(e)
261
-
262
- # === 🧠 Explication automatique avec Mistral ===
263
- mean_shap_values = shap_values.abs.mean(0).values
264
- feature_names = lr.feature_names_in_
265
-
266
- sorted_indices = mean_shap_values.argsort()[::-1]
267
- top_n = 10
268
- list_coef = "\n".join([
269
- f"{feature_names[i]}: {mean_shap_values[i]:.4f}"
270
- for i in sorted_indices[:top_n]
271
- ])
272
-
273
- prompt_template = f"""
274
- 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.
275
-
276
- Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
277
-
278
- Ta mission :
279
- 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 :
280
-
281
- - Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
282
- - Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
283
- - Une interprétation compréhensible par un public non-expert, mais avec une rigueur statistique.
284
-
285
- Voici les coefficients :
286
- {list_coef}
287
-
288
- Contexte :
289
- - Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des différents types de déchets en France.
290
- - Variable cible : {typologie}
291
- - Modèle utilisé : OLS de Statsmodel avec coefficients de Shapley.
292
- - Variables explicatives :
293
- - Secteurs d’activités : Nombre de salariés par secteur : Agricole, Service, Industrie.
294
- - Profils socioprofessionnels (CSP) :
295
- 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é.
296
- - Tranches d’âge : tranche_age_0-24, tranche_age_25-59, tranche_age_60+.
297
- - Autres variables :
298
- Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
299
- Valeurs historiques à n-2 pour chaque variable cible
300
- - tu ne dois pas prendre en compte les {exclude_vars} dans ton analyse
301
- """
302
-
303
- load_dotenv()
304
- api_key = os.getenv("MISTRAL_API_KEY")
305
-
306
- try:
307
- with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
308
- model_llm = ChatMistralAI(model="mistral-small-latest", mistral_api_key=api_key)
309
- parser = StrOutputParser()
310
- response = model_llm.invoke(prompt_template)
311
- explanation_text = parser.invoke(response)
312
-
313
- st.markdown("#### 🤖 Interprétation automatique (LLM)")
314
- st.success(explanation_text)
315
-
316
- except Exception as e:
317
- st.error("Erreur lors de l'appel au LLM Mistral.")
318
- st.exception(e)
 
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
 
 
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
 
 
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:
 
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)
196
+ else:
197
+ sel_norm = _norm(selected_dept)
198
+ mask = (observed_df[DEPT_COL].astype(str).map(_norm) == sel_norm) & \
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 ""
206
+
207
+ if not filtered.empty and target_col:
208
+ valeurs_observees.append(get_numeric_value(filtered[target_col].iloc[:1]))
209
+ else:
210
+ valeurs_observees.append(0.0)
211
+
212
  except Exception as e:
213
  st.error(f"Erreur avec le modèle {typologie}")
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
 
240
  st.pyplot(fig)
241
 
242
  st.markdown("---")