From 4a2f78d3b2537b5d515c475a41145a32e394f572 Mon Sep 17 00:00:00 2001 From: twfarley Date: Tue, 15 Sep 2026 07:12:11 -0600 Subject: [PATCH] Align Caelus forecasts and bundle nine weather glyphs --- THIRD_PARTY_NOTICES.md | 10 + docs/architecture.md | 4 +- docs/user_guide.md | 18 + sensorius/__init__.py | 2 +- sensorius/saiWeatherForecast.py | 226 +++++----- sensorius/saiWeatherForecastApp.py | 103 ++--- .../test_integrated_weather_forecast.py | 46 +- testApparatus/test_weather_forecast.py | 56 ++- tests/weather-forecast.spec.js | 20 +- ui_static/weather_forecast/app.css | 9 +- .../weather_forecast/glyphs/LICENSE-GRAPHICS | 393 ++++++++++++++++++ ui_static/weather_forecast/glyphs/README.md | 14 + .../weather_forecast/glyphs/clear-night.svg | 1 + ui_static/weather_forecast/glyphs/cloudy.svg | 1 + ui_static/weather_forecast/glyphs/fog.svg | 1 + .../glyphs/partly-cloudy-night.svg | 1 + .../weather_forecast/glyphs/partly-cloudy.svg | 1 + ui_static/weather_forecast/glyphs/rain.svg | 1 + ui_static/weather_forecast/glyphs/snow.svg | 1 + ui_static/weather_forecast/glyphs/sunny.svg | 1 + ui_static/weather_forecast/glyphs/thunder.svg | 1 + ui_templates/weather_forecast/index.html | 22 +- 22 files changed, 742 insertions(+), 190 deletions(-) create mode 100644 ui_static/weather_forecast/glyphs/LICENSE-GRAPHICS create mode 100644 ui_static/weather_forecast/glyphs/README.md create mode 100644 ui_static/weather_forecast/glyphs/clear-night.svg create mode 100644 ui_static/weather_forecast/glyphs/cloudy.svg create mode 100644 ui_static/weather_forecast/glyphs/fog.svg create mode 100644 ui_static/weather_forecast/glyphs/partly-cloudy-night.svg create mode 100644 ui_static/weather_forecast/glyphs/partly-cloudy.svg create mode 100644 ui_static/weather_forecast/glyphs/rain.svg create mode 100644 ui_static/weather_forecast/glyphs/snow.svg create mode 100644 ui_static/weather_forecast/glyphs/sunny.svg create mode 100644 ui_static/weather_forecast/glyphs/thunder.svg diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 467994e..407ba1c 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -52,3 +52,13 @@ The three packages present on 2026-07-22 passed manifest size/SHA-256 checks and a static string scan found no committed runtime credentials. Their manifests do not record a source commit or license provenance, so reproducible source traceability remains a release-process requirement for future packages. + +## Weather Glyphs (Twemoji) + +The nine bundled weather SVGs in `ui_static/weather_forecast/glyphs/` use +Twemoji v17.0.2 artwork by Twitter and other contributors, licensed under +[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). +[Source artwork](https://github.com/jdecked/twemoji/tree/v17.0.2/assets/svg). +The partly cloudy night glyph combines and repositions the crescent moon and +foreground cloud. The other eight glyphs are unchanged. Asset mappings and the +full graphics license are included alongside the SVG files. diff --git a/docs/architecture.md b/docs/architecture.md index 4f3b6e0..866c12c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -209,8 +209,8 @@ Weather forecast: no forecast. - Missing precipitation probabilities are filled by timestamp without changing the selected forecast source. NWS hourly gaps use the NWS grid-data product; - MET Norway locations whose global model omits probability use Open-Meteo for - that field only. + MET Norway uses the same period and missing-probability estimates as standalone + Caelus (5%, 55%, or 85% based on precipitation amount), without mixing providers. - Forecast payloads are cached in SQLite in `weather_forecast` and reused for up to five minutes. Open dashboards poll that shared cache every five minutes, so the forecast card and its current-condition background update without a diff --git a/docs/user_guide.md b/docs/user_guide.md index e0f791f..e354502 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -480,6 +480,24 @@ Google Account when the hub is retired or no longer uses that account. #### Weather Forecast +Hourly conditions use the same MET Norway symbol and Open-Meteo weather-code +mappings as standalone Caelus; NWS conditions retain the provider's wording. +The full-screen Today card covers the remaining local day, and each daily glyph +represents the most common hourly condition (ties use the first encountered). +Daily summaries describe early skies and the prevailing precipitation period, +including snow/sleet and thunderstorms. Nine bundled SVG weather glyphs work offline without an emoji font. Hourly +clear and partly cloudy forecasts use moon artwork at night, selected from +provider daylight flags or MET day/night symbols. When those are absent, +Sensorius calculates solar position at the forecast timestamp and station +coordinates, including polar day/night. Incomplete offline records without +location or time retain daytime artwork. Daily glyphs use daytime artwork. +The icons use Twemoji artwork, with a composed partly cloudy night variant; +forecast condition selection remains aligned with Caelus. +MET amounts and probabilities come from the same shortest available forecast +period, preserving six- and twelve-hour precipitation totals. When MET omits a +probability, Caelus's estimate is used: 5% for no precipitation, 55% below 1 mm, +and 85% at or above 1 mm. + Both forecast tiles include a forecast synopsis. Open-Meteo and MET Norway summaries are assembled from hourly conditions, temperature range, maximum wind, and peak precipitation chance, using the selected display units. NWS supplies diff --git a/sensorius/__init__.py b/sensorius/__init__.py index 013883c..3627405 100644 --- a/sensorius/__init__.py +++ b/sensorius/__init__.py @@ -4,4 +4,4 @@ release notes, and supporting tooling can report a consistent build identity. """ -__version__ = "v0.26.257.1" +__version__ = "v0.26.258.2" diff --git a/sensorius/saiWeatherForecast.py b/sensorius/saiWeatherForecast.py index f6732ce..eb35083 100644 --- a/sensorius/saiWeatherForecast.py +++ b/sensorius/saiWeatherForecast.py @@ -7,6 +7,7 @@ from __future__ import annotations import asyncio +from collections import Counter import json import math import re @@ -228,55 +229,49 @@ def _period_name(hour: int) -> str: return "overnight" -def _precip_phrase(total_mm: float, max_hour_mm: float) -> str: - if total_mm < 0.05 and max_hour_mm < 0.05: - return "" - if total_mm < 3.0 and max_hour_mm < 1.2: - return "light rain/showers" - if total_mm < 12.0 and max_hour_mm < 4.0: - return "rain/showers" - return "heavy rain/showers" - - -def _overall_summary(hours: list[dict[str, Any]]) -> str: - if not hours: +def _overall_summary(rows: list[dict[str, Any]]) -> str: + """Describe the day's early sky and most likely precipitation period.""" + if not rows: return "Forecast unavailable" - - third = max(1, len(hours) // 3) - early = hours[:third] - late = hours[-third:] - - def _avg_cloud(items: list[dict[str, Any]]) -> float | None: - values = [float(h["cloud"]) for h in items if _safe_float(h.get("cloud")) is not None] - return (sum(values) / len(values)) if values else None - - early_cloud = _avg_cloud(early) - late_cloud = _avg_cloud(late) - phrases = [f"{_cloud_phrase(early_cloud)} early"] - - precip_hours = [h for h in hours if (_safe_float(h.get("precip_mm")) or 0.0) >= 0.05] - if precip_hours: - total_mm = sum(float(h.get("precip_mm") or 0.0) for h in hours) - max_mm = max(float(h.get("precip_mm") or 0.0) for h in hours) - phrase = _precip_phrase(total_mm, max_mm) - local_hours = [int(h.get("local_hour") or 0) for h in precip_hours] - period_counts: dict[str, int] = {} - for hour in local_hours: - period = _period_name(hour) - period_counts[period] = period_counts.get(period, 0) + 1 - period = sorted(period_counts.items(), key=lambda item: (-item[1], item[0]))[0][0] - if phrase: - phrases.append(f"{phrase} {period}") - - if early_cloud is not None and late_cloud is not None and early_cloud - late_cloud >= 25 and late_cloud < 65: - phrases.append("clearing overnight" if _period_name(int(late[-1].get("local_hour") or 0)) == "overnight" else "clearing late") - elif not precip_hours and late_cloud is not None: - late_phrase = _cloud_phrase(late_cloud) - if late_phrase != _cloud_phrase(early_cloud): - phrases.append(late_phrase.lower() + " late") - - text = ", ".join(dict.fromkeys(phrases)) - return text[:1].upper() + text[1:] + third = max(1, len(rows) // 3) + early_clouds = [float(row["cloud"]) for row in rows[:third] if row.get("cloud") is not None] + average_cloud = sum(early_clouds) / len(early_clouds) if early_clouds else None + if average_cloud is None: + opening = forecast_condition(rows[0]) + elif average_cloud < 20: + opening = "Clear" + elif average_cloud < 45: + opening = "Mostly clear" + elif average_cloud < 75: + opening = "Partly cloudy" + else: + opening = "Cloudy" + wet_rows = [ + row + for row in rows + if row.get("precip_mm", 0) >= 0.05 + or any(word in forecast_condition(row).lower() for word in ("rain", "shower", "snow", "sleet", "thunder")) + ] + if not wet_rows: + late_clouds = [float(row["cloud"]) for row in rows[-third:] if row.get("cloud") is not None] + if late_clouds: + late_average = sum(late_clouds) / len(late_clouds) + late = "Clear" if late_average < 20 else "Mostly clear" if late_average < 45 else "Partly cloudy" if late_average < 75 else "Cloudy" + if late != opening: + return f"{opening} early, {late.lower()} late" + return f"{opening} early" + periods = Counter( + _period_name(int(row.get("local_hour") or 0)) + for row in wet_rows + ) + wet_period = periods.most_common(1)[0][0] + total_mm = sum(float(row.get("precip_mm") or 0) for row in rows) + intensity = "light rain/showers" if total_mm < 3 else "rain/showers" if total_mm < 12 else "heavy rain/showers" + if any(any(word in forecast_condition(row).lower() for word in ("snow", "sleet")) for row in wet_rows): + intensity = "snow/sleet" + elif any("thunder" in forecast_condition(row).lower() for row in wet_rows): + intensity = "thunderstorms" + return f"{opening} early, {intensity} {wet_period}" def _date_label(local_date: date) -> str: @@ -293,6 +288,8 @@ def _summarize_hours(hours: list[dict[str, Any]], *, label: str = "") -> dict[st ] return { "label": label, + "condition": Counter(forecast_condition(row) for row in hours).most_common(1)[0][0] if hours else "Forecast unavailable", + "precip_label": "Snow chance" if any(any(word in forecast_condition(row).lower() for word in ("snow", "sleet")) for row in hours) else "Rain chance", "forecast": _overall_summary(hours), "overall": _overall_summary(hours), "temp_range": _format_temp_range(hours), @@ -324,6 +321,8 @@ def _normalize_hour(record: dict[str, Any], *, tz_name: str) -> dict[str, Any] | "precip_mm": _safe_float(record.get("precip_mm")) or 0.0, "precip_probability": _normalize_probability(record.get("precip_probability")), "symbol": str(record.get("symbol") or "").strip(), + "condition": str(record.get("condition") or ""), + "is_day": bool(record["is_day"]) if record.get("is_day") in (0, 1) else None, } @@ -346,19 +345,17 @@ def normalize_met_forecast(payload: dict[str, Any], *, tz_name: str) -> list[dic precip = None precip_probability = None symbol = "" - for block, divisor in ((next_1h, 1.0), (next_6h, 6.0), (next_12h, 12.0)): + for block in (next_1h, next_6h, next_12h): + if not block: + continue block_details = block.get("details") if isinstance(block.get("details"), dict) else {} - block_precip = _safe_float(block_details.get("precipitation_amount")) - block_probability = _normalize_probability(block_details.get("probability_of_precipitation")) + precip = _safe_float(block_details.get("precipitation_amount")) or 0.0 + precip_probability = _normalize_probability(block_details.get("probability_of_precipitation")) + if precip_probability is None: + precip_probability = 85 if precip >= 1 else 55 if precip > 0 else 5 summary = block.get("summary") if isinstance(block.get("summary"), dict) else {} - if not symbol: - symbol = str(summary.get("symbol_code") or "").strip() - if precip is None and block_precip is not None: - precip = block_precip / divisor - if precip_probability is None and block_probability is not None: - precip_probability = block_probability - if precip is not None and precip_probability is not None: - break + symbol = str(summary.get("symbol_code") or "").strip() + break row = _normalize_hour( { "time": item.get("time"), @@ -369,6 +366,7 @@ def normalize_met_forecast(payload: dict[str, Any], *, tz_name: str) -> list[dic "precip_mm": precip or 0.0, "precip_probability": precip_probability, "symbol": symbol, + "condition": _met_condition(symbol), }, tz_name=tz_name, ) @@ -377,15 +375,54 @@ def normalize_met_forecast(payload: dict[str, Any], *, tz_name: str) -> list[dic return sorted(rows, key=lambda row: row["time"]) -def _open_meteo_symbol(value: object) -> str: - code = _safe_float(value) - if code in (95, 96, 99): - return "Thunderstorms" - if code in (71, 73, 75, 77, 85, 86): - return "Snow" - if code in (51, 53, 55, 56, 57, 61, 63, 65, 66, 67, 80, 81, 82): +def _open_meteo_symbol(code: Any) -> str: + number = int(_safe_float(code) or 0) + if number == 0: + return "Clear" + if number in {1, 2}: + return "Partly cloudy" + if number == 3: + return "Cloudy" + if number in {45, 48}: + return "Fog" + if 51 <= number <= 67: return "Rain" - return {0: "Clear", 1: "Mostly clear", 2: "Partly cloudy", 3: "Overcast", 45: "Fog", 48: "Fog"}.get(code, "") + if 71 <= number <= 77: + return "Snow" + if 80 <= number <= 82: + return "Rain showers" + if 85 <= number <= 86: + return "Snow showers" + if number >= 95: + return "Thunderstorms" + return "Mixed skies" + +def _met_condition(symbol: str) -> str: + text = symbol.replace("_day", "").replace("_night", "").replace("_polartwilight", "") + if "thunder" in text: + return "Thunderstorms" + if "snow" in text or "sleet" in text: + return "Snow showers" + if "rain" in text: + return "Rain showers" + if "fog" in text: + return "Fog" + if "cloudy" in text: + return "Cloudy" if text == "cloudy" else "Partly cloudy" + return "Clear" + +def forecast_condition(row: dict[str, Any]) -> str: + """Return Caelus's provider condition, preserving native NWS wording.""" + if row.get("condition"): + return str(row["condition"]) + symbol = str(row.get("symbol") or "").strip() + if symbol: + if symbol == symbol.lower() and " " not in symbol: + return _met_condition(symbol) + return symbol + if (_safe_float(row.get("precip_mm")) or 0) >= 0.05: + return "Rain showers" + return _cloud_phrase(_safe_float(row.get("cloud"))) def normalize_open_meteo_forecast(payload: dict[str, Any], *, tz_name: str) -> list[dict[str, Any]]: @@ -401,6 +438,7 @@ def normalize_open_meteo_forecast(payload: dict[str, Any], *, tz_name: str) -> l clouds = hourly.get("cloud_cover") winds = hourly.get("wind_speed_10m") codes = hourly.get("weather_code") + daylight = hourly.get("is_day") if not isinstance(times, list): return [] rows: list[dict[str, Any]] = [] @@ -415,6 +453,7 @@ def _at(values: object) -> object: "rh": _at(rhs), "wind_mps": _at(winds), "symbol": _open_meteo_symbol(_at(codes)), + "is_day": _at(daylight), "cloud": _at(clouds), "precip_mm": _at(precip) or 0.0, "precip_probability": _at(precip_probability), @@ -460,23 +499,15 @@ def _nws_wind_speed_mps(value: object) -> float | None: return _mph_to_mps(speed) -def _nws_cloud_fraction(text: object) -> float | None: - forecast = str(text or "").strip().lower() - if not forecast: - return None - if any(word in forecast for word in ("thunder", "rain", "shower", "snow", "sleet", "drizzle")): - return 85.0 - if "mostly cloudy" in forecast: +def _nws_cloud_fraction(condition: str) -> float: + text = condition.lower() + if any(word in text for word in ("thunder", "rain", "shower", "snow", "sleet")): return 85.0 - if "partly cloudy" in forecast or "partly sunny" in forecast: - return 55.0 - if "mostly sunny" in forecast or "mostly clear" in forecast: - return 25.0 - if "cloudy" in forecast or "overcast" in forecast: - return 95.0 - if "sunny" in forecast or "clear" in forecast: - return 8.0 - return None + if "cloud" in text or "overcast" in text: + return 90.0 if "partly" not in text else 55.0 + if "fog" in text: + return 100.0 + return 10.0 def normalize_nws_forecast(payload: dict[str, Any], *, tz_name: str) -> list[dict[str, Any]]: @@ -503,6 +534,8 @@ def normalize_nws_forecast(payload: dict[str, Any], *, tz_name: str) -> list[dic period.get("probabilityOfPrecipitation") ), "symbol": short_forecast, + "condition": short_forecast or "Mixed skies", + "is_day": period.get("isDaytime"), }, tz_name=tz_name, ) @@ -619,12 +652,15 @@ def build_forecast_payload( "stale": False, "retrieved_utc": retrieved.astimezone(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"), "refresh_sec": FORECAST_REFRESH_SEC, + "condition_format": 1, "location": { "latitude": latitude, "longitude": longitude, "timezone": tz_name, "source": location_source, }, + "today": _summarize_hours(grouped.get(today_key) or next_24, label="Today"), + "today_hourly": grouped.get(today_key) or next_24, "current_24h": _summarize_hours(next_24, label="24 Hour Forecast") if next_24 else {}, "days": days, "hourly": next_24, @@ -719,6 +755,8 @@ def load_weather_forecast_cache( def _cache_age_sec(payload: dict[str, Any]) -> float | None: + if payload.get("condition_format") != 1: + return None retrieved = _parse_datetime(payload.get("retrieved_utc"), tz_name="UTC") if retrieved is None: return None @@ -739,31 +777,13 @@ async def _fetch_primary() -> list[dict[str, Any]]: resp.raise_for_status() return normalize_met_forecast(resp.json(), tz_name=tz_name) - async def _fetch_probability_supplement() -> list[dict[str, Any]]: - try: - return await _fetch_open_meteo_forecast( - latitude, - longitude, - tz_name=tz_name, - timeout_sec=timeout_sec, - ) - except Exception as exc: - if DEBUG: - printDM(f"MET probability supplement failed: {exc}", location=MODULE) - return [] - - # MET Norway does not publish precipitation probability for every global - # model location. Use timestamp-matched Open-Meteo probabilities only for - # missing values; all other forecast fields remain sourced from MET. - rows, supplemental = await asyncio.gather(_fetch_primary(), _fetch_probability_supplement()) - supplement_precipitation_probabilities(rows, supplemental) - return rows + return await _fetch_primary() async def _fetch_open_meteo_forecast(latitude: float, longitude: float, *, tz_name: str, timeout_sec: float) -> list[dict[str, Any]]: hourly = ( "temperature_2m,relative_humidity_2m,precipitation," - "precipitation_probability,cloud_cover,wind_speed_10m,weather_code" + "precipitation_probability,cloud_cover,wind_speed_10m,weather_code,is_day" ) async with httpx.AsyncClient(timeout=timeout_sec, headers={"User-Agent": USER_AGENT}, follow_redirects=True) as client: resp = await client.get( diff --git a/sensorius/saiWeatherForecastApp.py b/sensorius/saiWeatherForecastApp.py index f068c84..2bf1579 100644 --- a/sensorius/saiWeatherForecastApp.py +++ b/sensorius/saiWeatherForecastApp.py @@ -7,6 +7,7 @@ from __future__ import annotations import asyncio +from collections import Counter import math import re from datetime import datetime @@ -15,6 +16,9 @@ from urllib.parse import urlencode from zoneinfo import ZoneInfo +from astral import Observer +from astral.sun import elevation as sun_elevation + from fastapi import APIRouter, Request from fastapi.responses import HTMLResponse, JSONResponse @@ -28,7 +32,7 @@ ) from .saiSensorSettingsManager import SensorSettingsManager from .saiWeatherAstronomy import astronomy_context -from .saiWeatherForecast import get_weather_forecast_payload +from .saiWeatherForecast import forecast_condition, get_weather_forecast_payload from .saiThemeManager import ThemeManager, normalize_theme_selection from .sensor_modules.station_ecowitt import DEFAULT_POLL_INTERVAL_SEC as ECOWITT_DEFAULT_POLL_INTERVAL_SEC from .sensor_modules.station_weewx import DEFAULT_UPDATE_PERIOD_SEC as WEEWX_DEFAULT_UPDATE_PERIOD_SEC @@ -158,7 +162,7 @@ def _condition_icon(text: object) -> str: return "🌧️" if "fog" in value: return "🌫️" - if "partly" in value or "mostly clear" in value: + if "partly" in value: return "🌤️" if "cloud" in value or "overcast" in value: return "☁️" @@ -176,16 +180,44 @@ def _condition_icon_key(text: object) -> str: return "rain" if "fog" in value: return "fog" - if "partly" in value or "mostly clear" in value: + if "partly" in value: return "partly-cloudy" if "cloud" in value or "overcast" in value: return "cloudy" return "sunny" +def _hour_icon_key(row: dict[str, Any], location: dict[str, Any]) -> str: + """Choose bundled hourly artwork using provider daylight or solar position.""" + key = _condition_icon_key(forecast_condition(row)) + if key not in ("sunny", "partly-cloudy"): + return key + is_day = row.get("is_day") + if not isinstance(is_day, bool): + symbol = str(row.get("symbol") or "") + if symbol.endswith("_night"): + is_day = False + elif symbol.endswith("_day"): + is_day = True + else: + try: + at = datetime.fromisoformat(str(row.get("local_time") or row.get("time")).replace("Z", "+00:00")) + if at.tzinfo is None: + at = at.replace(tzinfo=ZoneInfo(str(location.get("timezone") or "UTC"))) + observer = Observer(latitude=float(location["latitude"]), longitude=float(location["longitude"])) + is_day = sun_elevation(observer, at, with_refraction=False) > -0.833 + except (KeyError, TypeError, ValueError): + # Legacy or incomplete offline payloads retain daytime artwork. + is_day = True + if not is_day: + return "clear-night" if key == "sunny" else "partly-cloudy-night" + return key + + def _precipitation_chance_label(condition: object) -> str: """Name a precipitation probability as a rain or snow chance.""" - return "Snow chance" if _condition_icon_key(condition) == "snow" else "Rain chance" + text = str(condition or "").lower() + return "Snow chance" if "snow" in text or "sleet" in text else "Rain chance" def _hour_temperature_f(hour: dict[str, Any]) -> float | None: @@ -281,31 +313,8 @@ def format_observation_time(value: object, timezone_name: str) -> str: def _hour_window_condition(hours: list[dict[str, Any]]) -> str: - """Describe one displayed hourly window without borrowing the daily summary.""" - symbols = [str(row.get("symbol") or "").strip() for row in hours] - lowered_symbols = [symbol.lower() for symbol in symbols if symbol] - if any("thunder" in symbol for symbol in lowered_symbols): - return "Thunderstorms" - if any(any(token in symbol for token in ("snow", "sleet")) for symbol in lowered_symbols): - return "Snow" - - precipitation_mm = sum(_safe_float(row.get("precip_mm")) or 0.0 for row in hours) - if precipitation_mm >= 0.05: - return "Rain/showers" - if any(any(token in symbol for token in ("rain", "shower", "drizzle")) for symbol in lowered_symbols): - return next(symbol for symbol in symbols if symbol) - if any(symbols): - return next(symbol for symbol in symbols if symbol) - - cloud_values = [value for value in (_safe_float(row.get("cloud")) for row in hours) if value is not None] - average_cloud = sum(cloud_values) / len(cloud_values) if cloud_values else None - if average_cloud is None: - return "Forecast unavailable" - if average_cloud >= 85.0: - return "Cloudy" - if average_cloud >= 35.0: - return "Partly cloudy" - return "Clear" + """Select the most common provider condition, as in standalone Caelus.""" + return Counter(forecast_condition(row) for row in hours).most_common(1)[0][0] if hours else "Forecast unavailable" def _forecast_synopsis(hours: list[dict[str, Any]], unit_system: str, provider: str) -> str: @@ -314,11 +323,8 @@ def _forecast_synopsis(hours: list[dict[str, Any]], unit_system: str, provider: return "" if provider == "us" and hours[0].get("narrative"): return f"{hours[0].get('narrative_period') or 'Forecast period'} (NWS · original units): {hours[0]['narrative']}" - names = {"sunny": "Clear", "partly-cloudy": "Partly cloudy", "cloudy": "Overcast", - "rain": "Rain", "snow": "Snow", "thunder": "Thunderstorms", "fog": "Fog"} def condition(row): - value = _hour_window_condition([row]) - return "Conditions unavailable" if value == "Forecast unavailable" else names[_condition_icon_key(value)] + return _hour_window_condition([row]) def when(row): value = str(row.get("local_time") or row.get("time") or "") first = str(hours[0].get("local_time") or hours[0].get("time") or "") @@ -352,7 +358,8 @@ def build_weather_display_forecast( ) -> dict[str, Any]: """Adapt the canonical Sensorius forecast payload for the full-screen UI.""" display_unit_system = normalize_display_unit_system(unit_system) - current = payload.get("current_24h") if isinstance(payload.get("current_24h"), dict) else {} + current = payload.get("today") or payload.get("current_24h") or {} + today_hours = payload.get("today_hourly") or payload.get("hourly") or [] raw_hours = payload.get("hourly") if isinstance(payload.get("hourly"), list) else [] hours = [] normalized_hours = [row for row in raw_hours[:24] if isinstance(row, dict)] @@ -370,11 +377,12 @@ def build_weather_display_forecast( hours.append( { "label": label, + "condition": condition, "humidity": round(rh) if (rh := _safe_float(raw.get("rh"))) is not None else None, "wind_speed": round(wind) if (wind := _forecast_display_value(raw.get("wind_mps"), "Wind Speed", "m/s", display_unit_system)[0]) is not None else None, "wind_unit": _forecast_display_value(None, "Wind Speed", "m/s", display_unit_system)[1], "icon": _condition_icon(condition), - "icon_key": _condition_icon_key(condition), + "icon_key": _hour_icon_key(raw, payload.get("location") or {}), "precip_label": _precipitation_chance_label(condition), "temperature_f": round(temp_f) if temp_f is not None else None, "temperature": round(temperature) if temperature is not None else None, @@ -398,9 +406,10 @@ def build_weather_display_forecast( "date": str(raw.get("date") or ""), "label": str(raw.get("label") or raw.get("date") or "Day"), "summary": summary, - "icon": _condition_icon(summary), - "icon_key": _condition_icon_key(summary), - "precip_label": _precipitation_chance_label(summary), + "condition": str(raw.get("condition") or summary), + "icon": _condition_icon(raw.get("condition") or summary), + "icon_key": _condition_icon_key(raw.get("condition") or summary), + "precip_label": raw.get("precip_label") or _precipitation_chance_label(summary), "temp_range": _forecast_temperature_range(raw.get("temp_range"), display_unit_system), "rh_range": str(raw.get("rh_range") or "--"), "wind": _forecast_wind(raw.get("wind"), display_unit_system), @@ -412,17 +421,17 @@ def build_weather_display_forecast( } ) - temp_values = [value for value in (_hour_temperature_f(row) for row in raw_hours) if value is not None] + temp_values = [value for value in (_hour_temperature_f(row) for row in today_hours) if value is not None] display_temp_values = [ converted - for row in raw_hours + for row in today_hours if (converted := _forecast_display_value( row.get("temp_c"), "Temperature", "°C", display_unit_system )[0]) is not None ] temperature_unit = _forecast_display_value(None, "Temperature", "°C", display_unit_system)[1] precipitation, precipitation_unit = _forecast_display_value( - sum(_safe_float(row.get("precip_mm")) or 0.0 for row in raw_hours), + sum(_safe_float(row.get("precip_mm")) or 0.0 for row in today_hours), "Rain", "mm", display_unit_system, @@ -435,7 +444,7 @@ def build_weather_display_forecast( current_probability = _safe_float(current.get("precip_probability")) if current_probability is None and probabilities: current_probability = max(probabilities) - condition = str(current.get("overall") or current.get("forecast") or "Forecast standing by") + condition = str(current.get("condition") or _hour_window_condition(today_hours)) return { "ok": bool(payload.get("ok")), "provider": str(payload.get("provider") or ""), @@ -447,17 +456,15 @@ def build_weather_display_forecast( "condition": condition, "synopsis": _forecast_synopsis(normalized_hours, display_unit_system, str(payload.get("provider") or "")) or condition, "wind_range": _forecast_wind(current.get("wind"), display_unit_system, include_description=False), - "icon": _condition_icon(_hour_window_condition(normalized_hours[:3]) if normalized_hours else condition), - "icon_key": _condition_icon_key( - _hour_window_condition(normalized_hours[:3]) if normalized_hours else condition - ), - "precip_label": _precipitation_chance_label(condition), + "icon": _condition_icon(condition), + "icon_key": _condition_icon_key(condition), + "precip_label": current.get("precip_label") or _precipitation_chance_label(condition), "high_f": round(max(temp_values)) if temp_values else None, "low_f": round(min(temp_values)) if temp_values else None, "high": round(max(display_temp_values)) if display_temp_values else None, "low": round(min(display_temp_values)) if display_temp_values else None, "temperature_unit": temperature_unit, - "precipitation_mm": round(sum(_safe_float(row.get("precip_mm")) or 0.0 for row in raw_hours), 1), + "precipitation_mm": round(sum(_safe_float(row.get("precip_mm")) or 0.0 for row in today_hours), 1), "precipitation": round(precipitation or 0.0, 2), "precipitation_unit": precipitation_unit, "precip_probability": round(current_probability) if current_probability is not None else None, diff --git a/testApparatus/test_integrated_weather_forecast.py b/testApparatus/test_integrated_weather_forecast.py index c3f95f2..54cf8f2 100644 --- a/testApparatus/test_integrated_weather_forecast.py +++ b/testApparatus/test_integrated_weather_forecast.py @@ -505,8 +505,8 @@ def test_open_meteo_hourly_rows_do_not_show_rain_until_precipitation_hour(): display = weather_app.build_weather_display_forecast(payload) - assert display["icon"] == "☀️" - assert display["icon_key"] == "sunny" + assert display["icon"] == "☁️" + assert display["icon_key"] == "cloudy" assert len(display["hours"]) == 13 assert [row["precipitation_mm"] for row in display["hours"][:10]] == [0.0] * 10 assert display["hours"][10]["precipitation_mm"] == 2.9 @@ -586,8 +586,9 @@ async def _fake_forecast(*_args, **_kwargs): assert "Updated from" not in page.text assert "data-open-forecast" not in page.text assert "PoP" not in page.text - assert 'class="forecast-icon forecast-icon--rain"' in page.text - assert 'class="forecast-icon forecast-icon--sunny"' in page.text + assert 'class="forecast-glyph"' in page.text + assert "/glyphs/partly-cloudy.svg?" in page.text + assert "/glyphs/sunny.svg?" in page.text assert current.json()["sensor_id"] == "nodus-weather" assert current.json()["location"] == "Kitchen Garden" assert current.json()["refresh_interval_sec"] == 60 @@ -867,7 +868,7 @@ def test_synopsis_uses_local_transition_time_units_and_missing_values(): {"local_time": "2026-09-11T00:00:00-06:00", "temp_c": 20, "symbol": "snow", "wind_mps": 4, "rh": 60, "precip_probability": 75}, ]} metric = weather_app.build_weather_display_forecast(payload, "Metric") - assert "then snow around 12 AM next day" in metric["synopsis"] + assert "then snow showers around 12 AM next day" in metric["synopsis"] assert "10–20°C" in metric["synopsis"] assert "14 km/h" in metric["synopsis"] assert "75% around 12 AM next day" in metric["synopsis"] @@ -893,3 +894,38 @@ def test_synopsis_prefers_nws_native_text_with_generated_fallback(): assert result["synopsis"] == "This Afternoon (NWS · original units): Sunny, with a high near 80." del payload["hourly"][0]["narrative"] assert "Temperatures 20–20°C" in weather_app.build_weather_display_forecast(payload, "Metric")["synopsis"] + + +@pytest.mark.parametrize('symbol,is_day,expected', [ + ('clearsky_night', None, 'clear-night'), + ('partlycloudy_night', None, 'partly-cloudy-night'), + ('clearsky_day', None, 'sunny'), + ('partlycloudy_day', None, 'partly-cloudy'), + ('Clear', False, 'clear-night'), + ('Partly cloudy', False, 'partly-cloudy-night'), + ('Clear', True, 'sunny'), + ('Rain', False, 'rain'), + ('Snow', False, 'snow'), + ('Thunderstorms', False, 'thunder'), + ('Fog', False, 'fog'), + ('Cloudy', False, 'cloudy'), +]) +def test_hourly_glyphs_use_provider_daylight(symbol, is_day, expected): + payload = _forecast_payload() + payload['hourly'] = [{**payload['hourly'][0], 'symbol': symbol, 'is_day': is_day}] + display = weather_app.build_weather_display_forecast(payload) + assert display['hours'][0]['icon_key'] == expected + assert display['days'][0]['icon_key'] == 'sunny' + + +@pytest.mark.parametrize('timestamp,latitude,expected', [ + ('2026-09-15T00:00:00+00:00', 0, 'clear-night'), + ('2026-09-15T12:00:00+00:00', 0, 'sunny'), + ('2026-06-21T00:00:00+00:00', 89, 'sunny'), + ('2026-12-21T12:00:00+00:00', 89, 'clear-night'), +]) +def test_hourly_glyph_solar_fallback_handles_polar_day_and_night(timestamp, latitude, expected): + assert weather_app._hour_icon_key( + {'symbol': 'Clear', 'time': timestamp}, + {'latitude': latitude, 'longitude': 0, 'timezone': 'UTC'}, + ) == expected diff --git a/testApparatus/test_weather_forecast.py b/testApparatus/test_weather_forecast.py index b2b1fe7..2d6fb23 100644 --- a/testApparatus/test_weather_forecast.py +++ b/testApparatus/test_weather_forecast.py @@ -117,7 +117,7 @@ def test_met_forecast_is_summarized_for_dashboard_card(): assert current["rh_range"] == "34-64%" assert "Cloudy early" in current["overall"] assert "light rain/showers afternoon" in current["overall"] - assert "clearing overnight" in current["overall"] + assert current["overall"] == "Cloudy early, light rain/showers afternoon" assert current["precip_probability"] == 65 assert payload["hourly"][0]["precip_probability"] == 10.0 @@ -126,7 +126,7 @@ def test_met_forecast_is_summarized_for_dashboard_card(): assert first_day["temp_range"] == "15.1-26.5°C / 59-80°F" -def test_met_probability_can_come_from_longer_block_than_hourly_amount(): +def test_met_probability_uses_same_period_as_condition_and_amount(): item = _sample_met_payload()["properties"]["timeseries"][0] item["data"]["next_1_hours"]["details"].pop("probability_of_precipitation") item["data"]["next_6_hours"] = { @@ -143,7 +143,7 @@ def test_met_probability_can_come_from_longer_block_than_hourly_amount(): ) assert hourly[0]["precip_mm"] == 0.0 - assert hourly[0]["precip_probability"] == 68.0 + assert hourly[0]["precip_probability"] == 5.0 def test_weather_forecast_provider_normalization(): @@ -360,3 +360,53 @@ def respond(request): assert len(rows) == 1 assert rows[0]["temp_c"] == 20 assert ("narrative" in rows[0]) == (narrative_status == 200) + + +@pytest.mark.parametrize('code,condition', [(0, 'Clear'), (1, 'Partly cloudy'), (2, 'Partly cloudy'), (3, 'Cloudy'), (45, 'Fog'), (51, 'Rain'), (80, 'Rain showers'), (71, 'Snow'), (85, 'Snow showers'), (95, 'Thunderstorms')]) +def test_caelus_weather_code_conditions(code, condition): + from sensorius.saiWeatherForecast import _open_meteo_symbol + assert _open_meteo_symbol(code) == condition + + +def test_caelus_met_period_totals_and_conditions(): + payload = {'properties': {'timeseries': [{'time': '2026-09-15T12:00:00Z', 'data': { + 'instant': {'details': {'air_temperature': 10}}, + 'next_6_hours': {'summary': {'symbol_code': 'sleetshowers_day'}, 'details': {'precipitation_amount': 6}}, + }}]}} + row = normalize_met_forecast(payload, tz_name='UTC')[0] + assert row['precip_mm'] == 6 + assert row['precip_probability'] == 85 + assert row['condition'] == 'Snow showers' + + +def test_caelus_today_and_daily_condition_are_independent_of_summary(): + from sensorius.saiWeatherForecast import _normalize_hour + from sensorius.saiWeatherForecastApp import build_weather_display_forecast + rows = [_normalize_hour({'time': time, 'temp_c': temp, 'symbol': symbol, 'cloud': 10, 'precip_mm': 0.2}, tz_name='UTC') + for time, temp, symbol in [('2026-09-15T23:00:00Z', 10, 'fair_night'), + ('2026-09-16T00:00:00Z', 30, 'clearsky_night'), + ('2026-09-16T01:00:00Z', 20, 'clearsky_night'), + ('2026-09-16T02:00:00Z', 15, 'snowshowers_night')]] + payload = build_forecast_payload(provider='met_no', latitude=1, longitude=1, tz_name='UTC', hourly=rows, retrieved_utc='2026-09-15T23:00:00Z') + display = build_weather_display_forecast(payload) + assert display['condition'] == 'Clear' + assert display['high_f'] == 50 + assert len(display['hours']) == 4 + assert display['hours'][0]['icon'] == '☀️' # Provider code wins over trace precipitation. + assert display['days'][0]['condition'] == 'Clear' + assert display['days'][0]['icon'] == '☀️' + assert 'snow/sleet' in display['days'][0]['summary'] + assert display['days'][0]['precip_label'] == 'Snow chance' + + +def test_provider_daylight_flags_survive_normalization(): + meteo = normalize_open_meteo_forecast({'hourly': { + 'time': ['2026-09-15T00:00', '2026-09-15T12:00'], + 'temperature_2m': [10, 20], 'weather_code': [0, 2], 'is_day': [0, 1], + }}, tz_name='UTC') + assert [row['is_day'] for row in meteo] == [False, True] + nws = normalize_nws_forecast({'properties': {'periods': [{ + 'startTime': '2026-09-15T00:00:00Z', 'temperature': 50, + 'temperatureUnit': 'F', 'shortForecast': 'Clear', 'isDaytime': False, + }]}}, tz_name='UTC') + assert nws[0]['is_day'] is False diff --git a/tests/weather-forecast.spec.js b/tests/weather-forecast.spec.js index 7f36883..c6648c9 100644 --- a/tests/weather-forecast.spec.js +++ b/tests/weather-forecast.spec.js @@ -15,7 +15,7 @@ for (const budget of cardBudgets) { const card = page.locator('.forecast-panel'); await expect(card).not.toContainText('Updated from'); await expect(card.getByRole('button', { name: '6-day details' })).toHaveCount(0); - await expect(card.locator('.forecast-synopsis')).toContainText('then rain around 8 PM'); + await expect(card.locator('.forecast-synopsis')).toContainText('then rain showers around 8 PM'); await expect(card.locator('.forecast-hour:visible').first()).toContainText('RH 55%'); await expect(card.locator('.forecast-hour:visible').first()).toContainText(units === 'Metric' ? 'Wind 14 km/h' : 'Wind 9 mph'); const originalHeight = (await card.boundingBox()).height; @@ -23,7 +23,7 @@ for (const budget of cardBudgets) { await expect(days).toHaveCount(6); for (const day of await days.all()) { await expect(day.locator('time')).toBeVisible(); - await expect(day.locator('svg')).toBeVisible(); + await expect(day.locator('.forecast-glyph')).toBeVisible(); await expect(day).toContainText(units === 'Metric' ? '17.8-30.0°C' : '64-86°F'); await expect(day).toContainText('RH 35-85%'); await expect(day).toContainText(units === 'Metric' ? 'Wind 4-29 km/h' : 'Wind 2-18 mph'); @@ -44,3 +44,19 @@ for (const budget of cardBudgets) { } }); } + + +test('all nine bundled glyphs render without remote assets or emoji fonts', async ({ page }, testInfo) => { + await page.route('**/*', route => { + const url = new URL(route.request().url()); + return ['127.0.0.1', 'localhost'].includes(url.hostname) ? route.continue() : route.abort(); + }); + await page.goto('/weather-forecast'); + const glyphs = ['sunny', 'partly-cloudy', 'cloudy', 'rain', 'snow', 'thunder', 'fog', 'clear-night', 'partly-cloudy-night']; + await page.setContent(`${glyphs.map(key => `
${key}
${key}
`).join('')}`); + await page.locator('img').evaluateAll(images => Promise.all(images.map(image => image.decode()))); + for (const img of await page.locator('img').all()) { + expect(await img.evaluate(image => image.naturalWidth)).toBeGreaterThan(0); + } + await page.screenshot({ path: testInfo.outputPath('nine-weather-glyphs.png') }); +}); diff --git a/ui_static/weather_forecast/app.css b/ui_static/weather_forecast/app.css index ecc7617..7b8c2db 100644 --- a/ui_static/weather_forecast/app.css +++ b/ui_static/weather_forecast/app.css @@ -527,13 +527,8 @@ body.caelus-theme-preview-mode .dashboard-return { opacity: 0; pointer-events: n .readings-footer { width: 100%; margin-top: auto; padding: 0.85rem 0 0.1rem; border-top: 1px solid var(--line); box-sizing: border-box; } .provider-label { color: var(--accent-2); font-size: 0.62rem; letter-spacing: 0.08em; text-transform: uppercase; } .forecast-summary { display: grid; grid-template-columns: 3rem minmax(0, 1fr); align-items: center; gap: 1rem; min-height: 8.4rem; border-bottom: 1px solid var(--line); } -.forecast-main-icon { font-size: 2.6rem; text-align: center; line-height: 0; } -.forecast-icon { width: 1em; height: 1em; overflow: visible; } -.forecast-icon-sun { fill: #ffd23f; stroke: #ffbd20; stroke-width: 3; stroke-linecap: round; } -.forecast-icon-cloud { fill: #edf5f7; stroke: #bad2d8; stroke-width: 1.5; stroke-linejoin: round; } -.forecast-icon-rain, .forecast-icon-fog { fill: none; stroke: #52c7ff; stroke-width: 4; stroke-linecap: round; } -.forecast-icon-snow { fill: none; stroke: #dff7ff; stroke-width: 2.5; stroke-linecap: round; } -.forecast-icon-bolt { fill: #ffd23f; stroke: #ffad1f; stroke-width: 1; stroke-linejoin: round; } +.forecast-main-icon { font-size: 2.6rem; text-align: center; line-height: 1.2; } +.forecast-glyph { width: 1em; height: 1em; vertical-align: middle; } .forecast-summary-content { min-width: 0; } .forecast-ranges { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.3rem; } .forecast-ranges > span { color: var(--muted); font-size: 0.52rem; text-align: center; } diff --git a/ui_static/weather_forecast/glyphs/LICENSE-GRAPHICS b/ui_static/weather_forecast/glyphs/LICENSE-GRAPHICS new file mode 100644 index 0000000..dc8853a --- /dev/null +++ b/ui_static/weather_forecast/glyphs/LICENSE-GRAPHICS @@ -0,0 +1,393 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/ui_static/weather_forecast/glyphs/README.md b/ui_static/weather_forecast/glyphs/README.md new file mode 100644 index 0000000..943f720 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/README.md @@ -0,0 +1,14 @@ +# Weather glyphs + +Eight original SVGs from Twemoji v17.0.2 by Twitter and other contributors: +https://github.com/jdecked/twemoji/tree/v17.0.2/assets/svg + +Licensed under CC BY 4.0: https://creativecommons.org/licenses/by/4.0/ +The full license is included in LICENSE-GRAPHICS. + +Mapping: sunny=2600, partly-cloudy=1f324, cloudy=2601, rain=1f327, +snow=1f328, thunder=26c8, fog=1f32b, clear-night=1f319. + +partly-cloudy-night.svg is a Sensorius adaptation combining the crescent +moon (1f319) and foreground cloud (2601), scaled and positioned together. +It is also distributed under CC BY 4.0. The other artwork is unmodified. diff --git a/ui_static/weather_forecast/glyphs/clear-night.svg b/ui_static/weather_forecast/glyphs/clear-night.svg new file mode 100644 index 0000000..d98dc2f --- /dev/null +++ b/ui_static/weather_forecast/glyphs/clear-night.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/cloudy.svg b/ui_static/weather_forecast/glyphs/cloudy.svg new file mode 100644 index 0000000..928baa6 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/cloudy.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/fog.svg b/ui_static/weather_forecast/glyphs/fog.svg new file mode 100644 index 0000000..fe6e480 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/fog.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/partly-cloudy-night.svg b/ui_static/weather_forecast/glyphs/partly-cloudy-night.svg new file mode 100644 index 0000000..acf21bc --- /dev/null +++ b/ui_static/weather_forecast/glyphs/partly-cloudy-night.svg @@ -0,0 +1 @@ + diff --git a/ui_static/weather_forecast/glyphs/partly-cloudy.svg b/ui_static/weather_forecast/glyphs/partly-cloudy.svg new file mode 100644 index 0000000..8ba8c52 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/partly-cloudy.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/rain.svg b/ui_static/weather_forecast/glyphs/rain.svg new file mode 100644 index 0000000..99f42f5 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/rain.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/snow.svg b/ui_static/weather_forecast/glyphs/snow.svg new file mode 100644 index 0000000..f937107 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/snow.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/sunny.svg b/ui_static/weather_forecast/glyphs/sunny.svg new file mode 100644 index 0000000..8602bae --- /dev/null +++ b/ui_static/weather_forecast/glyphs/sunny.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_static/weather_forecast/glyphs/thunder.svg b/ui_static/weather_forecast/glyphs/thunder.svg new file mode 100644 index 0000000..878ba81 --- /dev/null +++ b/ui_static/weather_forecast/glyphs/thunder.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/ui_templates/weather_forecast/index.html b/ui_templates/weather_forecast/index.html index 2f6b22a..6b64226 100644 --- a/ui_templates/weather_forecast/index.html +++ b/ui_templates/weather_forecast/index.html @@ -12,23 +12,7 @@ {% macro reading(value, suffix='') -%}{{ value if value is not none else '—' }}{{ suffix if value is not none else '' }}{%- endmacro %} {% macro weather_icon(kind, label) -%} - - {% if kind in ('sunny', 'partly-cloudy') %} - - {% endif %} - {% if kind != 'sunny' %} - - {% endif %} - {% if kind == 'rain' %} - - {% elif kind == 'snow' %} - - {% elif kind == 'thunder' %} - - {% elif kind == 'fog' %} - - {% endif %} - + {{ label }} {%- endmacro %} @@ -82,7 +66,7 @@

{{ location.name or 'Your weather, alive.' }}

{% set hour_count = forecast.hours | length %}

Hours 1–{{ 8 if hour_count > 8 else hour_count }} of {{ hour_count }}

@@ -93,7 +77,7 @@

{{ location.name or 'Your weather, alive.' }}

{% for day in forecast.days %}
- {{ weather_icon(day.icon_key, day.summary) }} + {{ weather_icon(day.icon_key, day.condition) }} {{ day.temp_range }} RH {{ day.rh_range }} Wind {{ day.wind_range }}