from collections.abc import MutableMapping from json import load from pathlib import Path LANG_DIR = Path(__file__).parent / "lang" FALLBACK_LANG = "en" LANG_CACHE: dict[str, dict[str, str]] = {} # https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys def __flatten(dictionary: dict, parent_key: str = "") -> dict[str, str]: items = [] for key, value in dictionary.items(): new_key = parent_key + "." + key if parent_key else key if isinstance(value, MutableMapping): items.extend(__flatten(value, new_key).items()) else: items.append((new_key, value)) return dict(items) def __get_lang_data(lang: str) -> dict[str, str]: if lang not in LANG_CACHE: file = LANG_DIR / f"{lang}.json" if not file.exists(): return __get_lang_data(FALLBACK_LANG) with file.open() as f: raw_data: dict = load(f) LANG_CACHE[lang] = __flatten(raw_data) return LANG_CACHE[lang] def get_lang(lang: str, key: str) -> str: data = __get_lang_data(lang) return data.get(key, key)