mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
feat: unified architecture and webcam archive optimization
- Refactor backend into a single process (FastAPI + APScheduler + Telegram Bot) - Implement 'current_forecasts' and 'past_forecasts' architecture in storage - Optimize historical webcam collector with date range discovery for Pajares, San Isidro, and Fuentes - Clean up legacy scripts and tables (prediction_runs, prediction_stations) - Update tests and operations documentation
This commit is contained in:
1 parent
a70eff3e45
commit
f6a65f41d9
14 files changed
+563
-660
No files matched your search
+47
-47
@@ -3,16 +3,13 @@
|
||||
Manages:
|
||||
- REST API serving forecast data
|
||||
- APScheduler for periodic forecast generation and retraining
|
||||
- Telegram bot as a subprocess
|
||||
- Telegram bot (in-process, no 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
|
||||
@@ -24,7 +21,7 @@ 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
|
||||
from app.scheduler.tasks import run_extended_task, run_standard_task, run_training_task
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -48,23 +45,30 @@ 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
|
||||
# Standard forecast: 5:00, 10:00, 15:00
|
||||
scheduler.add_job(
|
||||
run_retrain,
|
||||
trigger=CronTrigger(day_of_week="mon", hour=3, minute=0, timezone=_TIMEZONE),
|
||||
run_standard_task,
|
||||
trigger=CronTrigger(hour="5,10,15", minute=0, timezone=_TIMEZONE),
|
||||
id="forecast_standard",
|
||||
name="Standard forecast run",
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
# Extended forecast: 20:00
|
||||
scheduler.add_job(
|
||||
run_extended_task,
|
||||
trigger=CronTrigger(hour=20, minute=0, timezone=_TIMEZONE),
|
||||
id="forecast_extended",
|
||||
name="Extended forecast run (20:00)",
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
# Training: Sunday 21:00
|
||||
scheduler.add_job(
|
||||
run_training_task,
|
||||
trigger=CronTrigger(day_of_week="sun", hour=21, minute=0, timezone=_TIMEZONE),
|
||||
id="retrain_weekly",
|
||||
name="Weekly model retrain",
|
||||
name="Weekly model retrain (Sunday 21:00)",
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
@@ -100,8 +104,8 @@ def _update_next_runs(scheduler: BackgroundScheduler) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _start_bot_subprocess() -> subprocess.Popen | None:
|
||||
"""Launch the Telegram bot as a subprocess."""
|
||||
async def _start_bot() -> Any:
|
||||
"""Start the Telegram bot in-process. Returns the Application or None."""
|
||||
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
||||
if not token:
|
||||
logger.warning(
|
||||
@@ -109,50 +113,46 @@ def _start_bot_subprocess() -> subprocess.Popen | None:
|
||||
)
|
||||
return None
|
||||
|
||||
env = {**os.environ, "PYTHONPATH": str(_PROJECT_ROOT)}
|
||||
from bot.telegram_bot import create_bot_application
|
||||
|
||||
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)
|
||||
bot_app = create_bot_application(token)
|
||||
await bot_app.initialize()
|
||||
await bot_app.start()
|
||||
await bot_app.updater.start_polling()
|
||||
app_state["bot_active"] = True
|
||||
return proc
|
||||
logger.info("Telegram bot started in-process.")
|
||||
return bot_app
|
||||
except Exception as exc:
|
||||
logger.error("Failed to start Telegram bot subprocess: %s", exc)
|
||||
logger.error("Failed to start Telegram bot: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _stop_bot_subprocess(proc: subprocess.Popen | None) -> None:
|
||||
"""Gracefully terminate the Telegram bot subprocess."""
|
||||
if proc is None:
|
||||
async def _stop_bot(bot_app: Any) -> None:
|
||||
"""Gracefully stop the in-process Telegram bot."""
|
||||
if bot_app 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.")
|
||||
await bot_app.updater.stop()
|
||||
await bot_app.stop()
|
||||
await bot_app.shutdown()
|
||||
logger.info("Telegram bot stopped.")
|
||||
except Exception as exc:
|
||||
logger.error("Error stopping bot subprocess: %s", exc)
|
||||
logger.error("Error stopping Telegram bot: %s", exc)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI) -> AsyncIterator[None]:
|
||||
"""Manage startup and shutdown of scheduler and bot subprocess."""
|
||||
"""Manage startup and shutdown of scheduler and bot."""
|
||||
scheduler = _start_scheduler()
|
||||
bot_proc = _start_bot_subprocess()
|
||||
bot_app = await _start_bot()
|
||||
|
||||
yield
|
||||
|
||||
logger.info("Shutting down scheduler and bot subprocess...")
|
||||
logger.info("Shutting down scheduler and bot...")
|
||||
scheduler.shutdown(wait=False)
|
||||
_stop_bot_subprocess(bot_proc)
|
||||
await _stop_bot(bot_app)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
+77
-76
@@ -1,7 +1,9 @@
|
||||
"""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``.
|
||||
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
|
||||
@@ -35,21 +37,18 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Forecast cycle
|
||||
# Shared forecast logic
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def run_forecast_cycle(run_hour: int) -> None:
|
||||
"""Execute a full forecast cycle for a given run hour.
|
||||
def _run_forecast_core(
|
||||
*,
|
||||
include_today: bool,
|
||||
run_hour: int,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Shared forecast generation logic used by standard and extended tasks.
|
||||
|
||||
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.
|
||||
Returns the list of forecast dicts that were saved.
|
||||
"""
|
||||
logger.info("=== Forecast cycle started (run_hour=%d) ===", run_hour)
|
||||
store = SQLiteStore()
|
||||
@@ -72,7 +71,7 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
|
||||
if not weather_by_station:
|
||||
logger.error("No weather data collected. Aborting forecast cycle.")
|
||||
return
|
||||
return []
|
||||
|
||||
# 3. Scrape station status
|
||||
scraper = StationScraper()
|
||||
@@ -121,11 +120,11 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
forecast_dates = _available_prediction_dates(
|
||||
weather_by_station,
|
||||
base_date=base_date,
|
||||
include_today=run_hour < 15,
|
||||
include_today=include_today,
|
||||
)
|
||||
if not forecast_dates:
|
||||
logger.error("No usable forecast dates were returned by the weather provider.")
|
||||
return
|
||||
return []
|
||||
|
||||
# 6. Generate predictions
|
||||
predictor = HybridPredictor()
|
||||
@@ -143,7 +142,6 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
if weather_data is None:
|
||||
continue
|
||||
|
||||
# Build feature row
|
||||
features_df = None
|
||||
if not feature_base_df.empty:
|
||||
anchor = _select_feature_anchor_row(
|
||||
@@ -192,33 +190,81 @@ def run_forecast_cycle(run_hour: int) -> None:
|
||||
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 and crowd density
|
||||
if run_hour == 20:
|
||||
_scrape_daily_actuals(store, scraper)
|
||||
_collect_daily_crowd_density(store)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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.")
|
||||
# Local import to avoid circular dependencies
|
||||
from scripts.collect_historical_webcams import HistoricalWebcamCollector
|
||||
from scripts.collect_historical_webcams import HISTORICAL_CONFIG, HistoricalWebcamCollector
|
||||
|
||||
collector = HistoricalWebcamCollector(store=store)
|
||||
today = date.today()
|
||||
|
||||
# Process for each configured historical station
|
||||
from scripts.collect_historical_webcams import HISTORICAL_CONFIG
|
||||
|
||||
for station_id in HISTORICAL_CONFIG:
|
||||
try:
|
||||
logger.info("Collecting historical snapshot for %s on %s", station_id, today)
|
||||
@@ -227,33 +273,6 @@ def _collect_daily_crowd_density(store: SQLiteStore) -> None:
|
||||
logger.error("Daily crowd collection failed for %s: %s", station_id, exc)
|
||||
|
||||
|
||||
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.")
|
||||
@@ -278,21 +297,3 @@ def _scrape_daily_actuals(store: SQLiteStore, scraper: StationScraper) -> None:
|
||||
|
||||
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