feat: Open-Meteo parsing and icon mapping
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
839c1824a9
commit
37065a5fba
2 files changed
+209
No files matched your search
@@ -0,0 +1,101 @@
|
|||||||
|
import copy
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import weather_data
|
||||||
|
from weather_data import Icon, icon_for, parse_weather
|
||||||
|
|
||||||
|
FIXTURE = json.loads((Path(__file__).parent / "fixtures" / "open-meteo-zlin.json").read_text())
|
||||||
|
NOW = datetime(2026, 10, 22, 12, 45)
|
||||||
|
|
||||||
|
|
||||||
|
def payload():
|
||||||
|
return copy.deepcopy(FIXTURE)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_fixture_window():
|
||||||
|
w = parse_weather(payload(), NOW)
|
||||||
|
assert len(w.hours) == 12
|
||||||
|
assert w.hours[0].time == datetime(2026, 10, 22, 12, 0)
|
||||||
|
assert w.hours[-1].time == datetime(2026, 10, 22, 23, 0)
|
||||||
|
assert w.hours[0].rain_pct == FIXTURE["hourly"]["precipitation_probability"][12]
|
||||||
|
assert w.hours[0].mm == FIXTURE["hourly"]["precipitation"][12]
|
||||||
|
assert (w.temp, w.code) == (10.2, 61)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_today_max_min():
|
||||||
|
w = parse_weather(payload(), NOW)
|
||||||
|
assert (w.today_max, w.today_min) == (15.0, 6.0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_window_runs_into_tomorrow_late_in_the_day():
|
||||||
|
w = parse_weather(payload(), datetime(2026, 10, 22, 20, 10))
|
||||||
|
assert w.hours[0].time == datetime(2026, 10, 22, 20, 0)
|
||||||
|
assert w.hours[-1].time == datetime(2026, 10, 23, 7, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_icon_mapping():
|
||||||
|
assert icon_for(0) is Icon.SUN
|
||||||
|
assert icon_for(2) is Icon.PARTLY
|
||||||
|
assert icon_for(3) is Icon.CLOUDY
|
||||||
|
assert icon_for(45) is Icon.FOG
|
||||||
|
assert icon_for(61) is Icon.RAIN
|
||||||
|
assert icon_for(81) is Icon.RAIN
|
||||||
|
assert icon_for(73) is Icon.SNOW
|
||||||
|
assert icon_for(95) is Icon.STORM
|
||||||
|
assert icon_for(999) is None
|
||||||
|
assert icon_for(None) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_null_entries_become_none():
|
||||||
|
p = payload()
|
||||||
|
p["hourly"]["precipitation_probability"][13] = None
|
||||||
|
p["hourly"]["precipitation"][13] = None
|
||||||
|
w = parse_weather(p, NOW)
|
||||||
|
assert (w.hours[1].rain_pct, w.hours[1].mm) == (None, None)
|
||||||
|
assert w.hours[0].rain_pct is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_short_hourly_gives_fewer_hours():
|
||||||
|
p = payload()
|
||||||
|
for key in ("time", "precipitation_probability", "precipitation"):
|
||||||
|
p["hourly"][key] = p["hourly"][key][:14]
|
||||||
|
assert len(parse_weather(p, NOW).hours) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_current_gives_none_temp():
|
||||||
|
p = payload()
|
||||||
|
del p["current"]
|
||||||
|
w = parse_weather(p, NOW)
|
||||||
|
assert (w.temp, w.code) == (None, None)
|
||||||
|
assert len(w.hours) == 12
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_sections_do_not_raise():
|
||||||
|
w = parse_weather({}, NOW)
|
||||||
|
assert (w.temp, w.today_max, w.hours) == (None, None, ())
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_passes_coordinates():
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class Response:
|
||||||
|
def raise_for_status(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return payload()
|
||||||
|
|
||||||
|
def fake_get(url, params=None, timeout=None):
|
||||||
|
calls.append((url, params, timeout))
|
||||||
|
return Response()
|
||||||
|
|
||||||
|
w = weather_data.fetch_weather(NOW, get=fake_get)
|
||||||
|
url, params, timeout = calls[0]
|
||||||
|
assert url.startswith("https://api.open-meteo.com/")
|
||||||
|
assert params["latitude"] == weather_data.LAT == 49.2265
|
||||||
|
assert params["longitude"] == weather_data.LON == 17.6627
|
||||||
|
assert params["timezone"] == "Europe/Prague"
|
||||||
|
assert timeout == 10
|
||||||
|
assert len(w.hours) == 12
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
"""Open-Meteo forecast for Zlín: fetching and parsing (no drawing)."""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
LAT = 49.2265
|
||||||
|
LON = 17.6627
|
||||||
|
URL = "https://api.open-meteo.com/v1/forecast"
|
||||||
|
TIMEZONE = "Europe/Prague"
|
||||||
|
WINDOW_HOURS = 12
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Hour:
|
||||||
|
time: datetime # naive local time
|
||||||
|
rain_pct: int | None
|
||||||
|
mm: float | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Weather:
|
||||||
|
temp: float | None
|
||||||
|
code: int | None
|
||||||
|
today_max: float | None
|
||||||
|
today_min: float | None
|
||||||
|
hours: tuple[Hour, ...] # at most WINDOW_HOURS, starting with the hour containing "now"
|
||||||
|
|
||||||
|
|
||||||
|
class Icon(Enum):
|
||||||
|
SUN = "sun"
|
||||||
|
PARTLY = "partly"
|
||||||
|
CLOUDY = "cloudy"
|
||||||
|
RAIN = "rain"
|
||||||
|
SNOW = "snow"
|
||||||
|
STORM = "storm"
|
||||||
|
FOG = "fog"
|
||||||
|
|
||||||
|
|
||||||
|
_WMO_ICONS = {
|
||||||
|
Icon.SUN: (0,),
|
||||||
|
Icon.PARTLY: (1, 2),
|
||||||
|
Icon.CLOUDY: (3,),
|
||||||
|
Icon.FOG: (45, 48),
|
||||||
|
Icon.RAIN: (*range(51, 58), *range(61, 68), 80, 81, 82),
|
||||||
|
Icon.SNOW: (*range(71, 78), 85, 86),
|
||||||
|
Icon.STORM: (95, 96, 99),
|
||||||
|
}
|
||||||
|
_ICON_BY_CODE = {code: icon for icon, codes in _WMO_ICONS.items() for code in codes}
|
||||||
|
|
||||||
|
|
||||||
|
def icon_for(code: int | None) -> Icon | None:
|
||||||
|
return _ICON_BY_CODE.get(code)
|
||||||
|
|
||||||
|
|
||||||
|
def _at(values, i: int):
|
||||||
|
"""values[i] or None when the list is missing, short, or holds a null."""
|
||||||
|
if not isinstance(values, list) or i >= len(values):
|
||||||
|
return None
|
||||||
|
return values[i]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_weather(payload: dict, now: datetime) -> Weather:
|
||||||
|
current = payload.get("current") or {}
|
||||||
|
daily = payload.get("daily") or {}
|
||||||
|
hourly = payload.get("hourly") or {}
|
||||||
|
|
||||||
|
day = now.strftime("%Y-%m-%d")
|
||||||
|
days = daily.get("time") or []
|
||||||
|
d = days.index(day) if day in days else None
|
||||||
|
today_max = _at(daily.get("temperature_2m_max"), d) if d is not None else None
|
||||||
|
today_min = _at(daily.get("temperature_2m_min"), d) if d is not None else None
|
||||||
|
|
||||||
|
hours: list[Hour] = []
|
||||||
|
times = hourly.get("time") or []
|
||||||
|
start = now.strftime("%Y-%m-%dT%H:00")
|
||||||
|
if start in times:
|
||||||
|
first = times.index(start)
|
||||||
|
for i in range(first, min(first + WINDOW_HOURS, len(times))):
|
||||||
|
hours.append(Hour(
|
||||||
|
time=datetime.fromisoformat(times[i]),
|
||||||
|
rain_pct=_at(hourly.get("precipitation_probability"), i),
|
||||||
|
mm=_at(hourly.get("precipitation"), i),
|
||||||
|
))
|
||||||
|
|
||||||
|
return Weather(
|
||||||
|
temp=current.get("temperature_2m"),
|
||||||
|
code=current.get("weather_code"),
|
||||||
|
today_max=today_max,
|
||||||
|
today_min=today_min,
|
||||||
|
hours=tuple(hours),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_weather(now: datetime, get=requests.get) -> Weather:
|
||||||
|
params = {
|
||||||
|
"latitude": LAT,
|
||||||
|
"longitude": LON,
|
||||||
|
"current": "temperature_2m,weather_code",
|
||||||
|
"hourly": "precipitation_probability,precipitation",
|
||||||
|
"daily": "temperature_2m_max,temperature_2m_min",
|
||||||
|
"timezone": TIMEZONE,
|
||||||
|
"forecast_days": 2,
|
||||||
|
}
|
||||||
|
response = get(URL, params=params, timeout=10)
|
||||||
|
response.raise_for_status()
|
||||||
|
return parse_weather(response.json(), now)
|
||||||
Reference in new issue
Block a user