Download streamlit_app/app.py from PythonMindset/dakar-power-prediction: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/spaces/PythonMindset/dakar-power-prediction/resolve/main/streamlit_app/app.py
- Command line
-
hf download hf://spaces/PythonMindset/dakar-power-prediction/streamlit_app/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PythonMindset/dakar-power-prediction/resolve/main/streamlit_app/app.py
14.9 kB
| 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', | |
| } | |
| 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)") | |