merge: clean predictor debt

# Conflicts:
#	predictor/rules.py
This commit is contained in:
dasemu committed 2026-03-13 10:52:48 +01:00
commit a70eff3e45
10 files changed
+266 -64

No files matched your search

+20 -4
View File
@@ -6,10 +6,10 @@ import logging
import os import os
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import bcrypt
import jwt import jwt
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from app.api.schemas import TokenResponse, UserCreate, UserResponse from app.api.schemas import TokenResponse, UserCreate, UserResponse
from storage import SQLiteStore from storage import SQLiteStore
@@ -19,7 +19,6 @@ logger = logging.getLogger(__name__)
_TOKEN_EXPIRE_DAYS = 14 _TOKEN_EXPIRE_DAYS = 14
_ALGORITHM = "HS256" _ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"]) auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
@@ -43,6 +42,23 @@ def _create_token(user_id: int, email: str) -> str:
return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM) return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM)
def _hash_password(password: str) -> str:
"""Return a bcrypt password hash."""
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def _verify_password(password: str, password_hash: str) -> bool:
"""Validate a plaintext password against a stored bcrypt hash."""
try:
return bcrypt.checkpw(
password.encode("utf-8"),
password_hash.encode("utf-8"),
)
except ValueError:
logger.warning("Encountered an invalid stored password hash.")
return False
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict: def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
"""FastAPI dependency that validates the JWT and returns user info.""" """FastAPI dependency that validates the JWT and returns user info."""
try: try:
@@ -82,7 +98,7 @@ def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
def register(body: UserCreate) -> UserResponse: def register(body: UserCreate) -> UserResponse:
"""Create a new user account.""" """Create a new user account."""
store = SQLiteStore() store = SQLiteStore()
hashed = pwd_context.hash(body.password) hashed = _hash_password(body.password)
now_iso = datetime.now(timezone.utc).isoformat() now_iso = datetime.now(timezone.utc).isoformat()
with store.connect() as conn: with store.connect() as conn:
@@ -117,7 +133,7 @@ def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse:
(form.username,), (form.username,),
).fetchone() ).fetchone()
if row is None or not pwd_context.verify(form.password, row["password_hash"]): if row is None or not _verify_password(form.password, row["password_hash"]):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials", detail="invalid credentials",
+19 -17
View File
@@ -7,7 +7,7 @@ reuse the same pipeline components as ``scripts/collect_daily_data.py``.
from __future__ import annotations from __future__ import annotations
import logging import logging
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timezone
from typing import Any from typing import Any
import pandas as pd import pandas as pd
@@ -18,7 +18,9 @@ from pipeline.build_dataset import DatasetBuilder
from pipeline.feature_engineering import FeatureEngineer from pipeline.feature_engineering import FeatureEngineer
from predictor.hybrid_predictor import HybridPredictor from predictor.hybrid_predictor import HybridPredictor
from scripts.collect_daily_data import ( from scripts.collect_daily_data import (
_available_prediction_dates,
_load_prediction_feature_base, _load_prediction_feature_base,
_select_forecast_row_for_date,
_select_feature_anchor_row, _select_feature_anchor_row,
) )
from scripts.retrain_model import main as retrain_main from scripts.retrain_model import main as retrain_main
@@ -75,7 +77,7 @@ def run_forecast_cycle(run_hour: int) -> None:
# 3. Scrape station status # 3. Scrape station status
scraper = StationScraper() scraper = StationScraper()
station_records: list[dict[str, Any]] = [] station_records: list[dict[str, Any]] = []
for station_id in scraper._stations: for station_id in scraper.station_ids:
try: try:
record = scraper.scrape_station(station_id) record = scraper.scrape_station(station_id)
station_records.append(record) station_records.append(record)
@@ -116,12 +118,14 @@ def run_forecast_cycle(run_hour: int) -> None:
# 5. Determine forecast dates # 5. Determine forecast dates
base_date = date.today() base_date = date.today()
if run_hour >= 15: forecast_dates = _available_prediction_dates(
# Skip today, start from tomorrow weather_by_station,
forecast_dates = [base_date + timedelta(days=d) for d in range(1, 8)] base_date=base_date,
else: include_today=run_hour < 15,
# Include today )
forecast_dates = [base_date + timedelta(days=d) for d in range(8)] if not forecast_dates:
logger.error("No usable forecast dates were returned by the weather provider.")
return
# 6. Generate predictions # 6. Generate predictions
predictor = HybridPredictor() predictor = HybridPredictor()
@@ -131,16 +135,14 @@ def run_forecast_cycle(run_hour: int) -> None:
for station_id, weather_df in weather_by_station.items(): for station_id, weather_df in weather_by_station.items():
station_rec = station_map.get(station_id, {}) station_rec = station_map.get(station_id, {})
for target_date in forecast_dates: for target_date in forecast_dates:
days_ahead = (target_date - base_date).days weather_data = _select_forecast_row_for_date(
target_rows = weather_df[weather_df["date"] == target_date] weather_df,
if target_rows.empty: station_id=station_id,
idx = max(0, min(days_ahead, len(weather_df) - 1)) target_date=target_date,
target_rows = weather_df.iloc[idx : idx + 1] )
if target_rows.empty: if weather_data is None:
continue continue
weather_data = target_rows.iloc[0].to_dict()
# Build feature row # Build feature row
features_df = None features_df = None
if not feature_base_df.empty: if not feature_base_df.empty:
@@ -258,7 +260,7 @@ def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
today_iso = date.today().isoformat() today_iso = date.today().isoformat()
records: list[dict[str, Any]] = [] records: list[dict[str, Any]] = []
for station_id in scraper._stations: for station_id in scraper.station_ids:
try: try:
data = scraper.scrape_station(station_id) data = scraper.scrape_station(station_id)
records.append( records.append(
+23 -17
View File
@@ -23,6 +23,8 @@ from pathlib import Path
from typing import Any from typing import Any
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
import yaml
# Ensure the project root is importable when the bot is launched as a script # Ensure the project root is importable when the bot is launched as a script
# (e.g. ``python bot/telegram_bot.py`` from start.sh or systemd). # (e.g. ``python bot/telegram_bot.py`` from start.sh or systemd).
_BOT_DIR = Path(__file__).resolve().parent _BOT_DIR = Path(__file__).resolve().parent
@@ -51,25 +53,29 @@ logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING) logging.getLogger("httpcore").setLevel(logging.WARNING)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Station metadata (mirrors config/stations.yaml without adding a runtime # Station metadata
# dependency on pyyaml inside the bot module itself).
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
STATIONS = { _STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml"
"pajares": {
"name": "Valgrande-Pajares",
"max_km": 22.0, def _load_station_metadata() -> dict[str, dict[str, Any]]:
}, """Load bot-visible station metadata from the shared YAML config."""
"sanisidro": { with _STATIONS_YAML.open("r", encoding="utf-8") as fh:
"name": "San Isidro", raw = yaml.safe_load(fh) or {}
"max_km": 31.0,
}, stations = raw.get("stations") or {}
"fuentes": { return {
"name": "Fuentes de Invierno", station_id: {
"max_km": 8.6, "name": station_cfg["name"],
}, "max_km": float(station_cfg["max_km_skiable"]),
} }
STATION_ORDER = ("pajares", "sanisidro", "fuentes") for station_id, station_cfg in stations.items()
}
STATIONS = _load_station_metadata()
STATION_ORDER = tuple(STATIONS.keys())
DISPLAY_TIMEZONE = ZoneInfo("Europe/Madrid") DISPLAY_TIMEZONE = ZoneInfo("Europe/Madrid")
SAME_DAY_PREDICTION_CUTOFF_HOUR = 10 SAME_DAY_PREDICTION_CUTOFF_HOUR = 10
+6 -1
View File
@@ -255,6 +255,11 @@ class StationScraper:
# Public API # Public API
# ------------------------------------------------------------------ # ------------------------------------------------------------------
@property
def station_ids(self) -> tuple[str, ...]:
"""Return the configured station identifiers."""
return tuple(self._stations.keys())
def scrape_station(self, station_id: str) -> dict: def scrape_station(self, station_id: str) -> dict:
""" """
Scrape operational data for a single station. Scrape operational data for a single station.
@@ -297,7 +302,7 @@ class StationScraper:
List of dicts, one per station, in the same format as scrape_station(). List of dicts, one per station, in the same format as scrape_station().
""" """
results = [] results = []
for station_id in self._stations: for station_id in self.station_ids:
record = self.scrape_station(station_id) record = self.scrape_station(station_id)
results.append(record) results.append(record)
return results return results
+26 -6
View File
@@ -19,11 +19,10 @@ logger = logging.getLogger(__name__)
# Path relative to repository root # Path relative to repository root
_CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml" _CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml"
# Fresh snowfall (cm in 24 h) considered "heavy" # Warm rain quickly degrades skiable terrain even when opening remains possible.
_HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0 _WARM_RAIN_TEMP_THRESHOLD_C = 10.0
_WARM_RAIN_PRECIP_THRESHOLD_MM = 1.0
# Wind gust (km/h) considered "moderate" when combined with heavy snow _WARM_RAIN_KM_FACTOR = 0.6
_MODERATE_WIND_THRESHOLD_KMH = 40.0
def _load_station_configs() -> dict[str, Any]: def _load_station_configs() -> dict[str, Any]:
@@ -137,7 +136,6 @@ class RulesEngine:
) )
force_closed = False force_closed = False
force_open = False
reasons: list[str] = [] reasons: list[str] = []
km_factor = 1.0 km_factor = 1.0
@@ -178,6 +176,28 @@ class RulesEngine:
min_snow, min_snow,
) )
# ---- Rule 3: Warm rain reduces skiable terrain -------------------
max_temperature = weather_data.get("temperature_2m_max")
precipitation = weather_data.get("precipitation_sum")
if (
max_temperature is not None
and max_temperature > _WARM_RAIN_TEMP_THRESHOLD_C
and precipitation is not None
and precipitation >= _WARM_RAIN_PRECIP_THRESHOLD_MM
and not force_closed
):
km_factor = min(km_factor, _WARM_RAIN_KM_FACTOR)
reasons.append(
f"Lluvia ({precipitation:.1f} mm) con temperatura alta "
f"({max_temperature:.1f} C); se reduce el km esquiable estimado."
)
logger.info(
"[%s] Rule 6 fired: warm rain %.1f C / %.1f mm -> km_factor %.2f",
station_name,
max_temperature,
precipitation,
km_factor,
)
# ---- Derive confidence ------------------------------------------- # ---- Derive confidence -------------------------------------------
# Confidence is 1.0 only if a deterministic closure rule fired. # Confidence is 1.0 only if a deterministic closure rule fired.
# Otherwise, confidence is 0.0, delegating all responsibility to ML. # Otherwise, confidence is 0.0, delegating all responsibility to ML.
+1 -1
View File
@@ -15,6 +15,6 @@ fastapi>=0.115.0
uvicorn[standard]>=0.30.0 uvicorn[standard]>=0.30.0
apscheduler>=3.10.0 apscheduler>=3.10.0
PyJWT>=2.8.0 PyJWT>=2.8.0
passlib[bcrypt]>=1.7.4 bcrypt>=3.2.0
python-multipart>=0.0.9 python-multipart>=0.0.9
ultralytics>=8.0.0 ultralytics>=8.0.0
+68 -12
View File
@@ -104,7 +104,7 @@ def collect_station_status(
"""Scrape current operational status for all stations.""" """Scrape current operational status for all stations."""
logger.info("Step 2/5 - Collecting station status.") logger.info("Step 2/5 - Collecting station status.")
records = [] records = []
for station_id in scraper._stations: for station_id in scraper.station_ids:
try: try:
record = scraper.scrape_station(station_id) record = scraper.scrape_station(station_id)
records.append(record) records.append(record)
@@ -176,6 +176,59 @@ def run_feature_engineering(
return featured return featured
def _available_prediction_dates(
weather_by_station: dict[str, pd.DataFrame],
*,
base_date: date,
include_today: bool,
) -> list[date]:
"""Return the real prediction dates available in the collected forecasts."""
available_dates: set[date] = set()
for weather_df in weather_by_station.values():
if weather_df.empty or "date" not in weather_df.columns:
continue
station_dates = pd.to_datetime(weather_df["date"], format="mixed").dt.date
available_dates.update(station_dates.tolist())
if include_today:
return sorted(d for d in available_dates if d >= base_date)
return sorted(d for d in available_dates if d > base_date)
def _select_forecast_row_for_date(
weather_df: pd.DataFrame,
*,
station_id: str,
target_date: date,
) -> dict[str, object] | None:
"""Return the exact forecast row for *target_date*, or None when unavailable."""
if weather_df.empty or "date" not in weather_df.columns:
logger.warning("No forecast rows available for %s.", station_id)
return None
weather_dates = pd.to_datetime(weather_df["date"], format="mixed").dt.date
target_rows = weather_df.loc[weather_dates == target_date]
if not target_rows.empty:
return target_rows.iloc[0].to_dict()
available_dates = sorted(set(weather_dates.tolist()))
if available_dates:
logger.warning(
"Forecast for %s on %s is unavailable. Available range: %s -> %s.",
station_id,
target_date.isoformat(),
available_dates[0].isoformat(),
available_dates[-1].isoformat(),
)
else:
logger.warning(
"Forecast for %s on %s is unavailable.",
station_id,
target_date.isoformat(),
)
return None
def _load_prediction_feature_base( def _load_prediction_feature_base(
store: SQLiteStore, store: SQLiteStore,
runtime_featured_df: pd.DataFrame, runtime_featured_df: pd.DataFrame,
@@ -267,22 +320,17 @@ def generate_predictions(
logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat()) logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat())
predictions = {} predictions = {}
station_map = {r["station_id"]: r for r in station_records} station_map = {r["station_id"]: r for r in station_records}
base_date = date.today()
days_ahead = (target_date - base_date).days
feature_base_df = _load_prediction_feature_base(store, featured_df) feature_base_df = _load_prediction_feature_base(store, featured_df)
for station_id, weather_df in weather_by_station.items(): for station_id, weather_df in weather_by_station.items():
# Get target-date forecast row as weather_data dict. weather_data = _select_forecast_row_for_date(
target_rows = weather_df[weather_df["date"] == target_date] weather_df,
if target_rows.empty: station_id=station_id,
fallback_index = max(0, min(days_ahead, len(weather_df) - 1)) target_date=target_date,
target_rows = weather_df.iloc[fallback_index:fallback_index + 1] )
if target_rows.empty: if weather_data is None:
logger.warning("No forecast for %s for %s.", station_id, target_date.isoformat())
continue continue
weather_data = target_rows.iloc[0].to_dict()
# Build a feature row: target-date weather + today's station data. # Build a feature row: target-date weather + today's station data.
# Current station observations are still the best proxy available for # Current station observations are still the best proxy available for
# same-day or next-day inference. # same-day or next-day inference.
@@ -327,6 +375,14 @@ def generate_predictions(
except Exception as exc: except Exception as exc:
logger.error("Prediction failed for %s: %s", station_id, exc) logger.error("Prediction failed for %s: %s", station_id, exc)
if not predictions:
logger.error(
"No predictions generated for %s; the requested horizon is outside the "
"available forecast window or every station failed.",
target_date.isoformat(),
)
return
output = { output = {
"generated_at": datetime.now(timezone.utc).isoformat(), "generated_at": datetime.now(timezone.utc).isoformat(),
"prediction_date": target_date.isoformat(), "prediction_date": target_date.isoformat(),
+10 -6
View File
@@ -30,10 +30,7 @@ logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parents[1] _PROJECT_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_DB_PATH = Path( DEFAULT_DB_PATH = Path(
os.environ.get( _PROJECT_ROOT / "data" / "processed" / "skipredictor.db"
"SKIPREDICTOR_DB_PATH",
_PROJECT_ROOT / "data" / "processed" / "skipredictor.db",
)
) )
LATEST_WEATHER_TABLE = "latest_weather_forecast" LATEST_WEATHER_TABLE = "latest_weather_forecast"
@@ -73,8 +70,8 @@ _WEATHER_COLUMNS: list[str] = [
class SQLiteStore: class SQLiteStore:
"""Convenience wrapper around the project SQLite database.""" """Convenience wrapper around the project SQLite database."""
def __init__(self, db_path: Path | str = DEFAULT_DB_PATH) -> None: def __init__(self, db_path: Path | str | None = None) -> None:
self.db_path = Path(db_path) self.db_path = self._resolve_db_path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True) self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._ensure_schema() self._ensure_schema()
@@ -838,6 +835,13 @@ class SQLiteStore:
""" """
) )
@staticmethod
def _resolve_db_path(db_path: Path | str | None) -> Path:
"""Resolve the effective database path, honoring the environment at runtime."""
if db_path is not None:
return Path(db_path)
return Path(os.environ.get("SKIPREDICTOR_DB_PATH", DEFAULT_DB_PATH))
def _load_prediction_payload( def _load_prediction_payload(
self, self,
conn: sqlite3.Connection, conn: sqlite3.Connection,
+72
View File
@@ -0,0 +1,72 @@
"""Unit tests for daily prediction horizon helpers."""
from __future__ import annotations
from datetime import date
import pandas as pd
from scripts.collect_daily_data import (
_available_prediction_dates,
_select_forecast_row_for_date,
)
def _forecast_df(start: str = "2026-03-13", periods: int = 7) -> pd.DataFrame:
"""Build a minimal forecast frame with consecutive daily dates."""
dates = pd.date_range(start=start, periods=periods, freq="D")
return pd.DataFrame(
{
"date": dates,
"station_id": ["pajares"] * periods,
"temperature_2m_max": [1.0] * periods,
}
)
def test_available_prediction_dates_match_real_forecast_horizon():
"""Helpers must not invent an eighth day when the provider returns seven."""
forecast_dates = _available_prediction_dates(
{"pajares": _forecast_df()},
base_date=date(2026, 3, 13),
include_today=True,
)
assert forecast_dates == [
date(2026, 3, 13),
date(2026, 3, 14),
date(2026, 3, 15),
date(2026, 3, 16),
date(2026, 3, 17),
date(2026, 3, 18),
date(2026, 3, 19),
]
def test_available_prediction_dates_can_skip_today():
"""Afternoon scheduler runs must start from tomorrow when requested."""
forecast_dates = _available_prediction_dates(
{"pajares": _forecast_df()},
base_date=date(2026, 3, 13),
include_today=False,
)
assert forecast_dates == [
date(2026, 3, 14),
date(2026, 3, 15),
date(2026, 3, 16),
date(2026, 3, 17),
date(2026, 3, 18),
date(2026, 3, 19),
]
def test_select_forecast_row_returns_none_when_target_date_is_missing():
"""Out-of-range requests must fail cleanly instead of reusing the last row."""
row = _select_forecast_row_for_date(
_forecast_df(),
station_id="pajares",
target_date=date(2026, 3, 20),
)
assert row is None
+21
View File
@@ -5,8 +5,11 @@ from __future__ import annotations
import sys import sys
import types import types
from datetime import datetime from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
import yaml
telegram_module = types.ModuleType("telegram") telegram_module = types.ModuleType("telegram")
@@ -186,3 +189,21 @@ def test_format_daily_predictions_includes_all_three_stations():
assert "San Isidro" in text assert "San Isidro" in text
assert "Fuentes de Invierno" in text assert "Fuentes de Invierno" in text
assert "2026-03-14" in text assert "2026-03-14" in text
def test_station_metadata_is_loaded_from_shared_config():
"""Bot station labels and max km must come from config/stations.yaml."""
config_path = Path(__file__).resolve().parents[1] / "config" / "stations.yaml"
with config_path.open("r", encoding="utf-8") as fh:
stations = yaml.safe_load(fh)["stations"]
expected = {
station_id: {
"name": station_cfg["name"],
"max_km": float(station_cfg["max_km_skiable"]),
}
for station_id, station_cfg in stations.items()
}
assert telegram_bot.STATIONS == expected
assert telegram_bot.STATION_ORDER == tuple(stations.keys())