Source code for todays_paper_web.widgets.weather.core

import math
from datetime import date, datetime, timedelta, timezone, tzinfo
from enum import Enum
from pathlib import Path, PurePath
from typing import Union

from PIL import Image
from pydantic import BaseModel, Field

from todays_paper_web.widgets import registerView
from todays_paper_web.widgets.core.image import ImageBaseView, ImageParams

BASE_PATH = Path(__file__).parent.resolve()


class WeatherType(Enum):
    Unknown = 0
    ClearSky = 1
    FewClouds = 2
    ScatteredClouds = 3
    BrokenClouds = 4
    ShowerRain = 9
    Rain = 10
    Thunderstorm = 11
    Snow = 13
    Mist = 50


class TimeOfDay(Enum):
    Day = "d"
    Night = "n"


class WeatherIcon(BaseModel):
    weather: WeatherType
    timeOfDay: TimeOfDay

    def id(self) -> str:
        return f"{self.weather.value:02d}{self.timeOfDay.value}"


class WeatherForecast(BaseModel):
    timestamp: datetime
    icon: WeatherIcon
    airTemperature: Union[float, None]
    precipitation: Union[float, None]
    relativeHumidity: Union[float, None]
    windGustSpeed: Union[float, None]
    windSpeed: Union[float, None]


class WeatherForecastModel:
    def __init__(
        self,
        forecasts: list[WeatherForecast],
        lat: Union[float, None] = None,
        lon: Union[float, None] = None,
    ):
        self._forecasts = forecasts
        self._lat = lat
        self._lon = lon

    def between(self, start: datetime, end: datetime) -> list[WeatherForecast]:
        """All forecasts from start (inclusive) to end (exclusive), in start's timezone."""
        return [
            forecast.copy(
                update={"timestamp": forecast.timestamp.astimezone(start.tzinfo)}
            )
            for forecast in self._forecasts
            if start <= forecast.timestamp < end
        ]

    def sunriseSunset(
        self, day: date, tzinfo: tzinfo
    ) -> Union[tuple[datetime, datetime], None]:
        """Sunrise and sunset for the forecast location, or None during midnight sun/polar night."""
        if self._lat is None or self._lon is None:
            return None
        # https://en.wikipedia.org/wiki/Sunrise_equation
        J2000 = 2451545.0
        meanSolarTime = day.toordinal() - date(2000, 1, 1).toordinal() - self._lon / 360
        anomaly = math.radians((357.5291 + 0.98560028 * meanSolarTime) % 360)
        center = (
            1.9148 * math.sin(anomaly)
            + 0.02 * math.sin(2 * anomaly)
            + 0.0003 * math.sin(3 * anomaly)
        )
        longitude = math.radians(
            (math.degrees(anomaly) + center + 180 + 102.9372) % 360
        )
        transit = (
            J2000
            + meanSolarTime
            + 0.0053 * math.sin(anomaly)
            - 0.0069 * math.sin(2 * longitude)
        )
        declination = math.asin(math.sin(longitude) * math.sin(math.radians(23.4397)))
        lat = math.radians(self._lat)
        cosHourAngle = (
            math.sin(math.radians(-0.833)) - math.sin(lat) * math.sin(declination)
        ) / (math.cos(lat) * math.cos(declination))
        if abs(cosHourAngle) > 1:
            return None
        hourAngle = math.degrees(math.acos(cosHourAngle)) / 360

        def toDatetime(julian: float) -> datetime:
            noon = datetime(2000, 1, 1, 12, tzinfo=timezone.utc)
            return (noon + timedelta(days=julian - J2000)).astimezone(tzinfo)

        return toDatetime(transit - hourAngle), toDatetime(transit + hourAngle)

    def nextHour(self, timestamp: datetime, hour: int) -> Union[WeatherForecast, None]:
        target = timestamp.replace(hour=hour)
        if target < timestamp:
            target += timedelta(days=1)

        best = None
        delta = timedelta.max
        for forecast in self._forecasts:
            newDelta = abs(forecast.timestamp - target)
            if newDelta < delta:
                best = forecast
                delta = newDelta
            if delta == timedelta():
                # No need to search longer, found an exact match
                break
        # Return the forecast adjusted to the correct timezone
        return best.copy(
            update={"timestamp": best.timestamp.astimezone(timestamp.tzinfo)}
        )


[docs] class WeatherIconParams(ImageParams): icon: str = Field( ..., description='The icon id, e.g. `"01d"` - see `WeatherIcon.id()` for how it\'s built.' ) theme: str = Field( "openweather", description="Which bundled icon set to use: `openweather` or `erikflower`." )
@registerView("weather.icon") class WeatherIconView(ImageBaseView): Params = WeatherIconParams def fetch_img(self): symbol_path = PurePath( BASE_PATH, "img", self.params.theme, self.params.icon ).with_suffix(".png") if Path(symbol_path).exists(): return Image.open(str(symbol_path)) return None