onwAMD / onw /i18n.py
ryugyosoft's picture
onw AMD 0.1.0: LLMs on the AMD Ryzen AI NPU through FastFlowLM
d0bf6e2 verified
Raw History Blame Contribute Delete
2.86 kB
"""UI language. The UI is written in Japanese; i18n.json maps those strings to English and Simplified Chinese.
T("ロードできません: {0}", e) the string in the current language (config "lang": auto / ja / en / zh)
page(path) an HTML page with the table for its language (web/i18n.js does the swapping)
"""
import json, os, time
HERE = os.path.dirname(os.path.abspath(__file__))
LANGS = {"ja": "日本語", "en": "English", "zh": "简体中文"}
_table = None
_cur = (0.0, "ja")
def table():
global _table
if _table is None:
with open(os.path.join(HERE, "i18n.json"), encoding="utf8") as f:
_table = json.load(f)
return _table
def system():
"""The OS display language: ja / zh / en (everything else)."""
try:
if os.name == "nt":
import ctypes
return {0x11: "ja", 0x04: "zh"}.get(ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF, "en")
v = next((os.environ[k] for k in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG") if os.environ.get(k)), "")
return "ja" if v.startswith("ja") else "zh" if v.startswith("zh") else "en"
except Exception:
return "en"
def current(cfg=None):
global _cur
if cfg is None:
if time.time() - _cur[0] < 2: # T() is called many times per page refresh
return _cur[1]
from . import app
cfg = app.load_config()
v = cfg.get("lang", "auto")
lang = v if v in LANGS else system()
_cur = (time.time(), lang)
return lang
def strings(lang):
"""Japanese -> lang (Chinese falls back to English where it has no entry)."""
if lang == "ja":
return {}
t = table()
return {**t.get("en", {}), **t.get(lang, {})}
def T(s, *a, lang=None):
lang = lang or current()
r = s if lang == "ja" else strings(lang).get(s, s)
return r.format(*a) if a else r
def page(path, lang=None):
"""The page's HTML with its language table and web/i18n.js in place of the <script>/*i18n*/</script> marker."""
if lang is None:
from . import app
lang = current(app.load_config()) # not the cached value: the page may follow a language change
html = open(path, encoding="utf8").read()
js = open(os.path.join(HERE, "web", "i18n.js"), encoding="utf8").read()
data = json.dumps(strings(lang), ensure_ascii=False).replace("</", "<\\/")
html = html.replace('<html lang="ja">', f'<html lang="{lang}">', 1)
zh = ('<style>html:lang(zh) body { font-family: system-ui, "Segoe UI", "Microsoft YaHei UI", "PingFang SC", '
'"Noto Sans CJK SC", "Noto Sans SC", sans-serif; }</style>\n')
html = html.replace("<script>/*i18n*/</script>", f"{zh}<script>const LANG = {json.dumps(lang)}, I18N = {data};\n{js}</script>", 1)
return html.encode("utf8")