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
Whitespace-only changes.
Whitespace-only changes.
+132
@@ -0,0 +1,132 @@
|
||||
"""JWT authentication: register, login, and token validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import jwt
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.api.schemas import TokenResponse, UserCreate, UserResponse
|
||||
from storage import SQLiteStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_TOKEN_EXPIRE_DAYS = 14
|
||||
_ALGORITHM = "HS256"
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _get_secret_key() -> str:
|
||||
key = os.environ.get("JWT_SECRET_KEY")
|
||||
if not key:
|
||||
raise RuntimeError("JWT_SECRET_KEY environment variable is not set")
|
||||
return key
|
||||
|
||||
|
||||
def _create_token(user_id: int, email: str) -> str:
|
||||
now = datetime.now(timezone.utc)
|
||||
payload = {
|
||||
"sub": str(user_id),
|
||||
"email": email,
|
||||
"iat": now,
|
||||
"exp": now + timedelta(days=_TOKEN_EXPIRE_DAYS),
|
||||
}
|
||||
return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM)
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
||||
"""FastAPI dependency that validates the JWT and returns user info."""
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token, _get_secret_key(), algorithms=[_ALGORITHM]
|
||||
)
|
||||
user_id = payload.get("sub")
|
||||
email = payload.get("email")
|
||||
if user_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="login required",
|
||||
)
|
||||
return {"user_id": int(user_id), "email": email}
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="login required",
|
||||
)
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="login required",
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@auth_router.post(
|
||||
"/register",
|
||||
response_model=UserResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def register(body: UserCreate) -> UserResponse:
|
||||
"""Create a new user account."""
|
||||
store = SQLiteStore()
|
||||
hashed = pwd_context.hash(body.password)
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
|
||||
with store.connect() as conn:
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM users WHERE email = ?", (body.email,)
|
||||
).fetchone()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="email already registered",
|
||||
)
|
||||
cursor = conn.execute(
|
||||
"""
|
||||
INSERT INTO users (email, password_hash, created_at)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(body.email, hashed, now_iso),
|
||||
)
|
||||
user_id = cursor.lastrowid
|
||||
|
||||
return UserResponse(id=user_id, email=body.email)
|
||||
|
||||
|
||||
@auth_router.post("/login", response_model=TokenResponse)
|
||||
def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse:
|
||||
"""Authenticate and return a JWT token."""
|
||||
store = SQLiteStore()
|
||||
|
||||
with store.connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, email, password_hash FROM users WHERE email = ?",
|
||||
(form.username,),
|
||||
).fetchone()
|
||||
|
||||
if row is None or not pwd_context.verify(form.password, row["password_hash"]):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="invalid credentials",
|
||||
)
|
||||
|
||||
conn.execute(
|
||||
"UPDATE users SET last_login_at = ? WHERE id = ?",
|
||||
(datetime.now(timezone.utc).isoformat(), row["id"]),
|
||||
)
|
||||
|
||||
token = _create_token(row["id"], row["email"])
|
||||
return TokenResponse(access_token=token)
|
||||
@@ -0,0 +1,277 @@
|
||||
"""REST API endpoints for the SkiPredictor backend."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
|
||||
from app.api.auth import get_current_user
|
||||
from app.api.schemas import (
|
||||
DayForecast,
|
||||
ForecastAllResponse,
|
||||
ForecastHistoryResponse,
|
||||
ForecastHistoryRun,
|
||||
ForecastStationResponse,
|
||||
HealthResponse,
|
||||
StationForecast,
|
||||
StationInfo,
|
||||
StationsResponse,
|
||||
StatusResponse,
|
||||
)
|
||||
from storage import SQLiteStore
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
_STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_VALID_STATION_IDS: set[str] | None = None
|
||||
|
||||
|
||||
def _load_stations_config() -> dict[str, Any]:
|
||||
"""Load and cache the stations YAML configuration."""
|
||||
with open(_STATIONS_YAML) as fh:
|
||||
return yaml.safe_load(fh)["stations"]
|
||||
|
||||
|
||||
def _valid_station_ids() -> set[str]:
|
||||
global _VALID_STATION_IDS
|
||||
if _VALID_STATION_IDS is None:
|
||||
_VALID_STATION_IDS = set(_load_stations_config().keys())
|
||||
return _VALID_STATION_IDS
|
||||
|
||||
|
||||
def _open_label(probability: float) -> str:
|
||||
if probability >= 0.70:
|
||||
return "Abierta"
|
||||
if probability >= 0.40:
|
||||
return "Probable apertura"
|
||||
return "Cerrada"
|
||||
|
||||
|
||||
def _get_store() -> SQLiteStore:
|
||||
return SQLiteStore()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/stations", response_model=StationsResponse)
|
||||
def get_stations(user: dict = Depends(get_current_user)) -> StationsResponse:
|
||||
"""List all tracked ski stations with metadata."""
|
||||
cfg = _load_stations_config()
|
||||
stations = []
|
||||
for sid, data in cfg.items():
|
||||
stations.append(
|
||||
StationInfo(
|
||||
station_id=sid,
|
||||
name=data["name"],
|
||||
max_km=data["max_km_skiable"],
|
||||
latitude=data["latitude"],
|
||||
longitude=data["longitude"],
|
||||
altitude=data["altitude"],
|
||||
wind_closure_threshold_kmh=data["wind_closure_threshold"],
|
||||
min_snow_depth_cm=data["minimum_snow_depth"],
|
||||
)
|
||||
)
|
||||
return StationsResponse(stations=stations)
|
||||
|
||||
|
||||
@router.get("/forecast", response_model=ForecastAllResponse)
|
||||
def get_forecast_all(user: dict = Depends(get_current_user)) -> ForecastAllResponse:
|
||||
"""Get the latest forecast for all stations."""
|
||||
store = _get_store()
|
||||
rows = store.load_current_forecasts()
|
||||
return _build_forecast_all(rows)
|
||||
|
||||
|
||||
@router.get("/forecast/history", response_model=ForecastHistoryResponse)
|
||||
def get_forecast_history(
|
||||
station_id: str | None = Query(None),
|
||||
date_from: str | None = Query(None),
|
||||
date_to: str | None = Query(None),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
user: dict = Depends(get_current_user),
|
||||
) -> ForecastHistoryResponse:
|
||||
"""Get past forecast runs with pagination."""
|
||||
store = _get_store()
|
||||
total = store.count_past_forecasts(
|
||||
station_id=station_id, date_from=date_from, date_to=date_to
|
||||
)
|
||||
rows = store.load_past_forecasts(
|
||||
station_id=station_id,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
runs = [
|
||||
ForecastHistoryRun(
|
||||
generated_at=r["generated_at"],
|
||||
run_hour=r["run_hour"],
|
||||
prediction_date=r["prediction_date"],
|
||||
station_id=r["station_id"],
|
||||
open_probability=r.get("open_probability"),
|
||||
km_open=r.get("km_open"),
|
||||
crowd_level=r.get("crowd_level"),
|
||||
prediction_source=r.get("prediction_source"),
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
return ForecastHistoryResponse(
|
||||
total=total, limit=limit, offset=offset, runs=runs
|
||||
)
|
||||
|
||||
|
||||
@router.get("/forecast/{station_id}", response_model=ForecastStationResponse)
|
||||
def get_forecast_station(station_id: str, user: dict = Depends(get_current_user)) -> ForecastStationResponse:
|
||||
"""Get the latest forecast for a single station."""
|
||||
valid = _valid_station_ids()
|
||||
if station_id not in valid:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Station '{station_id}' not found. Valid: {', '.join(sorted(valid))}",
|
||||
)
|
||||
|
||||
store = _get_store()
|
||||
rows = store.load_current_forecasts(station_id=station_id)
|
||||
cfg = _load_stations_config()
|
||||
|
||||
generated_at = rows[0]["generated_at"] if rows else None
|
||||
run_hour = rows[0]["run_hour"] if rows else None
|
||||
station_cfg = cfg[station_id]
|
||||
max_km = station_cfg["max_km_skiable"]
|
||||
|
||||
days = _rows_to_day_forecasts(rows, max_km)
|
||||
return ForecastStationResponse(
|
||||
generated_at=generated_at,
|
||||
run_hour=run_hour,
|
||||
station_id=station_id,
|
||||
name=station_cfg["name"],
|
||||
days=days,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
def get_health() -> HealthResponse:
|
||||
"""Health check endpoint."""
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
timestamp=datetime.now().astimezone().isoformat(),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/status", response_model=StatusResponse)
|
||||
def get_status(user: dict = Depends(get_current_user)) -> StatusResponse:
|
||||
"""System status: last/next forecast run, training info, bot status."""
|
||||
from app.main import app_state
|
||||
|
||||
store = _get_store()
|
||||
|
||||
# Last forecast run
|
||||
forecasts = store.load_current_forecasts()
|
||||
last_forecast = forecasts[0]["generated_at"] if forecasts else None
|
||||
|
||||
# Last training run
|
||||
last_training: str | None = None
|
||||
with store.connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT completed_at FROM training_runs ORDER BY completed_at DESC LIMIT 1"
|
||||
).fetchone()
|
||||
if row:
|
||||
last_training = row["completed_at"]
|
||||
|
||||
# Model info
|
||||
models: dict[str, str] = {}
|
||||
model_dir = _PROJECT_ROOT / "ml" / "models"
|
||||
if model_dir.exists():
|
||||
for model_file in model_dir.glob("*.joblib"):
|
||||
target = model_file.stem
|
||||
models[target] = target
|
||||
|
||||
# Database size
|
||||
db_size_mb = 0.0
|
||||
if store.db_path.exists():
|
||||
db_size_mb = round(store.db_path.stat().st_size / (1024 * 1024), 1)
|
||||
|
||||
return StatusResponse(
|
||||
last_forecast_run=last_forecast,
|
||||
next_forecast_run=app_state.get("next_forecast_run"),
|
||||
last_training_run=last_training,
|
||||
next_training_run=app_state.get("next_training_run"),
|
||||
models=models,
|
||||
telegram_bot_active=app_state.get("bot_active", False),
|
||||
stations_count=len(_valid_station_ids()),
|
||||
database_size_mb=db_size_mb,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _rows_to_day_forecasts(
|
||||
rows: list[dict[str, Any]], max_km: float
|
||||
) -> list[DayForecast]:
|
||||
"""Convert raw DB rows into DayForecast models."""
|
||||
days = []
|
||||
for r in rows:
|
||||
prob = r.get("open_probability")
|
||||
notes_raw = r.get("rule_notes_json") or "[]"
|
||||
notes = json.loads(notes_raw) if isinstance(notes_raw, str) else notes_raw
|
||||
days.append(
|
||||
DayForecast(
|
||||
date=r["prediction_date"],
|
||||
open_probability=prob,
|
||||
open_label=_open_label(prob) if prob is not None else None,
|
||||
km_open=r.get("km_open"),
|
||||
max_km=max_km,
|
||||
crowd_level=r.get("crowd_level"),
|
||||
weather_summary=r.get("weather_summary"),
|
||||
rule_notes=notes,
|
||||
prediction_source=r.get("prediction_source"),
|
||||
)
|
||||
)
|
||||
return days
|
||||
|
||||
|
||||
def _build_forecast_all(rows: list[dict[str, Any]]) -> ForecastAllResponse:
|
||||
"""Group raw DB rows by station into the all-stations response."""
|
||||
cfg = _load_stations_config()
|
||||
|
||||
generated_at = rows[0]["generated_at"] if rows else None
|
||||
run_hour = rows[0]["run_hour"] if rows else None
|
||||
|
||||
by_station: dict[str, list[dict[str, Any]]] = {}
|
||||
for r in rows:
|
||||
by_station.setdefault(r["station_id"], []).append(r)
|
||||
|
||||
stations: dict[str, StationForecast] = {}
|
||||
for sid, station_rows in by_station.items():
|
||||
station_cfg = cfg.get(sid, {})
|
||||
max_km = station_cfg.get("max_km_skiable", 0.0)
|
||||
stations[sid] = StationForecast(
|
||||
station_id=sid,
|
||||
name=station_cfg.get("name", sid),
|
||||
days=_rows_to_day_forecasts(station_rows, max_km),
|
||||
)
|
||||
|
||||
return ForecastAllResponse(
|
||||
generated_at=generated_at, run_hour=run_hour, stations=stations
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Pydantic response models for the SkiPredictor REST API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# -- Stations ---------------------------------------------------------------
|
||||
|
||||
class StationInfo(BaseModel):
|
||||
station_id: str
|
||||
name: str
|
||||
max_km: float
|
||||
latitude: float
|
||||
longitude: float
|
||||
altitude: int
|
||||
wind_closure_threshold_kmh: int
|
||||
min_snow_depth_cm: int
|
||||
|
||||
|
||||
class StationsResponse(BaseModel):
|
||||
stations: list[StationInfo]
|
||||
|
||||
|
||||
# -- Forecasts ---------------------------------------------------------------
|
||||
|
||||
class DayForecast(BaseModel):
|
||||
date: str
|
||||
open_probability: float | None = None
|
||||
open_label: str | None = None
|
||||
km_open: float | None = None
|
||||
max_km: float | None = None
|
||||
crowd_level: str | None = None
|
||||
weather_summary: str | None = None
|
||||
rule_notes: list[str] = Field(default_factory=list)
|
||||
prediction_source: str | None = None
|
||||
|
||||
|
||||
class StationForecast(BaseModel):
|
||||
station_id: str
|
||||
name: str
|
||||
days: list[DayForecast]
|
||||
|
||||
|
||||
class ForecastAllResponse(BaseModel):
|
||||
generated_at: str | None = None
|
||||
run_hour: int | None = None
|
||||
stations: dict[str, StationForecast]
|
||||
|
||||
|
||||
class ForecastStationResponse(BaseModel):
|
||||
generated_at: str | None = None
|
||||
run_hour: int | None = None
|
||||
station_id: str
|
||||
name: str
|
||||
days: list[DayForecast]
|
||||
|
||||
|
||||
# -- Forecast history --------------------------------------------------------
|
||||
|
||||
class ForecastHistoryRun(BaseModel):
|
||||
generated_at: str
|
||||
run_hour: int
|
||||
prediction_date: str
|
||||
station_id: str
|
||||
open_probability: float | None = None
|
||||
km_open: float | None = None
|
||||
crowd_level: str | None = None
|
||||
prediction_source: str | None = None
|
||||
|
||||
|
||||
class ForecastHistoryResponse(BaseModel):
|
||||
total: int
|
||||
limit: int
|
||||
offset: int
|
||||
runs: list[ForecastHistoryRun]
|
||||
|
||||
|
||||
# -- System ------------------------------------------------------------------
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str
|
||||
timestamp: str
|
||||
|
||||
|
||||
class StatusResponse(BaseModel):
|
||||
last_forecast_run: str | None = None
|
||||
next_forecast_run: str | None = None
|
||||
last_training_run: str | None = None
|
||||
next_training_run: str | None = None
|
||||
models: dict[str, str] = Field(default_factory=dict)
|
||||
telegram_bot_active: bool = False
|
||||
stations_count: int = 0
|
||||
database_size_mb: float = 0.0
|
||||
|
||||
|
||||
# -- Auth -------------------------------------------------------------------
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
email: str = Field(..., min_length=3)
|
||||
password: str = Field(..., min_length=8)
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
"""FastAPI application for the SkiPredictor backend.
|
||||
|
||||
Manages:
|
||||
- REST API serving forecast data
|
||||
- APScheduler for periodic forecast generation and retraining
|
||||
- Telegram bot as a subprocess
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from fastapi import FastAPI
|
||||
|
||||
from app.api.auth import auth_router
|
||||
from app.api.routes import router
|
||||
from app.scheduler.tasks import run_forecast_cycle, run_retrain
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
_TIMEZONE = "Europe/Madrid"
|
||||
|
||||
# Shared mutable state visible to the /status endpoint
|
||||
app_state: dict[str, Any] = {
|
||||
"bot_active": False,
|
||||
"next_forecast_run": None,
|
||||
"next_training_run": None,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Lifespan
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _start_scheduler() -> BackgroundScheduler:
|
||||
"""Configure and start the APScheduler instance."""
|
||||
scheduler = BackgroundScheduler(timezone=_TIMEZONE)
|
||||
|
||||
# Forecast runs: 00, 05, 10, 15, 20 Europe/Madrid
|
||||
for hour in (0, 5, 10, 15, 20):
|
||||
scheduler.add_job(
|
||||
run_forecast_cycle,
|
||||
trigger=CronTrigger(hour=hour, minute=0, timezone=_TIMEZONE),
|
||||
args=[hour],
|
||||
id=f"forecast_{hour:02d}",
|
||||
name=f"Forecast run {hour:02d}:00",
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
# Weekly retrain: Monday 03:00
|
||||
scheduler.add_job(
|
||||
run_retrain,
|
||||
trigger=CronTrigger(day_of_week="mon", hour=3, minute=0, timezone=_TIMEZONE),
|
||||
id="retrain_weekly",
|
||||
name="Weekly model retrain",
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
scheduler.start()
|
||||
logger.info("APScheduler started with %d jobs.", len(scheduler.get_jobs()))
|
||||
|
||||
# Populate next-run info for /status
|
||||
_update_next_runs(scheduler)
|
||||
|
||||
return scheduler
|
||||
|
||||
|
||||
def _update_next_runs(scheduler: BackgroundScheduler) -> None:
|
||||
"""Refresh next_forecast_run and next_training_run in app_state."""
|
||||
forecast_next: datetime | None = None
|
||||
training_next: datetime | None = None
|
||||
|
||||
for job in scheduler.get_jobs():
|
||||
nrt = job.next_run_time
|
||||
if nrt is None:
|
||||
continue
|
||||
if job.id.startswith("forecast_"):
|
||||
if forecast_next is None or nrt < forecast_next:
|
||||
forecast_next = nrt
|
||||
elif job.id == "retrain_weekly":
|
||||
training_next = nrt
|
||||
|
||||
app_state["next_forecast_run"] = (
|
||||
forecast_next.isoformat() if forecast_next else None
|
||||
)
|
||||
app_state["next_training_run"] = (
|
||||
training_next.isoformat() if training_next else None
|
||||
)
|
||||
|
||||
|
||||
def _start_bot_subprocess() -> subprocess.Popen | None:
|
||||
"""Launch the Telegram bot as a subprocess."""
|
||||
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
||||
if not token:
|
||||
logger.warning(
|
||||
"TELEGRAM_BOT_TOKEN not set. Telegram bot will NOT start."
|
||||
)
|
||||
return None
|
||||
|
||||
env = {**os.environ, "PYTHONPATH": str(_PROJECT_ROOT)}
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "bot.telegram_bot"],
|
||||
cwd=str(_PROJECT_ROOT),
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
logger.info("Telegram bot subprocess started (PID=%d).", proc.pid)
|
||||
app_state["bot_active"] = True
|
||||
return proc
|
||||
except Exception as exc:
|
||||
logger.error("Failed to start Telegram bot subprocess: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _stop_bot_subprocess(proc: subprocess.Popen | None) -> None:
|
||||
"""Gracefully terminate the Telegram bot subprocess."""
|
||||
if proc is None:
|
||||
return
|
||||
app_state["bot_active"] = False
|
||||
try:
|
||||
proc.send_signal(signal.SIGTERM)
|
||||
proc.wait(timeout=10)
|
||||
logger.info("Telegram bot subprocess stopped.")
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
logger.warning("Telegram bot subprocess killed after timeout.")
|
||||
except Exception as exc:
|
||||
logger.error("Error stopping bot subprocess: %s", exc)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI) -> AsyncIterator[None]:
|
||||
"""Manage startup and shutdown of scheduler and bot subprocess."""
|
||||
scheduler = _start_scheduler()
|
||||
bot_proc = _start_bot_subprocess()
|
||||
|
||||
yield
|
||||
|
||||
logger.info("Shutting down scheduler and bot subprocess...")
|
||||
scheduler.shutdown(wait=False)
|
||||
_stop_bot_subprocess(bot_proc)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# App
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DESCRIPTION = """\
|
||||
Forecast API for ski stations in northern Spain.
|
||||
|
||||
## Authentication
|
||||
|
||||
All endpoints except `/health` require a valid JWT bearer token.
|
||||
Register a user and login to obtain one (valid for 14 days).
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/api/v1/auth/register` | No | Create user account |
|
||||
| POST | `/api/v1/auth/login` | No | Obtain JWT (14 days) |
|
||||
| GET | `/api/v1/health` | No | Health check |
|
||||
| GET | `/api/v1/stations` | **Yes** | List tracked stations |
|
||||
| GET | `/api/v1/forecast` | **Yes** | Latest forecast (all stations) |
|
||||
| GET | `/api/v1/forecast/history` | **Yes** | Past forecast runs |
|
||||
| GET | `/api/v1/forecast/{station_id}` | **Yes** | Forecast for one station |
|
||||
| GET | `/api/v1/status` | **Yes** | System status |
|
||||
"""
|
||||
|
||||
app = FastAPI(
|
||||
title="SkiPredictor API",
|
||||
version="1.0.0",
|
||||
description=_DESCRIPTION,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.include_router(router)
|
||||
app.include_router(auth_router)
|
||||
Whitespace-only changes.
@@ -0,0 +1,276 @@
|
||||
"""Scheduled tasks for forecast generation and model retraining.
|
||||
|
||||
These functions are invoked by APScheduler from the FastAPI lifespan and
|
||||
reuse the same pipeline components as ``scripts/collect_daily_data.py``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from data_sources.station_scraper import StationScraper
|
||||
from data_sources.weather_api import WeatherCollector
|
||||
from pipeline.build_dataset import DatasetBuilder
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
from predictor.hybrid_predictor import HybridPredictor
|
||||
from scripts.collect_daily_data import (
|
||||
_load_prediction_feature_base,
|
||||
_select_feature_anchor_row,
|
||||
)
|
||||
from scripts.retrain_model import main as retrain_main
|
||||
from storage import (
|
||||
LATEST_WEATHER_TABLE,
|
||||
RUNTIME_DATASET_TABLE,
|
||||
RUNTIME_FEATURED_TABLE,
|
||||
SQLiteStore,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Forecast cycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def run_forecast_cycle(run_hour: int) -> None:
|
||||
"""Execute a full forecast cycle for a given run hour.
|
||||
|
||||
Steps:
|
||||
1. Archive current forecasts into past_forecasts.
|
||||
2. Fetch weather forecasts via Open-Meteo.
|
||||
3. Scrape current station status.
|
||||
4. Append to runtime dataset + feature engineering.
|
||||
5. Generate predictions for each station x each forecast day.
|
||||
6. Save results to current_forecasts.
|
||||
7. At hour 20, scrape today's actual data into historical_actuals.
|
||||
"""
|
||||
logger.info("=== Forecast cycle started (run_hour=%d) ===", run_hour)
|
||||
store = SQLiteStore()
|
||||
|
||||
# 1. Archive previous forecasts
|
||||
store.archive_current_forecasts()
|
||||
|
||||
# 2. Collect weather
|
||||
weather_collector = WeatherCollector()
|
||||
weather_by_station: dict[str, pd.DataFrame] = {}
|
||||
for station_id, cfg in weather_collector.stations.items():
|
||||
try:
|
||||
df = weather_collector.get_forecast(
|
||||
station_id, cfg["latitude"], cfg["longitude"]
|
||||
)
|
||||
weather_by_station[station_id] = df
|
||||
logger.info("Weather OK: %s (%d rows)", station_id, len(df))
|
||||
except Exception as exc:
|
||||
logger.error("Weather failed for %s: %s", station_id, exc)
|
||||
|
||||
if not weather_by_station:
|
||||
logger.error("No weather data collected. Aborting forecast cycle.")
|
||||
return
|
||||
|
||||
# 3. Scrape station status
|
||||
scraper = StationScraper()
|
||||
station_records: list[dict[str, Any]] = []
|
||||
for station_id in scraper._stations:
|
||||
try:
|
||||
record = scraper.scrape_station(station_id)
|
||||
station_records.append(record)
|
||||
except Exception as exc:
|
||||
logger.error("Scraping failed for %s: %s", station_id, exc)
|
||||
|
||||
# 4. Dataset append + feature engineering
|
||||
builder = DatasetBuilder(store=store)
|
||||
engineer = FeatureEngineer()
|
||||
station_map = {r["station_id"]: r for r in station_records}
|
||||
today = pd.Timestamp(date.today())
|
||||
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
station_rec = station_map.get(station_id)
|
||||
if station_rec is None:
|
||||
continue
|
||||
today_rows = weather_df[pd.to_datetime(weather_df["date"]) == today]
|
||||
if today_rows.empty:
|
||||
today_rows = weather_df.head(1)
|
||||
try:
|
||||
builder.append_daily(
|
||||
weather_data=today_rows.iloc[0].to_dict(),
|
||||
station_data=station_rec,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Dataset append failed for %s: %s", station_id, exc)
|
||||
|
||||
# Save weather snapshot
|
||||
if weather_by_station:
|
||||
snapshot = pd.concat(weather_by_station.values(), ignore_index=True)
|
||||
store.save_weather_snapshot(snapshot, table_name=LATEST_WEATHER_TABLE)
|
||||
|
||||
runtime_df = store.read_dataframe(RUNTIME_DATASET_TABLE, parse_dates=("date",))
|
||||
featured_df = pd.DataFrame()
|
||||
if not runtime_df.empty:
|
||||
featured_df = engineer.transform(runtime_df)
|
||||
store.replace_dataframe(RUNTIME_FEATURED_TABLE, featured_df)
|
||||
|
||||
# 5. Determine forecast dates
|
||||
base_date = date.today()
|
||||
if run_hour >= 15:
|
||||
# Skip today, start from tomorrow
|
||||
forecast_dates = [base_date + timedelta(days=d) for d in range(1, 8)]
|
||||
else:
|
||||
# Include today
|
||||
forecast_dates = [base_date + timedelta(days=d) for d in range(8)]
|
||||
|
||||
# 6. Generate predictions
|
||||
predictor = HybridPredictor()
|
||||
feature_base_df = _load_prediction_feature_base(store, featured_df)
|
||||
all_forecasts: list[dict[str, Any]] = []
|
||||
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
station_rec = station_map.get(station_id, {})
|
||||
for target_date in forecast_dates:
|
||||
days_ahead = (target_date - base_date).days
|
||||
target_rows = weather_df[weather_df["date"] == target_date]
|
||||
if target_rows.empty:
|
||||
idx = max(0, min(days_ahead, len(weather_df) - 1))
|
||||
target_rows = weather_df.iloc[idx : idx + 1]
|
||||
if target_rows.empty:
|
||||
continue
|
||||
|
||||
weather_data = target_rows.iloc[0].to_dict()
|
||||
|
||||
# Build feature row
|
||||
features_df = None
|
||||
if not feature_base_df.empty:
|
||||
anchor = _select_feature_anchor_row(
|
||||
feature_base_df, station_id, target_date
|
||||
)
|
||||
if anchor is not None:
|
||||
features_df = anchor.copy()
|
||||
features_df["date"] = pd.Timestamp(target_date)
|
||||
for col in weather_data:
|
||||
if col in features_df.columns and col not in (
|
||||
"date",
|
||||
"station_id",
|
||||
):
|
||||
features_df[col] = weather_data[col]
|
||||
if station_rec.get("snow_depth") is not None:
|
||||
features_df["snow_depth"] = station_rec["snow_depth"]
|
||||
if station_rec.get("lifts_open") is not None:
|
||||
features_df["lifts_open"] = station_rec["lifts_open"]
|
||||
|
||||
if station_rec.get("snow_depth") is not None:
|
||||
weather_data["snow_depth"] = station_rec["snow_depth"]
|
||||
|
||||
try:
|
||||
result = predictor.predict(station_id, weather_data, features_df)
|
||||
all_forecasts.append(
|
||||
{
|
||||
"station_id": station_id,
|
||||
"prediction_date": target_date.isoformat(),
|
||||
"open_probability": result["open_probability"],
|
||||
"km_open": result["km_open"],
|
||||
"crowd_level": result["crowd_level"],
|
||||
"weather_summary": result.get("weather_summary"),
|
||||
"rule_notes": result.get("rule_overrides", []),
|
||||
"prediction_source": result["prediction_source"],
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Prediction failed for %s on %s: %s",
|
||||
station_id,
|
||||
target_date.isoformat(),
|
||||
exc,
|
||||
)
|
||||
|
||||
# 7. Save to current_forecasts
|
||||
if all_forecasts:
|
||||
store.save_current_forecasts(all_forecasts, run_hour)
|
||||
|
||||
# Also save as a published prediction run for the bot's existing flow
|
||||
# (one run per distinct target date, same as collect_daily_data.py)
|
||||
_save_as_prediction_runs(store, all_forecasts, run_hour)
|
||||
|
||||
# 8. At hour 20: scrape today's actual data
|
||||
if run_hour == 20:
|
||||
_scrape_daily_actuals(store, scraper)
|
||||
|
||||
logger.info(
|
||||
"=== Forecast cycle finished (run_hour=%d, forecasts=%d) ===",
|
||||
run_hour,
|
||||
len(all_forecasts),
|
||||
)
|
||||
|
||||
|
||||
def _save_as_prediction_runs(
|
||||
store: SQLiteStore,
|
||||
forecasts: list[dict[str, Any]],
|
||||
run_hour: int,
|
||||
) -> None:
|
||||
"""Persist forecasts as published prediction_runs for bot compatibility."""
|
||||
by_date: dict[str, dict[str, Any]] = {}
|
||||
for f in forecasts:
|
||||
by_date.setdefault(f["prediction_date"], {})[f["station_id"]] = {
|
||||
"station_name": f["station_id"],
|
||||
"open_probability": f["open_probability"],
|
||||
"km_open": f["km_open"],
|
||||
"crowd_level": f["crowd_level"],
|
||||
"weather_summary": f.get("weather_summary"),
|
||||
"rule_overrides": f.get("rule_notes", []),
|
||||
"prediction_source": f["prediction_source"],
|
||||
}
|
||||
|
||||
for pred_date, stations in by_date.items():
|
||||
payload = {
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"prediction_date": pred_date,
|
||||
"stations": stations,
|
||||
}
|
||||
store.save_prediction_run(payload, run_kind="published")
|
||||
|
||||
|
||||
def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
|
||||
"""Scrape today's actual station data and save to historical_actuals."""
|
||||
logger.info("Scraping today's actual station data.")
|
||||
today_iso = date.today().isoformat()
|
||||
records: list[dict[str, Any]] = []
|
||||
|
||||
for station_id in scraper._stations:
|
||||
try:
|
||||
data = scraper.scrape_station(station_id)
|
||||
records.append(
|
||||
{
|
||||
"date": today_iso,
|
||||
"station_id": station_id,
|
||||
"open_status": int(data["open_status"]) if data.get("open_status") is not None else None,
|
||||
"km_open": data.get("km_open"),
|
||||
"lifts_open": data.get("lifts_open"),
|
||||
"snow_depth": data.get("snow_depth"),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Actual scrape failed for %s: %s", station_id, exc)
|
||||
|
||||
if records:
|
||||
store.save_historical_actual(records)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Retrain
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def run_retrain() -> None:
|
||||
"""Run the full model retraining pipeline."""
|
||||
logger.info("=== Model retraining triggered by scheduler ===")
|
||||
try:
|
||||
exit_code = retrain_main()
|
||||
if exit_code != 0:
|
||||
logger.error("Retraining finished with exit code %d.", exit_code)
|
||||
else:
|
||||
logger.info("=== Model retraining completed successfully ===")
|
||||
except Exception as exc:
|
||||
logger.error("Retraining failed: %s", exc, exc_info=True)
|
||||
Reference in new issue
Block a user