"""Config loading and tiny on-disk JSON cache so re-runs don't re-hit the API.""" from __future__ import annotations import json import os from pathlib import Path import yaml def load_config(path: str = "config.yaml") -> dict: p = Path(path) if not p.exists(): raise SystemExit( f"{path} not found. Copy config.example.yaml -> config.yaml and edit it." ) with p.open() as f: return yaml.safe_load(f) def data_dir(cfg: dict) -> Path: d = Path(cfg.get("data_dir", "data")) d.mkdir(parents=True, exist_ok=True) return d def cache_path(cfg: dict, *parts: str) -> Path: d = data_dir(cfg) for part in parts[:-1]: d = d / part d.mkdir(parents=True, exist_ok=True) return d / parts[-1] def read_json(path: Path): if path.exists(): with path.open() as f: return json.load(f) return None def write_json(path: Path, obj) -> None: tmp = path.with_suffix(path.suffix + ".tmp") with tmp.open("w") as f: json.dump(obj, f) os.replace(tmp, path)