Download streamlit_app/utils_simple.py from PythonMindset/dakar-power-prediction: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/PythonMindset/dakar-power-prediction/resolve/554fba2d19809fb2be5bcf5eabe2aaa729eb2f15/streamlit_app/utils_simple.py
- Command line
-
hf download hf://spaces/PythonMindset/dakar-power-prediction@554fba2d19809fb2be5bcf5eabe2aaa729eb2f15/streamlit_app/utils_simple.py
-
curl -L -o utils_simple.py https://huggingface.co/spaces/PythonMindset/dakar-power-prediction/resolve/554fba2d19809fb2be5bcf5eabe2aaa729eb2f15/streamlit_app/utils_simple.py
13.2 kB
| """ | |
| Fonctions utilitaires - THÈME PAR DÉFAUT STREAMLIT/PLOTLY | |
| """ | |
| import logging | |
| import warnings | |
| import pickle | |
| from datetime import datetime | |
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.graph_objects as go | |
| try: | |
| from tensorflow import keras | |
| _KERAS_AVAILABLE = True | |
| except ImportError: | |
| keras = None | |
| _KERAS_AVAILABLE = False | |
| warnings.filterwarnings('ignore', category=UserWarning, module='keras') | |
| warnings.filterwarnings('ignore', category=UserWarning, module='lightgbm') | |
| from src.config import QUARTIERS_DAKAR, COORDONNEES_QUARTIERS, QUARTIER_ADJUSTMENT, classify_risk | |
| logger = logging.getLogger(__name__) | |
| def load_models_cached(): | |
| models = {'lgb': None, 'lstm': None, 'scaler': None} | |
| try: | |
| with open('models/lgbm_model.pkl', 'rb') as f: | |
| models['lgb'] = pickle.load(f) | |
| except Exception as e: | |
| st.warning(f"⚠️ LightGBM: {e}") | |
| if not _KERAS_AVAILABLE: | |
| logger.warning("TensorFlow non disponible — LSTM désactivé, LightGBM seul utilisé.") | |
| models['lstm'] = None | |
| else: | |
| try: | |
| # Charger LSTM avec compile=False pour éviter les erreurs de compatibilité | |
| models['lstm'] = keras.models.load_model('models/lstm_model.keras', compile=False) | |
| # Compiler manuellement avec les bons paramètres | |
| models['lstm'].compile(optimizer='adam', loss='binary_crossentropy') | |
| except Exception: | |
| # Si LSTM échoue, utiliser seulement LightGBM (pas d'avertissement affiché) | |
| models['lstm'] = None | |
| try: | |
| with open('models/scaler.pkl', 'rb') as f: | |
| models['scaler'] = pickle.load(f) | |
| except Exception as e: | |
| st.error(f"❌ Scaler: {e}") | |
| return models | |
| def create_time_features(date_time: datetime, hour_override: int = None) -> dict: | |
| hour = hour_override if hour_override is not None else date_time.hour | |
| month = date_time.month | |
| # Encodage 3 saisons Dakar — doit correspondre exactement à data_generator.get_season() | |
| if month in [11, 12, 1, 2]: | |
| saison = 0 # Saison sèche fraîche | |
| elif month in [3, 4, 5]: | |
| saison = 1 # Saison sèche chaude | |
| else: | |
| saison = 2 # Saison des pluies (Jun-Oct) | |
| # Heures de pointe — doit correspondre à data_generator.is_peak_hour() | |
| is_peak_hour = 1 if (7 <= hour <= 9 or 18 <= hour <= 21) else 0 | |
| return { | |
| 'hour': hour, | |
| 'day_of_week': date_time.weekday(), | |
| 'month': month, | |
| 'saison': saison, | |
| 'is_peak_hour': is_peak_hour, | |
| } | |
| def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_features): | |
| lgb_model = models['lgb'] | |
| lstm_model = models['lstm'] | |
| scaler = models['scaler'] | |
| if lgb_model is None or scaler is None: | |
| return None | |
| try: | |
| features = [temp, humidite, vent, conso, time_features['hour'], time_features['day_of_week'], time_features['month'], time_features['saison'], time_features['is_peak_hour']] | |
| features_array = np.array([features]) | |
| features_scaled = scaler.transform(features_array) | |
| try: | |
| pred_lgb = float(lgb_model.predict(features_scaled)[0]) * 100 | |
| except Exception as e: | |
| logger.error(f"LightGBM prediction failed: {e}") | |
| pred_lgb = 50.0 | |
| if lstm_model is not None: | |
| try: | |
| features_lstm = features_scaled.reshape(1, 1, -1) | |
| pred_lstm = float(lstm_model.predict(features_lstm, verbose=0)[0][0]) * 100 | |
| except Exception as e: | |
| logger.warning(f"LSTM prediction failed, falling back to LightGBM: {e}") | |
| pred_lstm = pred_lgb | |
| else: | |
| pred_lstm = pred_lgb | |
| risque_base = (pred_lgb + pred_lstm) / 2 | |
| adjustment = QUARTIER_ADJUSTMENT.get(quartier, 1.0) | |
| risque_ajuste = max(5.0, risque_base * adjustment) | |
| pred_lgb = np.clip(pred_lgb, 0, 100) | |
| pred_lstm = np.clip(pred_lstm, 0, 100) | |
| risque_ajuste = np.clip(risque_ajuste, 0, 100) | |
| return pred_lgb, pred_lstm, risque_ajuste | |
| except Exception as e: | |
| st.error(f"❌ Erreur: {e}") | |
| return None | |
| def compute_map_risks(models, temperature, humidite, vitesse_vent, consommation, time_features): | |
| lgb_model = models['lgb'] | |
| lstm_model = models['lstm'] | |
| scaler = models['scaler'] | |
| if lgb_model is None or scaler is None: | |
| return None | |
| feature_row = [ | |
| temperature, humidite, vitesse_vent, consommation, | |
| time_features['hour'], time_features['day_of_week'], | |
| time_features['month'], time_features['saison'], | |
| time_features['is_peak_hour'], | |
| ] | |
| X = np.tile(feature_row, (len(QUARTIERS_DAKAR), 1)) | |
| X_scaled = scaler.transform(X) | |
| preds_lgb = lgb_model.predict(X_scaled) * 100 | |
| if lstm_model is not None: | |
| preds_lstm = lstm_model.predict(X_scaled.reshape(len(QUARTIERS_DAKAR), 1, -1), verbose=0).flatten() * 100 | |
| else: | |
| preds_lstm = preds_lgb.copy() | |
| risque_base = (preds_lgb + preds_lstm) / 2 | |
| return [ | |
| { | |
| 'Quartier': q, | |
| 'Risque': float(np.clip(max(5.0, risque_base[i] * QUARTIER_ADJUSTMENT.get(q, 1.0)), 0, 100)), | |
| } | |
| for i, q in enumerate(QUARTIERS_DAKAR) | |
| ] | |
| def get_risk_color(risque_pct): | |
| if risque_pct < 40: | |
| return "#2ecc71" | |
| elif risque_pct < 70: | |
| return "#f39c12" | |
| else: | |
| return "#e74c3c" | |
| def create_gauge_chart(risque, quartier): | |
| color = get_risk_color(risque) | |
| niveau = classify_risk(risque) | |
| fig = go.Figure(go.Indicator( | |
| mode="gauge+number", | |
| value=risque, | |
| domain={'x': [0, 1], 'y': [0, 1]}, | |
| title={'text': f"{quartier}", 'font': {'size': 20}}, | |
| number={'suffix': "%", 'font': {'size': 50}}, | |
| gauge={ | |
| 'axis': {'range': [None, 100], 'tickwidth': 2}, | |
| 'bar': {'color': color, 'thickness': 0.75}, | |
| 'steps': [ | |
| {'range': [0, 40], 'color': '#d4edda'}, | |
| {'range': [40, 70], 'color': '#fff3cd'}, | |
| {'range': [70, 100], 'color': '#f8d7da'} | |
| ] | |
| } | |
| )) | |
| fig.add_annotation( | |
| text=f"<b>{niveau}</b>", | |
| x=0.5, y=0.2, | |
| showarrow=False, | |
| font=dict(size=28, color=color) | |
| ) | |
| fig.update_layout(height=350, margin=dict(l=20, r=20, t=40, b=20)) | |
| return fig | |
| def create_map(results): | |
| df_map = [] | |
| for result in results: | |
| quartier = result['Quartier'] | |
| if quartier in COORDONNEES_QUARTIERS: | |
| coords = COORDONNEES_QUARTIERS[quartier] | |
| r = result['Risque'] | |
| niveau = classify_risk(r) | |
| df_map.append({ | |
| 'Quartier': quartier, 'Latitude': coords['lat'], 'Longitude': coords['lon'], | |
| 'Risque': r, 'Niveau': niveau | |
| }) | |
| df_map = pd.DataFrame(df_map) | |
| df_map['Couleur'] = df_map['Risque'].apply(get_risk_color) | |
| df_map['Taille'] = 20 + (df_map['Risque'] / 100) * 30 | |
| fig = go.Figure() | |
| fig.add_trace(go.Scattermapbox( | |
| lat=df_map['Latitude'], lon=df_map['Longitude'], mode='markers', | |
| marker=dict(size=df_map['Taille'], color=df_map['Couleur'], opacity=0.85), | |
| text=df_map['Quartier'], | |
| customdata=df_map[['Risque', 'Niveau']], | |
| hovertemplate=( | |
| '<b>%{text}</b><br>' | |
| 'Risque : %{customdata[0]:.1f}%<br>' | |
| 'Niveau : %{customdata[1]}<extra></extra>' | |
| ), | |
| )) | |
| fig.update_layout( | |
| mapbox=dict(style="open-street-map", center=dict(lat=14.72, lon=-17.45), zoom=11), | |
| title="Carte des Risques de Coupure", | |
| height=600, | |
| margin=dict(l=0, r=0, t=40, b=0), | |
| ) | |
| return fig | |
| def create_bar_chart_quartiers(df_stats): | |
| if df_stats is None or len(df_stats) == 0: | |
| return None | |
| df_sorted = df_stats.sort_values('taux_coupure', ascending=False) | |
| risques_pct = (df_sorted['taux_coupure'] * 100).tolist() | |
| colors = [get_risk_color(r) for r in risques_pct] | |
| niveaux = [classify_risk(r) for r in risques_pct] | |
| fig = go.Figure() | |
| fig.add_trace(go.Bar( | |
| x=df_sorted['quartier'], y=risques_pct, marker=dict(color=colors), | |
| text=[f"{r:.1f}%" for r in risques_pct], textposition='outside', | |
| customdata=list(zip(niveaux, df_sorted['temp_moy'], df_sorted['conso_moy'])), | |
| hovertemplate='<b>%{x}</b><br>Taux: %{y:.2f}%<br>Niveau: %{customdata[0]}<br>Temp: %{customdata[1]:.1f}°C<br>Conso: %{customdata[2]:.0f} MW<extra></extra>' | |
| )) | |
| fig.update_layout(title="Taux de Coupure", xaxis_title="Quartier", yaxis_title="Taux (%)", height=500) | |
| return fig | |
| def create_temporal_chart(df_hist, quartier_filter): | |
| if df_hist is None or len(df_hist) == 0: | |
| return None | |
| try: | |
| df = df_hist.copy() | |
| date_col = None | |
| for col in ['timestamp', 'date', 'datetime', 'time']: | |
| if col in df.columns: | |
| date_col = col | |
| break | |
| if date_col is None: | |
| df['index_date'] = pd.date_range(start='2023-01-01', periods=len(df), freq='H') | |
| date_col = 'index_date' | |
| df[date_col] = pd.to_datetime(df[date_col], errors='coerce') | |
| df = df.sort_values(date_col) | |
| if quartier_filter != "Tous" and 'quartier' in df.columns: | |
| df = df[df['quartier'] == quartier_filter] | |
| df_agg = ( | |
| df.set_index(date_col) | |
| .resample('W')[['conso_megawatt', 'temp_celsius']] | |
| .mean() | |
| .reset_index() | |
| ) | |
| df_agg[['conso_megawatt', 'temp_celsius']] = ( | |
| df_agg[['conso_megawatt', 'temp_celsius']] | |
| .interpolate(method='linear') | |
| ) | |
| df_agg = df_agg.dropna() | |
| fig = go.Figure() | |
| if 'conso_megawatt' in df_agg.columns: | |
| fig.add_trace(go.Scatter( | |
| x=df_agg[date_col], y=df_agg['conso_megawatt'], | |
| mode='lines', name='Consommation', line=dict(color='#00bcd4', width=1.5), | |
| fill='tozeroy', hovertemplate='<b>Conso</b><br>%{y:.0f} MW<extra></extra>' | |
| )) | |
| if 'temp_celsius' in df_agg.columns: | |
| fig.add_trace(go.Scatter( | |
| x=df_agg[date_col], y=df_agg['temp_celsius'], | |
| mode='lines', name='Température', line=dict(color='#ff5722', width=1.5, dash='dot'), | |
| yaxis='y2', hovertemplate='<b>Temp</b><br>%{y:.1f}°C<extra></extra>' | |
| )) | |
| title = f"Évolution Hebdomadaire — Consommation & Température ({quartier_filter})" if quartier_filter != "Tous" else "Évolution Hebdomadaire — Consommation & Température" | |
| fig.update_layout( | |
| title=title, xaxis_title="Semaine", | |
| yaxis=dict(title="Consommation (MW)"), | |
| yaxis2=dict(title="Température (°C)", overlaying='y', side='right'), | |
| hovermode='x unified', height=500 | |
| ) | |
| return fig | |
| except Exception as e: | |
| logger.warning(f"create_temporal_chart failed: {e}") | |
| return None | |
| def create_risk_trend_chart(df_hist, quartier_filter): | |
| if df_hist is None or len(df_hist) == 0 or 'coupure' not in df_hist.columns: | |
| return None | |
| try: | |
| df = df_hist.copy() | |
| date_col = None | |
| for col in ['timestamp', 'date', 'datetime', 'time']: | |
| if col in df.columns: | |
| date_col = col | |
| break | |
| if date_col is None: | |
| df['index_date'] = pd.date_range(start='2023-01-01', periods=len(df), freq='H') | |
| date_col = 'index_date' | |
| df[date_col] = pd.to_datetime(df[date_col]) | |
| if quartier_filter != "Tous" and 'quartier' in df.columns: | |
| df = df[df['quartier'] == quartier_filter] | |
| df = df.sort_values(date_col) | |
| df_daily = df.groupby(df[date_col].dt.date).agg({'coupure': ['sum', 'count']}).reset_index() | |
| df_daily.columns = ['date', 'coupures', 'total'] | |
| df_daily['taux'] = (df_daily['coupures'] / df_daily['total'] * 100) | |
| df_daily['niveau'] = df_daily['taux'].apply(classify_risk) | |
| df_daily['couleur'] = df_daily['taux'].apply(get_risk_color) | |
| fig = go.Figure() | |
| fig.add_trace(go.Scatter( | |
| x=df_daily['date'], y=df_daily['taux'], | |
| mode='lines+markers', name='Taux', line=dict(width=2, color='#28a745'), | |
| marker=dict(size=6, color=df_daily['couleur']), | |
| fill='tozeroy', | |
| customdata=df_daily[['niveau', 'coupures']], | |
| hovertemplate='<b>%{x}</b><br>Taux: %{y:.1f}%<br>Niveau: %{customdata[0]}<extra></extra>' | |
| )) | |
| fig.add_hline(y=40, line_dash="dash", line_color="#ffc107", annotation_text="Seuil MOYEN") | |
| fig.add_hline(y=70, line_dash="dash", line_color="#dc3545", annotation_text="Seuil ÉLEVÉ") | |
| title = f"Tendance - {quartier_filter}" if quartier_filter != "Tous" else "Tendance" | |
| fig.update_layout(title=title, xaxis_title="Date", yaxis_title="Taux (%)", height=500) | |
| return fig | |
| except Exception as e: | |
| logger.warning(f"create_risk_trend_chart failed: {e}") | |
| return None | |