Files
skipredictor/data_sources/infonieve_historical.py
T

183 lines
5.5 KiB
Python

"""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 stores the combined raw history in SQLite.
"""
import io
import logging
import time
from pathlib import Path
import pandas as pd
import requests
from storage import SQLiteStore
logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
_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(store: SQLiteStore | None = None) -> 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)
effective_store = store if store is not None else SQLiteStore()
effective_store.save_historical_station_raw(combined)
logger.info("Historical data saved to SQLite: %d total rows.", 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"),
))