chore: bootstrap Claude setup

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5 committed 2026-10-18 15:02:48 +02:00
1 parent b4453917dc
commit d99aed9a3c
12 files changed
+175 -7

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
# SkiPredictor API Specification v1
Base URL: `/api/v1`
All responses use JSON. Dates use ISO 8601 format (`YYYY-MM-DD`). Timestamps use ISO 8601 with timezone (`YYYY-MM-DDTHH:MM:SS+HH:MM`).
---
## Authentication
All endpoints except `/health`, `/auth/register`, and `/auth/login` require a valid JWT bearer token.
### `POST /api/v1/auth/register`
Create a new user account.
**Request Body:**
```json
{
"email": "user@example.com",
"password": "securepassword123"
}
```
**Response 201:**
```json
{
"id": 1,
"email": "user@example.com"
}
```
---
### `POST /api/v1/auth/login`
Obtain a JWT token valid for 14 days. Uses OAuth2 Password Flow (form data).
**Request Body (form-data):**
- `username`: email
- `password`: password
**Response 200:**
```json
{
"access_token": "eyJhbG...",
"token_type": "bearer"
}
```
---
## Stations
### `GET /api/v1/stations`
List all tracked ski stations with metadata.
**Response 200:**
```json
{
"stations": [
{
"station_id": "pajares",
"name": "Valgrande-Pajares",
"max_km": 22.0,
"latitude": 43.05,
"longitude": -5.77,
"altitude": 1505,
"wind_closure_threshold_kmh": 80,
"min_snow_depth_cm": 30
}
]
}
```
---
## Forecasts
### `GET /api/v1/forecast`
Get the latest forecast for **all stations**. Returns today + next 7 days per station.
**Response 200:**
```json
{
"generated_at": "2026-03-13T10:00:00+01:00",
"run_hour": 10,
"stations": {
"pajares": {
"station_id": "pajares",
"name": "Valgrande-Pajares",
"days": [
{
"date": "2026-03-13",
"open_probability": 0.85,
"open_label": "Abierta",
"km_open": 18.5,
"max_km": 22.0,
"crowd_level": "medium",
"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"
}
]
}
}
}
```
**Notes:**
- `open_label`: `"Abierta"` (>=0.70), `"Probable apertura"` (>=0.40), `"Cerrada"` (<0.40)
- At run hours 15 and 20, `days[0]` is tomorrow (today is omitted)
- At run hours 00, 05, and 10, `days[0]` is today
---
### `GET /api/v1/forecast/{station_id}`
Get the latest forecast for a **single station**.
**Path parameters:**
- `station_id`: `pajares` | `sanisidro` | `fuentes`
**Response 200:**
```json
{
"generated_at": "2026-03-13T10:00:00+01:00",
"run_hour": 10,
"station_id": "pajares",
"name": "Valgrande-Pajares",
"days": [ ... ]
}
```
---
### `GET /api/v1/forecast/history`
Get past forecast runs (archived when a new run replaces them).
**Query parameters:**
- `station_id` (optional): filter by station
- `date_from` (optional): earliest prediction date (`YYYY-MM-DD`)
- `date_to` (optional): latest prediction date (`YYYY-MM-DD`)
- `limit` (optional, default 50, max 200): number of runs to return
- `offset` (optional, default 0): pagination offset
**Response 200:**
```json
{
"total": 150,
"limit": 50,
"offset": 0,
"runs": [
{
"generated_at": "2026-03-13T05:00:00+01:00",
"run_hour": 5,
"prediction_date": "2026-03-13",
"station_id": "pajares",
"open_probability": 0.85,
"km_open": 18.5,
"crowd_level": "medium",
"prediction_source": "hybrid"
}
]
}
```
---
## System
### `GET /api/v1/health`
Public health check endpoint.
**Response 200:**
```json
{
"status": "ok",
"timestamp": "2026-03-13T10:15:00+01:00"
}
```
---
### `GET /api/v1/status`
System status: last forecast run, next scheduled run, model info, bot status.
**Response 200:**
```json
{
"last_forecast_run": "2026-03-13T10:00:00+01:00",
"next_forecast_run": "2026-03-13T15:00:00+01:00",
"last_training_run": "2026-03-10T03:00:00+01:00",
"next_training_run": "2026-03-17T03:00:00+01:00",
"models": {
"station_open": "station_open",
"km_open": "km_open",
"crowd_level": "crowd_level"
},
"telegram_bot_active": true,
"stations_count": 3,
"database_size_mb": 8.1
}
```
---
## Internal Schedule
The backend (FastAPI + APScheduler) orchestrates these tasks internally:
| Hour (Europe/Madrid) | Task |
|---|---|
| 00:00 | Forecast run: today + 7 days |
| 05:00 | Forecast run: today + 7 days |
| 10:00 | Forecast run: today + 7 days |
| 15:00 | Forecast run: tomorrow + 6 days |
| 20:00 | Forecast run: tomorrow + 6 days |
| Weekly (Mon 03:00) | ML model retraining |
---
## Storage Schema (SQLite)
### `users`
| Column | Type |
|---|---|
| id | INTEGER PK |
| email | TEXT UNIQUE |
| password_hash | TEXT |
| created_at | TEXT |
| last_login_at | TEXT |
### `current_forecasts` / `past_forecasts`
| Column | Type |
|---|---|
| generated_at | TEXT |
| run_hour | INTEGER |
| station_id | TEXT |
| prediction_date | TEXT |
| 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 |
|---|---|
| id | INTEGER PK |
| completed_at | TEXT |
| metrics_json | TEXT |
| parameters_json | TEXT |
+97
View File
@@ -0,0 +1,97 @@
# 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
```
## Requirements
- Python 3.11+
- ~2 GB disk (YOLO model downloads on first run)
- Internet access (Open-Meteo API, infonieve.es scraping, Telegram API)
- **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
### 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
```
Output:
- `data/processed/skipredictor.db`: SQLite database with all data.
- `ml/models/*.joblib`: Trained models.
### Retraining with accumulated data
```bash
.venv/bin/python scripts/retrain_model.py
```
## FastAPI Backend & Scheduler
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
```
### Systemd Service Setup
Create `/etc/systemd/system/skipredictor.service`:
```ini
[Unit]
Description=SkiPredictor Backend & Bot
After=network.target
[Service]
Type=simple
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
[Install]
WantedBy=multi-user.target
```
## Legacy Cron Jobs (Optional)
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
- **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
*See [README.md](../README.md) for the full directory tree.*
+196
View File
@@ -0,0 +1,196 @@
# SkiPredictor Operations Guide
This guide covers common administrative and maintenance tasks for the SkiPredictor system.
## Architecture
Single unified process: FastAPI + APScheduler + Telegram Bot (in-process).
**Scheduled tasks:**
- Standard (5h, 10h, 15h): archive forecasts, collect weather, generate predictions
- Extended (20h): same + webcam snapshot + crowd analysis + actuals scraping
- Training (Sunday 21h): retrain ML models
**Single source of truth:** `current_forecasts` / `past_forecasts` tables in SQLite.
## Database Management
The authoritative data source is the SQLite database at `data/processed/skipredictor.db`.
### Inspecting latest predictions
```bash
sqlite3 data/processed/skipredictor.db "SELECT * FROM current_forecasts ORDER BY station_id, prediction_date LIMIT 10;"
```
### Checking system status via CLI
```bash
.venv/bin/python -c "from storage import SQLiteStore; s=SQLiteStore(); print(f'DB Size: {s.db_path.stat().st_size/1024/1024:.2f} MB')"
```
## Setup (first time)
```bash
./setup.sh
```
This creates a venv, installs dependencies, downloads historical data, trains models, and collects webcam snapshots.
## Starting the unified daemon
```bash
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
```
This starts FastAPI (REST API), APScheduler (scheduled tasks), and the Telegram bot (in-process polling).
## Manual Forecast Cycles
### Run a full prediction cycle now
```bash
.venv/bin/python scripts/collect_daily_data.py
```
### Scrape today's actual results
```bash
.venv/bin/python data_sources/station_scraper.py
```
## ML Model Operations
### Force manual retraining
```bash
.venv/bin/python scripts/retrain_model.py
```
### Inspecting model metrics
```bash
sqlite3 data/processed/skipredictor.db "SELECT metrics_json FROM training_runs ORDER BY completed_at DESC LIMIT 1;"
```
## Telegram Bot
### Running the bot standalone (dev)
```bash
export TELEGRAM_BOT_TOKEN='your_token'
.venv/bin/python -m bot.telegram_bot
```
## Troubleshooting
### Missing forecasts?
1. Check `data/pipeline.log`.
2. Verify Open-Meteo connectivity: `curl "https://api.open-meteo.com/v1/forecast?latitude=43.05&longitude=-5.77&daily=snowfall_sum"`
3. Ensure models exist in `ml/models/`.
### Bot not responding?
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;"
```
+35
View File
@@ -0,0 +1,35 @@
# SkiPredictor TODO & Roadmap
This file tracks the current state of the project and planned enhancements.
## 🟢 In Progress / High Priority
- [ ] **Capacitor Mobile App**: Build a hybrid mobile application (iOS/Android) using the FastAPI backend.
- [ ] **FastAPI Backend Expansion**: Add more robust user management and potentially a web dashboard.
- [ ] **Advanced Crowd Analysis**: Refine the YOLO-based detection and integrate it more deeply into the hybrid predictor.
## 🟡 Planned Features
- [ ] **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
- [ ] **Model Retraining**: Monitor weekly retraining performance and tune hyperparameters.
- [ ] **Data Quality**: Continuously verify scraping reliability from Infonieve and Open-Meteo.
- [ ] **Documentation**: Keep the API spec and operations guide updated as features are added.
## ⚪ Completed Milestones
- [x] **SQLite Migration**: Moved from CSV/JSON file-based storage to a unified SQLite database.
- [x] **JWT Authentication**: Implemented secure API access with registration and login.
- [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.