docs: update API, deployment, and lessons for the new backend

- Updated API_SPEC.md with JWT auth and storage schema.
- Updated DEPLOYMENT.md for the new uvicorn-based setup.
- Added LESSONS.md pattern for worktree management.
- Included new README, TODO, and OPERATIONS files.
This commit is contained in:
dasemu committed 2026-03-13 10:01:48 +01:00
1 parent b5b62e582e
commit e952cea417
7 files changed
+281 -279

No files matched your search

+23 -168
View File
@@ -8,18 +8,14 @@ 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)
- **Environment Variables**:
- `TELEGRAM_BOT_TOKEN`: Required for the Telegram bot.
- `JWT_SECRET_KEY`: Required for the FastAPI backend authentication.
## ML Training
@@ -35,201 +31,60 @@ This downloads 16+ seasons of station data from infonieve.es, fetches matching h
.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
- `data/processed/skipredictor.db`: SQLite database with all data.
- `ml/models/*.joblib`: Trained models.
### 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/`.
## FastAPI Backend & Scheduler
### Recommended retraining schedule
The backend uses FastAPI and includes an internal APScheduler to run forecast cycles at 00, 05, 10, 15, and 20:00 (Europe/Madrid), and a weekly retrain on Mondays at 03:00. It also manages the Telegram bot as a subprocess.
Add a monthly cron job to retrain automatically:
### Running the Backend
```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
export TELEGRAM_BOT_TOKEN='...'
export JWT_SECRET_KEY='...'
.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000
```
Or install it with:
### Systemd Service Setup
```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`:
Create `/etc/systemd/system/skipredictor.service`:
```ini
[Unit]
Description=Ski Predictor Telegram Bot
Description=SkiPredictor Backend & 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
Environment=TELEGRAM_BOT_TOKEN=your_token
Environment=JWT_SECRET_KEY=your_secret
ExecStart=/path/to/skipredictor/.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
```
Then:
## Legacy Cron Jobs (Optional)
```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
```
If you prefer not to use the internal scheduler, you can still use standard cron jobs for daily collection and retraining. See [OPERATIONS.md](OPERATIONS.md) for details.
## 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]}')
"
```
- **Logs**: `data/pipeline.log`, `data/retrain.log`, `data/bot.log`.
- **API Status**: `GET /api/v1/status` (requires auth).
- **Health**: `GET /api/v1/health` (public).
## 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
```
*See [README.md](README.md) for the full directory tree.*