Some checks failed
Gitea/kapitanbooru-uploader/pipeline/head There was a failure building this commit
49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
import gettext
|
|
import locale
|
|
from typing import Dict
|
|
from importlib.resources import files
|
|
|
|
class I18N:
|
|
def __init__(self, locale_dir=None):
|
|
# If no locale_dir is provided, use the locales folder relative to this file.
|
|
if locale_dir is None:
|
|
locale_dir = files("kapitanbooru_uploader").joinpath("locales")
|
|
self.locale_dir = str(locale_dir)
|
|
self.languages = {"en": "English", "pl": "Polski"}
|
|
self.current_lang = "en"
|
|
self.translations: Dict[str, str] = {}
|
|
self.load_translations()
|
|
|
|
def load_translations(self):
|
|
"""Load all available translations"""
|
|
for lang in self.languages:
|
|
try:
|
|
trans = gettext.translation(
|
|
"messages", localedir=self.locale_dir, languages=[lang]
|
|
)
|
|
self.translations[lang] = trans.gettext
|
|
except FileNotFoundError:
|
|
self.translations[lang] = lambda x: x
|
|
|
|
def set_language(self, lang: str):
|
|
"""Set application language"""
|
|
if lang in self.languages:
|
|
self.current_lang = lang
|
|
# For Windows language detection
|
|
try:
|
|
locale.setlocale(locale.LC_ALL, self.get_locale_code(lang))
|
|
except locale.Error:
|
|
pass
|
|
|
|
def get_locale_code(self, lang: str) -> str:
|
|
"""Map languages to locale codes"""
|
|
return {"en": "en_US.UTF-8", "pl": "pl_PL.UTF-8"}.get(lang, "en_US.UTF-8")
|
|
|
|
def __call__(self, text: str) -> str:
|
|
"""Translate text using current language"""
|
|
return self.translations[self.current_lang](text)
|
|
|
|
|
|
# Shortcut for translation function
|
|
_ = I18N()
|