mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 23:36:17 +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)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user