mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
merge: clean predictor debt
# Conflicts: # predictor/rules.py
This commit is contained in:
commit
a70eff3e45
10 files changed
+266
-64
No files matched your search
+20
-4
@@ -6,10 +6,10 @@ import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import bcrypt
|
||||
import jwt
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.api.schemas import TokenResponse, UserCreate, UserResponse
|
||||
from storage import SQLiteStore
|
||||
@@ -19,7 +19,6 @@ logger = logging.getLogger(__name__)
|
||||
_TOKEN_EXPIRE_DAYS = 14
|
||||
_ALGORITHM = "HS256"
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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:
|
||||
"""FastAPI dependency that validates the JWT and returns user info."""
|
||||
try:
|
||||
@@ -82,7 +98,7 @@ def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
||||
def register(body: UserCreate) -> UserResponse:
|
||||
"""Create a new user account."""
|
||||
store = SQLiteStore()
|
||||
hashed = pwd_context.hash(body.password)
|
||||
hashed = _hash_password(body.password)
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
with store.connect() as conn:
|
||||
@@ -117,7 +133,7 @@ def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse:
|
||||
(form.username,),
|
||||
).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(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="invalid credentials",
|
||||
|
||||
+19
-17
@@ -7,7 +7,7 @@ reuse the same pipeline components as ``scripts/collect_daily_data.py``.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
@@ -18,7 +18,9 @@ from pipeline.build_dataset import DatasetBuilder
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
from predictor.hybrid_predictor import HybridPredictor
|
||||
from scripts.collect_daily_data import (
|
||||
_available_prediction_dates,
|
||||
_load_prediction_feature_base,
|
||||
_select_forecast_row_for_date,
|
||||
_select_feature_anchor_row,
|
||||
)
|
||||
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
|
||||
scraper = StationScraper()
|
||||
station_records: list[dict[str, Any]] = []
|
||||
for station_id in scraper._stations:
|
||||
for station_id in scraper.station_ids:
|
||||
try:
|
||||
record = scraper.scrape_station(station_id)
|
||||
station_records.append(record)
|
||||
@@ -116,12 +118,14 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
|
||||
# 5. Determine forecast dates
|
||||
base_date = date.today()
|
||||
if run_hour >= 15:
|
||||
# Skip today, start from tomorrow
|
||||
forecast_dates = [base_date + timedelta(days=d) for d in range(1, 8)]
|
||||
else:
|
||||
# Include today
|
||||
forecast_dates = [base_date + timedelta(days=d) for d in range(8)]
|
||||
forecast_dates = _available_prediction_dates(
|
||||
weather_by_station,
|
||||
base_date=base_date,
|
||||
include_today=run_hour < 15,
|
||||
)
|
||||
if not forecast_dates:
|
||||
logger.error("No usable forecast dates were returned by the weather provider.")
|
||||
return
|
||||
|
||||
# 6. Generate predictions
|
||||
predictor = HybridPredictor()
|
||||
@@ -131,16 +135,14 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
station_rec = station_map.get(station_id, {})
|
||||
for target_date in forecast_dates:
|
||||
days_ahead = (target_date - base_date).days
|
||||
target_rows = weather_df[weather_df["date"] == target_date]
|
||||
if target_rows.empty:
|
||||
idx = max(0, min(days_ahead, len(weather_df) - 1))
|
||||
target_rows = weather_df.iloc[idx : idx + 1]
|
||||
if target_rows.empty:
|
||||
weather_data = _select_forecast_row_for_date(
|
||||
weather_df,
|
||||
station_id=station_id,
|
||||
target_date=target_date,
|
||||
)
|
||||
if weather_data is None:
|
||||
continue
|
||||
|
||||
weather_data = target_rows.iloc[0].to_dict()
|
||||
|
||||
# Build feature row
|
||||
features_df = None
|
||||
if not feature_base_df.empty:
|
||||
@@ -258,7 +260,7 @@ def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
|
||||
today_iso = date.today().isoformat()
|
||||
records: list[dict[str, Any]] = []
|
||||
|
||||
for station_id in scraper._stations:
|
||||
for station_id in scraper.station_ids:
|
||||
try:
|
||||
data = scraper.scrape_station(station_id)
|
||||
records.append(
|
||||
|
||||
+23
-17
@@ -23,6 +23,8 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import yaml
|
||||
|
||||
# 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).
|
||||
_BOT_DIR = Path(__file__).resolve().parent
|
||||
@@ -51,25 +53,29 @@ logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
logging.getLogger("httpcore").setLevel(logging.WARNING)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Station metadata (mirrors config/stations.yaml without adding a runtime
|
||||
# dependency on pyyaml inside the bot module itself).
|
||||
# Station metadata
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
STATIONS = {
|
||||
"pajares": {
|
||||
"name": "Valgrande-Pajares",
|
||||
"max_km": 22.0,
|
||||
},
|
||||
"sanisidro": {
|
||||
"name": "San Isidro",
|
||||
"max_km": 31.0,
|
||||
},
|
||||
"fuentes": {
|
||||
"name": "Fuentes de Invierno",
|
||||
"max_km": 8.6,
|
||||
},
|
||||
}
|
||||
STATION_ORDER = ("pajares", "sanisidro", "fuentes")
|
||||
_STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml"
|
||||
|
||||
|
||||
def _load_station_metadata() -> dict[str, dict[str, Any]]:
|
||||
"""Load bot-visible station metadata from the shared YAML config."""
|
||||
with _STATIONS_YAML.open("r", encoding="utf-8") as fh:
|
||||
raw = yaml.safe_load(fh) or {}
|
||||
|
||||
stations = raw.get("stations") or {}
|
||||
return {
|
||||
station_id: {
|
||||
"name": station_cfg["name"],
|
||||
"max_km": float(station_cfg["max_km_skiable"]),
|
||||
}
|
||||
for station_id, station_cfg in stations.items()
|
||||
}
|
||||
|
||||
|
||||
STATIONS = _load_station_metadata()
|
||||
STATION_ORDER = tuple(STATIONS.keys())
|
||||
DISPLAY_TIMEZONE = ZoneInfo("Europe/Madrid")
|
||||
SAME_DAY_PREDICTION_CUTOFF_HOUR = 10
|
||||
|
||||
|
||||
@@ -255,6 +255,11 @@ class StationScraper:
|
||||
# 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:
|
||||
"""
|
||||
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().
|
||||
"""
|
||||
results = []
|
||||
for station_id in self._stations:
|
||||
for station_id in self.station_ids:
|
||||
record = self.scrape_station(station_id)
|
||||
results.append(record)
|
||||
return results
|
||||
|
||||
+26
-6
@@ -19,11 +19,10 @@ logger = logging.getLogger(__name__)
|
||||
# Path relative to repository root
|
||||
_CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml"
|
||||
|
||||
# Fresh snowfall (cm in 24 h) considered "heavy"
|
||||
_HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0
|
||||
|
||||
# Wind gust (km/h) considered "moderate" when combined with heavy snow
|
||||
_MODERATE_WIND_THRESHOLD_KMH = 40.0
|
||||
# Warm rain quickly degrades skiable terrain even when opening remains possible.
|
||||
_WARM_RAIN_TEMP_THRESHOLD_C = 10.0
|
||||
_WARM_RAIN_PRECIP_THRESHOLD_MM = 1.0
|
||||
_WARM_RAIN_KM_FACTOR = 0.6
|
||||
|
||||
|
||||
def _load_station_configs() -> dict[str, Any]:
|
||||
@@ -137,7 +136,6 @@ class RulesEngine:
|
||||
)
|
||||
|
||||
force_closed = False
|
||||
force_open = False
|
||||
reasons: list[str] = []
|
||||
km_factor = 1.0
|
||||
|
||||
@@ -178,6 +176,28 @@ class RulesEngine:
|
||||
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 -------------------------------------------
|
||||
# Confidence is 1.0 only if a deterministic closure rule fired.
|
||||
# Otherwise, confidence is 0.0, delegating all responsibility to ML.
|
||||
|
||||
+1
-1
@@ -15,6 +15,6 @@ fastapi>=0.115.0
|
||||
uvicorn[standard]>=0.30.0
|
||||
apscheduler>=3.10.0
|
||||
PyJWT>=2.8.0
|
||||
passlib[bcrypt]>=1.7.4
|
||||
bcrypt>=3.2.0
|
||||
python-multipart>=0.0.9
|
||||
ultralytics>=8.0.0
|
||||
@@ -104,7 +104,7 @@ def collect_station_status(
|
||||
"""Scrape current operational status for all stations."""
|
||||
logger.info("Step 2/5 - Collecting station status.")
|
||||
records = []
|
||||
for station_id in scraper._stations:
|
||||
for station_id in scraper.station_ids:
|
||||
try:
|
||||
record = scraper.scrape_station(station_id)
|
||||
records.append(record)
|
||||
@@ -176,6 +176,59 @@ def run_feature_engineering(
|
||||
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(
|
||||
store: SQLiteStore,
|
||||
runtime_featured_df: pd.DataFrame,
|
||||
@@ -267,22 +320,17 @@ def generate_predictions(
|
||||
logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat())
|
||||
predictions = {}
|
||||
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)
|
||||
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
# Get target-date forecast row as weather_data dict.
|
||||
target_rows = weather_df[weather_df["date"] == target_date]
|
||||
if target_rows.empty:
|
||||
fallback_index = max(0, min(days_ahead, len(weather_df) - 1))
|
||||
target_rows = weather_df.iloc[fallback_index:fallback_index + 1]
|
||||
if target_rows.empty:
|
||||
logger.warning("No forecast for %s for %s.", station_id, target_date.isoformat())
|
||||
weather_data = _select_forecast_row_for_date(
|
||||
weather_df,
|
||||
station_id=station_id,
|
||||
target_date=target_date,
|
||||
)
|
||||
if weather_data is None:
|
||||
continue
|
||||
|
||||
weather_data = target_rows.iloc[0].to_dict()
|
||||
|
||||
# Build a feature row: target-date weather + today's station data.
|
||||
# Current station observations are still the best proxy available for
|
||||
# same-day or next-day inference.
|
||||
@@ -327,6 +375,14 @@ def generate_predictions(
|
||||
except Exception as 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 = {
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"prediction_date": target_date.isoformat(),
|
||||
|
||||
+10
-6
@@ -30,10 +30,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_DB_PATH = Path(
|
||||
os.environ.get(
|
||||
"SKIPREDICTOR_DB_PATH",
|
||||
_PROJECT_ROOT / "data" / "processed" / "skipredictor.db",
|
||||
)
|
||||
_PROJECT_ROOT / "data" / "processed" / "skipredictor.db"
|
||||
)
|
||||
|
||||
LATEST_WEATHER_TABLE = "latest_weather_forecast"
|
||||
@@ -73,8 +70,8 @@ _WEATHER_COLUMNS: list[str] = [
|
||||
class SQLiteStore:
|
||||
"""Convenience wrapper around the project SQLite database."""
|
||||
|
||||
def __init__(self, db_path: Path | str = DEFAULT_DB_PATH) -> None:
|
||||
self.db_path = Path(db_path)
|
||||
def __init__(self, db_path: Path | str | None = None) -> None:
|
||||
self.db_path = self._resolve_db_path(db_path)
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
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(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
|
||||
@@ -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
|
||||
@@ -5,8 +5,11 @@ from __future__ import annotations
|
||||
import sys
|
||||
import types
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import yaml
|
||||
|
||||
telegram_module = types.ModuleType("telegram")
|
||||
|
||||
|
||||
@@ -186,3 +189,21 @@ def test_format_daily_predictions_includes_all_three_stations():
|
||||
assert "San Isidro" in text
|
||||
assert "Fuentes de Invierno" 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())
|
||||
Reference in new issue
Block a user