PoroKami commited on
Commit
6cc8cd3
·
1 Parent(s): 882b86a

normalement c'est bon pitié

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. src/app.py +23 -14
  3. src/app_llm.py +0 -310
Dockerfile CHANGED
@@ -18,4 +18,4 @@ EXPOSE 8501
18
 
19
  HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
20
 
21
- ENTRYPOINT ["streamlit", "run", "src/app_llm.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
18
 
19
  HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
20
 
21
+ ENTRYPOINT ["streamlit", "run", "src/app.py", "--server.port=8501", "--server.address=0.0.0.0"]
src/app.py CHANGED
@@ -209,27 +209,35 @@ try:
209
 
210
 
211
  # === Première ligne : Waterfall + Beeswarm + Moyenne des contributions
212
- col1, col2, col3 = st.columns(3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
  with col1:
215
  st.markdown("<h6 style='text-align: center;'>🩜 Waterfall</h6>", unsafe_allow_html=True)
216
  fig = plt.figure(figsize=(3, 2))
217
- shap.plots.waterfall(shap_values[selected_index], max_display=10, show=False)
218
- st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
219
-
220
- with col2:
221
- st.markdown("<h6 style='text-align: center;'>🐝 Beeswarm</h6>", unsafe_allow_html=True)
222
- fig = plt.figure(figsize=(3, 2))
223
- shap.plots.beeswarm(shap_values, max_display=15, show=False)
224
  st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
225
 
 
226
 
227
- with col3:
228
- st.markdown("<h6 style='text-align: center;'>📊 Moyenne des contributions</h6>", unsafe_allow_html=True)
229
- fig = plt.figure(figsize=(3, 2))
230
- shap.plots.bar(shap_values, max_display=15, show=False)
231
- st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
232
 
 
233
  except Exception as e:
234
  st.error(f"Erreur dans le SHAP pour {typologie}")
235
  st.exception(e)
@@ -257,7 +265,7 @@ Tu es un expert en data science et en statistique, spécialisé dans l'interpré
257
  Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
258
 
259
  Ta mission :
260
- 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 mais tu ne dois pas prendre en compte pour ton explication. Tu dois identifier :
261
 
262
  - Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
263
  - Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
@@ -278,6 +286,7 @@ Contexte :
278
  - Autres variables :
279
  Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
280
  Valeurs historiques à n-2 pour chaque variable cible
 
281
  """
282
 
283
  # 4. Appel à l’API Mistral
 
209
 
210
 
211
  # === Première ligne : Waterfall + Beeswarm + Moyenne des contributions
212
+ exclude_vars = [
213
+ "tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
214
+ "Total_autres_dechets_n-2", "Total_autres_dechets",
215
+ "Déblais_gravats_n-2", "Déblais_gravats",
216
+ "Déchets_verts_n-2", "Déchets_verts",
217
+ "Encombrants_n-2", "Encombrants",
218
+ "Matériaux_recyclables_n-2", "Matériaux_recyclables"
219
+ ]
220
+ # Création d’un masque pour filtrer les SHAP plots sans toucher à la prédiction
221
+ mask = np.array([name not in exclude_vars for name in shap_values.feature_names])
222
+ filtered_shap = shap.Explanation(
223
+ values=shap_values.values[:, mask],
224
+ base_values=shap_values.base_values,
225
+ data=shap_values.data[:, mask],
226
+ feature_names=[name for name in shap_values.feature_names if name not in exclude_vars]
227
+ )
228
+
229
+ col1 = st.columns(1)[0]
230
 
231
  with col1:
232
  st.markdown("<h6 style='text-align: center;'>🩜 Waterfall</h6>", unsafe_allow_html=True)
233
  fig = plt.figure(figsize=(3, 2))
234
+ shap.plots.waterfall(filtered_shap[selected_index], max_display=10, show=False)
 
 
 
 
 
 
235
  st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
236
 
237
+
238
 
 
 
 
 
 
239
 
240
+
241
  except Exception as e:
242
  st.error(f"Erreur dans le SHAP pour {typologie}")
243
  st.exception(e)
 
265
  Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
266
 
267
  Ta mission :
268
+ 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 :
269
 
270
  - Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
271
  - Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
 
286
  - Autres variables :
287
  Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
288
  Valeurs historiques à n-2 pour chaque variable cible
289
+ - tu ne dois pas prendre en compte les {exclude_vars} dans ton analyse
290
  """
291
 
292
  # 4. Appel à l’API Mistral
src/app_llm.py DELETED
@@ -1,310 +0,0 @@
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
-
8
- import numpy as np
9
- import shap
10
- from sklearn.linear_model import LinearRegression
11
- from langchain_mistralai import ChatMistralAI
12
- from langchain_core.output_parsers import StrOutputParser
13
-
14
- # === Chargement des données
15
- df = pd.read_csv("https://geodechet.s3.eu-west-3.amazonaws.com/v1/dataset/df_dummies.csv").drop(columns=["Unnamed: 0"], errors="ignore")
16
- observed_df = pd.read_excel("https://geodechet.s3.eu-west-3.amazonaws.com/v1/dataset/data_wip_v5.xlsx")
17
-
18
- # === Liste des départements
19
- departements = [col.replace("Département_", "") for col in df.columns if col.startswith("Département_")]
20
-
21
- # === Mise en page
22
- st.set_page_config(layout="wide")
23
- st.markdown("<h1 style='text-align: center;'>♻️ Simulateur de production de déchets par département</h1>", unsafe_allow_html=True)
24
-
25
- # === Titre + Choix département alignés
26
- top_col1, top_col2 = st.columns([1, 2])
27
- with top_col1:
28
- st.markdown("<h3 style='text-align: center;'>📍 Choix du département</h3>", unsafe_allow_html=True)
29
- with top_col2:
30
- st.markdown("<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>", unsafe_allow_html=True)
31
-
32
- # === Séparation en colonnes
33
- top_input_col, chart_col = st.columns([1, 2])
34
-
35
- with top_input_col:
36
- selected_dept = st.selectbox("Sélectionner un département", sorted(departements), index=sorted(departements).index("Ain") if "Ain" in departements else 0)
37
- row_default = df[df[f"Département_{selected_dept}"] == 1].iloc[0]
38
- default_dict = row_default.to_dict()
39
-
40
- st.subheader("⚙️ Paramètres modifiables")
41
- form_input = {}
42
-
43
- categories = {
44
- "📊 Population": [
45
- "densité_n-2", "densité", "pop_globale_n-2", "pop_globale",
46
- "tranche_age_0-24", "tranche_age_25-59", "tranche_age_60+",
47
- "csp1_agriculteurs", "csp2_artisans_commerçant_chef_entreprises",
48
- "csp3_cadres_professions_intellectuelles", "csp4_professions_intermédiaires",
49
- "csp5_employés", "csp6_ouvriers", "csp7_retraités", "csp8_sans_activité"
50
- ],
51
- "🏭 Activité économique": [
52
- "nb_salaries_secteur_agricole", "nb_salaries_secteur_industrie", "nb_salaries_secteur_service",
53
- "nbre_entreprises", "nbre_entreprises_agricole", "nbre_entreprises_industrie", "nbre_entreprises_service"
54
- ],
55
- "🗑️ Déchets": [
56
- "tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
57
- "Total_autres_dechets_n-2", "Total_autres_dechets",
58
- "Déblais_gravats_n-2", "Déblais_gravats",
59
- "Déchets_verts_n-2", "Déchets_verts",
60
- "Encombrants_n-2", "Encombrants",
61
- "Matériaux_recyclables_n-2", "Matériaux_recyclables"
62
- ]
63
- }
64
-
65
- for category_name, variables in categories.items():
66
- with st.expander(category_name, expanded=True):
67
- for var in variables:
68
- if var in default_dict:
69
- col_slider, col_input = st.columns([2, 1])
70
- with col_slider:
71
- slider_value = st.slider(
72
- f"🔧 {var}",
73
- min_value=float(default_dict[var]) * 0,
74
- max_value=float(default_dict[var]) * 1.5,
75
- value=float(default_dict[var]),
76
- step=1.0,
77
- key=f"slider_{var}"
78
- )
79
- with col_input:
80
- text_val = st.text_input(f"{var} (manuel)", value=str(slider_value), key=f"text_{var}")
81
- try:
82
- form_input[var] = float(text_val)
83
- except ValueError:
84
- form_input[var] = slider_value
85
-
86
- input_df = pd.DataFrame([form_input])
87
- input_df_complete = row_default.to_frame().T.copy()
88
- for col in input_df.columns:
89
- if col in input_df_complete.columns:
90
- input_df_complete.at[input_df_complete.index[0], col] = input_df.at[0, col]
91
-
92
- with chart_col:
93
- st.markdown("<div style='margin-top: 30px;'></div>", unsafe_allow_html=True)
94
-
95
- btn_col = st.columns([3, 2, 3])[1]
96
- with btn_col:
97
- run_eval = st.button("🔍 Lancer l'évaluation")
98
-
99
- st.markdown("<div style='margin-top: 40px;'></div>", unsafe_allow_html=True)
100
-
101
- model_paths = {
102
- "Déblais et Gravats": "src/model_paths/Déblais_gravats.pkl",
103
- "Déchets verts": "src/model_paths/Déchets_verts.pkl",
104
- "Encombrants": "src/model_paths/Encombrants.pkl",
105
- "Matériaux recyclables": "src/model_paths/Matériaux_recyclables.pkl",
106
- "Total autres déchets": "src/model_paths/Total_autres_dechets.pkl"
107
- }
108
-
109
- col_mapping = {
110
- "Déblais et Gravats": "Déblais_gravats",
111
- "Déchets verts": "Déchets_verts",
112
- "Encombrants": "Encombrants",
113
- "Matériaux recyclables": "Matériaux_recyclables",
114
- "Total autres déchets": "Total_autres_dechets"
115
- }
116
-
117
- valeurs_observees = []
118
- valeurs_predites = []
119
- labels = []
120
-
121
- if run_eval:
122
- for typologie, path in model_paths.items():
123
- try:
124
- with open(path, "rb") as f:
125
- model = pickle.load(f)
126
-
127
- expected_cols = model.model.exog_names
128
- if "const" in expected_cols and "const" not in input_df_complete.columns:
129
- input_df_complete["const"] = 1.0
130
-
131
- prediction = max(0, model.predict(input_df_complete[expected_cols]).iloc[0])
132
- valeurs_predites.append(prediction)
133
- labels.append(typologie)
134
-
135
- filtered = observed_df[
136
- (observed_df["Département"] == selected_dept) & (observed_df["année"] == 2019)
137
- ]
138
-
139
- excel_col = col_mapping.get(typologie)
140
- if not filtered.empty and excel_col in filtered.columns:
141
- valeurs_observees.append(filtered[excel_col].values[0])
142
- else:
143
- valeurs_observees.append(0.0)
144
- except Exception as e:
145
- st.error(f"Erreur avec le modèle {typologie}")
146
- st.exception(e)
147
-
148
- if valeurs_observees and valeurs_predites:
149
- x = np.arange(len(labels))
150
- width = 0.4
151
- fig, ax = plt.subplots(figsize=(10, 6))
152
-
153
- bars1 = ax.bar(x - width / 2, valeurs_observees, width, label='Observé (2019)', color='steelblue')
154
- bar_colors = [(1, 0, 0, 0.6) if pred > obs else (0, 0.6, 0, 0.6)
155
- for pred, obs in zip(valeurs_predites, valeurs_observees)]
156
- bars2 = ax.bar(x + width / 2, valeurs_predites, width, label='Prévision', color=bar_colors)
157
-
158
- for i in range(len(labels)):
159
- ax.text(x[i] - width / 2, valeurs_observees[i] + max(valeurs_observees) * 0.01, f"{valeurs_observees[i]:,.0f}",
160
- ha='center', va='bottom', fontsize=9)
161
- ax.text(x[i] + width / 2, valeurs_predites[i] + max(valeurs_predites) * 0.01, f"{valeurs_predites[i]:,.0f}",
162
- ha='center', va='bottom', fontsize=9)
163
-
164
- ax.set_ylabel("Tonnes")
165
- ax.set_title("Comparaison Observé vs Prédit")
166
- ax.set_xticks(x)
167
- ax.set_xticklabels(labels, rotation=45, ha='right')
168
- ax.legend()
169
- st.pyplot(fig)
170
-
171
- # === Graphiques SHAP ===
172
- st.markdown("---")
173
- st.subheader(f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}")
174
-
175
- # Menu déroulant
176
- selected_typologie = st.selectbox("Choisissez une typologie de déchets à analyser avec SHAP :", list(model_paths.keys()))
177
-
178
- # SHAP pour la typologie sélectionnée
179
- typologie = selected_typologie
180
- path = model_paths[typologie]
181
-
182
- st.markdown(f"### 🔍 {typologie}")
183
-
184
- try:
185
- with open(path, "rb") as f:
186
- model_sm = pickle.load(f)
187
-
188
- used_features = model_sm.model.exog_names
189
- used_features_no_const = [f for f in used_features if f != "const"]
190
- X_used = df[used_features_no_const].copy()
191
-
192
- if "const" in used_features:
193
- X_used["const"] = 1.0
194
-
195
- intercept = model_sm.params['const'] if 'const' in model_sm.params else 0
196
- coefs = model_sm.params[used_features_no_const].values
197
-
198
- lr = LinearRegression()
199
- lr.intercept_ = intercept
200
- lr.coef_ = coefs
201
- lr.feature_names_in_ = np.array(used_features_no_const)
202
-
203
- X_used_corrected = X_used.reindex(columns=lr.feature_names_in_, fill_value=0)
204
-
205
- explainer = shap.Explainer(lr, X_used_corrected)
206
- shap_values = explainer(X_used_corrected)
207
-
208
- selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]
209
-
210
-
211
- # === Première ligne : Waterfall + Beeswarm + Moyenne des contributions
212
- exclude_vars = [
213
- "tonnage_dechet_produit_n-2", "tonnage_dechet_produit",
214
- "Total_autres_dechets_n-2", "Total_autres_dechets",
215
- "Déblais_gravats_n-2", "Déblais_gravats",
216
- "Déchets_verts_n-2", "Déchets_verts",
217
- "Encombrants_n-2", "Encombrants",
218
- "Matériaux_recyclables_n-2", "Matériaux_recyclables"
219
- ]
220
- # Création d’un masque pour filtrer les SHAP plots sans toucher à la prédiction
221
- mask = np.array([name not in exclude_vars for name in shap_values.feature_names])
222
- filtered_shap = shap.Explanation(
223
- values=shap_values.values[:, mask],
224
- base_values=shap_values.base_values,
225
- data=shap_values.data[:, mask],
226
- feature_names=[name for name in shap_values.feature_names if name not in exclude_vars]
227
- )
228
-
229
- col1 = st.columns(1)[0]
230
-
231
- with col1:
232
- st.markdown("<h6 style='text-align: center;'>🩜 Waterfall</h6>", unsafe_allow_html=True)
233
- fig = plt.figure(figsize=(3, 2))
234
- shap.plots.waterfall(filtered_shap[selected_index], max_display=10, show=False)
235
- st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
236
-
237
-
238
-
239
-
240
-
241
- except Exception as e:
242
- st.error(f"Erreur dans le SHAP pour {typologie}")
243
- st.exception(e)
244
-
245
- # === 🧠 Explication automatique avec Mistral ===
246
-
247
-
248
-
249
- # 1. Récupération des moyennes absolues des SHAP values
250
- mean_shap_values = shap_values.abs.mean(0).values
251
- feature_names = lr.feature_names_in_
252
-
253
- # 2. Création d’un résumé lisible des coefficients (triés par impact)
254
- sorted_indices = mean_shap_values.argsort()[::-1]
255
- top_n = 10 # on peut ajuster ce nombre
256
- list_coef = "\n".join([
257
- f"{feature_names[i]}: {mean_shap_values[i]:.4f}"
258
- for i in sorted_indices[:top_n]
259
- ])
260
-
261
- # 3. Prompt + contexte
262
- prompt_template = f"""
263
- 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.
264
-
265
- Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
266
-
267
- Ta mission :
268
- 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 :
269
-
270
- - Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
271
- - Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
272
- - Une interprétation compréhensible par un public non-expert, mais avec une rigueur statistique.
273
-
274
- Voici les coefficients :
275
- {list_coef}
276
-
277
- Contexte :
278
- - Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des différents types de déchets en France.
279
- - Variable cible : {typologie}
280
- - Modèle utilisé : OLS de Statsmodel avec coefficients de Shapley.
281
- - Variables explicatives :
282
- - Secteurs d’activités : Nombre de salariés par secteur : Agricole, Service, Industrie.
283
- - Profils socioprofessionnels (CSP) :
284
- 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é.
285
- - Tranches d’âge : tranche_age_0-24, tranche_age_25-59, tranche_age_60+.
286
- - Autres variables :
287
- Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
288
- Valeurs historiques à n-2 pour chaque variable cible
289
- - tu ne dois pas prendre en compte les {exclude_vars} dans ton analyse
290
- """
291
-
292
- # 4. Appel à l’API Mistral
293
- # Charge les variables d'environnement à partir du fichier .env
294
- load_dotenv()
295
- api_key = os.getenv("MISTRAL_API_KEY")
296
-
297
- try:
298
- with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
299
- model_llm = ChatMistralAI(model="mistral-large-latest", mistral_api_key=api_key)
300
- parser = StrOutputParser()
301
- response = model_llm.invoke(prompt_template)
302
- explanation_text = parser.invoke(response)
303
-
304
- # 5. Affichage dans l’interface Streamlit
305
- st.markdown("#### 🤖 Interprétation automatique (LLM)")
306
- st.success(explanation_text)
307
-
308
- except Exception as e:
309
- st.error("Erreur lors de l'appel au LLM Mistral.")
310
- st.exception(e)