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
@@ -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 ===")
|
||||
|
||||
Reference in new issue
Block a user