KankenOnline/kanken_online/lang.py

35 lines
1.1 KiB
Python
Raw Normal View History

import json
from pathlib import Path
from flask import session
LanguageMapping = dict[str, str]
2024-10-14 10:49:16 +00:00
def load_language(lang_code: str) -> LanguageMapping:
with open(Path("kanken_online/static/lang", f"{lang_code}.json")) as f:
return json.load(f)
2024-10-14 10:49:16 +00:00
LANGUAGES = {}
2024-10-14 10:49:16 +00:00
def update_languages():
ENGLISH = load_language("en")
JAPANESE = load_language("ja")
global LANGUAGES
LANGUAGES = {
"en": ENGLISH,
"ja": JAPANESE
}
update_languages()
2024-10-14 10:49:16 +00:00
# assert all(all(key in lang for key in EXISTING_STRINGS) for lang in LANGUAGES) # Ensure all strings are mapped for all existing languages
# assert not [key for lang in LANGUAGES for key in lang if ((key in lang) and (key not in EXISTING_STRINGS))]
2024-10-14 11:46:16 +00:00
# assert not any((((key in lang) and (key not in EXISTING_STRINGS)) for key in lang) for lang in LANGUAGES) # Ensure no languages have strings not specified by the main index
2024-10-14 10:49:16 +00:00
def localize(text_id: str, language: dict[str, str] = None) -> str:
if language is None:
2024-10-14 16:31:54 +00:00
preference = session.get("language", "ja")
language = LANGUAGES.get(preference)
2024-10-14 10:49:16 +00:00
return language[text_id]