feat(storage): migrate project to sqlite

This commit is contained in:
dasemu committed 2026-03-13 06:50:18 +01:00
1 parent 1bc1e58781
commit 9c8ba03574
17 files changed
+1204 -688

No files matched your search

+53 -107
View File
@@ -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
``<repo_root>/data/raw``.
processed_dir:
Directory where the processed dataset is written. Defaults to
``<repo_root>/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