mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
feat(api): add FastAPI backend with JWT authentication
REST API serving forecast data with HS256 JWT auth (14-day tokens).
Public: /health, /auth/register, /auth/login.
Protected: /stations, /forecast, /forecast/history, /forecast/{id}, /status.
Includes APScheduler for periodic forecasts and Telegram bot subprocess.
This commit is contained in:
1 parent
c8188e3995
commit
9d97afe538
14 files changed
+1631
-10
No files matched your search
@@ -3,15 +3,18 @@
|
||||
from storage.sqlite_store import (
|
||||
AD_HOC_RUN_KIND,
|
||||
CROWD_ANALYSIS_TABLE,
|
||||
CURRENT_FORECASTS_TABLE,
|
||||
DEFAULT_DB_PATH,
|
||||
EVALUATION_RUNS_TABLE,
|
||||
FEATURE_IMPORTANCE_TABLE,
|
||||
HISTORICAL_ACTUALS_TABLE,
|
||||
HISTORICAL_FEATURED_TABLE,
|
||||
HISTORICAL_MERGED_TABLE,
|
||||
HISTORICAL_STATION_TABLE,
|
||||
HISTORICAL_WEATHER_TABLE,
|
||||
LATEST_STATION_STATUS_TABLE,
|
||||
LATEST_WEATHER_TABLE,
|
||||
PAST_FORECASTS_TABLE,
|
||||
PUBLISHED_RUN_KIND,
|
||||
RUNTIME_DATASET_TABLE,
|
||||
RUNTIME_FEATURED_TABLE,
|
||||
@@ -21,15 +24,18 @@ from storage.sqlite_store import (
|
||||
__all__ = [
|
||||
"AD_HOC_RUN_KIND",
|
||||
"CROWD_ANALYSIS_TABLE",
|
||||
"CURRENT_FORECASTS_TABLE",
|
||||
"DEFAULT_DB_PATH",
|
||||
"EVALUATION_RUNS_TABLE",
|
||||
"FEATURE_IMPORTANCE_TABLE",
|
||||
"HISTORICAL_ACTUALS_TABLE",
|
||||
"HISTORICAL_FEATURED_TABLE",
|
||||
"HISTORICAL_MERGED_TABLE",
|
||||
"HISTORICAL_STATION_TABLE",
|
||||
"HISTORICAL_WEATHER_TABLE",
|
||||
"LATEST_STATION_STATUS_TABLE",
|
||||
"LATEST_WEATHER_TABLE",
|
||||
"PAST_FORECASTS_TABLE",
|
||||
"PUBLISHED_RUN_KIND",
|
||||
"RUNTIME_DATASET_TABLE",
|
||||
"RUNTIME_FEATURED_TABLE",
|
||||
|
||||
@@ -47,6 +47,9 @@ 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"
|
||||
@@ -500,6 +503,186 @@ class SQLiteStore:
|
||||
)
|
||||
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
|
||||
# ------------------------------------------------------------------
|
||||
@@ -604,6 +787,54 @@ class SQLiteStore:
|
||||
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
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
Reference in new issue
Block a user