mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 23:36:17 +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
@@ -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"),
|
||||
))
|
||||
Reference in new issue
Block a user