import json from pathlib import Path DEFAULT_LANG = "sk" SUPPORTED_LANGS = {"sk", "cs", "en", "de", "hu", "pl", "it"} def normalize_lang(lang: str | None) -> str: value = str(lang or DEFAULT_LANG).strip().lower() if value == "cz": value = "cs" return value if value in SUPPORTED_LANGS else DEFAULT_LANG class Translator: def __init__(self, lang: str = DEFAULT_LANG, locale_dir: str | Path | None = None): self.locale_dir = Path(locale_dir) if locale_dir else Path(__file__).with_name("locales") self.lang = DEFAULT_LANG self.messages: dict[str, str] = {} self.set_lang(lang) def set_lang(self, lang: str | None): self.lang = normalize_lang(lang) fallback = self._load(DEFAULT_LANG) current = self._load(self.lang) if self.lang != DEFAULT_LANG else {} self.messages = {**fallback, **current} def _load(self, lang: str) -> dict[str, str]: path = self.locale_dir / f"{normalize_lang(lang)}.json" if not path.exists(): return {} try: with path.open("r", encoding="utf-8") as f: data = json.load(f) except Exception as e: print(f"Invalid locale JSON : {e}") return {} return {str(k): str(v) for k, v in data.items()} def tr(self, key: str, default: str | None = None, **kwargs) -> str: text = self.messages.get(key, default if default is not None else key) if kwargs: try: return text.format(**kwargs) except Exception: return text return text def available_locales(locale_dir: str | Path | None = None) -> list[str]: base = Path(locale_dir) if locale_dir else Path(__file__).with_name("locales") if not base.exists(): return [] return sorted(path.stem for path in base.glob("*.json"))