-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.py
36 lines (27 loc) · 955 Bytes
/
i18n.py
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
import os
import json
from typing import Optional
class I18nAuto:
def __init__(self, lang: Optional[str] = None) -> None:
if lang is None:
lang_value = os.environ.get("LANG")
if lang_value is None:
raise ValueError("Language not found.")
lang = lang_value.split(".")[0]
if not os.path.exists(f"src/i18n/locale/{lang}.json"):
lang = "en_US"
self.lang = lang
self.lang_map = self._load_lang_list(lang)
def __call__(self, key) -> str:
return self.lang_map.get(key, key)
def __repr__(self) -> str:
return f"Use Language: {self.lang}"
def _load_lang_list(self, lang) -> dict[str, str]:
with open(f"src/i18n/locale/{lang}.json", "r", encoding="utf-8") as f:
lang_list = json.load(f)
return lang_list
def main() -> None:
i18n = I18nAuto()
print(i18n)
if __name__ == "__main__":
main()