cheikhaidev-ui commited on
Commit
e49e56b
·
1 Parent(s): 472a145

fix(ux): auto map + hour slider + dark theme + data fixes

Browse files

- fix(map): remove button gate, map now auto-renders on parameter change
- fix(predictions): add hour slider (0-23) to control is_peak_hour correctly
- fix(map): carte updates dynamically with all sidebar parameters
- fix(weather): clamp precipitation to 0 (no negative values)
- fix(chart): filter empty weeks in temporal chart (conso > 100 MW)
- feat(theme): add Streamlit dark theme with red primary color

.streamlit/config.toml CHANGED
@@ -10,4 +10,11 @@ gatherUsageStats = false
10
 
11
  [client]
12
  showErrorDetails = false
13
- toolbarMode = "minimal"
 
 
 
 
 
 
 
 
10
 
11
  [client]
12
  showErrorDetails = false
13
+ toolbarMode = "minimal"
14
+
15
+ [theme]
16
+ base = "dark"
17
+ primaryColor = "#e74c3c"
18
+ backgroundColor = "#0e1117"
19
+ secondaryBackgroundColor = "#1a1f2e"
20
+ textColor = "#fafafa"
src/weather_api.py CHANGED
@@ -61,7 +61,7 @@ def get_weather_forecast_7days() -> list[dict] | None:
61
  'date': daily['time'][i],
62
  'temp_max': daily['temperature_2m_max'][i],
63
  'temp_min': daily['temperature_2m_min'][i],
64
- 'precipitation': daily['precipitation_sum'][i],
65
  'wind_max': daily['wind_speed_10m_max'][i],
66
  }
67
  for i in range(len(daily['time']))
 
61
  'date': daily['time'][i],
62
  'temp_max': daily['temperature_2m_max'][i],
63
  'temp_min': daily['temperature_2m_min'][i],
64
+ 'precipitation': max(0.0, daily['precipitation_sum'][i] or 0.0),
65
  'wind_max': daily['wind_speed_10m_max'][i],
66
  }
67
  for i in range(len(daily['time']))
streamlit_app/app.py CHANGED
@@ -71,6 +71,12 @@ temperature = st.sidebar.slider("Température (°C)", 15.0, 45.0, 25.0, 0.
71
  humidite = st.sidebar.slider("Humidité (%)", 30.0, 100.0, 65.0, 1.0, key='s_hum')
72
  vitesse_vent = st.sidebar.slider("Vent (km/h)", 0.0, 50.0, 15.0, 1.0, key='s_wind')
73
  consommation = st.sidebar.slider("Consommation (MW)", 400.0, 1500.0, 800.0, 10.0)
 
 
 
 
 
 
74
  quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
75
 
76
  if st.sidebar.button("🔮 Lancer la Prédiction", type="primary", use_container_width=True):
@@ -114,7 +120,7 @@ with tab1:
114
  st.header("🎯 Prédiction Immédiate")
115
  if st.session_state.get('run', False):
116
  params = st.session_state['params']
117
- time_features = create_time_features(params['timestamp'])
118
  result = make_prediction_single(models, params['quartier'], params['temperature'], params['humidite'], params['vitesse_vent'], params['consommation'], time_features)
119
 
120
  if result:
@@ -161,50 +167,45 @@ with tab1:
161
 
162
  with tab2:
163
  st.header("🗺️ Carte Interactive")
164
- if st.button("🔄 Calculer pour tous les quartiers"):
165
- time_features = create_time_features(datetime.now())
166
- lgb_model = models['lgb']
167
- lstm_model = models['lstm']
168
- scaler = models['scaler']
169
-
170
- results = []
171
- if lgb_model is None or scaler is None:
172
- st.error("Modèles non chargés — impossible de calculer la carte.")
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  else:
174
- # Matrice 8×9 : une ligne par quartier, mêmes features météo pour tous
175
- feature_row = [
176
- temperature, humidite, vitesse_vent, consommation,
177
- time_features['hour'], time_features['day_of_week'],
178
- time_features['month'], time_features['saison'],
179
- time_features['is_peak_hour'],
180
- ]
181
- X = np.tile(feature_row, (len(QUARTIERS_DAKAR), 1)) # (8, 9)
182
- X_scaled = scaler.transform(X) # une seule passe
183
-
184
- preds_lgb = lgb_model.predict(X_scaled) * 100 # (8,) en un appel
185
-
186
- if lstm_model is not None:
187
- X_lstm = X_scaled.reshape(len(QUARTIERS_DAKAR), 1, -1) # (8, 1, 9)
188
- preds_lstm = lstm_model.predict(X_lstm, verbose=0).flatten() * 100
189
- else:
190
- preds_lstm = preds_lgb.copy()
191
-
192
- risque_base = (preds_lgb + preds_lstm) / 2
193
-
194
- results = [
195
- {
196
- 'Quartier': q,
197
- 'Risque': float(np.clip(risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0), 0, 100)),
198
- }
199
- for i, q in enumerate(QUARTIERS_DAKAR)
200
- ]
201
- if results:
202
- fig = create_map(results)
203
- st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': True})
204
- df_res = pd.DataFrame(results).sort_values('Risque', ascending=False)
205
- df_res['Niveau'] = df_res['Risque'].apply(classify_risk)
206
- df_res['Risque'] = df_res['Risque'].apply(lambda x: f"{x:.1f}%")
207
- st.dataframe(df_res, use_container_width=True, hide_index=True)
208
 
209
  with tab3:
210
  st.header("📊 Statistiques CSV")
 
71
  humidite = st.sidebar.slider("Humidité (%)", 30.0, 100.0, 65.0, 1.0, key='s_hum')
