mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
424 lines
15 KiB
Python
424 lines
15 KiB
Python
"""Scheduled tasks for forecast generation and model retraining.
|
|
|
|
Three scheduled tasks:
|
|
- run_standard_task() — 5h, 10h, 15h: archive + weather + predict
|
|
- run_extended_task() — 20h: same + webcam + crowd + actuals scraping
|
|
- run_training_task() — Sunday 21h: retrain ML models
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
from datetime import date, datetime, 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 (
|
|
_available_prediction_dates,
|
|
_load_prediction_feature_base,
|
|
_select_forecast_row_for_date,
|
|
_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__)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Shared forecast logic
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _run_forecast_core(
|
|
*,
|
|
include_today: bool,
|
|
run_hour: int,
|
|
) -> list[dict[str, Any]]:
|
|
"""Shared forecast generation logic used by standard and extended tasks.
|
|
|
|
Returns the list of forecast dicts that were saved.
|
|
"""
|
|
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.station_ids:
|
|
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()
|
|
forecast_dates = _available_prediction_dates(
|
|
weather_by_station,
|
|
base_date=base_date,
|
|
include_today=include_today,
|
|
)
|
|
if not forecast_dates:
|
|
logger.error("No usable forecast dates were returned by the weather provider.")
|
|
return []
|
|
|
|
# 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:
|
|
weather_data = _select_forecast_row_for_date(
|
|
weather_df,
|
|
station_id=station_id,
|
|
target_date=target_date,
|
|
)
|
|
if weather_data is None:
|
|
continue
|
|
|
|
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"],
|
|
"sky_condition": result.get("sky_condition"),
|
|
"snow_type": result.get("snow_type"),
|
|
"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)
|
|
|
|
logger.info(
|
|
"=== Forecast cycle finished (run_hour=%d, forecasts=%d) ===",
|
|
run_hour,
|
|
len(all_forecasts),
|
|
)
|
|
return all_forecasts
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Standard task (5h, 10h, 15h)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def run_standard_task() -> None:
|
|
"""Standard forecast cycle: archive + weather + predict (today included)."""
|
|
_run_forecast_core(include_today=True, run_hour=_current_hour())
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Extended task (20h)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def run_extended_task() -> None:
|
|
"""Extended forecast cycle: predictions from tomorrow + webcam + actuals."""
|
|
_run_forecast_core(include_today=False, run_hour=20)
|
|
|
|
store = SQLiteStore()
|
|
scraper = StationScraper()
|
|
|
|
# Scrape today's actual station data
|
|
_scrape_daily_actuals(store, scraper)
|
|
|
|
# Webcam snapshot + crowd analysis
|
|
_collect_daily_crowd_density(store)
|
|
|
|
# Send daily prediction notification to subscribers
|
|
_send_daily_notifications(store)
|
|
|
|
# Send accuracy report to admins
|
|
_send_admin_accuracy_report(store)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Training task (Sunday 21h)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def run_training_task() -> 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)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _current_hour() -> int:
|
|
"""Return the current hour in Europe/Madrid."""
|
|
from zoneinfo import ZoneInfo
|
|
|
|
return datetime.now(ZoneInfo("Europe/Madrid")).hour
|
|
|
|
|
|
def _collect_daily_crowd_density(store: SQLiteStore) -> None:
|
|
"""Download and analyze today's 10:00 AM webcam snapshot from Infonieve."""
|
|
logger.info("Collecting today's crowd density from historical archive.")
|
|
from scripts.collect_historical_webcams import HISTORICAL_CONFIG, HistoricalWebcamCollector
|
|
|
|
collector = HistoricalWebcamCollector(store=store)
|
|
today = date.today()
|
|
|
|
for station_id in HISTORICAL_CONFIG:
|
|
try:
|
|
logger.info("Collecting historical snapshot for %s on %s", station_id, today)
|
|
collector.process_day(station_id, today)
|
|
except Exception as exc:
|
|
logger.error("Daily crowd collection failed for %s: %s", station_id, exc)
|
|
|
|
|
|
async def _send_notifications_async(store: SQLiteStore) -> None:
|
|
"""Send the next-day prediction to all active notification subscribers."""
|
|
from telegram import Bot
|
|
from telegram.constants import ParseMode
|
|
|
|
from bot.telegram_bot import (
|
|
format_daily_predictions,
|
|
load_predictions_for_date,
|
|
prediction_dates_window,
|
|
)
|
|
|
|
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
|
if not token:
|
|
logger.warning("No TELEGRAM_BOT_TOKEN set, skipping notifications.")
|
|
return
|
|
|
|
bot = Bot(token=token)
|
|
subscribers = store.get_active_subscribers()
|
|
|
|
if not subscribers:
|
|
logger.info("No active subscribers for notifications.")
|
|
return
|
|
|
|
tomorrow_dates = prediction_dates_window(start_offset=1, length=1)
|
|
if not tomorrow_dates:
|
|
return
|
|
|
|
predictions = load_predictions_for_date(tomorrow_dates[0], store=store)
|
|
if predictions is None:
|
|
logger.warning("No predictions available for tomorrow notification.")
|
|
return
|
|
|
|
message = "\U0001f4e2 <b>Predicción diaria</b>\n\n" + format_daily_predictions(
|
|
predictions
|
|
)
|
|
|
|
for sub in subscribers:
|
|
chat_id = sub["telegram_chat_id"]
|
|
try:
|
|
await bot.send_message(
|
|
chat_id=chat_id, text=message, parse_mode=ParseMode.HTML
|
|
)
|
|
except Exception as exc:
|
|
logger.error("Failed to send notification to %s: %s", chat_id, exc)
|
|
if "Forbidden" in str(exc) or "blocked" in str(exc).lower():
|
|
store.unsubscribe_notifications(chat_id)
|
|
logger.info("Deactivated subscription for blocked user %s", chat_id)
|
|
|
|
|
|
def _send_daily_notifications(store: SQLiteStore) -> None:
|
|
"""Send daily prediction notifications to all subscribers."""
|
|
logger.info("Sending daily notification to subscribers.")
|
|
try:
|
|
asyncio.run(_send_notifications_async(store))
|
|
except RuntimeError:
|
|
# If an event loop is already running (e.g. inside FastAPI/uvicorn),
|
|
# schedule the coroutine on the existing loop instead.
|
|
loop = asyncio.get_event_loop()
|
|
loop.create_task(_send_notifications_async(store))
|
|
|
|
|
|
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.station_ids:
|
|
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)
|
|
|
|
|
|
def _send_admin_accuracy_report(store: SQLiteStore) -> None:
|
|
"""Send daily accuracy report to admin Telegram users."""
|
|
admin_ids_str = os.environ.get("ADMIN_TELEGRAM_IDS", "")
|
|
if not admin_ids_str.strip():
|
|
logger.info("No ADMIN_TELEGRAM_IDS configured, skipping accuracy report.")
|
|
return
|
|
|
|
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
|
if not token:
|
|
logger.warning("No TELEGRAM_BOT_TOKEN set, skipping admin report.")
|
|
return
|
|
|
|
admin_ids = [int(x.strip()) for x in admin_ids_str.split(",") if x.strip()]
|
|
if not admin_ids:
|
|
return
|
|
|
|
logger.info("Computing accuracy report for %d admin(s).", len(admin_ids))
|
|
|
|
try:
|
|
from predictor.accuracy import (
|
|
compute_accumulated_accuracy,
|
|
compute_daily_accuracy,
|
|
format_accuracy_report,
|
|
)
|
|
|
|
daily = compute_daily_accuracy(date.today(), store=store)
|
|
accumulated = compute_accumulated_accuracy(30, store=store)
|
|
message = format_accuracy_report(daily, accumulated)
|
|
except Exception as exc:
|
|
logger.error("Failed to compute accuracy report: %s", exc)
|
|
return
|
|
|
|
import asyncio
|
|
|
|
from telegram import Bot
|
|
from telegram.constants import ParseMode
|
|
|
|
async def _send() -> None:
|
|
bot = Bot(token=token)
|
|
for admin_id in admin_ids:
|
|
try:
|
|
await bot.send_message(
|
|
chat_id=admin_id, text=message, parse_mode=ParseMode.HTML
|
|
)
|
|
logger.info("Sent accuracy report to admin %d.", admin_id)
|
|
except Exception as exc:
|
|
logger.error(
|
|
"Failed to send accuracy report to admin %d: %s", admin_id, exc
|
|
)
|
|
|
|
asyncio.run(_send())
|