From 9c8ba0357493d18d463161095b56982c4a6871c0 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Fri, 13 Mar 2026 06:50:18 +0100 Subject: [PATCH] feat(storage): migrate project to sqlite --- DEPLOYMENT.md | 27 +- LESSONS.md | 12 + bot/telegram_bot.py | 106 +---- data_sources/crowd_analyzer.py | 64 +-- data_sources/infonieve_historical.py | 16 +- data_sources/station_scraper.py | 22 +- data_sources/weather_api.py | 27 +- ml/evaluate_model.py | 84 ++-- ml/train_model.py | 53 ++- pipeline/build_dataset.py | 160 +++---- scripts/build_full_dataset.py | 152 +++---- scripts/collect_daily_data.py | 155 ++++--- scripts/retrain_model.py | 155 +------ storage/__init__.py | 37 ++ storage/sqlite_store.py | 651 +++++++++++++++++++++++++++ tests/test_crowd_analyzer.py | 60 +-- tests/test_sqlite_store.py | 111 +++++ 17 files changed, 1204 insertions(+), 688 deletions(-) create mode 100644 storage/__init__.py create mode 100644 storage/sqlite_store.py create mode 100644 tests/test_sqlite_store.py diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 952746e..2627d0d 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -35,10 +35,10 @@ This downloads 16+ seasons of station data from infonieve.es, fetches matching h .venv/bin/python scripts/build_full_dataset.py ``` -Step 2 fetches weather data from Open-Meteo in 1-year chunks. Each chunk is cached in `data/raw/weather_cache/`, so reruns skip already-fetched years. First run may need 15-20 min due to API rate limits. Subsequent runs are fast. +Step 2 fetches weather data from Open-Meteo in 1-year chunks and persists the full historical state in SQLite. First run may need 15-20 min due to API rate limits. Subsequent runs reuse the database cache. Output: -- `data/processed/dataset_featured.csv` - Full dataset with engineered features +- `data/processed/skipredictor.db` - SQLite database with historical/runtime datasets, predictions, and reports - `ml/models/station_open_model.joblib` - Open/closed classifier (RandomForest) - `ml/models/km_open_model.joblib` - Km open regressor (GradientBoosting) - `ml/models/crowd_level_model.joblib` - Crowd classifier (LightGBM) @@ -52,7 +52,7 @@ As the daily pipeline collects new data, retrain periodically to improve the mod .venv/bin/python scripts/retrain_model.py ``` -This loads `data/processed/dataset_featured.csv`, trains all models, evaluates with cross-validation, and overwrites the model files in `ml/models/`. +This loads the historical featured dataset from SQLite, trains all models, evaluates them, and overwrites the model files in `ml/models/`. ### Recommended retraining schedule @@ -82,9 +82,9 @@ Runs every day at 22:00 (after stations close for the day): The pipeline executes 5 steps: 1. Fetch weather forecasts from Open-Meteo for all 3 stations 2. Scrape current station status from infonieve.es (lifts, km, snow depth) -3. Append today's data to `data/processed/dataset.csv` -4. Run feature engineering -> `data/processed/dataset_featured.csv` -5. Generate next-day predictions -> `data/processed/predictions_latest.json` +3. Append today's data to the SQLite runtime dataset tables +4. Run feature engineering into SQLite runtime feature tables +5. Generate next-day predictions and publish them into SQLite for the bot ### Monthly model retraining (optional, recommended) @@ -177,15 +177,20 @@ journalctl -u skipredictor-bot -f ### Check predictions ```bash -cat data/processed/predictions_latest.json | python -m json.tool +sqlite3 data/processed/skipredictor.db " +SELECT generated_at, prediction_date, run_kind +FROM prediction_runs +ORDER BY generated_at DESC, id DESC +LIMIT 5; +" ``` ### Check dataset health ```bash .venv/bin/python -c " -import pandas as pd -df = pd.read_csv('data/processed/dataset_featured.csv') +from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore +df = SQLiteStore().read_dataframe(HISTORICAL_FEATURED_TABLE, parse_dates=('date',)) print(f'Rows: {len(df)}') print(f'Date range: {df[\"date\"].min()} to {df[\"date\"].max()}') print(f'Stations: {df[\"station_id\"].unique()}') @@ -225,6 +230,6 @@ skipredictor/ ├── start.sh # Setup and launch script ├── requirements.txt # Python dependencies └── data/ # Runtime data (gitignored) - ├── raw/ # Station CSVs, weather cache - └── processed/ # Dataset, features, predictions + ├── raw/ # Webcam snapshots and transient downloads + └── processed/ # SQLite database and runtime logs ``` diff --git a/LESSONS.md b/LESSONS.md index 8dac01b..3c8aa95 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -9,3 +9,15 @@ **Example:** The production JSON at `/opt/skipredictor/data/processed/predictions_latest.json` on the server contained valid predictions under `stations`, and the checked-in [telegram_bot.py](/home/dasemu/Hacking/Darío Sevilla/skipredictor/bot/telegram_bot.py) still expected top-level station keys plus legacy fields like `station_open_probability`, while [collect_daily_data.py](/home/dasemu/Hacking/Darío Sevilla/skipredictor/scripts/collect_daily_data.py) writes predictions under `stations` with fields such as `open_probability` and `km_open`. **Files affected:** `bot/telegram_bot.py`, `scripts/collect_daily_data.py` + +## Migration Scope - 2026-03-13 + +**What went wrong:** I started a database migration while preserving compatibility fallbacks to the previous CSV/JSON storage flow. + +**Root cause:** I optimized for low-risk rollout instead of following the user's explicit migration intent. In this repository, that creates extra complexity and leaves ambiguous sources of truth. + +**Prevention rule:** When the user asks for a migration in this repo and does not request coexistence, implement a single authoritative path after the migration. Do not keep legacy file fallbacks unless the user asks for a transitional phase. + +**Example:** The SQLite migration must make the bot, the daily pipeline, and model training read from the database directly instead of keeping fallbacks to `data/processed/predictions_latest.json` or `data/processed/dataset_featured.csv`. + +**Files affected:** `bot/telegram_bot.py`, `scripts/collect_daily_data.py`, `ml/train_model.py` diff --git a/bot/telegram_bot.py b/bot/telegram_bot.py index f6e4825..bcdedab 100644 --- a/bot/telegram_bot.py +++ b/bot/telegram_bot.py @@ -6,8 +6,7 @@ Serves next-day predictions for three ski stations in northern Spain: - San Isidro (/sanisidro) - Fuentes de Invierno (/fuentes) -The bot reads predictions from the JSON file generated by the daily -pipeline at data/processed/predictions_latest.json. +The bot reads the latest published prediction run from SQLite. Usage: Set the TELEGRAM_BOT_TOKEN environment variable and run: @@ -15,16 +14,16 @@ Usage: or call main() directly. """ -import json import logging import os -from pathlib import Path from typing import Any from telegram import Update from telegram.constants import ParseMode from telegram.ext import Application, CommandHandler, ContextTypes +from storage import PUBLISHED_RUN_KIND, SQLiteStore + # --------------------------------------------------------------------------- # Logging # --------------------------------------------------------------------------- @@ -35,14 +34,6 @@ logging.basicConfig( ) logger = logging.getLogger(__name__) -# --------------------------------------------------------------------------- -# Paths -# --------------------------------------------------------------------------- - -# Resolve project root relative to this file regardless of cwd. -_PROJECT_ROOT = Path(__file__).resolve().parent.parent -PREDICTIONS_FILE = _PROJECT_ROOT / "data" / "processed" / "predictions_latest.json" - # --------------------------------------------------------------------------- # Station metadata (mirrors config/stations.yaml without adding a runtime # dependency on pyyaml inside the bot module itself). @@ -69,23 +60,19 @@ STATIONS = { def load_predictions() -> dict | None: - """Load the latest predictions from the JSON file produced by the pipeline. + """Load the latest published predictions from SQLite. - Returns the parsed dictionary on success, or None if the file is missing - or cannot be decoded. + Returns the parsed dictionary on success, or None if no published + prediction run exists yet. """ - if not PREDICTIONS_FILE.exists(): - logger.warning("Predictions file not found: %s", PREDICTIONS_FILE) + store = SQLiteStore() + data = store.load_latest_predictions(run_kind=PUBLISHED_RUN_KIND) + if data is None: + logger.warning("No published prediction run found in %s", store.db_path) return None - try: - with PREDICTIONS_FILE.open(encoding="utf-8") as fh: - data = json.load(fh) - logger.info("Predictions loaded from %s", PREDICTIONS_FILE) - return data - except json.JSONDecodeError as exc: - logger.error("Failed to decode predictions file: %s", exc) - return None + logger.info("Predictions loaded from SQLite (%s)", store.db_path) + return data # --------------------------------------------------------------------------- @@ -114,16 +101,11 @@ def _open_label(probability: float) -> str: def _extract_station_predictions(payload: dict[str, Any]) -> dict[str, dict[str, Any]]: - """Return the per-station prediction map from either supported schema.""" + """Return the per-station prediction map.""" stations = payload.get("stations") if isinstance(stations, dict): return stations - - return { - key: value - for key, value in payload.items() - if key in STATIONS and isinstance(value, dict) - } + return {} def _message_title(station_name: str, prediction_date: str | None) -> str: @@ -142,7 +124,7 @@ def format_station_prediction( Args: station_key: One of 'pajares', 'sanisidro', 'fuentes'. - prediction: Sub-dictionary for this station from predictions_latest.json. + prediction: Sub-dictionary for this station from SQLite. prediction_date: ISO date string for the prediction target day. Returns: @@ -152,33 +134,12 @@ def format_station_prediction( station_name = meta["name"] max_km = meta["max_km"] - open_prob = float( - prediction.get( - "open_probability", - prediction.get("station_open_probability", 0.0), - ) - ) - km_open = float( - prediction.get( - "km_open", - prediction.get("km_open_prediction", 0.0), - ) - ) - crowd_raw = str( - prediction.get( - "crowd_level", - prediction.get("crowd_level_prediction", "unknown"), - ) - ) + open_prob = float(prediction.get("open_probability", 0.0)) + km_open = float(prediction.get("km_open", 0.0)) + crowd_raw = str(prediction.get("crowd_level", "unknown")) weather_summary = prediction.get("weather_summary") - - source = str( - prediction.get( - "prediction_source", - prediction.get("source", "prediccion hibrida (reglas + ML)"), - ) - ) + source = str(prediction.get("prediction_source", "prediccion hibrida (reglas + ML)")) open_pct = int(round(open_prob * 100)) open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)" @@ -189,33 +150,6 @@ def format_station_prediction( weather_block = "" if weather_summary: weather_block = f"\nTiempo previsto:\n{weather_summary}\n" - else: - # Legacy schema support: weather as structured sub-dict. - weather: dict[str, Any] = prediction.get("weather_forecast", {}) - temp_min = weather.get("temperature_min") - temp_max = weather.get("temperature_max") - snowfall = weather.get("snowfall_cm") - wind_speed = weather.get("wind_speed_kmh") - wind_gust = weather.get("wind_gust_kmh") - - weather_lines: list[str] = [] - if temp_min is not None and temp_max is not None: - weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C") - elif temp_max is not None: - weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C") - - if snowfall is not None: - weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos") - - if wind_speed is not None and wind_gust is not None: - weather_lines.append( - f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)" - ) - elif wind_speed is not None: - weather_lines.append(f"Viento: {wind_speed:.0f} km/h") - - if weather_lines: - weather_block = "\nTiempo previsto:\n" + "\n".join(weather_lines) + "\n" overrides = prediction.get("rule_overrides") or [] reasons_block = "" @@ -247,7 +181,7 @@ def _no_prediction_message(station_name: str) -> str: def _unavailable_message() -> str: - """Return a message when the predictions file cannot be loaded at all.""" + """Return a message when published predictions cannot be loaded at all.""" return ( "No se han podido cargar las predicciones.\n\n" "Asegurate de que el pipeline diario se ha ejecutado correctamente. " diff --git a/data_sources/crowd_analyzer.py b/data_sources/crowd_analyzer.py index ad25d73..7dd355c 100644 --- a/data_sources/crowd_analyzer.py +++ b/data_sources/crowd_analyzer.py @@ -10,8 +10,7 @@ Detected object counts are mapped to three crowd density levels: * **medium** – 20–50 cars OR 10–30 people * **high** – more than 50 cars OR more than 30 people -Analysis results are persisted as JSON files in ``data/raw/`` following the -naming pattern ``crowd_{station_id}_{date}.json``. +Analysis results are persisted in the project SQLite database. Typical usage:: @@ -22,20 +21,19 @@ Typical usage:: from __future__ import annotations -import json import logging import warnings -from datetime import date, datetime +from datetime import datetime from pathlib import Path from typing import Any import yaml +from storage import SQLiteStore logger = logging.getLogger(__name__) BASE_DIR = Path(__file__).resolve().parent.parent CONFIG_PATH = BASE_DIR / "config" / "stations.yaml" -RAW_DATA_DIR = BASE_DIR / "data" / "raw" # YOLO model weights file – downloaded automatically on first use. YOLO_MODEL_WEIGHTS = "yolov8n.pt" @@ -70,22 +68,20 @@ class CrowdAnalyzer: model_weights: YOLOv8 weights identifier passed to ``ultralytics.YOLO()``. Defaults to ``"yolov8n.pt"`` (nano model). - output_dir: - Directory where JSON result files are written. Created if it does - not exist. Defaults to ``data/raw/``. + store: + SQLite store where analysis results are written. """ def __init__( self, config_path: Path = CONFIG_PATH, model_weights: str = YOLO_MODEL_WEIGHTS, - output_dir: Path = RAW_DATA_DIR, + store: SQLiteStore | None = None, ) -> None: self.config_path = config_path self.model_weights = model_weights - self.output_dir = output_dir + self.store = store if store is not None else SQLiteStore() self.stations = self._load_stations() - self.output_dir.mkdir(parents=True, exist_ok=True) self._model: Any = None # Lazy-loaded on first inference call. # ------------------------------------------------------------------ @@ -170,7 +166,7 @@ class CrowdAnalyzer: """Capture the latest webcam snapshot for *station_id* and analyse it. Downloads one image via :class:`~data_sources.webcam_collector.WebcamCollector`, - runs object detection, saves the result as a JSON file and returns the + runs object detection, saves the result to SQLite, and returns the analysis dict. Parameters @@ -199,7 +195,7 @@ class CrowdAnalyzer: station_id, ) result = self._empty_result(station_id, image_path=None) - self._save_result(result, station_id) + self._save_result(result) return result # Analyse only the first captured image to keep latency low. @@ -215,12 +211,12 @@ class CrowdAnalyzer: exc, ) result = self._empty_result(station_id, image_path=image_path) - self._save_result(result, station_id) + self._save_result(result) return result analysis["station_id"] = station_id analysis["image_path"] = image_path - self._save_result(analysis, station_id) + self._save_result(analysis) return analysis def analyze_all_stations(self) -> dict[str, dict[str, Any]]: @@ -334,35 +330,11 @@ class CrowdAnalyzer: "timestamp": datetime.now().isoformat(timespec="seconds"), } - def _save_result(self, result: dict[str, Any], station_id: str) -> None: - """Persist an analysis result dict as a JSON file. - - Filename format: ``crowd_{station_id}_{date}.json`` - - Parameters - ---------- - result: - Analysis dict to serialise. - station_id: - Used to construct the output filename. - """ - today = date.today().strftime("%Y-%m-%d") - filename = self.output_dir / f"crowd_{station_id}_{today}.json" - - # Append to an existing file (list of results) or create a new one. - if filename.exists(): - try: - existing = json.loads(filename.read_text(encoding="utf-8")) - if not isinstance(existing, list): - existing = [existing] - except (json.JSONDecodeError, OSError): - existing = [] - else: - existing = [] - - existing.append(result) - filename.write_text( - json.dumps(existing, indent=2, ensure_ascii=False), - encoding="utf-8", + def _save_result(self, result: dict[str, Any]) -> None: + """Persist an analysis result dict to SQLite.""" + row_id = self.store.save_crowd_analysis(result) + logger.info( + "Saved crowd analysis row %d for station=%s", + row_id, + result.get("station_id"), ) - logger.info("Saved crowd analysis to %s", filename) diff --git a/data_sources/infonieve_historical.py b/data_sources/infonieve_historical.py index c655e3b..7182357 100644 --- a/data_sources/infonieve_historical.py +++ b/data_sources/infonieve_historical.py @@ -11,7 +11,7 @@ Columns in the TSV: pistasprocessed, minprocessed, maxprocessed, idestado This module downloads all available seasons for the three target stations -and saves the combined data as CSVs in data/raw/. +and stores the combined raw history in SQLite. """ import io @@ -22,11 +22,11 @@ from pathlib import Path import pandas as pd import requests +from storage import SQLiteStore + logger = logging.getLogger(__name__) _PROJECT_ROOT = Path(__file__).resolve().parent.parent -_RAW_DIR = _PROJECT_ROOT / "data" / "raw" - _BASE_URL = "https://www.infonieve.es/estacion-esqui.historico-nieve.tsv.php" # Infonieve internal IDs for our stations @@ -101,7 +101,7 @@ def download_season( return df -def download_all_history() -> pd.DataFrame: +def download_all_history(store: SQLiteStore | None = None) -> pd.DataFrame: """Download all available historical data for all three stations. Returns @@ -145,11 +145,9 @@ def download_all_history() -> pd.DataFrame: # Sort combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True) - # Save - _RAW_DIR.mkdir(parents=True, exist_ok=True) - output_path = _RAW_DIR / "station_historical_all.csv" - combined.to_csv(output_path, index=False) - logger.info("Historical data saved to %s: %d total rows.", output_path, len(combined)) + effective_store = store if store is not None else SQLiteStore() + effective_store.save_historical_station_raw(combined) + logger.info("Historical data saved to SQLite: %d total rows.", len(combined)) # Summary for sid in _STATION_IDS: diff --git a/data_sources/station_scraper.py b/data_sources/station_scraper.py index bd5dfb9..aa85135 100644 --- a/data_sources/station_scraper.py +++ b/data_sources/station_scraper.py @@ -10,12 +10,8 @@ managed by the government of Asturias/León: Primary source: infonieve.es (https://www.infonieve.es/estacion-esqui/{slug}/) Fallback: returns None values with a logged warning when scraping fails. - -Raw responses are saved to: - data/raw/station_{station_id}_{date}.json """ -import json import logging import re from datetime import date @@ -34,8 +30,6 @@ logger = logging.getLogger(__name__) _PROJECT_ROOT = Path(__file__).resolve().parent.parent _CONFIG_PATH = _PROJECT_ROOT / "config" / "stations.yaml" -_RAW_DATA_DIR = _PROJECT_ROOT / "data" / "raw" - _USER_AGENT = ( "Mozilla/5.0 (X11; Linux x86_64) " "AppleWebKit/537.36 (KHTML, like Gecko) " @@ -94,19 +88,6 @@ def _get_session() -> requests.Session: return session -def _save_raw(station_id: str, payload: dict) -> None: - """Persist raw scraped payload to data/raw/ as JSON.""" - _RAW_DATA_DIR.mkdir(parents=True, exist_ok=True) - today = date.today().isoformat() - filename = _RAW_DATA_DIR / f"station_{station_id}_{today}.json" - try: - with open(filename, "w", encoding="utf-8") as fh: - json.dump(payload, fh, ensure_ascii=False, indent=2) - logger.debug("Raw data saved to %s", filename) - except OSError as exc: - logger.warning("Could not save raw data for %s: %s", station_id, exc) - - def _parse_float(text: Optional[str]) -> Optional[float]: """Extract the first float-like value from a string, or return None.""" if not text: @@ -305,7 +286,6 @@ class StationScraper: logger.info("Scraping station: %s", station_id) record = self._scrape_infonieve(station_id) - _save_raw(station_id, record) return record def scrape_all_stations(self) -> list[dict]: @@ -402,4 +382,4 @@ if __name__ == "__main__": ) scraper = StationScraper() records = scraper.scrape_all_stations() - print(json.dumps(records, indent=2, ensure_ascii=False)) + print(records) diff --git a/data_sources/weather_api.py b/data_sources/weather_api.py index a4c2362..f19b3ea 100644 --- a/data_sources/weather_api.py +++ b/data_sources/weather_api.py @@ -1,7 +1,7 @@ """Weather data collector using Open-Meteo API. Fetches historical and forecast weather data for ski stations -defined in config/stations.yaml. No API key required. +defined in config/stations.yaml and persists snapshots in SQLite. Historical endpoint: https://archive-api.open-meteo.com/v1/archive Forecast endpoint: https://api.open-meteo.com/v1/forecast @@ -24,8 +24,6 @@ logger = logging.getLogger(__name__) BASE_DIR = Path(__file__).resolve().parent.parent CONFIG_PATH = BASE_DIR / "config" / "stations.yaml" -RAW_DATA_DIR = BASE_DIR / "data" / "raw" - HISTORICAL_URL = "https://archive-api.open-meteo.com/v1/archive" FORECAST_URL = "https://api.open-meteo.com/v1/forecast" @@ -65,7 +63,6 @@ class WeatherCollector: def __init__(self, config_path: Path = CONFIG_PATH) -> None: self.config_path = config_path self.stations = self._load_stations() - RAW_DATA_DIR.mkdir(parents=True, exist_ok=True) # ------------------------------------------------------------------ # Public API @@ -126,8 +123,6 @@ class WeatherCollector: raw = self._request(HISTORICAL_URL, params) df = self._parse_response(raw, station_id) - - self._save(df, station_id) return df def get_forecast( @@ -169,8 +164,6 @@ class WeatherCollector: raw = self._request(FORECAST_URL, params) df = self._parse_response(raw, station_id) - - self._save(df, station_id) return df def collect_all_stations( @@ -338,21 +331,3 @@ class WeatherCollector: # Keep only the expected column order columns = ["date"] + DAILY_VARIABLES + ["station_id"] return df[columns] - - def _save(self, df: pd.DataFrame, station_id: str) -> None: - """Persist a weather DataFrame to a CSV file. - - Filename format: ``weather_{station_id}_{date}.csv`` - where ``{date}`` is today's date (the collection date). - - Parameters - ---------- - df: - DataFrame to save. - station_id: - Station identifier used in the filename. - """ - today = date.today().strftime("%Y-%m-%d") - filename = RAW_DATA_DIR / f"weather_{station_id}_{today}.csv" - df.to_csv(filename, index=False) - logger.info("Saved weather data to %s", filename) diff --git a/ml/evaluate_model.py b/ml/evaluate_model.py index c564d60..b94561b 100644 --- a/ml/evaluate_model.py +++ b/ml/evaluate_model.py @@ -1,14 +1,13 @@ """Evaluate trained ski-condition prediction models. -Loads each model from ml/models/, runs evaluation on a held-out test split -of the processed feature dataset, computes task-appropriate metrics, and -writes a JSON report to ml/models/evaluation_report.json. +Loads each model from ``ml/models/``, runs evaluation on a held-out test +split of the processed feature dataset, computes task-appropriate metrics, +and persists the evaluation report in SQLite. Classification metrics: accuracy, precision, recall, F1 (macro), AUC. Regression metrics: MAE, RMSE, R2. """ -import json import logging from pathlib import Path from typing import Any @@ -28,15 +27,15 @@ from sklearn.metrics import ( from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder +from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore + logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Paths # --------------------------------------------------------------------------- _REPO_ROOT = Path(__file__).resolve().parents[1] -DATASET_PATH = _REPO_ROOT / "data" / "processed" / "dataset_featured.csv" MODELS_DIR = _REPO_ROOT / "ml" / "models" -REPORT_PATH = MODELS_DIR / "evaluation_report.json" # Test split fraction. With a small dataset 20 % gives at least a handful of # samples per class while keeping enough for stratification. @@ -59,8 +58,10 @@ class ModelEvaluator: Parameters ---------- - dataset_path: - Path to the processed feature CSV. + store: + SQLite store from which the feature dataset is loaded. + dataset_table: + SQLite table containing the feature dataset. models_dir: Directory containing the trained ``.joblib`` model files. test_size: @@ -69,11 +70,13 @@ class ModelEvaluator: def __init__( self, - dataset_path: Path | str = DATASET_PATH, + store: SQLiteStore | None = None, + dataset_table: str = HISTORICAL_FEATURED_TABLE, models_dir: Path | str = MODELS_DIR, test_size: float = TEST_SIZE, ) -> None: - self.dataset_path = Path(dataset_path) + self.store = store if store is not None else SQLiteStore() + self.dataset_table = dataset_table self.models_dir = Path(models_dir) self.test_size = test_size @@ -87,16 +90,13 @@ class ModelEvaluator: # ------------------------------------------------------------------ def evaluate_all(self) -> dict[str, dict[str, float]]: - """Evaluate all trained models and persist a JSON report. + """Evaluate all trained models and persist the report to SQLite. Returns ------- dict ``{target_name: {metric_name: value, ...}}`` - Side effects - ------------ - Writes ``ml/models/evaluation_report.json``. """ self._load_dataset() self._load_models() @@ -121,9 +121,8 @@ class ModelEvaluator: def get_feature_importance(self, model_name: str) -> list[tuple[str, float]]: """Return feature importances for a trained model, sorted descending. - This method reads the pre-computed importance JSON written by - ``ModelTrainer`` rather than recomputing from the model, so the - trainer must have been run first. + This method reads the latest feature importances written by + ``ModelTrainer`` into SQLite, so the trainer must have been run first. Parameters ---------- @@ -137,7 +136,7 @@ class ModelEvaluator: Raises ------ FileNotFoundError - If the corresponding JSON importance file does not exist. + If no persisted feature importances exist for the requested target. ValueError If *model_name* is not a recognised target. """ @@ -147,18 +146,13 @@ class ModelEvaluator: f"Valid names: {list(TARGETS.keys())}" ) - importance_path = self.models_dir / f"{model_name}_feature_importances.json" - if not importance_path.exists(): + importances = self.store.load_feature_importances(model_name) + if not importances: raise FileNotFoundError( - f"Feature importance file not found: {importance_path}. " + f"Feature importances not found in SQLite for target: {model_name}. " "Run train_model.py first." ) - - with open(importance_path, encoding="utf-8") as fh: - raw: dict[str, float] = json.load(fh) - - sorted_importances = sorted(raw.items(), key=lambda kv: kv[1], reverse=True) - return sorted_importances + return importances # ------------------------------------------------------------------ # Private helpers @@ -166,16 +160,30 @@ class ModelEvaluator: def _load_dataset(self) -> None: """Load the processed dataset and derive feature column names.""" - if not self.dataset_path.exists(): + self._df = self.store.read_dataframe( + self.dataset_table, + parse_dates=("date",), + ) + if self._df.empty: raise FileNotFoundError( - f"Processed dataset not found at {self.dataset_path}. " + f"Processed dataset not found in SQLite table {self.dataset_table}. " "Run the pipeline first." ) - logger.info("Loading dataset from %s", self.dataset_path) - self._df = pd.read_csv(self.dataset_path, parse_dates=["date"]) + logger.info("Loading dataset from SQLite table %s", self.dataset_table) - non_feature_cols = set(TARGETS.keys()) | {"date", "station"} + non_feature_cols = set(TARGETS.keys()) | { + "date", + "station", + "station_id", + "open_status", + "snow_quality", + "season", + } + string_cols = set( + self._df.select_dtypes(include=["object", "string"]).columns + ) + non_feature_cols |= string_cols self._feature_columns = [ col for col in self._df.columns if col not in non_feature_cols ] @@ -332,11 +340,13 @@ class ModelEvaluator: } def _save_report(self, report: dict[str, Any]) -> None: - """Write the evaluation report to disk as JSON.""" - self.models_dir.mkdir(parents=True, exist_ok=True) - with open(REPORT_PATH, "w", encoding="utf-8") as fh: - json.dump(report, fh, indent=2) - logger.info("Evaluation report saved to %s", REPORT_PATH) + """Persist the evaluation report to SQLite.""" + run_id = self.store.save_evaluation_run( + dataset_table=self.dataset_table, + report=report, + models_dir=str(self.models_dir), + ) + logger.info("Evaluation report saved to SQLite with id %d", run_id) # --------------------------------------------------------------------------- diff --git a/ml/train_model.py b/ml/train_model.py index 2aa8f80..f4bfda4 100644 --- a/ml/train_model.py +++ b/ml/train_model.py @@ -5,14 +5,13 @@ Trains three models against the processed feature dataset: - km_open: regression (GradientBoostingRegressor) - crowd_level: multi-class classification (LGBMClassifier) -Models and feature importances are persisted under ml/models/ via joblib. +Trained models are persisted under ``ml/models/`` via joblib. Structured +training metadata and feature importances are stored in SQLite. Cross-validation (5-fold stratified for classifiers, KFold for regression) is used throughout to compensate for the small dataset size. """ -import json import logging -import os from pathlib import Path from typing import Any @@ -24,13 +23,14 @@ from sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier from sklearn.model_selection import KFold, StratifiedKFold, cross_validate from sklearn.preprocessing import LabelEncoder +from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore + logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Paths # --------------------------------------------------------------------------- _REPO_ROOT = Path(__file__).resolve().parents[1] -DATASET_PATH = _REPO_ROOT / "data" / "processed" / "dataset_featured.csv" MODELS_DIR = _REPO_ROOT / "ml" / "models" # --------------------------------------------------------------------------- @@ -87,9 +87,10 @@ class ModelTrainer: Parameters ---------- - dataset_path: - Path to the processed feature CSV. Defaults to - ``data/processed/dataset_featured.csv`` relative to the repo root. + store: + SQLite store from which the feature dataset is loaded. + dataset_table: + SQLite table containing the feature dataset. models_dir: Directory where trained models and importances are saved. Defaults to ``ml/models/`` relative to the repo root. @@ -97,10 +98,12 @@ class ModelTrainer: def __init__( self, - dataset_path: Path | str = DATASET_PATH, + store: SQLiteStore | None = None, + dataset_table: str = HISTORICAL_FEATURED_TABLE, models_dir: Path | str = MODELS_DIR, ) -> None: - self.dataset_path = Path(dataset_path) + self.store = store if store is not None else SQLiteStore() + self.dataset_table = dataset_table self.models_dir = Path(models_dir) self.models_dir.mkdir(parents=True, exist_ok=True) @@ -127,6 +130,12 @@ class ModelTrainer: logger.info("Training model for target: %s", target) cv_results[target] = self.train_model(target, task_type) + self.store.save_training_run( + dataset_table=self.dataset_table, + dataset_rows=len(self._df) if self._df is not None else 0, + metrics=cv_results, + models_dir=str(self.models_dir), + ) logger.info("All models trained successfully.") return cv_results @@ -191,14 +200,17 @@ class ModelTrainer: def _load_dataset(self) -> None: """Load the processed dataset from disk and derive feature columns.""" - if not self.dataset_path.exists(): + self._df = self.store.read_dataframe( + self.dataset_table, + parse_dates=("date",), + ) + if self._df.empty: raise FileNotFoundError( - f"Processed dataset not found at {self.dataset_path}. " - "Run the pipeline first." + f"Processed dataset not found in SQLite table {self.dataset_table}. " + "Run the full dataset pipeline first." ) - logger.info("Loading dataset from %s", self.dataset_path) - self._df = pd.read_csv(self.dataset_path, parse_dates=["date"]) + logger.info("Loading dataset from SQLite table %s", self.dataset_table) target_cols = set(MODEL_REGISTRY.keys()) # Exclude date, station identifiers, target aliases, and non-numeric @@ -316,7 +328,7 @@ class ModelTrainer: logger.info("Model saved to %s", path) def _save_feature_importances(self, model: Any, target: str) -> None: - """Save feature importances as a sorted JSON file.""" + """Persist feature importances for the latest trained model.""" if not hasattr(model, "feature_importances_"): logger.warning( "Model for '%s' has no feature_importances_ attribute; skipping.", @@ -330,12 +342,11 @@ class ModelTrainer: sorted_importances = dict( sorted(importances.items(), key=lambda kv: kv[1], reverse=True) ) - - path = self.models_dir / f"{target}_feature_importances.json" - with open(path, "w", encoding="utf-8") as fh: - json.dump(sorted_importances, fh, indent=2) - - logger.info("Feature importances saved to %s", path) + self.store.save_feature_importances( + target=target, + importances=sorted_importances, + ) + logger.info("Feature importances saved to SQLite for %s", target) top5 = list(sorted_importances.items())[:5] logger.debug("Top-5 features for %s: %s", target, top5) diff --git a/pipeline/build_dataset.py b/pipeline/build_dataset.py index 6d13a1c..d88f792 100644 --- a/pipeline/build_dataset.py +++ b/pipeline/build_dataset.py @@ -1,23 +1,23 @@ """Dataset builder for the ski predictor pipeline. -Loads raw weather CSVs and station JSONs, merges them on date and station_id, -handles missing data, and writes a processed dataset to disk. +Loads weather and station snapshots from SQLite, merges them on date and +station_id, imputes missing values, and persists the processed dataset back +to SQLite. """ -import glob -import json import logging -from pathlib import Path from typing import Optional import pandas as pd -logger = logging.getLogger(__name__) +from storage import ( + LATEST_STATION_STATUS_TABLE, + LATEST_WEATHER_TABLE, + RUNTIME_DATASET_TABLE, + SQLiteStore, +) -# Paths are relative to the repository root. -_REPO_ROOT = Path(__file__).resolve().parents[1] -_RAW_DIR = _REPO_ROOT / "data" / "raw" -_PROCESSED_DIR = _REPO_ROOT / "data" / "processed" +logger = logging.getLogger(__name__) # Numeric weather columns that can be safely interpolated when values are # missing in the middle of a time series. Columns not listed here are filled @@ -50,30 +50,22 @@ _STATION_TARGET_COLS = [ class DatasetBuilder: """Merges raw weather and station data into a single processed dataset. - Raw weather data is expected as CSV files matching the glob pattern - ``data/raw/weather_*.csv``. Raw station data is expected as JSON files - matching ``data/raw/station_*.json``. - - Both sources must contain a ``date`` column (or key) and a ``station_id`` - column (or key). They are merged on ``(date, station_id)``. - - Parameters - ---------- - raw_dir: - Directory that contains the raw input files. Defaults to - ``/data/raw``. - processed_dir: - Directory where the processed dataset is written. Defaults to - ``/data/processed``. + The builder reads the latest forecast snapshot and latest station status + snapshot from SQLite, merges them on ``(date, station_id)``, and persists + the processed result into another SQLite table. """ def __init__( self, - raw_dir: Optional[Path] = None, - processed_dir: Optional[Path] = None, + store: Optional[SQLiteStore] = None, + weather_table: str = LATEST_WEATHER_TABLE, + station_table: str = LATEST_STATION_STATUS_TABLE, + dataset_table: str = RUNTIME_DATASET_TABLE, ) -> None: - self.raw_dir = Path(raw_dir) if raw_dir else _RAW_DIR - self.processed_dir = Path(processed_dir) if processed_dir else _PROCESSED_DIR + self.store = store if store is not None else SQLiteStore() + self.weather_table = weather_table + self.station_table = station_table + self.dataset_table = dataset_table # ------------------------------------------------------------------ # Public API @@ -82,9 +74,9 @@ class DatasetBuilder: def build(self) -> pd.DataFrame: """Run the full build pipeline and persist the result. - Reads all raw weather CSVs and station JSONs, merges them, fills - missing values and saves the result to - ``data/processed/dataset.csv``. + Reads the latest weather and station snapshots from SQLite, merges + them, fills missing values, and saves the result to the configured + dataset table. Returns ------- @@ -93,8 +85,8 @@ class DatasetBuilder: """ logger.info("Starting full dataset build.") - weather_df = self._load_weather_csvs() - station_df = self._load_station_jsons() + weather_df = self._load_weather_snapshot() + station_df = self._load_station_snapshot() if weather_df.empty and station_df.empty: logger.warning("No raw data found. Returning empty dataset.") @@ -166,78 +158,34 @@ class DatasetBuilder: # Private helpers – loading # ------------------------------------------------------------------ - def _load_weather_csvs(self) -> pd.DataFrame: - """Load and concatenate all ``weather_*.csv`` files from raw_dir.""" - pattern = str(self.raw_dir / "weather_*.csv") - files = sorted(glob.glob(pattern)) + def _load_weather_snapshot(self) -> pd.DataFrame: + """Load the latest persisted weather forecast snapshot.""" + df = self.store.load_weather_snapshot(self.weather_table) + if df.empty: + logger.warning("No weather snapshot found in table %s.", self.weather_table) + return df + logger.info("Loaded %d weather rows from table %s.", len(df), self.weather_table) + return df - if not files: - logger.warning("No weather CSV files found at %s.", pattern) - return pd.DataFrame() - - frames = [] - for path in files: - logger.debug("Reading weather file: %s", path) - try: - df = pd.read_csv(path) - frames.append(df) - except Exception as exc: - logger.error("Failed to read %s: %s", path, exc) - - if not frames: - return pd.DataFrame() - - combined = pd.concat(frames, ignore_index=True) - combined["date"] = pd.to_datetime(combined["date"]) - logger.info("Loaded %d weather rows from %d file(s).", len(combined), len(files)) - return combined - - def _load_station_jsons(self) -> pd.DataFrame: - """Load and concatenate all ``station_*.json`` files from raw_dir.""" - pattern = str(self.raw_dir / "station_*.json") - files = sorted(glob.glob(pattern)) - - if not files: - logger.warning("No station JSON files found at %s.", pattern) - return pd.DataFrame() - - frames = [] - for path in files: - logger.debug("Reading station file: %s", path) - try: - with open(path, "r", encoding="utf-8") as fh: - raw = json.load(fh) - - # Accept either a single record (dict) or a list of records. - if isinstance(raw, dict): - raw = [raw] - - df = pd.DataFrame(raw) - frames.append(df) - except Exception as exc: - logger.error("Failed to read %s: %s", path, exc) - - if not frames: - return pd.DataFrame() - - combined = pd.concat(frames, ignore_index=True) - combined["date"] = pd.to_datetime(combined["date"]) - logger.info( - "Loaded %d station rows from %d file(s).", len(combined), len(files) - ) - return combined + def _load_station_snapshot(self) -> pd.DataFrame: + """Load the latest persisted station status snapshot.""" + df = self.store.read_dataframe(self.station_table, parse_dates=("date",)) + if df.empty: + logger.warning("No station snapshot found in table %s.", self.station_table) + return df + logger.info("Loaded %d station rows from table %s.", len(df), self.station_table) + return df def _load_existing_dataset(self) -> pd.DataFrame: """Return the persisted processed dataset, or an empty DataFrame.""" - dataset_path = self.processed_dir / "dataset.csv" - if dataset_path.exists(): - df = pd.read_csv(dataset_path) - df["date"] = pd.to_datetime(df["date"], format="mixed") - logger.debug("Loaded existing dataset with %d rows.", len(df)) - return df - - logger.debug("No existing dataset found at %s.", dataset_path) - return pd.DataFrame() + df = self.store.read_dataframe(self.dataset_table, parse_dates=("date",)) + if not df.empty: + logger.debug( + "Loaded existing dataset from table %s with %d rows.", + self.dataset_table, + len(df), + ) + return df # ------------------------------------------------------------------ # Private helpers – merging and cleaning @@ -342,11 +290,9 @@ class DatasetBuilder: # ------------------------------------------------------------------ def _save(self, df: pd.DataFrame) -> None: - """Write dataset to ``data/processed/dataset.csv``.""" - self.processed_dir.mkdir(parents=True, exist_ok=True) - output_path = self.processed_dir / "dataset.csv" - df.to_csv(output_path, index=False) - logger.info("Dataset saved to %s.", output_path) + """Write the processed dataset to SQLite.""" + self.store.replace_dataframe(self.dataset_table, df) + logger.info("Dataset saved to table %s.", self.dataset_table) # ------------------------------------------------------------------ # Private helpers – type coercion diff --git a/scripts/build_full_dataset.py b/scripts/build_full_dataset.py index 8e72f6e..3c022f1 100644 --- a/scripts/build_full_dataset.py +++ b/scripts/build_full_dataset.py @@ -1,12 +1,12 @@ """Build the full historical dataset by merging station data with weather. Steps: -1. Load historical station CSV from infonieve.es (data/raw/station_historical_all.csv) +1. Load historical station data from SQLite or download it from infonieve.es 2. Map infonieve columns to the project schema -3. Fetch historical weather from Open-Meteo for 2009-2026 in 1-year chunks +3. Fetch historical weather from Open-Meteo for 2009-2026 when SQLite has no cache 4. Merge weather + station data on (date, station_id) 5. Run feature engineering -6. Save to data/processed/dataset_featured.csv +6. Save the merged and featured datasets to SQLite 7. Train ML models Column mapping from infonieve schema to project schema: @@ -21,8 +21,7 @@ Column mapping from infonieve schema to project schema: import logging import sys -import time -from datetime import date +from datetime import date, timedelta from pathlib import Path import pandas as pd @@ -34,8 +33,16 @@ REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT)) from data_sources.weather_api import WeatherCollector +from data_sources.infonieve_historical import download_all_history from pipeline.feature_engineering import FeatureEngineer from ml.train_model import ModelTrainer +from storage import ( + HISTORICAL_FEATURED_TABLE, + HISTORICAL_MERGED_TABLE, + HISTORICAL_STATION_TABLE, + HISTORICAL_WEATHER_TABLE, + SQLiteStore, +) # --------------------------------------------------------------------------- # Logging @@ -49,10 +56,6 @@ logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- -STATION_CSV = REPO_ROOT / "data" / "raw" / "station_historical_all.csv" -OUTPUT_DIR = REPO_ROOT / "data" / "processed" -OUTPUT_PATH = OUTPUT_DIR / "dataset_featured.csv" - # Weather fetch range - driven by what is in the station data WEATHER_START_YEAR = 2009 WEATHER_END_YEAR = 2026 # inclusive @@ -68,25 +71,18 @@ STATIONS = { "sanisidro": {"latitude": 43.0700, "longitude": -5.3700}, } -# Delay between API calls to avoid rate-limiting (seconds) -API_CALL_DELAY = 3.0 - -# Extra pause between stations (seconds) -INTER_STATION_DELAY = 10.0 - -# Local cache directory for per-year weather chunks -WEATHER_CACHE_DIR = REPO_ROOT / "data" / "raw" / "weather_cache" - - # --------------------------------------------------------------------------- # Step 1: Load and map station data # --------------------------------------------------------------------------- -def load_station_data() -> pd.DataFrame: - """Load the infonieve historical CSV and map columns to project schema.""" - logger.info("Loading station data from %s", STATION_CSV) - df = pd.read_csv(STATION_CSV) - logger.info("Loaded %d rows, %d columns", len(df), len(df.columns)) +def load_station_data(store: SQLiteStore) -> pd.DataFrame: + """Load historical station raw data from SQLite and map it to project schema.""" + df = store.load_historical_station_raw() + if df.empty: + logger.info("No historical station data found in SQLite. Downloading fresh history.") + df = download_all_history(store=store) + else: + logger.info("Loaded %d historical station rows from SQLite.", len(df)) # Parse dates with mixed formats (ISO and day-first variants) df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True) @@ -158,25 +154,22 @@ def load_station_data() -> pd.DataFrame: # --------------------------------------------------------------------------- -# Step 2: Fetch historical weather in 1-year chunks +# Step 2: Fetch historical weather # --------------------------------------------------------------------------- -def _cache_path(station_id: str, year: int) -> Path: - """Return the local cache file path for a (station, year) chunk.""" - return WEATHER_CACHE_DIR / f"weather_{station_id}_{year}.csv" +def fetch_weather_all_stations(store: SQLiteStore) -> pd.DataFrame: + """Load cached historical weather from SQLite or fetch it from Open-Meteo.""" + cached = store.read_dataframe(HISTORICAL_WEATHER_TABLE, parse_dates=("date",)) + yesterday = pd.Timestamp(date.today() - timedelta(days=1)) + if not cached.empty and cached["date"].max() >= yesterday: + logger.info( + "Loaded %d historical weather rows from SQLite table %s.", + len(cached), + HISTORICAL_WEATHER_TABLE, + ) + return cached - -def fetch_weather_all_stations() -> pd.DataFrame: - """Fetch full historical weather for all stations in annual chunks. - - Each (station, year) chunk is cached to - ``data/raw/weather_cache/weather_{station_id}_{year}.csv``. - If the cache file already exists the API call is skipped, making - reruns fast and avoiding rate-limit exhaustion. - - The current year's cache is always refreshed (partial year grows daily). - """ - WEATHER_CACHE_DIR.mkdir(parents=True, exist_ok=True) + logger.info("Historical weather cache missing or stale. Fetching from Open-Meteo.") collector = WeatherCollector() all_frames: list[pd.DataFrame] = [] @@ -187,36 +180,21 @@ def fetch_weather_all_stations() -> pd.DataFrame: lat = coords["latitude"] lon = coords["longitude"] station_frames: list[pd.DataFrame] = [] - needs_api_call = False for year in range(WEATHER_START_YEAR, end_year + 1): - cache_file = _cache_path(station_id, year) start_date = f"{year}-01-01" - - # For the current partial year always refresh the cache - is_current_year = year == today.year - if cache_file.exists() and not is_current_year: - logger.info( - "Cache hit: %s (skipping API call)", cache_file.name - ) - df = pd.read_csv(cache_file) - df["date"] = pd.to_datetime(df["date"]) - station_frames.append(df) - continue - - # For the current year, only fetch up to yesterday - if is_current_year: - from datetime import timedelta - yesterday = today - timedelta(days=1) - end_date = yesterday.strftime("%Y-%m-%d") - else: - end_date = f"{year}-12-31" - + end_date = ( + (today - timedelta(days=1)).strftime("%Y-%m-%d") + if year == today.year + else f"{year}-12-31" + ) logger.info( "Fetching weather for station=%s year=%d (%s to %s)", - station_id, year, start_date, end_date, + station_id, + year, + start_date, + end_date, ) - needs_api_call = True try: df = collector.get_historical( @@ -228,42 +206,29 @@ def fetch_weather_all_stations() -> pd.DataFrame: ) if not df.empty: df["date"] = pd.to_datetime(df["date"]) - # Save to per-year cache (not the rolling weather_X_today.csv) - df.to_csv(cache_file, index=False) - logger.info( - " -> Got %d rows; cached to %s", - len(df), cache_file.name, - ) station_frames.append(df) except RuntimeError as exc: logger.error( "Weather fetch failed for station=%s year=%d: %s", - station_id, year, exc, + station_id, + year, + exc, ) - # Be polite to the API between calls - time.sleep(API_CALL_DELAY) - if station_frames: combined = pd.concat(station_frames, ignore_index=True) combined["date"] = pd.to_datetime(combined["date"]) combined.drop_duplicates(subset=["date", "station_id"], inplace=True) combined.sort_values("date", inplace=True) all_frames.append(combined) - logger.info( - "Total weather rows for %s: %d", station_id, len(combined) - ) - - if needs_api_call: - # Only pause if we actually made API calls for this station - logger.info("Pausing %ds before next station.", INTER_STATION_DELAY) - time.sleep(INTER_STATION_DELAY) + logger.info("Total weather rows for %s: %d", station_id, len(combined)) if not all_frames: raise RuntimeError("No weather data fetched for any station.") weather = pd.concat(all_frames, ignore_index=True) weather["date"] = pd.to_datetime(weather["date"]) + store.save_weather_snapshot(weather, table_name=HISTORICAL_WEATHER_TABLE) logger.info("Total weather rows across all stations: %d", len(weather)) return weather @@ -318,11 +283,15 @@ def run_feature_engineering(df: pd.DataFrame) -> pd.DataFrame: # Step 5: Save # --------------------------------------------------------------------------- -def save_dataset(df: pd.DataFrame) -> None: - """Persist the featured dataset to disk.""" - OUTPUT_DIR.mkdir(parents=True, exist_ok=True) - df.to_csv(OUTPUT_PATH, index=False) - logger.info("Featured dataset saved to %s (%d rows)", OUTPUT_PATH, len(df)) +def save_dataset(store: SQLiteStore, merged_df: pd.DataFrame, featured_df: pd.DataFrame) -> None: + """Persist merged and featured datasets to SQLite.""" + store.replace_dataframe(HISTORICAL_MERGED_TABLE, merged_df) + store.replace_dataframe(HISTORICAL_FEATURED_TABLE, featured_df) + logger.info( + "Historical datasets saved to SQLite tables %s and %s.", + HISTORICAL_MERGED_TABLE, + HISTORICAL_FEATURED_TABLE, + ) # --------------------------------------------------------------------------- @@ -391,12 +360,13 @@ def print_summary(df: pd.DataFrame) -> None: def main() -> None: logger.info("Starting full dataset build pipeline.") + store = SQLiteStore() # Step 1: Load and map station data - station_df = load_station_data() + station_df = load_station_data(store) # Step 2: Fetch historical weather - weather_df = fetch_weather_all_stations() + weather_df = fetch_weather_all_stations(store) # Step 3: Merge merged = merge_datasets(weather_df, station_df) @@ -405,14 +375,14 @@ def main() -> None: featured = run_feature_engineering(merged) # Step 5: Save - save_dataset(featured) + save_dataset(store, merged, featured) # Step 6: Summary print_summary(featured) # Step 7: Train models logger.info("Starting model training on the full dataset.") - trainer = ModelTrainer(dataset_path=OUTPUT_PATH) + trainer = ModelTrainer(store=store, dataset_table=HISTORICAL_FEATURED_TABLE) cv_results = trainer.train_all() print("\nCROSS-VALIDATION RESULTS") diff --git a/scripts/collect_daily_data.py b/scripts/collect_daily_data.py index 78273b6..763eea0 100644 --- a/scripts/collect_daily_data.py +++ b/scripts/collect_daily_data.py @@ -8,15 +8,13 @@ This script is designed for cron execution. It runs every day to: 4. Run feature engineering on the updated dataset. 5. Generate predictions for the configured target date using the HybridPredictor. - 6. Save the predictions to data/processed/predictions_latest.json. + 6. Save the prediction run to SQLite. Cron example (run daily at 20:00, after stations close): 0 20 * * * /path/to/.venv/bin/python /path/to/scripts/collect_daily_data.py -Ad hoc example for same-day verification without overwriting production: - python scripts/collect_daily_data.py \ - --days-ahead 0 \ - --output-path data/processed/predictions_today_check.json +Ad hoc example for same-day verification without affecting the bot: + python scripts/collect_daily_data.py --days-ahead 0 --run-kind adhoc Exit codes: 0 - Pipeline completed (partial failures are logged but do not abort). @@ -24,7 +22,6 @@ Exit codes: """ import argparse -import json import logging import sys from datetime import date, datetime, timedelta, timezone @@ -46,6 +43,15 @@ from data_sources.station_scraper import StationScraper 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, +) # --------------------------------------------------------------------------- # Logging setup @@ -59,15 +65,10 @@ logging.basicConfig( logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- -# Output paths +# Storage # --------------------------------------------------------------------------- -_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed" -_RUNTIME_DIR = _PROCESSED_DIR / "runtime" -_DATASET_PATH = _RUNTIME_DIR / "dataset.csv" -_FEATURED_PATH = _RUNTIME_DIR / "dataset_featured.csv" -_HISTORICAL_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv" -_PREDICTIONS_PATH = _PROCESSED_DIR / "predictions_latest.json" +_DEFAULT_RUN_KIND = PUBLISHED_RUN_KIND # --------------------------------------------------------------------------- @@ -75,7 +76,10 @@ _PREDICTIONS_PATH = _PROCESSED_DIR / "predictions_latest.json" # --------------------------------------------------------------------------- -def collect_weather(collector: WeatherCollector) -> dict[str, pd.DataFrame]: +def collect_weather( + collector: WeatherCollector, + store: SQLiteStore, +) -> dict[str, pd.DataFrame]: """Fetch weather forecasts for all stations.""" logger.info("Step 1/5 - Collecting weather forecasts.") results = {} @@ -86,10 +90,17 @@ def collect_weather(collector: WeatherCollector) -> dict[str, pd.DataFrame]: logger.info("Weather forecast: station=%s, %d rows.", station_id, len(df)) except Exception as exc: logger.error("Weather failed for %s: %s", station_id, exc) + + if results: + snapshot = pd.concat(results.values(), ignore_index=True) + store.save_weather_snapshot(snapshot, table_name=LATEST_WEATHER_TABLE) return results -def collect_station_status(scraper: StationScraper) -> list[dict]: +def collect_station_status( + scraper: StationScraper, + store: SQLiteStore, +) -> list[dict]: """Scrape current operational status for all stations.""" logger.info("Step 2/5 - Collecting station status.") records = [] @@ -104,6 +115,9 @@ def collect_station_status(scraper: StationScraper) -> list[dict]: ) except Exception as exc: logger.error("Scraping failed for %s: %s", station_id, exc) + + if records: + store.save_latest_station_status(records) return records @@ -115,7 +129,7 @@ def append_to_dataset( """Append today's data to the processed dataset.""" logger.info("Step 3/5 - Appending data to dataset.") station_map = {r["station_id"]: r for r in station_records} - today = date.today() + today = pd.Timestamp(date.today()) for station_id, weather_df in weather_by_station.items(): station_record = station_map.get(station_id) @@ -124,7 +138,7 @@ def append_to_dataset( continue # Use today's forecast row for the weather data - today_rows = weather_df[weather_df["date"] == today] + today_rows = weather_df[pd.to_datetime(weather_df["date"]) == today] if today_rows.empty: # Fallback to first available row today_rows = weather_df.head(1) @@ -137,15 +151,14 @@ def append_to_dataset( except Exception as exc: logger.error("Append failed for %s: %s", station_id, exc) - # Return the current dataset - if _DATASET_PATH.exists(): - df = pd.read_csv(_DATASET_PATH) - df["date"] = pd.to_datetime(df["date"]) - return df - return pd.DataFrame() + return builder.store.read_dataframe(RUNTIME_DATASET_TABLE, parse_dates=("date",)) -def run_feature_engineering(engineer: FeatureEngineer, df: pd.DataFrame) -> pd.DataFrame: +def run_feature_engineering( + engineer: FeatureEngineer, + store: SQLiteStore, + df: pd.DataFrame, +) -> pd.DataFrame: """Run feature engineering on the dataset.""" logger.info("Step 4/5 - Running feature engineering.") if df.empty: @@ -153,38 +166,40 @@ def run_feature_engineering(engineer: FeatureEngineer, df: pd.DataFrame) -> pd.D return df featured = engineer.transform(df) - _FEATURED_PATH.parent.mkdir(parents=True, exist_ok=True) - featured.to_csv(_FEATURED_PATH, index=False) - logger.info("Featured dataset saved: %d rows, %d cols.", len(featured), len(featured.columns)) + store.replace_dataframe(RUNTIME_FEATURED_TABLE, featured) + logger.info( + "Featured dataset saved to table %s: %d rows, %d cols.", + RUNTIME_FEATURED_TABLE, + len(featured), + len(featured.columns), + ) return featured -def _load_prediction_feature_base(runtime_featured_df: pd.DataFrame) -> pd.DataFrame: +def _load_prediction_feature_base( + store: SQLiteStore, + runtime_featured_df: pd.DataFrame, +) -> pd.DataFrame: """Return the best available feature base for inference. Preference order: - 1. Historical `dataset_featured.csv` used for model training, when it + 1. Historical featured dataset used for model training, when it exists and contains more rows than the runtime snapshot. 2. The runtime-engineered dataset generated during this script run. This prevents the daily pipeline from relying on a tiny runtime snapshot when rich historical features are available. """ - historical_df = pd.DataFrame() - if _HISTORICAL_FEATURED_PATH.exists(): - try: - historical_df = pd.read_csv(_HISTORICAL_FEATURED_PATH, parse_dates=["date"]) - logger.info( - "Loaded historical feature base from %s (%d rows).", - _HISTORICAL_FEATURED_PATH, - len(historical_df), - ) - except Exception as exc: - logger.warning( - "Could not load historical feature base from %s: %s", - _HISTORICAL_FEATURED_PATH, - exc, - ) + historical_df = store.read_dataframe( + HISTORICAL_FEATURED_TABLE, + parse_dates=("date",), + ) + if not historical_df.empty: + logger.info( + "Loaded historical feature base from table %s (%d rows).", + HISTORICAL_FEATURED_TABLE, + len(historical_df), + ) candidates = [] if not historical_df.empty: @@ -240,20 +255,21 @@ def _select_feature_anchor_row( def generate_predictions( + store: SQLiteStore, predictor: HybridPredictor, weather_by_station: dict[str, pd.DataFrame], featured_df: pd.DataFrame, station_records: list[dict], target_date: date, - output_path: Path, + run_kind: str, ) -> None: - """Generate predictions for a target date and save them to disk.""" + """Generate predictions for a target date and save them to SQLite.""" 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(featured_df) + 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. @@ -311,20 +327,17 @@ def generate_predictions( except Exception as exc: logger.error("Prediction failed for %s: %s", station_id, exc) - # Save predictions - output_path.parent.mkdir(parents=True, exist_ok=True) output = { "generated_at": datetime.now(timezone.utc).isoformat(), "prediction_date": target_date.isoformat(), "stations": predictions, } - with output_path.open("w", encoding="utf-8") as fh: - json.dump(output, fh, indent=2, ensure_ascii=False, default=str) - logger.info("Predictions saved to %s.", output_path) + store.save_prediction_run(output, run_kind=run_kind) + logger.info("Predictions saved to SQLite as %s run.", run_kind) def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: - """Parse CLI arguments for ad hoc prediction runs.""" + """Parse CLI arguments for prediction runs.""" parser = argparse.ArgumentParser( description="Collect station/weather data and generate ski predictions.", ) @@ -335,21 +348,17 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: help="Prediction horizon in days relative to today (default: 1). Use 0 for today.", ) parser.add_argument( - "--output-path", - default=str(_PREDICTIONS_PATH), - help="Path for the generated predictions JSON. Defaults to predictions_latest.json.", + "--run-kind", + choices=[PUBLISHED_RUN_KIND, AD_HOC_RUN_KIND], + default=_DEFAULT_RUN_KIND, + help=( + "Whether this prediction run should be published to the bot " + "or stored as an ad hoc diagnostic run." + ), ) return parser.parse_args(argv) -def _resolve_output_path(raw_path: str) -> Path: - """Resolve an output path against the project root when relative.""" - path = Path(raw_path) - if path.is_absolute(): - return path - return (_PROJECT_ROOT / path).resolve() - - # --------------------------------------------------------------------------- # Main entry point # --------------------------------------------------------------------------- @@ -359,18 +368,19 @@ def main(argv: list[str] | None = None) -> int: """Run the full daily data collection and prediction pipeline.""" args = _parse_args(argv) target_date = date.today() + timedelta(days=args.days_ahead) - output_path = _resolve_output_path(args.output_path) + store = SQLiteStore() logger.info( - "=== Daily pipeline started (target_date=%s, output_path=%s) ===", + "=== Daily pipeline started (target_date=%s, run_kind=%s, db=%s) ===", target_date.isoformat(), - output_path, + args.run_kind, + store.db_path, ) try: weather_collector = WeatherCollector() station_scraper = StationScraper() - dataset_builder = DatasetBuilder(processed_dir=_RUNTIME_DIR) + dataset_builder = DatasetBuilder(store=store) feature_engineer = FeatureEngineer() hybrid_predictor = HybridPredictor() except Exception as exc: @@ -378,8 +388,8 @@ def main(argv: list[str] | None = None) -> int: return 1 # Steps 1-2: collect data - weather_data = collect_weather(weather_collector) - station_records = collect_station_status(station_scraper) + weather_data = collect_weather(weather_collector, store) + station_records = collect_station_status(station_scraper, store) if not weather_data and not station_records: logger.error("No data collected. Aborting.") @@ -389,16 +399,17 @@ def main(argv: list[str] | None = None) -> int: df = append_to_dataset(dataset_builder, weather_data, station_records) # Step 4: feature engineering - featured_df = run_feature_engineering(feature_engineer, df) + featured_df = run_feature_engineering(feature_engineer, store, df) # Step 5: predictions generate_predictions( + store, hybrid_predictor, weather_data, featured_df, station_records, target_date=target_date, - output_path=output_path, + run_kind=args.run_kind, ) logger.info("=== Daily pipeline finished ===") diff --git a/scripts/retrain_model.py b/scripts/retrain_model.py index 1071afa..f3bcdbd 100644 --- a/scripts/retrain_model.py +++ b/scripts/retrain_model.py @@ -1,17 +1,7 @@ """Model retraining script for the ski predictor. -Loads the latest processed and feature-engineered dataset, trains all -configured ML models (RandomForest, GradientBoosting, LightGBM) for each -target variable, evaluates them, and logs metrics. - -Usage: - python scripts/retrain_model.py - -The trained models are persisted to ml/models/ by the training module. - -Exit codes: - 0 - Training and evaluation completed successfully. - 1 - Fatal error prevented any training. +Retrains models from the historical featured dataset stored in SQLite and +evaluates the saved artefacts on a held-out split from the same dataset. """ import logging @@ -28,9 +18,9 @@ _PROJECT_ROOT = _SCRIPT_DIR.parent if str(_PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(_PROJECT_ROOT)) -from pipeline.feature_engineering import FeatureEngineer from ml.train_model import ModelTrainer from ml.evaluate_model import ModelEvaluator +from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore # --------------------------------------------------------------------------- # Logging setup @@ -43,115 +33,6 @@ logging.basicConfig( ) logger = logging.getLogger(__name__) -# --------------------------------------------------------------------------- -# Dataset path -# --------------------------------------------------------------------------- - -_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed" -_FEATURES_DATASET_PATH = _PROCESSED_DIR / "dataset_features.csv" -_DATASET_PATH = _PROCESSED_DIR / "dataset.csv" - - -# --------------------------------------------------------------------------- -# Retraining steps -# --------------------------------------------------------------------------- - - -def load_feature_dataset(): - """Load the feature-engineered dataset from disk. - - Falls back to running feature engineering on the base dataset when the - features file does not exist yet. - - Returns - ------- - pandas.DataFrame - Feature-engineered dataset ready for ML training. - - Raises - ------ - FileNotFoundError - When neither the features dataset nor the base dataset is found. - RuntimeError - When feature engineering fails unexpectedly. - """ - import pandas as pd - - if _FEATURES_DATASET_PATH.exists(): - logger.info("Loading features dataset from %s.", _FEATURES_DATASET_PATH) - df = pd.read_csv(_FEATURES_DATASET_PATH) - logger.info("Loaded %d rows.", len(df)) - return df - - logger.warning( - "Features dataset not found at %s. Running feature engineering first.", - _FEATURES_DATASET_PATH, - ) - - if not _DATASET_PATH.exists(): - raise FileNotFoundError( - f"Base dataset not found at {_DATASET_PATH}. " - "Run collect_daily_data.py or pipeline/build_dataset.py first." - ) - - engineer = FeatureEngineer() - df = engineer.run() - logger.info("Feature engineering produced %d rows.", len(df)) - return df - - -def train_models(df) -> dict: - """Train all models on the provided feature dataset. - - Parameters - ---------- - df: - Feature-engineered DataFrame with target columns present. - - Returns - ------- - dict - Mapping of target variable name to fitted model objects, as returned - by ModelTrainer.train_all(). - """ - logger.info("Starting model training.") - trainer = ModelTrainer() - trained_models = trainer.train_all(df) - logger.info( - "Training complete. Models trained for targets: %s.", - list(trained_models.keys()), - ) - return trained_models - - -def evaluate_models(trained_models: dict, df) -> dict: - """Evaluate trained models and log per-target metrics. - - Parameters - ---------- - trained_models: - Output of :func:`train_models`. - df: - Feature-engineered DataFrame used for evaluation (held-out split is - managed internally by ModelEvaluator). - - Returns - ------- - dict - Nested dict of {target: {model_name: {metric: value}}}. - """ - logger.info("Evaluating trained models.") - evaluator = ModelEvaluator() - metrics = evaluator.evaluate_all(trained_models, df) - - for target, model_metrics in metrics.items(): - for model_name, scores in model_metrics.items(): - metric_str = " ".join(f"{k}={v:.4f}" for k, v in scores.items()) - logger.info("[%s] %s -> %s", target, model_name, metric_str) - - return metrics - - # --------------------------------------------------------------------------- # Main entry point # --------------------------------------------------------------------------- @@ -166,28 +47,40 @@ def main() -> int: Exit code: 0 on success, 1 on fatal error. """ logger.info("=== Model retraining started at %s ===", datetime.utcnow().isoformat()) + store = SQLiteStore() try: - df = load_feature_dataset() - except FileNotFoundError as exc: - logger.critical("Dataset not found: %s.", exc) - return 1 + dataset = store.read_dataframe(HISTORICAL_FEATURED_TABLE, parse_dates=("date",)) except Exception as exc: - logger.critical("Failed to load dataset: %s.", exc, exc_info=True) + logger.critical("Failed to load dataset from SQLite: %s.", exc, exc_info=True) return 1 - if df.empty: - logger.critical("Dataset is empty. Cannot train models.") + if dataset.empty: + logger.critical( + "Dataset table %s is empty. Run scripts/build_full_dataset.py first.", + HISTORICAL_FEATURED_TABLE, + ) return 1 + logger.info( + "Loaded %d rows from SQLite table %s.", + len(dataset), + HISTORICAL_FEATURED_TABLE, + ) + + trainer = ModelTrainer(store=store, dataset_table=HISTORICAL_FEATURED_TABLE) + evaluator = ModelEvaluator(store=store, dataset_table=HISTORICAL_FEATURED_TABLE) + try: - trained_models = train_models(df) + cv_results = trainer.train_all() + logger.info("Training complete: %s", cv_results) except Exception as exc: logger.critical("Training failed: %s.", exc, exc_info=True) return 1 try: - evaluate_models(trained_models, df) + evaluation = evaluator.evaluate_all() + logger.info("Evaluation complete: %s", evaluation) except Exception as exc: # Evaluation failure is non-fatal; models are already saved. logger.error("Evaluation failed: %s. Models were still saved.", exc, exc_info=True) diff --git a/storage/__init__.py b/storage/__init__.py new file mode 100644 index 0000000..21d8c98 --- /dev/null +++ b/storage/__init__.py @@ -0,0 +1,37 @@ +"""SQLite-backed storage helpers for the ski predictor.""" + +from storage.sqlite_store import ( + AD_HOC_RUN_KIND, + CROWD_ANALYSIS_TABLE, + DEFAULT_DB_PATH, + EVALUATION_RUNS_TABLE, + FEATURE_IMPORTANCE_TABLE, + HISTORICAL_FEATURED_TABLE, + HISTORICAL_MERGED_TABLE, + HISTORICAL_STATION_TABLE, + HISTORICAL_WEATHER_TABLE, + LATEST_STATION_STATUS_TABLE, + LATEST_WEATHER_TABLE, + PUBLISHED_RUN_KIND, + RUNTIME_DATASET_TABLE, + RUNTIME_FEATURED_TABLE, + SQLiteStore, +) + +__all__ = [ + "AD_HOC_RUN_KIND", + "CROWD_ANALYSIS_TABLE", + "DEFAULT_DB_PATH", + "EVALUATION_RUNS_TABLE", + "FEATURE_IMPORTANCE_TABLE", + "HISTORICAL_FEATURED_TABLE", + "HISTORICAL_MERGED_TABLE", + "HISTORICAL_STATION_TABLE", + "HISTORICAL_WEATHER_TABLE", + "LATEST_STATION_STATUS_TABLE", + "LATEST_WEATHER_TABLE", + "PUBLISHED_RUN_KIND", + "RUNTIME_DATASET_TABLE", + "RUNTIME_FEATURED_TABLE", + "SQLiteStore", +] diff --git a/storage/sqlite_store.py b/storage/sqlite_store.py new file mode 100644 index 0000000..2099fde --- /dev/null +++ b/storage/sqlite_store.py @@ -0,0 +1,651 @@ +"""SQLite-backed persistence layer for the ski predictor. + +SQLite is the single source of truth for structured project data: + +* fetched forecast snapshots +* latest station status snapshots +* historical station/weather datasets +* processed datasets used for inference and training +* prediction runs consumed by the Telegram bot +* training metadata + +Model binaries remain on disk under ``ml/models/`` because they are large +binary artefacts rather than relational data. +""" + +from __future__ import annotations + +import json +import logging +import os +import sqlite3 +from contextlib import contextmanager +from datetime import date, datetime, timezone +from pathlib import Path +from typing import Any, Iterable, Iterator, Sequence + +import pandas as pd + +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", + ) +) + +LATEST_WEATHER_TABLE = "latest_weather_forecast" +LATEST_STATION_STATUS_TABLE = "latest_station_status" +HISTORICAL_WEATHER_TABLE = "historical_weather" +HISTORICAL_STATION_TABLE = "historical_station_raw" +HISTORICAL_MERGED_TABLE = "historical_merged_dataset" +HISTORICAL_FEATURED_TABLE = "historical_featured_dataset" +RUNTIME_DATASET_TABLE = "runtime_dataset" +RUNTIME_FEATURED_TABLE = "runtime_featured_dataset" +CROWD_ANALYSIS_TABLE = "crowd_analysis" +FEATURE_IMPORTANCE_TABLE = "feature_importances" +EVALUATION_RUNS_TABLE = "evaluation_runs" + +PUBLISHED_RUN_KIND = "published" +AD_HOC_RUN_KIND = "adhoc" + +_WEATHER_COLUMNS: list[str] = [ + "date", + "station_id", + "temperature_2m_max", + "temperature_2m_min", + "temperature_2m_mean", + "precipitation_sum", + "snowfall_sum", + "wind_speed_10m_max", + "wind_gusts_10m_max", + "wind_direction_10m_dominant", + "relative_humidity_2m_mean", + "surface_pressure_mean", +] + + +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) + self.db_path.parent.mkdir(parents=True, exist_ok=True) + self._ensure_schema() + + # ------------------------------------------------------------------ + # Connection helpers + # ------------------------------------------------------------------ + + @contextmanager + def connect(self) -> Iterator[sqlite3.Connection]: + """Yield a SQLite connection with dict-like row access.""" + conn = sqlite3.connect(self.db_path) + conn.row_factory = sqlite3.Row + try: + yield conn + conn.commit() + finally: + conn.close() + + def table_exists(self, table_name: str) -> bool: + """Return True when *table_name* exists in the current database.""" + with self.connect() as conn: + row = conn.execute( + """ + SELECT name + FROM sqlite_master + WHERE type = 'table' AND name = ? + """, + (table_name,), + ).fetchone() + return row is not None + + # ------------------------------------------------------------------ + # Structured tables + # ------------------------------------------------------------------ + + def save_weather_snapshot( + self, + df: pd.DataFrame, + *, + table_name: str, + snapshot_date: date | str | None = None, + ) -> None: + """Replace a weather snapshot table with *df* plus snapshot metadata.""" + if snapshot_date is None: + snapshot_date = date.today().isoformat() + if isinstance(snapshot_date, date): + snapshot_date = snapshot_date.isoformat() + + payload = df.copy() + payload["date"] = pd.to_datetime(payload["date"]).dt.strftime("%Y-%m-%d") + payload["snapshot_date"] = snapshot_date + payload["collected_at"] = self._now_iso() + + ordered = payload[[* _WEATHER_COLUMNS, "snapshot_date", "collected_at"]] + self.replace_dataframe(table_name, ordered) + logger.info("Saved %d weather rows to table %s.", len(ordered), table_name) + + def load_weather_snapshot(self, table_name: str) -> pd.DataFrame: + """Load a weather snapshot table as a DataFrame.""" + return self.read_dataframe(table_name, parse_dates=("date",)) + + def save_latest_station_status( + self, + records: Sequence[dict[str, Any]], + *, + snapshot_date: date | str | None = None, + ) -> None: + """Replace the latest station status snapshot.""" + if snapshot_date is None: + snapshot_date = date.today().isoformat() + if isinstance(snapshot_date, date): + snapshot_date = snapshot_date.isoformat() + + rows: list[dict[str, Any]] = [] + collected_at = self._now_iso() + for record in records: + row = dict(record) + row["date"] = pd.Timestamp(row["date"]).strftime("%Y-%m-%d") + row["snapshot_date"] = snapshot_date + row["collected_at"] = collected_at + rows.append(row) + + df = pd.DataFrame(rows) + self.replace_dataframe(LATEST_STATION_STATUS_TABLE, df) + logger.info("Saved %d latest station rows.", len(df)) + + def load_latest_station_status(self) -> pd.DataFrame: + """Return the latest station status snapshot.""" + return self.read_dataframe(LATEST_STATION_STATUS_TABLE, parse_dates=("date",)) + + def save_historical_station_raw(self, df: pd.DataFrame) -> None: + """Persist the full historical station raw dataset.""" + payload = df.copy() + if "date" in payload.columns: + payload["date"] = pd.to_datetime(payload["date"]).dt.strftime("%Y-%m-%d") + self.replace_dataframe(HISTORICAL_STATION_TABLE, payload) + logger.info("Saved %d historical station rows.", len(payload)) + + def load_historical_station_raw(self) -> pd.DataFrame: + """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: + run = conn.execute( + """ + 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,), + ).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 + + def save_training_run( + self, + *, + dataset_table: str, + dataset_rows: int, + metrics: dict[str, Any], + models_dir: str, + ) -> None: + """Persist metadata about a training run.""" + with self.connect() as conn: + conn.execute( + """ + INSERT INTO training_runs ( + started_at, + completed_at, + dataset_table, + dataset_rows, + metrics_json, + models_dir + ) + VALUES (?, ?, ?, ?, ?, ?) + """, + ( + self._now_iso(), + self._now_iso(), + dataset_table, + dataset_rows, + json.dumps(metrics, ensure_ascii=False), + models_dir, + ), + ) + + def save_feature_importances( + self, + *, + target: str, + importances: dict[str, float], + ) -> None: + """Persist the latest feature importances for a trained target.""" + rows = [ + ( + target, + feature_name, + float(importance), + self._now_iso(), + ) + for feature_name, importance in importances.items() + ] + + with self.connect() as conn: + conn.execute( + "DELETE FROM feature_importances WHERE target = ?", + (target,), + ) + conn.executemany( + """ + INSERT INTO feature_importances ( + target, + feature_name, + importance, + recorded_at + ) + VALUES (?, ?, ?, ?) + """, + rows, + ) + + def load_feature_importances(self, target: str) -> list[tuple[str, float]]: + """Return persisted feature importances for *target* sorted descending.""" + with self.connect() as conn: + rows = conn.execute( + """ + SELECT feature_name, importance + FROM feature_importances + WHERE target = ? + ORDER BY importance DESC, feature_name ASC + """, + (target,), + ).fetchall() + + return [(row["feature_name"], float(row["importance"])) for row in rows] + + def save_evaluation_run( + self, + *, + dataset_table: str, + report: dict[str, Any], + models_dir: str, + ) -> int: + """Persist an evaluation report and return its row id.""" + with self.connect() as conn: + cursor = conn.execute( + """ + INSERT INTO evaluation_runs ( + created_at, + dataset_table, + report_json, + models_dir + ) + VALUES (?, ?, ?, ?) + """, + ( + self._now_iso(), + dataset_table, + json.dumps(report, ensure_ascii=False), + models_dir, + ), + ) + return int(cursor.lastrowid) + + def load_latest_evaluation_run(self) -> dict[str, Any] | None: + """Return the most recent evaluation report stored in SQLite.""" + with self.connect() as conn: + row = conn.execute( + """ + SELECT id, created_at, dataset_table, report_json, models_dir + FROM evaluation_runs + ORDER BY created_at DESC, id DESC + LIMIT 1 + """, + ).fetchone() + + if row is None: + return None + + return { + "id": int(row["id"]), + "created_at": row["created_at"], + "dataset_table": row["dataset_table"], + "report": json.loads(row["report_json"]), + "models_dir": row["models_dir"], + } + + def save_crowd_analysis(self, result: dict[str, Any]) -> int: + """Persist a single crowd-analysis result and return its row id.""" + analyzed_at = str(result.get("timestamp") or self._now_iso()) + analysis_date = pd.Timestamp(analyzed_at).date().isoformat() + + with self.connect() as conn: + cursor = conn.execute( + """ + INSERT INTO crowd_analysis ( + analyzed_at, + analysis_date, + station_id, + image_path, + cars_detected, + people_detected, + buses_detected, + total_vehicles, + crowd_density, + confidence_scores_json + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + analyzed_at, + analysis_date, + result.get("station_id"), + result.get("image_path"), + int(result.get("cars_detected", 0)), + int(result.get("people_detected", 0)), + int(result.get("buses_detected", 0)), + int(result.get("total_vehicles", 0)), + result.get("crowd_density"), + json.dumps(result.get("confidence_scores") or [], ensure_ascii=False), + ), + ) + return int(cursor.lastrowid) + + def load_crowd_analyses( + self, + *, + station_id: str | None = None, + analysis_date: date | str | None = None, + ) -> pd.DataFrame: + """Load crowd-analysis rows, optionally filtered by station and date.""" + if not self.table_exists(CROWD_ANALYSIS_TABLE): + return pd.DataFrame() + + clauses: list[str] = [] + params: list[str] = [] + + if station_id is not None: + clauses.append("station_id = ?") + params.append(station_id) + if analysis_date is not None: + if isinstance(analysis_date, date): + analysis_date = analysis_date.isoformat() + clauses.append("analysis_date = ?") + params.append(analysis_date) + + where = "" + if clauses: + where = "WHERE " + " AND ".join(clauses) + + query = f""" + SELECT analyzed_at, analysis_date, station_id, image_path, + cars_detected, people_detected, buses_detected, + total_vehicles, crowd_density, confidence_scores_json + FROM crowd_analysis + {where} + ORDER BY analyzed_at ASC, id ASC + """ + + with self.connect() as conn: + df = pd.read_sql_query(query, conn, params=params) + + if df.empty: + return df + + df["analyzed_at"] = pd.to_datetime(df["analyzed_at"], format="mixed") + df["confidence_scores"] = df["confidence_scores_json"].map( + lambda raw: json.loads(raw or "[]") + ) + return df.drop(columns=["confidence_scores_json"]) + + # ------------------------------------------------------------------ + # Generic DataFrame helpers + # ------------------------------------------------------------------ + + def replace_dataframe(self, table_name: str, df: pd.DataFrame) -> None: + """Replace *table_name* with the exact contents of *df*.""" + payload = self._normalise_dataframe(df) + with self.connect() as conn: + payload.to_sql(table_name, conn, if_exists="replace", index=False) + + def append_dataframe(self, table_name: str, df: pd.DataFrame) -> None: + """Append *df* to *table_name*.""" + payload = self._normalise_dataframe(df) + with self.connect() as conn: + payload.to_sql(table_name, conn, if_exists="append", index=False) + + def read_dataframe( + self, + table_name: str, + *, + parse_dates: Iterable[str] = (), + ) -> pd.DataFrame: + """Read *table_name* into a DataFrame or return an empty frame.""" + if not self.table_exists(table_name): + return pd.DataFrame() + + with self.connect() as conn: + df = pd.read_sql_query(f'SELECT * FROM "{table_name}"', conn) + + for column in parse_dates: + if column in df.columns: + df[column] = pd.to_datetime(df[column], format="mixed") + + return df + + # ------------------------------------------------------------------ + # Private helpers + # ------------------------------------------------------------------ + + def _ensure_schema(self) -> None: + """Create fixed-schema tables used by the application.""" + 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, + completed_at TEXT NOT NULL, + dataset_table TEXT NOT NULL, + dataset_rows INTEGER NOT NULL, + metrics_json TEXT NOT NULL, + models_dir TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS feature_importances ( + target TEXT NOT NULL, + feature_name TEXT NOT NULL, + importance REAL NOT NULL, + recorded_at TEXT NOT NULL, + PRIMARY KEY (target, feature_name) + ); + + CREATE TABLE IF NOT EXISTS evaluation_runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + dataset_table TEXT NOT NULL, + report_json TEXT NOT NULL, + models_dir TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS crowd_analysis ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + analyzed_at TEXT NOT NULL, + analysis_date TEXT NOT NULL, + station_id TEXT NOT NULL, + image_path TEXT, + cars_detected INTEGER NOT NULL, + people_detected INTEGER NOT NULL, + buses_detected INTEGER NOT NULL, + total_vehicles INTEGER NOT NULL, + crowd_density TEXT NOT NULL, + confidence_scores_json TEXT NOT NULL + ); + """ + ) + + @staticmethod + def _normalise_dataframe(df: pd.DataFrame) -> pd.DataFrame: + """Convert unsupported pandas cell types to SQLite-safe values.""" + payload = df.copy() + for column in payload.columns: + payload[column] = payload[column].map(SQLiteStore._normalise_value) + return payload + + @staticmethod + def _normalise_value(value: Any) -> Any: + """Normalise a single value for SQLite persistence.""" + if isinstance(value, pd.Timestamp): + return value.isoformat() + if isinstance(value, datetime): + return value.isoformat() + if isinstance(value, date): + return value.isoformat() + if isinstance(value, (list, dict)): + return json.dumps(value, ensure_ascii=False) + if pd.isna(value): + return None + return value + + @staticmethod + def _coerce_float(value: Any) -> float | None: + """Convert nullable numeric values to float.""" + if value is None: + return None + return float(value) + + @staticmethod + def _now_iso() -> str: + """Return a UTC ISO timestamp.""" + return datetime.now(timezone.utc).isoformat() diff --git a/tests/test_crowd_analyzer.py b/tests/test_crowd_analyzer.py index f22040f..759a1d4 100644 --- a/tests/test_crowd_analyzer.py +++ b/tests/test_crowd_analyzer.py @@ -6,12 +6,11 @@ Tests cover: - analyze_image() with a mocked YOLO model. - estimate_crowd_level() with mocked WebcamCollector and YOLO. - analyze_all_stations() integration across all three stations. -- JSON persistence of results. +- SQLite persistence of results. """ from __future__ import annotations -import json from pathlib import Path from unittest.mock import MagicMock, patch @@ -95,10 +94,11 @@ def _make_analyzer(tmp_path: Path) -> "CrowdAnalyzer": return_value=_STATIONS_CONFIG["stations"], ): from data_sources.crowd_analyzer import CrowdAnalyzer + from storage import SQLiteStore analyzer = CrowdAnalyzer( config_path=tmp_path / "stations.yaml", - output_dir=tmp_path, + store=SQLiteStore(tmp_path / "skipredictor.db"), ) return analyzer @@ -146,20 +146,21 @@ class TestInstantiation: # The model must remain un-loaded (lazy) after construction. assert analyzer._model is None - def test_output_dir_is_created(self, tmp_path): - """The output directory must exist after initialisation.""" - out_dir = tmp_path / "outputs" / "raw" + def test_store_is_initialized(self, tmp_path): + """The analyzer must initialise a writable SQLite store.""" with patch( "data_sources.crowd_analyzer.CrowdAnalyzer._load_stations", return_value=_STATIONS_CONFIG["stations"], ): from data_sources.crowd_analyzer import CrowdAnalyzer + from storage import SQLiteStore - CrowdAnalyzer( + analyzer = CrowdAnalyzer( config_path=tmp_path / "stations.yaml", - output_dir=out_dir, + store=SQLiteStore(tmp_path / "skipredictor.db"), ) - assert out_dir.is_dir() + assert analyzer.store.db_path == tmp_path / "skipredictor.db" + assert analyzer.store.db_path.exists() def test_stations_are_loaded(self, tmp_path): """All three stations must be present in self.stations after init.""" @@ -403,39 +404,38 @@ class TestEstimateCrowdLevel: result = self._run_with_mocks(tmp_path, "pajares", [], [], []) assert result["crowd_density"] == "unknown" - def test_result_is_saved_to_json(self, tmp_path): - """A JSON file must be written to output_dir after analysis.""" + def test_result_is_saved_to_sqlite(self, tmp_path): + """A crowd-analysis row must be written to SQLite after analysis.""" img = str(tmp_path / "frame.jpg") self._run_with_mocks(tmp_path, "pajares", [img], ["person"] * 3, [0.9] * 3) - from datetime import date + from storage import SQLiteStore - today = date.today().strftime("%Y-%m-%d") - json_file = tmp_path / f"crowd_pajares_{today}.json" - assert json_file.exists() + store = SQLiteStore(tmp_path / "skipredictor.db") + rows = store.load_crowd_analyses(station_id="pajares") + assert len(rows) == 1 - def test_json_contains_valid_list(self, tmp_path): - """The saved JSON file must contain a list with at least one result.""" + def test_sqlite_contains_saved_row(self, tmp_path): + """The saved SQLite row must retain the analysis payload.""" img = str(tmp_path / "frame.jpg") self._run_with_mocks(tmp_path, "pajares", [img], ["car"], [0.85]) - from datetime import date + from storage import SQLiteStore - today = date.today().strftime("%Y-%m-%d") - json_file = tmp_path / f"crowd_pajares_{today}.json" - data = json.loads(json_file.read_text()) - assert isinstance(data, list) - assert len(data) >= 1 + store = SQLiteStore(tmp_path / "skipredictor.db") + rows = store.load_crowd_analyses(station_id="pajares") + assert len(rows) == 1 + assert rows.iloc[0]["crowd_density"] == "low" + assert rows.iloc[0]["confidence_scores"] == [0.85] - def test_multiple_calls_append_to_json(self, tmp_path): - """Successive calls must append results to the same JSON file.""" + def test_multiple_calls_append_to_sqlite(self, tmp_path): + """Successive calls must append results to SQLite.""" img = str(tmp_path / "frame.jpg") self._run_with_mocks(tmp_path, "sanisidro", [img], ["car"], [0.9]) self._run_with_mocks(tmp_path, "sanisidro", [img], ["person"], [0.8]) - from datetime import date + from storage import SQLiteStore - today = date.today().strftime("%Y-%m-%d") - json_file = tmp_path / f"crowd_sanisidro_{today}.json" - data = json.loads(json_file.read_text()) - assert len(data) == 2 + store = SQLiteStore(tmp_path / "skipredictor.db") + rows = store.load_crowd_analyses(station_id="sanisidro") + assert len(rows) == 2 # --------------------------------------------------------------------------- diff --git a/tests/test_sqlite_store.py b/tests/test_sqlite_store.py new file mode 100644 index 0000000..ae390a1 --- /dev/null +++ b/tests/test_sqlite_store.py @@ -0,0 +1,111 @@ +"""Unit tests for the SQLite-backed persistence layer.""" + +from __future__ import annotations + +from storage import SQLiteStore + + +def test_prediction_run_roundtrip(tmp_path): + """Prediction payloads must round-trip through SQLite unchanged.""" + 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", + } + }, + } + + store.save_prediction_run(payload) + + loaded = store.load_latest_predictions() + assert loaded == payload + + +def test_feature_importances_replace_latest_values(tmp_path): + """Saving importances twice for the same target must replace older rows.""" + store = SQLiteStore(tmp_path / "skipredictor.db") + + store.save_feature_importances( + target="station_open", + importances={"snow_depth": 0.9, "wind_gusts_10m_max": 0.5}, + ) + store.save_feature_importances( + target="station_open", + importances={"snow_depth": 0.2, "temperature_2m_mean": 0.8}, + ) + + assert store.load_feature_importances("station_open") == [ + ("temperature_2m_mean", 0.8), + ("snow_depth", 0.2), + ] + + +def test_evaluation_run_roundtrip(tmp_path): + """Evaluation reports must be persisted and reloaded from SQLite.""" + store = SQLiteStore(tmp_path / "skipredictor.db") + report = { + "station_open": {"accuracy": 0.91}, + "km_open": {"mae": 1.2}, + } + + run_id = store.save_evaluation_run( + dataset_table="historical_featured_dataset", + report=report, + models_dir="ml/models", + ) + + loaded = store.load_latest_evaluation_run() + assert loaded is not None + assert loaded["id"] == run_id + assert loaded["dataset_table"] == "historical_featured_dataset" + assert loaded["report"] == report + assert loaded["models_dir"] == "ml/models" + + +def test_crowd_analysis_roundtrip(tmp_path): + """Crowd analysis rows must be queryable with parsed confidence scores.""" + store = SQLiteStore(tmp_path / "skipredictor.db") + store.save_crowd_analysis( + { + "timestamp": "2026-03-13T11:00:00", + "station_id": "sanisidro", + "image_path": "/tmp/frame.jpg", + "cars_detected": 5, + "people_detected": 2, + "buses_detected": 0, + "total_vehicles": 5, + "crowd_density": "low", + "confidence_scores": [0.91, 0.88], + } + ) + store.save_crowd_analysis( + { + "timestamp": "2026-03-13T12:00:00", + "station_id": "sanisidro", + "image_path": "/tmp/frame2.jpg", + "cars_detected": 25, + "people_detected": 4, + "buses_detected": 1, + "total_vehicles": 26, + "crowd_density": "medium", + "confidence_scores": [0.77], + } + ) + + rows = store.load_crowd_analyses( + station_id="sanisidro", + analysis_date="2026-03-13", + ) + + assert len(rows) == 2 + assert rows.iloc[0]["confidence_scores"] == [0.91, 0.88] + assert rows.iloc[1]["crowd_density"] == "medium"