72
  vitesse_vent = st.sidebar.slider("Vent (km/h)", 0.0, 50.0, 15.0, 1.0, key='s_wind')
73
  consommation = st.sidebar.slider("Consommation (MW)", 400.0, 1500.0, 800.0, 10.0)
74
+ heure_pred = st.sidebar.slider(
75
+ "🕐 Heure de prédiction", 0, 23,
76
+ datetime.now().hour, 1,
77
+ key='s_hour',
78
+ help="Changer l'heure affecte is_peak_hour (pic 18-22h)",
79
+ )
80
  quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
81
 
82
  if st.sidebar.button("🔮 Lancer la Prédiction", type="primary", use_container_width=True):
 
120
  st.header("🎯 Prédiction Immédiate")
121
  if st.session_state.get('run', False):
122
  params = st.session_state['params']
123
+ time_features = create_time_features(params['timestamp'], hour_override=heure_pred)
124
  result = make_prediction_single(models, params['quartier'], params['temperature'], params['humidite'], params['vitesse_vent'], params['consommation'], time_features)
125
 
126
  if result:
 
167
 
168
  with tab2:
169
  st.header("🗺️ Carte Interactive")
170
+
171
+ # Calcul automatique basé sur les paramètres actuels
172
+ time_features_map = create_time_features(datetime.now(), hour_override=heure_pred)
173
+ lgb_model = models['lgb']
174
+ lstm_model = models['lstm']
175
+ scaler = models['scaler']
176
+
177
+ if lgb_model is None or scaler is None:
178
+ st.error("Modèles non chargés — impossible de calculer la carte.")
179
+ else:
180
+ feature_row = [
181
+ temperature, humidite, vitesse_vent, consommation,
182
+ time_features_map['hour'], time_features_map['day_of_week'],
183
+ time_features_map['month'], time_features_map['saison'],
184
+ time_features_map['is_peak_hour'],
185
+ ]
186
+ X = np.tile(feature_row, (len(QUARTIERS_DAKAR), 1)) # (8, 9)
187
+ X_scaled = scaler.transform(X) # une seule passe
188
+ preds_lgb = lgb_model.predict(X_scaled) * 100 # (8,) en un appel
189
+ if lstm_model is not None:
190
+ X_lstm = X_scaled.reshape(len(QUARTIERS_DAKAR), 1, -1) # (8, 1, 9)
191
+ preds_lstm = lstm_model.predict(X_lstm, verbose=0).flatten() * 100
192
  else:
193
+ preds_lstm = preds_lgb.copy()
194
+ risque_base = (preds_lgb + preds_lstm) / 2
195
+ results = [
196
+ {
197
+ 'Quartier': q,
198
+ 'Risque': float(np.clip(risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0), 0, 100)),
199
+ }
200
+ for i, q in enumerate(QUARTIERS_DAKAR)
201
+ ]
202
+ st.session_state['map_results'] = results
203
+ fig = create_map(results)
204
+ st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': True})
205
+ df_res = pd.DataFrame(results).sort_values('Risque', ascending=False)
206
+ df_res['Niveau'] = df_res['Risque'].apply(classify_risk)
207
+ df_res['Risque'] = df_res['Risque'].apply(lambda x: f"{x:.1f}%")
208
+ st.dataframe(df_res, use_container_width=True, hide_index=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
 
210
  with tab3:
211
  st.header("📊 Statistiques CSV")
streamlit_app/utils_simple.py CHANGED
@@ -52,13 +52,20 @@ def load_models_cached():
52
  st.error(f"❌ Scaler: {e}")
53
  return models
54
 
55
- def create_time_features(date_time):
 
56
  month = date_time.month
57
  # Encodage binaire calé sur synthetic_data_v2.csv : saison pluies (Jun-Août) = 1, reste = 0
58
  saison = 1 if month in [6, 7, 8] else 0
59
  # is_peak_hour calé sur le CSV : heures 18-22 = 1 (soir uniquement)
60
- is_peak_hour = 1 if 18 <= date_time.hour <= 22 else 0
61
- return {'hour': date_time.hour, 'day_of_week': date_time.weekday(), 'month': date_time.month, 'saison': saison, 'is_peak_hour': is_peak_hour}
 
 
 
 
 
 
62
 
63
  def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_features):
64
  lgb_model = models['lgb']
@@ -209,6 +216,7 @@ def create_temporal_chart(df_hist, quartier_filter):
209
  .mean()
210
  .reset_index()
211
  )
 
212
 
213
  fig = go.Figure()
214
  if 'conso_megawatt' in df_agg.columns:
 
52
  st.error(f"❌ Scaler: {e}")
53
  return models
54
 
55
+ def create_time_features(date_time: datetime, hour_override: int = None) -> dict:
56
+ hour = hour_override if hour_override is not None else date_time.hour
57
  month = date_time.month
58
  # Encodage binaire calé sur synthetic_data_v2.csv : saison pluies (Jun-Août) = 1, reste = 0
59
  saison = 1 if month in [6, 7, 8] else 0
60
  # is_peak_hour calé sur le CSV : heures 18-22 = 1 (soir uniquement)
61
+ is_peak_hour = 1 if 18 <= hour <= 22 else 0
62
+ return {
63
+ 'hour': hour,
64
+ 'day_of_week': date_time.weekday(),
65
+ 'month': month,
66
+ 'saison': saison,
67
+ 'is_peak_hour': is_peak_hour,
68
+ }
69
 
70
  def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_features):
71
  lgb_model = models['lgb']
 
216
  .mean()
217
  .reset_index()
218
  )
219
+ df_agg = df_agg[df_agg['conso_megawatt'] > 100] # filtre semaines avec données manquantes
220
 
221
  fig = go.Figure()
222
  if 'conso_megawatt' in df_agg.columns: