PoroKami commited on
Commit
652cb28
·
1 Parent(s): 3f683bb

chgt graph

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. src/app_corrected.py +328 -0
  3. src/app_test.py +50 -46
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_corrected_shap.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_corrected.py", "--server.port=8501", "--server.address=0.0.0.0"]
src/app_corrected.py ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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
32
+ top_col1, top_col2 = st.columns([1, 2])
33
+ with top_col1:
34
+ st.markdown("<h3 style='text-align: center;'>📍 Choix du département</h3>", unsafe_allow_html=True)
35
+ with top_col2:
36
+ st.markdown("<h3 style='text-align: center;'>📈 Comparaison entre valeurs observées et prédites</h3>", unsafe_allow_html=True)
37
+
38
+ # === Séparation en colonnes
39
+ top_input_col, chart_col = st.columns([1, 2])
40
+
41
+ with top_input_col:
42
+ selected_dept = st.selectbox("Sélectionner un département", sorted(departements), index=sorted(departements).index("Ain") if "Ain" in departements else 0)
43
+ row_default = df[df[f"Département_{selected_dept}"] == 1].iloc[0]
44
+ default_dict = row_default.to_dict()
45
+
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()
97
+ for col in input_df.columns:
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
+
105
+ btn_col = st.columns([3, 2, 3])[1]
106
+ with btn_col:
107
+ run_eval = st.button("🔍 Lancer l'évaluation")
108
+
109
+ st.markdown("<div style='margin-top: 40px;'></div>", unsafe_allow_html=True)
110
+
111
+ model_paths = {
112
+ "Déblais et Gravats": "src/model_paths/Déblais_gravats.pkl",
113
+ "Déchets verts": "src/model_paths/Déchets_verts.pkl",
114
+ "Encombrants": "src/model_paths/Encombrants.pkl",
115
+ "Matériaux recyclables": "src/model_paths/Matériaux_recyclables.pkl",
116
+ "Total autres déchets": "src/model_paths/Total_autres_dechets.pkl"
117
+ }
118
+
119
+ col_mapping = {
120
+ "Déblais et Gravats": "Déblais_gravats",
121
+ "Déchets verts": "Déchets_verts",
122
+ "Encombrants": "Encombrants",
123
+ "Matériaux recyclables": "Matériaux_recyclables",
124
+ "Total autres déchets": "Total_autres_dechets"
125
+ }
126
+
127
+ valeurs_observees = []
128
+ valeurs_predites = []
129
+ labels = []
130
+
131
+ if run_eval:
132
+ for typologie, path in model_paths.items():
133
+ try:
134
+ with open(path, "rb") as f:
135
+ model = pickle.load(f)
136
+
137
+ expected_cols = model.model.exog_names
138
+ if "const" in expected_cols and "const" not in input_df_complete.columns:
139
+ input_df_complete["const"] = 1.0
140
+
141
+ prediction = max(0, model.predict(input_df_complete[expected_cols]).iloc[0])
142
+ valeurs_predites.append(prediction)
143
+ labels.append(typologie)
144
+
145
+ filtered = observed_df[
146
+ (observed_df["Département"] == selected_dept) & (observed_df["année"] == 2019)
147
+ ]
148
+
149
+ excel_col = col_mapping.get(typologie)
150
+ if not filtered.empty and excel_col in filtered.columns:
151
+ valeurs_observees.append(filtered[excel_col].values[0])
152
+ else:
153
+ valeurs_observees.append(0.0)
154
+ except Exception as e:
155
+ st.error(f"Erreur avec le modèle {typologie}")
156
+ st.exception(e)
157
+
158
+ if valeurs_observees and valeurs_predites:
159
+ x = np.arange(len(labels))
160
+ width = 0.4
161
+ fig, ax = plt.subplots(figsize=(10, 6))
162
+
163
+ bars1 = ax.bar(x - width / 2, valeurs_observees, width, label='Observé (2019)', color='steelblue')
164
+ bar_colors = [(1, 0, 0, 0.6) if pred > obs else (0, 0.6, 0, 0.6)
165
+ for pred, obs in zip(valeurs_predites, valeurs_observees)]
166
+ bars2 = ax.bar(x + width / 2, valeurs_predites, width, label='Prévision', color=bar_colors)
167
+
168
+ for i in range(len(labels)):
169
+ ax.text(x[i] - width / 2, valeurs_observees[i] + max(valeurs_observees) * 0.01, f"{valeurs_observees[i]:,.0f}",
170
+ ha='center', va='bottom', fontsize=9)
171
+ ax.text(x[i] + width / 2, valeurs_predites[i] + max(valeurs_predites) * 0.01, f"{valeurs_predites[i]:,.0f}",
172
+ ha='center', va='bottom', fontsize=9)
173
+
174
+ ax.set_ylabel("Tonnes")
175
+ ax.set_title("Comparaison Observé vs Prédit")
176
+ ax.set_xticks(x)
177
+ ax.set_xticklabels(labels, rotation=45, ha='right')
178
+ ax.legend()
179
+ st.pyplot(fig)
180
+
181
+ # Graphique SHAP Waterfall déplacé ici
182
+ with col1:
183
+ st.markdown("<h6 style='text-align: center;'>🩜 Waterfall</h6>", unsafe_allow_html=True)
184
+ fig = plt.figure(figsize=(3, 2))
185
+ shap.plots.waterfall(shap_values[selected_index], max_display=10, show=False)
186
+ st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
187
+
188
+ # === Graphiques SHAP ===
189
+ st.markdown("---")
190
+ st.subheader(f"📉 SHAP - Analyse des contributions pour le département : {selected_dept}")
191
+
192
+ # Menu déroulant
193
+ selected_typologie = st.selectbox("Choisissez une typologie de déchets à analyser avec SHAP :", list(model_paths.keys()))
194
+
195
+ # SHAP pour la typologie sélectionnée
196
+ typologie = selected_typologie
197
+ path = model_paths[typologie]
198
+
199
+ st.markdown(f"### 🔍 {typologie}")
200
+
201
+ try:
202
+ with open(path, "rb") as f:
203
+ model_sm = pickle.load(f)
204
+
205
+ used_features = model_sm.model.exog_names
206
+ used_features_no_const = [f for f in used_features if f != "const"]
207
+
208
+ # Liste des colonnes cibles à exclure de l'analyse SHAP
209
+ excluded_targets = [
210
+ "tonnage_dechet_produit", "tonnage_dechet_produit_n-2",
211
+ "Déchets_verts", "Déchets_verts_n-2",
212
+ "Déblais_gravats", "Déblais_gravats_n-2",
213
+ "Encombrants", "Encombrants_n-2",
214
+ "Matériaux_recyclables", "Matériaux_recyclables_n-2",
215
+ "Total_autres_dechets", "Total_autres_dechets_n-2"
216
+ ]
217
+
218
+ # Filtrage des variables cibles
219
+ used_features_no_const = [f for f in used_features_no_const if f not in excluded_targets]
220
+
221
+ X_used = df[used_features_no_const].copy()
222
+
223
+ if "const" in used_features:
224
+ X_used["const"] = 1.0
225
+
226
+ intercept = model_sm.params['const'] if 'const' in model_sm.params else 0
227
+ coefs = model_sm.params[used_features_no_const].values
228
+
229
+ lr = LinearRegression()
230
+ lr.intercept_ = intercept
231
+ lr.coef_ = coefs
232
+ lr.feature_names_in_ = np.array(used_features_no_const)
233
+
234
+ X_used_corrected = X_used.reindex(columns=lr.feature_names_in_, fill_value=0)
235
+
236
+ explainer = shap.Explainer(lr, X_used_corrected)
237
+ shap_values = explainer(X_used_corrected)
238
+
239
+ selected_index = df[df[f"Département_{selected_dept}"] == 1].index[0]
240
+
241
+
242
+ # === Première ligne : Waterfall + Beeswarm + Moyenne des contributions
243
+ col1, col2, col3 = st.columns(3)
244
+
245
+
246
+
247
+ with col2:
248
+ st.markdown("<h6 style='text-align: center;'>📊 Analyse générale (Beeswarm)</h6>", unsafe_allow_html=True)
249
+ fig = plt.figure(figsize=(3, 2))
250
+ shap.plots.beeswarm(shap_values, max_display=15, show=False)
251
+ st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
252
+
253
+
254
+ with col3:
255
+ st.markdown("<h6 style='text-align: center;'>📊 Analyse générale (Bar plot)</h6>", unsafe_allow_html=True)
256
+ fig = plt.figure(figsize=(3, 2))
257
+ shap.plots.bar(shap_values, max_display=15, show=False)
258
+ st.pyplot(fig, bbox_inches='tight', dpi=200, clear_figure=True)
259
+
260
+ except Exception as e:
261
+ st.error(f"Erreur dans le SHAP pour {typologie}")
262
+ st.exception(e)
263
+
264
+ # === 🧠 Explication automatique avec Mistral ===
265
+
266
+
267
+
268
+ # 1. Récupération des moyennes absolues des SHAP values
269
+ mean_shap_values = shap_values.abs.mean(0).values
270
+ feature_names = lr.feature_names_in_
271
+
272
+ # 2. Création d’un résumé lisible des coefficients (triés par impact)
273
+ sorted_indices = mean_shap_values.argsort()[::-1]
274
+ top_n = 10 # on peut ajuster ce nombre
275
+ list_coef = "\n".join([
276
+ f"{feature_names[i]}: {mean_shap_values[i]:.4f}"
277
+ for i in sorted_indices[:top_n]
278
+ ])
279
+
280
+ # 3. Prompt + contexte
281
+ prompt_template = f"""
282
+ 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.
283
+
284
+ Je vais te fournir les valeurs des coefficients de Shapley pour un modèle linéaire de régression, associés à chaque variable explicative.
285
+
286
+ Ta mission :
287
+ 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 :
288
+
289
+ - Les variables qui ont le plus d’impact positif ou négatif sur la variable cible.
290
+ - Les grandes tendances démographiques ou économiques qui expliquent la production de déchets.
291
+ - Une interprétation compréhensible par un public non-expert, mais avec une rigueur statistique.
292
+
293
+ Voici les coefficients :
294
+ {list_coef}
295
+
296
+ Contexte :
297
+ - Objectif : Comprendre comment les caractéristiques démographiques et économiques influencent la production des différents types de déchets en France.
298
+ - Variable cible : {typologie}
299
+ - Modèle utilisé : OLS de Statsmodel avec coefficients de Shapley.
300
+ - Variables explicatives :
301
+ - Secteurs d’activités : Nombre de salariés par secteur : Agricole, Service, Industrie.
302
+ - Profils socioprofessionnels (CSP) :
303
+ 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é.
304
+ - Tranches d’âge : tranche_age_0-24, tranche_age_25-59, tranche_age_60+.
305
+ - Autres variables :
306
+ Nombre entreprise globale, Densité de population, Population globale, Typologie d'entreprises
307
+ Valeurs historiques à n-2 pour chaque variable cible
308
+ """
309
+
310
+ # 4. Appel à l’API Mistral
311
+ # Charge les variables d'environnement à partir du fichier .env
312
+ load_dotenv()
313
+ api_key = os.getenv("MISTRAL_API_KEY")
314
+
315
+ try:
316
+ with st.spinner("🧠 Génération de l'interprétation avec Mistral..."):
317
+ model_llm = ChatMistralAI(model="mistral-large-latest", mistral_api_key=api_key)
318
+ parser = StrOutputParser()
319
+ response = model_llm.invoke(prompt_template)
320
+ explanation_text = parser.invoke(response)
321
+
322
+ # 5. Affichage dans l’interface Streamlit
323
+ st.markdown("#### 🤖 Interprétation automatique (LLM)")
324
+ st.success(explanation_text)
325
+
326
+ except Exception as e:
327
+ st.error("Erreur lors de l'appel au LLM Mistral.")
328
+ st.exception(e)
src/app_test.py CHANGED
@@ -1,4 +1,5 @@
1
  import streamlit as st
 
2
  import pandas as pd
3
  import pickle
4
  import matplotlib.pyplot as plt
@@ -8,14 +9,14 @@ import os
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
  @st.cache_data
16
-
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",encoding="utf-8")
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
 
@@ -25,7 +26,6 @@ df, observed_df = load_data()
25
  departements = [col.replace("Département_", "") for col in df.columns if col.startswith("Département_")]
26
 
27
  # === Mise en page
28
- st.set_page_config(layout="wide")
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,48 +46,51 @@ with top_input_col:
46
  st.subheader("⚙️ Paramètres modifiables")
47
  form_input = {}
48
 
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
  input_df = pd.DataFrame([form_input])
93
  input_df_complete = row_default.to_frame().T.copy()
@@ -95,6 +98,7 @@ with top_input_col:
95
  if col in input_df_complete.columns:
96
  input_df_complete.at[input_df_complete.index[0], col] = input_df.at[0, col]
97
 
 
98
  with chart_col:
99
  st.markdown("<div style='margin-top: 30px;'></div>", unsafe_allow_html=True)
100
 
 
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
  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
 
 
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
  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
  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