cheikhaidev-ui Claude Sonnet 4.6 commited on
Commit
a937dc4
·
1 Parent(s): 2eff224

refactor: centralize risk thresholds, floor and slider config in config.py

Browse files

- Add RISK_THRESHOLDS, RISK_FLOOR, SLIDER_CONFIG to src/config.py
- Update classify_risk() to use RISK_THRESHOLDS
- Replace all hardcoded 40/70 thresholds and 5.0 floor in utils_simple.py
- Replace hardcoded slider ranges in app.py with SLIDER_CONFIG
- Fix peak hour help text: 18-22h → 7-9h et 18-21h

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

src/config.py CHANGED
@@ -55,11 +55,21 @@ QUARTIER_ADJUSTMENT = {
55
  'Fann': 0.95 # ATTENTION : absent des données d'entraînement
56
  }
57
 
 
 
 
58
  def classify_risk(score: float) -> str:
59
- if score < 40: return "FAIBLE"
60
- elif score < 70: return "MOYEN"
61
  return "ÉLEVÉ"
62
 
 
 
 
 
 
 
 
63
  # ============================================================================
64
  # CONFIGURATION MODÈLES ML
65
  # ============================================================================
 
55
  'Fann': 0.95 # ATTENTION : absent des données d'entraînement
56
  }
57
 
58
+ RISK_THRESHOLDS = {'faible': 40, 'eleve': 70}
59
+ RISK_FLOOR = 5.0
60
+
61
  def classify_risk(score: float) -> str:
62
+ if score < RISK_THRESHOLDS['faible']: return "FAIBLE"
63
+ elif score < RISK_THRESHOLDS['eleve']: return "MOYEN"
64
  return "ÉLEVÉ"
65
 
66
+ SLIDER_CONFIG = {
67
+ 'temperature': {'min': 15.0, 'max': 45.0, 'default': 25.0, 'step': 0.5},
68
+ 'humidite': {'min': 30.0, 'max': 100.0, 'default': 65.0, 'step': 1.0},
69
+ 'vitesse_vent': {'min': 0.0, 'max': 50.0, 'default': 15.0, 'step': 1.0},
70
+ 'consommation': {'min': 400.0, 'max': 1500.0, 'default': 800.0, 'step': 10.0},
71
+ }
72
+
73
  # ============================================================================
74
  # CONFIGURATION MODÈLES ML
75
  # ============================================================================
streamlit_app/app.py CHANGED
@@ -23,7 +23,7 @@ from streamlit_app.utils_simple import (
23
  create_temporal_chart,
24
  create_risk_trend_chart,
25
  )
26
- from src.config import QUARTIERS_DAKAR, classify_risk
27
  from src.weather_api import get_current_weather_dakar, get_weather_forecast_7days
28
 
29
  st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
@@ -69,15 +69,16 @@ if st.sidebar.button("🌤️ Météo actuelle Dakar", use_container_width=True)
69
  if 'wx_time' in st.session_state:
70
  st.sidebar.caption(f"⏱️ Données météo en temps réel — {st.session_state['wx_time']}")
71
 
72
- temperature = st.sidebar.slider("Température (°C)", 15.0, 45.0, 25.0, 0.5, key='s_temp')
73
- humidite = st.sidebar.slider("Humidité (%)", 30.0, 100.0, 65.0, 1.0, key='s_hum')
74
- vitesse_vent = st.sidebar.slider("Vent (km/h)", 0.0, 50.0, 15.0, 1.0, key='s_wind')
75
- consommation = st.sidebar.slider("Consommation (MW)", 400.0, 1500.0, 800.0, 10.0)
 
76
  heure_pred = st.sidebar.slider(
77
  "🕐 Heure de prédiction", 0, 23,
78
  datetime.now().hour, 1,
79
  key='s_hour',
80
- help="Changer l'heure affecte is_peak_hour (pic 18-22h)",
81
  )
82
  quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
83
 
@@ -145,9 +146,9 @@ with tab1:
145
  with col3:
146
  st.metric("⚠️ NIVEAU", niveau)
147
 
148
- if risque < 40:
149
  st.success(f"✅ Risque {niveau} ({risque:.0f}%)")
150
- elif risque < 70:
151
  st.warning(f"⚠️ Risque {niveau} ({risque:.0f}%)")
152
  else:
153
  st.error(f"🚨 Risque {niveau} ({risque:.0f}%)")
 
23
  create_temporal_chart,
24
  create_risk_trend_chart,
25
  )
26
+ from src.config import QUARTIERS_DAKAR, classify_risk, RISK_THRESHOLDS, SLIDER_CONFIG
27
  from src.weather_api import get_current_weather_dakar, get_weather_forecast_7days
28
 
29
  st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
 
69
  if 'wx_time' in st.session_state:
70
  st.sidebar.caption(f"⏱️ Données météo en temps réel — {st.session_state['wx_time']}")
