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