File size: 14,856 Bytes
f76db68 72821ef 5cda98e 1c045e4 09a6a42 5cda98e f76db68 5cda98e f76db68 9a0b5bd f76db68 657a409 7b3e17e 4e08d2e 72821ef 82db717 72821ef f76db68 657a409 09a6a42 5cda98e 72821ef 5cda98e 09a6a42 8fd2116 09a6a42 5cda98e 09a6a42 f76db68 5cda98e d248d81 58cb03d d248d81 a937dc4 657a409 4e08d2e e49e56b 4e08d2e e49e56b 26e90d4 e49e56b 5cda98e 657a409 5cda98e 58cb03d 5cda98e 58cb03d 5cda98e 58cb03d 5cda98e 58cb03d 5cda98e e49e56b 657a409 5cda98e a408d59 5cda98e 7b3e17e 5cda98e 7b3e17e 5cda98e 72821ef fd738e7 5cda98e e49e56b 9a0b5bd 657a409 9a0b5bd e49e56b 7b3e17e e49e56b 4ccfebd 5cda98e 58cb03d 09a6a42 5cda98e 09a6a42 58cb03d 09a6a42 3e12c0f 09a6a42 5cda98e 58cb03d 5cda98e a83d1a4 5cda98e 09a6a42 82db717 09a6a42 5cda98e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | import logging
import streamlit as st
import streamlit.components.v1 as components
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime
from pathlib import Path
import sys
logger = logging.getLogger(__name__)
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from streamlit_app.utils_simple import (
load_models_cached,
create_time_features,
make_prediction_single,
compute_map_risks,
create_gauge_chart,
create_map,
create_bar_chart_quartiers,
create_temporal_chart,
create_risk_trend_chart,
check_training_range,
format_risk,
sync_conso_default,
risk_message,
create_forecast_chart,
NO_TRANSLATE_JS,
)
from src.config import QUARTIERS_DAKAR, classify_risk, RISK_THRESHOLDS, SLIDER_CONFIG, TRAINING_RANGES
from src.weather_api import get_current_weather_dakar, get_weather_forecast_7days
st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
# Empêche la traduction automatique du navigateur (voir NO_TRANSLATE_JS)
components.html(NO_TRANSLATE_JS, height=0)
# Clear old session state
if 'initialized' not in st.session_state:
for key in list(st.session_state.keys()):
del st.session_state[key]
st.session_state['initialized'] = True
models = load_models_cached()
_QUARTIER_RENAME = {
'Guediawaye': 'Guédiawaye',
'Sicap-Liberte': 'Sicap-Liberté',
'Mermoz-Sacre-Coeur': 'Mermoz-Sacré-Cœur',
}
@st.cache_data
def load_csv():
try:
df = pd.read_csv("data/synthetic/synthetic_data_v2.csv")
df['quartier'] = df['quartier'].replace(_QUARTIER_RENAME)
return df
except Exception as e:
logger.error(f"Failed to load CSV: {e}")
return None
df_hist = load_csv()
st.sidebar.title("🌡️ Paramètres")
if st.sidebar.button("🌤️ Météo actuelle Dakar", use_container_width=True):
weather = get_current_weather_dakar()
if weather:
st.session_state['s_temp'] = float(np.clip(weather['temperature'], 15.0, 45.0))
st.session_state['s_hum'] = float(np.clip(weather['humidity'], 30.0, 100.0))
st.session_state['s_wind'] = float(np.clip(weather['wind_speed'], 0.0, 50.0))
st.session_state['wx_time'] = weather['timestamp']
else:
st.sidebar.error("❌ API météo indisponible")
if 'wx_time' in st.session_state:
st.sidebar.caption(f"⏱️ Météo Open-Meteo relevée à {st.session_state['wx_time']} (seule donnée réelle de l'app)")
_sc = SLIDER_CONFIG
_tr = TRAINING_RANGES
def _range_help(key, unit):
return f"Plage vue à l'entraînement : {_tr[key][0]:g}-{_tr[key][1]:g} {unit}. Au-delà, le modèle extrapole."
temperature = st.sidebar.slider("Température (°C)", _sc['temperature']['min'], _sc['temperature']['max'], _sc['temperature']['default'], _sc['temperature']['step'], key='s_temp', help=_range_help('temperature', '°C'))
humidite = st.sidebar.slider("Humidité (%)", _sc['humidite']['min'], _sc['humidite']['max'], _sc['humidite']['default'], _sc['humidite']['step'], key='s_hum', help=_range_help('humidite', '%'))
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', help=_range_help('vitesse_vent', 'km/h'))
# Consommation par défaut selon l'heure (1 100 MW en pointe, 600 MW sinon) : initialisée au
# premier affichage, puis remise à jour quand l'heure bascule entre pointe et hors pointe.
if 's_hour' not in st.session_state:
st.session_state['s_hour'] = datetime.now().hour
sync_conso_default(st.session_state)
consommation = st.sidebar.slider(
"Consommation (MW)", min_value=_sc['consommation']['min'], max_value=_sc['consommation']['max'],
step=_sc['consommation']['step'], key='s_conso',
help=_range_help('consommation', 'MW') + " En pointe (18h-22h) : 900-1400 MW ; hors pointe : 400-900 MW. "
"Valeur par défaut ajustée à l'heure choisie.",
)
heure_pred = st.sidebar.slider(
"🕐 Heure de prédiction", 0, 23,
step=1,
key='s_hour',
help="Changer l'heure affecte is_peak_hour (pointe 18h-22h, comme dans les données d'entraînement)",
)
quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
def _warn_hors_plage(messages, consequence):
if messages:
details = "\n".join(f"- {m}" for m in messages)
st.warning(f"⚠️ **Hors plage d'entraînement** — {consequence} :\n\n{details}")
_is_peak_now = create_time_features(datetime.now(), hour_override=heure_pred)['is_peak_hour']
for _msg in check_training_range(temperature, humidite, vitesse_vent, consommation, _is_peak_now):
st.sidebar.warning(f"⚠️ {_msg}")
if st.sidebar.button("🔮 Lancer la Prédiction", type="primary", use_container_width=True):
st.session_state['run'] = True
st.session_state['params'] = {
'quartier': quartier, 'temperature': temperature, 'humidite': humidite,
'vitesse_vent': vitesse_vent, 'consommation': consommation, 'timestamp': datetime.now()
}
st.sidebar.markdown("---")
st.sidebar.header("ℹ️ À propos")
st.sidebar.info("""
**Dakar Power Prediction**
Application de prédiction des coupures d'électricité à Dakar.
**Modèles :**
- 🌳 LightGBM
- 🧠 LSTM
**Données :**
- 70 000 enregistrements **synthétiques**
- 8 quartiers
- Aucune mesure réelle du réseau
""")
st.sidebar.markdown("---")
st.sidebar.caption("⚡ Version 1.0")
st.title("⚡ Dakar Power Prediction")
st.warning("⚠️ **Données synthétiques : démonstration technique, pas des mesures du réseau SENELEC.**")
col1, col2, col3 = st.columns(3)
with col1:
st.success("✅ LightGBM" if models['lgb'] else "❌ LightGBM")
with col2:
st.success("✅ LSTM" if models['lstm'] else "⚠️ LSTM")
with col3:
st.success(f"✅ CSV ({len(df_hist):,} lignes)" if df_hist is not None else "❌ CSV")
tab1, tab2, tab3, tab4 = st.tabs(["🎯 Prédiction", "🗺️ Carte", "📊 Statistiques", "📈 Tendances"])
with tab1:
st.header("🎯 Prédiction Immédiate")
if st.session_state.get('run', False):
params = st.session_state['params']
time_features = create_time_features(params['timestamp'], hour_override=heure_pred)
_hors_plage = check_training_range(params['temperature'], params['humidite'], params['vitesse_vent'], params['consommation'], time_features['is_peak_hour'])
_warn_hors_plage(_hors_plage, "le modèle extrapole, résultat peu fiable")
result = make_prediction_single(models, params['quartier'], params['temperature'], params['humidite'], params['vitesse_vent'], params['consommation'], time_features)
if result:
pred_lgb, pred_lstm, risque = result
niveau = classify_risk(risque)
if 'predictions_history' not in st.session_state:
st.session_state['predictions_history'] = []
st.session_state['predictions_history'].append({'Date': params['timestamp'], 'Quartier': params['quartier'], 'Température': params['temperature'], 'Humidité': params['humidite'], 'Vent': params['vitesse_vent'], 'Consommation': params['consommation'], 'LightGBM': pred_lgb, 'LSTM': pred_lstm, 'Risque': risque, 'Niveau': niveau})
st.subheader(f"📍 {params['quartier']}")
fig = create_gauge_chart(risque, params['quartier'])
st.plotly_chart(fig, use_container_width=True)
col1, col2, col3 = st.columns(3)
with col1:
st.metric("🌳 LightGBM (hors quartier)", format_risk(pred_lgb))
with col2:
st.metric("🧠 LSTM (hors quartier)", format_risk(pred_lstm))
with col3:
st.metric("⚠️ NIVEAU", niveau)
_kind, _texte = risk_message(risque)
getattr(st, _kind)(_texte)
st.caption(
f"Probabilité de coupure estimée par le modèle (moyenne LightGBM/LSTM × coefficient du quartier). "
f"Niveaux : FAIBLE < {RISK_THRESHOLDS['faible']} %, MOYEN < {RISK_THRESHOLDS['eleve']} %, ÉLEVÉ au-delà. "
f"Sur le jeu de test synthétique, le taux réel de coupure est de 2,5 % / 22 % / 51,5 % dans ces trois niveaux."
)
if st.session_state.get('predictions_history'):
df_export = pd.DataFrame(st.session_state['predictions_history'])
csv = df_export.to_csv(index=False).encode('utf-8')
st.download_button("📥 Télécharger CSV", csv, f"predictions_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv", "text/csv")
st.session_state['run'] = False
else:
st.info("👈 Configurez et cliquez sur 'Lancer la Prédiction'")
col1, col2 = st.columns(2)
with col1:
st.metric("🌡️ Température", f"{temperature}°C")
st.metric("💧 Humidité", f"{humidite}%")
with col2:
st.metric("💨 Vent", f"{vitesse_vent} km/h")
st.metric("⚡ Consommation", f"{consommation} MW")
with tab2:
st.header("🗺️ Carte Interactive")
time_features_map = create_time_features(datetime.now(), hour_override=heure_pred)
results = compute_map_risks(models, temperature, humidite, vitesse_vent, consommation, time_features_map)
_hors_plage_map = check_training_range(temperature, humidite, vitesse_vent, consommation, time_features_map['is_peak_hour'])
_warn_hors_plage(_hors_plage_map, "carte peu fiable")
if results is None:
st.error("Modèles non chargés — impossible de calculer la carte.")
else:
st.session_state['map_results'] = results
fig = create_map(results)
st.plotly_chart(fig, use_container_width=True, config={'scrollZoom': True})
df_res = pd.DataFrame(results).sort_values('Risque', ascending=False)
df_res['Niveau'] = df_res['Risque'].apply(classify_risk)
df_res['Risque'] = df_res['Risque'].apply(format_risk)
st.dataframe(df_res, use_container_width=True, hide_index=True)
st.caption("ℹ️ Le quartier n'est pas une variable du modèle : le risque de base est le même partout, puis multiplié par un coefficient par quartier tiré des taux du dataset synthétique.")
with tab3:
st.header("📊 Statistiques CSV")
if df_hist is not None:
# Métriques globales du dataset synthétique
m1, m2, m3, m4 = st.columns(4)
q_max = df_hist.groupby('quartier')['coupure'].mean().idxmax()
with m1:
st.metric("🔴 Total Coupures", f"{int(df_hist['coupure'].sum()):,}")
with m2:
st.metric("⚠️ Plus à risque", q_max)
with m3:
st.metric("📊 Taux moyen", f"{df_hist['coupure'].mean()*100:.1f}%")
with m4:
st.metric("🌡️ Temp. moyenne", f"{df_hist['temp_celsius'].mean():.1f}°C")
st.markdown("---")
quartier_filter = st.selectbox("Quartier", ["Tous"] + QUARTIERS_DAKAR, index=0, key='stats_q')
df_f = df_hist if quartier_filter == "Tous" else df_hist[df_hist['quartier'] == quartier_filter]
stats = df_f.groupby('quartier').agg({'coupure': ['sum', 'count'], 'temp_celsius': 'mean', 'conso_megawatt': 'mean'}).reset_index()
stats.columns = ['quartier', 'coupures', 'total', 'temp_moy', 'conso_moy']
stats['taux_coupure'] = stats['coupures'] / stats['total']
fig = create_bar_chart_quartiers(stats)
if fig:
st.plotly_chart(fig, use_container_width=True)
st.dataframe(stats, use_container_width=True, hide_index=True)
st.info(f"📊 {len(df_f):,} enregistrements")
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
st.subheader("⏰ Risque par Heure")
by_hour = df_hist.groupby('heure')['coupure'].mean() * 100
fig_h = go.Figure()
fig_h.add_trace(go.Scatter(
x=list(range(24)),
y=by_hour.reindex(range(24), fill_value=0).values,
mode='lines+markers', fill='tozeroy',
line=dict(color='#e74c3c', width=2), marker=dict(size=5),
))
fig_h.update_layout(
xaxis_title="Heure", yaxis_title="Taux (%)",
xaxis=dict(tickmode='linear', tick0=0, dtick=3),
height=350, margin=dict(t=10),
)
st.plotly_chart(fig_h, use_container_width=True)
st.caption("ℹ️ Dataset synthétique : le pic 18-22h reflète la règle de génération des données, pas une mesure du réseau.")
with col2:
st.subheader("📅 Risque par Mois")
by_month = df_hist.groupby('mois')['coupure'].mean() * 100
month_labels = ['Jan','Fév','Mar','Avr','Mai','Juin','Juil','Aoû','Sep','Oct','Nov','Déc']
fig_m = go.Figure()
fig_m.add_trace(go.Bar(
x=month_labels,
y=by_month.reindex(range(1, 13), fill_value=0).values,
marker_color='#f39c12', opacity=0.85,
))
fig_m.update_layout(xaxis_title="Mois", yaxis_title="Taux (%)", height=350, margin=dict(t=10))
st.plotly_chart(fig_m, use_container_width=True)
st.caption("ℹ️ Dataset synthétique 2023-2024 : les pics de Déc/Fév reflètent la distribution des données d'entraînement, pas la saisonnalité réelle du réseau.")
with tab4:
st.header("📈 Tendances du dataset synthétique")
if df_hist is not None:
quartier_hist = st.selectbox("Quartier", ["Tous"] + QUARTIERS_DAKAR, index=0, key='hist_q')
col1, col2 = st.columns(2)
with col1:
st.subheader("📉 Évolution Temporelle")
fig_temp = create_temporal_chart(df_hist, quartier_hist)
if fig_temp:
st.plotly_chart(fig_temp, use_container_width=True)
with col2:
st.subheader("📊 Tendance des Risques")
fig_risk = create_risk_trend_chart(df_hist, quartier_hist)
if fig_risk:
st.plotly_chart(fig_risk, use_container_width=True)
st.caption("ℹ️ Taux moyen journalier sur 24 h. Les seuils MOYEN et ÉLEVÉ s'appliquent au risque d'une heure précise, donc une moyenne journalière atteint rarement ÉLEVÉ.")
st.markdown("---")
st.subheader("🌤️ Prévisions Météo 7 Jours")
forecast = get_weather_forecast_7days()
if forecast:
st.plotly_chart(create_forecast_chart(forecast), use_container_width=True)
else:
st.info("🌐 Prévisions indisponibles (API météo)")
|