File size: 2,205 Bytes
a0d1de2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | """Config loading and dotted-access wrapper."""
from __future__ import annotations
from pathlib import Path
from typing import Any
import yaml
REPO_ROOT = Path(__file__).resolve().parents[2]
CONFIG_DIR = REPO_ROOT / "configs"
class Config(dict):
"""A dict that also supports attribute access and nested ``get`` via dots."""
def __getattr__(self, item: str) -> Any:
try:
value = self[item]
except KeyError as exc:
raise AttributeError(item) from exc
if isinstance(value, dict) and not isinstance(value, Config):
value = Config(value)
self[item] = value
return value
def get_path(self, dotted: str, default: Any = None) -> Any:
node: Any = self
for part in dotted.split("."):
if not isinstance(node, dict) or part not in node:
return default
node = node[part]
return node
def load_config(name_or_path: str = "default") -> Config:
"""Load a YAML config by short name (``default``) or explicit path."""
candidate = Path(name_or_path)
if candidate.suffix in {".yaml", ".yml"} and candidate.exists():
path = candidate
else:
path = CONFIG_DIR / f"{name_or_path}.yaml"
if not path.exists():
raise FileNotFoundError(f"Config not found: {path}")
with path.open("r", encoding="utf-8") as fh:
data = yaml.safe_load(fh) or {}
cfg = Config(data)
_resolve_paths(cfg)
return cfg
def _resolve_paths(cfg: Config) -> None:
"""Make data/outputs/cache dirs absolute under the repo root and create them.
Entries that point to files (path has a suffix, e.g. ``.jsonl``) are resolved
but their parent directory is created; the file itself is not touched.
"""
paths = cfg.get("paths", {})
for key, rel in list(paths.items()):
abs_path = (REPO_ROOT / rel).resolve()
if abs_path.suffix:
# File path — only ensure the parent directory exists
abs_path.parent.mkdir(parents=True, exist_ok=True)
else:
abs_path.mkdir(parents=True, exist_ok=True)
paths[key] = str(abs_path)
cfg["paths"] = Config(paths)
|