RoboServant/textgen/weather.py

65 lines
2.3 KiB
Python

import openmeteo_requests
import pytz
import pandas as pd
import requests_cache
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)
URL = "https://api.open-meteo.com/v1/forecast"
class OpenMeteo:
openmeteo: openmeteo_requests.Client
def __init__(self):
self.openmeteo = openmeteo_requests.Client(session = retry_session)
def get_weather(self) -> pd.DataFrame:
params = {
"latitude": 36.0626,
"longitude": -94.1574,
"hourly": ["temperature_2m", "rain"],
"timezone": "America/Chicago",
# "forecast_days": 1,
"start_date": "2025-09-30",
"end_date": "2025-09-30",
"temperature_unit": 'fahrenheit',
# "bounding_box": "-90,-180,90,180",
# "models": "dwd_icon_global"
}
responses = self.openmeteo.weather_api(URL, params=params)
# Process first location. Add a for-loop for multiple locations or weather models
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")
# Process hourly data. The order of variables needs to be the same as requested.
hourly = response.Hourly()
hourly_temperature_2m = hourly.Variables(0).ValuesAsNumpy()
hourly_rain = hourly.Variables(1).ValuesAsNumpy()
hourly_data = {"date": pd.date_range(
start = pd.to_datetime(hourly.Time(), unit = "s", utc = True).astimezone(pytz.timezone('US/Central')),
end = pd.to_datetime(hourly.TimeEnd(), unit = "s", utc = True).astimezone(pytz.timezone('US/Central')),
freq = pd.Timedelta(seconds = hourly.Interval()),
inclusive = "left"
)}
hourly_data["temperature_2m"] = hourly_temperature_2m
hourly_data['rain'] = hourly_rain
hourly_dataframe = pd.DataFrame(data = hourly_data)
# print("\nHourly data\n", hourly_dataframe)
return hourly_dataframe