46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
"""Cached JSON config loader for config/<name>_config.json files.
|
|
|
|
Usage:
|
|
from utils.config import load_config
|
|
cfg = load_config("core") # reads config/core_config.json
|
|
conf_threshold = cfg["detection"]["conf"]
|
|
|
|
String values pass through ``os.path.expandvars`` on load, so JSON like
|
|
``"$HOME/miniconda3"`` resolves at read time.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from typing import Any, Dict
|
|
|
|
from core.paths import CONFIG_DIR
|
|
|
|
_CACHE: Dict[str, Dict[str, Any]] = {}
|
|
|
|
|
|
def _expand(value):
|
|
if isinstance(value, str):
|
|
return os.path.expandvars(value)
|
|
if isinstance(value, list):
|
|
return [_expand(v) for v in value]
|
|
if isinstance(value, dict):
|
|
return {k: _expand(v) for k, v in value.items()}
|
|
return value
|
|
|
|
|
|
def load_config(name: str) -> Dict[str, Any]:
|
|
"""Return the parsed JSON config for ``config/<name>_config.json`` (cached)."""
|
|
if name in _CACHE:
|
|
return _CACHE[name]
|
|
|
|
path = CONFIG_DIR / f"{name}_config.json"
|
|
if not path.exists():
|
|
raise FileNotFoundError(f"Config not found: {path}")
|
|
|
|
with open(path, "r") as f:
|
|
raw = json.load(f)
|
|
cfg = _expand(raw)
|
|
_CACHE[name] = cfg
|
|
return cfg
|