# Ski Predictor - Deployment and Operations Guide ## Quick Start ```bash git clone https://git.dariosevilla.es/dasemu/skipredictor.git cd skipredictor ./start.sh --cron --collect-now --bot ``` That single command will: 1. Create a Python virtualenv and install all dependencies 2. Install the daily cron job (22:00) 3. Run an immediate data collection + prediction cycle 4. Start the Telegram bot in the background ## Requirements - Python 3.11+ - ~2 GB disk (YOLO model downloads on first run) - Internet access (Open-Meteo API, infonieve.es scraping, Telegram API) - `TELEGRAM_BOT_TOKEN` environment variable (for the bot) ## ML Training ### First-time training (full historical dataset) This downloads 16+ seasons of station data from infonieve.es, fetches matching historical weather from Open-Meteo, builds features, and trains all 3 models: ```bash # 1. Download historical station data from infonieve.es .venv/bin/python data_sources/infonieve_historical.py # 2. Build the full dataset (weather + station merge) and train models .venv/bin/python scripts/build_full_dataset.py ``` Step 2 fetches weather data from Open-Meteo in 1-year chunks and persists the full historical state in SQLite. First run may need 15-20 min due to API rate limits. Subsequent runs reuse the database cache. Output: - `data/processed/skipredictor.db` - SQLite database with historical/runtime datasets, predictions, and reports - `ml/models/station_open_model.joblib` - Open/closed classifier (RandomForest) - `ml/models/km_open_model.joblib` - Km open regressor (GradientBoosting) - `ml/models/crowd_level_model.joblib` - Crowd classifier (LightGBM) - `ml/models/crowd_level_label_encoder.joblib` - Label encoder for crowd classes ### Retraining with accumulated data As the daily pipeline collects new data, retrain periodically to improve the models: ```bash .venv/bin/python scripts/retrain_model.py ``` This loads the historical featured dataset from SQLite, trains all models, evaluates them, and overwrites the model files in `ml/models/`. ### Recommended retraining schedule Add a monthly cron job to retrain automatically: ```bash # Retrain models on the 1st of each month at 02:00 0 2 1 * * /path/to/skipredictor/.venv/bin/python /path/to/skipredictor/scripts/retrain_model.py >> /path/to/skipredictor/data/retrain.log 2>&1 ``` Or install it with: ```bash (crontab -l 2>/dev/null; echo "0 2 1 * * \"$(pwd)/.venv/bin/python\" \"$(pwd)/scripts/retrain_model.py\" >> \"$(pwd)/data/retrain.log\" 2>&1") | crontab - ``` ## Cron Jobs ### Daily data collection (installed by `start.sh --cron`) Runs every day at 22:00 (after stations close for the day): ``` 0 22 * * * /path/to/.venv/bin/python /path/to/scripts/collect_daily_data.py >> /path/to/data/pipeline.log 2>&1 ``` The pipeline executes 5 steps: 1. Fetch weather forecasts from Open-Meteo for all 3 stations 2. Scrape current station status from infonieve.es (lifts, km, snow depth) 3. Append today's data to the SQLite runtime dataset tables 4. Run feature engineering into SQLite runtime feature tables 5. Generate next-day predictions and publish them into SQLite for the bot ### Monthly model retraining (optional, recommended) ``` 0 2 1 * * /path/to/.venv/bin/python /path/to/scripts/retrain_model.py >> /path/to/data/retrain.log 2>&1 ``` ### Verify cron is running ```bash crontab -l # List installed cron jobs tail -f data/pipeline.log # Watch daily pipeline output tail -f data/retrain.log # Watch retraining output ``` ## Server Setup (LXC / VPS) ### 1. Clone and initialize ```bash git clone https://git.dariosevilla.es/dasemu/skipredictor.git cd skipredictor ``` ### 2. Set environment variables ```bash # Add to ~/.bashrc or ~/.profile for persistence export TELEGRAM_BOT_TOKEN='your_bot_token_here' ``` ### 3. First-time setup with full training ```bash # Install deps + create venv ./start.sh # Download historical data and train models .venv/bin/python data_sources/infonieve_historical.py .venv/bin/python scripts/build_full_dataset.py # Install cron + start bot ./start.sh --cron --bot ``` ### 4. Run the bot as a systemd service (recommended for 24/7) Create `/etc/systemd/system/skipredictor-bot.service`: ```ini [Unit] Description=Ski Predictor Telegram Bot After=network.target [Service] Type=simple User=dasemu WorkingDirectory=/path/to/skipredictor Environment=TELEGRAM_BOT_TOKEN=your_token_here ExecStart=/path/to/skipredictor/.venv/bin/python bot/telegram_bot.py Restart=on-failure RestartSec=10 [Install] WantedBy=multi-user.target ``` Then: ```bash sudo systemctl daemon-reload sudo systemctl enable skipredictor-bot sudo systemctl start skipredictor-bot # Check status sudo systemctl status skipredictor-bot journalctl -u skipredictor-bot -f ``` ## Monitoring ### Log files | Log | Location | Content | |-----|----------|---------| | Daily pipeline | `data/pipeline.log` | Weather fetch, scraping, predictions | | Model retraining | `data/retrain.log` | Training metrics, cross-validation | | Telegram bot | `data/bot.log` | User commands, errors | ### Check predictions ```bash sqlite3 data/processed/skipredictor.db " SELECT generated_at, prediction_date, run_kind FROM prediction_runs ORDER BY generated_at DESC, id DESC LIMIT 5; " ``` ### Check dataset health ```bash .venv/bin/python -c " from storage import HISTORICAL_FEATURED_TABLE, SQLiteStore df = SQLiteStore().read_dataframe(HISTORICAL_FEATURED_TABLE, parse_dates=('date',)) print(f'Rows: {len(df)}') print(f'Date range: {df[\"date\"].min()} to {df[\"date\"].max()}') print(f'Stations: {df[\"station_id\"].unique()}') print(f'Missing values:\n{df.isnull().sum()[df.isnull().sum() > 0]}') " ``` ## Project Structure ``` skipredictor/ ├── bot/telegram_bot.py # Telegram bot (/pajares, /sanisidro, /fuentes) ├── config/ │ ├── stations.yaml # Station configs, thresholds, webcam URLs │ └── features.yaml # Feature definitions ├── data_sources/ │ ├── weather_api.py # Open-Meteo API client │ ├── station_scraper.py # Infonieve.es scraper │ ├── infonieve_historical.py # Historical TSV downloader │ ├── webcam_collector.py # Webcam snapshot fetcher │ └── crowd_analyzer.py # YOLOv8 crowd detection ├── pipeline/ │ ├── build_dataset.py # Weather + station data merger │ └── feature_engineering.py # Rolling features, calendar, trends ├── predictor/ │ ├── rules.py # Rules engine (wind, snow, rain) │ ├── ml_predictor.py # ML model inference │ └── hybrid_predictor.py # Rules + ML combined ├── ml/ │ ├── train_model.py # Model training (RF, GBR, LGBM) │ ├── evaluate_model.py # Cross-validation metrics │ └── models/ # Trained .joblib files (gitignored) ├── scripts/ │ ├── build_full_dataset.py # Full historical build + train │ ├── collect_daily_data.py # Daily cron pipeline │ └── retrain_model.py # Retrain on accumulated data ├── start.sh # Setup and launch script ├── requirements.txt # Python dependencies └── data/ # Runtime data (gitignored) ├── raw/ # Webcam snapshots and transient downloads └── processed/ # SQLite database and runtime logs ```