mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
919 lines
32 KiB
Python
919 lines
32 KiB
Python
"""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(
|
|
_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"
|
|
CURRENT_FORECASTS_TABLE = "current_forecasts"
|
|
PAST_FORECASTS_TABLE = "past_forecasts"
|
|
HISTORICAL_ACTUALS_TABLE = "historical_actuals"
|
|
|
|
PUBLISHED_RUN_KIND = "published"
|
|
AD_HOC_RUN_KIND = "adhoc"
|
|
|
|
_WEATHER_COLUMNS: list[str] = [
|
|
"date",
|
|
"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 | None = None) -> None:
|
|
self.db_path = self._resolve_db_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:
|
|
return self._load_prediction_payload(
|
|
conn,
|
|
"""
|
|
SELECT id, generated_at, prediction_date, run_kind
|
|
FROM prediction_runs
|
|
WHERE run_kind = ?
|
|
ORDER BY generated_at DESC, id DESC
|
|
LIMIT 1
|
|
""",
|
|
(run_kind,),
|
|
)
|
|
|
|
def load_predictions_for_date(
|
|
self,
|
|
*,
|
|
prediction_date: date | str,
|
|
run_kind: str = PUBLISHED_RUN_KIND,
|
|
) -> dict[str, Any] | None:
|
|
"""Return the latest stored prediction payload for a specific date."""
|
|
if isinstance(prediction_date, date):
|
|
prediction_date = prediction_date.isoformat()
|
|
|
|
with self.connect() as conn:
|
|
return self._load_prediction_payload(
|
|
conn,
|
|
"""
|
|
SELECT id, generated_at, prediction_date, run_kind
|
|
FROM prediction_runs
|
|
WHERE run_kind = ? AND prediction_date = ?
|
|
ORDER BY generated_at DESC, id DESC
|
|
LIMIT 1
|
|
""",
|
|
(run_kind, str(prediction_date)),
|
|
)
|
|
|
|
def save_training_run(
|
|
self,
|
|
*,
|
|
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"])
|
|
|
|
# ------------------------------------------------------------------
|
|
# Current / Past forecasts (API-oriented)
|
|
# ------------------------------------------------------------------
|
|
|
|
def save_current_forecasts(
|
|
self,
|
|
forecasts: list[dict[str, Any]],
|
|
run_hour: int,
|
|
) -> None:
|
|
"""Clear current_forecasts and insert new rows."""
|
|
generated_at = self._now_iso()
|
|
with self.connect() as conn:
|
|
conn.execute(f"DELETE FROM {CURRENT_FORECASTS_TABLE}")
|
|
conn.executemany(
|
|
f"""
|
|
INSERT INTO {CURRENT_FORECASTS_TABLE} (
|
|
generated_at, run_hour, station_id, prediction_date,
|
|
open_probability, km_open, crowd_level,
|
|
weather_summary, rule_notes_json, prediction_source
|
|
)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
[
|
|
(
|
|
generated_at,
|
|
run_hour,
|
|
f["station_id"],
|
|
f["prediction_date"],
|
|
self._coerce_float(f.get("open_probability")),
|
|
self._coerce_float(f.get("km_open")),
|
|
f.get("crowd_level"),
|
|
f.get("weather_summary"),
|
|
json.dumps(f.get("rule_notes") or [], ensure_ascii=False),
|
|
f.get("prediction_source"),
|
|
)
|
|
for f in forecasts
|
|
],
|
|
)
|
|
logger.info(
|
|
"Saved %d current forecasts (run_hour=%d).", len(forecasts), run_hour
|
|
)
|
|
|
|
def archive_current_forecasts(self) -> int:
|
|
"""Move all current_forecasts rows into past_forecasts. Return count."""
|
|
with self.connect() as conn:
|
|
cursor = conn.execute(
|
|
f"""
|
|
INSERT INTO {PAST_FORECASTS_TABLE} (
|
|
generated_at, run_hour, station_id, prediction_date,
|
|
open_probability, km_open, crowd_level,
|
|
weather_summary, rule_notes_json, prediction_source
|
|
)
|
|
SELECT
|
|
generated_at, run_hour, station_id, prediction_date,
|
|
open_probability, km_open, crowd_level,
|
|
weather_summary, rule_notes_json, prediction_source
|
|
FROM {CURRENT_FORECASTS_TABLE}
|
|
"""
|
|
)
|
|
archived = cursor.rowcount
|
|
conn.execute(f"DELETE FROM {CURRENT_FORECASTS_TABLE}")
|
|
if archived:
|
|
logger.info("Archived %d forecast rows to past_forecasts.", archived)
|
|
return archived
|
|
|
|
def load_current_forecasts(
|
|
self,
|
|
station_id: str | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""Return current forecast rows, optionally filtered by station."""
|
|
query = f"SELECT * FROM {CURRENT_FORECASTS_TABLE}"
|
|
params: list[str] = []
|
|
if station_id is not None:
|
|
query += " WHERE station_id = ?"
|
|
params.append(station_id)
|
|
query += " ORDER BY station_id, prediction_date"
|
|
|
|
with self.connect() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
return [dict(row) for row in rows]
|
|
|
|
def load_past_forecasts(
|
|
self,
|
|
station_id: str | None = None,
|
|
date_from: str | None = None,
|
|
date_to: str | None = None,
|
|
limit: int = 50,
|
|
offset: int = 0,
|
|
) -> list[dict[str, Any]]:
|
|
"""Return past forecast rows with optional filters and pagination."""
|
|
clauses: list[str] = []
|
|
params: list[Any] = []
|
|
|
|
if station_id is not None:
|
|
clauses.append("station_id = ?")
|
|
params.append(station_id)
|
|
if date_from is not None:
|
|
clauses.append("prediction_date >= ?")
|
|
params.append(date_from)
|
|
if date_to is not None:
|
|
clauses.append("prediction_date <= ?")
|
|
params.append(date_to)
|
|
|
|
where = ""
|
|
if clauses:
|
|
where = "WHERE " + " AND ".join(clauses)
|
|
|
|
query = f"""
|
|
SELECT * FROM {PAST_FORECASTS_TABLE}
|
|
{where}
|
|
ORDER BY generated_at DESC, id DESC
|
|
LIMIT ? OFFSET ?
|
|
"""
|
|
params.extend([limit, offset])
|
|
|
|
with self.connect() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
return [dict(row) for row in rows]
|
|
|
|
def count_past_forecasts(
|
|
self,
|
|
station_id: str | None = None,
|
|
date_from: str | None = None,
|
|
date_to: str | None = None,
|
|
) -> int:
|
|
"""Return total count of past forecast rows matching filters."""
|
|
clauses: list[str] = []
|
|
params: list[Any] = []
|
|
|
|
if station_id is not None:
|
|
clauses.append("station_id = ?")
|
|
params.append(station_id)
|
|
if date_from is not None:
|
|
clauses.append("prediction_date >= ?")
|
|
params.append(date_from)
|
|
if date_to is not None:
|
|
clauses.append("prediction_date <= ?")
|
|
params.append(date_to)
|
|
|
|
where = ""
|
|
if clauses:
|
|
where = "WHERE " + " AND ".join(clauses)
|
|
|
|
query = f"SELECT COUNT(*) FROM {PAST_FORECASTS_TABLE} {where}"
|
|
|
|
with self.connect() as conn:
|
|
row = conn.execute(query, params).fetchone()
|
|
return int(row[0])
|
|
|
|
def save_historical_actual(self, records: Sequence[dict[str, Any]]) -> None:
|
|
"""Upsert actual station data scraped at end of day."""
|
|
scraped_at = self._now_iso()
|
|
with self.connect() as conn:
|
|
for rec in records:
|
|
conn.execute(
|
|
f"""
|
|
INSERT INTO {HISTORICAL_ACTUALS_TABLE} (
|
|
date, station_id, open_status, km_open,
|
|
lifts_open, snow_depth, scraped_at
|
|
)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
ON CONFLICT(date, station_id) DO UPDATE SET
|
|
open_status = excluded.open_status,
|
|
km_open = excluded.km_open,
|
|
lifts_open = excluded.lifts_open,
|
|
snow_depth = excluded.snow_depth,
|
|
scraped_at = excluded.scraped_at
|
|
""",
|
|
(
|
|
rec["date"],
|
|
rec["station_id"],
|
|
rec.get("open_status"),
|
|
self._coerce_float(rec.get("km_open")),
|
|
rec.get("lifts_open"),
|
|
self._coerce_float(rec.get("snow_depth")),
|
|
scraped_at,
|
|
),
|
|
)
|
|
logger.info("Saved %d historical actual records.", len(records))
|
|
|
|
# ------------------------------------------------------------------
|
|
# 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
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS current_forecasts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
generated_at TEXT NOT NULL,
|
|
run_hour INTEGER NOT NULL,
|
|
station_id TEXT NOT NULL,
|
|
prediction_date TEXT NOT NULL,
|
|
open_probability REAL,
|
|
km_open REAL,
|
|
crowd_level TEXT,
|
|
weather_summary TEXT,
|
|
rule_notes_json TEXT,
|
|
prediction_source TEXT
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS past_forecasts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
generated_at TEXT NOT NULL,
|
|
run_hour INTEGER NOT NULL,
|
|
station_id TEXT NOT NULL,
|
|
prediction_date TEXT NOT NULL,
|
|
open_probability REAL,
|
|
km_open REAL,
|
|
crowd_level TEXT,
|
|
weather_summary TEXT,
|
|
rule_notes_json TEXT,
|
|
prediction_source TEXT
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS historical_actuals (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
date TEXT NOT NULL,
|
|
station_id TEXT NOT NULL,
|
|
open_status INTEGER,
|
|
km_open REAL,
|
|
lifts_open INTEGER,
|
|
snow_depth REAL,
|
|
scraped_at TEXT NOT NULL,
|
|
UNIQUE(date, station_id)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
email TEXT NOT NULL UNIQUE,
|
|
password_hash TEXT NOT NULL,
|
|
created_at TEXT NOT NULL,
|
|
last_login_at TEXT
|
|
);
|
|
"""
|
|
)
|
|
|
|
@staticmethod
|
|
def _resolve_db_path(db_path: Path | str | None) -> Path:
|
|
"""Resolve the effective database path, honoring the environment at runtime."""
|
|
if db_path is not None:
|
|
return Path(db_path)
|
|
return Path(os.environ.get("SKIPREDICTOR_DB_PATH", DEFAULT_DB_PATH))
|
|
|
|
def _load_prediction_payload(
|
|
self,
|
|
conn: sqlite3.Connection,
|
|
run_query: str,
|
|
params: Sequence[Any],
|
|
) -> dict[str, Any] | None:
|
|
"""Load a prediction payload from a prediction-runs query."""
|
|
run = conn.execute(run_query, tuple(params)).fetchone()
|
|
if run is None:
|
|
return None
|
|
|
|
station_rows = conn.execute(
|
|
"""
|
|
SELECT station_id, station_name, open_probability, km_open,
|
|
crowd_level, weather_summary, rule_overrides_json,
|
|
prediction_source
|
|
FROM prediction_stations
|
|
WHERE run_id = ?
|
|
ORDER BY station_id
|
|
""",
|
|
(run["id"],),
|
|
).fetchall()
|
|
|
|
payload = {
|
|
"generated_at": run["generated_at"],
|
|
"prediction_date": run["prediction_date"],
|
|
"stations": {},
|
|
}
|
|
for row in station_rows:
|
|
payload["stations"][row["station_id"]] = {
|
|
"station_name": row["station_name"],
|
|
"open_probability": row["open_probability"],
|
|
"km_open": row["km_open"],
|
|
"crowd_level": row["crowd_level"],
|
|
"weather_summary": row["weather_summary"],
|
|
"rule_overrides": json.loads(row["rule_overrides_json"] or "[]"),
|
|
"prediction_source": row["prediction_source"],
|
|
}
|
|
return payload
|
|
|
|
@staticmethod
|
|
def _normalise_dataframe(df: pd.DataFrame) -> pd.DataFrame:
|
|
"""Convert unsupported pandas cell types to SQLite-safe values."""
|
|
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()
|