mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
feat(storage): migrate project to sqlite
This commit is contained in:
1 parent
1bc1e58781
commit
9c8ba03574
17 files changed
+1204
-688
No files matched your search
@@ -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")
|
||||
|
||||
@@ -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 ===")
|
||||
|
||||
+24
-131
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user