diff --git a/OPERATIONS.md b/OPERATIONS.md index 3d3edea..f57e538 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -2,7 +2,18 @@ This guide covers common administrative and maintenance tasks for the SkiPredictor system. -## 🗄️ Database Management +## Architecture + +Single unified process: FastAPI + APScheduler + Telegram Bot (in-process). + +**Scheduled tasks:** +- Standard (5h, 10h, 15h): archive forecasts, collect weather, generate predictions +- Extended (20h): same + webcam snapshot + crowd analysis + actuals scraping +- Training (Sunday 21h): retrain ML models + +**Single source of truth:** `current_forecasts` / `past_forecasts` tables in SQLite. + +## Database Management The authoritative data source is the SQLite database at `data/processed/skipredictor.db`. @@ -16,9 +27,26 @@ sqlite3 data/processed/skipredictor.db "SELECT * FROM current_forecasts ORDER BY .venv/bin/python -c "from storage import SQLiteStore; s=SQLiteStore(); print(f'DB Size: {s.db_path.stat().st_size/1024/1024:.2f} MB')" ``` -## 🔄 Manual Forecast Cycles +## Setup (first time) -While the FastAPI backend handles the schedule via APScheduler, you can trigger cycles manually: +```bash +./setup.sh +``` + +This creates a venv, installs dependencies, downloads historical data, trains models, and collects webcam snapshots. + +## Starting the unified daemon + +```bash +source .venv/bin/activate +export TELEGRAM_BOT_TOKEN='your_token' +export JWT_SECRET_KEY='your_secret' +uvicorn app.main:app --host 0.0.0.0 --port 8000 +``` + +This starts FastAPI (REST API), APScheduler (scheduled tasks), and the Telegram bot (in-process polling). + +## Manual Forecast Cycles ### Run a full prediction cycle now ```bash @@ -30,7 +58,7 @@ While the FastAPI backend handles the schedule via APScheduler, you can trigger .venv/bin/python data_sources/station_scraper.py ``` -## 🧠 ML Model Operations +## ML Model Operations ### Force manual retraining ```bash @@ -38,39 +66,19 @@ While the FastAPI backend handles the schedule via APScheduler, you can trigger ``` ### Inspecting model metrics -The metrics from the last training run are stored in the `training_runs` table: ```bash sqlite3 data/processed/skipredictor.db "SELECT metrics_json FROM training_runs ORDER BY completed_at DESC LIMIT 1;" ``` -## 🤖 Telegram Bot +## Telegram Bot -### Running the bot standalone +### Running the bot standalone (dev) ```bash export TELEGRAM_BOT_TOKEN='your_token' -.venv/bin/python bot/telegram_bot.py +.venv/bin/python -m bot.telegram_bot ``` -### Monitoring bot logs -```bash -tail -f data/bot.log -``` - -## 🌐 FastAPI Backend - -### Running the API server (Production) -```bash -export TELEGRAM_BOT_TOKEN='your_token' -export JWT_SECRET_KEY='your_secret' -.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 -``` - -### Running the API server (Development/Reload) -```bash -uvicorn app.main:app --reload -``` - -## 🛠️ Troubleshooting +## Troubleshooting ### Missing forecasts? 1. Check `data/pipeline.log`. @@ -78,6 +86,6 @@ uvicorn app.main:app --reload 3. Ensure models exist in `ml/models/`. ### Bot not responding? -1. Check if the subprocess is alive via `GET /api/v1/status`. -2. Check `data/bot.log` for API errors (e.g., Invalid Token). -3. Ensure `TELEGRAM_BOT_TOKEN` is correctly exported in the environment where the backend is running. +1. Check if the bot is active via `GET /api/v1/status`. +2. Ensure `TELEGRAM_BOT_TOKEN` is correctly exported in the environment. +3. Check uvicorn logs for bot startup errors. diff --git a/app/main.py b/app/main.py index 1f39e48..8d944a0 100644 --- a/app/main.py +++ b/app/main.py @@ -3,16 +3,13 @@ Manages: - REST API serving forecast data - APScheduler for periodic forecast generation and retraining - - Telegram bot as a subprocess + - Telegram bot (in-process, no subprocess) """ from __future__ import annotations import logging import os -import signal -import subprocess -import sys from contextlib import asynccontextmanager from datetime import datetime from pathlib import Path @@ -24,7 +21,7 @@ from fastapi import FastAPI from app.api.auth import auth_router from app.api.routes import router -from app.scheduler.tasks import run_forecast_cycle, run_retrain +from app.scheduler.tasks import run_extended_task, run_standard_task, run_training_task logger = logging.getLogger(__name__) @@ -48,23 +45,30 @@ def _start_scheduler() -> BackgroundScheduler: """Configure and start the APScheduler instance.""" scheduler = BackgroundScheduler(timezone=_TIMEZONE) - # Forecast runs: 00, 05, 10, 15, 20 Europe/Madrid - for hour in (0, 5, 10, 15, 20): - scheduler.add_job( - run_forecast_cycle, - trigger=CronTrigger(hour=hour, minute=0, timezone=_TIMEZONE), - args=[hour], - id=f"forecast_{hour:02d}", - name=f"Forecast run {hour:02d}:00", - replace_existing=True, - ) - - # Weekly retrain: Monday 03:00 + # Standard forecast: 5:00, 10:00, 15:00 scheduler.add_job( - run_retrain, - trigger=CronTrigger(day_of_week="mon", hour=3, minute=0, timezone=_TIMEZONE), + run_standard_task, + trigger=CronTrigger(hour="5,10,15", minute=0, timezone=_TIMEZONE), + id="forecast_standard", + name="Standard forecast run", + replace_existing=True, + ) + + # Extended forecast: 20:00 + scheduler.add_job( + run_extended_task, + trigger=CronTrigger(hour=20, minute=0, timezone=_TIMEZONE), + id="forecast_extended", + name="Extended forecast run (20:00)", + replace_existing=True, + ) + + # Training: Sunday 21:00 + scheduler.add_job( + run_training_task, + trigger=CronTrigger(day_of_week="sun", hour=21, minute=0, timezone=_TIMEZONE), id="retrain_weekly", - name="Weekly model retrain", + name="Weekly model retrain (Sunday 21:00)", replace_existing=True, ) @@ -100,8 +104,8 @@ def _update_next_runs(scheduler: BackgroundScheduler) -> None: ) -def _start_bot_subprocess() -> subprocess.Popen | None: - """Launch the Telegram bot as a subprocess.""" +async def _start_bot() -> Any: + """Start the Telegram bot in-process. Returns the Application or None.""" token = os.environ.get("TELEGRAM_BOT_TOKEN") if not token: logger.warning( @@ -109,50 +113,46 @@ def _start_bot_subprocess() -> subprocess.Popen | None: ) return None - env = {**os.environ, "PYTHONPATH": str(_PROJECT_ROOT)} + from bot.telegram_bot import create_bot_application + try: - proc = subprocess.Popen( - [sys.executable, "-m", "bot.telegram_bot"], - cwd=str(_PROJECT_ROOT), - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - ) - logger.info("Telegram bot subprocess started (PID=%d).", proc.pid) + bot_app = create_bot_application(token) + await bot_app.initialize() + await bot_app.start() + await bot_app.updater.start_polling() app_state["bot_active"] = True - return proc + logger.info("Telegram bot started in-process.") + return bot_app except Exception as exc: - logger.error("Failed to start Telegram bot subprocess: %s", exc) + logger.error("Failed to start Telegram bot: %s", exc) return None -def _stop_bot_subprocess(proc: subprocess.Popen | None) -> None: - """Gracefully terminate the Telegram bot subprocess.""" - if proc is None: +async def _stop_bot(bot_app: Any) -> None: + """Gracefully stop the in-process Telegram bot.""" + if bot_app is None: return app_state["bot_active"] = False try: - proc.send_signal(signal.SIGTERM) - proc.wait(timeout=10) - logger.info("Telegram bot subprocess stopped.") - except subprocess.TimeoutExpired: - proc.kill() - logger.warning("Telegram bot subprocess killed after timeout.") + await bot_app.updater.stop() + await bot_app.stop() + await bot_app.shutdown() + logger.info("Telegram bot stopped.") except Exception as exc: - logger.error("Error stopping bot subprocess: %s", exc) + logger.error("Error stopping Telegram bot: %s", exc) @asynccontextmanager async def lifespan(application: FastAPI) -> AsyncIterator[None]: - """Manage startup and shutdown of scheduler and bot subprocess.""" + """Manage startup and shutdown of scheduler and bot.""" scheduler = _start_scheduler() - bot_proc = _start_bot_subprocess() + bot_app = await _start_bot() yield - logger.info("Shutting down scheduler and bot subprocess...") + logger.info("Shutting down scheduler and bot...") scheduler.shutdown(wait=False) - _stop_bot_subprocess(bot_proc) + await _stop_bot(bot_app) # --------------------------------------------------------------------------- diff --git a/app/scheduler/tasks.py b/app/scheduler/tasks.py index 16f854a..24cefb7 100644 --- a/app/scheduler/tasks.py +++ b/app/scheduler/tasks.py @@ -1,7 +1,9 @@ """Scheduled tasks for forecast generation and model retraining. -These functions are invoked by APScheduler from the FastAPI lifespan and -reuse the same pipeline components as ``scripts/collect_daily_data.py``. +Three scheduled tasks: + - run_standard_task() — 5h, 10h, 15h: archive + weather + predict + - run_extended_task() — 20h: same + webcam + crowd + actuals scraping + - run_training_task() — Sunday 21h: retrain ML models """ from __future__ import annotations @@ -35,21 +37,18 @@ logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- -# Forecast cycle +# Shared forecast logic # --------------------------------------------------------------------------- -def run_forecast_cycle(run_hour: int) -> None: - """Execute a full forecast cycle for a given run hour. +def _run_forecast_core( + *, + include_today: bool, + run_hour: int, +) -> list[dict[str, Any]]: + """Shared forecast generation logic used by standard and extended tasks. - Steps: - 1. Archive current forecasts into past_forecasts. - 2. Fetch weather forecasts via Open-Meteo. - 3. Scrape current station status. - 4. Append to runtime dataset + feature engineering. - 5. Generate predictions for each station x each forecast day. - 6. Save results to current_forecasts. - 7. At hour 20, scrape today's actual data into historical_actuals. + Returns the list of forecast dicts that were saved. """ logger.info("=== Forecast cycle started (run_hour=%d) ===", run_hour) store = SQLiteStore() @@ -72,7 +71,7 @@ def run_forecast_cycle(run_hour: int) -> None: if not weather_by_station: logger.error("No weather data collected. Aborting forecast cycle.") - return + return [] # 3. Scrape station status scraper = StationScraper() @@ -121,11 +120,11 @@ def run_forecast_cycle(run_hour: int) -> None: forecast_dates = _available_prediction_dates( weather_by_station, base_date=base_date, - include_today=run_hour < 15, + include_today=include_today, ) if not forecast_dates: logger.error("No usable forecast dates were returned by the weather provider.") - return + return [] # 6. Generate predictions predictor = HybridPredictor() @@ -143,7 +142,6 @@ def run_forecast_cycle(run_hour: int) -> None: if weather_data is None: continue - # Build feature row features_df = None if not feature_base_df.empty: anchor = _select_feature_anchor_row( @@ -192,33 +190,81 @@ def run_forecast_cycle(run_hour: int) -> None: if all_forecasts: store.save_current_forecasts(all_forecasts, run_hour) - # Also save as a published prediction run for the bot's existing flow - # (one run per distinct target date, same as collect_daily_data.py) - _save_as_prediction_runs(store, all_forecasts, run_hour) - - # 8. At hour 20: scrape today's actual data and crowd density - if run_hour == 20: - _scrape_daily_actuals(store, scraper) - _collect_daily_crowd_density(store) - logger.info( "=== Forecast cycle finished (run_hour=%d, forecasts=%d) ===", run_hour, len(all_forecasts), ) + return all_forecasts + + +# --------------------------------------------------------------------------- +# Standard task (5h, 10h, 15h) +# --------------------------------------------------------------------------- + + +def run_standard_task() -> None: + """Standard forecast cycle: archive + weather + predict (today included).""" + _run_forecast_core(include_today=True, run_hour=_current_hour()) + + +# --------------------------------------------------------------------------- +# Extended task (20h) +# --------------------------------------------------------------------------- + + +def run_extended_task() -> None: + """Extended forecast cycle: predictions from tomorrow + webcam + actuals.""" + _run_forecast_core(include_today=False, run_hour=20) + + store = SQLiteStore() + scraper = StationScraper() + + # Scrape today's actual station data + _scrape_daily_actuals(store, scraper) + + # Webcam snapshot + crowd analysis + _collect_daily_crowd_density(store) + + +# --------------------------------------------------------------------------- +# Training task (Sunday 21h) +# --------------------------------------------------------------------------- + + +def run_training_task() -> None: + """Run the full model retraining pipeline.""" + logger.info("=== Model retraining triggered by scheduler ===") + try: + exit_code = retrain_main() + if exit_code != 0: + logger.error("Retraining finished with exit code %d.", exit_code) + else: + logger.info("=== Model retraining completed successfully ===") + except Exception as exc: + logger.error("Retraining failed: %s", exc, exc_info=True) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _current_hour() -> int: + """Return the current hour in Europe/Madrid.""" + from zoneinfo import ZoneInfo + + return datetime.now(ZoneInfo("Europe/Madrid")).hour def _collect_daily_crowd_density(store: SQLiteStore) -> None: """Download and analyze today's 10:00 AM webcam snapshot from Infonieve.""" logger.info("Collecting today's crowd density from historical archive.") - # Local import to avoid circular dependencies - from scripts.collect_historical_webcams import HistoricalWebcamCollector + from scripts.collect_historical_webcams import HISTORICAL_CONFIG, HistoricalWebcamCollector collector = HistoricalWebcamCollector(store=store) today = date.today() - - # Process for each configured historical station - from scripts.collect_historical_webcams import HISTORICAL_CONFIG + for station_id in HISTORICAL_CONFIG: try: logger.info("Collecting historical snapshot for %s on %s", station_id, today) @@ -227,33 +273,6 @@ def _collect_daily_crowd_density(store: SQLiteStore) -> None: logger.error("Daily crowd collection failed for %s: %s", station_id, exc) -def _save_as_prediction_runs( - store: SQLiteStore, - forecasts: list[dict[str, Any]], - run_hour: int, -) -> None: - """Persist forecasts as published prediction_runs for bot compatibility.""" - by_date: dict[str, dict[str, Any]] = {} - for f in forecasts: - by_date.setdefault(f["prediction_date"], {})[f["station_id"]] = { - "station_name": f["station_id"], - "open_probability": f["open_probability"], - "km_open": f["km_open"], - "crowd_level": f["crowd_level"], - "weather_summary": f.get("weather_summary"), - "rule_overrides": f.get("rule_notes", []), - "prediction_source": f["prediction_source"], - } - - for pred_date, stations in by_date.items(): - payload = { - "generated_at": datetime.now(timezone.utc).isoformat(), - "prediction_date": pred_date, - "stations": stations, - } - store.save_prediction_run(payload, run_kind="published") - - def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None: """Scrape today's actual station data and save to historical_actuals.""" logger.info("Scraping today's actual station data.") @@ -278,21 +297,3 @@ def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None: if records: store.save_historical_actual(records) - - -# --------------------------------------------------------------------------- -# Retrain -# --------------------------------------------------------------------------- - - -def run_retrain() -> None: - """Run the full model retraining pipeline.""" - logger.info("=== Model retraining triggered by scheduler ===") - try: - exit_code = retrain_main() - if exit_code != 0: - logger.error("Retraining finished with exit code %d.", exit_code) - else: - logger.info("=== Model retraining completed successfully ===") - except Exception as exc: - logger.error("Retraining failed: %s", exc, exc_info=True) diff --git a/bot/telegram_bot.py b/bot/telegram_bot.py index 8908255..ba39a2c 100644 --- a/bot/telegram_bot.py +++ b/bot/telegram_bot.py @@ -6,8 +6,9 @@ Serves published predictions for three ski stations in northern Spain: - San Isidro (/sanisidro) - Fuentes de Invierno (/fuentes) -The bot reads published prediction runs from SQLite and supports both -single-station queries and multi-station horizon commands. +The bot reads forecasts from the ``current_forecasts`` / ``past_forecasts`` +tables in SQLite and supports both single-station queries and multi-station +horizon commands. Usage: Set the TELEGRAM_BOT_TOKEN environment variable and run: @@ -15,6 +16,7 @@ Usage: or call main() directly. """ +import json import logging import os import sys @@ -36,7 +38,7 @@ from telegram import Update from telegram.constants import ParseMode from telegram.ext import Application, CommandHandler, ContextTypes -from storage import PUBLISHED_RUN_KIND, SQLiteStore +from storage import SQLiteStore # --------------------------------------------------------------------------- # Logging @@ -121,45 +123,85 @@ def prediction_dates_window( ] +def _forecasts_to_payload( + rows: list[dict[str, Any]], + prediction_date: str | None = None, +) -> dict[str, Any] | None: + """Convert flat forecast rows into the nested payload the bot expects. + + Returns a dict with ``prediction_date`` and ``stations`` keys, or None + when *rows* is empty. + """ + if not rows: + return None + + stations: dict[str, dict[str, Any]] = {} + first_date = prediction_date + for row in rows: + if prediction_date is not None and row["prediction_date"] != prediction_date: + continue + if first_date is None: + first_date = row["prediction_date"] + stations[row["station_id"]] = { + "station_name": row["station_id"], + "open_probability": row.get("open_probability"), + "km_open": row.get("km_open"), + "crowd_level": row.get("crowd_level"), + "weather_summary": row.get("weather_summary"), + "rule_overrides": json.loads(row["rule_notes_json"] or "[]") + if isinstance(row.get("rule_notes_json"), str) + else (row.get("rule_notes_json") or []), + "prediction_source": row.get("prediction_source"), + } + + if not stations: + return None + + return { + "generated_at": rows[0].get("generated_at"), + "prediction_date": first_date, + "stations": stations, + } + + def load_predictions( *, now: datetime | None = None, store: SQLiteStore | None = None, ) -> dict | None: - """Load the published predictions most relevant for the current hour. + """Load the predictions most relevant for the current hour. - Returns the parsed dictionary on success, or None if no published - prediction run exists yet. + Queries ``current_forecasts`` for the preferred prediction dates, falling + back to whatever is available. """ store = store or SQLiteStore() + all_rows = store.load_current_forecasts() - for prediction_date in _preferred_prediction_dates(now): - data = store.load_predictions_for_date( - prediction_date=prediction_date, - run_kind=PUBLISHED_RUN_KIND, - ) - if data is not None: - logger.info( - "Predicciones cargadas desde SQLite (%s) para %s", - store.db_path, - prediction_date, - ) - return data - - data = store.load_latest_predictions(run_kind=PUBLISHED_RUN_KIND) - if data is None: + if not all_rows: logger.warning( - "No hay ninguna predicción publicada en SQLite (%s)", + "No hay ninguna predicción en current_forecasts (%s)", store.db_path, ) return None + for prediction_date in _preferred_prediction_dates(now): + payload = _forecasts_to_payload(all_rows, prediction_date) + if payload is not None: + logger.info( + "Predicciones cargadas desde current_forecasts (%s) para %s", + store.db_path, + prediction_date, + ) + return payload + + # Fallback: return the earliest date available in current_forecasts + payload = _forecasts_to_payload(all_rows, all_rows[0]["prediction_date"]) logger.info( - "Predicciones cargadas desde SQLite (%s) como fallback (%s)", + "Predicciones cargadas desde current_forecasts (%s) como fallback (%s)", store.db_path, - data.get("prediction_date"), + payload.get("prediction_date") if payload else None, ) - return data + return payload def load_predictions_for_date( @@ -167,26 +209,25 @@ def load_predictions_for_date( *, store: SQLiteStore | None = None, ) -> dict | None: - """Load the latest published predictions for a specific target date.""" + """Load the current forecasts for a specific target date.""" store = store or SQLiteStore() - data = store.load_predictions_for_date( - prediction_date=prediction_date, - run_kind=PUBLISHED_RUN_KIND, - ) - if data is None: + all_rows = store.load_current_forecasts() + payload = _forecasts_to_payload(all_rows, prediction_date) + + if payload is None: logger.info( - "No hay predicción publicada en SQLite (%s) para %s", + "No hay predicción en current_forecasts (%s) para %s", store.db_path, prediction_date, ) return None logger.info( - "Predicciones cargadas desde SQLite (%s) para %s", + "Predicciones cargadas desde current_forecasts (%s) para %s", store.db_path, prediction_date, ) - return data + return payload # --------------------------------------------------------------------------- @@ -559,22 +600,21 @@ async def cmd_semana(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None # --------------------------------------------------------------------------- -def main() -> None: - """Build and start the Telegram bot using long-polling. +def create_bot_application(token: str | None = None) -> Application: + """Build the Telegram Application with all handlers registered. - Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable. - Raises: - EnvironmentError: If TELEGRAM_BOT_TOKEN is not set. + When *token* is None the ``TELEGRAM_BOT_TOKEN`` env var is used. + The returned Application has NOT been started yet — callers can either + use ``app.run_polling()`` (standalone) or manage the lifecycle manually + (in-process with FastAPI). """ - token = os.environ.get("TELEGRAM_BOT_TOKEN") + token = token or os.environ.get("TELEGRAM_BOT_TOKEN") if not token: raise EnvironmentError( "La variable de entorno TELEGRAM_BOT_TOKEN no está definida. " "Configura el token del bot antes de iniciar." ) - logger.info("Iniciando bot de predicción de esquí...") - app = Application.builder().token(token).build() app.add_handler(CommandHandler("start", cmd_start)) @@ -588,6 +628,16 @@ def main() -> None: app.add_handler(CommandHandler("tresdias", cmd_tresdias)) app.add_handler(CommandHandler("semana", cmd_semana)) + return app + + +def main() -> None: + """Build and start the Telegram bot using long-polling (standalone mode). + + Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable. + """ + logger.info("Iniciando bot de predicción de esquí...") + app = create_bot_application() logger.info("Bot listo. Esperando mensajes...") app.run_polling(allowed_updates=Update.ALL_TYPES) diff --git a/predictor/rules.py b/predictor/rules.py index 304df16..f3554b2 100644 --- a/predictor/rules.py +++ b/predictor/rules.py @@ -175,29 +175,6 @@ class RulesEngine: snow_depth, 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. diff --git a/scripts/collect_daily_data.py b/scripts/collect_daily_data.py index ce8afb4..68091cc 100644 --- a/scripts/collect_daily_data.py +++ b/scripts/collect_daily_data.py @@ -44,10 +44,8 @@ from pipeline.build_dataset import DatasetBuilder from pipeline.feature_engineering import FeatureEngineer from predictor.hybrid_predictor import HybridPredictor from storage import ( - AD_HOC_RUN_KIND, HISTORICAL_FEATURED_TABLE, LATEST_WEATHER_TABLE, - PUBLISHED_RUN_KIND, RUNTIME_DATASET_TABLE, RUNTIME_FEATURED_TABLE, SQLiteStore, @@ -68,7 +66,7 @@ logger = logging.getLogger(__name__) # Storage # --------------------------------------------------------------------------- -_DEFAULT_RUN_KIND = PUBLISHED_RUN_KIND +_DEFAULT_RUN_KIND = "published" # --------------------------------------------------------------------------- @@ -316,9 +314,9 @@ def generate_predictions( target_date: date, run_kind: str, ) -> None: - """Generate predictions for a target date and save them to SQLite.""" + """Generate predictions for a target date and save them to current_forecasts.""" logger.info("Step 5/5 - Generating predictions for %s.", target_date.isoformat()) - predictions = {} + forecasts: list[dict] = [] station_map = {r["station_id"]: r for r in station_records} feature_base_df = _load_prediction_feature_base(store, featured_df) @@ -331,9 +329,6 @@ def generate_predictions( if weather_data is None: continue - # 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. features_df = None if not feature_base_df.empty: anchor_row = _select_feature_anchor_row( @@ -342,28 +337,35 @@ def generate_predictions( target_date=target_date, ) if anchor_row is not None: - # Start from the latest featured row (has rolling features) features_df = anchor_row features_df["date"] = pd.Timestamp(target_date) - # Overlay target-date weather for col in weather_data: if col in features_df.columns and col not in ("date", "station_id"): features_df[col] = weather_data[col] - # Overlay today's station data as best proxy station_rec = station_map.get(station_id, {}) if station_rec.get("snow_depth") is not None: features_df["snow_depth"] = station_rec["snow_depth"] if station_rec.get("lifts_open") is not None: features_df["lifts_open"] = station_rec["lifts_open"] - # Also inject snow_depth into weather_data for the rules engine station_rec = station_map.get(station_id, {}) if station_rec.get("snow_depth") is not None: weather_data["snow_depth"] = station_rec["snow_depth"] try: result = predictor.predict(station_id, weather_data, features_df) - predictions[station_id] = result + forecasts.append( + { + "station_id": station_id, + "prediction_date": target_date.isoformat(), + "open_probability": result["open_probability"], + "km_open": result["km_open"], + "crowd_level": result["crowd_level"], + "weather_summary": result.get("weather_summary"), + "rule_notes": result.get("rule_overrides", []), + "prediction_source": result["prediction_source"], + } + ) logger.info( "Prediction for %s: open=%.2f, km=%.1f, crowd=%s, source=%s", station_id, @@ -375,7 +377,7 @@ def generate_predictions( except Exception as exc: logger.error("Prediction failed for %s: %s", station_id, exc) - if not predictions: + if not forecasts: logger.error( "No predictions generated for %s; the requested horizon is outside the " "available forecast window or every station failed.", @@ -383,13 +385,10 @@ def generate_predictions( ) return - output = { - "generated_at": datetime.now(timezone.utc).isoformat(), - "prediction_date": target_date.isoformat(), - "stations": predictions, - } - store.save_prediction_run(output, run_kind=run_kind) - logger.info("Predictions saved to SQLite as %s run.", run_kind) + # Archive existing and save new forecasts + store.archive_current_forecasts() + store.save_current_forecasts(forecasts, run_hour=0) + logger.info("Predictions saved to current_forecasts (%s).", run_kind) def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: @@ -405,7 +404,7 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: ) parser.add_argument( "--run-kind", - choices=[PUBLISHED_RUN_KIND, AD_HOC_RUN_KIND], + choices=["published", "adhoc"], default=_DEFAULT_RUN_KIND, help=( "Whether this prediction run should be published to the bot " diff --git a/scripts/collect_historical_webcams.py b/scripts/collect_historical_webcams.py index 784bc2c..e9ff3f3 100644 --- a/scripts/collect_historical_webcams.py +++ b/scripts/collect_historical_webcams.py @@ -14,9 +14,11 @@ Usage: import argparse import logging +import re import time from datetime import date, datetime, timedelta from pathlib import Path +from urllib.parse import quote import pandas as pd import requests @@ -45,6 +47,7 @@ HISTORICAL_CONFIG = { PEAK_HOUR = 10 _BASE_URL = "https://www.infonieve.es/estacion-esqui/{slug}/historico-webcams/{cam_id}-{date_str}-{hour}" +_HISTORICO_AJAX_URL = "https://www.infonieve.es/webcams/historico.php?id={cam_id}&anyo={anyo}&mes={mes}&dia={dia}&hora=&base={base}" _USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" @@ -57,28 +60,107 @@ class HistoricalWebcamCollector: self.temp_dir = Path("data/raw/webcams/historical") self.temp_dir.mkdir(parents=True, exist_ok=True) + + # Cache for discovered date ranges per station + self._available_ranges: dict[str, tuple[date, date]] = {} + + def get_available_date_range(self, station_id: str) -> tuple[date, date] | None: + """Query Infonieve's AJAX endpoint to find the actual available date range for a station.""" + if station_id in self._available_ranges: + return self._available_ranges[station_id] + + cfg = HISTORICAL_CONFIG.get(station_id) + if not cfg: + return None + + logger.info("Discovering available historical range for %s...", station_id) + + try: + base_path = quote(f"estacion-esqui/{cfg['slug']}/historico-webcams/") + + # 1. Find years + url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo="", mes="", dia="", base=base_path) + resp = self.session.get(url, timeout=15) + resp.raise_for_status() + + years = sorted([int(y) for y in set(re.findall(r'rel="anyo-(\d{4})"', resp.text))]) + if not years: + logger.warning("No historical years found for %s", station_id) + return None + + min_year, max_year = years[0], years[-1] + + # 2. Find min month/day + url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=min_year, mes="", dia="", base=base_path) + resp = self.session.get(url, timeout=15) + months = sorted([int(m) for m in set(re.findall(r'rel="mes-(\d+)"', resp.text))]) + min_month = months[0] if months else 1 + + url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=min_year, mes=f"{min_month:02d}", dia="", base=base_path) + resp = self.session.get(url, timeout=15) + days = sorted([int(d) for d in set(re.findall(r'reldia="(\d+)"', resp.text))]) + min_day = days[0] if days else 1 + + start_date = date(min_year, min_month, min_day) + + # 3. Find max month/day + url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=max_year, mes="", dia="", base=base_path) + resp = self.session.get(url, timeout=15) + months = sorted([int(m) for m in set(re.findall(r'rel="mes-(\d+)"', resp.text))]) + max_month = months[-1] if months else 12 + + url = _HISTORICO_AJAX_URL.format(cam_id=cfg["cam_id"], anyo=max_year, mes=f"{max_month:02d}", dia="", base=base_path) + resp = self.session.get(url, timeout=15) + days = sorted([int(d) for d in set(re.findall(r'reldia="(\d+)"', resp.text))]) + max_day = days[-1] if days else 28 + + end_date = date(max_year, max_month, max_day) + + logger.info("Range for %s: %s to %s", station_id, start_date, end_date) + self._available_ranges[station_id] = (start_date, end_date) + return start_date, end_date + + except Exception as exc: + logger.error("Failed to discover range for %s: %s", station_id, exc) + return None def process_range(self, start_date: date, end_date: date, station_ids: list[str] | None = None): - """Process all stations for a given date range.""" + """Process all stations for a given date range, respecting the discovered archive range.""" if station_ids is None: station_ids = list(HISTORICAL_CONFIG.keys()) - current = start_date - while current <= end_date: - for sid in station_ids: - if sid not in HISTORICAL_CONFIG: + for sid in station_ids: + if sid not in HISTORICAL_CONFIG: + continue + + # Discover available archive range + archive_range = self.get_available_date_range(sid) + actual_start = start_date + actual_end = end_date + + if archive_range: + start_limit, end_limit = archive_range + actual_start = max(start_date, start_limit) + actual_end = min(end_date, end_limit) + + if actual_start > actual_end: + logger.info("Requested range for %s is outside available archive range (%s to %s)", + sid, start_limit, end_limit) continue + logger.info("Adjusted range for %s: %s to %s", sid, actual_start, actual_end) + + current = actual_start + while current <= actual_end: # Skip if we already have analysis for this date/station if self._is_already_processed(sid, current): logger.debug("Skipping %s for %s (already processed)", sid, current) - continue - - self.process_day(sid, current) - # Be polite to Infonieve - time.sleep(1.0) - - current += timedelta(days=1) + else: + self.process_day(sid, current) + # Be polite to Infonieve + time.sleep(1.0) + + current += timedelta(days=1) def auto_sync(self, station_ids: list[str] | None = None): """Find all dates in historical_station_raw that lack crowd analysis and fill them.""" @@ -99,7 +181,7 @@ class HistoricalWebcamCollector: time.sleep(1.0) def get_missing_dates(self, station_id: str) -> list[date]: - """Return a list of dates that have snow data but no crowd analysis.""" + """Return a list of dates that have snow data but no crowd analysis, filtered by available archive range.""" # 1. Get all dates with historical station data station_df = self.store.read_dataframe(HISTORICAL_STATION_TABLE, parse_dates=("date",)) if station_df.empty: @@ -108,14 +190,23 @@ class HistoricalWebcamCollector: station_dates = set(station_df[station_df["station_id"] == station_id]["date"].dt.date) - # 2. Get dates that already have crowd analysis + # 2. Discover available webcam archive range + archive_range = self.get_available_date_range(station_id) + if archive_range: + start_limit, end_limit = archive_range + station_dates = {d for d in station_dates if start_limit <= d <= end_limit} + if not station_dates: + logger.info("No station data dates fall within the discovered archive range for %s", station_id) + return [] + + # 3. Get dates that already have crowd analysis crowd_df = self.store.load_crowd_analyses(station_id=station_id) if crowd_df.empty: existing_dates = set() else: existing_dates = set(pd.to_datetime(crowd_df["timestamp"]).dt.date) - # 3. Missing is the difference + # 4. Missing is the difference missing = sorted(list(station_dates - existing_dates)) return missing diff --git a/setup.sh b/setup.sh new file mode 100755 index 0000000..8b0f9d4 --- /dev/null +++ b/setup.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Ski Predictor - One-time bootstrap script +# +# Usage: ./setup.sh +# +# This script sets up the environment, downloads historical data, +# and trains the ML models. After running it, start the unified +# daemon with: +# +# source .venv/bin/activate +# export TELEGRAM_BOT_TOKEN='your_token' +# uvicorn app.main:app --host 0.0.0.0 --port 8000 + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +VENV="$SCRIPT_DIR/.venv" +PYTHON="$VENV/bin/python" +DATA_DIR="$SCRIPT_DIR/data" +ENV_FILE="$SCRIPT_DIR/.env" + +# --------------------------------------------------------------- +# Colors +# --------------------------------------------------------------- +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +info() { echo -e "${GREEN}[INFO]${NC} $1"; } +warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } + +# --------------------------------------------------------------- +# 1. Create venv + install deps +# --------------------------------------------------------------- +if [ ! -d "$VENV" ]; then + info "Creating virtualenv..." + python3 -m venv "$VENV" +fi + +info "Installing dependencies..." +"$VENV/bin/pip" install -q -r "$SCRIPT_DIR/requirements.txt" + +# --------------------------------------------------------------- +# 2. Create data directories +# --------------------------------------------------------------- +mkdir -p "$DATA_DIR/raw" "$DATA_DIR/processed" "$SCRIPT_DIR/ml/models" + +# --------------------------------------------------------------- +# 3. Load environment from .env when present +# --------------------------------------------------------------- +if [ -f "$ENV_FILE" ]; then + info "Loading environment from $ENV_FILE" + set -a + # shellcheck disable=SC1090 + . "$ENV_FILE" + set +a +fi + +# --------------------------------------------------------------- +# 4. Download historical station data + weather + train models +# --------------------------------------------------------------- +info "Building full dataset (station history + weather + feature engineering + training)..." +"$PYTHON" -m scripts.build_full_dataset + +# --------------------------------------------------------------- +# 5. Download historical webcam images + crowd detection +# --------------------------------------------------------------- +info "Collecting historical webcam snapshots and crowd analysis..." +"$PYTHON" -m scripts.collect_historical_webcams + +# --------------------------------------------------------------- +# Summary +# --------------------------------------------------------------- +echo "" +info "=== Setup complete ===" +echo " Project: $SCRIPT_DIR" +echo " Python: $PYTHON" +echo " Data: $DATA_DIR" +echo "" +info "To start the unified daemon:" +echo " source .venv/bin/activate" +echo " export TELEGRAM_BOT_TOKEN='your_token'" +echo " uvicorn app.main:app --host 0.0.0.0 --port 8000" +echo "" diff --git a/start.sh b/start.sh deleted file mode 100755 index 3a759f2..0000000 --- a/start.sh +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env bash -# Ski Predictor - Setup and start script -# Usage: ./start.sh [--bot] [--cron] [--collect-now] -# -# --bot Start the Telegram bot (requires TELEGRAM_BOT_TOKEN) -# --cron Install the daily cron job (22:00) -# --collect-now Run the data collection pipeline immediately -# -# First run: ./start.sh --cron --collect-now -# With bot: ./start.sh --cron --collect-now --bot - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -VENV="$SCRIPT_DIR/.venv" -PYTHON="$VENV/bin/python" -DATA_DIR="$SCRIPT_DIR/data" -ENV_FILE="$SCRIPT_DIR/.env" - -# --------------------------------------------------------------- -# Colors -# --------------------------------------------------------------- -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -RED='\033[0;31m' -NC='\033[0m' - -info() { echo -e "${GREEN}[INFO]${NC} $1"; } -warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } -error() { echo -e "${RED}[ERROR]${NC} $1"; } - -# --------------------------------------------------------------- -# 1. Create virtualenv and install dependencies -# --------------------------------------------------------------- -if [ ! -d "$VENV" ]; then - info "Creating virtualenv..." - python3 -m venv "$VENV" -fi - -info "Installing dependencies..." -"$VENV/bin/pip" install -q -r "$SCRIPT_DIR/requirements.txt" -"$VENV/bin/pip" install -q pytest - -# --------------------------------------------------------------- -# 2. Create data directories -# --------------------------------------------------------------- -mkdir -p "$DATA_DIR/raw" "$DATA_DIR/processed" "$SCRIPT_DIR/ml/models" - -# --------------------------------------------------------------- -# 3. Parse arguments -# --------------------------------------------------------------- -DO_BOT=false -DO_CRON=false -DO_COLLECT=false - -for arg in "$@"; do - case "$arg" in - --bot) DO_BOT=true ;; - --cron) DO_CRON=true ;; - --collect-now) DO_COLLECT=true ;; - *) error "Unknown argument: $arg"; exit 1 ;; - esac -done - -# --------------------------------------------------------------- -# 3.5 Load environment from .env when present -# --------------------------------------------------------------- -if [ -f "$ENV_FILE" ]; then - info "Loading environment from $ENV_FILE" - set -a - # shellcheck disable=SC1090 - . "$ENV_FILE" - set +a -fi - -# --------------------------------------------------------------- -# 4. Install cron job -# --------------------------------------------------------------- -if [ "$DO_CRON" = true ]; then - CRON_CMD="0 22 * * * \"$PYTHON\" \"$SCRIPT_DIR/scripts/collect_daily_data.py\" >> \"$DATA_DIR/pipeline.log\" 2>&1" - - if crontab -l 2>/dev/null | grep -qF "collect_daily_data.py"; then - warn "Cron job already exists, skipping." - else - (crontab -l 2>/dev/null; echo "$CRON_CMD") | crontab - - info "Cron job installed (daily at 22:00)." - fi -fi - -# --------------------------------------------------------------- -# 5. Run initial data collection -# --------------------------------------------------------------- -if [ "$DO_COLLECT" = true ]; then - info "Running initial data collection..." - "$PYTHON" "$SCRIPT_DIR/scripts/collect_daily_data.py" 2>&1 | tee -a "$DATA_DIR/pipeline.log" - info "Data collection complete." -fi - -# --------------------------------------------------------------- -# 6. Start FastAPI backend (includes scheduler + bot subprocess) -# --------------------------------------------------------------- -if [ "$DO_BOT" = true ]; then - if [ -z "${TELEGRAM_BOT_TOKEN:-}" ]; then - error "TELEGRAM_BOT_TOKEN not set. Export it first:" - echo " export TELEGRAM_BOT_TOKEN='your_token_here'" - exit 1 - fi - - # Kill existing processes if running - if pgrep -f "uvicorn app.main:app|bot/telegram_bot.py|bot\\.telegram_bot" > /dev/null 2>&1; then - warn "Killing existing processes..." - pkill -f "uvicorn app.main:app|bot/telegram_bot.py|bot\\.telegram_bot" || true - sleep 1 - fi - - info "Starting FastAPI backend (scheduler + Telegram bot)..." - : > "$DATA_DIR/bot.log" - nohup env PYTHONPATH="$SCRIPT_DIR" "$VENV/bin/uvicorn" app.main:app \ - --host 0.0.0.0 --port 8000 \ - > "$DATA_DIR/bot.log" 2>&1 & - SERVER_PID=$! - info "Backend started (PID: $SERVER_PID). Logs: $DATA_DIR/bot.log" -fi - -# --------------------------------------------------------------- -# Summary -# --------------------------------------------------------------- -echo "" -info "=== Ski Predictor ===" -echo " Project: $SCRIPT_DIR" -echo " Python: $PYTHON" -echo " Data: $DATA_DIR" -if [ "$DO_CRON" = true ]; then - echo " Cron: Daily at 22:00" -fi -if [ "$DO_BOT" = true ]; then - echo " Server PID: $SERVER_PID" - echo " API: http://0.0.0.0:8000/api/v1" -fi -echo "" -info "Done." diff --git a/storage/__init__.py b/storage/__init__.py index 5a70a22..730dc0d 100644 --- a/storage/__init__.py +++ b/storage/__init__.py @@ -1,7 +1,6 @@ """SQLite-backed storage helpers for the ski predictor.""" from storage.sqlite_store import ( - AD_HOC_RUN_KIND, CROWD_ANALYSIS_TABLE, CURRENT_FORECASTS_TABLE, DEFAULT_DB_PATH, @@ -15,14 +14,12 @@ from storage.sqlite_store import ( LATEST_STATION_STATUS_TABLE, LATEST_WEATHER_TABLE, PAST_FORECASTS_TABLE, - PUBLISHED_RUN_KIND, RUNTIME_DATASET_TABLE, RUNTIME_FEATURED_TABLE, SQLiteStore, ) __all__ = [ - "AD_HOC_RUN_KIND", "CROWD_ANALYSIS_TABLE", "CURRENT_FORECASTS_TABLE", "DEFAULT_DB_PATH", @@ -36,7 +33,6 @@ __all__ = [ "LATEST_STATION_STATUS_TABLE", "LATEST_WEATHER_TABLE", "PAST_FORECASTS_TABLE", - "PUBLISHED_RUN_KIND", "RUNTIME_DATASET_TABLE", "RUNTIME_FEATURED_TABLE", "SQLiteStore", diff --git a/storage/sqlite_store.py b/storage/sqlite_store.py index 007bc75..3e8c0d7 100644 --- a/storage/sqlite_store.py +++ b/storage/sqlite_store.py @@ -48,8 +48,6 @@ CURRENT_FORECASTS_TABLE = "current_forecasts" PAST_FORECASTS_TABLE = "past_forecasts" HISTORICAL_ACTUALS_TABLE = "historical_actuals" -PUBLISHED_RUN_KIND = "published" -AD_HOC_RUN_KIND = "adhoc" _WEATHER_COLUMNS: list[str] = [ "date", @@ -174,115 +172,6 @@ class SQLiteStore: """Return the historical station raw dataset.""" return self.read_dataframe(HISTORICAL_STATION_TABLE, parse_dates=("date",)) - def save_prediction_run( - self, - payload: dict[str, Any], - *, - run_kind: str = PUBLISHED_RUN_KIND, - ) -> int: - """Persist a prediction payload and return the inserted run id.""" - generated_at = payload.get("generated_at") or self._now_iso() - prediction_date = str(payload["prediction_date"]) - stations = payload.get("stations", {}) - - with self.connect() as conn: - cursor = conn.execute( - """ - INSERT INTO prediction_runs (generated_at, prediction_date, run_kind) - VALUES (?, ?, ?) - """, - (generated_at, prediction_date, run_kind), - ) - run_id = int(cursor.lastrowid) - - rows = [] - for station_id, prediction in stations.items(): - rows.append( - ( - run_id, - station_id, - prediction.get("station_name"), - self._coerce_float(prediction.get("open_probability")), - self._coerce_float(prediction.get("km_open")), - prediction.get("crowd_level"), - prediction.get("weather_summary"), - json.dumps( - prediction.get("rule_overrides") or [], - ensure_ascii=False, - ), - prediction.get("prediction_source"), - ) - ) - - conn.executemany( - """ - INSERT INTO prediction_stations ( - run_id, - station_id, - station_name, - open_probability, - km_open, - crowd_level, - weather_summary, - rule_overrides_json, - prediction_source - ) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - rows, - ) - - logger.info( - "Saved prediction run %d (%s, %s) with %d stations.", - run_id, - run_kind, - prediction_date, - len(stations), - ) - return run_id - - def load_latest_predictions( - self, - *, - run_kind: str = PUBLISHED_RUN_KIND, - ) -> dict[str, Any] | None: - """Return the latest stored prediction payload for *run_kind*.""" - with self.connect() as conn: - return self._load_prediction_payload( - conn, - """ - SELECT id, generated_at, prediction_date, run_kind - FROM prediction_runs - WHERE run_kind = ? - ORDER BY generated_at DESC, id DESC - LIMIT 1 - """, - (run_kind,), - ) - - def load_predictions_for_date( - self, - *, - prediction_date: date | str, - run_kind: str = PUBLISHED_RUN_KIND, - ) -> dict[str, Any] | None: - """Return the latest stored prediction payload for a specific date.""" - if isinstance(prediction_date, date): - prediction_date = prediction_date.isoformat() - - with self.connect() as conn: - return self._load_prediction_payload( - conn, - """ - SELECT id, generated_at, prediction_date, run_kind - FROM prediction_runs - WHERE run_kind = ? AND prediction_date = ? - ORDER BY generated_at DESC, id DESC - LIMIT 1 - """, - (run_kind, str(prediction_date)), - ) - def save_training_run( self, *, @@ -724,27 +613,6 @@ class SQLiteStore: with self.connect() as conn: conn.executescript( """ - CREATE TABLE IF NOT EXISTS prediction_runs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - generated_at TEXT NOT NULL, - prediction_date TEXT NOT NULL, - run_kind TEXT NOT NULL - ); - - CREATE TABLE IF NOT EXISTS prediction_stations ( - run_id INTEGER NOT NULL, - station_id TEXT NOT NULL, - station_name TEXT, - open_probability REAL, - km_open REAL, - crowd_level TEXT, - weather_summary TEXT, - rule_overrides_json TEXT, - prediction_source TEXT, - PRIMARY KEY (run_id, station_id), - FOREIGN KEY (run_id) REFERENCES prediction_runs(id) ON DELETE CASCADE - ); - CREATE TABLE IF NOT EXISTS training_runs ( id INTEGER PRIMARY KEY AUTOINCREMENT, started_at TEXT NOT NULL, @@ -842,46 +710,6 @@ class SQLiteStore: return Path(db_path) return Path(os.environ.get("SKIPREDICTOR_DB_PATH", DEFAULT_DB_PATH)) - def _load_prediction_payload( - self, - conn: sqlite3.Connection, - run_query: str, - params: Sequence[Any], - ) -> dict[str, Any] | None: - """Load a prediction payload from a prediction-runs query.""" - run = conn.execute(run_query, tuple(params)).fetchone() - if run is None: - return None - - station_rows = conn.execute( - """ - SELECT station_id, station_name, open_probability, km_open, - crowd_level, weather_summary, rule_overrides_json, - prediction_source - FROM prediction_stations - WHERE run_id = ? - ORDER BY station_id - """, - (run["id"],), - ).fetchall() - - payload = { - "generated_at": run["generated_at"], - "prediction_date": run["prediction_date"], - "stations": {}, - } - for row in station_rows: - payload["stations"][row["station_id"]] = { - "station_name": row["station_name"], - "open_probability": row["open_probability"], - "km_open": row["km_open"], - "crowd_level": row["crowd_level"], - "weather_summary": row["weather_summary"], - "rule_overrides": json.loads(row["rule_overrides_json"] or "[]"), - "prediction_source": row["prediction_source"], - } - return payload - @staticmethod def _normalise_dataframe(df: pd.DataFrame) -> pd.DataFrame: """Convert unsupported pandas cell types to SQLite-safe values.""" diff --git a/tests/test_sqlite_store.py b/tests/test_sqlite_store.py index b4e2ab3..15f0eb6 100644 --- a/tests/test_sqlite_store.py +++ b/tests/test_sqlite_store.py @@ -5,70 +5,57 @@ from __future__ import annotations from storage import SQLiteStore -def test_prediction_run_roundtrip(tmp_path): - """Prediction payloads must round-trip through SQLite unchanged.""" +def test_current_forecasts_roundtrip(tmp_path): + """Forecasts must round-trip through current_forecasts table.""" store = SQLiteStore(tmp_path / "skipredictor.db") - payload = { - "generated_at": "2026-03-13T10:00:00+00:00", - "prediction_date": "2026-03-14", - "stations": { - "pajares": { - "station_name": "Valgrande-Pajares", - "open_probability": 0.82, - "km_open": 12.4, - "crowd_level": "medium", - "weather_summary": "Temp -2-5 C", - "rule_overrides": ["Wind below threshold."], - "prediction_source": "ml", - } - }, - } + forecasts = [ + { + "station_id": "pajares", + "prediction_date": "2026-03-14", + "open_probability": 0.82, + "km_open": 12.4, + "crowd_level": "medium", + "weather_summary": "Temp -2-5 C", + "rule_notes": ["Wind below threshold."], + "prediction_source": "ml", + } + ] - store.save_prediction_run(payload) + store.save_current_forecasts(forecasts, run_hour=10) + loaded = store.load_current_forecasts() - loaded = store.load_latest_predictions() - assert loaded == payload + assert len(loaded) == 1 + row = loaded[0] + assert row["station_id"] == "pajares" + assert row["prediction_date"] == "2026-03-14" + assert row["open_probability"] == 0.82 + assert row["km_open"] == 12.4 -def test_load_predictions_for_date_ignores_newer_other_dates(tmp_path): - """Date-specific loads must not be displaced by a newer run for tomorrow.""" +def test_archive_moves_to_past_forecasts(tmp_path): + """Archiving must move rows from current to past_forecasts.""" store = SQLiteStore(tmp_path / "skipredictor.db") - today_payload = { - "generated_at": "2026-03-13T06:00:00+00:00", - "prediction_date": "2026-03-13", - "stations": { - "pajares": { - "station_name": "Valgrande-Pajares", - "open_probability": 0.79, - "km_open": 10.1, - "crowd_level": "low", - "weather_summary": "Temp 0-5 C", - "rule_overrides": [], - "prediction_source": "ml", - } - }, - } - tomorrow_payload = { - "generated_at": "2026-03-13T07:00:00+00:00", - "prediction_date": "2026-03-14", - "stations": { - "pajares": { - "station_name": "Valgrande-Pajares", - "open_probability": 0.88, - "km_open": 7.4, - "crowd_level": "medium", - "weather_summary": "Temp 2-7 C", - "rule_overrides": ["Warm rain expected."], - "prediction_source": "hybrid", - } - }, - } + forecasts = [ + { + "station_id": "pajares", + "prediction_date": "2026-03-14", + "open_probability": 0.79, + "km_open": 10.1, + "crowd_level": "low", + "weather_summary": "Temp 0-5 C", + "rule_notes": [], + "prediction_source": "ml", + } + ] - store.save_prediction_run(today_payload) - store.save_prediction_run(tomorrow_payload) + store.save_current_forecasts(forecasts, run_hour=5) + archived = store.archive_current_forecasts() - loaded = store.load_predictions_for_date(prediction_date="2026-03-13") - assert loaded == today_payload + assert archived == 1 + assert store.load_current_forecasts() == [] + past = store.load_past_forecasts() + assert len(past) == 1 + assert past[0]["station_id"] == "pajares" def test_feature_importances_replace_latest_values(tmp_path): diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py index 1a4d311..a544ec1 100644 --- a/tests/test_telegram_bot.py +++ b/tests/test_telegram_bot.py @@ -70,31 +70,53 @@ from bot import telegram_bot class FakeStore: - """In-memory stand-in for SQLiteStore used in selection tests.""" + """In-memory stand-in for SQLiteStore used in selection tests. - def __init__(self, by_date: dict[str, dict], latest: dict | None = None) -> None: - self.by_date = by_date - self.latest = latest + Exposes ``load_current_forecasts()`` which returns flat forecast rows + matching the ``current_forecasts`` table schema. + """ + + def __init__( + self, + rows: list[dict] | None = None, + ) -> None: + self.rows = rows or [] self.db_path = "/tmp/fake.db" - self.requested_dates: list[str] = [] - def load_predictions_for_date(self, *, prediction_date: str, run_kind: str): - self.requested_dates.append(prediction_date) - return self.by_date.get(prediction_date) + def load_current_forecasts(self, station_id=None): + if station_id is not None: + return [r for r in self.rows if r["station_id"] == station_id] + return list(self.rows) - def load_latest_predictions(self, *, run_kind: str): - return self.latest + +def _make_forecast_row( + station_id: str, + prediction_date: str, + open_probability: float = 0.5, +) -> dict: + """Build a minimal forecast row matching the current_forecasts schema.""" + return { + "id": 1, + "generated_at": "2026-03-13T10:00:00+00:00", + "run_hour": 10, + "station_id": station_id, + "prediction_date": prediction_date, + "open_probability": open_probability, + "km_open": 10.0, + "crowd_level": "medium", + "weather_summary": None, + "rule_notes_json": "[]", + "prediction_source": "hybrid", + } def test_load_predictions_prefers_today_before_ten(): """Before 10:00 local time the bot should prefer today's run.""" - today_payload = {"prediction_date": "2026-03-13", "stations": {}} - tomorrow_payload = {"prediction_date": "2026-03-14", "stations": {}} store = FakeStore( - { - "2026-03-13": today_payload, - "2026-03-14": tomorrow_payload, - } + rows=[ + _make_forecast_row("pajares", "2026-03-13"), + _make_forecast_row("pajares", "2026-03-14"), + ] ) loaded = telegram_bot.load_predictions( @@ -102,19 +124,17 @@ def test_load_predictions_prefers_today_before_ten(): store=store, ) - assert loaded == today_payload - assert store.requested_dates == ["2026-03-13"] + assert loaded is not None + assert loaded["prediction_date"] == "2026-03-13" def test_load_predictions_prefers_tomorrow_after_ten(): """From 10:00 onwards the bot should prefer tomorrow's run.""" - today_payload = {"prediction_date": "2026-03-13", "stations": {}} - tomorrow_payload = {"prediction_date": "2026-03-14", "stations": {}} store = FakeStore( - { - "2026-03-13": today_payload, - "2026-03-14": tomorrow_payload, - } + rows=[ + _make_forecast_row("pajares", "2026-03-13"), + _make_forecast_row("pajares", "2026-03-14"), + ] ) loaded = telegram_bot.load_predictions( @@ -122,22 +142,25 @@ def test_load_predictions_prefers_tomorrow_after_ten(): store=store, ) - assert loaded == tomorrow_payload - assert store.requested_dates == ["2026-03-14"] + assert loaded is not None + assert loaded["prediction_date"] == "2026-03-14" def test_load_predictions_falls_back_when_preferred_dates_are_missing(): - """If the preferred dates are absent, fall back to the latest published run.""" - fallback_payload = {"prediction_date": "2026-03-16", "stations": {}} - store = FakeStore({}, latest=fallback_payload) + """If the preferred dates are absent, fall back to whatever is available.""" + store = FakeStore( + rows=[ + _make_forecast_row("pajares", "2026-03-16"), + ] + ) loaded = telegram_bot.load_predictions( now=datetime(2026, 3, 13, 8, 0, tzinfo=ZoneInfo("Europe/Madrid")), store=store, ) - assert loaded == fallback_payload - assert store.requested_dates == ["2026-03-13", "2026-03-14"] + assert loaded is not None + assert loaded["prediction_date"] == "2026-03-16" def test_prediction_dates_window_returns_consecutive_dates(): diff --git a/yolov8n.pt b/yolov8n.pt new file mode 100644 index 0000000..0db4ca4 Binary files /dev/null and b/yolov8n.pt differ