mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 15:26:15 +00:00
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
This commit is contained in:
commit
1afe2b73e0
34 files changed
+7201
No files matched your search
+32
@@ -0,0 +1,32 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
.venv/
|
||||
*.egg-info/
|
||||
|
||||
# Data (raw data is collected per-server, not versioned)
|
||||
data/raw/
|
||||
data/processed/
|
||||
data/pipeline.log
|
||||
data/bot.log
|
||||
|
||||
# ML models (trained per-server)
|
||||
ml/models/*.joblib
|
||||
ml/models/evaluation_report.json
|
||||
ml/models/*_feature_importances.json
|
||||
|
||||
# Environment
|
||||
.env
|
||||
bot/.env
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# pytest
|
||||
.pytest_cache/
|
||||
@@ -0,0 +1,359 @@
|
||||
Ski Station Predictor – Autonomous Agent Specification
|
||||
Project Goal
|
||||
|
||||
Build a system that predicts next-day ski station conditions for the following stations in northern Spain:
|
||||
|
||||
Valgrande-Pajares
|
||||
|
||||
San Isidro
|
||||
|
||||
Fuentes de Invierno
|
||||
|
||||
Predictions must include:
|
||||
|
||||
Probability that the station will open
|
||||
|
||||
Estimated kilometers of skiable slopes
|
||||
|
||||
Expected crowd level
|
||||
|
||||
The prediction system must combine:
|
||||
|
||||
Historical operational data
|
||||
|
||||
Weather forecasts
|
||||
|
||||
Rule-based logic
|
||||
|
||||
Machine learning predictions
|
||||
|
||||
The results must be accessible through a Telegram bot.
|
||||
|
||||
This repository is designed to be developed collaboratively by AI coding agents.
|
||||
|
||||
Core System Philosophy
|
||||
|
||||
Predictions must follow a hybrid architecture.
|
||||
|
||||
ML predictions are useful but must never override physical constraints.
|
||||
|
||||
Prediction pipeline concept:
|
||||
|
||||
rules_engine → ml_model → hybrid_decision
|
||||
|
||||
Rules always have priority when safety or physical conditions make the outcome deterministic.
|
||||
|
||||
Example rule logic:
|
||||
|
||||
If wind gust exceeds operational limits the station is assumed closed regardless of ML prediction.
|
||||
|
||||
Development Stages
|
||||
|
||||
Agents must implement the system incrementally.
|
||||
|
||||
Phase 1 – Data Collection
|
||||
|
||||
Goal: build a historical dataset.
|
||||
|
||||
Required data sources:
|
||||
|
||||
Weather data
|
||||
Station operational status
|
||||
Calendar features
|
||||
|
||||
Outputs:
|
||||
|
||||
Daily structured dataset stored locally.
|
||||
|
||||
Phase 2 – Dataset Builder
|
||||
|
||||
Goal: transform raw data into ML-ready features.
|
||||
|
||||
Tasks:
|
||||
|
||||
Normalize weather variables
|
||||
|
||||
Aggregate daily features
|
||||
|
||||
Encode categorical features
|
||||
|
||||
Align timestamps
|
||||
|
||||
Outputs:
|
||||
|
||||
Processed dataset suitable for ML training.
|
||||
|
||||
Phase 3 – ML Training
|
||||
|
||||
Goal: train baseline predictive models.
|
||||
|
||||
Target variables:
|
||||
|
||||
station_open_probability
|
||||
km_open_prediction
|
||||
crowd_level_prediction
|
||||
|
||||
Recommended algorithms:
|
||||
|
||||
RandomForest
|
||||
GradientBoosting
|
||||
LightGBM
|
||||
|
||||
Agents must prioritize:
|
||||
|
||||
interpretability
|
||||
|
||||
robustness
|
||||
|
||||
small dataset performance
|
||||
|
||||
Phase 4 – Hybrid Predictor
|
||||
|
||||
Goal: combine rules with ML predictions.
|
||||
|
||||
Example architecture:
|
||||
|
||||
rules_engine
|
||||
ml_predictor
|
||||
hybrid_predictor
|
||||
|
||||
Rules must handle obvious constraints such as extreme wind conditions.
|
||||
|
||||
The ML model provides probabilistic refinement when rules are inconclusive.
|
||||
|
||||
Phase 5 – Telegram Bot
|
||||
|
||||
Goal: expose predictions to users.
|
||||
|
||||
Commands must include:
|
||||
|
||||
/pajares
|
||||
/sanisidro
|
||||
/fuentes
|
||||
|
||||
The bot should respond with:
|
||||
|
||||
open probability
|
||||
|
||||
estimated ski kilometers
|
||||
|
||||
predicted crowd level
|
||||
|
||||
weather summary
|
||||
|
||||
Example response structure:
|
||||
|
||||
Station name
|
||||
Probability of opening
|
||||
Expected kilometers open
|
||||
Crowd level estimate
|
||||
Key weather factors
|
||||
|
||||
Repository Structure
|
||||
|
||||
The repository must follow this structure.
|
||||
|
||||
ski-predictor
|
||||
|
||||
data
|
||||
raw
|
||||
processed
|
||||
|
||||
data_sources
|
||||
weather_api.py
|
||||
station_scraper.py
|
||||
webcam_collector.py
|
||||
|
||||
pipeline
|
||||
build_dataset.py
|
||||
feature_engineering.py
|
||||
|
||||
ml
|
||||
train_model.py
|
||||
evaluate_model.py
|
||||
models
|
||||
|
||||
predictor
|
||||
rules.py
|
||||
ml_predictor.py
|
||||
hybrid_predictor.py
|
||||
|
||||
bot
|
||||
telegram_bot.py
|
||||
|
||||
config
|
||||
stations.yaml
|
||||
features.yaml
|
||||
|
||||
scripts
|
||||
collect_daily_data.py
|
||||
retrain_model.py
|
||||
|
||||
tests
|
||||
|
||||
Agents must not deviate from this structure without justification.
|
||||
|
||||
Data Sources
|
||||
|
||||
Agents should prioritize reliable and free APIs.
|
||||
|
||||
Preferred weather providers:
|
||||
|
||||
Meteostat
|
||||
Open-Meteo
|
||||
AEMET (if accessible)
|
||||
|
||||
Required weather variables:
|
||||
|
||||
temperature
|
||||
snowfall
|
||||
precipitation
|
||||
wind_speed
|
||||
wind_gust
|
||||
wind_direction
|
||||
humidity
|
||||
pressure
|
||||
|
||||
Forecast data must be supported for next-day predictions.
|
||||
|
||||
Station Operational Data
|
||||
|
||||
Agents must scrape official station sources to collect:
|
||||
|
||||
open_status
|
||||
km_open
|
||||
lifts_open
|
||||
snow_depth
|
||||
|
||||
Scrapers must be robust to layout changes and include basic failure handling.
|
||||
|
||||
Optional Data Sources (Future Phase)
|
||||
|
||||
Webcam analysis can later be used to estimate crowd levels.
|
||||
|
||||
Potential signals:
|
||||
|
||||
number_of_people
|
||||
number_of_cars
|
||||
queue density
|
||||
|
||||
Computer vision may be used to extract these signals automatically.
|
||||
|
||||
This phase is not required for the first working version.
|
||||
|
||||
Feature Engineering
|
||||
|
||||
Agents must construct meaningful features such as:
|
||||
|
||||
snow_last_3_days
|
||||
snow_last_7_days
|
||||
avg_temperature
|
||||
max_wind_gust
|
||||
is_weekend
|
||||
is_holiday
|
||||
month_of_year
|
||||
|
||||
Temporal alignment between weather and station data is critical.
|
||||
|
||||
Machine Learning Constraints
|
||||
|
||||
The dataset will initially be small.
|
||||
|
||||
Agents must therefore prefer models that work well with limited data.
|
||||
|
||||
Recommended techniques:
|
||||
|
||||
tree-based models
|
||||
cross-validation
|
||||
feature importance inspection
|
||||
|
||||
Deep learning is not appropriate for this project.
|
||||
|
||||
Rule Engine
|
||||
|
||||
The rule engine must capture known operational constraints.
|
||||
|
||||
Examples include:
|
||||
|
||||
Extreme wind automatically prevents operation.
|
||||
|
||||
Rain at low altitude combined with high temperature reduces open slope probability.
|
||||
|
||||
Snow depth below operational threshold reduces open kilometers.
|
||||
|
||||
Rules must be configurable.
|
||||
|
||||
Hybrid Prediction Strategy
|
||||
|
||||
The final prediction is computed in three stages.
|
||||
|
||||
Step 1: evaluate rule engine
|
||||
Step 2: compute ML prediction
|
||||
Step 3: combine outputs into final decision
|
||||
|
||||
Rules may override ML outputs when conditions are physically impossible.
|
||||
|
||||
Daily Data Pipeline
|
||||
|
||||
The system must support a daily automated workflow.
|
||||
|
||||
Daily pipeline concept:
|
||||
|
||||
collect weather forecast
|
||||
collect station status
|
||||
append dataset
|
||||
generate prediction for tomorrow
|
||||
serve prediction through Telegram bot
|
||||
|
||||
Automation scripts should support cron execution.
|
||||
|
||||
Configuration
|
||||
|
||||
All station-specific parameters must live in configuration files.
|
||||
|
||||
Example configuration fields:
|
||||
|
||||
station_name
|
||||
location_coordinates
|
||||
altitude
|
||||
wind_closure_threshold
|
||||
minimum_snow_depth
|
||||
|
||||
Agents must not hardcode station parameters.
|
||||
|
||||
Code Quality Requirements
|
||||
|
||||
Agents must ensure:
|
||||
|
||||
Readable Python code
|
||||
Clear function boundaries
|
||||
Minimal dependencies
|
||||
Logging for data collectors
|
||||
Basic unit tests for core components
|
||||
|
||||
All modules must include docstrings.
|
||||
|
||||
Priority Order for Agents
|
||||
|
||||
Agents should work in the following order.
|
||||
|
||||
1 Build weather data collector
|
||||
2 Build station status scraper
|
||||
3 Implement dataset builder
|
||||
4 Implement baseline ML training
|
||||
5 Implement hybrid predictor
|
||||
6 Implement Telegram bot
|
||||
|
||||
The first milestone is a working prediction for tomorrow.
|
||||
|
||||
Definition of Success
|
||||
|
||||
A successful version of the system can:
|
||||
|
||||
Collect weather data automatically
|
||||
Collect station operational data
|
||||
Train a baseline ML model
|
||||
Generate a next-day prediction
|
||||
Deliver the prediction through a Telegram bot
|
||||
|
||||
All predictions must be reproducible.
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
# 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
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
TELEGRAM_BOT_TOKEN=your_bot_token_here
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
Bot package for the ski predictor Telegram bot.
|
||||
|
||||
Exposes the Telegram bot that serves next-day predictions
|
||||
for Valgrande-Pajares, San Isidro, and Fuentes de Invierno.
|
||||
"""
|
||||
@@ -0,0 +1,331 @@
|
||||
"""
|
||||
Telegram bot for the ski predictor system.
|
||||
|
||||
Serves next-day predictions for three ski stations in northern Spain:
|
||||
- Valgrande-Pajares (/pajares)
|
||||
- San Isidro (/sanisidro)
|
||||
- Fuentes de Invierno (/fuentes)
|
||||
|
||||
The bot reads predictions from the JSON file generated by the daily
|
||||
pipeline at data/processed/predictions_latest.json.
|
||||
|
||||
Usage:
|
||||
Set the TELEGRAM_BOT_TOKEN environment variable and run:
|
||||
python -m bot.telegram_bot
|
||||
or call main() directly.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from telegram import Update
|
||||
from telegram.constants import ParseMode
|
||||
from telegram.ext import Application, CommandHandler, ContextTypes
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Logging
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
logging.basicConfig(
|
||||
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
||||
level=logging.INFO,
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Resolve project root relative to this file regardless of cwd.
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
PREDICTIONS_FILE = _PROJECT_ROOT / "data" / "processed" / "predictions_latest.json"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Station metadata (mirrors config/stations.yaml without adding a runtime
|
||||
# dependency on pyyaml inside the bot module itself).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
STATIONS = {
|
||||
"pajares": {
|
||||
"name": "Valgrande-Pajares",
|
||||
"max_km": 22.0,
|
||||
},
|
||||
"sanisidro": {
|
||||
"name": "San Isidro",
|
||||
"max_km": 31.0,
|
||||
},
|
||||
"fuentes": {
|
||||
"name": "Fuentes de Invierno",
|
||||
"max_km": 8.6,
|
||||
},
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prediction loading
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def load_predictions() -> dict | None:
|
||||
"""Load the latest predictions from the JSON file produced by the pipeline.
|
||||
|
||||
Returns the parsed dictionary on success, or None if the file is missing
|
||||
or cannot be decoded.
|
||||
"""
|
||||
if not PREDICTIONS_FILE.exists():
|
||||
logger.warning("Predictions file not found: %s", PREDICTIONS_FILE)
|
||||
return None
|
||||
|
||||
try:
|
||||
with PREDICTIONS_FILE.open(encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
logger.info("Predictions loaded from %s", PREDICTIONS_FILE)
|
||||
return data
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.error("Failed to decode predictions file: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Message formatting
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_CROWD_LABELS = {
|
||||
"low": "Bajo",
|
||||
"medium": "Medio",
|
||||
"high": "Alto",
|
||||
}
|
||||
|
||||
|
||||
def _crowd_label(raw: str) -> str:
|
||||
"""Translate a crowd level key to its Spanish display label."""
|
||||
return _CROWD_LABELS.get(str(raw).lower(), raw.capitalize())
|
||||
|
||||
|
||||
def _open_label(probability: float) -> str:
|
||||
"""Return a human-readable open/closed label based on probability."""
|
||||
if probability >= 0.70:
|
||||
return "Abierta"
|
||||
if probability >= 0.40:
|
||||
return "Probable apertura"
|
||||
return "Cerrada"
|
||||
|
||||
|
||||
def format_station_prediction(station_key: str, prediction: dict) -> str:
|
||||
"""Build the Telegram Markdown message for a single station prediction.
|
||||
|
||||
Args:
|
||||
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
|
||||
prediction: Sub-dictionary for this station from predictions_latest.json.
|
||||
|
||||
Returns:
|
||||
Formatted string ready to be sent with ParseMode.MARKDOWN_V2
|
||||
(uses MarkdownV2 escaping where needed).
|
||||
"""
|
||||
meta = STATIONS[station_key]
|
||||
station_name = meta["name"]
|
||||
max_km = meta["max_km"]
|
||||
|
||||
open_prob: float = prediction.get("station_open_probability", 0.0)
|
||||
km_open: float = prediction.get("km_open_prediction", 0.0)
|
||||
crowd_raw: str = prediction.get("crowd_level_prediction", "unknown")
|
||||
|
||||
# Weather sub-dict is optional; provide sensible defaults.
|
||||
weather: dict = prediction.get("weather_forecast", {})
|
||||
temp_min: float | None = weather.get("temperature_min")
|
||||
temp_max: float | None = weather.get("temperature_max")
|
||||
snowfall: float | None = weather.get("snowfall_cm")
|
||||
wind_speed: float | None = weather.get("wind_speed_kmh")
|
||||
wind_gust: float | None = weather.get("wind_gust_kmh")
|
||||
|
||||
source: str = prediction.get("source", "prediccion hibrida (reglas + ML)")
|
||||
|
||||
open_pct = int(round(open_prob * 100))
|
||||
open_str = f"{_open_label(open_prob)} ({open_pct}% probabilidad)"
|
||||
|
||||
crowd_str = _crowd_label(crowd_raw)
|
||||
km_str = f"{km_open:.1f} / {max_km:.1f}"
|
||||
|
||||
# Build weather block only with available data.
|
||||
weather_lines: list[str] = []
|
||||
if temp_min is not None and temp_max is not None:
|
||||
weather_lines.append(f"Temperatura: {temp_min:.0f}C / {temp_max:.0f}C")
|
||||
elif temp_max is not None:
|
||||
weather_lines.append(f"Temperatura maxima: {temp_max:.0f}C")
|
||||
|
||||
if snowfall is not None:
|
||||
weather_lines.append(f"Nieve: {snowfall:.0f}cm nuevos")
|
||||
|
||||
if wind_speed is not None and wind_gust is not None:
|
||||
weather_lines.append(
|
||||
f"Viento: {wind_speed:.0f} km/h (rachas {wind_gust:.0f} km/h)"
|
||||
)
|
||||
elif wind_speed is not None:
|
||||
weather_lines.append(f"Viento: {wind_speed:.0f} km/h")
|
||||
|
||||
weather_block = ""
|
||||
if weather_lines:
|
||||
weather_block = "\n*Tiempo previsto:*\n" + "\n".join(weather_lines) + "\n"
|
||||
|
||||
message = (
|
||||
f"*{station_name} \\- Prediccion para manana*\n"
|
||||
f"\n"
|
||||
f"Estado: {open_str}\n"
|
||||
f"Km esquiables: {km_str}\n"
|
||||
f"Nivel de afluencia: {crowd_str}\n"
|
||||
f"{weather_block}"
|
||||
f"\n_Fuente: {source}_"
|
||||
)
|
||||
|
||||
return message
|
||||
|
||||
|
||||
def _no_prediction_message(station_name: str) -> str:
|
||||
"""Return a friendly error message when prediction data is unavailable."""
|
||||
return (
|
||||
f"Lo siento, no hay prediccion disponible para *{station_name}* en este "
|
||||
f"momento\\.\n\n"
|
||||
f"_El pipeline de datos se ejecuta diariamente\\. "
|
||||
f"Intentalo de nuevo mas tarde\\._"
|
||||
)
|
||||
|
||||
|
||||
def _unavailable_message() -> str:
|
||||
"""Return a message when the predictions file cannot be loaded at all."""
|
||||
return (
|
||||
"No se han podido cargar las predicciones\\.\n\n"
|
||||
"_Asegurate de que el pipeline diario se ha ejecutado correctamente\\. "
|
||||
"Intentalo de nuevo mas tarde\\._"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Command handlers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def cmd_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Handle the /start command with a welcome message."""
|
||||
text = (
|
||||
"*Bienvenido al bot de prediccion de estaciones de esqui* \\!\n\n"
|
||||
"Este bot te informa sobre las condiciones previstas para el dia "
|
||||
"siguiente en tres estaciones de esqui del norte de Espana:\n\n"
|
||||
" \\- *Valgrande\\-Pajares*\n"
|
||||
" \\- *San Isidro*\n"
|
||||
" \\- *Fuentes de Invierno*\n\n"
|
||||
"Las predicciones combinan reglas operacionales y modelos de "
|
||||
"aprendizaje automatico basados en datos meteorologicos\\.\n\n"
|
||||
"Escribe /help para ver los comandos disponibles\\."
|
||||
)
|
||||
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
|
||||
|
||||
|
||||
async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Handle the /help command with a list of available commands."""
|
||||
text = (
|
||||
"*Comandos disponibles:*\n\n"
|
||||
"/pajares \\— Prediccion para Valgrande\\-Pajares\n"
|
||||
"/sanisidro \\— Prediccion para San Isidro\n"
|
||||
"/fuentes \\— Prediccion para Fuentes de Invierno\n"
|
||||
"/all \\— Predicciones para las tres estaciones\n"
|
||||
"/help \\— Mostrar esta ayuda\n"
|
||||
)
|
||||
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
|
||||
|
||||
|
||||
async def _send_station(
|
||||
update: Update,
|
||||
station_key: str,
|
||||
) -> None:
|
||||
"""Fetch and send the prediction for a single station.
|
||||
|
||||
Args:
|
||||
update: Telegram Update object.
|
||||
station_key: One of 'pajares', 'sanisidro', 'fuentes'.
|
||||
"""
|
||||
station_name = STATIONS[station_key]["name"]
|
||||
predictions = load_predictions()
|
||||
|
||||
if predictions is None:
|
||||
text = _unavailable_message()
|
||||
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
|
||||
return
|
||||
|
||||
station_pred = predictions.get(station_key)
|
||||
if not station_pred:
|
||||
logger.warning("No prediction entry for station '%s'", station_key)
|
||||
text = _no_prediction_message(station_name)
|
||||
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
|
||||
return
|
||||
|
||||
try:
|
||||
text = format_station_prediction(station_key, station_pred)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("Error formatting prediction for '%s': %s", station_key, exc)
|
||||
text = _no_prediction_message(station_name)
|
||||
|
||||
await update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN_V2)
|
||||
|
||||
|
||||
async def cmd_pajares(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Handle the /pajares command — prediction for Valgrande-Pajares."""
|
||||
logger.info("User %s requested /pajares", update.effective_user.id)
|
||||
await _send_station(update, "pajares")
|
||||
|
||||
|
||||
async def cmd_sanisidro(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Handle the /sanisidro command — prediction for San Isidro."""
|
||||
logger.info("User %s requested /sanisidro", update.effective_user.id)
|
||||
await _send_station(update, "sanisidro")
|
||||
|
||||
|
||||
async def cmd_fuentes(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Handle the /fuentes command — prediction for Fuentes de Invierno."""
|
||||
logger.info("User %s requested /fuentes", update.effective_user.id)
|
||||
await _send_station(update, "fuentes")
|
||||
|
||||
|
||||
async def cmd_all(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||
"""Handle the /all command — predictions for all three stations."""
|
||||
logger.info("User %s requested /all", update.effective_user.id)
|
||||
for station_key in ("pajares", "sanisidro", "fuentes"):
|
||||
await _send_station(update, station_key)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bot entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Build and start the Telegram bot using long-polling.
|
||||
|
||||
Reads the bot token from the TELEGRAM_BOT_TOKEN environment variable.
|
||||
Raises:
|
||||
EnvironmentError: If TELEGRAM_BOT_TOKEN is not set.
|
||||
"""
|
||||
token = os.environ.get("TELEGRAM_BOT_TOKEN")
|
||||
if not token:
|
||||
raise EnvironmentError(
|
||||
"La variable de entorno TELEGRAM_BOT_TOKEN no esta definida. "
|
||||
"Configura el token del bot antes de iniciar."
|
||||
)
|
||||
|
||||
logger.info("Iniciando bot de prediccion de esqui...")
|
||||
|
||||
app = Application.builder().token(token).build()
|
||||
|
||||
app.add_handler(CommandHandler("start", cmd_start))
|
||||
app.add_handler(CommandHandler("help", cmd_help))
|
||||
app.add_handler(CommandHandler("pajares", cmd_pajares))
|
||||
app.add_handler(CommandHandler("sanisidro", cmd_sanisidro))
|
||||
app.add_handler(CommandHandler("fuentes", cmd_fuentes))
|
||||
app.add_handler(CommandHandler("all", cmd_all))
|
||||
|
||||
logger.info("Bot listo. Esperando mensajes...")
|
||||
app.run_polling(allowed_updates=Update.ALL_TYPES)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,34 @@
|
||||
weather_variables:
|
||||
- temperature_2m_max
|
||||
- temperature_2m_min
|
||||
- temperature_2m_mean
|
||||
- precipitation_sum
|
||||
- snowfall_sum
|
||||
- wind_speed_10m_max
|
||||
- wind_gusts_10m_max
|
||||
- wind_direction_10m_dominant
|
||||
- relative_humidity_2m_mean
|
||||
- surface_pressure_mean
|
||||
|
||||
engineered_features:
|
||||
- snow_last_3_days
|
||||
- snow_last_7_days
|
||||
- avg_temperature_3_days
|
||||
- max_wind_gust
|
||||
- is_weekend
|
||||
- is_holiday
|
||||
- month_of_year
|
||||
- day_of_week
|
||||
- days_since_last_snowfall
|
||||
- temperature_trend_3_days
|
||||
- pressure_trend_3_days
|
||||
|
||||
target_variables:
|
||||
- station_open
|
||||
- km_open
|
||||
- crowd_level
|
||||
|
||||
crowd_levels:
|
||||
- low
|
||||
- medium
|
||||
- high
|
||||
@@ -0,0 +1,77 @@
|
||||
stations:
|
||||
pajares:
|
||||
name: "Valgrande-Pajares"
|
||||
latitude: 43.0500
|
||||
longitude: -5.7700
|
||||
altitude: 1500
|
||||
wind_closure_threshold: 80 # km/h
|
||||
minimum_snow_depth: 30 # cm
|
||||
max_km_skiable: 22.0
|
||||
url: "https://www.valgrande-pajares.com"
|
||||
telegram_command: "/pajares"
|
||||
webcams:
|
||||
# infonieve.es embeds a timestamp in the filename for Pajares.
|
||||
# The collector resolves the current URL by scraping the page at runtime.
|
||||
# primary_webcam_page is fetched to extract the live snapshot URL.
|
||||
primary_webcam_page: "https://www.infonieve.es/estacion-esqui/valgrande-pajares/webcams/"
|
||||
# Fallback static snapshots served by webcamsdeasturias.com via infonieve.
|
||||
# These URLs include a timestamp suffix; the page-scrape strategy is preferred.
|
||||
snapshots:
|
||||
- label: "Cuitu Negru - Telecabina"
|
||||
url_pattern: "https://www.infonieve.es/webcams/pajares-cuitu_{timestamp}.jpg"
|
||||
static: false
|
||||
- label: "Panoramica"
|
||||
url_pattern: "https://www.infonieve.es/webcams/pajares-panoramica_{timestamp}.jpg"
|
||||
static: false
|
||||
|
||||
sanisidro:
|
||||
name: "San Isidro"
|
||||
latitude: 43.0700
|
||||
longitude: -5.3700
|
||||
altitude: 1500
|
||||
wind_closure_threshold: 80
|
||||
minimum_snow_depth: 30
|
||||
max_km_skiable: 31.0
|
||||
url: "https://www.san-isidro.net"
|
||||
telegram_command: "/sanisidro"
|
||||
webcams:
|
||||
# Static snapshot URLs served by nieveleonsanisidro.com.
|
||||
# These are overwritten in-place on each camera refresh cycle (no timestamp).
|
||||
primary_webcam_page: "https://www.infonieve.es/estacion-esqui/san-isidro/webcams/"
|
||||
snapshots:
|
||||
- label: "Cebolledo I"
|
||||
url: "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/CebolledoI.jpg"
|
||||
static: true
|
||||
- label: "Salencias"
|
||||
url: "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/Salencias.jpg"
|
||||
static: true
|
||||
- label: "Riopinos"
|
||||
url: "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/Riopinos.jpg"
|
||||
static: true
|
||||
- label: "Cebolledo II"
|
||||
url: "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/CebolledoII.jpg"
|
||||
static: true
|
||||
|
||||
fuentes:
|
||||
name: "Fuentes de Invierno"
|
||||
latitude: 43.0833
|
||||
longitude: -5.9333
|
||||
altitude: 1500
|
||||
wind_closure_threshold: 80
|
||||
minimum_snow_depth: 30
|
||||
max_km_skiable: 8.6
|
||||
url: "https://www.fuentesdeinvierno.com"
|
||||
telegram_command: "/fuentes"
|
||||
webcams:
|
||||
# fuentesdeinvierno.com serves snapshots under /tmp/ with a self-signed TLS
|
||||
# certificate. ssl_verify is set to false for these entries.
|
||||
primary_webcam_page: "https://www.infonieve.es/estacion-esqui/fuentes-de-invierno/webcams/"
|
||||
snapshots:
|
||||
- label: "Camara 1"
|
||||
url: "https://fuentesdeinvierno.com/tmp/camara1.jpg"
|
||||
static: true
|
||||
ssl_verify: false
|
||||
- label: "Camara 2"
|
||||
url: "https://fuentesdeinvierno.com/tmp/camara2.jpg"
|
||||
static: true
|
||||
ssl_verify: false
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Data sources package for ski predictor.
|
||||
|
||||
Modules:
|
||||
weather_api: Fetches weather data from Open-Meteo API.
|
||||
"""
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Crowd density estimator using YOLOv8 object detection.
|
||||
|
||||
Analyses webcam snapshot images from ski stations to estimate crowd levels.
|
||||
Uses the YOLOv8 nano model (``yolov8n.pt``) from the ``ultralytics`` package
|
||||
to detect people, cars, buses and trucks.
|
||||
|
||||
Detected object counts are mapped to three crowd density levels:
|
||||
|
||||
* **low** – fewer than 20 cars OR fewer than 10 people visible
|
||||
* **medium** – 20–50 cars OR 10–30 people
|
||||
* **high** – more than 50 cars OR more than 30 people
|
||||
|
||||
Analysis results are persisted as JSON files in ``data/raw/`` following the
|
||||
naming pattern ``crowd_{station_id}_{date}.json``.
|
||||
|
||||
Typical usage::
|
||||
|
||||
analyzer = CrowdAnalyzer()
|
||||
result = analyzer.estimate_crowd_level("pajares")
|
||||
print(result["crowd_density"]) # "low" / "medium" / "high"
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import warnings
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
|
||||
RAW_DATA_DIR = BASE_DIR / "data" / "raw"
|
||||
|
||||
# YOLO model weights file – downloaded automatically on first use.
|
||||
YOLO_MODEL_WEIGHTS = "yolov8n.pt"
|
||||
|
||||
# COCO class names that count towards crowd estimation.
|
||||
VEHICLE_CLASSES = {"car", "bus", "truck", "motorcycle"}
|
||||
PERSON_CLASS = "person"
|
||||
|
||||
# Crowd density thresholds.
|
||||
_CAR_THRESHOLD_LOW = 20
|
||||
_CAR_THRESHOLD_HIGH = 50
|
||||
_PERSON_THRESHOLD_LOW = 10
|
||||
_PERSON_THRESHOLD_HIGH = 30
|
||||
|
||||
# Minimum YOLO confidence score for a detection to be counted.
|
||||
DETECTION_CONFIDENCE = 0.25
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CrowdAnalyzer
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class CrowdAnalyzer:
|
||||
"""Estimates crowd levels at ski stations from webcam snapshot images.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
config_path:
|
||||
Path to the stations YAML configuration file. Defaults to
|
||||
``config/stations.yaml`` relative to the project root.
|
||||
model_weights:
|
||||
YOLOv8 weights identifier passed to ``ultralytics.YOLO()``.
|
||||
Defaults to ``"yolov8n.pt"`` (nano model).
|
||||
output_dir:
|
||||
Directory where JSON result files are written. Created if it does
|
||||
not exist. Defaults to ``data/raw/``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_path: Path = CONFIG_PATH,
|
||||
model_weights: str = YOLO_MODEL_WEIGHTS,
|
||||
output_dir: Path = RAW_DATA_DIR,
|
||||
) -> None:
|
||||
self.config_path = config_path
|
||||
self.model_weights = model_weights
|
||||
self.output_dir = output_dir
|
||||
self.stations = self._load_stations()
|
||||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._model: Any = None # Lazy-loaded on first inference call.
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def analyze_image(self, image_path: str) -> dict[str, Any]:
|
||||
"""Run object detection on a single webcam snapshot.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
image_path:
|
||||
Path to a JPEG or PNG webcam image.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Keys:
|
||||
|
||||
* ``cars_detected`` – number of cars detected
|
||||
* ``people_detected`` – number of people detected
|
||||
* ``buses_detected`` – number of buses detected
|
||||
* ``total_vehicles`` – cars + buses + trucks combined
|
||||
* ``crowd_density`` – ``"low"``, ``"medium"``, or ``"high"``
|
||||
* ``confidence_scores`` – list of per-detection confidence values
|
||||
* ``timestamp`` – ISO-8601 timestamp of when analysis ran
|
||||
|
||||
Raises
|
||||
------
|
||||
FileNotFoundError
|
||||
If *image_path* does not exist.
|
||||
RuntimeError
|
||||
If the YOLO model cannot be loaded (e.g. ``ultralytics`` not
|
||||
installed).
|
||||
"""
|
||||
path = Path(image_path)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Image not found: {image_path}")
|
||||
|
||||
model = self._load_model()
|
||||
results = model(str(path), conf=DETECTION_CONFIDENCE, verbose=False)
|
||||
|
||||
cars = 0
|
||||
people = 0
|
||||
buses = 0
|
||||
trucks = 0
|
||||
confidence_scores: list[float] = []
|
||||
|
||||
for result in results:
|
||||
boxes = result.boxes
|
||||
if boxes is None:
|
||||
continue
|
||||
for box in boxes:
|
||||
conf = float(box.conf[0])
|
||||
cls_id = int(box.cls[0])
|
||||
cls_name = result.names.get(cls_id, "").lower()
|
||||
|
||||
confidence_scores.append(round(conf, 4))
|
||||
|
||||
if cls_name == PERSON_CLASS:
|
||||
people += 1
|
||||
elif cls_name == "car":
|
||||
cars += 1
|
||||
elif cls_name == "bus":
|
||||
buses += 1
|
||||
elif cls_name == "truck":
|
||||
trucks += 1
|
||||
|
||||
total_vehicles = cars + buses + trucks
|
||||
|
||||
return {
|
||||
"cars_detected": cars,
|
||||
"people_detected": people,
|
||||
"buses_detected": buses,
|
||||
"total_vehicles": total_vehicles,
|
||||
"crowd_density": self._classify_density(cars, people),
|
||||
"confidence_scores": confidence_scores,
|
||||
"timestamp": datetime.now().isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
def estimate_crowd_level(self, station_id: str) -> dict[str, Any]:
|
||||
"""Capture the latest webcam snapshot for *station_id* and analyse it.
|
||||
|
||||
Downloads one image via :class:`~data_sources.webcam_collector.WebcamCollector`,
|
||||
runs object detection, saves the result as a JSON file and returns the
|
||||
analysis dict.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
station_id:
|
||||
Must match a key in ``config/stations.yaml``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Same structure as :meth:`analyze_image`, with an additional
|
||||
``station_id`` key and a ``image_path`` key (``None`` if the
|
||||
webcam capture failed). When capture fails a minimal dict with
|
||||
``crowd_density="unknown"`` is returned so the pipeline can
|
||||
continue.
|
||||
"""
|
||||
# Import here to avoid circular imports at module level.
|
||||
from data_sources.webcam_collector import WebcamCollector # noqa: PLC0415
|
||||
|
||||
collector = WebcamCollector(config_path=self.config_path)
|
||||
saved_paths = collector.capture(station_id)
|
||||
|
||||
if not saved_paths:
|
||||
logger.warning(
|
||||
"No webcam images captured for station=%s; crowd level unknown",
|
||||
station_id,
|
||||
)
|
||||
result = self._empty_result(station_id, image_path=None)
|
||||
self._save_result(result, station_id)
|
||||
return result
|
||||
|
||||
# Analyse only the first captured image to keep latency low.
|
||||
image_path = saved_paths[0]
|
||||
|
||||
try:
|
||||
analysis = self.analyze_image(image_path)
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Image analysis failed for station=%s path=%s: %s",
|
||||
station_id,
|
||||
image_path,
|
||||
exc,
|
||||
)
|
||||
result = self._empty_result(station_id, image_path=image_path)
|
||||
self._save_result(result, station_id)
|
||||
return result
|
||||
|
||||
analysis["station_id"] = station_id
|
||||
analysis["image_path"] = image_path
|
||||
self._save_result(analysis, station_id)
|
||||
return analysis
|
||||
|
||||
def analyze_all_stations(self) -> dict[str, dict[str, Any]]:
|
||||
"""Run crowd estimation for every station defined in the config.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, dict]
|
||||
Mapping of station_id to its crowd analysis result dict.
|
||||
"""
|
||||
results: dict[str, dict[str, Any]] = {}
|
||||
for station_id in self.stations:
|
||||
logger.info("Analysing crowd for station=%s", station_id)
|
||||
results[station_id] = self.estimate_crowd_level(station_id)
|
||||
logger.info(
|
||||
"analyze_all_stations complete. Densities: %s",
|
||||
{k: v.get("crowd_density") for k, v in results.items()},
|
||||
)
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _classify_density(cars: int, people: int) -> str:
|
||||
"""Map raw detection counts to a density label.
|
||||
|
||||
The classification uses whichever signal indicates the *highest*
|
||||
crowd level – i.e. if cars suggest "high" but people suggest "low",
|
||||
the result is "high".
|
||||
|
||||
Parameters
|
||||
----------
|
||||
cars:
|
||||
Number of cars detected in the image.
|
||||
people:
|
||||
Number of people detected in the image.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str
|
||||
One of ``"low"``, ``"medium"``, or ``"high"``.
|
||||
"""
|
||||
|
||||
def _level(value: int, low_threshold: int, high_threshold: int) -> int:
|
||||
"""Return 0=low, 1=medium, 2=high for a given count."""
|
||||
if value < low_threshold:
|
||||
return 0
|
||||
if value <= high_threshold:
|
||||
return 1
|
||||
return 2
|
||||
|
||||
car_level = _level(cars, _CAR_THRESHOLD_LOW, _CAR_THRESHOLD_HIGH)
|
||||
person_level = _level(people, _PERSON_THRESHOLD_LOW, _PERSON_THRESHOLD_HIGH)
|
||||
combined = max(car_level, person_level)
|
||||
return ["low", "medium", "high"][combined]
|
||||
|
||||
def _load_model(self) -> Any:
|
||||
"""Lazy-load the YOLOv8 model.
|
||||
|
||||
The model is cached in ``self._model`` after the first call.
|
||||
|
||||
Returns
|
||||
-------
|
||||
ultralytics.YOLO
|
||||
Loaded model instance.
|
||||
|
||||
Raises
|
||||
------
|
||||
RuntimeError
|
||||
If the ``ultralytics`` package is not installed.
|
||||
"""
|
||||
if self._model is not None:
|
||||
return self._model
|
||||
|
||||
try:
|
||||
from ultralytics import YOLO # noqa: PLC0415
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"The 'ultralytics' package is required for crowd analysis. "
|
||||
"Install it with: pip install ultralytics>=8.0.0"
|
||||
) from exc
|
||||
|
||||
logger.info("Loading YOLO model: %s", self.model_weights)
|
||||
# Suppress ultralytics INFO logs during model loading.
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
self._model = YOLO(self.model_weights)
|
||||
|
||||
return self._model
|
||||
|
||||
def _load_stations(self) -> dict[str, Any]:
|
||||
"""Load station configuration from YAML."""
|
||||
with open(self.config_path, "r", encoding="utf-8") as fh:
|
||||
config = yaml.safe_load(fh)
|
||||
return config.get("stations", {})
|
||||
|
||||
@staticmethod
|
||||
def _empty_result(station_id: str, image_path: str | None) -> dict[str, Any]:
|
||||
"""Return a placeholder result when capture or analysis fails."""
|
||||
return {
|
||||
"station_id": station_id,
|
||||
"image_path": image_path,
|
||||
"cars_detected": 0,
|
||||
"people_detected": 0,
|
||||
"buses_detected": 0,
|
||||
"total_vehicles": 0,
|
||||
"crowd_density": "unknown",
|
||||
"confidence_scores": [],
|
||||
"timestamp": datetime.now().isoformat(timespec="seconds"),
|
||||
}
|
||||
|
||||
def _save_result(self, result: dict[str, Any], station_id: str) -> None:
|
||||
"""Persist an analysis result dict as a JSON file.
|
||||
|
||||
Filename format: ``crowd_{station_id}_{date}.json``
|
||||
|
||||
Parameters
|
||||
----------
|
||||
result:
|
||||
Analysis dict to serialise.
|
||||
station_id:
|
||||
Used to construct the output filename.
|
||||
"""
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
filename = self.output_dir / f"crowd_{station_id}_{today}.json"
|
||||
|
||||
# Append to an existing file (list of results) or create a new one.
|
||||
if filename.exists():
|
||||
try:
|
||||
existing = json.loads(filename.read_text(encoding="utf-8"))
|
||||
if not isinstance(existing, list):
|
||||
existing = [existing]
|
||||
except (json.JSONDecodeError, OSError):
|
||||
existing = []
|
||||
else:
|
||||
existing = []
|
||||
|
||||
existing.append(result)
|
||||
filename.write_text(
|
||||
json.dumps(existing, indent=2, ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
logger.info("Saved crowd analysis to %s", filename)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Download historical station data from infonieve.es TSV endpoints.
|
||||
|
||||
Infonieve provides daily operational data for ski stations going back to
|
||||
the 2009-10 season via a TSV endpoint:
|
||||
|
||||
estacion-esqui.historico-nieve.tsv.php?id={station_id}&anyo={year}&data=parte
|
||||
|
||||
Columns in the TSV:
|
||||
date, closedflag, turisticoflag, kmtotal, kmopen, pistastotal,
|
||||
pistasopen, espesormin, espesormax, calidadnieve, kmprocessed,
|
||||
pistasprocessed, minprocessed, maxprocessed, idestado
|
||||
|
||||
This module downloads all available seasons for the three target stations
|
||||
and saves the combined data as CSVs in data/raw/.
|
||||
"""
|
||||
|
||||
import io
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
_RAW_DIR = _PROJECT_ROOT / "data" / "raw"
|
||||
|
||||
_BASE_URL = "https://www.infonieve.es/estacion-esqui.historico-nieve.tsv.php"
|
||||
|
||||
# Infonieve internal IDs for our stations
|
||||
_STATION_IDS = {
|
||||
"pajares": 13,
|
||||
"sanisidro": 14,
|
||||
"fuentes": 5448,
|
||||
}
|
||||
|
||||
# Seasons available (the year parameter is the year the season starts in autumn)
|
||||
# e.g. 2024 = season 2024-25
|
||||
_SEASONS = list(range(2009, 2026))
|
||||
|
||||
_USER_AGENT = (
|
||||
"Mozilla/5.0 (X11; Linux x86_64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/120.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
def download_season(
|
||||
station_id: str, infonieve_id: int, year: int, session: requests.Session
|
||||
) -> pd.DataFrame | None:
|
||||
"""Download a single season's daily data from infonieve.es.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
station_id:
|
||||
Our station key (e.g. 'pajares').
|
||||
infonieve_id:
|
||||
Infonieve internal numeric ID for the station.
|
||||
year:
|
||||
The season start year (e.g. 2024 for 2024-25 season).
|
||||
session:
|
||||
Requests session with appropriate headers.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame or None
|
||||
DataFrame with daily records, or None if no data available.
|
||||
"""
|
||||
params = {"id": infonieve_id, "anyo": year, "data": "parte"}
|
||||
try:
|
||||
resp = session.get(_BASE_URL, params=params, timeout=30)
|
||||
resp.raise_for_status()
|
||||
except requests.RequestException as exc:
|
||||
logger.warning("Failed to fetch %s season %d-%d: %s", station_id, year, year + 1, exc)
|
||||
return None
|
||||
|
||||
text = resp.text.strip()
|
||||
if not text or len(text) < 20:
|
||||
logger.debug("No data for %s season %d-%d.", station_id, year, year + 1)
|
||||
return None
|
||||
|
||||
try:
|
||||
df = pd.read_csv(io.StringIO(text), sep="\t")
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to parse TSV for %s season %d-%d: %s", station_id, year, year + 1, exc)
|
||||
return None
|
||||
|
||||
if df.empty:
|
||||
return None
|
||||
|
||||
# Normalize column names
|
||||
df.columns = df.columns.str.strip().str.lower()
|
||||
|
||||
# Add metadata
|
||||
df["station_id"] = station_id
|
||||
df["season"] = f"{year}-{str(year + 1)[-2:]}"
|
||||
|
||||
logger.debug("Downloaded %s season %d-%d: %d rows.", station_id, year, year + 1, len(df))
|
||||
return df
|
||||
|
||||
|
||||
def download_all_history() -> pd.DataFrame:
|
||||
"""Download all available historical data for all three stations.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Combined DataFrame with all seasons and stations.
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": _USER_AGENT,
|
||||
"Accept-Language": "es-ES,es;q=0.9",
|
||||
"Referer": "https://www.infonieve.es/",
|
||||
})
|
||||
|
||||
all_frames = []
|
||||
|
||||
for station_id, infonieve_id in _STATION_IDS.items():
|
||||
logger.info("Downloading history for %s (infonieve id=%d)...", station_id, infonieve_id)
|
||||
|
||||
for year in _SEASONS:
|
||||
df = download_season(station_id, infonieve_id, year, session)
|
||||
if df is not None and not df.empty:
|
||||
all_frames.append(df)
|
||||
|
||||
# Be polite to the server
|
||||
time.sleep(0.3)
|
||||
|
||||
logger.info("Finished %s: %d seasons with data.", station_id,
|
||||
sum(1 for f in all_frames if f["station_id"].iloc[0] == station_id))
|
||||
|
||||
if not all_frames:
|
||||
logger.error("No historical data downloaded from any station.")
|
||||
return pd.DataFrame()
|
||||
|
||||
combined = pd.concat(all_frames, ignore_index=True)
|
||||
|
||||
# Normalize the date column
|
||||
if "date" in combined.columns:
|
||||
combined["date"] = pd.to_datetime(combined["date"], format="mixed", dayfirst=True)
|
||||
|
||||
# Sort
|
||||
combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True)
|
||||
|
||||
# Save
|
||||
_RAW_DIR.mkdir(parents=True, exist_ok=True)
|
||||
output_path = _RAW_DIR / "station_historical_all.csv"
|
||||
combined.to_csv(output_path, index=False)
|
||||
logger.info("Historical data saved to %s: %d total rows.", output_path, len(combined))
|
||||
|
||||
# Summary
|
||||
for sid in _STATION_IDS:
|
||||
station_data = combined[combined["station_id"] == sid]
|
||||
if not station_data.empty:
|
||||
logger.info(
|
||||
" %s: %d rows, %s to %s, %d seasons",
|
||||
sid,
|
||||
len(station_data),
|
||||
station_data["date"].min().strftime("%Y-%m-%d"),
|
||||
station_data["date"].max().strftime("%Y-%m-%d"),
|
||||
station_data["season"].nunique(),
|
||||
)
|
||||
|
||||
return combined
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
|
||||
)
|
||||
df = download_all_history()
|
||||
print(f"\nTotal: {len(df)} rows")
|
||||
print(f"Columns: {list(df.columns)}")
|
||||
print(f"\nPer station:")
|
||||
print(df.groupby("station_id").agg(
|
||||
rows=("date", "count"),
|
||||
first_date=("date", "min"),
|
||||
last_date=("date", "max"),
|
||||
seasons=("season", "nunique"),
|
||||
))
|
||||
@@ -0,0 +1,405 @@
|
||||
"""
|
||||
station_scraper.py
|
||||
|
||||
Scrapes ski station operational data for the three northern Spain stations
|
||||
managed by the government of Asturias/León:
|
||||
|
||||
- Valgrande-Pajares (station_id: pajares)
|
||||
- San Isidro (station_id: sanisidro)
|
||||
- Fuentes de Invierno(station_id: fuentes)
|
||||
|
||||
Primary source: infonieve.es (https://www.infonieve.es/estacion-esqui/{slug}/)
|
||||
Fallback: returns None values with a logged warning when scraping fails.
|
||||
|
||||
Raw responses are saved to:
|
||||
data/raw/station_{station_id}_{date}.json
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import requests
|
||||
import yaml
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
_CONFIG_PATH = _PROJECT_ROOT / "config" / "stations.yaml"
|
||||
_RAW_DATA_DIR = _PROJECT_ROOT / "data" / "raw"
|
||||
|
||||
_USER_AGENT = (
|
||||
"Mozilla/5.0 (X11; Linux x86_64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/120.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
_REQUEST_TIMEOUT = 15 # seconds
|
||||
|
||||
# Mapping from station_id to the slug used on infonieve.es
|
||||
_INFONIEVE_SLUGS: dict[str, str] = {
|
||||
"pajares": "valgrande-pajares",
|
||||
"sanisidro": "san-isidro",
|
||||
"fuentes": "fuentes-de-invierno",
|
||||
}
|
||||
|
||||
# Known snow quality label normalisations (infonieve uses Spanish)
|
||||
_QUALITY_TRANSLATIONS: dict[str, str] = {
|
||||
"polvo": "powder",
|
||||
"nieve polvo": "powder",
|
||||
"granulada": "granular",
|
||||
"nieve granulada": "granular",
|
||||
"compacta": "compact",
|
||||
"nieve compacta": "compact",
|
||||
"helada": "icy",
|
||||
"nieve helada": "icy",
|
||||
"húmeda": "wet",
|
||||
"nieve húmeda": "wet",
|
||||
"primaveral": "spring",
|
||||
"nieve primaveral": "spring",
|
||||
"artificial": "artificial",
|
||||
"nieve artificial": "artificial",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _load_config() -> dict:
|
||||
"""Load station configuration from stations.yaml."""
|
||||
with open(_CONFIG_PATH, encoding="utf-8") as fh:
|
||||
return yaml.safe_load(fh)
|
||||
|
||||
|
||||
def _get_session() -> requests.Session:
|
||||
"""Return a requests Session with a browser-like User-Agent."""
|
||||
session = requests.Session()
|
||||
session.headers.update(
|
||||
{
|
||||
"User-Agent": _USER_AGENT,
|
||||
"Accept-Language": "es-ES,es;q=0.9,en;q=0.8",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
}
|
||||
)
|
||||
return session
|
||||
|
||||
|
||||
def _save_raw(station_id: str, payload: dict) -> None:
|
||||
"""Persist raw scraped payload to data/raw/ as JSON."""
|
||||
_RAW_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
today = date.today().isoformat()
|
||||
filename = _RAW_DATA_DIR / f"station_{station_id}_{today}.json"
|
||||
try:
|
||||
with open(filename, "w", encoding="utf-8") as fh:
|
||||
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||||
logger.debug("Raw data saved to %s", filename)
|
||||
except OSError as exc:
|
||||
logger.warning("Could not save raw data for %s: %s", station_id, exc)
|
||||
|
||||
|
||||
def _parse_float(text: Optional[str]) -> Optional[float]:
|
||||
"""Extract the first float-like value from a string, or return None."""
|
||||
if not text:
|
||||
return None
|
||||
match = re.search(r"[\d]+[.,]?[\d]*", text.replace(",", "."))
|
||||
if match:
|
||||
try:
|
||||
return float(match.group().replace(",", "."))
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _parse_int(text: Optional[str]) -> Optional[int]:
|
||||
"""Extract the first integer value from a string, or return None."""
|
||||
value = _parse_float(text)
|
||||
return int(value) if value is not None else None
|
||||
|
||||
|
||||
def _normalise_quality(raw: Optional[str]) -> Optional[str]:
|
||||
"""Normalise a Spanish snow quality label to a short English keyword."""
|
||||
if not raw:
|
||||
return None
|
||||
key = raw.strip().lower()
|
||||
return _QUALITY_TRANSLATIONS.get(key, raw.strip())
|
||||
|
||||
|
||||
def _empty_record(station_id: str) -> dict:
|
||||
"""Return a record with all operational fields set to None."""
|
||||
return {
|
||||
"station_id": station_id,
|
||||
"date": date.today().isoformat(),
|
||||
"open_status": None,
|
||||
"km_open": None,
|
||||
"lifts_open": None,
|
||||
"snow_depth": None,
|
||||
"snow_quality": None,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Infonieve parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _fetch_infonieve_page(slug: str, session: requests.Session) -> Optional[BeautifulSoup]:
|
||||
"""
|
||||
Fetch and parse the infonieve.es station page.
|
||||
|
||||
Returns a BeautifulSoup tree on success, None on any network or HTTP error.
|
||||
"""
|
||||
url = f"https://www.infonieve.es/estacion-esqui/{slug}/"
|
||||
try:
|
||||
response = session.get(url, timeout=_REQUEST_TIMEOUT)
|
||||
response.raise_for_status()
|
||||
return BeautifulSoup(response.text, "lxml")
|
||||
except requests.exceptions.Timeout:
|
||||
logger.warning("Timeout fetching infonieve page for slug '%s'", slug)
|
||||
except requests.exceptions.HTTPError as exc:
|
||||
logger.warning("HTTP error fetching infonieve page for slug '%s': %s", slug, exc)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
logger.warning("Request error fetching infonieve page for slug '%s': %s", slug, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _parse_infonieve(soup: BeautifulSoup, station_id: str) -> dict:
|
||||
"""Extract operational fields from a parsed infonieve.es page.
|
||||
|
||||
Infonieve uses a layout with keywords (Remontes, Kilómetros, Nieve)
|
||||
followed by ``<strong>value</strong>/total`` patterns. This parser
|
||||
works on the flattened page text with regex to be resilient to minor
|
||||
HTML restructuring.
|
||||
|
||||
All fields default to None when the value cannot be reliably extracted.
|
||||
"""
|
||||
record = _empty_record(station_id)
|
||||
page_text = soup.get_text(separator=" ")
|
||||
|
||||
# --- open_status ---
|
||||
# Look for <strong>Abierta</strong> or <strong>Cerrada</strong>
|
||||
status_tag = soup.find("strong", string=re.compile(r"abierta|cerrada", re.I))
|
||||
if status_tag:
|
||||
label = status_tag.get_text(strip=True).lower()
|
||||
record["open_status"] = "abierta" in label
|
||||
else:
|
||||
# Fallback: scan page text
|
||||
text_lower = page_text.lower()
|
||||
if "abierta" in text_lower:
|
||||
record["open_status"] = True
|
||||
elif "cerrada" in text_lower:
|
||||
record["open_status"] = False
|
||||
|
||||
# --- lifts_open ---
|
||||
# Pattern: "Remontes" ... <strong>N</strong>/M
|
||||
lifts_match = re.search(
|
||||
r"Remontes\s*(\d+)\s*/\s*(\d+)",
|
||||
page_text,
|
||||
re.I,
|
||||
)
|
||||
if lifts_match:
|
||||
record["lifts_open"] = int(lifts_match.group(1))
|
||||
logger.debug("Parsed lifts_open=%s (total=%s)", lifts_match.group(1), lifts_match.group(2))
|
||||
|
||||
# --- km_open ---
|
||||
# Pattern: "Kilómetros" ... <strong>N,NN</strong>/M,MM
|
||||
km_match = re.search(
|
||||
r"(?:Kil[óo]metros|Km)\s*([\d]+[.,]?\d*)\s*/\s*([\d]+[.,]?\d*)",
|
||||
page_text,
|
||||
re.I,
|
||||
)
|
||||
if km_match:
|
||||
record["km_open"] = float(km_match.group(1).replace(",", "."))
|
||||
logger.debug("Parsed km_open=%s (total=%s)", km_match.group(1), km_match.group(2))
|
||||
|
||||
# --- snow_depth ---
|
||||
# Pattern: "Nieve" ... <strong>N</strong> cm
|
||||
snow_match = re.search(
|
||||
r"Nieve\s*(\d+)\s*cm",
|
||||
page_text,
|
||||
re.I,
|
||||
)
|
||||
if snow_match:
|
||||
record["snow_depth"] = int(snow_match.group(1))
|
||||
logger.debug("Parsed snow_depth=%s cm", snow_match.group(1))
|
||||
|
||||
# --- snow_quality ---
|
||||
# Pattern: "Calidad" or "Tipo de nieve" followed by text
|
||||
quality_match = re.search(
|
||||
r"(?:calidad|tipo)\s+(?:de\s+)?(?:la\s+)?nieve[:\s]+([a-záéíóúñü]+)",
|
||||
page_text,
|
||||
re.I,
|
||||
)
|
||||
if quality_match:
|
||||
record["snow_quality"] = _normalise_quality(quality_match.group(1))
|
||||
|
||||
return record
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public scraper class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class StationScraper:
|
||||
"""
|
||||
Scrapes operational status data for the three Asturias/León ski stations.
|
||||
|
||||
Usage
|
||||
-----
|
||||
>>> scraper = StationScraper()
|
||||
>>> record = scraper.scrape_station("pajares")
|
||||
>>> all_records = scraper.scrape_all_stations()
|
||||
|
||||
The scraper attempts to collect data from infonieve.es. When a page
|
||||
cannot be fetched or parsed, it logs a warning and returns a record with
|
||||
None values so that the rest of the pipeline can continue.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
config = _load_config()
|
||||
self._stations: dict = config.get("stations", {})
|
||||
self._session: requests.Session = _get_session()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def scrape_station(self, station_id: str) -> dict:
|
||||
"""
|
||||
Scrape operational data for a single station.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
station_id:
|
||||
One of the keys defined in config/stations.yaml
|
||||
(e.g. 'pajares', 'sanisidro', 'fuentes').
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict with keys:
|
||||
station_id (str)
|
||||
date (str, ISO-8601)
|
||||
open_status (bool or None)
|
||||
km_open (float or None)
|
||||
lifts_open (int or None)
|
||||
snow_depth (int or None, centimetres)
|
||||
snow_quality(str or None)
|
||||
"""
|
||||
if station_id not in self._stations:
|
||||
logger.error(
|
||||
"Unknown station_id '%s'. Known stations: %s",
|
||||
station_id,
|
||||
list(self._stations.keys()),
|
||||
)
|
||||
return _empty_record(station_id)
|
||||
|
||||
logger.info("Scraping station: %s", station_id)
|
||||
record = self._scrape_infonieve(station_id)
|
||||
_save_raw(station_id, record)
|
||||
return record
|
||||
|
||||
def scrape_all_stations(self) -> list[dict]:
|
||||
"""
|
||||
Scrape operational data for all stations defined in stations.yaml.
|
||||
|
||||
Returns
|
||||
-------
|
||||
List of dicts, one per station, in the same format as scrape_station().
|
||||
"""
|
||||
results = []
|
||||
for station_id in self._stations:
|
||||
record = self.scrape_station(station_id)
|
||||
results.append(record)
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal scraping logic
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _scrape_infonieve(self, station_id: str) -> dict:
|
||||
"""
|
||||
Attempt to scrape from infonieve.es and return an operational record.
|
||||
|
||||
Falls back to an empty record (all fields None) when the page cannot
|
||||
be fetched or the content does not match expected patterns.
|
||||
"""
|
||||
slug = _INFONIEVE_SLUGS.get(station_id)
|
||||
if slug is None:
|
||||
logger.warning(
|
||||
"No infonieve.es slug configured for station '%s'. "
|
||||
"Returning empty record.",
|
||||
station_id,
|
||||
)
|
||||
return _empty_record(station_id)
|
||||
|
||||
soup = _fetch_infonieve_page(slug, self._session)
|
||||
if soup is None:
|
||||
logger.warning(
|
||||
"Could not fetch infonieve.es page for '%s' (slug: '%s'). "
|
||||
"All fields will be None. Check network connectivity or "
|
||||
"whether the URL has changed.",
|
||||
station_id,
|
||||
slug,
|
||||
)
|
||||
return _empty_record(station_id)
|
||||
|
||||
try:
|
||||
record = _parse_infonieve(soup, station_id)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.warning(
|
||||
"Unexpected error parsing infonieve.es page for '%s': %s. "
|
||||
"Returning empty record.",
|
||||
station_id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
return _empty_record(station_id)
|
||||
|
||||
self._log_record_summary(record)
|
||||
return record
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Utilities
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _log_record_summary(record: dict) -> None:
|
||||
"""Emit a one-line summary of the scraped record at INFO level."""
|
||||
status_label = (
|
||||
"OPEN" if record["open_status"] is True
|
||||
else "CLOSED" if record["open_status"] is False
|
||||
else "UNKNOWN"
|
||||
)
|
||||
logger.info(
|
||||
"[%s] %s | km=%-5s lifts=%-3s depth=%-4s quality=%s",
|
||||
record["station_id"],
|
||||
status_label,
|
||||
record["km_open"],
|
||||
record["lifts_open"],
|
||||
record["snow_depth"],
|
||||
record["snow_quality"],
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI entry-point (for manual testing / cron scripts)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
|
||||
)
|
||||
scraper = StationScraper()
|
||||
records = scraper.scrape_all_stations()
|
||||
print(json.dumps(records, indent=2, ensure_ascii=False))
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Weather data collector using Open-Meteo API.
|
||||
|
||||
Fetches historical and forecast weather data for ski stations
|
||||
defined in config/stations.yaml. No API key required.
|
||||
|
||||
Historical endpoint: https://archive-api.open-meteo.com/v1/archive
|
||||
Forecast endpoint: https://api.open-meteo.com/v1/forecast
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import requests
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
|
||||
RAW_DATA_DIR = BASE_DIR / "data" / "raw"
|
||||
|
||||
HISTORICAL_URL = "https://archive-api.open-meteo.com/v1/archive"
|
||||
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"
|
||||
|
||||
# Variables requested from Open-Meteo for both endpoints.
|
||||
DAILY_VARIABLES = [
|
||||
"temperature_2m_max",
|
||||
"temperature_2m_min",
|
||||
"temperature_2m_mean",
|
||||
"precipitation_sum",
|
||||
"snowfall_sum",
|
||||
"wind_speed_10m_max",
|
||||
"wind_gusts_10m_max",
|
||||
"wind_direction_10m_dominant",
|
||||
"relative_humidity_2m_mean",
|
||||
"surface_pressure_mean",
|
||||
]
|
||||
|
||||
MAX_RETRIES = 6
|
||||
RETRY_BACKOFF = 2 # seconds between retries
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# WeatherCollector
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WeatherCollector:
|
||||
"""Fetches and persists weather data from Open-Meteo for ski stations.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
config_path:
|
||||
Path to the stations YAML config file. Defaults to
|
||||
``config/stations.yaml`` relative to the project root.
|
||||
"""
|
||||
|
||||
def __init__(self, config_path: Path = CONFIG_PATH) -> None:
|
||||
self.config_path = config_path
|
||||
self.stations = self._load_stations()
|
||||
RAW_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_historical(
|
||||
self,
|
||||
station_id: str,
|
||||
lat: float,
|
||||
lon: float,
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
) -> pd.DataFrame:
|
||||
"""Fetch historical daily weather for a station.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
station_id:
|
||||
Identifier used in output filenames and the ``station_id`` column.
|
||||
lat:
|
||||
Latitude of the station.
|
||||
lon:
|
||||
Longitude of the station.
|
||||
start_date:
|
||||
Inclusive start date in ``YYYY-MM-DD`` format.
|
||||
end_date:
|
||||
Inclusive end date in ``YYYY-MM-DD`` format.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pandas.DataFrame
|
||||
Columns: date, temperature_2m_max, temperature_2m_min,
|
||||
temperature_2m_mean, precipitation_sum, snowfall_sum,
|
||||
wind_speed_10m_max, wind_gusts_10m_max,
|
||||
wind_direction_10m_dominant, relative_humidity_2m_mean,
|
||||
surface_pressure_mean, station_id.
|
||||
|
||||
Raises
|
||||
------
|
||||
RuntimeError
|
||||
If the API request fails after all retries.
|
||||
"""
|
||||
logger.info(
|
||||
"Fetching historical weather for station=%s (%s to %s)",
|
||||
station_id,
|
||||
start_date,
|
||||
end_date,
|
||||
)
|
||||
|
||||
params = {
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"daily": ",".join(DAILY_VARIABLES),
|
||||
"timezone": "Europe/Madrid",
|
||||
}
|
||||
|
||||
raw = self._request(HISTORICAL_URL, params)
|
||||
df = self._parse_response(raw, station_id)
|
||||
|
||||
self._save(df, station_id)
|
||||
return df
|
||||
|
||||
def get_forecast(
|
||||
self,
|
||||
station_id: str,
|
||||
lat: float,
|
||||
lon: float,
|
||||
) -> pd.DataFrame:
|
||||
"""Fetch 7-day daily weather forecast for a station.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
station_id:
|
||||
Identifier used in output filenames and the ``station_id`` column.
|
||||
lat:
|
||||
Latitude of the station.
|
||||
lon:
|
||||
Longitude of the station.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pandas.DataFrame
|
||||
Same columns as :meth:`get_historical`.
|
||||
|
||||
Raises
|
||||
------
|
||||
RuntimeError
|
||||
If the API request fails after all retries.
|
||||
"""
|
||||
logger.info("Fetching 7-day forecast for station=%s", station_id)
|
||||
|
||||
params = {
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"forecast_days": 7,
|
||||
"daily": ",".join(DAILY_VARIABLES),
|
||||
"timezone": "Europe/Madrid",
|
||||
}
|
||||
|
||||
raw = self._request(FORECAST_URL, params)
|
||||
df = self._parse_response(raw, station_id)
|
||||
|
||||
self._save(df, station_id)
|
||||
return df
|
||||
|
||||
def collect_all_stations(
|
||||
self,
|
||||
start_date: str | None = None,
|
||||
end_date: str | None = None,
|
||||
include_forecast: bool = True,
|
||||
) -> dict[str, pd.DataFrame]:
|
||||
"""Collect weather data for every station in the config.
|
||||
|
||||
Fetches historical data when ``start_date`` / ``end_date`` are
|
||||
provided, and optionally the 7-day forecast.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
start_date:
|
||||
Inclusive start date (``YYYY-MM-DD``) for historical collection.
|
||||
Defaults to 365 days before today.
|
||||
end_date:
|
||||
Inclusive end date (``YYYY-MM-DD``) for historical collection.
|
||||
Defaults to yesterday.
|
||||
include_forecast:
|
||||
Whether to also fetch the 7-day forecast. Defaults to ``True``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, pandas.DataFrame]
|
||||
Mapping of station_id to a combined DataFrame (historical + forecast
|
||||
when ``include_forecast`` is True, otherwise historical only).
|
||||
"""
|
||||
if start_date is None:
|
||||
start_date = (date.today() - timedelta(days=365)).strftime("%Y-%m-%d")
|
||||
if end_date is None:
|
||||
end_date = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
results: dict[str, pd.DataFrame] = {}
|
||||
|
||||
for station_id, cfg in self.stations.items():
|
||||
lat = cfg["latitude"]
|
||||
lon = cfg["longitude"]
|
||||
frames: list[pd.DataFrame] = []
|
||||
|
||||
try:
|
||||
hist_df = self.get_historical(station_id, lat, lon, start_date, end_date)
|
||||
frames.append(hist_df)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Historical fetch failed for station=%s: %s", station_id, exc)
|
||||
|
||||
if include_forecast:
|
||||
try:
|
||||
forecast_df = self.get_forecast(station_id, lat, lon)
|
||||
frames.append(forecast_df)
|
||||
except RuntimeError as exc:
|
||||
logger.error("Forecast fetch failed for station=%s: %s", station_id, exc)
|
||||
|
||||
if frames:
|
||||
combined = pd.concat(frames, ignore_index=True)
|
||||
combined.drop_duplicates(subset=["date", "station_id"], inplace=True)
|
||||
combined.sort_values("date", inplace=True)
|
||||
results[station_id] = combined
|
||||
|
||||
logger.info("collect_all_stations complete. Stations collected: %s", list(results.keys()))
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_stations(self) -> dict:
|
||||
"""Load station configuration from YAML."""
|
||||
with open(self.config_path, "r", encoding="utf-8") as fh:
|
||||
config = yaml.safe_load(fh)
|
||||
return config.get("stations", {})
|
||||
|
||||
def _request(self, url: str, params: dict) -> dict:
|
||||
"""Send a GET request with retry logic.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
url:
|
||||
API endpoint URL.
|
||||
params:
|
||||
Query parameters to include in the request.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Parsed JSON response body.
|
||||
|
||||
Raises
|
||||
------
|
||||
RuntimeError
|
||||
If all retries are exhausted or a non-retryable error occurs.
|
||||
"""
|
||||
last_exc: Exception | None = None
|
||||
|
||||
for attempt in range(1, MAX_RETRIES + 1):
|
||||
try:
|
||||
response = requests.get(url, params=params, timeout=30)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.exceptions.HTTPError as exc:
|
||||
status = exc.response.status_code if exc.response is not None else None
|
||||
# 429 Too Many Requests is retryable with a longer back-off
|
||||
if status == 429:
|
||||
wait = RETRY_BACKOFF * attempt * 10
|
||||
logger.warning(
|
||||
"Rate-limited (429) on attempt %d/%d. Waiting %ds before retry.",
|
||||
attempt, MAX_RETRIES, wait,
|
||||
)
|
||||
last_exc = exc
|
||||
time.sleep(wait)
|
||||
continue
|
||||
# Other 4xx errors are not retryable
|
||||
if status is not None and 400 <= status < 500:
|
||||
raise RuntimeError(
|
||||
f"Client error {status} from {url}: {exc}"
|
||||
) from exc
|
||||
last_exc = exc
|
||||
logger.warning("Attempt %d/%d failed: %s", attempt, MAX_RETRIES, exc)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
last_exc = exc
|
||||
logger.warning("Attempt %d/%d failed: %s", attempt, MAX_RETRIES, exc)
|
||||
|
||||
if attempt < MAX_RETRIES:
|
||||
time.sleep(RETRY_BACKOFF * attempt)
|
||||
|
||||
raise RuntimeError(
|
||||
f"All {MAX_RETRIES} attempts failed for {url}. Last error: {last_exc}"
|
||||
)
|
||||
|
||||
def _parse_response(self, raw: dict, station_id: str) -> pd.DataFrame:
|
||||
"""Convert an Open-Meteo daily response dict into a DataFrame.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
raw:
|
||||
Parsed JSON response from the API.
|
||||
station_id:
|
||||
Station identifier to add as a column.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pandas.DataFrame
|
||||
"""
|
||||
daily = raw.get("daily", {})
|
||||
|
||||
if not daily:
|
||||
logger.warning("Empty daily data in response for station=%s", station_id)
|
||||
return pd.DataFrame(
|
||||
columns=["date"] + DAILY_VARIABLES + ["station_id"]
|
||||
)
|
||||
|
||||
df = pd.DataFrame(daily)
|
||||
df.rename(columns={"time": "date"}, inplace=True)
|
||||
df["date"] = pd.to_datetime(df["date"]).dt.date
|
||||
df["station_id"] = station_id
|
||||
|
||||
# Ensure all expected columns are present
|
||||
for col in DAILY_VARIABLES:
|
||||
if col not in df.columns:
|
||||
logger.warning("Column %s missing in API response for station=%s", col, station_id)
|
||||
df[col] = None
|
||||
|
||||
# Keep only the expected column order
|
||||
columns = ["date"] + DAILY_VARIABLES + ["station_id"]
|
||||
return df[columns]
|
||||
|
||||
def _save(self, df: pd.DataFrame, station_id: str) -> None:
|
||||
"""Persist a weather DataFrame to a CSV file.
|
||||
|
||||
Filename format: ``weather_{station_id}_{date}.csv``
|
||||
where ``{date}`` is today's date (the collection date).
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df:
|
||||
DataFrame to save.
|
||||
station_id:
|
||||
Station identifier used in the filename.
|
||||
"""
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
filename = RAW_DATA_DIR / f"weather_{station_id}_{today}.csv"
|
||||
df.to_csv(filename, index=False)
|
||||
logger.info("Saved weather data to %s", filename)
|
||||
@@ -0,0 +1,355 @@
|
||||
"""Webcam snapshot collector for ski station crowd analysis.
|
||||
|
||||
Downloads the latest JPEG snapshot from each station's public webcam feeds
|
||||
and persists them to ``data/raw/webcams/``. The collector supports two URL
|
||||
strategies:
|
||||
|
||||
* **Static URL** – the remote server overwrites the same file in-place on
|
||||
every camera refresh cycle (e.g. nieveleonsanisidro.com, fuentesdeinvierno.com).
|
||||
The configured URL is used directly.
|
||||
|
||||
* **Page-scraped URL** – the remote page embeds a timestamped filename for
|
||||
the current snapshot (e.g. infonieve.es/webcams/pajares-cuitu_<ts>.jpg).
|
||||
The collector fetches the HTML of ``primary_webcam_page`` and extracts
|
||||
the first ``/webcams/*.jpg`` URL it finds.
|
||||
|
||||
URL configuration lives in ``config/stations.yaml`` under
|
||||
``stations.<id>.webcams``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
CONFIG_PATH = BASE_DIR / "config" / "stations.yaml"
|
||||
WEBCAM_DIR = BASE_DIR / "data" / "raw" / "webcams"
|
||||
|
||||
# HTTP settings
|
||||
REQUEST_TIMEOUT = 20 # seconds
|
||||
MAX_RETRIES = 3
|
||||
RETRY_BACKOFF = 2 # seconds between retries
|
||||
|
||||
# Minimum acceptable image size – smaller responses are treated as errors.
|
||||
MIN_IMAGE_BYTES = 5_000
|
||||
|
||||
# User-agent that avoids bot-blocking on some servers.
|
||||
_USER_AGENT = (
|
||||
"Mozilla/5.0 (X11; Linux x86_64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/122.0 Safari/537.36"
|
||||
)
|
||||
|
||||
_HEADERS = {"User-Agent": _USER_AGENT}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# WebcamCollector
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WebcamCollector:
|
||||
"""Downloads and saves the latest webcam snapshots for each ski station.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
config_path:
|
||||
Path to the stations YAML configuration file. Defaults to
|
||||
``config/stations.yaml`` relative to the project root.
|
||||
output_dir:
|
||||
Directory where captured images are saved. Created automatically
|
||||
if it does not exist. Defaults to ``data/raw/webcams/``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_path: Path = CONFIG_PATH,
|
||||
output_dir: Path = WEBCAM_DIR,
|
||||
) -> None:
|
||||
self.config_path = config_path
|
||||
self.output_dir = output_dir
|
||||
self.stations = self._load_stations()
|
||||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def capture(self, station_id: str) -> list[str]:
|
||||
"""Download the latest snapshot(s) for *station_id*.
|
||||
|
||||
Iterates over all configured snapshot entries for the station and
|
||||
attempts to download each one. Failed downloads are logged and
|
||||
skipped; at least one successful download is not guaranteed (webcams
|
||||
are frequently offline).
|
||||
|
||||
Parameters
|
||||
----------
|
||||
station_id:
|
||||
Must match a key in ``config/stations.yaml`` (e.g. ``"pajares"``).
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[str]
|
||||
Absolute paths to successfully saved image files. Empty list if
|
||||
all downloads failed or the station has no webcam configuration.
|
||||
"""
|
||||
if station_id not in self.stations:
|
||||
logger.error("Unknown station_id=%s", station_id)
|
||||
return []
|
||||
|
||||
station_cfg = self.stations[station_id]
|
||||
webcam_cfg = station_cfg.get("webcams")
|
||||
if not webcam_cfg:
|
||||
logger.warning("No webcam config for station_id=%s", station_id)
|
||||
return []
|
||||
|
||||
snapshots = webcam_cfg.get("snapshots", [])
|
||||
if not snapshots:
|
||||
logger.warning("No snapshots configured for station_id=%s", station_id)
|
||||
return []
|
||||
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
saved_paths: list[str] = []
|
||||
|
||||
for idx, snap in enumerate(snapshots):
|
||||
label = snap.get("label", f"cam{idx}")
|
||||
ssl_verify: bool = snap.get("ssl_verify", True)
|
||||
|
||||
# Resolve the actual download URL for this snapshot entry.
|
||||
url = self._resolve_snapshot_url(snap, webcam_cfg, station_id)
|
||||
if not url:
|
||||
logger.warning(
|
||||
"Could not resolve URL for station=%s label=%s", station_id, label
|
||||
)
|
||||
continue
|
||||
|
||||
# Sanitise label for use as a filename component.
|
||||
safe_label = re.sub(r"[^a-zA-Z0-9_-]", "_", label).strip("_").lower()
|
||||
filename = self.output_dir / f"{station_id}_{safe_label}_{timestamp}.jpg"
|
||||
|
||||
path = self._download_image(url, filename, ssl_verify=ssl_verify)
|
||||
if path:
|
||||
saved_paths.append(path)
|
||||
|
||||
if saved_paths:
|
||||
logger.info(
|
||||
"Captured %d image(s) for station=%s", len(saved_paths), station_id
|
||||
)
|
||||
else:
|
||||
logger.warning("No images captured for station=%s", station_id)
|
||||
|
||||
return saved_paths
|
||||
|
||||
def capture_all(self) -> dict[str, list[str]]:
|
||||
"""Capture snapshots for every configured station.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, list[str]]
|
||||
Mapping of station_id to the list of saved image paths for that
|
||||
station. Stations with no successful captures map to an empty list.
|
||||
"""
|
||||
results: dict[str, list[str]] = {}
|
||||
for station_id in self.stations:
|
||||
results[station_id] = self.capture(station_id)
|
||||
logger.info(
|
||||
"capture_all complete. Stations: %s",
|
||||
{k: len(v) for k, v in results.items()},
|
||||
)
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_stations(self) -> dict[str, Any]:
|
||||
"""Load station configuration from YAML."""
|
||||
with open(self.config_path, "r", encoding="utf-8") as fh:
|
||||
config = yaml.safe_load(fh)
|
||||
return config.get("stations", {})
|
||||
|
||||
def _resolve_snapshot_url(
|
||||
self,
|
||||
snap: dict[str, Any],
|
||||
webcam_cfg: dict[str, Any],
|
||||
station_id: str,
|
||||
) -> str | None:
|
||||
"""Return the concrete download URL for a snapshot entry.
|
||||
|
||||
For static entries the ``url`` field is returned directly. For
|
||||
timestamped entries the current URL is scraped from the station's
|
||||
webcam page on infonieve.es.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
snap:
|
||||
A single entry from the ``snapshots`` list in the YAML config.
|
||||
webcam_cfg:
|
||||
The ``webcams`` dict for the station (contains ``primary_webcam_page``).
|
||||
station_id:
|
||||
Used for log messages only.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str | None
|
||||
Resolved URL, or ``None`` if resolution failed.
|
||||
"""
|
||||
if snap.get("static", True):
|
||||
return snap.get("url")
|
||||
|
||||
# Dynamic / timestamped strategy: scrape the page.
|
||||
page_url = webcam_cfg.get("primary_webcam_page")
|
||||
if not page_url:
|
||||
logger.warning("No primary_webcam_page for station=%s", station_id)
|
||||
return None
|
||||
|
||||
return self._scrape_first_webcam_url(page_url, station_id)
|
||||
|
||||
def _scrape_first_webcam_url(
|
||||
self, page_url: str, station_id: str
|
||||
) -> str | None:
|
||||
"""Scrape the infonieve.es webcam page and return the first snapshot URL.
|
||||
|
||||
infonieve.es embeds timestamped filenames such as:
|
||||
``https://www.infonieve.es/webcams/pajares-cuitu_2026-03-12-13-01-602.jpg``
|
||||
|
||||
Parameters
|
||||
----------
|
||||
page_url:
|
||||
URL of the infonieve.es webcam listing page.
|
||||
station_id:
|
||||
Used for log messages only.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str | None
|
||||
First absolute JPEG URL found, or ``None`` on failure.
|
||||
"""
|
||||
try:
|
||||
resp = requests.get(
|
||||
page_url,
|
||||
headers=_HEADERS,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except requests.RequestException as exc:
|
||||
logger.warning(
|
||||
"Failed to fetch webcam page for station=%s: %s", station_id, exc
|
||||
)
|
||||
return None
|
||||
|
||||
# Match the first direct JPEG image under /webcams/ path.
|
||||
match = re.search(
|
||||
r'https://www\.infonieve\.es/webcams/[^\s"\'<>)]+\.jpg',
|
||||
resp.text,
|
||||
)
|
||||
if not match:
|
||||
logger.warning(
|
||||
"No /webcams/*.jpg URL found on page %s for station=%s",
|
||||
page_url,
|
||||
station_id,
|
||||
)
|
||||
return None
|
||||
|
||||
url = match.group(0)
|
||||
logger.debug("Resolved webcam URL for station=%s: %s", station_id, url)
|
||||
return url
|
||||
|
||||
def _download_image(
|
||||
self,
|
||||
url: str,
|
||||
dest: Path,
|
||||
ssl_verify: bool = True,
|
||||
) -> str | None:
|
||||
"""Download a JPEG from *url* and write it to *dest*.
|
||||
|
||||
Implements a simple retry loop with exponential back-off.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
url:
|
||||
Direct image URL.
|
||||
dest:
|
||||
Destination file path.
|
||||
ssl_verify:
|
||||
Whether to verify the server's TLS certificate. Set to
|
||||
``False`` for servers with self-signed certificates (e.g.
|
||||
fuentesdeinvierno.com).
|
||||
|
||||
Returns
|
||||
-------
|
||||
str | None
|
||||
Absolute path to the saved file, or ``None`` on failure.
|
||||
"""
|
||||
last_exc: Exception | None = None
|
||||
|
||||
for attempt in range(1, MAX_RETRIES + 1):
|
||||
try:
|
||||
resp = requests.get(
|
||||
url,
|
||||
headers=_HEADERS,
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
verify=ssl_verify,
|
||||
stream=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
content = resp.content
|
||||
if len(content) < MIN_IMAGE_BYTES:
|
||||
logger.warning(
|
||||
"Image too small (%d bytes) from %s, skipping",
|
||||
len(content),
|
||||
url,
|
||||
)
|
||||
return None
|
||||
|
||||
dest.write_bytes(content)
|
||||
logger.info("Saved webcam image to %s (%d bytes)", dest, len(content))
|
||||
return str(dest)
|
||||
|
||||
except requests.exceptions.SSLError as exc:
|
||||
# Non-retryable if ssl_verify=True was intentional.
|
||||
logger.error("SSL error downloading %s: %s", url, exc)
|
||||
return None
|
||||
|
||||
except requests.exceptions.HTTPError as exc:
|
||||
if exc.response is not None and 400 <= exc.response.status_code < 500:
|
||||
logger.error(
|
||||
"Client error %d downloading %s",
|
||||
exc.response.status_code,
|
||||
url,
|
||||
)
|
||||
return None
|
||||
last_exc = exc
|
||||
|
||||
except requests.exceptions.RequestException as exc:
|
||||
last_exc = exc
|
||||
|
||||
logger.warning(
|
||||
"Download attempt %d/%d failed for %s: %s",
|
||||
attempt,
|
||||
MAX_RETRIES,
|
||||
url,
|
||||
last_exc,
|
||||
)
|
||||
if attempt < MAX_RETRIES:
|
||||
time.sleep(RETRY_BACKOFF * attempt)
|
||||
|
||||
logger.error(
|
||||
"All %d download attempts failed for %s. Last error: %s",
|
||||
MAX_RETRIES,
|
||||
url,
|
||||
last_exc,
|
||||
)
|
||||
return None
|
||||
@@ -0,0 +1,7 @@
|
||||
"""ML package for ski predictor.
|
||||
|
||||
Modules:
|
||||
train_model: Trains RandomForest, GradientBoosting, and LightGBM models
|
||||
for station_open, km_open, and crowd_level targets.
|
||||
evaluate_model: Evaluates trained models and produces a JSON report.
|
||||
"""
|
||||
@@ -0,0 +1,384 @@
|
||||
"""Evaluate trained ski-condition prediction models.
|
||||
|
||||
Loads each model from ml/models/, runs evaluation on a held-out test split
|
||||
of the processed feature dataset, computes task-appropriate metrics, and
|
||||
writes a JSON report to ml/models/evaluation_report.json.
|
||||
|
||||
Classification metrics: accuracy, precision, recall, F1 (macro), AUC.
|
||||
Regression metrics: MAE, RMSE, R2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.metrics import (
|
||||
accuracy_score,
|
||||
f1_score,
|
||||
mean_absolute_error,
|
||||
precision_score,
|
||||
r2_score,
|
||||
recall_score,
|
||||
roc_auc_score,
|
||||
)
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
DATASET_PATH = _REPO_ROOT / "data" / "processed" / "dataset_featured.csv"
|
||||
MODELS_DIR = _REPO_ROOT / "ml" / "models"
|
||||
REPORT_PATH = MODELS_DIR / "evaluation_report.json"
|
||||
|
||||
# Test split fraction. With a small dataset 20 % gives at least a handful of
|
||||
# samples per class while keeping enough for stratification.
|
||||
TEST_SIZE = 0.20
|
||||
RANDOM_STATE = 42
|
||||
|
||||
# Targets and their task types
|
||||
TARGETS: dict[str, str] = {
|
||||
"station_open": "binary",
|
||||
"km_open": "regression",
|
||||
"crowd_level": "multiclass",
|
||||
}
|
||||
|
||||
# Ordered crowd-level labels – must match what ModelTrainer used
|
||||
CROWD_LEVEL_LABELS = ["low", "medium", "high"]
|
||||
|
||||
|
||||
class ModelEvaluator:
|
||||
"""Evaluate persisted ski-condition models against a held-out test set.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
dataset_path:
|
||||
Path to the processed feature CSV.
|
||||
models_dir:
|
||||
Directory containing the trained ``.joblib`` model files.
|
||||
test_size:
|
||||
Fraction of the dataset to use as the test set.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset_path: Path | str = DATASET_PATH,
|
||||
models_dir: Path | str = MODELS_DIR,
|
||||
test_size: float = TEST_SIZE,
|
||||
) -> None:
|
||||
self.dataset_path = Path(dataset_path)
|
||||
self.models_dir = Path(models_dir)
|
||||
self.test_size = test_size
|
||||
|
||||
self._df: pd.DataFrame | None = None
|
||||
self._feature_columns: list[str] = []
|
||||
self._models: dict[str, Any] = {}
|
||||
self._label_encoder: LabelEncoder | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def evaluate_all(self) -> dict[str, dict[str, float]]:
|
||||
"""Evaluate all trained models and persist a JSON report.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
``{target_name: {metric_name: value, ...}}``
|
||||
|
||||
Side effects
|
||||
------------
|
||||
Writes ``ml/models/evaluation_report.json``.
|
||||
"""
|
||||
self._load_dataset()
|
||||
self._load_models()
|
||||
|
||||
report: dict[str, Any] = {}
|
||||
for target, task_type in TARGETS.items():
|
||||
if target not in self._models:
|
||||
logger.warning(
|
||||
"No model found for target '%s'; skipping evaluation.",
|
||||
target,
|
||||
)
|
||||
continue
|
||||
|
||||
logger.info("Evaluating model for target: %s", target)
|
||||
metrics = self._evaluate_single(target, task_type)
|
||||
report[target] = metrics
|
||||
logger.info("Metrics for %s: %s", target, metrics)
|
||||
|
||||
self._save_report(report)
|
||||
return report
|
||||
|
||||
def get_feature_importance(self, model_name: str) -> list[tuple[str, float]]:
|
||||
"""Return feature importances for a trained model, sorted descending.
|
||||
|
||||
This method reads the pre-computed importance JSON written by
|
||||
``ModelTrainer`` rather than recomputing from the model, so the
|
||||
trainer must have been run first.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
model_name:
|
||||
One of ``station_open``, ``km_open``, or ``crowd_level``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list of (feature_name, importance) tuples sorted by importance descending.
|
||||
|
||||
Raises
|
||||
------
|
||||
FileNotFoundError
|
||||
If the corresponding JSON importance file does not exist.
|
||||
ValueError
|
||||
If *model_name* is not a recognised target.
|
||||
"""
|
||||
if model_name not in TARGETS:
|
||||
raise ValueError(
|
||||
f"Unknown model name '{model_name}'. "
|
||||
f"Valid names: {list(TARGETS.keys())}"
|
||||
)
|
||||
|
||||
importance_path = self.models_dir / f"{model_name}_feature_importances.json"
|
||||
if not importance_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Feature importance file not found: {importance_path}. "
|
||||
"Run train_model.py first."
|
||||
)
|
||||
|
||||
with open(importance_path, encoding="utf-8") as fh:
|
||||
raw: dict[str, float] = json.load(fh)
|
||||
|
||||
sorted_importances = sorted(raw.items(), key=lambda kv: kv[1], reverse=True)
|
||||
return sorted_importances
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_dataset(self) -> None:
|
||||
"""Load the processed dataset and derive feature column names."""
|
||||
if not self.dataset_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Processed dataset not found at {self.dataset_path}. "
|
||||
"Run the pipeline first."
|
||||
)
|
||||
|
||||
logger.info("Loading dataset from %s", self.dataset_path)
|
||||
self._df = pd.read_csv(self.dataset_path, parse_dates=["date"])
|
||||
|
||||
non_feature_cols = set(TARGETS.keys()) | {"date", "station"}
|
||||
self._feature_columns = [
|
||||
col for col in self._df.columns if col not in non_feature_cols
|
||||
]
|
||||
logger.info(
|
||||
"Dataset loaded: %d rows, %d features",
|
||||
len(self._df),
|
||||
len(self._feature_columns),
|
||||
)
|
||||
|
||||
def _load_models(self) -> None:
|
||||
"""Load all model files found in models_dir."""
|
||||
for target in TARGETS:
|
||||
model_path = self.models_dir / f"{target}_model.joblib"
|
||||
if model_path.exists():
|
||||
self._models[target] = joblib.load(model_path)
|
||||
logger.info("Loaded model: %s", model_path.name)
|
||||
else:
|
||||
logger.warning("Model file not found: %s", model_path)
|
||||
|
||||
# Load the label encoder for crowd_level if available
|
||||
encoder_path = self.models_dir / "crowd_level_label_encoder.joblib"
|
||||
if encoder_path.exists():
|
||||
self._label_encoder = joblib.load(encoder_path)
|
||||
logger.info("Loaded crowd_level LabelEncoder.")
|
||||
else:
|
||||
logger.warning(
|
||||
"crowd_level_label_encoder.joblib not found; "
|
||||
"crowd_level evaluation may fail."
|
||||
)
|
||||
|
||||
def _prepare_test_split(
|
||||
self, target: str
|
||||
) -> tuple[pd.DataFrame, np.ndarray]:
|
||||
"""Return (X_test, y_test) for a given target using a fixed split.
|
||||
|
||||
The split is deterministic via ``RANDOM_STATE`` so repeated calls
|
||||
for different targets use the same test rows.
|
||||
"""
|
||||
assert self._df is not None
|
||||
|
||||
df = self._df.dropna(subset=[target]).copy()
|
||||
if len(df) < 5:
|
||||
raise RuntimeError(
|
||||
f"Too few non-null rows ({len(df)}) for target '{target}' "
|
||||
"to create a meaningful train/test split."
|
||||
)
|
||||
|
||||
X = df[self._feature_columns].fillna(
|
||||
df[self._feature_columns].median(numeric_only=True)
|
||||
)
|
||||
|
||||
if target == "crowd_level":
|
||||
if self._label_encoder is None:
|
||||
le = LabelEncoder()
|
||||
le.fit(CROWD_LEVEL_LABELS)
|
||||
self._label_encoder = le
|
||||
y_encoded = self._label_encoder.transform(
|
||||
df[target].astype(str)
|
||||
)
|
||||
y = y_encoded
|
||||
stratify = y
|
||||
else:
|
||||
y = df[target].values
|
||||
stratify = y if target == "station_open" else None
|
||||
|
||||
_, X_test, _, y_test = train_test_split(
|
||||
X,
|
||||
y,
|
||||
test_size=self.test_size,
|
||||
random_state=RANDOM_STATE,
|
||||
stratify=stratify,
|
||||
)
|
||||
return X_test, y_test
|
||||
|
||||
def _evaluate_single(
|
||||
self, target: str, task_type: str
|
||||
) -> dict[str, float]:
|
||||
"""Compute evaluation metrics for one model on the test split."""
|
||||
model = self._models[target]
|
||||
X_test, y_test = self._prepare_test_split(target)
|
||||
y_pred = model.predict(X_test)
|
||||
|
||||
if task_type == "binary":
|
||||
metrics = self._classification_metrics(
|
||||
model, X_test, y_test, y_pred, multiclass=False
|
||||
)
|
||||
elif task_type == "multiclass":
|
||||
metrics = self._classification_metrics(
|
||||
model, X_test, y_test, y_pred, multiclass=True
|
||||
)
|
||||
else:
|
||||
metrics = self._regression_metrics(y_test, y_pred)
|
||||
|
||||
metrics["n_test_samples"] = int(len(y_test))
|
||||
return metrics
|
||||
|
||||
@staticmethod
|
||||
def _classification_metrics(
|
||||
model: Any,
|
||||
X_test: pd.DataFrame,
|
||||
y_test: np.ndarray,
|
||||
y_pred: np.ndarray,
|
||||
*,
|
||||
multiclass: bool,
|
||||
) -> dict[str, float]:
|
||||
"""Compute accuracy, precision, recall, F1, and AUC."""
|
||||
average = "macro" if multiclass else "binary"
|
||||
|
||||
metrics: dict[str, float] = {
|
||||
"accuracy": round(float(accuracy_score(y_test, y_pred)), 4),
|
||||
"precision": round(
|
||||
float(precision_score(y_test, y_pred, average=average, zero_division=0)),
|
||||
4,
|
||||
),
|
||||
"recall": round(
|
||||
float(recall_score(y_test, y_pred, average=average, zero_division=0)),
|
||||
4,
|
||||
),
|
||||
"f1": round(
|
||||
float(f1_score(y_test, y_pred, average=average, zero_division=0)),
|
||||
4,
|
||||
),
|
||||
}
|
||||
|
||||
# AUC requires probability estimates
|
||||
try:
|
||||
if hasattr(model, "predict_proba"):
|
||||
y_proba = model.predict_proba(X_test)
|
||||
if multiclass:
|
||||
auc = roc_auc_score(
|
||||
y_test, y_proba, multi_class="ovr", average="weighted"
|
||||
)
|
||||
else:
|
||||
auc = roc_auc_score(y_test, y_proba[:, 1])
|
||||
metrics["auc"] = round(float(auc), 4)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Could not compute AUC for model: %s", exc)
|
||||
|
||||
return metrics
|
||||
|
||||
@staticmethod
|
||||
def _regression_metrics(
|
||||
y_test: np.ndarray, y_pred: np.ndarray
|
||||
) -> dict[str, float]:
|
||||
"""Compute MAE, RMSE, and R2."""
|
||||
mae = mean_absolute_error(y_test, y_pred)
|
||||
rmse = float(np.sqrt(mean_squared_error_compat(y_test, y_pred)))
|
||||
r2 = r2_score(y_test, y_pred)
|
||||
|
||||
return {
|
||||
"mae": round(float(mae), 4),
|
||||
"rmse": round(rmse, 4),
|
||||
"r2": round(float(r2), 4),
|
||||
}
|
||||
|
||||
def _save_report(self, report: dict[str, Any]) -> None:
|
||||
"""Write the evaluation report to disk as JSON."""
|
||||
self.models_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(REPORT_PATH, "w", encoding="utf-8") as fh:
|
||||
json.dump(report, fh, indent=2)
|
||||
logger.info("Evaluation report saved to %s", REPORT_PATH)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compatibility shim: sklearn removed mean_squared_error's squared kwarg
|
||||
# in 1.4 and added root_mean_squared_error in 1.4.
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
from sklearn.metrics import root_mean_squared_error as _rmse_fn
|
||||
|
||||
def mean_squared_error_compat(y_true: np.ndarray, y_pred: np.ndarray) -> float:
|
||||
"""Return RMSE using the sklearn API available in the environment."""
|
||||
return float(_rmse_fn(y_true, y_pred))
|
||||
|
||||
except ImportError:
|
||||
from sklearn.metrics import mean_squared_error as _mse_fn # type: ignore[assignment]
|
||||
|
||||
def mean_squared_error_compat(y_true: np.ndarray, y_pred: np.ndarray) -> float: # type: ignore[misc]
|
||||
"""Return RMSE using the sklearn API available in the environment."""
|
||||
return float(np.sqrt(_mse_fn(y_true, y_pred)))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
evaluator = ModelEvaluator()
|
||||
results = evaluator.evaluate_all()
|
||||
|
||||
print("\nEvaluation results:")
|
||||
for target, metrics in results.items():
|
||||
print(f" {target}: {metrics}")
|
||||
|
||||
print("\nFeature importances (top 5 per model):")
|
||||
for target in TARGETS:
|
||||
try:
|
||||
importances = evaluator.get_feature_importance(target)
|
||||
top5 = importances[:5]
|
||||
print(f" {target}: {top5}")
|
||||
except FileNotFoundError as exc:
|
||||
print(f" {target}: {exc}")
|
||||
@@ -0,0 +1,356 @@
|
||||
"""Train predictive models for ski station conditions.
|
||||
|
||||
Trains three models against the processed feature dataset:
|
||||
- station_open: binary classification (RandomForestClassifier)
|
||||
- km_open: regression (GradientBoostingRegressor)
|
||||
- crowd_level: multi-class classification (LGBMClassifier)
|
||||
|
||||
Models and feature importances are persisted under ml/models/ via joblib.
|
||||
Cross-validation (5-fold stratified for classifiers, KFold for regression)
|
||||
is used throughout to compensate for the small dataset size.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from lightgbm import LGBMClassifier
|
||||
from sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier
|
||||
from sklearn.model_selection import KFold, StratifiedKFold, cross_validate
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
DATASET_PATH = _REPO_ROOT / "data" / "processed" / "dataset_featured.csv"
|
||||
MODELS_DIR = _REPO_ROOT / "ml" / "models"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Model registry
|
||||
# ---------------------------------------------------------------------------
|
||||
# Maps each target to a (model_instance, task_type) tuple.
|
||||
# task_type is one of: "binary", "regression", "multiclass"
|
||||
MODEL_REGISTRY: dict[str, tuple[Any, str]] = {
|
||||
"station_open": (
|
||||
RandomForestClassifier(
|
||||
n_estimators=200,
|
||||
max_depth=8,
|
||||
min_samples_leaf=2,
|
||||
class_weight="balanced",
|
||||
random_state=42,
|
||||
n_jobs=-1,
|
||||
),
|
||||
"binary",
|
||||
),
|
||||
"km_open": (
|
||||
GradientBoostingRegressor(
|
||||
n_estimators=200,
|
||||
max_depth=4,
|
||||
learning_rate=0.05,
|
||||
subsample=0.8,
|
||||
min_samples_leaf=2,
|
||||
random_state=42,
|
||||
),
|
||||
"regression",
|
||||
),
|
||||
"crowd_level": (
|
||||
LGBMClassifier(
|
||||
n_estimators=200,
|
||||
max_depth=6,
|
||||
learning_rate=0.05,
|
||||
num_leaves=31,
|
||||
min_child_samples=5,
|
||||
class_weight="balanced",
|
||||
random_state=42,
|
||||
verbose=-1,
|
||||
),
|
||||
"multiclass",
|
||||
),
|
||||
}
|
||||
|
||||
# Ordered crowd-level labels used for LabelEncoder consistency
|
||||
CROWD_LEVEL_LABELS = ["low", "medium", "high"]
|
||||
|
||||
N_CV_FOLDS = 5
|
||||
|
||||
|
||||
class ModelTrainer:
|
||||
"""Train and persist ski-condition prediction models.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
dataset_path:
|
||||
Path to the processed feature CSV. Defaults to
|
||||
``data/processed/dataset_featured.csv`` relative to the repo root.
|
||||
models_dir:
|
||||
Directory where trained models and importances are saved. Defaults to
|
||||
``ml/models/`` relative to the repo root.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset_path: Path | str = DATASET_PATH,
|
||||
models_dir: Path | str = MODELS_DIR,
|
||||
) -> None:
|
||||
self.dataset_path = Path(dataset_path)
|
||||
self.models_dir = Path(models_dir)
|
||||
self.models_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self._df: pd.DataFrame | None = None
|
||||
self._feature_columns: list[str] = []
|
||||
self._label_encoder: LabelEncoder | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def train_all(self) -> dict[str, dict[str, float]]:
|
||||
"""Train all three models and return their cross-validation scores.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
``{target_name: {metric_name: score, ...}}``
|
||||
"""
|
||||
self._load_dataset()
|
||||
|
||||
cv_results: dict[str, dict[str, float]] = {}
|
||||
for target, (_, task_type) in MODEL_REGISTRY.items():
|
||||
logger.info("Training model for target: %s", target)
|
||||
cv_results[target] = self.train_model(target, task_type)
|
||||
|
||||
logger.info("All models trained successfully.")
|
||||
return cv_results
|
||||
|
||||
def train_model(self, target: str, model_type: str) -> dict[str, float]:
|
||||
"""Train a single model, evaluate it with cross-validation, and save it.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
target:
|
||||
Column name of the prediction target (``station_open``,
|
||||
``km_open``, or ``crowd_level``).
|
||||
model_type:
|
||||
One of ``"binary"``, ``"multiclass"``, or ``"regression"``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Cross-validation metric averages for the model.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If *target* or *model_type* are not recognised.
|
||||
RuntimeError
|
||||
If the dataset has not been loaded yet (call ``train_all()`` or
|
||||
``_load_dataset()`` first).
|
||||
"""
|
||||
if self._df is None:
|
||||
self._load_dataset()
|
||||
|
||||
if target not in MODEL_REGISTRY:
|
||||
raise ValueError(
|
||||
f"Unknown target '{target}'. "
|
||||
f"Valid targets: {list(MODEL_REGISTRY.keys())}"
|
||||
)
|
||||
|
||||
valid_types = {"binary", "multiclass", "regression"}
|
||||
if model_type not in valid_types:
|
||||
raise ValueError(
|
||||
f"Unknown model_type '{model_type}'. Valid: {valid_types}"
|
||||
)
|
||||
|
||||
X, y = self._prepare_features_and_target(target)
|
||||
model, _ = MODEL_REGISTRY[target]
|
||||
|
||||
# Cross-validate before final fit on all data
|
||||
cv_scores = self._cross_validate(model, X, y, model_type)
|
||||
logger.info("CV scores for %s: %s", target, cv_scores)
|
||||
|
||||
# Final fit on the full available dataset
|
||||
model.fit(X, y)
|
||||
logger.info("Final fit complete for target: %s", target)
|
||||
|
||||
self._save_model(model, target)
|
||||
self._save_feature_importances(model, target)
|
||||
|
||||
return cv_scores
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_dataset(self) -> None:
|
||||
"""Load the processed dataset from disk and derive feature columns."""
|
||||
if not self.dataset_path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Processed dataset not found at {self.dataset_path}. "
|
||||
"Run the pipeline first."
|
||||
)
|
||||
|
||||
logger.info("Loading dataset from %s", self.dataset_path)
|
||||
self._df = pd.read_csv(self.dataset_path, parse_dates=["date"])
|
||||
|
||||
target_cols = set(MODEL_REGISTRY.keys())
|
||||
# Exclude date, station identifiers, target aliases, and non-numeric
|
||||
# categorical columns that cannot be used as model inputs directly.
|
||||
non_feature_cols = target_cols | {
|
||||
"date",
|
||||
"station",
|
||||
"station_id",
|
||||
# open_status is an alias for station_open (target); exclude it
|
||||
"open_status",
|
||||
# snow_quality is free-text; exclude until encoding is added
|
||||
"snow_quality",
|
||||
# season is a string label, not a numeric feature
|
||||
"season",
|
||||
}
|
||||
# Also exclude any remaining object/string columns to prevent sklearn errors
|
||||
string_cols = set(
|
||||
self._df.select_dtypes(include=["object", "string"]).columns
|
||||
)
|
||||
non_feature_cols |= string_cols
|
||||
|
||||
self._feature_columns = [
|
||||
col for col in self._df.columns if col not in non_feature_cols
|
||||
]
|
||||
logger.info(
|
||||
"Dataset loaded: %d rows, %d features",
|
||||
len(self._df),
|
||||
len(self._feature_columns),
|
||||
)
|
||||
|
||||
def _prepare_features_and_target(
|
||||
self, target: str
|
||||
) -> tuple[pd.DataFrame, pd.Series | np.ndarray]:
|
||||
"""Return (X, y) with rows that have a valid target value."""
|
||||
assert self._df is not None # guaranteed by callers
|
||||
|
||||
df = self._df.dropna(subset=[target]).copy()
|
||||
if len(df) == 0:
|
||||
raise RuntimeError(
|
||||
f"No non-null rows found for target '{target}' in the dataset."
|
||||
)
|
||||
|
||||
X = df[self._feature_columns].copy()
|
||||
X = X.fillna(X.median(numeric_only=True))
|
||||
|
||||
if target == "crowd_level":
|
||||
# Encode string labels to integers in a stable order
|
||||
le = LabelEncoder()
|
||||
le.fit(CROWD_LEVEL_LABELS)
|
||||
y = le.transform(df[target].astype(str))
|
||||
self._label_encoder = le
|
||||
# Persist the encoder so the evaluator can decode predictions
|
||||
joblib.dump(le, self.models_dir / "crowd_level_label_encoder.joblib")
|
||||
logger.debug("LabelEncoder classes: %s", list(le.classes_))
|
||||
else:
|
||||
y = df[target].values
|
||||
|
||||
return X, y
|
||||
|
||||
def _cross_validate(
|
||||
self,
|
||||
model: Any,
|
||||
X: pd.DataFrame,
|
||||
y: pd.Series | np.ndarray,
|
||||
model_type: str,
|
||||
) -> dict[str, float]:
|
||||
"""Run k-fold cross-validation and return mean scores.
|
||||
|
||||
Uses StratifiedKFold for classification targets so that class
|
||||
proportions are preserved in each fold.
|
||||
"""
|
||||
if model_type in {"binary", "multiclass"}:
|
||||
scoring = {
|
||||
"accuracy": "accuracy",
|
||||
"f1_macro": "f1_macro",
|
||||
"roc_auc": (
|
||||
"roc_auc"
|
||||
if model_type == "binary"
|
||||
else "roc_auc_ovr_weighted"
|
||||
),
|
||||
}
|
||||
cv = StratifiedKFold(
|
||||
n_splits=N_CV_FOLDS, shuffle=True, random_state=42
|
||||
)
|
||||
else:
|
||||
scoring = {
|
||||
"neg_mae": "neg_mean_absolute_error",
|
||||
"neg_rmse": "neg_root_mean_squared_error",
|
||||
"r2": "r2",
|
||||
}
|
||||
cv = KFold(n_splits=N_CV_FOLDS, shuffle=True, random_state=42)
|
||||
|
||||
results = cross_validate(
|
||||
model, X, y, cv=cv, scoring=scoring, return_train_score=False
|
||||
)
|
||||
|
||||
mean_scores: dict[str, float] = {}
|
||||
for metric, values in results.items():
|
||||
if not metric.startswith("test_"):
|
||||
continue
|
||||
key = metric[len("test_"):]
|
||||
score = float(np.mean(values))
|
||||
# Convert negated metrics back to positive for readability
|
||||
if key.startswith("neg_"):
|
||||
key = key[len("neg_"):]
|
||||
score = -score
|
||||
mean_scores[key] = round(score, 4)
|
||||
|
||||
return mean_scores
|
||||
|
||||
def _save_model(self, model: Any, target: str) -> None:
|
||||
"""Persist a trained model with joblib."""
|
||||
path = self.models_dir / f"{target}_model.joblib"
|
||||
joblib.dump(model, path)
|
||||
logger.info("Model saved to %s", path)
|
||||
|
||||
def _save_feature_importances(self, model: Any, target: str) -> None:
|
||||
"""Save feature importances as a sorted JSON file."""
|
||||
if not hasattr(model, "feature_importances_"):
|
||||
logger.warning(
|
||||
"Model for '%s' has no feature_importances_ attribute; skipping.",
|
||||
target,
|
||||
)
|
||||
return
|
||||
|
||||
importances = dict(
|
||||
zip(self._feature_columns, model.feature_importances_.tolist())
|
||||
)
|
||||
sorted_importances = dict(
|
||||
sorted(importances.items(), key=lambda kv: kv[1], reverse=True)
|
||||
)
|
||||
|
||||
path = self.models_dir / f"{target}_feature_importances.json"
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(sorted_importances, fh, indent=2)
|
||||
|
||||
logger.info("Feature importances saved to %s", path)
|
||||
top5 = list(sorted_importances.items())[:5]
|
||||
logger.debug("Top-5 features for %s: %s", target, top5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
trainer = ModelTrainer()
|
||||
results = trainer.train_all()
|
||||
print("\nCross-validation results:")
|
||||
for target, scores in results.items():
|
||||
print(f" {target}: {scores}")
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Pipeline package for ski predictor.
|
||||
|
||||
Modules:
|
||||
build_dataset: Merges raw weather and station data into a processed dataset.
|
||||
feature_engineering: Derives ML-ready features from the merged dataset.
|
||||
"""
|
||||
@@ -0,0 +1,361 @@
|
||||
"""Dataset builder for the ski predictor pipeline.
|
||||
|
||||
Loads raw weather CSVs and station JSONs, merges them on date and station_id,
|
||||
handles missing data, and writes a processed dataset to disk.
|
||||
"""
|
||||
|
||||
import glob
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import pandas as pd
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Paths are relative to the repository root.
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
_RAW_DIR = _REPO_ROOT / "data" / "raw"
|
||||
_PROCESSED_DIR = _REPO_ROOT / "data" / "processed"
|
||||
_DATASET_PATH = _PROCESSED_DIR / "dataset.csv"
|
||||
|
||||
# Numeric weather columns that can be safely interpolated when values are
|
||||
# missing in the middle of a time series. Columns not listed here are filled
|
||||
# with forward-fill only (e.g. station metadata).
|
||||
_INTERPOLATABLE_WEATHER_COLS = [
|
||||
"temperature_2m_max",
|
||||
"temperature_2m_min",
|
||||
"temperature_2m_mean",
|
||||
"precipitation_sum",
|
||||
"snowfall_sum",
|
||||
"wind_speed_10m_max",
|
||||
"wind_gusts_10m_max",
|
||||
"wind_direction_10m_dominant",
|
||||
"relative_humidity_2m_mean",
|
||||
"surface_pressure_mean",
|
||||
]
|
||||
|
||||
# Station operational columns are TARGET variables for ML and must NEVER
|
||||
# be forward-filled or interpolated. Missing values mean we have no
|
||||
# observation for that date and should remain as NaN.
|
||||
_STATION_TARGET_COLS = [
|
||||
"open_status",
|
||||
"km_open",
|
||||
"lifts_open",
|
||||
"snow_depth",
|
||||
"snow_quality",
|
||||
]
|
||||
|
||||
|
||||
class DatasetBuilder:
|
||||
"""Merges raw weather and station data into a single processed dataset.
|
||||
|
||||
Raw weather data is expected as CSV files matching the glob pattern
|
||||
``data/raw/weather_*.csv``. Raw station data is expected as JSON files
|
||||
matching ``data/raw/station_*.json``.
|
||||
|
||||
Both sources must contain a ``date`` column (or key) and a ``station_id``
|
||||
column (or key). They are merged on ``(date, station_id)``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
raw_dir:
|
||||
Directory that contains the raw input files. Defaults to
|
||||
``<repo_root>/data/raw``.
|
||||
processed_dir:
|
||||
Directory where the processed dataset is written. Defaults to
|
||||
``<repo_root>/data/processed``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
raw_dir: Optional[Path] = None,
|
||||
processed_dir: Optional[Path] = None,
|
||||
) -> None:
|
||||
self.raw_dir = Path(raw_dir) if raw_dir else _RAW_DIR
|
||||
self.processed_dir = Path(processed_dir) if processed_dir else _PROCESSED_DIR
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def build(self) -> pd.DataFrame:
|
||||
"""Run the full build pipeline and persist the result.
|
||||
|
||||
Reads all raw weather CSVs and station JSONs, merges them, fills
|
||||
missing values and saves the result to
|
||||
``data/processed/dataset.csv``.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
The fully merged and cleaned dataset.
|
||||
"""
|
||||
logger.info("Starting full dataset build.")
|
||||
|
||||
weather_df = self._load_weather_csvs()
|
||||
station_df = self._load_station_jsons()
|
||||
|
||||
if weather_df.empty and station_df.empty:
|
||||
logger.warning("No raw data found. Returning empty dataset.")
|
||||
return pd.DataFrame()
|
||||
|
||||
merged = self._merge(weather_df, station_df)
|
||||
merged = self._handle_missing(merged)
|
||||
|
||||
self._save(merged)
|
||||
logger.info("Dataset build complete. Rows: %d", len(merged))
|
||||
return merged
|
||||
|
||||
def append_daily(
|
||||
self,
|
||||
weather_data: dict | pd.DataFrame,
|
||||
station_data: dict | pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""Append a single day's data to the existing processed dataset.
|
||||
|
||||
Useful for daily cron-driven updates without reprocessing the full
|
||||
history.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
weather_data:
|
||||
Either a ``dict`` (single record) or a one-row ``DataFrame``
|
||||
containing weather measurements for the day.
|
||||
station_data:
|
||||
Either a ``dict`` (single record) or a one-row ``DataFrame``
|
||||
containing station operational data for the day.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
The updated full dataset (existing rows + new row).
|
||||
"""
|
||||
weather_row = self._to_dataframe(weather_data)
|
||||
station_row = self._to_dataframe(station_data)
|
||||
|
||||
new_row = self._merge(weather_row, station_row)
|
||||
new_row = self._handle_missing(new_row)
|
||||
|
||||
existing = self._load_existing_dataset()
|
||||
|
||||
# Normalize date columns to pd.Timestamp before concat to avoid
|
||||
# mixed-type sort errors (datetime.date vs Timestamp).
|
||||
new_row["date"] = pd.to_datetime(new_row["date"])
|
||||
if not existing.empty:
|
||||
existing["date"] = pd.to_datetime(existing["date"], format="mixed")
|
||||
|
||||
combined = pd.concat([existing, new_row], ignore_index=True)
|
||||
|
||||
# Ensure date column is uniform Timestamp after concat
|
||||
combined["date"] = pd.to_datetime(combined["date"], format="mixed")
|
||||
|
||||
# Drop duplicate (date, station_id) pairs, keeping the latest entry.
|
||||
combined = combined.drop_duplicates(
|
||||
subset=["date", "station_id"], keep="last"
|
||||
)
|
||||
combined = combined.sort_values(["station_id", "date"]).reset_index(drop=True)
|
||||
|
||||
self._save(combined)
|
||||
logger.info(
|
||||
"Appended daily data. Total rows: %d", len(combined)
|
||||
)
|
||||
return combined
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers – loading
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_weather_csvs(self) -> pd.DataFrame:
|
||||
"""Load and concatenate all ``weather_*.csv`` files from raw_dir."""
|
||||
pattern = str(self.raw_dir / "weather_*.csv")
|
||||
files = sorted(glob.glob(pattern))
|
||||
|
||||
if not files:
|
||||
logger.warning("No weather CSV files found at %s.", pattern)
|
||||
return pd.DataFrame()
|
||||
|
||||
frames = []
|
||||
for path in files:
|
||||
logger.debug("Reading weather file: %s", path)
|
||||
try:
|
||||
df = pd.read_csv(path)
|
||||
frames.append(df)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to read %s: %s", path, exc)
|
||||
|
||||
if not frames:
|
||||
return pd.DataFrame()
|
||||
|
||||
combined = pd.concat(frames, ignore_index=True)
|
||||
combined["date"] = pd.to_datetime(combined["date"])
|
||||
logger.info("Loaded %d weather rows from %d file(s).", len(combined), len(files))
|
||||
return combined
|
||||
|
||||
def _load_station_jsons(self) -> pd.DataFrame:
|
||||
"""Load and concatenate all ``station_*.json`` files from raw_dir."""
|
||||
pattern = str(self.raw_dir / "station_*.json")
|
||||
files = sorted(glob.glob(pattern))
|
||||
|
||||
if not files:
|
||||
logger.warning("No station JSON files found at %s.", pattern)
|
||||
return pd.DataFrame()
|
||||
|
||||
frames = []
|
||||
for path in files:
|
||||
logger.debug("Reading station file: %s", path)
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
raw = json.load(fh)
|
||||
|
||||
# Accept either a single record (dict) or a list of records.
|
||||
if isinstance(raw, dict):
|
||||
raw = [raw]
|
||||
|
||||
df = pd.DataFrame(raw)
|
||||
frames.append(df)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to read %s: %s", path, exc)
|
||||
|
||||
if not frames:
|
||||
return pd.DataFrame()
|
||||
|
||||
combined = pd.concat(frames, ignore_index=True)
|
||||
combined["date"] = pd.to_datetime(combined["date"])
|
||||
logger.info(
|
||||
"Loaded %d station rows from %d file(s).", len(combined), len(files)
|
||||
)
|
||||
return combined
|
||||
|
||||
def _load_existing_dataset(self) -> pd.DataFrame:
|
||||
"""Return the persisted processed dataset, or an empty DataFrame."""
|
||||
if _DATASET_PATH.exists():
|
||||
df = pd.read_csv(_DATASET_PATH)
|
||||
df["date"] = pd.to_datetime(df["date"], format="mixed")
|
||||
logger.debug("Loaded existing dataset with %d rows.", len(df))
|
||||
return df
|
||||
|
||||
logger.debug("No existing dataset found at %s.", _DATASET_PATH)
|
||||
return pd.DataFrame()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers – merging and cleaning
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _merge(
|
||||
self, weather_df: pd.DataFrame, station_df: pd.DataFrame
|
||||
) -> pd.DataFrame:
|
||||
"""Outer-merge weather and station frames on (date, station_id).
|
||||
|
||||
An outer merge is used so that rows present in only one source are
|
||||
still retained (with NaN in the missing columns). This allows the
|
||||
missing-data handler to fill or interpolate the gaps.
|
||||
"""
|
||||
if weather_df.empty and station_df.empty:
|
||||
return pd.DataFrame()
|
||||
|
||||
if weather_df.empty:
|
||||
logger.warning(
|
||||
"Weather data is empty; returning station data only."
|
||||
)
|
||||
return station_df.copy()
|
||||
|
||||
if station_df.empty:
|
||||
logger.warning(
|
||||
"Station data is empty; returning weather data only."
|
||||
)
|
||||
return weather_df.copy()
|
||||
|
||||
merged = pd.merge(
|
||||
weather_df,
|
||||
station_df,
|
||||
on=["date", "station_id"],
|
||||
how="outer",
|
||||
)
|
||||
merged = merged.sort_values(["station_id", "date"]).reset_index(drop=True)
|
||||
logger.debug("Merged dataset shape: %s", merged.shape)
|
||||
return merged
|
||||
|
||||
def _handle_missing(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Fill or interpolate missing values.
|
||||
|
||||
Strategy per column type:
|
||||
- Interpolatable numeric weather columns: linear interpolation, then
|
||||
forward-fill for leading/trailing NaNs.
|
||||
- All other numeric columns: forward-fill then backward-fill.
|
||||
- Non-numeric columns: forward-fill within each station group.
|
||||
"""
|
||||
if df.empty:
|
||||
return df
|
||||
|
||||
result = df.copy()
|
||||
|
||||
# Interpolate known numeric weather variables within each station group.
|
||||
weather_cols_present = [
|
||||
c for c in _INTERPOLATABLE_WEATHER_COLS if c in result.columns
|
||||
]
|
||||
if weather_cols_present:
|
||||
result[weather_cols_present] = (
|
||||
result.groupby("station_id", group_keys=False)[weather_cols_present]
|
||||
.apply(
|
||||
lambda g: g.interpolate(method="linear", limit_direction="both")
|
||||
)
|
||||
)
|
||||
|
||||
# Forward-fill / backward-fill remaining numeric columns,
|
||||
# but NEVER fill station target columns (those are real observations).
|
||||
numeric_cols = result.select_dtypes(include="number").columns.tolist()
|
||||
remaining_numeric = [
|
||||
c for c in numeric_cols
|
||||
if c not in weather_cols_present and c not in _STATION_TARGET_COLS
|
||||
]
|
||||
if remaining_numeric:
|
||||
result[remaining_numeric] = (
|
||||
result.groupby("station_id", group_keys=False)[remaining_numeric]
|
||||
.apply(lambda g: g.ffill().bfill())
|
||||
)
|
||||
|
||||
# Forward-fill non-numeric columns (e.g. station name, categorical fields),
|
||||
# but NEVER fill station target columns.
|
||||
non_numeric_cols = result.select_dtypes(exclude="number").columns.tolist()
|
||||
skip_cols = {"date"} | set(_STATION_TARGET_COLS)
|
||||
fill_non_numeric = [
|
||||
c for c in non_numeric_cols if c not in skip_cols
|
||||
]
|
||||
if fill_non_numeric:
|
||||
result[fill_non_numeric] = (
|
||||
result.groupby("station_id", group_keys=False)[fill_non_numeric]
|
||||
.apply(lambda g: g.ffill())
|
||||
)
|
||||
|
||||
missing_after = result.isnull().sum().sum()
|
||||
if missing_after > 0:
|
||||
logger.warning(
|
||||
"%d missing values remain after imputation.", missing_after
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers – persistence
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _save(self, df: pd.DataFrame) -> None:
|
||||
"""Write dataset to ``data/processed/dataset.csv``."""
|
||||
self.processed_dir.mkdir(parents=True, exist_ok=True)
|
||||
output_path = self.processed_dir / "dataset.csv"
|
||||
df.to_csv(output_path, index=False)
|
||||
logger.info("Dataset saved to %s.", output_path)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers – type coercion
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _to_dataframe(data: dict | pd.DataFrame) -> pd.DataFrame:
|
||||
"""Coerce a dict or DataFrame to a one-row DataFrame."""
|
||||
if isinstance(data, pd.DataFrame):
|
||||
return data.copy()
|
||||
return pd.DataFrame([data])
|
||||
@@ -0,0 +1,397 @@
|
||||
"""Feature engineering for the ski predictor pipeline.
|
||||
|
||||
Derives temporal, rolling, and calendar features from a merged weather +
|
||||
station DataFrame to produce an ML-ready feature set.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
_DEFAULT_FEATURES_CONFIG = _REPO_ROOT / "config" / "features.yaml"
|
||||
|
||||
# Spanish national public holidays (month, day). Regional holidays for
|
||||
# Asturias (where all three target stations are located) are also included.
|
||||
_SPANISH_HOLIDAYS: set[tuple[int, int]] = {
|
||||
# National
|
||||
(1, 1), # New Year's Day
|
||||
(1, 6), # Epiphany
|
||||
(5, 1), # Labour Day
|
||||
(8, 15), # Assumption of Mary
|
||||
(10, 12), # National Day of Spain
|
||||
(11, 1), # All Saints' Day
|
||||
(12, 6), # Constitution Day
|
||||
(12, 8), # Immaculate Conception
|
||||
(12, 25), # Christmas Day
|
||||
# Asturian regional
|
||||
(9, 8), # Day of Asturias
|
||||
}
|
||||
|
||||
# Approximate Good Friday dates for years 2018-2035 (moveable feast).
|
||||
# Keyed by year, value is (month, day).
|
||||
_GOOD_FRIDAY: dict[int, tuple[int, int]] = {
|
||||
2018: (3, 30),
|
||||
2019: (4, 19),
|
||||
2020: (4, 10),
|
||||
2021: (4, 2),
|
||||
2022: (4, 15),
|
||||
2023: (4, 7),
|
||||
2024: (3, 29),
|
||||
2025: (4, 18),
|
||||
2026: (4, 3),
|
||||
2027: (3, 26),
|
||||
2028: (4, 14),
|
||||
2029: (3, 30),
|
||||
2030: (4, 19),
|
||||
2031: (4, 11),
|
||||
2032: (3, 26),
|
||||
2033: (4, 15),
|
||||
2034: (4, 7),
|
||||
2035: (3, 23),
|
||||
}
|
||||
|
||||
|
||||
def _build_holiday_set(years: Optional[list[int]] = None) -> set[pd.Timestamp]:
|
||||
"""Return a set of Timestamps for every known holiday across the given years.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
years:
|
||||
Calendar years to include. Defaults to 2018-2035.
|
||||
"""
|
||||
if years is None:
|
||||
years = list(range(2018, 2036))
|
||||
|
||||
holidays: set[pd.Timestamp] = set()
|
||||
for year in years:
|
||||
for month, day in _SPANISH_HOLIDAYS:
|
||||
try:
|
||||
holidays.add(pd.Timestamp(year=year, month=month, day=day))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
gf = _GOOD_FRIDAY.get(year)
|
||||
if gf:
|
||||
holidays.add(pd.Timestamp(year=year, month=gf[0], day=gf[1]))
|
||||
|
||||
return holidays
|
||||
|
||||
|
||||
class FeatureEngineer:
|
||||
"""Derives engineered features from a merged weather + station DataFrame.
|
||||
|
||||
All features defined in ``config/features.yaml`` under
|
||||
``engineered_features`` are computed. Columns required by each feature
|
||||
must be present in the input DataFrame; missing source columns are logged
|
||||
as warnings and the corresponding feature is set to NaN.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
config_path:
|
||||
Path to the ``features.yaml`` configuration file. Defaults to
|
||||
``<repo_root>/config/features.yaml``.
|
||||
"""
|
||||
|
||||
def __init__(self, config_path: Optional[Path] = None) -> None:
|
||||
self.config_path = (
|
||||
Path(config_path) if config_path else _DEFAULT_FEATURES_CONFIG
|
||||
)
|
||||
self._config = self._load_config()
|
||||
self._holidays = _build_holiday_set()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def transform(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Add all engineered features to *df* and return the result.
|
||||
|
||||
The input DataFrame must contain at minimum:
|
||||
- ``date`` (datetime-like)
|
||||
- ``station_id`` (str or int)
|
||||
- ``snowfall_sum`` (float) – daily snowfall in cm
|
||||
- ``temperature_2m_mean`` (float) – mean temperature in degrees C
|
||||
- ``wind_gusts_10m_max`` (float) – maximum wind gust in km/h
|
||||
- ``surface_pressure_mean`` (float) – mean surface pressure in hPa
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df:
|
||||
Merged weather + station DataFrame, one row per (date, station_id).
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Original DataFrame with additional feature columns appended.
|
||||
"""
|
||||
if df.empty:
|
||||
logger.warning("Input DataFrame is empty; returning as-is.")
|
||||
return df
|
||||
|
||||
result = df.copy()
|
||||
result["date"] = pd.to_datetime(result["date"])
|
||||
result = result.sort_values(["station_id", "date"]).reset_index(drop=True)
|
||||
|
||||
enabled = set(self._config.get("engineered_features", []))
|
||||
|
||||
result = self._add_rolling_snow(result, enabled)
|
||||
result = self._add_rolling_temperature(result, enabled)
|
||||
result = self._add_max_wind_gust(result, enabled)
|
||||
result = self._add_calendar_features(result, enabled)
|
||||
result = self._add_days_since_last_snowfall(result, enabled)
|
||||
result = self._add_temperature_trend(result, enabled)
|
||||
result = self._add_pressure_trend(result, enabled)
|
||||
|
||||
computed = [c for c in result.columns if c not in df.columns]
|
||||
logger.info("Feature engineering complete. Added columns: %s", computed)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private feature methods
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _add_rolling_snow(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Compute rolling snowfall sums over 3 and 7 days.
|
||||
|
||||
Features produced:
|
||||
- ``snow_last_3_days``: sum of snowfall_sum over the 3 preceding days
|
||||
(exclusive of the current day).
|
||||
- ``snow_last_7_days``: sum of snowfall_sum over the 7 preceding days
|
||||
(exclusive of the current day).
|
||||
|
||||
The shift-by-one before rolling ensures these features capture
|
||||
antecedent conditions, which is the meaningful signal for a
|
||||
next-day opening-probability model.
|
||||
"""
|
||||
source = "snowfall_sum"
|
||||
if not self._check_source(df, source):
|
||||
for feat in ("snow_last_3_days", "snow_last_7_days"):
|
||||
if feat in enabled:
|
||||
df[feat] = np.nan
|
||||
return df
|
||||
|
||||
grp = df.groupby("station_id")[source]
|
||||
|
||||
if "snow_last_3_days" in enabled:
|
||||
shifted = grp.shift(1)
|
||||
df["snow_last_3_days"] = (
|
||||
shifted.groupby(df["station_id"])
|
||||
.transform(lambda s: s.rolling(window=3, min_periods=1).sum())
|
||||
)
|
||||
|
||||
if "snow_last_7_days" in enabled:
|
||||
shifted = grp.shift(1)
|
||||
df["snow_last_7_days"] = (
|
||||
shifted.groupby(df["station_id"])
|
||||
.transform(lambda s: s.rolling(window=7, min_periods=1).sum())
|
||||
)
|
||||
|
||||
return df
|
||||
|
||||
def _add_rolling_temperature(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Compute 3-day rolling mean temperature.
|
||||
|
||||
Feature produced:
|
||||
- ``avg_temperature_3_days``: mean of temperature_2m_mean over the
|
||||
3 preceding days (exclusive of the current day).
|
||||
"""
|
||||
feat = "avg_temperature_3_days"
|
||||
if feat not in enabled:
|
||||
return df
|
||||
|
||||
source = "temperature_2m_mean"
|
||||
if not self._check_source(df, source):
|
||||
df[feat] = np.nan
|
||||
return df
|
||||
|
||||
shifted = df.groupby("station_id")[source].shift(1)
|
||||
df[feat] = (
|
||||
shifted.groupby(df["station_id"])
|
||||
.transform(lambda s: s.rolling(window=3, min_periods=1).mean())
|
||||
)
|
||||
return df
|
||||
|
||||
def _add_max_wind_gust(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Alias the daily maximum wind gust into a consistently named feature.
|
||||
|
||||
Feature produced:
|
||||
- ``max_wind_gust``: maximum wind gust (km/h) for the current day,
|
||||
sourced directly from ``wind_gusts_10m_max``.
|
||||
|
||||
The raw column already represents the 24-hour maximum, so no rolling
|
||||
aggregation is required.
|
||||
"""
|
||||
feat = "max_wind_gust"
|
||||
if feat not in enabled:
|
||||
return df
|
||||
|
||||
source = "wind_gusts_10m_max"
|
||||
if not self._check_source(df, source):
|
||||
df[feat] = np.nan
|
||||
else:
|
||||
df[feat] = df[source]
|
||||
|
||||
return df
|
||||
|
||||
def _add_calendar_features(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Add calendar-derived features.
|
||||
|
||||
Features produced:
|
||||
- ``is_weekend``: 1 if the date falls on Saturday (5) or Sunday (6).
|
||||
- ``is_holiday``: 1 if the date is a Spanish or Asturian public holiday.
|
||||
- ``month_of_year``: integer month 1-12.
|
||||
- ``day_of_week``: integer weekday 0 (Monday) through 6 (Sunday).
|
||||
"""
|
||||
dates = df["date"]
|
||||
|
||||
if "is_weekend" in enabled:
|
||||
df["is_weekend"] = dates.dt.dayofweek.isin([5, 6]).astype(int)
|
||||
|
||||
if "is_holiday" in enabled:
|
||||
df["is_holiday"] = dates.isin(self._holidays).astype(int)
|
||||
|
||||
if "month_of_year" in enabled:
|
||||
df["month_of_year"] = dates.dt.month
|
||||
|
||||
if "day_of_week" in enabled:
|
||||
df["day_of_week"] = dates.dt.dayofweek
|
||||
|
||||
return df
|
||||
|
||||
def _add_days_since_last_snowfall(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Compute days elapsed since the most recent snowfall event.
|
||||
|
||||
A snowfall event is defined as ``snowfall_sum > 0``.
|
||||
|
||||
Feature produced:
|
||||
- ``days_since_last_snowfall``: integer count of days since the last
|
||||
day with non-zero snowfall. 0 means it snowed today. NaN is used
|
||||
for rows where no prior snowfall is present in the history window.
|
||||
"""
|
||||
feat = "days_since_last_snowfall"
|
||||
if feat not in enabled:
|
||||
return df
|
||||
|
||||
source = "snowfall_sum"
|
||||
if not self._check_source(df, source):
|
||||
df[feat] = np.nan
|
||||
return df
|
||||
|
||||
def _days_since_for_group(group: pd.Series) -> pd.Series:
|
||||
"""Vectorised computation for a single station's snowfall series."""
|
||||
snow = group.values
|
||||
result = np.full(len(snow), np.nan)
|
||||
last_snow_idx: Optional[int] = None
|
||||
|
||||
for i, val in enumerate(snow):
|
||||
if val > 0:
|
||||
last_snow_idx = i
|
||||
if last_snow_idx is not None:
|
||||
result[i] = float(i - last_snow_idx)
|
||||
|
||||
return pd.Series(result, index=group.index)
|
||||
|
||||
df[feat] = (
|
||||
df.groupby("station_id")[source]
|
||||
.transform(_days_since_for_group)
|
||||
)
|
||||
return df
|
||||
|
||||
def _add_temperature_trend(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Compute temperature change over the last 3 days.
|
||||
|
||||
Feature produced:
|
||||
- ``temperature_trend_3_days``: difference between today's mean
|
||||
temperature and the mean temperature 3 days ago. A positive value
|
||||
indicates warming; a negative value indicates cooling.
|
||||
"""
|
||||
feat = "temperature_trend_3_days"
|
||||
if feat not in enabled:
|
||||
return df
|
||||
|
||||
source = "temperature_2m_mean"
|
||||
if not self._check_source(df, source):
|
||||
df[feat] = np.nan
|
||||
return df
|
||||
|
||||
df[feat] = (
|
||||
df[source]
|
||||
- df.groupby("station_id")[source].transform(lambda s: s.shift(3))
|
||||
)
|
||||
return df
|
||||
|
||||
def _add_pressure_trend(
|
||||
self, df: pd.DataFrame, enabled: set
|
||||
) -> pd.DataFrame:
|
||||
"""Compute surface pressure change over the last 3 days.
|
||||
|
||||
Feature produced:
|
||||
- ``pressure_trend_3_days``: difference between today's mean surface
|
||||
pressure and the value 3 days ago. A positive value indicates a
|
||||
rising pressure (improving conditions); a negative value indicates
|
||||
a falling pressure (approaching precipitation).
|
||||
"""
|
||||
feat = "pressure_trend_3_days"
|
||||
if feat not in enabled:
|
||||
return df
|
||||
|
||||
source = "surface_pressure_mean"
|
||||
if not self._check_source(df, source):
|
||||
df[feat] = np.nan
|
||||
return df
|
||||
|
||||
df[feat] = (
|
||||
df[source]
|
||||
- df.groupby("station_id")[source].transform(lambda s: s.shift(3))
|
||||
)
|
||||
return df
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_config(self) -> dict:
|
||||
"""Load and return the features YAML configuration."""
|
||||
if not self.config_path.exists():
|
||||
logger.warning(
|
||||
"Features config not found at %s. All features enabled by default.",
|
||||
self.config_path,
|
||||
)
|
||||
return {}
|
||||
|
||||
with open(self.config_path, "r", encoding="utf-8") as fh:
|
||||
config = yaml.safe_load(fh)
|
||||
|
||||
logger.debug("Loaded features config from %s.", self.config_path)
|
||||
return config or {}
|
||||
|
||||
@staticmethod
|
||||
def _check_source(df: pd.DataFrame, column: str) -> bool:
|
||||
"""Return True if *column* exists in *df*, otherwise log a warning."""
|
||||
if column not in df.columns:
|
||||
logger.warning(
|
||||
"Source column '%s' not found in DataFrame. "
|
||||
"Dependent feature(s) will be set to NaN.",
|
||||
column,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Predictor package for ski predictor.
|
||||
|
||||
Modules:
|
||||
rules: Rule-based engine that enforces physical and operational constraints.
|
||||
ml_predictor: Loads trained ML models and generates probabilistic predictions.
|
||||
hybrid_predictor: Combines rules engine and ML predictions into a final decision.
|
||||
"""
|
||||
@@ -0,0 +1,452 @@
|
||||
"""Hybrid predictor combining rule-based and ML predictions.
|
||||
|
||||
Implements the three-stage prediction pipeline defined in AGENTS.md:
|
||||
|
||||
Stage 1 – Evaluate the rules engine.
|
||||
Stage 2 – Compute ML prediction (when rules are inconclusive).
|
||||
Stage 3 – Merge both outputs into a single final prediction.
|
||||
|
||||
Rules always have priority over the ML model when a physical or safety
|
||||
constraint makes the outcome deterministic. The ML model is used for
|
||||
probabilistic refinement when rules do not resolve the outcome.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml"
|
||||
|
||||
# When rules are inconclusive the ML crowd prediction is used as-is.
|
||||
# These defaults are applied only when neither source provides a crowd level.
|
||||
_DEFAULT_CROWD_LEVEL = "medium"
|
||||
_DEFAULT_OPEN_PROBABILITY = 0.5
|
||||
_DEFAULT_KM_FACTOR = 1.0
|
||||
|
||||
|
||||
def _load_station_name(station_id: str, config_path: Path) -> str:
|
||||
"""Return the human-readable station name from configuration.
|
||||
|
||||
Args:
|
||||
station_id: Key identifying the station (e.g. ``"pajares"``).
|
||||
config_path: Path to ``stations.yaml``.
|
||||
|
||||
Returns:
|
||||
The ``name`` field from the station config, or ``station_id`` if
|
||||
the file or key cannot be read.
|
||||
"""
|
||||
try:
|
||||
with config_path.open("r", encoding="utf-8") as fh:
|
||||
raw = yaml.safe_load(fh)
|
||||
return raw["stations"][station_id]["name"]
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.warning(
|
||||
"Could not read station name for '%s' from %s: %s",
|
||||
station_id,
|
||||
config_path,
|
||||
exc,
|
||||
)
|
||||
return station_id
|
||||
|
||||
|
||||
def _build_weather_summary(weather_data: dict[str, Any]) -> str:
|
||||
"""Compose a concise human-readable summary of relevant weather conditions.
|
||||
|
||||
Args:
|
||||
weather_data: The same dict passed to :meth:`HybridPredictor.predict`.
|
||||
|
||||
Returns:
|
||||
A single-line string summarising the most operationally relevant
|
||||
weather factors present in the data.
|
||||
"""
|
||||
parts: list[str] = []
|
||||
|
||||
temp_max = weather_data.get("temperature_2m_max")
|
||||
temp_min = weather_data.get("temperature_2m_min")
|
||||
if temp_max is not None and temp_min is not None:
|
||||
parts.append(f"Temp {temp_min:.0f}–{temp_max:.0f} °C")
|
||||
elif temp_max is not None:
|
||||
parts.append(f"Temp max {temp_max:.0f} °C")
|
||||
|
||||
snowfall = weather_data.get("snowfall_sum")
|
||||
if snowfall is not None and snowfall > 0:
|
||||
parts.append(f"Snow {snowfall:.0f} cm")
|
||||
|
||||
snow_depth = weather_data.get("snow_depth")
|
||||
if snow_depth is not None:
|
||||
parts.append(f"Depth {snow_depth:.0f} cm")
|
||||
|
||||
precip = weather_data.get("precipitation_sum")
|
||||
if precip is not None and precip > 0:
|
||||
parts.append(f"Rain {precip:.1f} mm")
|
||||
|
||||
wind_gust = weather_data.get("wind_gusts_10m_max")
|
||||
if wind_gust is not None:
|
||||
parts.append(f"Gusts {wind_gust:.0f} km/h")
|
||||
|
||||
return " | ".join(parts) if parts else "No weather data available."
|
||||
|
||||
|
||||
class HybridPredictor:
|
||||
"""Combines the rule engine and ML predictor into a single interface.
|
||||
|
||||
The prediction logic follows a strict priority order:
|
||||
|
||||
1. If the rules engine marks the station as ``force_closed`` the
|
||||
outcome is ``open_probability=0.0`` and ``km_open=0.0``, regardless
|
||||
of what the ML model says.
|
||||
2. If the rules engine marks the station as ``force_open`` the
|
||||
``open_probability`` is set to 1.0, and the ML km prediction (if
|
||||
available) is used for slope coverage.
|
||||
3. Otherwise the ML prediction is used and the ``estimated_km_factor``
|
||||
from the rules engine is applied as a multiplier to the km estimate.
|
||||
4. When neither source can determine the crowd level a default of
|
||||
``"medium"`` is used.
|
||||
|
||||
Usage::
|
||||
|
||||
from predictor.rules import RulesEngine
|
||||
from predictor.ml_predictor import MLPredictor
|
||||
from predictor.hybrid_predictor import HybridPredictor
|
||||
|
||||
predictor = HybridPredictor()
|
||||
result = predictor.predict("pajares", weather_data, features_df)
|
||||
|
||||
Args:
|
||||
rules_engine: A :class:`~predictor.rules.RulesEngine` instance.
|
||||
If None, one is created with default settings.
|
||||
ml_predictor: A :class:`~predictor.ml_predictor.MLPredictor` instance.
|
||||
If None, one is created with default settings.
|
||||
config_path: Optional override for the path to ``stations.yaml``.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rules_engine: Any | None = None,
|
||||
ml_predictor: Any | None = None,
|
||||
config_path: Path | None = None,
|
||||
) -> None:
|
||||
# Import here to avoid circular imports at module level
|
||||
from predictor.rules import RulesEngine
|
||||
from predictor.ml_predictor import MLPredictor
|
||||
|
||||
self._rules = rules_engine if rules_engine is not None else RulesEngine()
|
||||
self._ml = ml_predictor if ml_predictor is not None else MLPredictor()
|
||||
self._config_path = config_path or _CONFIG_PATH
|
||||
|
||||
logger.info("HybridPredictor initialised.")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def predict(
|
||||
self,
|
||||
station_id: str,
|
||||
weather_data: dict[str, Any],
|
||||
features_df: pd.DataFrame | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Generate a combined prediction for tomorrow's station conditions.
|
||||
|
||||
Args:
|
||||
station_id: Key identifying the station in ``stations.yaml``
|
||||
(e.g. ``"pajares"``).
|
||||
weather_data: Dict of weather variables for the prediction day.
|
||||
See :meth:`~predictor.rules.RulesEngine.evaluate` for the
|
||||
full list of expected keys.
|
||||
features_df: A single-row ``pandas.DataFrame`` with the
|
||||
engineered ML features. May be ``None`` if no trained models
|
||||
exist yet; in that case only the rules engine is used.
|
||||
|
||||
Returns:
|
||||
A dict with the following keys:
|
||||
|
||||
- ``station_name`` (str): Human-readable station name.
|
||||
- ``open_probability`` (float): Probability the station opens
|
||||
(0–1).
|
||||
- ``km_open`` (float): Estimated km of open slopes.
|
||||
- ``crowd_level`` (str): Expected crowd level
|
||||
(``"low"``, ``"medium"``, or ``"high"``).
|
||||
- ``weather_summary`` (str): Brief weather description.
|
||||
- ``rule_overrides`` (list[str]): Reasons from the rules
|
||||
engine that influenced the prediction.
|
||||
- ``prediction_source`` (str): One of ``"rules"``, ``"ml"``,
|
||||
or ``"hybrid"`` indicating which source drove the result.
|
||||
|
||||
Raises:
|
||||
ValueError: If station_id is not found in the configuration.
|
||||
"""
|
||||
station_name = _load_station_name(station_id, self._config_path)
|
||||
weather_summary = _build_weather_summary(weather_data)
|
||||
|
||||
logger.info("HybridPredictor.predict called for station '%s'.", station_name)
|
||||
|
||||
# Stage 1: Rules engine ------------------------------------------
|
||||
rules_result = self._rules.evaluate(station_id, weather_data)
|
||||
force_closed = rules_result["force_closed"]
|
||||
force_open = rules_result["force_open"]
|
||||
km_factor = rules_result.get("estimated_km_factor", _DEFAULT_KM_FACTOR)
|
||||
rule_reasons = rules_result.get("reasons", [])
|
||||
|
||||
logger.debug(
|
||||
"Rules result for '%s': force_closed=%s, force_open=%s, km_factor=%.2f",
|
||||
station_name,
|
||||
force_closed,
|
||||
force_open,
|
||||
km_factor,
|
||||
)
|
||||
|
||||
# Stage 2: ML prediction (skipped when rules are deterministic) ---
|
||||
ml_result: dict[str, Any] | None = None
|
||||
|
||||
if not force_closed and features_df is not None:
|
||||
try:
|
||||
ml_result = self._ml.predict(features_df)
|
||||
if ml_result is not None:
|
||||
logger.debug("ML result for '%s': %s", station_name, ml_result)
|
||||
else:
|
||||
logger.info(
|
||||
"ML predictor returned None for '%s'; using rules only.",
|
||||
station_name,
|
||||
)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error(
|
||||
"ML prediction failed for '%s': %s. Falling back to rules.",
|
||||
station_name,
|
||||
exc,
|
||||
)
|
||||
|
||||
# Stage 3: Merge -------------------------------------------------
|
||||
open_probability, km_open, crowd_level, prediction_source = self._merge(
|
||||
station_id=station_id,
|
||||
station_name=station_name,
|
||||
force_closed=force_closed,
|
||||
force_open=force_open,
|
||||
km_factor=km_factor,
|
||||
rules_result=rules_result,
|
||||
ml_result=ml_result,
|
||||
weather_data=weather_data,
|
||||
)
|
||||
|
||||
result = {
|
||||
"station_name": station_name,
|
||||
"open_probability": round(open_probability, 4),
|
||||
"km_open": round(km_open, 2),
|
||||
"crowd_level": crowd_level,
|
||||
"weather_summary": weather_summary,
|
||||
"rule_overrides": rule_reasons,
|
||||
"prediction_source": prediction_source,
|
||||
}
|
||||
|
||||
logger.info(
|
||||
"Final prediction for '%s': open_prob=%.2f, km_open=%.1f, "
|
||||
"crowd=%s, source=%s",
|
||||
station_name,
|
||||
result["open_probability"],
|
||||
result["km_open"],
|
||||
result["crowd_level"],
|
||||
result["prediction_source"],
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _merge(
|
||||
self,
|
||||
station_id: str,
|
||||
station_name: str,
|
||||
force_closed: bool,
|
||||
force_open: bool,
|
||||
km_factor: float,
|
||||
rules_result: dict[str, Any],
|
||||
ml_result: dict[str, Any] | None,
|
||||
weather_data: dict[str, Any],
|
||||
) -> tuple[float, float, str, str]:
|
||||
"""Apply the merge strategy and return the four core prediction values.
|
||||
|
||||
Args:
|
||||
station_id: Station key used to retrieve max_km_skiable.
|
||||
station_name: Human-readable name for logging.
|
||||
force_closed: Whether the rules engine mandates closure.
|
||||
force_open: Whether the rules engine mandates opening.
|
||||
km_factor: Rules engine multiplier for km estimate (0–1).
|
||||
rules_result: Full dict returned by the rules engine.
|
||||
ml_result: Full dict returned by the ML predictor, or None.
|
||||
weather_data: Raw weather variables (used for crowd inference).
|
||||
|
||||
Returns:
|
||||
Tuple of (open_probability, km_open, crowd_level, prediction_source).
|
||||
"""
|
||||
# Load max km for this station to bound km_open
|
||||
max_km = self._get_max_km(station_id)
|
||||
|
||||
# ---- Deterministic closure --------------------------------------
|
||||
if force_closed:
|
||||
crowd_level = self._resolve_crowd(
|
||||
rules_result=rules_result,
|
||||
ml_result=None, # crowd is irrelevant when closed
|
||||
weather_data=weather_data,
|
||||
is_open=False,
|
||||
)
|
||||
return 0.0, 0.0, crowd_level, "rules"
|
||||
|
||||
# ---- Deterministic opening (e.g. heavy fresh snow) --------------
|
||||
if force_open:
|
||||
km_open = self._apply_km_factor(
|
||||
ml_km=ml_result.get("km_open_prediction") if ml_result else None,
|
||||
km_factor=km_factor,
|
||||
max_km=max_km,
|
||||
)
|
||||
crowd_level = self._resolve_crowd(
|
||||
rules_result=rules_result,
|
||||
ml_result=ml_result,
|
||||
weather_data=weather_data,
|
||||
is_open=True,
|
||||
)
|
||||
source = "hybrid" if ml_result else "rules"
|
||||
return 1.0, km_open, crowd_level, source
|
||||
|
||||
# ---- ML-driven prediction (rules inconclusive) ------------------
|
||||
if ml_result is not None:
|
||||
open_prob = ml_result.get("open_probability", _DEFAULT_OPEN_PROBABILITY)
|
||||
raw_km = ml_result.get("km_open_prediction")
|
||||
km_open = self._apply_km_factor(
|
||||
ml_km=raw_km,
|
||||
km_factor=km_factor,
|
||||
max_km=max_km,
|
||||
)
|
||||
crowd_level = self._resolve_crowd(
|
||||
rules_result=rules_result,
|
||||
ml_result=ml_result,
|
||||
weather_data=weather_data,
|
||||
is_open=open_prob >= 0.5,
|
||||
)
|
||||
|
||||
# km_factor < 1.0 means a soft rule also contributed
|
||||
source = "hybrid" if km_factor < 1.0 else "ml"
|
||||
return float(open_prob), km_open, crowd_level, source
|
||||
|
||||
# ---- Rules-only fallback (no ML models and no deterministic rule)
|
||||
logger.info(
|
||||
"[%s] No ML result and no deterministic rule; "
|
||||
"using rules confidence=%.2f as open_probability.",
|
||||
station_name,
|
||||
rules_result.get("confidence", 0.0),
|
||||
)
|
||||
open_prob = rules_result.get("confidence", _DEFAULT_OPEN_PROBABILITY)
|
||||
km_open = max_km * km_factor
|
||||
crowd_level = self._resolve_crowd(
|
||||
rules_result=rules_result,
|
||||
ml_result=None,
|
||||
weather_data=weather_data,
|
||||
is_open=open_prob >= 0.5,
|
||||
)
|
||||
return float(open_prob), km_open, crowd_level, "rules"
|
||||
|
||||
def _apply_km_factor(
|
||||
self,
|
||||
ml_km: float | None,
|
||||
km_factor: float,
|
||||
max_km: float,
|
||||
) -> float:
|
||||
"""Return km_open bounded by max_km and adjusted by km_factor.
|
||||
|
||||
Args:
|
||||
ml_km: Raw km prediction from the ML model. If None, max_km
|
||||
is used as a ceiling reference.
|
||||
km_factor: Multiplier from the rules engine (0–1).
|
||||
max_km: Maximum skiable km for the station.
|
||||
|
||||
Returns:
|
||||
Adjusted km value, clamped to [0, max_km].
|
||||
"""
|
||||
base = ml_km if ml_km is not None else max_km
|
||||
adjusted = base * km_factor
|
||||
clamped = max(0.0, min(adjusted, max_km))
|
||||
logger.debug(
|
||||
"km calculation: base=%.2f * factor=%.2f = %.2f (max=%.2f)",
|
||||
base,
|
||||
km_factor,
|
||||
adjusted,
|
||||
max_km,
|
||||
)
|
||||
return clamped
|
||||
|
||||
def _resolve_crowd(
|
||||
self,
|
||||
rules_result: dict[str, Any],
|
||||
ml_result: dict[str, Any] | None,
|
||||
weather_data: dict[str, Any],
|
||||
is_open: bool,
|
||||
) -> str:
|
||||
"""Determine the crowd level from available sources.
|
||||
|
||||
Priority:
|
||||
1. If station is closed -> "low" (no visitors).
|
||||
2. If the rules engine fired a crowd-related reason, infer
|
||||
from that reason.
|
||||
3. ML crowd_level if available.
|
||||
4. Calendar-based heuristic (weekend/holiday vs. weekday).
|
||||
5. Default: "medium".
|
||||
|
||||
Args:
|
||||
rules_result: Full rules engine output.
|
||||
ml_result: Full ML predictor output, or None.
|
||||
weather_data: Raw weather dict (for calendar features).
|
||||
is_open: Whether the station is predicted to open.
|
||||
|
||||
Returns:
|
||||
A crowd level string: ``"low"``, ``"medium"``, or ``"high"``.
|
||||
"""
|
||||
if not is_open:
|
||||
return "low"
|
||||
|
||||
reasons = rules_result.get("reasons", [])
|
||||
reasons_text = " ".join(reasons).lower()
|
||||
|
||||
# Infer crowd from rule reasons text
|
||||
if "high crowd" in reasons_text or "busy" in reasons_text:
|
||||
return "high"
|
||||
if "low crowd" in reasons_text:
|
||||
return "low"
|
||||
|
||||
# Use ML prediction if available
|
||||
if ml_result and "crowd_level" in ml_result:
|
||||
return str(ml_result["crowd_level"])
|
||||
|
||||
# Calendar heuristic
|
||||
is_weekend = bool(weather_data.get("is_weekend", False))
|
||||
is_holiday = bool(weather_data.get("is_holiday", False))
|
||||
if is_weekend or is_holiday:
|
||||
return "medium"
|
||||
|
||||
return _DEFAULT_CROWD_LEVEL
|
||||
|
||||
def _get_max_km(self, station_id: str) -> float:
|
||||
"""Return max_km_skiable for the given station from config.
|
||||
|
||||
Args:
|
||||
station_id: Station key in ``stations.yaml``.
|
||||
|
||||
Returns:
|
||||
The configured maximum skiable km, or 10.0 if it cannot be read.
|
||||
"""
|
||||
try:
|
||||
with self._config_path.open("r", encoding="utf-8") as fh:
|
||||
raw = yaml.safe_load(fh)
|
||||
return float(raw["stations"][station_id]["max_km_skiable"])
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.warning(
|
||||
"Could not read max_km_skiable for '%s': %s. Defaulting to 10.0.",
|
||||
station_id,
|
||||
exc,
|
||||
)
|
||||
return 10.0
|
||||
@@ -0,0 +1,293 @@
|
||||
"""ML-based predictor for ski station conditions.
|
||||
|
||||
Loads pre-trained models from the ml/models/ directory and generates
|
||||
probabilistic predictions for station opening, skiable kilometres, and
|
||||
crowd level. When models are absent the predictor degrades gracefully
|
||||
and returns None so callers can fall back to rule-based logic.
|
||||
|
||||
Expected model files under ml/models/:
|
||||
- open_model.joblib : binary classifier -> open_probability
|
||||
- km_model.joblib : regressor -> km_open_prediction
|
||||
- crowd_model.joblib : multiclass classifier -> crowd_level
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import joblib
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MODELS_DIR = Path(__file__).parent.parent / "ml" / "models"
|
||||
|
||||
_CROWD_LABELS: list[str] = ["low", "medium", "high"]
|
||||
|
||||
# Filename constants make it easy to swap model artefacts without touching logic
|
||||
_OPEN_MODEL_FILE = "station_open_model.joblib"
|
||||
_KM_MODEL_FILE = "km_open_model.joblib"
|
||||
_CROWD_MODEL_FILE = "crowd_level_model.joblib"
|
||||
_CROWD_ENCODER_FILE = "crowd_level_label_encoder.joblib"
|
||||
|
||||
|
||||
def _load_model(path: Path) -> Any | None:
|
||||
"""Load a joblib model artefact from disk.
|
||||
|
||||
Args:
|
||||
path: Absolute path to the ``.joblib`` file.
|
||||
|
||||
Returns:
|
||||
The deserialised model object, or None if the file does not exist
|
||||
or cannot be loaded.
|
||||
"""
|
||||
if not path.exists():
|
||||
logger.warning("Model file not found: %s", path)
|
||||
return None
|
||||
|
||||
try:
|
||||
model = joblib.load(path)
|
||||
logger.info("Loaded model from %s", path)
|
||||
return model
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("Failed to load model %s: %s", path, exc)
|
||||
return None
|
||||
|
||||
|
||||
class MLPredictor:
|
||||
"""Generates ML-based predictions for ski station conditions.
|
||||
|
||||
Models are loaded lazily from ``ml/models/`` the first time
|
||||
:meth:`predict` is called, or eagerly if ``eager_load=True`` is passed
|
||||
to the constructor.
|
||||
|
||||
When a required model file is missing the corresponding output field
|
||||
is omitted from the returned dict and a warning is logged. The caller
|
||||
(typically :class:`~predictor.hybrid_predictor.HybridPredictor`) must
|
||||
handle a ``None`` return gracefully.
|
||||
|
||||
Usage::
|
||||
|
||||
predictor = MLPredictor()
|
||||
result = predictor.predict(features_df)
|
||||
if result is None:
|
||||
# No models available; fall back to rules only
|
||||
...
|
||||
|
||||
Args:
|
||||
models_dir: Optional override for the directory containing model
|
||||
artefacts. Defaults to ``ml/models/`` in the repository
|
||||
root.
|
||||
eager_load: If True, models are loaded during ``__init__``.
|
||||
Defaults to False.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
models_dir: Path | None = None,
|
||||
eager_load: bool = False,
|
||||
) -> None:
|
||||
self._models_dir = Path(models_dir) if models_dir else _MODELS_DIR
|
||||
self._open_model: Any | None = None
|
||||
self._km_model: Any | None = None
|
||||
self._crowd_model: Any | None = None
|
||||
self._crowd_encoder: Any | None = None
|
||||
self._loaded = False
|
||||
|
||||
if eager_load:
|
||||
self._load_all_models()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _load_all_models(self) -> None:
|
||||
"""Load all model artefacts from disk."""
|
||||
self._open_model = _load_model(self._models_dir / _OPEN_MODEL_FILE)
|
||||
self._km_model = _load_model(self._models_dir / _KM_MODEL_FILE)
|
||||
self._crowd_model = _load_model(self._models_dir / _CROWD_MODEL_FILE)
|
||||
self._crowd_encoder = _load_model(self._models_dir / _CROWD_ENCODER_FILE)
|
||||
self._loaded = True
|
||||
|
||||
available = [
|
||||
name
|
||||
for name, mdl in [
|
||||
("open_model", self._open_model),
|
||||
("km_model", self._km_model),
|
||||
("crowd_model", self._crowd_model),
|
||||
]
|
||||
if mdl is not None
|
||||
]
|
||||
logger.info(
|
||||
"MLPredictor loaded %d/%d model(s): %s",
|
||||
len(available),
|
||||
3,
|
||||
available,
|
||||
)
|
||||
|
||||
def _ensure_loaded(self) -> None:
|
||||
"""Lazy-load models on first prediction call."""
|
||||
if not self._loaded:
|
||||
self._load_all_models()
|
||||
|
||||
def _prepare_features(self, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Select and align features to match the trained model inputs.
|
||||
|
||||
Drops non-feature columns (date, station_id, target variables) and
|
||||
fills any missing feature columns with 0.0 so the model always
|
||||
receives the expected input shape.
|
||||
"""
|
||||
# Determine expected features from the first available model
|
||||
ref_model = self._open_model or self._km_model or self._crowd_model
|
||||
if ref_model is None:
|
||||
return df
|
||||
|
||||
try:
|
||||
expected = list(ref_model.feature_names_in_)
|
||||
except AttributeError:
|
||||
# Fallback: drop known non-feature columns
|
||||
drop_cols = {
|
||||
"date", "station_id", "station_open", "open_status",
|
||||
"km_open", "crowd_level", "snow_quality", "season",
|
||||
}
|
||||
expected = [c for c in df.columns if c not in drop_cols]
|
||||
|
||||
# Select only expected columns, adding missing ones as 0
|
||||
result = pd.DataFrame(index=df.index)
|
||||
for col in expected:
|
||||
if col in df.columns:
|
||||
result[col] = pd.to_numeric(df[col], errors="coerce").fillna(0.0)
|
||||
else:
|
||||
result[col] = 0.0
|
||||
logger.debug("Feature '%s' missing in input; filled with 0.0.", col)
|
||||
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def predict(self, features_df: pd.DataFrame) -> dict[str, Any] | None:
|
||||
"""Generate predictions from a feature row.
|
||||
|
||||
Args:
|
||||
features_df: A ``pandas.DataFrame`` with exactly one row
|
||||
containing the engineered features for the prediction day.
|
||||
Column names must match those expected by the trained models
|
||||
(as defined in ``config/features.yaml``).
|
||||
|
||||
Returns:
|
||||
A dict with the following keys, or ``None`` if no models are
|
||||
available at all:
|
||||
|
||||
- ``open_probability`` (float 0–1): Probability the station opens.
|
||||
- ``km_open_prediction`` (float): Predicted km of open slopes.
|
||||
- ``crowd_level`` (str): Most likely crowd level
|
||||
(``"low"``, ``"medium"``, or ``"high"``).
|
||||
- ``crowd_probabilities`` (dict): Probability for each crowd
|
||||
level, e.g. ``{"low": 0.1, "medium": 0.4, "high": 0.5}``.
|
||||
|
||||
Any key whose model is missing is omitted from the dict.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``features_df`` is empty or has more than one row.
|
||||
"""
|
||||
if features_df is None or features_df.empty:
|
||||
raise ValueError("features_df must be a non-empty DataFrame.")
|
||||
if len(features_df) != 1:
|
||||
raise ValueError(
|
||||
f"features_df must contain exactly one row; got {len(features_df)}."
|
||||
)
|
||||
|
||||
self._ensure_loaded()
|
||||
|
||||
any_model_available = any(
|
||||
m is not None
|
||||
for m in [self._open_model, self._km_model, self._crowd_model]
|
||||
)
|
||||
if not any_model_available:
|
||||
logger.warning(
|
||||
"No ML models are available in %s. "
|
||||
"Returning None; hybrid predictor will rely on rules only.",
|
||||
self._models_dir,
|
||||
)
|
||||
return None
|
||||
|
||||
# Select only the features the models were trained on, dropping
|
||||
# non-feature columns (date, station_id, target variables, etc.).
|
||||
features_df = self._prepare_features(features_df)
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
|
||||
# ---- Open probability -------------------------------------------
|
||||
if self._open_model is not None:
|
||||
try:
|
||||
proba = self._open_model.predict_proba(features_df)
|
||||
# scikit-learn convention: class order matches model.classes_
|
||||
classes = list(self._open_model.classes_)
|
||||
open_idx = classes.index(1) if 1 in classes else -1
|
||||
open_prob = float(proba[0][open_idx]) if open_idx >= 0 else float(proba[0][1])
|
||||
result["open_probability"] = float(np.clip(open_prob, 0.0, 1.0))
|
||||
logger.debug("open_probability: %.3f", result["open_probability"])
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("open_model prediction failed: %s", exc)
|
||||
else:
|
||||
logger.warning("open_model not loaded; 'open_probability' will be absent.")
|
||||
|
||||
# ---- km open prediction -----------------------------------------
|
||||
if self._km_model is not None:
|
||||
try:
|
||||
km_pred = float(self._km_model.predict(features_df)[0])
|
||||
result["km_open_prediction"] = max(0.0, km_pred)
|
||||
logger.debug("km_open_prediction: %.2f", result["km_open_prediction"])
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("km_model prediction failed: %s", exc)
|
||||
else:
|
||||
logger.warning("km_model not loaded; 'km_open_prediction' will be absent.")
|
||||
|
||||
# ---- Crowd level -------------------------------------------------
|
||||
if self._crowd_model is not None:
|
||||
try:
|
||||
crowd_proba = self._crowd_model.predict_proba(features_df)[0]
|
||||
predicted_encoded = int(np.argmax(crowd_proba))
|
||||
|
||||
# Decode numeric class back to string label
|
||||
if self._crowd_encoder is not None:
|
||||
encoded_classes = list(self._crowd_model.classes_)
|
||||
decoded_classes = list(
|
||||
self._crowd_encoder.inverse_transform(encoded_classes)
|
||||
)
|
||||
predicted_crowd = str(
|
||||
self._crowd_encoder.inverse_transform(
|
||||
[encoded_classes[predicted_encoded]]
|
||||
)[0]
|
||||
)
|
||||
else:
|
||||
# Fallback: assume classes map directly to _CROWD_LABELS
|
||||
decoded_classes = _CROWD_LABELS[: len(self._crowd_model.classes_)]
|
||||
predicted_crowd = decoded_classes[predicted_encoded]
|
||||
|
||||
# Build probability dict aligned to canonical label order
|
||||
crowd_prob_dict: dict[str, float] = {}
|
||||
for i, label in enumerate(decoded_classes):
|
||||
crowd_prob_dict[label] = float(crowd_proba[i])
|
||||
# Ensure all canonical labels present
|
||||
for label in _CROWD_LABELS:
|
||||
if label not in crowd_prob_dict:
|
||||
crowd_prob_dict[label] = 0.0
|
||||
|
||||
result["crowd_level"] = predicted_crowd
|
||||
result["crowd_probabilities"] = crowd_prob_dict
|
||||
logger.debug(
|
||||
"crowd_level: %s | probabilities: %s",
|
||||
result["crowd_level"],
|
||||
crowd_prob_dict,
|
||||
)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logger.error("crowd_model prediction failed: %s", exc)
|
||||
else:
|
||||
logger.warning("crowd_model not loaded; crowd fields will be absent.")
|
||||
|
||||
logger.info("MLPredictor result keys: %s", list(result.keys()))
|
||||
return result if result else None
|
||||
@@ -0,0 +1,278 @@
|
||||
"""Rule-based engine for ski station predictions.
|
||||
|
||||
Evaluates physical and operational constraints for a given station and
|
||||
weather observation. Rules always take priority over ML predictions when
|
||||
conditions are deterministic (e.g. extreme wind, insufficient snow depth).
|
||||
|
||||
All thresholds are loaded from config/stations.yaml. No station-specific
|
||||
values are hardcoded in this module.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Path relative to repository root
|
||||
_CONFIG_PATH = Path(__file__).parent.parent / "config" / "stations.yaml"
|
||||
|
||||
# Temperature above which rain becomes operationally problematic
|
||||
_RAIN_TEMPERATURE_THRESHOLD_C = 10.0
|
||||
|
||||
# Precipitation threshold (mm) to be considered rain at high temperature
|
||||
_RAIN_PRECIPITATION_THRESHOLD_MM = 2.0
|
||||
|
||||
# Fresh snowfall (cm in 24 h) considered "heavy"
|
||||
_HEAVY_FRESH_SNOW_THRESHOLD_CM = 20.0
|
||||
|
||||
# Wind gust (km/h) considered "moderate" when combined with heavy snow
|
||||
_MODERATE_WIND_THRESHOLD_KMH = 40.0
|
||||
|
||||
# km_factor reduction applied when warm rain is detected
|
||||
_WARM_RAIN_KM_FACTOR_REDUCTION = 0.4
|
||||
|
||||
|
||||
def _load_station_configs() -> dict[str, Any]:
|
||||
"""Load all station configurations from stations.yaml.
|
||||
|
||||
Returns:
|
||||
A dict mapping station IDs to their configuration dicts.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If stations.yaml cannot be found.
|
||||
KeyError: If the 'stations' key is absent from the file.
|
||||
"""
|
||||
if not _CONFIG_PATH.exists():
|
||||
raise FileNotFoundError(f"Station config not found: {_CONFIG_PATH}")
|
||||
|
||||
with _CONFIG_PATH.open("r", encoding="utf-8") as fh:
|
||||
raw = yaml.safe_load(fh)
|
||||
|
||||
if "stations" not in raw:
|
||||
raise KeyError(f"'stations' key missing in {_CONFIG_PATH}")
|
||||
|
||||
logger.debug("Loaded station configs for: %s", list(raw["stations"].keys()))
|
||||
return raw["stations"]
|
||||
|
||||
|
||||
class RulesEngine:
|
||||
"""Evaluates operational rule constraints for a ski station.
|
||||
|
||||
Rules are deterministic: when a rule fires, the outcome is certain
|
||||
regardless of what the ML model predicts. Rules are derived exclusively
|
||||
from the station configuration file so they remain configurable without
|
||||
code changes.
|
||||
|
||||
Usage::
|
||||
|
||||
engine = RulesEngine()
|
||||
result = engine.evaluate("pajares", weather_data)
|
||||
|
||||
Args:
|
||||
config_path: Optional override for the path to stations.yaml.
|
||||
Defaults to config/stations.yaml in the repository root.
|
||||
"""
|
||||
|
||||
def __init__(self, config_path: Path | None = None) -> None:
|
||||
effective_path = config_path or _CONFIG_PATH
|
||||
if config_path:
|
||||
# Re-read from custom path
|
||||
with Path(effective_path).open("r", encoding="utf-8") as fh:
|
||||
raw = yaml.safe_load(fh)
|
||||
self._stations = raw.get("stations", {})
|
||||
else:
|
||||
self._stations = _load_station_configs()
|
||||
|
||||
logger.info(
|
||||
"RulesEngine initialised with %d station(s): %s",
|
||||
len(self._stations),
|
||||
list(self._stations.keys()),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def evaluate(self, station_id: str, weather_data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Evaluate rule-based constraints for a station and weather snapshot.
|
||||
|
||||
Args:
|
||||
station_id: Key identifying the station in stations.yaml
|
||||
(e.g. ``"pajares"``).
|
||||
weather_data: Dict of weather variables for the prediction day.
|
||||
Expected keys (all optional; missing keys are skipped):
|
||||
- ``wind_gusts_10m_max`` (float, km/h)
|
||||
- ``snow_depth`` (float, cm)
|
||||
- ``snowfall_sum`` (float, cm in last 24 h)
|
||||
- ``temperature_2m_max`` (float, °C)
|
||||
- ``precipitation_sum`` (float, mm)
|
||||
- ``is_weekend`` (bool or int 0/1)
|
||||
- ``is_holiday`` (bool or int 0/1)
|
||||
|
||||
Returns:
|
||||
A dict with the following keys:
|
||||
|
||||
- ``force_closed`` (bool): Rule mandates the station is closed.
|
||||
- ``force_open`` (bool): Rule mandates the station is open
|
||||
(reserved for future use; currently always False).
|
||||
- ``confidence`` (float 0–1): How certain the rule engine is
|
||||
about its assessment. 1.0 when a force_closed or force_open
|
||||
rule fires; lower when only soft rules apply.
|
||||
- ``reasons`` (list[str]): Human-readable explanations for
|
||||
each rule that fired.
|
||||
- ``estimated_km_factor`` (float 0–1): Multiplier to apply to
|
||||
the maximum skiable km. 1.0 = all slopes available, 0.0 =
|
||||
none.
|
||||
|
||||
Raises:
|
||||
ValueError: If station_id is not present in the configuration.
|
||||
"""
|
||||
if station_id not in self._stations:
|
||||
raise ValueError(
|
||||
f"Unknown station '{station_id}'. "
|
||||
f"Known stations: {list(self._stations.keys())}"
|
||||
)
|
||||
|
||||
config = self._stations[station_id]
|
||||
station_name = config.get("name", station_id)
|
||||
|
||||
logger.debug(
|
||||
"Evaluating rules for '%s' with weather_data keys: %s",
|
||||
station_name,
|
||||
list(weather_data.keys()),
|
||||
)
|
||||
|
||||
force_closed = False
|
||||
force_open = False
|
||||
reasons: list[str] = []
|
||||
km_factor = 1.0
|
||||
|
||||
# ---- Rule 1: Extreme wind gust -> force close --------------------
|
||||
wind_gust = weather_data.get("wind_gusts_10m_max")
|
||||
wind_threshold = config["wind_closure_threshold"]
|
||||
|
||||
if wind_gust is not None:
|
||||
if wind_gust >= wind_threshold:
|
||||
force_closed = True
|
||||
reasons.append(
|
||||
f"Wind gust {wind_gust:.1f} km/h exceeds closure threshold "
|
||||
f"of {wind_threshold} km/h."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 1 fired: wind gust %.1f > %.1f km/h -> force_closed",
|
||||
station_name,
|
||||
wind_gust,
|
||||
wind_threshold,
|
||||
)
|
||||
|
||||
# ---- Rule 2: Snow depth below minimum -> force close -------------
|
||||
snow_depth = weather_data.get("snow_depth")
|
||||
min_snow = config["minimum_snow_depth"]
|
||||
|
||||
if snow_depth is not None:
|
||||
if snow_depth < min_snow:
|
||||
force_closed = True
|
||||
km_factor = 0.0
|
||||
reasons.append(
|
||||
f"Snow depth {snow_depth:.1f} cm is below the minimum "
|
||||
f"required {min_snow} cm."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 2 fired: snow depth %.1f < %.1f cm -> force_closed",
|
||||
station_name,
|
||||
snow_depth,
|
||||
min_snow,
|
||||
)
|
||||
|
||||
# ---- Rule 3: High temperature + rain -> reduce km_factor ---------
|
||||
temp_max = weather_data.get("temperature_2m_max")
|
||||
precip = weather_data.get("precipitation_sum", 0.0)
|
||||
|
||||
if (
|
||||
temp_max is not None
|
||||
and temp_max > _RAIN_TEMPERATURE_THRESHOLD_C
|
||||
and precip > _RAIN_PRECIPITATION_THRESHOLD_MM
|
||||
):
|
||||
km_factor = max(0.0, km_factor - _WARM_RAIN_KM_FACTOR_REDUCTION)
|
||||
reasons.append(
|
||||
f"Temperature {temp_max:.1f} °C above {_RAIN_TEMPERATURE_THRESHOLD_C} °C "
|
||||
f"with {precip:.1f} mm precipitation; estimated open slopes reduced."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 3 fired: temp %.1f °C + rain %.1f mm -> km_factor reduced to %.2f",
|
||||
station_name,
|
||||
temp_max,
|
||||
precip,
|
||||
km_factor,
|
||||
)
|
||||
|
||||
# ---- Rule 4: Heavy fresh snow + moderate wind -> likely open -----
|
||||
snowfall_24h = weather_data.get("snowfall_sum")
|
||||
wind_speed = weather_data.get("wind_gusts_10m_max", 0.0)
|
||||
|
||||
if (
|
||||
snowfall_24h is not None
|
||||
and snowfall_24h >= _HEAVY_FRESH_SNOW_THRESHOLD_CM
|
||||
and wind_speed is not None
|
||||
and wind_speed <= _MODERATE_WIND_THRESHOLD_KMH
|
||||
and not force_closed
|
||||
):
|
||||
force_open = True
|
||||
reasons.append(
|
||||
f"Heavy fresh snow ({snowfall_24h:.1f} cm in 24 h) with manageable "
|
||||
f"wind ({wind_speed:.1f} km/h); station very likely open and busy."
|
||||
)
|
||||
logger.info(
|
||||
"[%s] Rule 4 fired: heavy snow %.1f cm + wind %.1f km/h -> force_open",
|
||||
station_name,
|
||||
snowfall_24h,
|
||||
wind_speed,
|
||||
)
|
||||
|
||||
# ---- Rule 5: Weekday + no fresh snow -> low crowd ----------------
|
||||
is_weekend = bool(weather_data.get("is_weekend", False))
|
||||
is_holiday = bool(weather_data.get("is_holiday", False))
|
||||
is_busy_day = is_weekend or is_holiday
|
||||
no_fresh_snow = (snowfall_24h is None or snowfall_24h < 5.0)
|
||||
|
||||
if not is_busy_day and no_fresh_snow and not force_closed:
|
||||
reasons.append(
|
||||
"Weekday with no significant fresh snow; crowd level expected to be low."
|
||||
)
|
||||
logger.debug("[%s] Rule 5 fired: weekday + no fresh snow -> low crowd", station_name)
|
||||
|
||||
# ---- Rule 6: Weekend/holiday + fresh snow -> high crowd ----------
|
||||
if is_busy_day and snowfall_24h is not None and snowfall_24h >= 5.0 and not force_closed:
|
||||
reasons.append(
|
||||
f"Weekend or holiday with {snowfall_24h:.1f} cm of fresh snow; "
|
||||
"crowd level expected to be high."
|
||||
)
|
||||
logger.debug(
|
||||
"[%s] Rule 6 fired: busy day + fresh snow %.1f cm -> high crowd",
|
||||
station_name,
|
||||
snowfall_24h,
|
||||
)
|
||||
|
||||
# ---- Derive confidence -------------------------------------------
|
||||
if force_closed or force_open:
|
||||
confidence = 1.0
|
||||
elif reasons:
|
||||
# Soft rules fired but no deterministic outcome
|
||||
confidence = 0.6
|
||||
else:
|
||||
# No rules fired; rules engine is inconclusive
|
||||
confidence = 0.0
|
||||
|
||||
result = {
|
||||
"force_closed": force_closed,
|
||||
"force_open": force_open,
|
||||
"confidence": confidence,
|
||||
"reasons": reasons,
|
||||
"estimated_km_factor": km_factor,
|
||||
}
|
||||
|
||||
logger.debug("[%s] Rules result: %s", station_name, result)
|
||||
return result
|
||||
@@ -0,0 +1,13 @@
|
||||
requests>=2.31.0
|
||||
pandas>=2.1.0
|
||||
numpy>=1.24.0
|
||||
scikit-learn>=1.3.0
|
||||
lightgbm>=4.0.0
|
||||
pyyaml>=6.0
|
||||
python-telegram-bot>=20.0
|
||||
beautifulsoup4>=4.12.0
|
||||
lxml>=4.9.0
|
||||
schedule>=1.2.0
|
||||
joblib>=1.3.0
|
||||
ultralytics>=8.0.0
|
||||
opencv-python-headless>=4.8.0
|
||||
@@ -0,0 +1 @@
|
||||
"""Scripts package for ski predictor automation tasks."""
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Build the full historical dataset by merging station data with weather.
|
||||
|
||||
Steps:
|
||||
1. Load historical station CSV from infonieve.es (data/raw/station_historical_all.csv)
|
||||
2. Map infonieve columns to the project schema
|
||||
3. Fetch historical weather from Open-Meteo for 2009-2026 in 1-year chunks
|
||||
4. Merge weather + station data on (date, station_id)
|
||||
5. Run feature engineering
|
||||
6. Save to data/processed/dataset_featured.csv
|
||||
7. Train ML models
|
||||
|
||||
Column mapping from infonieve schema to project schema:
|
||||
closedflag / idestado -> open_status (1=open, 0=closed)
|
||||
kmopen -> km_open
|
||||
pistasopen -> lifts_open (actually slopes, but matches schema)
|
||||
espesormax -> snow_depth
|
||||
calidadnieve -> snow_quality
|
||||
pistasopen/pistastotal ratio -> crowd_level (low/medium/high)
|
||||
open_status + km_open -> station_open (ML target alias)
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Path setup - add repo root to sys.path so project modules are importable
|
||||
# ---------------------------------------------------------------------------
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from data_sources.weather_api import WeatherCollector
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
from ml.train_model import ModelTrainer
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Logging
|
||||
# ---------------------------------------------------------------------------
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
STATION_CSV = REPO_ROOT / "data" / "raw" / "station_historical_all.csv"
|
||||
OUTPUT_DIR = REPO_ROOT / "data" / "processed"
|
||||
OUTPUT_PATH = OUTPUT_DIR / "dataset_featured.csv"
|
||||
|
||||
# Weather fetch range - driven by what is in the station data
|
||||
WEATHER_START_YEAR = 2009
|
||||
WEATHER_END_YEAR = 2026 # inclusive
|
||||
|
||||
# Crowd level thresholds based on pistas open / pistas total ratio
|
||||
CROWD_LOW_THRESHOLD = 0.33
|
||||
CROWD_HIGH_THRESHOLD = 0.67
|
||||
|
||||
# Station coordinates from config/stations.yaml
|
||||
STATIONS = {
|
||||
"fuentes": {"latitude": 43.0833, "longitude": -5.9333},
|
||||
"pajares": {"latitude": 43.0500, "longitude": -5.7700},
|
||||
"sanisidro": {"latitude": 43.0700, "longitude": -5.3700},
|
||||
}
|
||||
|
||||
# Delay between API calls to avoid rate-limiting (seconds)
|
||||
API_CALL_DELAY = 3.0
|
||||
|
||||
# Extra pause between stations (seconds)
|
||||
INTER_STATION_DELAY = 10.0
|
||||
|
||||
# Local cache directory for per-year weather chunks
|
||||
WEATHER_CACHE_DIR = REPO_ROOT / "data" / "raw" / "weather_cache"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 1: Load and map station data
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def load_station_data() -> pd.DataFrame:
|
||||
"""Load the infonieve historical CSV and map columns to project schema."""
|
||||
logger.info("Loading station data from %s", STATION_CSV)
|
||||
df = pd.read_csv(STATION_CSV)
|
||||
logger.info("Loaded %d rows, %d columns", len(df), len(df.columns))
|
||||
|
||||
# Parse dates with mixed formats (ISO and day-first variants)
|
||||
df["date"] = pd.to_datetime(df["date"], format="mixed", dayfirst=True)
|
||||
|
||||
# ---------- open_status ----------
|
||||
# idestado=1: open (normal operation)
|
||||
# idestado=4: open (special/summer operation, some km data present)
|
||||
# idestado=0: closed (no operation that day)
|
||||
# idestado=2: off-season (not yet / no longer open)
|
||||
# idestado=3: temporarily closed (weather/maintenance)
|
||||
# Best signal: station is open if kmopen > 0, else use idestado
|
||||
df["open_status"] = 0
|
||||
has_km_data = df["kmopen"].notna() & (df["kmopen"] > 0)
|
||||
df.loc[has_km_data, "open_status"] = 1
|
||||
# Also mark idestado=1 rows where kmopen may be missing as open
|
||||
df.loc[(df["idestado"] == 1.0) & ~has_km_data, "open_status"] = 1
|
||||
|
||||
# station_open is the ML binary classification target (same as open_status)
|
||||
df["station_open"] = df["open_status"]
|
||||
|
||||
# ---------- km_open ----------
|
||||
df["km_open"] = pd.to_numeric(df["kmopen"], errors="coerce")
|
||||
|
||||
# ---------- lifts_open (slopes in this dataset) ----------
|
||||
df["lifts_open"] = pd.to_numeric(df["pistasopen"], errors="coerce")
|
||||
|
||||
# ---------- snow_depth ----------
|
||||
df["snow_depth"] = pd.to_numeric(df["espesormax"], errors="coerce")
|
||||
|
||||
# ---------- snow_quality ----------
|
||||
df["snow_quality"] = df["calidadnieve"].astype(str)
|
||||
df.loc[df["snow_quality"] == "nan", "snow_quality"] = None
|
||||
|
||||
# ---------- crowd_level ----------
|
||||
# Derived from fraction of slopes open vs total available
|
||||
pistastotal = pd.to_numeric(df["pistastotal"], errors="coerce")
|
||||
pistasopen = pd.to_numeric(df["pistasopen"], errors="coerce")
|
||||
ratio = pistasopen / pistastotal.replace(0, float("nan"))
|
||||
|
||||
crowd = pd.Series(index=df.index, dtype="object")
|
||||
crowd[ratio < CROWD_LOW_THRESHOLD] = "low"
|
||||
crowd[(ratio >= CROWD_LOW_THRESHOLD) & (ratio < CROWD_HIGH_THRESHOLD)] = "medium"
|
||||
crowd[ratio >= CROWD_HIGH_THRESHOLD] = "high"
|
||||
# Only assign crowd_level when the station is open
|
||||
df["crowd_level"] = None
|
||||
df.loc[df["open_status"] == 1, "crowd_level"] = crowd[df["open_status"] == 1]
|
||||
|
||||
# Keep only the columns needed for merging
|
||||
keep = [
|
||||
"date", "station_id",
|
||||
"open_status", "station_open",
|
||||
"km_open", "lifts_open",
|
||||
"snow_depth", "snow_quality",
|
||||
"crowd_level",
|
||||
]
|
||||
result = df[keep].copy()
|
||||
result = result.sort_values(["station_id", "date"]).reset_index(drop=True)
|
||||
|
||||
logger.info(
|
||||
"Station data mapped. Open rows: %d / %d",
|
||||
(result["open_status"] == 1).sum(),
|
||||
len(result),
|
||||
)
|
||||
logger.info(
|
||||
"crowd_level distribution:\n%s",
|
||||
result["crowd_level"].value_counts(),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 2: Fetch historical weather in 1-year chunks
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _cache_path(station_id: str, year: int) -> Path:
|
||||
"""Return the local cache file path for a (station, year) chunk."""
|
||||
return WEATHER_CACHE_DIR / f"weather_{station_id}_{year}.csv"
|
||||
|
||||
|
||||
def fetch_weather_all_stations() -> pd.DataFrame:
|
||||
"""Fetch full historical weather for all stations in annual chunks.
|
||||
|
||||
Each (station, year) chunk is cached to
|
||||
``data/raw/weather_cache/weather_{station_id}_{year}.csv``.
|
||||
If the cache file already exists the API call is skipped, making
|
||||
reruns fast and avoiding rate-limit exhaustion.
|
||||
|
||||
The current year's cache is always refreshed (partial year grows daily).
|
||||
"""
|
||||
WEATHER_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
collector = WeatherCollector()
|
||||
all_frames: list[pd.DataFrame] = []
|
||||
|
||||
today = date.today()
|
||||
end_year = min(WEATHER_END_YEAR, today.year)
|
||||
|
||||
for station_id, coords in STATIONS.items():
|
||||
lat = coords["latitude"]
|
||||
lon = coords["longitude"]
|
||||
station_frames: list[pd.DataFrame] = []
|
||||
needs_api_call = False
|
||||
|
||||
for year in range(WEATHER_START_YEAR, end_year + 1):
|
||||
cache_file = _cache_path(station_id, year)
|
||||
start_date = f"{year}-01-01"
|
||||
|
||||
# For the current partial year always refresh the cache
|
||||
is_current_year = year == today.year
|
||||
if cache_file.exists() and not is_current_year:
|
||||
logger.info(
|
||||
"Cache hit: %s (skipping API call)", cache_file.name
|
||||
)
|
||||
df = pd.read_csv(cache_file)
|
||||
df["date"] = pd.to_datetime(df["date"])
|
||||
station_frames.append(df)
|
||||
continue
|
||||
|
||||
# For the current year, only fetch up to yesterday
|
||||
if is_current_year:
|
||||
from datetime import timedelta
|
||||
yesterday = today - timedelta(days=1)
|
||||
end_date = yesterday.strftime("%Y-%m-%d")
|
||||
else:
|
||||
end_date = f"{year}-12-31"
|
||||
|
||||
logger.info(
|
||||
"Fetching weather for station=%s year=%d (%s to %s)",
|
||||
station_id, year, start_date, end_date,
|
||||
)
|
||||
needs_api_call = True
|
||||
|
||||
try:
|
||||
df = collector.get_historical(
|
||||
station_id=station_id,
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
)
|
||||
if not df.empty:
|
||||
df["date"] = pd.to_datetime(df["date"])
|
||||
# Save to per-year cache (not the rolling weather_X_today.csv)
|
||||
df.to_csv(cache_file, index=False)
|
||||
logger.info(
|
||||
" -> Got %d rows; cached to %s",
|
||||
len(df), cache_file.name,
|
||||
)
|
||||
station_frames.append(df)
|
||||
except RuntimeError as exc:
|
||||
logger.error(
|
||||
"Weather fetch failed for station=%s year=%d: %s",
|
||||
station_id, year, exc,
|
||||
)
|
||||
|
||||
# Be polite to the API between calls
|
||||
time.sleep(API_CALL_DELAY)
|
||||
|
||||
if station_frames:
|
||||
combined = pd.concat(station_frames, ignore_index=True)
|
||||
combined["date"] = pd.to_datetime(combined["date"])
|
||||
combined.drop_duplicates(subset=["date", "station_id"], inplace=True)
|
||||
combined.sort_values("date", inplace=True)
|
||||
all_frames.append(combined)
|
||||
logger.info(
|
||||
"Total weather rows for %s: %d", station_id, len(combined)
|
||||
)
|
||||
|
||||
if needs_api_call:
|
||||
# Only pause if we actually made API calls for this station
|
||||
logger.info("Pausing %ds before next station.", INTER_STATION_DELAY)
|
||||
time.sleep(INTER_STATION_DELAY)
|
||||
|
||||
if not all_frames:
|
||||
raise RuntimeError("No weather data fetched for any station.")
|
||||
|
||||
weather = pd.concat(all_frames, ignore_index=True)
|
||||
weather["date"] = pd.to_datetime(weather["date"])
|
||||
logger.info("Total weather rows across all stations: %d", len(weather))
|
||||
return weather
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 3: Merge weather + station data
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def merge_datasets(
|
||||
weather_df: pd.DataFrame,
|
||||
station_df: pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""Outer-merge weather and station frames on (date, station_id)."""
|
||||
logger.info(
|
||||
"Merging weather (%d rows) with station (%d rows).",
|
||||
len(weather_df), len(station_df),
|
||||
)
|
||||
|
||||
# Normalise date type for both frames before merging
|
||||
weather_df = weather_df.copy()
|
||||
station_df = station_df.copy()
|
||||
weather_df["date"] = pd.to_datetime(weather_df["date"])
|
||||
station_df["date"] = pd.to_datetime(station_df["date"])
|
||||
|
||||
merged = pd.merge(
|
||||
weather_df,
|
||||
station_df,
|
||||
on=["date", "station_id"],
|
||||
how="outer",
|
||||
)
|
||||
merged = merged.sort_values(["station_id", "date"]).reset_index(drop=True)
|
||||
logger.info("Merged dataset shape: %s", merged.shape)
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 4: Feature engineering
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run_feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Apply the standard feature engineering pipeline."""
|
||||
logger.info("Running feature engineering on %d rows.", len(df))
|
||||
engineer = FeatureEngineer()
|
||||
featured = engineer.transform(df)
|
||||
logger.info(
|
||||
"Feature engineering complete. Output shape: %s", featured.shape
|
||||
)
|
||||
return featured
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 5: Save
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def save_dataset(df: pd.DataFrame) -> None:
|
||||
"""Persist the featured dataset to disk."""
|
||||
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
df.to_csv(OUTPUT_PATH, index=False)
|
||||
logger.info("Featured dataset saved to %s (%d rows)", OUTPUT_PATH, len(df))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Step 6: Summary statistics
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def print_summary(df: pd.DataFrame) -> None:
|
||||
"""Print summary statistics about the final dataset."""
|
||||
print("\n" + "=" * 60)
|
||||
print("DATASET SUMMARY")
|
||||
print("=" * 60)
|
||||
print(f"Total rows: {len(df):,}")
|
||||
print(f"Total columns: {len(df.columns)}")
|
||||
print(f"Date range: {df['date'].min().date()} to {df['date'].max().date()}")
|
||||
print(f"Stations: {sorted(df['station_id'].unique())}")
|
||||
print()
|
||||
print("Rows per station:")
|
||||
for sid, count in df.groupby("station_id").size().items():
|
||||
print(f" {sid}: {count:,}")
|
||||
print()
|
||||
|
||||
if "station_open" in df.columns:
|
||||
open_rows = df["station_open"].notna()
|
||||
total_labeled = open_rows.sum()
|
||||
open_count = (df.loc[open_rows, "station_open"] == 1).sum()
|
||||
closed_count = (df.loc[open_rows, "station_open"] == 0).sum()
|
||||
print(f"station_open labels: {total_labeled:,} total")
|
||||
print(f" open: {open_count:,} ({100*open_count/total_labeled:.1f}%)")
|
||||
print(f" closed: {closed_count:,} ({100*closed_count/total_labeled:.1f}%)")
|
||||
print()
|
||||
|
||||
if "crowd_level" in df.columns:
|
||||
crowd_dist = df["crowd_level"].value_counts()
|
||||
print("crowd_level distribution:")
|
||||
for level, cnt in crowd_dist.items():
|
||||
print(f" {level}: {cnt:,}")
|
||||
print()
|
||||
|
||||
if "km_open" in df.columns:
|
||||
km = df["km_open"].dropna()
|
||||
print(f"km_open stats (non-null, n={len(km):,}):")
|
||||
print(f" mean={km.mean():.2f} median={km.median():.2f} "
|
||||
f"min={km.min():.2f} max={km.max():.2f}")
|
||||
print()
|
||||
|
||||
if "snow_depth" in df.columns:
|
||||
sd = df["snow_depth"].dropna()
|
||||
print(f"snow_depth stats (non-null, n={len(sd):,}):")
|
||||
print(f" mean={sd.mean():.1f}cm max={sd.max():.1f}cm")
|
||||
print()
|
||||
|
||||
missing_pct = 100 * df.isnull().sum() / len(df)
|
||||
high_missing = missing_pct[missing_pct > 20].sort_values(ascending=False)
|
||||
if not high_missing.empty:
|
||||
print("Columns with >20% missing values:")
|
||||
for col, pct in high_missing.items():
|
||||
print(f" {col}: {pct:.1f}%")
|
||||
else:
|
||||
print("No columns with >20% missing values.")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def main() -> None:
|
||||
logger.info("Starting full dataset build pipeline.")
|
||||
|
||||
# Step 1: Load and map station data
|
||||
station_df = load_station_data()
|
||||
|
||||
# Step 2: Fetch historical weather
|
||||
weather_df = fetch_weather_all_stations()
|
||||
|
||||
# Step 3: Merge
|
||||
merged = merge_datasets(weather_df, station_df)
|
||||
|
||||
# Step 4: Feature engineering
|
||||
featured = run_feature_engineering(merged)
|
||||
|
||||
# Step 5: Save
|
||||
save_dataset(featured)
|
||||
|
||||
# Step 6: Summary
|
||||
print_summary(featured)
|
||||
|
||||
# Step 7: Train models
|
||||
logger.info("Starting model training on the full dataset.")
|
||||
trainer = ModelTrainer(dataset_path=OUTPUT_PATH)
|
||||
cv_results = trainer.train_all()
|
||||
|
||||
print("\nCROSS-VALIDATION RESULTS")
|
||||
print("=" * 60)
|
||||
for target, scores in cv_results.items():
|
||||
print(f"\n {target}:")
|
||||
for metric, value in scores.items():
|
||||
print(f" {metric}: {value:.4f}")
|
||||
print("=" * 60)
|
||||
|
||||
logger.info("Pipeline complete.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,267 @@
|
||||
"""Daily data collection pipeline for the ski predictor.
|
||||
|
||||
This script is designed for cron execution. It runs every day to:
|
||||
|
||||
1. Collect weather forecasts for all configured stations.
|
||||
2. Collect current station operational status.
|
||||
3. Append new rows to the processed dataset.
|
||||
4. Run feature engineering on the updated dataset.
|
||||
5. Generate predictions for the next day using the HybridPredictor.
|
||||
6. Save the predictions to data/processed/predictions_latest.json.
|
||||
|
||||
Cron example (run daily at 20:00, after stations close):
|
||||
0 20 * * * /path/to/.venv/bin/python /path/to/scripts/collect_daily_data.py
|
||||
|
||||
Exit codes:
|
||||
0 - Pipeline completed (partial failures are logged but do not abort).
|
||||
1 - Fatal error that prevented any useful work.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Ensure the project root is on sys.path so all project packages are
|
||||
# importable when this script is executed directly (e.g. via cron or CLI).
|
||||
# ---------------------------------------------------------------------------
|
||||
_SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
_PROJECT_ROOT = _SCRIPT_DIR.parent
|
||||
if str(_PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_PROJECT_ROOT))
|
||||
|
||||
from data_sources.weather_api import WeatherCollector
|
||||
from data_sources.station_scraper import StationScraper
|
||||
from pipeline.build_dataset import DatasetBuilder
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
from predictor.hybrid_predictor import HybridPredictor
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Logging setup
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Output paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
|
||||
_DATASET_PATH = _PROCESSED_DIR / "dataset.csv"
|
||||
_FEATURED_PATH = _PROCESSED_DIR / "dataset_featured.csv"
|
||||
_PREDICTIONS_PATH = _PROCESSED_DIR / "predictions_latest.json"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pipeline steps
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def collect_weather(collector: WeatherCollector) -> dict[str, pd.DataFrame]:
|
||||
"""Fetch weather forecasts for all stations."""
|
||||
logger.info("Step 1/5 - Collecting weather forecasts.")
|
||||
results = {}
|
||||
for station_id, cfg in collector.stations.items():
|
||||
try:
|
||||
df = collector.get_forecast(station_id, cfg["latitude"], cfg["longitude"])
|
||||
results[station_id] = df
|
||||
logger.info("Weather forecast: station=%s, %d rows.", station_id, len(df))
|
||||
except Exception as exc:
|
||||
logger.error("Weather failed for %s: %s", station_id, exc)
|
||||
return results
|
||||
|
||||
|
||||
def collect_station_status(scraper: StationScraper) -> list[dict]:
|
||||
"""Scrape current operational status for all stations."""
|
||||
logger.info("Step 2/5 - Collecting station status.")
|
||||
records = []
|
||||
for station_id in scraper._stations:
|
||||
try:
|
||||
record = scraper.scrape_station(station_id)
|
||||
records.append(record)
|
||||
logger.info(
|
||||
"Station status: %s open=%s km=%s depth=%s",
|
||||
station_id, record.get("open_status"),
|
||||
record.get("km_open"), record.get("snow_depth"),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Scraping failed for %s: %s", station_id, exc)
|
||||
return records
|
||||
|
||||
|
||||
def append_to_dataset(
|
||||
builder: DatasetBuilder,
|
||||
weather_by_station: dict[str, pd.DataFrame],
|
||||
station_records: list[dict],
|
||||
) -> pd.DataFrame:
|
||||
"""Append today's data to the processed dataset."""
|
||||
logger.info("Step 3/5 - Appending data to dataset.")
|
||||
station_map = {r["station_id"]: r for r in station_records}
|
||||
today = date.today()
|
||||
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
station_record = station_map.get(station_id)
|
||||
if station_record is None:
|
||||
logger.warning("No station record for %s, skipping.", station_id)
|
||||
continue
|
||||
|
||||
# Use today's forecast row for the weather data
|
||||
today_rows = weather_df[weather_df["date"] == today]
|
||||
if today_rows.empty:
|
||||
# Fallback to first available row
|
||||
today_rows = weather_df.head(1)
|
||||
|
||||
weather_row = today_rows.iloc[0].to_dict()
|
||||
|
||||
try:
|
||||
builder.append_daily(weather_data=weather_row, station_data=station_record)
|
||||
logger.info("Dataset updated for %s.", station_id)
|
||||
except Exception as exc:
|
||||
logger.error("Append failed for %s: %s", station_id, exc)
|
||||
|
||||
# Return the current dataset
|
||||
if _DATASET_PATH.exists():
|
||||
df = pd.read_csv(_DATASET_PATH)
|
||||
df["date"] = pd.to_datetime(df["date"])
|
||||
return df
|
||||
return pd.DataFrame()
|
||||
|
||||
|
||||
def run_feature_engineering(engineer: FeatureEngineer, df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Run feature engineering on the dataset."""
|
||||
logger.info("Step 4/5 - Running feature engineering.")
|
||||
if df.empty:
|
||||
logger.warning("Empty dataset, skipping feature engineering.")
|
||||
return df
|
||||
|
||||
featured = engineer.transform(df)
|
||||
_PROCESSED_DIR.mkdir(parents=True, exist_ok=True)
|
||||
featured.to_csv(_FEATURED_PATH, index=False)
|
||||
logger.info("Featured dataset saved: %d rows, %d cols.", len(featured), len(featured.columns))
|
||||
return featured
|
||||
|
||||
|
||||
def generate_predictions(
|
||||
predictor: HybridPredictor,
|
||||
weather_by_station: dict[str, pd.DataFrame],
|
||||
featured_df: pd.DataFrame,
|
||||
station_records: list[dict],
|
||||
) -> None:
|
||||
"""Generate next-day predictions and save to disk."""
|
||||
logger.info("Step 5/5 - Generating predictions.")
|
||||
tomorrow = date.today() + timedelta(days=1)
|
||||
predictions = {}
|
||||
station_map = {r["station_id"]: r for r in station_records}
|
||||
|
||||
for station_id, weather_df in weather_by_station.items():
|
||||
# Get tomorrow's forecast row as weather_data dict
|
||||
tomorrow_rows = weather_df[weather_df["date"] == tomorrow]
|
||||
if tomorrow_rows.empty:
|
||||
tomorrow_rows = weather_df.iloc[1:2]
|
||||
if tomorrow_rows.empty:
|
||||
logger.warning("No forecast for tomorrow for %s.", station_id)
|
||||
continue
|
||||
|
||||
weather_data = tomorrow_rows.iloc[0].to_dict()
|
||||
|
||||
# Build a feature row: tomorrow's weather + today's station data
|
||||
# (lifts_open, snow_depth are current observations - best proxy for tomorrow)
|
||||
features_df = None
|
||||
if not featured_df.empty:
|
||||
station_featured = featured_df[featured_df["station_id"] == station_id]
|
||||
if not station_featured.empty:
|
||||
# Start from the latest featured row (has rolling features)
|
||||
features_df = station_featured.tail(1).copy()
|
||||
# Overlay tomorrow's weather
|
||||
for col in weather_data:
|
||||
if col in features_df.columns and col not in ("date", "station_id"):
|
||||
features_df[col] = weather_data[col]
|
||||
# Overlay today's station data as best proxy
|
||||
station_rec = station_map.get(station_id, {})
|
||||
if station_rec.get("snow_depth") is not None:
|
||||
features_df["snow_depth"] = station_rec["snow_depth"]
|
||||
if station_rec.get("lifts_open") is not None:
|
||||
features_df["lifts_open"] = station_rec["lifts_open"]
|
||||
|
||||
# Also inject snow_depth into weather_data for the rules engine
|
||||
station_rec = station_map.get(station_id, {})
|
||||
if station_rec.get("snow_depth") is not None:
|
||||
weather_data["snow_depth"] = station_rec["snow_depth"]
|
||||
|
||||
try:
|
||||
result = predictor.predict(station_id, weather_data, features_df)
|
||||
predictions[station_id] = result
|
||||
logger.info(
|
||||
"Prediction for %s: open=%.2f, km=%.1f, crowd=%s, source=%s",
|
||||
station_id,
|
||||
result["open_probability"],
|
||||
result["km_open"],
|
||||
result["crowd_level"],
|
||||
result["prediction_source"],
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Prediction failed for %s: %s", station_id, exc)
|
||||
|
||||
# Save predictions
|
||||
_PREDICTIONS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
output = {
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"prediction_date": tomorrow.isoformat(),
|
||||
"stations": predictions,
|
||||
}
|
||||
with open(_PREDICTIONS_PATH, "w", encoding="utf-8") as fh:
|
||||
json.dump(output, fh, indent=2, ensure_ascii=False, default=str)
|
||||
logger.info("Predictions saved to %s.", _PREDICTIONS_PATH)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Run the full daily data collection and prediction pipeline."""
|
||||
logger.info("=== Daily pipeline started ===")
|
||||
|
||||
try:
|
||||
weather_collector = WeatherCollector()
|
||||
station_scraper = StationScraper()
|
||||
dataset_builder = DatasetBuilder()
|
||||
feature_engineer = FeatureEngineer()
|
||||
hybrid_predictor = HybridPredictor()
|
||||
except Exception as exc:
|
||||
logger.critical("Failed to initialise components: %s", exc, exc_info=True)
|
||||
return 1
|
||||
|
||||
# Steps 1-2: collect data
|
||||
weather_data = collect_weather(weather_collector)
|
||||
station_records = collect_station_status(station_scraper)
|
||||
|
||||
if not weather_data and not station_records:
|
||||
logger.error("No data collected. Aborting.")
|
||||
return 1
|
||||
|
||||
# Step 3: append to dataset
|
||||
df = append_to_dataset(dataset_builder, weather_data, station_records)
|
||||
|
||||
# Step 4: feature engineering
|
||||
featured_df = run_feature_engineering(feature_engineer, df)
|
||||
|
||||
# Step 5: predictions
|
||||
generate_predictions(hybrid_predictor, weather_data, featured_df, station_records)
|
||||
|
||||
logger.info("=== Daily pipeline finished ===")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Model retraining script for the ski predictor.
|
||||
|
||||
Loads the latest processed and feature-engineered dataset, trains all
|
||||
configured ML models (RandomForest, GradientBoosting, LightGBM) for each
|
||||
target variable, evaluates them, and logs metrics.
|
||||
|
||||
Usage:
|
||||
python scripts/retrain_model.py
|
||||
|
||||
The trained models are persisted to ml/models/ by the training module.
|
||||
|
||||
Exit codes:
|
||||
0 - Training and evaluation completed successfully.
|
||||
1 - Fatal error prevented any training.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Ensure the project root is on sys.path so all project packages are importable
|
||||
# when this script is executed directly.
|
||||
# ---------------------------------------------------------------------------
|
||||
_SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
_PROJECT_ROOT = _SCRIPT_DIR.parent
|
||||
if str(_PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_PROJECT_ROOT))
|
||||
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
from ml.train_model import ModelTrainer
|
||||
from ml.evaluate_model import ModelEvaluator
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Logging setup
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)-8s %(name)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dataset path
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
|
||||
_FEATURES_DATASET_PATH = _PROCESSED_DIR / "dataset_features.csv"
|
||||
_DATASET_PATH = _PROCESSED_DIR / "dataset.csv"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Retraining steps
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def load_feature_dataset():
|
||||
"""Load the feature-engineered dataset from disk.
|
||||
|
||||
Falls back to running feature engineering on the base dataset when the
|
||||
features file does not exist yet.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pandas.DataFrame
|
||||
Feature-engineered dataset ready for ML training.
|
||||
|
||||
Raises
|
||||
------
|
||||
FileNotFoundError
|
||||
When neither the features dataset nor the base dataset is found.
|
||||
RuntimeError
|
||||
When feature engineering fails unexpectedly.
|
||||
"""
|
||||
import pandas as pd
|
||||
|
||||
if _FEATURES_DATASET_PATH.exists():
|
||||
logger.info("Loading features dataset from %s.", _FEATURES_DATASET_PATH)
|
||||
df = pd.read_csv(_FEATURES_DATASET_PATH)
|
||||
logger.info("Loaded %d rows.", len(df))
|
||||
return df
|
||||
|
||||
logger.warning(
|
||||
"Features dataset not found at %s. Running feature engineering first.",
|
||||
_FEATURES_DATASET_PATH,
|
||||
)
|
||||
|
||||
if not _DATASET_PATH.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Base dataset not found at {_DATASET_PATH}. "
|
||||
"Run collect_daily_data.py or pipeline/build_dataset.py first."
|
||||
)
|
||||
|
||||
engineer = FeatureEngineer()
|
||||
df = engineer.run()
|
||||
logger.info("Feature engineering produced %d rows.", len(df))
|
||||
return df
|
||||
|
||||
|
||||
def train_models(df) -> dict:
|
||||
"""Train all models on the provided feature dataset.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df:
|
||||
Feature-engineered DataFrame with target columns present.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Mapping of target variable name to fitted model objects, as returned
|
||||
by ModelTrainer.train_all().
|
||||
"""
|
||||
logger.info("Starting model training.")
|
||||
trainer = ModelTrainer()
|
||||
trained_models = trainer.train_all(df)
|
||||
logger.info(
|
||||
"Training complete. Models trained for targets: %s.",
|
||||
list(trained_models.keys()),
|
||||
)
|
||||
return trained_models
|
||||
|
||||
|
||||
def evaluate_models(trained_models: dict, df) -> dict:
|
||||
"""Evaluate trained models and log per-target metrics.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
trained_models:
|
||||
Output of :func:`train_models`.
|
||||
df:
|
||||
Feature-engineered DataFrame used for evaluation (held-out split is
|
||||
managed internally by ModelEvaluator).
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict
|
||||
Nested dict of {target: {model_name: {metric: value}}}.
|
||||
"""
|
||||
logger.info("Evaluating trained models.")
|
||||
evaluator = ModelEvaluator()
|
||||
metrics = evaluator.evaluate_all(trained_models, df)
|
||||
|
||||
for target, model_metrics in metrics.items():
|
||||
for model_name, scores in model_metrics.items():
|
||||
metric_str = " ".join(f"{k}={v:.4f}" for k, v in scores.items())
|
||||
logger.info("[%s] %s -> %s", target, model_name, metric_str)
|
||||
|
||||
return metrics
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""Run the full retraining pipeline.
|
||||
|
||||
Returns
|
||||
-------
|
||||
int
|
||||
Exit code: 0 on success, 1 on fatal error.
|
||||
"""
|
||||
logger.info("=== Model retraining started at %s ===", datetime.utcnow().isoformat())
|
||||
|
||||
try:
|
||||
df = load_feature_dataset()
|
||||
except FileNotFoundError as exc:
|
||||
logger.critical("Dataset not found: %s.", exc)
|
||||
return 1
|
||||
except Exception as exc:
|
||||
logger.critical("Failed to load dataset: %s.", exc, exc_info=True)
|
||||
return 1
|
||||
|
||||
if df.empty:
|
||||
logger.critical("Dataset is empty. Cannot train models.")
|
||||
return 1
|
||||
|
||||
try:
|
||||
trained_models = train_models(df)
|
||||
except Exception as exc:
|
||||
logger.critical("Training failed: %s.", exc, exc_info=True)
|
||||
return 1
|
||||
|
||||
try:
|
||||
evaluate_models(trained_models, df)
|
||||
except Exception as exc:
|
||||
# Evaluation failure is non-fatal; models are already saved.
|
||||
logger.error("Evaluation failed: %s. Models were still saved.", exc, exc_info=True)
|
||||
|
||||
logger.info("=== Model retraining finished successfully. ===")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
# Ski Predictor - Setup and start script
|
||||
# Usage: ./start.sh [--bot] [--cron] [--collect-now]
|
||||
#
|
||||
# --bot Start the Telegram bot (requires TELEGRAM_BOT_TOKEN)
|
||||
# --cron Install the daily cron job (22:00)
|
||||
# --collect-now Run the data collection pipeline immediately
|
||||
#
|
||||
# First run: ./start.sh --cron --collect-now
|
||||
# With bot: ./start.sh --cron --collect-now --bot
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
VENV="$SCRIPT_DIR/.venv"
|
||||
PYTHON="$VENV/bin/python"
|
||||
DATA_DIR="$SCRIPT_DIR/data"
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# Colors
|
||||
# ---------------------------------------------------------------
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m'
|
||||
|
||||
info() { echo -e "${GREEN}[INFO]${NC} $1"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $1"; }
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 1. Create virtualenv and install dependencies
|
||||
# ---------------------------------------------------------------
|
||||
if [ ! -d "$VENV" ]; then
|
||||
info "Creating virtualenv..."
|
||||
python3 -m venv "$VENV"
|
||||
fi
|
||||
|
||||
info "Installing dependencies..."
|
||||
"$VENV/bin/pip" install -q -r "$SCRIPT_DIR/requirements.txt"
|
||||
"$VENV/bin/pip" install -q pytest
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 2. Create data directories
|
||||
# ---------------------------------------------------------------
|
||||
mkdir -p "$DATA_DIR/raw" "$DATA_DIR/processed" "$SCRIPT_DIR/ml/models"
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 3. Parse arguments
|
||||
# ---------------------------------------------------------------
|
||||
DO_BOT=false
|
||||
DO_CRON=false
|
||||
DO_COLLECT=false
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--bot) DO_BOT=true ;;
|
||||
--cron) DO_CRON=true ;;
|
||||
--collect-now) DO_COLLECT=true ;;
|
||||
*) error "Unknown argument: $arg"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 4. Install cron job
|
||||
# ---------------------------------------------------------------
|
||||
if [ "$DO_CRON" = true ]; then
|
||||
CRON_CMD="0 22 * * * \"$PYTHON\" \"$SCRIPT_DIR/scripts/collect_daily_data.py\" >> \"$DATA_DIR/pipeline.log\" 2>&1"
|
||||
|
||||
if crontab -l 2>/dev/null | grep -qF "collect_daily_data.py"; then
|
||||
warn "Cron job already exists, skipping."
|
||||
else
|
||||
(crontab -l 2>/dev/null; echo "$CRON_CMD") | crontab -
|
||||
info "Cron job installed (daily at 22:00)."
|
||||
fi
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 5. Run initial data collection
|
||||
# ---------------------------------------------------------------
|
||||
if [ "$DO_COLLECT" = true ]; then
|
||||
info "Running initial data collection..."
|
||||
"$PYTHON" "$SCRIPT_DIR/scripts/collect_daily_data.py" 2>&1 | tee -a "$DATA_DIR/pipeline.log"
|
||||
info "Data collection complete."
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 6. Start Telegram bot
|
||||
# ---------------------------------------------------------------
|
||||
if [ "$DO_BOT" = true ]; then
|
||||
if [ -z "${TELEGRAM_BOT_TOKEN:-}" ]; then
|
||||
error "TELEGRAM_BOT_TOKEN not set. Export it first:"
|
||||
echo " export TELEGRAM_BOT_TOKEN='your_token_here'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Kill existing bot process if running
|
||||
if pgrep -f "telegram_bot.py" > /dev/null 2>&1; then
|
||||
warn "Killing existing bot process..."
|
||||
pkill -f "telegram_bot.py" || true
|
||||
sleep 1
|
||||
fi
|
||||
|
||||
info "Starting Telegram bot..."
|
||||
nohup "$PYTHON" "$SCRIPT_DIR/bot/telegram_bot.py" >> "$DATA_DIR/bot.log" 2>&1 &
|
||||
BOT_PID=$!
|
||||
info "Bot started (PID: $BOT_PID). Logs: $DATA_DIR/bot.log"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# Summary
|
||||
# ---------------------------------------------------------------
|
||||
echo ""
|
||||
info "=== Ski Predictor ==="
|
||||
echo " Project: $SCRIPT_DIR"
|
||||
echo " Python: $PYTHON"
|
||||
echo " Data: $DATA_DIR"
|
||||
if [ "$DO_CRON" = true ]; then
|
||||
echo " Cron: Daily at 22:00"
|
||||
fi
|
||||
if [ "$DO_BOT" = true ]; then
|
||||
echo " Bot PID: $BOT_PID"
|
||||
fi
|
||||
echo ""
|
||||
info "Done."
|
||||
@@ -0,0 +1 @@
|
||||
"""Test suite for the ski predictor project."""
|
||||
@@ -0,0 +1,483 @@
|
||||
"""Unit tests for CrowdAnalyzer in data_sources/crowd_analyzer.py.
|
||||
|
||||
Tests cover:
|
||||
- Instantiation without loading the YOLO model.
|
||||
- Crowd density threshold classification across all boundary conditions.
|
||||
- analyze_image() with a mocked YOLO model.
|
||||
- estimate_crowd_level() with mocked WebcamCollector and YOLO.
|
||||
- analyze_all_stations() integration across all three stations.
|
||||
- JSON persistence of results.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_STATIONS_CONFIG = {
|
||||
"stations": {
|
||||
"pajares": {
|
||||
"name": "Valgrande-Pajares",
|
||||
"latitude": 43.05,
|
||||
"longitude": -5.77,
|
||||
"altitude": 1500,
|
||||
"wind_closure_threshold": 80,
|
||||
"minimum_snow_depth": 30,
|
||||
"max_km_skiable": 22.0,
|
||||
"url": "https://www.valgrande-pajares.com",
|
||||
"telegram_command": "/pajares",
|
||||
"webcams": {
|
||||
"primary_webcam_page": "https://www.infonieve.es/estacion-esqui/valgrande-pajares/webcams/",
|
||||
"snapshots": [
|
||||
{
|
||||
"label": "Cuitu Negru - Telecabina",
|
||||
"static": False,
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
"sanisidro": {
|
||||
"name": "San Isidro",
|
||||
"latitude": 43.07,
|
||||
"longitude": -5.37,
|
||||
"altitude": 1500,
|
||||
"wind_closure_threshold": 80,
|
||||
"minimum_snow_depth": 30,
|
||||
"max_km_skiable": 31.0,
|
||||
"url": "https://www.san-isidro.net",
|
||||
"telegram_command": "/sanisidro",
|
||||
"webcams": {
|
||||
"snapshots": [
|
||||
{
|
||||
"label": "Cebolledo I",
|
||||
"url": "https://www.nieveleonsanisidro.com/img/sanisidro/webcam/CebolledoI.jpg",
|
||||
"static": True,
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
"fuentes": {
|
||||
"name": "Fuentes de Invierno",
|
||||
"latitude": 43.0833,
|
||||
"longitude": -5.9333,
|
||||
"altitude": 1500,
|
||||
"wind_closure_threshold": 80,
|
||||
"minimum_snow_depth": 30,
|
||||
"max_km_skiable": 8.6,
|
||||
"url": "https://www.fuentesdeinvierno.com",
|
||||
"telegram_command": "/fuentes",
|
||||
"webcams": {
|
||||
"snapshots": [
|
||||
{
|
||||
"label": "Camara 1",
|
||||
"url": "https://fuentesdeinvierno.com/tmp/camara1.jpg",
|
||||
"static": True,
|
||||
"ssl_verify": False,
|
||||
}
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _make_analyzer(tmp_path: Path) -> "CrowdAnalyzer":
|
||||
"""Return a CrowdAnalyzer with config loading and model instantiation bypassed."""
|
||||
with patch(
|
||||
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
|
||||
return_value=_STATIONS_CONFIG["stations"],
|
||||
):
|
||||
from data_sources.crowd_analyzer import CrowdAnalyzer
|
||||
|
||||
analyzer = CrowdAnalyzer(
|
||||
config_path=tmp_path / "stations.yaml",
|
||||
output_dir=tmp_path,
|
||||
)
|
||||
return analyzer
|
||||
|
||||
|
||||
def _make_yolo_result(
|
||||
cls_names: list[str],
|
||||
confidences: list[float],
|
||||
) -> list[MagicMock]:
|
||||
"""Build a fake YOLO results list with the given class names and confidences.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
cls_names:
|
||||
List of COCO class name strings for each detected box.
|
||||
confidences:
|
||||
Confidence score per detection (same order as cls_names).
|
||||
"""
|
||||
result = MagicMock()
|
||||
result.names = {i: name for i, name in enumerate(set(cls_names))}
|
||||
# Build a reverse lookup so the mock returns the right cls_id for each box.
|
||||
name_to_id = {v: k for k, v in result.names.items()}
|
||||
|
||||
boxes = []
|
||||
for name, conf in zip(cls_names, confidences):
|
||||
box = MagicMock()
|
||||
box.conf = [conf]
|
||||
box.cls = [name_to_id[name]]
|
||||
boxes.append(box)
|
||||
|
||||
result.boxes = boxes
|
||||
return [result]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – instantiation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestInstantiation:
|
||||
"""CrowdAnalyzer must be importable and instantiable without loading YOLO."""
|
||||
|
||||
def test_can_be_instantiated(self, tmp_path):
|
||||
"""CrowdAnalyzer.__init__ must not attempt to load the YOLO model."""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
# The model must remain un-loaded (lazy) after construction.
|
||||
assert analyzer._model is None
|
||||
|
||||
def test_output_dir_is_created(self, tmp_path):
|
||||
"""The output directory must exist after initialisation."""
|
||||
out_dir = tmp_path / "outputs" / "raw"
|
||||
with patch(
|
||||
"data_sources.crowd_analyzer.CrowdAnalyzer._load_stations",
|
||||
return_value=_STATIONS_CONFIG["stations"],
|
||||
):
|
||||
from data_sources.crowd_analyzer import CrowdAnalyzer
|
||||
|
||||
CrowdAnalyzer(
|
||||
config_path=tmp_path / "stations.yaml",
|
||||
output_dir=out_dir,
|
||||
)
|
||||
assert out_dir.is_dir()
|
||||
|
||||
def test_stations_are_loaded(self, tmp_path):
|
||||
"""All three stations must be present in self.stations after init."""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
assert set(analyzer.stations.keys()) == {"pajares", "sanisidro", "fuentes"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – _classify_density thresholds
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestClassifyDensity:
|
||||
"""_classify_density must apply the documented car/person thresholds."""
|
||||
|
||||
# Import once so all methods share it.
|
||||
@pytest.fixture(autouse=True)
|
||||
def _import(self):
|
||||
from data_sources.crowd_analyzer import CrowdAnalyzer
|
||||
|
||||
self.classify = CrowdAnalyzer._classify_density
|
||||
|
||||
# -- Low density --
|
||||
|
||||
def test_zero_cars_zero_people_is_low(self):
|
||||
assert self.classify(0, 0) == "low"
|
||||
|
||||
def test_below_car_threshold_is_low(self):
|
||||
"""19 cars and 0 people must produce 'low'."""
|
||||
assert self.classify(19, 0) == "low"
|
||||
|
||||
def test_below_person_threshold_is_low(self):
|
||||
"""0 cars and 9 people must produce 'low'."""
|
||||
assert self.classify(0, 9) == "low"
|
||||
|
||||
# -- Medium density --
|
||||
|
||||
def test_car_at_low_threshold_is_medium(self):
|
||||
"""Exactly 20 cars must cross into 'medium'."""
|
||||
assert self.classify(20, 0) == "medium"
|
||||
|
||||
def test_car_at_high_threshold_is_medium(self):
|
||||
"""Exactly 50 cars must still be 'medium' (not high)."""
|
||||
assert self.classify(50, 0) == "medium"
|
||||
|
||||
def test_person_at_low_threshold_is_medium(self):
|
||||
"""Exactly 10 people must cross into 'medium'."""
|
||||
assert self.classify(0, 10) == "medium"
|
||||
|
||||
def test_person_at_high_threshold_is_medium(self):
|
||||
"""Exactly 30 people must still be 'medium'."""
|
||||
assert self.classify(0, 30) == "medium"
|
||||
|
||||
def test_mixed_medium_cars_low_people(self):
|
||||
"""Medium cars + low people -> 'medium' (max wins)."""
|
||||
assert self.classify(25, 5) == "medium"
|
||||
|
||||
# -- High density --
|
||||
|
||||
def test_above_car_threshold_is_high(self):
|
||||
"""51 cars must produce 'high'."""
|
||||
assert self.classify(51, 0) == "high"
|
||||
|
||||
def test_above_person_threshold_is_high(self):
|
||||
"""31 people must produce 'high'."""
|
||||
assert self.classify(0, 31) == "high"
|
||||
|
||||
def test_high_people_overrides_low_cars(self):
|
||||
"""High person count must push density to 'high' even with few cars."""
|
||||
assert self.classify(5, 35) == "high"
|
||||
|
||||
def test_high_cars_overrides_low_people(self):
|
||||
"""High car count must push density to 'high' even with few people."""
|
||||
assert self.classify(60, 2) == "high"
|
||||
|
||||
# -- Boundary correctness --
|
||||
|
||||
def test_boundary_19_cars_is_low(self):
|
||||
assert self.classify(19, 0) == "low"
|
||||
|
||||
def test_boundary_20_cars_is_medium(self):
|
||||
assert self.classify(20, 0) == "medium"
|
||||
|
||||
def test_boundary_50_cars_is_medium(self):
|
||||
assert self.classify(50, 0) == "medium"
|
||||
|
||||
def test_boundary_51_cars_is_high(self):
|
||||
assert self.classify(51, 0) == "high"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – analyze_image with mocked YOLO
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestAnalyzeImage:
|
||||
"""analyze_image must correctly aggregate YOLO detections."""
|
||||
|
||||
def _run(self, tmp_path: Path, cls_names: list[str], confidences: list[float]):
|
||||
"""Helper: run analyze_image with a synthetic YOLO output."""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
fake_results = _make_yolo_result(cls_names, confidences)
|
||||
|
||||
# Create a dummy image file so the path existence check passes.
|
||||
img_path = tmp_path / "test_frame.jpg"
|
||||
img_path.write_bytes(b"\xff\xd8\xff" + b"\x00" * 100)
|
||||
|
||||
# Mock both _load_model and the YOLO call.
|
||||
mock_model = MagicMock(return_value=fake_results)
|
||||
analyzer._model = mock_model
|
||||
|
||||
return analyzer.analyze_image(str(img_path))
|
||||
|
||||
def test_counts_cars_correctly(self, tmp_path):
|
||||
"""Three cars in detections must produce cars_detected=3."""
|
||||
result = self._run(tmp_path, ["car", "car", "car"], [0.9, 0.85, 0.8])
|
||||
assert result["cars_detected"] == 3
|
||||
|
||||
def test_counts_people_correctly(self, tmp_path):
|
||||
"""Two people detections must produce people_detected=2."""
|
||||
result = self._run(tmp_path, ["person", "person"], [0.95, 0.88])
|
||||
assert result["people_detected"] == 2
|
||||
|
||||
def test_counts_buses_correctly(self, tmp_path):
|
||||
"""One bus detection must produce buses_detected=1."""
|
||||
result = self._run(tmp_path, ["bus"], [0.7])
|
||||
assert result["buses_detected"] == 1
|
||||
|
||||
def test_total_vehicles_excludes_people(self, tmp_path):
|
||||
"""total_vehicles must count cars + buses + trucks, not people."""
|
||||
result = self._run(
|
||||
tmp_path,
|
||||
["car", "person", "bus", "truck"],
|
||||
[0.9, 0.9, 0.8, 0.75],
|
||||
)
|
||||
assert result["total_vehicles"] == 3 # car + bus + truck
|
||||
assert result["people_detected"] == 1
|
||||
|
||||
def test_confidence_scores_are_included(self, tmp_path):
|
||||
"""All detection confidence scores must be present in the result."""
|
||||
result = self._run(tmp_path, ["car", "person"], [0.91, 0.82])
|
||||
assert len(result["confidence_scores"]) == 2
|
||||
assert all(0.0 <= s <= 1.0 for s in result["confidence_scores"])
|
||||
|
||||
def test_result_has_required_keys(self, tmp_path):
|
||||
"""analyze_image must return all documented keys."""
|
||||
result = self._run(tmp_path, [], [])
|
||||
required = {
|
||||
"cars_detected",
|
||||
"people_detected",
|
||||
"buses_detected",
|
||||
"total_vehicles",
|
||||
"crowd_density",
|
||||
"confidence_scores",
|
||||
"timestamp",
|
||||
}
|
||||
assert required.issubset(result.keys())
|
||||
|
||||
def test_crowd_density_is_valid_string(self, tmp_path):
|
||||
"""crowd_density must be one of the three documented values."""
|
||||
result = self._run(tmp_path, ["car"] * 5, [0.9] * 5)
|
||||
assert result["crowd_density"] in {"low", "medium", "high"}
|
||||
|
||||
def test_empty_image_gives_low_density(self, tmp_path):
|
||||
"""An image with no detections must yield density='low'."""
|
||||
result = self._run(tmp_path, [], [])
|
||||
assert result["crowd_density"] == "low"
|
||||
|
||||
def test_raises_file_not_found(self, tmp_path):
|
||||
"""FileNotFoundError must be raised when the image path does not exist."""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
analyzer._model = MagicMock()
|
||||
with pytest.raises(FileNotFoundError):
|
||||
analyzer.analyze_image(str(tmp_path / "nonexistent.jpg"))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – estimate_crowd_level
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestEstimateCrowdLevel:
|
||||
"""estimate_crowd_level must capture a webcam image and analyse it."""
|
||||
|
||||
def _run_with_mocks(
|
||||
self,
|
||||
tmp_path: Path,
|
||||
station_id: str,
|
||||
captured_paths: list[str],
|
||||
cls_names: list[str],
|
||||
confidences: list[float],
|
||||
):
|
||||
"""Run estimate_crowd_level with WebcamCollector and YOLO both mocked.
|
||||
|
||||
WebcamCollector is imported inside estimate_crowd_level at call-time,
|
||||
so we patch it at its definition site in ``data_sources.webcam_collector``.
|
||||
"""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
|
||||
# Ensure a real image file exists if the collector is to return a path.
|
||||
for p in captured_paths:
|
||||
Path(p).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(p).write_bytes(b"\xff\xd8\xff" + b"\x00" * 100)
|
||||
|
||||
fake_results = _make_yolo_result(cls_names, confidences)
|
||||
mock_yolo = MagicMock(return_value=fake_results)
|
||||
analyzer._model = mock_yolo
|
||||
|
||||
# Patch at the definition module so the local import inside
|
||||
# estimate_crowd_level picks up the mock.
|
||||
with patch(
|
||||
"data_sources.webcam_collector.WebcamCollector"
|
||||
) as MockCollector:
|
||||
mock_instance = MockCollector.return_value
|
||||
mock_instance.capture.return_value = captured_paths
|
||||
result = analyzer.estimate_crowd_level(station_id)
|
||||
|
||||
return result
|
||||
|
||||
def test_returns_crowd_density_string(self, tmp_path):
|
||||
"""estimate_crowd_level must return a dict with a crowd_density key."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
result = self._run_with_mocks(tmp_path, "pajares", [img], ["car"] * 5, [0.9] * 5)
|
||||
assert "crowd_density" in result
|
||||
assert result["crowd_density"] in {"low", "medium", "high", "unknown"}
|
||||
|
||||
def test_result_includes_station_id(self, tmp_path):
|
||||
"""The returned dict must carry the station_id."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
result = self._run_with_mocks(tmp_path, "sanisidro", [img], [], [])
|
||||
assert result["station_id"] == "sanisidro"
|
||||
|
||||
def test_result_includes_image_path(self, tmp_path):
|
||||
"""The returned dict must carry the image path used for analysis."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
result = self._run_with_mocks(tmp_path, "fuentes", [img], [], [])
|
||||
assert result["image_path"] == img
|
||||
|
||||
def test_unknown_density_when_no_capture(self, tmp_path):
|
||||
"""When the webcam collector returns no images, density must be 'unknown'."""
|
||||
result = self._run_with_mocks(tmp_path, "pajares", [], [], [])
|
||||
assert result["crowd_density"] == "unknown"
|
||||
|
||||
def test_result_is_saved_to_json(self, tmp_path):
|
||||
"""A JSON file must be written to output_dir after analysis."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
self._run_with_mocks(tmp_path, "pajares", [img], ["person"] * 3, [0.9] * 3)
|
||||
from datetime import date
|
||||
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
json_file = tmp_path / f"crowd_pajares_{today}.json"
|
||||
assert json_file.exists()
|
||||
|
||||
def test_json_contains_valid_list(self, tmp_path):
|
||||
"""The saved JSON file must contain a list with at least one result."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
self._run_with_mocks(tmp_path, "pajares", [img], ["car"], [0.85])
|
||||
from datetime import date
|
||||
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
json_file = tmp_path / f"crowd_pajares_{today}.json"
|
||||
data = json.loads(json_file.read_text())
|
||||
assert isinstance(data, list)
|
||||
assert len(data) >= 1
|
||||
|
||||
def test_multiple_calls_append_to_json(self, tmp_path):
|
||||
"""Successive calls must append results to the same JSON file."""
|
||||
img = str(tmp_path / "frame.jpg")
|
||||
self._run_with_mocks(tmp_path, "sanisidro", [img], ["car"], [0.9])
|
||||
self._run_with_mocks(tmp_path, "sanisidro", [img], ["person"], [0.8])
|
||||
from datetime import date
|
||||
|
||||
today = date.today().strftime("%Y-%m-%d")
|
||||
json_file = tmp_path / f"crowd_sanisidro_{today}.json"
|
||||
data = json.loads(json_file.read_text())
|
||||
assert len(data) == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – analyze_all_stations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestAnalyzeAllStations:
|
||||
"""analyze_all_stations must process every configured station."""
|
||||
|
||||
def test_returns_all_station_ids(self, tmp_path):
|
||||
"""The result dict must contain keys for all three stations."""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
|
||||
# Patch estimate_crowd_level to avoid real I/O.
|
||||
def _fake_estimate(station_id):
|
||||
return {
|
||||
"station_id": station_id,
|
||||
"crowd_density": "low",
|
||||
"cars_detected": 0,
|
||||
"people_detected": 0,
|
||||
"buses_detected": 0,
|
||||
"total_vehicles": 0,
|
||||
"confidence_scores": [],
|
||||
"timestamp": "2026-01-01T12:00:00",
|
||||
"image_path": None,
|
||||
}
|
||||
|
||||
with patch.object(analyzer, "estimate_crowd_level", side_effect=_fake_estimate):
|
||||
results = analyzer.analyze_all_stations()
|
||||
|
||||
assert set(results.keys()) == {"pajares", "sanisidro", "fuentes"}
|
||||
|
||||
def test_all_results_have_crowd_density(self, tmp_path):
|
||||
"""Every station result must contain a crowd_density key."""
|
||||
analyzer = _make_analyzer(tmp_path)
|
||||
|
||||
def _fake_estimate(station_id):
|
||||
return {"station_id": station_id, "crowd_density": "medium"}
|
||||
|
||||
with patch.object(analyzer, "estimate_crowd_level", side_effect=_fake_estimate):
|
||||
results = analyzer.analyze_all_stations()
|
||||
|
||||
for station_id, result in results.items():
|
||||
assert "crowd_density" in result, f"Missing crowd_density for {station_id}"
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Unit tests for the FeatureEngineer in pipeline/feature_engineering.py.
|
||||
|
||||
Tests verify that derived features are computed correctly against known
|
||||
reference DataFrames. Each test class is focused on a single feature group.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from datetime import date, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _next_weekday(weekday: int) -> date:
|
||||
"""Return the next calendar date whose weekday() equals *weekday*.
|
||||
|
||||
Monday=0, Tuesday=1, ..., Saturday=5, Sunday=6.
|
||||
"""
|
||||
today = date.today()
|
||||
days_ahead = (weekday - today.weekday()) % 7
|
||||
if days_ahead == 0:
|
||||
days_ahead = 7 # ensure we get a future date to avoid "today" edge case
|
||||
return today + timedelta(days=days_ahead)
|
||||
|
||||
|
||||
def _make_base_df(
|
||||
n_days: int = 14,
|
||||
station_id: str = "pajares",
|
||||
start_date: date | None = None,
|
||||
) -> pd.DataFrame:
|
||||
"""Build a minimal raw dataset for one station spanning n_days."""
|
||||
if start_date is None:
|
||||
start_date = date.today() - timedelta(days=n_days - 1)
|
||||
|
||||
dates = [start_date + timedelta(days=i) for i in range(n_days)]
|
||||
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"date": pd.to_datetime(dates),
|
||||
"station_id": station_id,
|
||||
"temperature_2m_max": [2.0] * n_days,
|
||||
"temperature_2m_min": [-4.0] * n_days,
|
||||
"temperature_2m_mean": [-1.0] * n_days,
|
||||
"precipitation_sum": [0.0] * n_days,
|
||||
"snowfall_sum": [0.0] * n_days,
|
||||
"wind_speed_10m_max": [20.0] * n_days,
|
||||
"wind_gusts_10m_max": [35.0] * n_days,
|
||||
"wind_direction_10m_dominant": [270.0] * n_days,
|
||||
"relative_humidity_2m_mean": [75.0] * n_days,
|
||||
"surface_pressure_mean": [1013.0] * n_days,
|
||||
"open_status": [True] * n_days,
|
||||
"km_open": [15.0] * n_days,
|
||||
"snow_depth": [60] * n_days,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
# Features config that enables all engineered features
|
||||
_FEATURES_CONFIG = {
|
||||
"engineered_features": [
|
||||
"snow_last_3_days",
|
||||
"snow_last_7_days",
|
||||
"avg_temperature_3_days",
|
||||
"max_wind_gust",
|
||||
"is_weekend",
|
||||
"is_holiday",
|
||||
"month_of_year",
|
||||
"day_of_week",
|
||||
"days_since_last_snowfall",
|
||||
"temperature_trend_3_days",
|
||||
"pressure_trend_3_days",
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def feature_engineer():
|
||||
"""Return a FeatureEngineer instance with config loading bypassed."""
|
||||
with patch(
|
||||
"pipeline.feature_engineering.FeatureEngineer._load_config",
|
||||
return_value=_FEATURES_CONFIG,
|
||||
):
|
||||
from pipeline.feature_engineering import FeatureEngineer
|
||||
engineer = FeatureEngineer()
|
||||
return engineer
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – is_weekend
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestIsWeekend:
|
||||
"""is_weekend must be 1 only for Saturday (5) and Sunday (6)."""
|
||||
|
||||
def test_saturday_is_weekend(self, feature_engineer):
|
||||
"""Saturday rows must have is_weekend == 1."""
|
||||
saturday = _next_weekday(5)
|
||||
df = _make_base_df(n_days=1, start_date=saturday)
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["is_weekend"].iloc[0] == 1
|
||||
|
||||
def test_sunday_is_weekend(self, feature_engineer):
|
||||
"""Sunday rows must have is_weekend == 1."""
|
||||
sunday = _next_weekday(6)
|
||||
df = _make_base_df(n_days=1, start_date=sunday)
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["is_weekend"].iloc[0] == 1
|
||||
|
||||
def test_monday_is_not_weekend(self, feature_engineer):
|
||||
"""Monday rows must have is_weekend == 0."""
|
||||
monday = _next_weekday(0)
|
||||
df = _make_base_df(n_days=1, start_date=monday)
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["is_weekend"].iloc[0] == 0
|
||||
|
||||
def test_friday_is_not_weekend(self, feature_engineer):
|
||||
"""Friday rows must have is_weekend == 0."""
|
||||
friday = _next_weekday(4)
|
||||
df = _make_base_df(n_days=1, start_date=friday)
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["is_weekend"].iloc[0] == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – snow_last_3_days
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestSnowLast3Days:
|
||||
"""snow_last_3_days is the rolling 3-day sum of previous snowfall."""
|
||||
|
||||
def test_correct_rolling_sum(self, feature_engineer):
|
||||
"""Rolling 3-day snowfall sum must match manual computation."""
|
||||
df = _make_base_df(n_days=7)
|
||||
snowfalls = [0.0, 5.0, 3.0, 0.0, 8.0, 2.0, 1.0]
|
||||
df["snowfall_sum"] = snowfalls
|
||||
|
||||
result = feature_engineer.transform(df)
|
||||
|
||||
# snow_last_3_days uses shift(1) then rolling(3), so for row 6:
|
||||
# shifted values at positions 3,4,5 = 0.0, 8.0, 2.0 -> sum = 10.0
|
||||
expected_last = snowfalls[3] + snowfalls[4] + snowfalls[5]
|
||||
assert result["snow_last_3_days"].iloc[6] == pytest.approx(expected_last)
|
||||
|
||||
def test_zero_snowfall_gives_zero(self, feature_engineer):
|
||||
"""All-zero snowfall must produce a zero rolling sum."""
|
||||
df = _make_base_df(n_days=5)
|
||||
df["snowfall_sum"] = 0.0
|
||||
result = feature_engineer.transform(df)
|
||||
assert (result["snow_last_3_days"].fillna(0.0) == 0.0).all()
|
||||
|
||||
def test_single_row_nan(self, feature_engineer):
|
||||
"""With only one row, snow_last_3_days is NaN (no prior data after shift)."""
|
||||
df = _make_base_df(n_days=1)
|
||||
df["snowfall_sum"] = 7.0
|
||||
result = feature_engineer.transform(df)
|
||||
assert pd.isna(result["snow_last_3_days"].iloc[0])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – days_since_last_snowfall
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDaysSinceLastSnowfall:
|
||||
"""days_since_last_snowfall counts days since the last snow event."""
|
||||
|
||||
def test_zero_when_it_snowed_today(self, feature_engineer):
|
||||
"""If the most recent row has snowfall > 0, days_since must be 0."""
|
||||
df = _make_base_df(n_days=5)
|
||||
df["snowfall_sum"] = [0.0, 0.0, 0.0, 0.0, 3.0]
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["days_since_last_snowfall"].iloc[4] == 0
|
||||
|
||||
def test_increments_correctly(self, feature_engineer):
|
||||
"""Days-since counter must increment by 1 for each snow-free day."""
|
||||
df = _make_base_df(n_days=5)
|
||||
df["snowfall_sum"] = [5.0, 0.0, 0.0, 0.0, 0.0]
|
||||
result = feature_engineer.transform(df)
|
||||
|
||||
assert result["days_since_last_snowfall"].iloc[1] == 1
|
||||
assert result["days_since_last_snowfall"].iloc[2] == 2
|
||||
assert result["days_since_last_snowfall"].iloc[3] == 3
|
||||
assert result["days_since_last_snowfall"].iloc[4] == 4
|
||||
|
||||
def test_resets_after_new_snowfall(self, feature_engineer):
|
||||
"""Counter must reset to 0 when snowfall resumes after a dry spell."""
|
||||
df = _make_base_df(n_days=6)
|
||||
df["snowfall_sum"] = [3.0, 0.0, 0.0, 0.0, 5.0, 0.0]
|
||||
result = feature_engineer.transform(df)
|
||||
|
||||
assert result["days_since_last_snowfall"].iloc[4] == 0
|
||||
assert result["days_since_last_snowfall"].iloc[5] == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – temperature_trend
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestTemperatureTrend:
|
||||
"""temperature_trend_3_days is the difference between today and 3 days ago."""
|
||||
|
||||
def test_positive_trend_when_warming(self, feature_engineer):
|
||||
"""Increasing temperatures must produce a positive trend value."""
|
||||
df = _make_base_df(n_days=5)
|
||||
df["temperature_2m_mean"] = [-5.0, -4.0, -3.0, -2.0, -1.0]
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["temperature_trend_3_days"].iloc[3] > 0
|
||||
|
||||
def test_negative_trend_when_cooling(self, feature_engineer):
|
||||
"""Decreasing temperatures must produce a negative trend value."""
|
||||
df = _make_base_df(n_days=5)
|
||||
df["temperature_2m_mean"] = [5.0, 4.0, 3.0, 2.0, 1.0]
|
||||
result = feature_engineer.transform(df)
|
||||
assert result["temperature_trend_3_days"].iloc[4] < 0
|
||||
|
||||
def test_zero_trend_when_stable(self, feature_engineer):
|
||||
"""Constant temperatures must produce a trend of zero."""
|
||||
df = _make_base_df(n_days=5)
|
||||
df["temperature_2m_mean"] = [0.0] * 5
|
||||
result = feature_engineer.transform(df)
|
||||
stable_rows = result["temperature_trend_3_days"].dropna()
|
||||
assert all(v == pytest.approx(0.0) for v in stable_rows)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Unit tests for the RulesEngine in predictor/rules.py.
|
||||
|
||||
Tests cover the physical and operational constraints that must override ML
|
||||
predictions when conditions are deterministic:
|
||||
|
||||
- Extreme wind forces the station closed regardless of other conditions.
|
||||
- Insufficient snow depth forces the station closed.
|
||||
- Normal conditions produce no forced outcome.
|
||||
- High temperature combined with rain reduces the estimated_km_factor.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures – station config
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def station_config():
|
||||
"""Minimal station configuration mirroring config/stations.yaml structure."""
|
||||
return {
|
||||
"pajares": {
|
||||
"name": "Valgrande-Pajares",
|
||||
"wind_closure_threshold": 80, # km/h
|
||||
"minimum_snow_depth": 30, # cm
|
||||
"max_km_skiable": 22.0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def rules_engine(station_config):
|
||||
"""RulesEngine instance with mocked config loading."""
|
||||
with patch("predictor.rules._load_station_configs", return_value=station_config):
|
||||
from predictor.rules import RulesEngine
|
||||
engine = RulesEngine()
|
||||
return engine
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _weather(
|
||||
wind_gust: float = 40.0,
|
||||
snow_depth: int = 60,
|
||||
temperature: float = 2.0,
|
||||
precipitation: float = 0.0,
|
||||
) -> dict:
|
||||
"""Build a minimal weather observation dict for testing."""
|
||||
return {
|
||||
"wind_gusts_10m_max": wind_gust,
|
||||
"snow_depth": snow_depth,
|
||||
"temperature_2m_max": temperature,
|
||||
"precipitation_sum": precipitation,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – wind closure
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestWindClosure:
|
||||
"""Rules triggered by wind gust exceeding the station threshold."""
|
||||
|
||||
def test_wind_above_threshold_forces_closed(self, rules_engine):
|
||||
"""Wind gust above 80 km/h must set force_closed to True."""
|
||||
weather = _weather(wind_gust=85.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is True
|
||||
|
||||
def test_wind_at_threshold_forces_closed(self, rules_engine):
|
||||
"""Wind gust exactly at the threshold (80 km/h) must force closure."""
|
||||
weather = _weather(wind_gust=80.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is True
|
||||
|
||||
def test_wind_below_threshold_does_not_force_closed(self, rules_engine):
|
||||
"""Wind gust below 80 km/h must not set force_closed."""
|
||||
weather = _weather(wind_gust=75.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – snow depth
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestSnowDepth:
|
||||
"""Rules triggered by insufficient snow depth."""
|
||||
|
||||
def test_snow_below_minimum_forces_closed(self, rules_engine):
|
||||
"""Snow depth below 30 cm must set force_closed to True."""
|
||||
weather = _weather(snow_depth=20)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is True
|
||||
|
||||
def test_snow_at_minimum_does_not_force_closed(self, rules_engine):
|
||||
"""Snow depth exactly at 30 cm is acceptable and must not force closure."""
|
||||
weather = _weather(snow_depth=30)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is False
|
||||
|
||||
def test_snow_above_minimum_does_not_force_closed(self, rules_engine):
|
||||
"""Snow depth well above the minimum must not force closure."""
|
||||
weather = _weather(snow_depth=80)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – normal conditions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestNormalConditions:
|
||||
"""No rules should trigger under benign conditions."""
|
||||
|
||||
def test_normal_conditions_produce_no_force(self, rules_engine):
|
||||
"""Standard winter conditions must leave all force flags unset."""
|
||||
weather = _weather(wind_gust=30.0, snow_depth=60, temperature=-2.0, precipitation=0.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["force_closed"] is False
|
||||
assert result["estimated_km_factor"] == pytest.approx(1.0)
|
||||
|
||||
def test_normal_conditions_return_dict(self, rules_engine):
|
||||
"""evaluate() must always return a dict with the expected keys."""
|
||||
weather = _weather()
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert isinstance(result, dict)
|
||||
assert "force_closed" in result
|
||||
assert "estimated_km_factor" in result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests – rain + high temperature reduces estimated_km_factor
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRainAndHighTemperature:
|
||||
"""Rain at positive temperatures should reduce the estimated open km."""
|
||||
|
||||
def test_high_temp_and_rain_reduces_km_factor(self, rules_engine):
|
||||
"""Temperature > 10 C combined with precipitation must reduce estimated_km_factor below 1.0."""
|
||||
weather = _weather(temperature=12.0, precipitation=8.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["estimated_km_factor"] < 1.0
|
||||
|
||||
def test_rain_without_high_temp_does_not_reduce_km_factor(self, rules_engine):
|
||||
"""Rain at sub-zero temperatures must not reduce estimated_km_factor."""
|
||||
weather = _weather(temperature=-3.0, precipitation=8.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["estimated_km_factor"] == pytest.approx(1.0)
|
||||
|
||||
def test_high_temp_without_rain_does_not_reduce_km_factor(self, rules_engine):
|
||||
"""High temperature without precipitation must not reduce estimated_km_factor."""
|
||||
weather = _weather(temperature=12.0, precipitation=0.0)
|
||||
result = rules_engine.evaluate("pajares", weather)
|
||||
assert result["estimated_km_factor"] == pytest.approx(1.0)
|
||||
Reference in new issue
Block a user