FrenchCastle's picture
ISORA FY2014-FY2024 v1.0.0: observations, indicators, indicator_history, jurisdictions, coverage, revisions + card, license, pipeline
cbd273f verified
Raw History Blame Contribute Delete
4 kB
"""Thin client for the IMF SDMX API with on-disk caching of every response used by the build."""
from __future__ import annotations
import logging
from datetime import UTC
from pathlib import Path
import requests
from isora_hf import config
log = logging.getLogger(__name__)
STRUCTURE_JSON = "application/vnd.sdmx.structure+json;version=2.0.0"
DATA_CSV = "application/vnd.sdmx.data+csv;version=2.0.0"
LEGACY_CSV = "text/csv"
def _get(url: str, accept: str, timeout: int = 300) -> bytes:
headers = {"Accept": accept, "User-Agent": config.USER_AGENT}
response = requests.get(url, headers=headers, timeout=timeout)
response.raise_for_status()
if response.status_code == 204 or not response.content:
raise RuntimeError(f"Empty response from {url}")
return response.content
def _cached(path: Path, url: str, accept: str, force: bool = False) -> Path:
if path.exists() and not force:
log.info("cache hit %s", path.name)
return path
path.parent.mkdir(parents=True, exist_ok=True)
log.info("GET %s", url)
path.write_bytes(_get(url, accept))
return path
def fetch_dataflows(force: bool = False) -> Path:
url = f"{config.SDMX3_BASE}/structure/dataflow/{config.AGENCY}/*/*"
return _cached(config.RAW_STRUCTURES_DIR / "dataflows__ISORA.json", url, STRUCTURE_JSON, force)
def fetch_dsd(version: str, force: bool = False) -> Path:
url = (
f"{config.SDMX3_BASE}/structure/datastructure/{config.AGENCY}/DSD_ISORA_PUBLISHED/"
f"{version}?references=descendants"
)
path = config.RAW_STRUCTURES_DIR / f"DSD_ISORA_PUBLISHED__{version}.json"
return _cached(path, url, STRUCTURE_JSON, force)
def fetch_hierarchies(force: bool = False) -> Path:
url = f"{config.SDMX3_BASE}/structure/hierarchy/{config.AGENCY}/*/*"
return _cached(config.RAW_STRUCTURES_DIR / "hierarchies__all.json", url, STRUCTURE_JSON, force)
def fetch_rafit_labels(force: bool = False) -> Path:
url = f"{config.SDMX3_BASE}/structure/codelist/{config.AGENCY}/CL_RAFIT_LABELS/*"
return _cached(
config.RAW_STRUCTURES_DIR / "CL_RAFIT_LABELS__all.json", url, STRUCTURE_JSON, force
)
def fetch_data(dataflow_id: str, version: str, force: bool = False) -> Path:
url = f"{config.SDMX3_BASE}/data/dataflow/{config.AGENCY}/{dataflow_id}/{version}/*"
path = config.RAW_DATA_DIR / f"{dataflow_id}__{version}.csv"
return _cached(path, url, DATA_CSV, force)
def fetch_dataset_metadata(dataflow_id: str, sample_key: str, force: bool = False) -> Path:
"""The SDMX 2.1 CSV repeats dataset-level attributes (license, citation, dates) on every row,
so a single tiny series is enough to capture them."""
url = f"{config.SDMX21_BASE}/data/{dataflow_id}/{sample_key}"
path = config.RAW_STRUCTURES_DIR / f"dataset_metadata__{dataflow_id}.csv"
return _cached(path, url, LEGACY_CSV, force)
METADATA_SAMPLE_KEYS = {
"ISORA_2016_DATA_PUB": "111.10010.A",
"ISORA_2018_DATA_PUB": "111.337_001.A",
"ISORA_LATEST_DATA_PUB": "ABW.PARTICIPATION_RATE.A",
}
def download_everything(force: bool = False) -> None:
"""Fetch every raw artifact the build needs. Safe to re-run; cached files are reused."""
fetch_dataflows(force)
fetch_hierarchies(force)
fetch_rafit_labels(force)
for flow in config.DATAFLOWS:
fetch_dsd(flow.dsd_version, force)
fetch_data(flow.id, flow.version, force)
fetch_dataset_metadata(flow.id, METADATA_SAMPLE_KEYS[flow.id], force)
for version, _label, _years in config.VINTAGES:
fetch_data("ISORA_LATEST_DATA_PUB", version, force)
stamp = config.RAW_DIR / "RETRIEVED_AT.txt"
if force or not stamp.exists():
from datetime import datetime
stamp.write_text(datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") + "\n")
if __name__ == "__main__":
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
download_everything(force="--force" in sys.argv)