diff --git a/API_SPEC.md b/API_SPEC.md index 32de482..9ca4e67 100644 --- a/API_SPEC.md +++ b/API_SPEC.md @@ -99,7 +99,9 @@ Get the latest forecast for **all stations**. Returns today + next 7 days per st "km_open": 18.5, "max_km": 22.0, "crowd_level": "medium", - "weather_summary": "Nieve ligera, -2°C, viento 25 km/h", + "sky_condition": "nublado", + "snow_type": "húmeda", + "weather_summary": "Nublado | Tª -2–2 °C | Nieve 5 cm | Lluvia 2.0 mm | Rachas 25 km/h", "rule_notes": [], "prediction_source": "hybrid" } @@ -246,10 +248,22 @@ The backend (FastAPI + APScheduler) orchestrates these tasks internally: | open_probability | REAL | | km_open | REAL | | crowd_level | TEXT | +| sky_condition | TEXT | +| snow_type | TEXT | +| weather_code | INTEGER | | weather_summary | TEXT | | rule_notes_json | TEXT | | prediction_source | TEXT | +### `notification_subscribers` +| Column | Type | +|---|---| +| id | INTEGER PK | +| telegram_chat_id | INTEGER UNIQUE | +| telegram_username | TEXT | +| subscribed_at | TEXT | +| active | INTEGER | + ### `training_runs` | Column | Type | |---|---| diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 23ba92a..a67e0fc 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -16,6 +16,7 @@ cd skipredictor - **Environment Variables**: - `TELEGRAM_BOT_TOKEN`: Required for the Telegram bot. - `JWT_SECRET_KEY`: Required for the FastAPI backend authentication. + - `ADMIN_TELEGRAM_IDS` (optional): Comma-separated Telegram user IDs for daily accuracy reports (e.g., `123456789,987654321`). ## ML Training @@ -43,13 +44,18 @@ Output: ## FastAPI Backend & Scheduler -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. +The backend uses FastAPI and includes an internal APScheduler to: +- Run forecast cycles at 05:00, 10:00, 15:00, and 20:00 (Europe/Madrid) +- At 20:00 specifically: send push notifications to subscribed users and accuracy reports to admins +- Retrain ML models weekly on Sundays at 21:00 +- Manage the Telegram bot as in-process polling ### Running the Backend ```bash export TELEGRAM_BOT_TOKEN='...' export JWT_SECRET_KEY='...' +export ADMIN_TELEGRAM_IDS='123456789,987654321' # Optional .venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 ``` @@ -68,6 +74,7 @@ User=dasemu WorkingDirectory=/path/to/skipredictor Environment=TELEGRAM_BOT_TOKEN=your_token Environment=JWT_SECRET_KEY=your_secret +Environment=ADMIN_TELEGRAM_IDS=123456789,987654321 ExecStart=/path/to/skipredictor/.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 Restart=on-failure diff --git a/OPERATIONS.md b/OPERATIONS.md index f57e538..8bf65fa 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -41,6 +41,7 @@ This creates a venv, installs dependencies, downloads historical data, trains mo source .venv/bin/activate export TELEGRAM_BOT_TOKEN='your_token' export JWT_SECRET_KEY='your_secret' +export ADMIN_TELEGRAM_IDS='123456789,987654321' # Optional: comma-separated admin user IDs uvicorn app.main:app --host 0.0.0.0 --port 8000 ``` @@ -89,3 +90,107 @@ export TELEGRAM_BOT_TOKEN='your_token' 1. Check if the bot is active via `GET /api/v1/status`. 2. Ensure `TELEGRAM_BOT_TOKEN` is correctly exported in the environment. 3. Check uvicorn logs for bot startup errors. + +## Telegram Bot Commands + +### User Commands +- `/start` — Welcome message with brief description +- `/help` — List all available commands +- `/hoy` — All three stations' forecast for today +- `/manana` — All three stations' forecast for tomorrow +- `/tresdias` — All three stations' forecasts for next 3 days +- `/semana` — All three stations' forecasts for next 7 days +- `/suscribir` — Subscribe to daily 20:00 push notifications (tomorrow's forecast) +- `/desuscribir` — Unsubscribe from push notifications + +### Push Notifications System + +Users who execute `/suscribir` receive automated daily predictions via push notification at 20:00 Madrid time. + +**How it works:** +1. User sends `/suscribir` → subscriber entry created in `notification_subscribers` table +2. At 20:00 daily, the extended task broadcasts tomorrow's forecast to all active subscribers +3. If a user blocks the bot (Telegram API returns "Forbidden"), their subscription is automatically deactivated + +**Database table:** +``` +notification_subscribers: + - telegram_chat_id (UNIQUE) + - telegram_username (optional) + - subscribed_at (ISO timestamp) + - active (0 or 1) +``` + +## Admin Accuracy Reports + +When `ADMIN_TELEGRAM_IDS` environment variable is set, the system sends daily accuracy reports to designated admins at 20:00. + +**How it works:** +1. Extract yesterday's 20:00 prediction for today from `past_forecasts` +2. Compare against today's actual station data in `historical_actuals` +3. Compute divergence metrics: + - `open_status_match`: Did prediction match actual open/closed? + - `open_prob_error`: |predicted_probability - actual_status| + - `km_error`: |predicted_km - actual_km| + - `km_error_pct`: percentage error for km +4. Compute 30-day accumulated accuracy +5. Format report in Spanish with station breakdowns +6. Send via Telegram to each admin ID + +**Report includes:** +- Per-station accuracy with match status (✅/❌) +- km prediction error +- Daily summary (% open accuracy, avg km error) +- 30-day accumulated statistics + +**Setup:** +```bash +export ADMIN_TELEGRAM_IDS='123456789,987654321' +``` + +## Weather Data Enhancements + +### New Forecast Fields + +All forecasts now include two new fields: + +- **`sky_condition`**: Derived from WMO weather code, values: `"soleado"`, `"parcialmente nublado"`, `"nublado"`, `"niebla"`, `"nublado con nieve"`, `"tormenta"`, `"desconocido"` +- **`snow_type`**: Inferred from temperature + snowfall or from Infonieve historical data, values: `"polvo"`, `"húmeda"`, `"dura"`, `"primavera"`, `"artificial"`, `"costra"`, `"desconocido"` + +These fields appear in: +- REST API responses (forecast endpoints) +- Telegram bot messages (displayed as "Cielo:" and "Tipo de nieve:") +- SQLite `current_forecasts` and `past_forecasts` tables + +### Data Source + +- **Weather codes** come from Open-Meteo (WMO standard codes) +- **Snow type** primarily from Infonieve's `calidadnieve` column when available; otherwise inferred from temperature and snowfall conditions + +## Database Schema Updates + +### New Table: `notification_subscribers` +```sql +CREATE TABLE notification_subscribers ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + telegram_chat_id INTEGER UNIQUE NOT NULL, + telegram_username TEXT, + subscribed_at TEXT NOT NULL, + active INTEGER DEFAULT 1 +); +``` + +### Updated Tables: `current_forecasts`, `past_forecasts` + +New columns added: +- `sky_condition TEXT` — Sky condition label +- `snow_type TEXT` — Snow type/quality label +- `weather_code INTEGER` — WMO weather code (raw) + +Example query to inspect new fields: +```bash +sqlite3 data/processed/skipredictor.db \ + "SELECT station_id, prediction_date, open_probability, sky_condition, snow_type + FROM current_forecasts + ORDER BY station_id, prediction_date;" +``` diff --git a/README.md b/README.md index 63171af..b86ceec 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@ SkiPredictor uses a hybrid approach (Rules Engine + Machine Learning) to provide - **Telegram Bot**: Instant updates and interactive station queries. - **FastAPI Backend**: Professional REST API for integration with web and mobile apps. - **Scheduled Tasks**: Internal APScheduler manages forecast cycles and weekly model retraining. -- **Crowd Analysis**: Experimental YOLOv8-based crowd detection via public webcams. +- **Crowd Analysis**: YOLOv11-based crowd detection via public webcams. +- **Push Notifications**: Telegram users can subscribe to daily forecasts via `/suscribir` and `/desuscribir` commands. +- **Admin Accuracy Reports**: Daily divergence analysis sent to admin Telegram accounts comparing predictions vs. actual data. ## 🛠️ Core Components diff --git a/TODO.md b/TODO.md index c41d6df..211fc5e 100644 --- a/TODO.md +++ b/TODO.md @@ -10,10 +10,11 @@ This file tracks the current state of the project and planned enhancements. ## 🟡 Planned Features -- [ ] **Push Notifications**: Integrate Firebase or similar for real-time station status alerts in the mobile app. +- [ ] **Mobile Push via Firebase**: Extend push notification system to mobile app (currently Telegram-only). - [ ] **User Preferences**: Allow users to "favorite" stations and set custom notification thresholds (e.g., "Alert me if km > 15"). - [ ] **Historical Analytics Dashboard**: A web interface to visualize 15+ years of station performance and weather trends. - [ ] **Expanded Station Support**: Add more stations in Northern Spain (e.g., Leitariegos, Alto Campoo). +- [ ] **Granular Notification Settings**: Allow subscribers to choose notification frequency and station subset. ## 🔵 Ongoing Maintenance @@ -28,3 +29,7 @@ This file tracks the current state of the project and planned enhancements. - [x] **Hybrid Predictor**: Combined rule-based logic with ML models for high accuracy. - [x] **Weighted Training**: Prioritized recent historical data to account for methodological changes. - [x] **Telegram Bot Subprocess**: Integrated the bot directly into the FastAPI lifespan. +- [x] **Bot Command Consolidation**: Removed individual station commands (`/pajares`, `/sanisidro`, `/fuentes`, `/all`) in favor of horizon-based commands (`/hoy`, `/manana`, `/tresdias`, `/semana`). +- [x] **Telegram Push Notifications**: Users can subscribe to daily forecast push-ups via `/suscribir` and `/desuscribir` commands. +- [x] **Admin Accuracy Reports**: Automated daily divergence analysis sent to admin Telegram accounts, comparing predictions vs. actual data with 30-day accumulated metrics. +- [x] **Sky Conditions & Snow Type**: Added WMO-based sky condition predictions (sunny/cloudy/foggy/snowy/thunderstorm) and snow type inference (powder/wet/hard/spring) to all forecast outputs.