71
 
72
+ _sc = SLIDER_CONFIG
73
+ temperature = st.sidebar.slider("Température (°C)", _sc['temperature']['min'], _sc['temperature']['max'], _sc['temperature']['default'], _sc['temperature']['step'], key='s_temp')
74
+ humidite = st.sidebar.slider("Humidité (%)", _sc['humidite']['min'], _sc['humidite']['max'], _sc['humidite']['default'], _sc['humidite']['step'], key='s_hum')
75
+ vitesse_vent = st.sidebar.slider("Vent (km/h)", _sc['vitesse_vent']['min'], _sc['vitesse_vent']['max'], _sc['vitesse_vent']['default'], _sc['vitesse_vent']['step'], key='s_wind')
76
+ consommation = st.sidebar.slider("Consommation (MW)", _sc['consommation']['min'], _sc['consommation']['max'], _sc['consommation']['default'], _sc['consommation']['step'])
77
  heure_pred = st.sidebar.slider(
78
  "🕐 Heure de prédiction", 0, 23,
79
  datetime.now().hour, 1,
80
  key='s_hour',
81
+ help="Changer l'heure affecte is_peak_hour (pic 7-9h et 18-21h)",
82
  )
83
  quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
84
 
 
146
  with col3:
147
  st.metric("⚠️ NIVEAU", niveau)
148
 
149
+ if risque < RISK_THRESHOLDS['faible']:
150
  st.success(f"✅ Risque {niveau} ({risque:.0f}%)")
151
+ elif risque < RISK_THRESHOLDS['eleve']:
152
  st.warning(f"⚠️ Risque {niveau} ({risque:.0f}%)")
153
  else:
154
  st.error(f"🚨 Risque {niveau} ({risque:.0f}%)")
streamlit_app/utils_simple.py CHANGED
@@ -21,7 +21,8 @@ except ImportError:
21
  warnings.filterwarnings('ignore', category=UserWarning, module='keras')
22
  warnings.filterwarnings('ignore', category=UserWarning, module='lightgbm')
23
 
24
- from src.config import QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT, classify_risk
 
25
 
26
  logger = logging.getLogger(__name__)
27
 
@@ -98,7 +99,7 @@ def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_f
98
  pred_lstm = pred_lgb
99
  risque_base = (pred_lgb + pred_lstm) / 2
100
  adjustment = QUARTIER_ADJUSTMENT.get(quartier, 1.0)
101
- risque_ajuste = max(5.0, risque_base * adjustment)
102
  pred_lgb = np.clip(pred_lgb, 0, 100)
103
  pred_lstm = np.clip(pred_lstm, 0, 100)
104
  risque_ajuste = np.clip(risque_ajuste, 0, 100)
@@ -130,15 +131,15 @@ def compute_map_risks(models, temperature, humidite, vitesse_vent, consommation,
130
  return [
131
  {
132
  'Quartier': q,
133
- 'Risque': float(np.clip(max(5.0, risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0)), 0, 100)),
134
  }
135
  for i, q in enumerate(QUARTIERS_DAKAR)
136
  ]
137
 
138
  def get_risk_color(risque_pct):
139
- if risque_pct < 40:
140
  return "#2ecc71"
141
- elif risque_pct < 70:
142
  return "#f39c12"
143
  else:
144
  return "#e74c3c"
 
21
  warnings.filterwarnings('ignore', category=UserWarning, module='keras')
22
  warnings.filterwarnings('ignore', category=UserWarning, module='lightgbm')
23
 
24
+ from src.config import (QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT,
25
+ classify_risk, RISK_THRESHOLDS, RISK_FLOOR)
26
 
27
  logger = logging.getLogger(__name__)
28
 
 
99
  pred_lstm = pred_lgb
100
  risque_base = (pred_lgb + pred_lstm) / 2
101
  adjustment = QUARTIER_ADJUSTMENT.get(quartier, 1.0)
102
+ risque_ajuste = max(RISK_FLOOR, risque_base * adjustment)
103
  pred_lgb = np.clip(pred_lgb, 0, 100)
104
  pred_lstm = np.clip(pred_lstm, 0, 100)
105
  risque_ajuste = np.clip(risque_ajuste, 0, 100)
 
131
  return [
132
  {
133
  'Quartier': q,
134
+ 'Risque': float(np.clip(max(RISK_FLOOR, risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0)), 0, 100)),
135
  }
136
  for i, q in enumerate(QUARTIERS_DAKAR)
137
  ]
138
 
139
  def get_risk_color(risque_pct):
140
+ if risque_pct < RISK_THRESHOLDS['faible']:
141
  return "#2ecc71"
142
+ elif risque_pct < RISK_THRESHOLDS['eleve']:
143
  return "#f39c12"
144
  else:
145
  return "#e74c3c"