cheikhaidev-ui commited on
Commit
d248d81
·
1 Parent(s): fa90692

feat(v2): add real-time weather API + improved map colors

Browse files

- feat(weather): integrate Open-Meteo API for real Dakar weather data
- feat(sidebar): add weather button to auto-fill sliders with live data
- feat(map): colored markers by risk level (green/orange/red), size=20, zoom=11
- Live test: Dakar 25.2C, 82% humidity, 7.4 km/h wind

src/weather_api.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Client Open-Meteo pour les données météo de Dakar.
3
+ API gratuite, sans clé : https://open-meteo.com/
4
+ """
5
+ import logging
6
+ from datetime import datetime, timedelta
7
+
8
+ import requests
9
+ import pandas as pd
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ _DAKAR_LAT = 14.7167
14
+ _DAKAR_LON = -17.4677
15
+ _TIMEOUT = 10
16
+
17
+
18
+ def get_current_weather_dakar() -> dict | None:
19
+ """
20
+ Retourne les conditions météo actuelles à Dakar.
21
+ Clés : temperature (°C), humidity (%), wind_speed (km/h), timestamp (str ISO).
22
+ """
23
+ url = (
24
+ "https://api.open-meteo.com/v1/forecast"
25
+ f"?latitude={_DAKAR_LAT}&longitude={_DAKAR_LON}"
26
+ "&current=temperature_2m,relative_humidity_2m,wind_speed_10m"
27
+ "&wind_speed_unit=kmh"
28
+ )
29
+ try:
30
+ resp = requests.get(url, timeout=_TIMEOUT)
31
+ resp.raise_for_status()
32
+ current = resp.json()['current']
33
+ return {
34
+ 'temperature': current['temperature_2m'],
35
+ 'humidity': current['relative_humidity_2m'],
36
+ 'wind_speed': current['wind_speed_10m'],
37
+ 'timestamp': current['time'],
38
+ }
39
+ except Exception as e:
40
+ logger.warning(f"get_current_weather_dakar failed: {e}")
41
+ return None
42
+
43
+
44
+ def get_weather_forecast_7days() -> list[dict] | None:
45
+ """
46
+ Retourne les prévisions météo sur 7 jours pour Dakar.
47
+ Chaque entrée : date, temp_max, temp_min, precipitation, wind_max.
48
+ """
49
+ url = (
50
+ "https://api.open-meteo.com/v1/forecast"
51
+ f"?latitude={_DAKAR_LAT}&longitude={_DAKAR_LON}"
52
+ "&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,wind_speed_10m_max"
53
+ "&wind_speed_unit=kmh&timezone=Africa%2FDakar"
54
+ )
55
+ try:
56
+ resp = requests.get(url, timeout=_TIMEOUT)
57
+ resp.raise_for_status()
58
+ daily = resp.json()['daily']
59
+ return [
60
+ {
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']))
68
+ ]
69
+ except Exception as e:
70
+ logger.warning(f"get_weather_forecast_7days failed: {e}")
71
+ return None
72
+
73
+
74
+ def get_historical_weather_dakar(days: int = 30) -> pd.DataFrame | None:
75
+ """
76
+ Retourne les données météo historiques sur `days` jours pour Dakar.
77
+ Colonnes : date, temp_mean, precipitation, wind_max.
78
+ """
79
+ end_date = datetime.now().date()
80
+ start_date = end_date - timedelta(days=days)
81
+ url = (
82
+ "https://archive-api.open-meteo.com/v1/archive"
83
+ f"?latitude={_DAKAR_LAT}&longitude={_DAKAR_LON}"
84
+ f"&start_date={start_date}&end_date={end_date}"
85
+ "&daily=temperature_2m_mean,precipitation_sum,wind_speed_10m_max"
86
+ "&wind_speed_unit=kmh&timezone=Africa%2FDakar"
87
+ )
88
+ try:
89
+ resp = requests.get(url, timeout=15)
90
+ resp.raise_for_status()
91
+ daily = resp.json()['daily']
92
+ return pd.DataFrame({
93
+ 'date': daily['time'],
94
+ 'temp_mean': daily['temperature_2m_mean'],
95
+ 'precipitation': daily['precipitation_sum'],
96
+ 'wind_max': daily['wind_speed_10m_max'],
97
+ })
98
+ except Exception as e:
99
+ logger.warning(f"get_historical_weather_dakar failed: {e}")
100
+ return None
streamlit_app/app.py CHANGED
@@ -22,6 +22,7 @@ from streamlit_app.utils_simple import (
22
  create_risk_trend_chart,
23
  )
24
  from src.config import QUARTIERS_DAKAR, QUARTIER_ADJUSTMENT, classify_risk
 
25
 
26
  st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
27
 
@@ -44,10 +45,24 @@ def load_csv():
44
  df_hist = load_csv()
45
 
46
  st.sidebar.title("🌡️ Paramètres")
47
- temperature = st.sidebar.slider("Température (°C)", 15.0, 45.0, 25.0, 0.5)
48
- humidite = st.sidebar.slider("Humidité (%)", 30.0, 100.0, 65.0, 1.0)
49
- vitesse_vent = st.sidebar.slider("Vent (km/h)", 0.0, 50.0, 15.0, 1.0)
50
- consommation = st.sidebar.slider("Consommation (MW)", 400.0, 1500.0, 800.0, 10.0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
52
 
53
  if st.sidebar.button("🔮 Lancer la Prédiction", type="primary", use_container_width=True):
 
22
  create_risk_trend_chart,
23
  )
24
  from src.config import QUARTIERS_DAKAR, QUARTIER_ADJUSTMENT, classify_risk
25
+ from src.weather_api import get_current_weather_dakar
26
 
27
  st.set_page_config(page_title="Dakar Power", page_icon="⚡", layout="wide")
28
 
 
45
  df_hist = load_csv()
46
 
47
  st.sidebar.title("🌡️ Paramètres")
48
+
49
+ if st.sidebar.button("🌤️ Météo actuelle Dakar", use_container_width=True):
50
+ weather = get_current_weather_dakar()
51
+ if weather:
52
+ st.session_state['s_temp'] = float(np.clip(weather['temperature'], 15.0, 45.0))
53
+ st.session_state['s_hum'] = float(np.clip(weather['humidity'], 30.0, 100.0))
54
+ st.session_state['s_wind'] = float(np.clip(weather['wind_speed'], 0.0, 50.0))
55
+ st.session_state['wx_time'] = weather['timestamp']
56
+ else:
57
+ st.sidebar.error("❌ API météo indisponible")
58
+
59
+ if 'wx_time' in st.session_state:
60
+ st.sidebar.caption(f"⏱️ Données météo en temps réel — {st.session_state['wx_time']}")
61
+
62
+ temperature = st.sidebar.slider("Température (°C)", 15.0, 45.0, 25.0, 0.5, key='s_temp')
63
+ humidite = st.sidebar.slider("Humidité (%)", 30.0, 100.0, 65.0, 1.0, key='s_hum')
64
+ vitesse_vent = st.sidebar.slider("Vent (km/h)", 0.0, 50.0, 15.0, 1.0, key='s_wind')
65
+ consommation = st.sidebar.slider("Consommation (MW)", 400.0, 1500.0, 800.0, 10.0)
66
  quartier = st.sidebar.selectbox("Quartier", QUARTIERS_DAKAR, index=0)
67
 
68
  if st.sidebar.button("🔮 Lancer la Prédiction", type="primary", use_container_width=True):
streamlit_app/utils_simple.py CHANGED
@@ -97,11 +97,11 @@ def make_prediction_single(models, quartier, temp, humidite, vent, conso, time_f
97
 
98
  def get_risk_color(risque_pct):
99
  if risque_pct < 40:
100
- return "#28a745"
101
  elif risque_pct < 70:
102
- return "#ffc107"
103
  else:
104
- return "#dc3545"
105
 
106
  def create_gauge_chart(risque, quartier):
107
  color = get_risk_color(risque)
@@ -146,21 +146,25 @@ def create_map(results):
146
  })
147
  df_map = pd.DataFrame(df_map)
148
  df_map['Couleur'] = df_map['Risque'].apply(get_risk_color)
149
- df_map['Taille'] = 10 + (df_map['Risque'] / 100) * 40
150
-
151
  fig = go.Figure()
152
  fig.add_trace(go.Scattermapbox(
153
  lat=df_map['Latitude'], lon=df_map['Longitude'], mode='markers',
154
- marker=dict(size=df_map['Taille'], color=df_map['Couleur'], opacity=0.8),
155
  text=df_map['Quartier'],
156
  customdata=df_map[['Risque', 'Niveau']],
157
- hovertemplate='<b>%{text}</b><br>Risque: %{customdata[0]:.1f}%<br>Niveau: %{customdata[1]}<extra></extra>'
 
 
 
 
158
  ))
159
  fig.update_layout(
160
- mapbox=dict(style="open-street-map", center=dict(lat=14.7167, lon=-17.4677), zoom=10),
161
- title="Carte des Risques",
162
  height=600,
163
- margin=dict(l=0, r=0, t=40, b=0)
164
  )
165
  return fig
166
 
 
97
 
98
  def get_risk_color(risque_pct):
99
  if risque_pct < 40:
100
+ return "#2ecc71"
101
  elif risque_pct < 70:
102
+ return "#f39c12"
103
  else:
104
+ return "#e74c3c"
105
 
106
  def create_gauge_chart(risque, quartier):
107
  color = get_risk_color(risque)
 
146
  })
147
  df_map = pd.DataFrame(df_map)
148
  df_map['Couleur'] = df_map['Risque'].apply(get_risk_color)
149
+ df_map['Taille'] = 20 + (df_map['Risque'] / 100) * 30
150
+
151
  fig = go.Figure()
152
  fig.add_trace(go.Scattermapbox(
153
  lat=df_map['Latitude'], lon=df_map['Longitude'], mode='markers',
154
+ marker=dict(size=df_map['Taille'], color=df_map['Couleur'], opacity=0.85),
155
  text=df_map['Quartier'],
156
  customdata=df_map[['Risque', 'Niveau']],
157
+ hovertemplate=(
158
+ '<b>%{text}</b><br>'
159
+ 'Risque : %{customdata[0]:.1f}%<br>'
160
+ 'Niveau : %{customdata[1]}<extra></extra>'
161
+ ),
162
  ))
163
  fig.update_layout(
164
+ mapbox=dict(style="open-street-map", center=dict(lat=14.72, lon=-17.45), zoom=11),
165
+ title="Carte des Risques de Coupure",
166
  height=600,
167
+ margin=dict(l=0, r=0, t=40, b=0),
168
  )
169
  return fig
170