Spaces:
Paused
Paused
import openmeteo_requests | |
import requests_cache | |
import pandas as pd | |
from retry_requests import retry | |
# Setup the Open-Meteo API client with cache and retry on error | |
cache_session = requests_cache.CachedSession('.cache', expire_after=3600) | |
retry_session = retry(cache_session, retries=5, backoff_factor=0.2) | |
openmeteo = openmeteo_requests.Client(session=retry_session) | |
def get_hourly_weather_data(response): | |
# Hourly dataframe | |
hourly = response.Hourly() | |
hourly_relative_humidity_2m = hourly.Variables(0).ValuesAsNumpy() | |
hourly_soil_temperature_0cm = hourly.Variables(1).ValuesAsNumpy() | |
hourly_soil_moisture_0_to_1cm = hourly.Variables(2).ValuesAsNumpy() | |
hourly_cloud_cover = hourly.Variables(3).ValuesAsNumpy() | |
hourly_data = {"date": pd.date_range( | |
start=pd.to_datetime(hourly.Time(), unit="s", utc=True), | |
end=pd.to_datetime(hourly.TimeEnd(), unit="s", utc=True), | |
freq=pd.Timedelta(seconds=hourly.Interval()), | |
inclusive="left" | |
)} | |
hourly_data["relative_humidity_2m_%"] = hourly_relative_humidity_2m | |
hourly_data["soil_temperature_0cm_C"] = hourly_soil_temperature_0cm | |
hourly_data["soil_moisture_0_to_1cm_m³"] = hourly_soil_moisture_0_to_1cm | |
hourly_data["cloud_cover_%"] = hourly_cloud_cover | |
hourly_dataframe = pd.DataFrame(data=hourly_data) | |
# print('hourly df', hourly_dataframe) | |
hourly_dataframe = pd.DataFrame(data=hourly_data) | |
# Average hourly data per day | |
hourly_dataframe['day_date'] = hourly_dataframe['date'].dt.strftime( | |
'%Y-%m-%d') | |
tmp1 = hourly_dataframe.groupby('day_date')[ | |
['relative_humidity_2m_%', 'soil_temperature_0cm_C', 'soil_moisture_0_to_1cm_m³']].mean() | |
avg_hourly_dataframe = tmp1.rename(columns={ | |
'relative_humidity_2m_%': 'avg_hourly_relative_humidity_2m_%', | |
'soil_temperature_0cm_C': 'avg_hourly_soil_temperature_0cm_C', | |
'soil_moisture_0_to_1cm_m³': 'avg_hourly_soil_moisture_0_to_1cm_m³' | |
} | |
) | |
# med cloud couverture | |
tmp2 = hourly_dataframe.groupby('day_date')[['cloud_cover_%']].median() | |
med_cloud_cover = tmp2.rename( | |
columns={'cloud_cover_%': 'med_cloud_cover_%'}) | |
return avg_hourly_dataframe, med_cloud_cover | |
def get_daily_weather_data(response): | |
# Daily dataframe | |
daily = response.Daily() | |
daily_temperature_2m_max = daily.Variables(0).ValuesAsNumpy() | |
daily_precipitation_sum = daily.Variables(1).ValuesAsNumpy() | |
daily_wind_speed_10m_max = daily.Variables(2).ValuesAsNumpy() | |
daily_sunshine_duration = daily.Variables(3).ValuesAsNumpy() | |
daily_rain_sum = daily.Variables(4).ValuesAsNumpy() | |
daily_data = {"date": pd.date_range( | |
start=pd.to_datetime(daily.Time(), unit="s", utc=True), | |
end=pd.to_datetime(daily.TimeEnd(), unit="s", utc=True), | |
freq='D', | |
inclusive="left" | |
)} | |
daily_data["daily_temperature_2m_max_C"] = daily_temperature_2m_max | |
daily_data["daily_precipitation_sum_mm"] = daily_precipitation_sum | |
daily_data["daily_wind_speed_10m_max_km/h"] = daily_wind_speed_10m_max | |
daily_data["daily_sunshine_duration_sec"] = daily_sunshine_duration | |
daily_data["daily_rain_sum_mm"] = daily_rain_sum | |
daily_dataframe = pd.DataFrame(data=daily_data) | |
# print('meteo_daily', daily_dataframe) | |
daily_dataframe['day_date'] = daily_dataframe['date'].dt.strftime( | |
'%Y-%m-%d') | |
return daily_dataframe | |
def get_info_meteo(latitude, longitude): | |
"""Function that creates a Json file containing the weather data of the location | |
ARGS: | |
latitude (Float) : latitude coordinate | |
longitude (Float): longitude coordinate | |
""" | |
url = "https://api.open-meteo.com/v1/forecast" | |
params = { | |
"latitude": latitude, | |
"longitude": longitude, # "cloud_cover_low", "cloud_cover_mid","cloud_cover_high" | |
"hourly": ["relative_humidity_2m", "soil_temperature_0cm", "soil_moisture_0_to_1cm", "cloud_cover"], | |
"daily": ["temperature_2m_max", "precipitation_sum", "wind_speed_10m_max", "sunshine_duration", "rain_sum"], | |
"past_days": 5, | |
"forecast_days": 7 | |
} | |
responses = openmeteo.weather_api(url, params=params) | |
response = responses[0] | |
print(f"Coordinates {response.Latitude()}°N {response.Longitude()}°E") | |
print(f"Elevation {response.Elevation()} m asl") | |
print(f"Timezone {response.Timezone()} {response.TimezoneAbbreviation()}") | |
print(f"Timezone difference to GMT+0 {response.UtcOffsetSeconds()} s") | |
avg_hourly_dataframe, med_cloud_cover = get_hourly_weather_data(response) | |
daily_dataframe = get_daily_weather_data(response) | |
total_df = pd.merge(daily_dataframe, avg_hourly_dataframe, | |
on="day_date", how="left") | |
total_df = pd.merge(total_df, med_cloud_cover, | |
on="day_date", how="left") | |
total_df['date'] = total_df['day_date'] | |
total_df = total_df.drop('day_date', axis=1) | |
# total_df.to_json("weather_data.json", orient='columns') | |
return total_df | |
if __name__ == "__main__": | |
df = get_info_meteo(48.832, 2.286) | |
print(df) | |