Files
skipredictor/DEPLOYMENT.md
T
dasemu 1afe2b73e0 feat: initial ski predictor system
Hybrid ML + rules prediction system for 3 Asturian ski stations
(Pajares, San Isidro, Fuentes de Invierno).

- Weather data from Open-Meteo (historical + forecast)
- Station scraping from infonieve.es (live + 16 seasons historical TSV)
- Feature engineering: rolling snow, calendar, temperature/pressure trends
- ML models: RandomForest (open/close), GradientBoosting (km), LightGBM (crowd)
- Rules engine: wind closure, snow depth, rain+heat, heavy snow
- YOLOv8 webcam crowd detection (cars, people in parking/lifts)
- Telegram bot with /pajares, /sanisidro, /fuentes commands
- Daily cron pipeline for automated data collection and predictions
- Deployment guide with systemd service and cron setup
2026-03-12 14:51:32 +01:00

231 lines
7.3 KiB
Markdown

# 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. Each chunk is cached in `data/raw/weather_cache/`, so reruns skip already-fetched years. First run may need 15-20 min due to API rate limits. Subsequent runs are fast.
Output:
- `data/processed/dataset_featured.csv` - Full dataset with engineered features
- `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 `data/processed/dataset_featured.csv`, trains all models, evaluates with cross-validation, 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 `data/processed/dataset.csv`
4. Run feature engineering -> `data/processed/dataset_featured.csv`
5. Generate next-day predictions -> `data/processed/predictions_latest.json`
### 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
cat data/processed/predictions_latest.json | python -m json.tool
```
### Check dataset health
```bash
.venv/bin/python -c "
import pandas as pd
df = pd.read_csv('data/processed/dataset_featured.csv')
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/ # Station CSVs, weather cache
└── processed/ # Dataset, features, predictions
```