Translations, suggestion box, UX
All checks were successful
Gitea/kapitanbooru-uploader/pipeline/head This commit looks good
All checks were successful
Gitea/kapitanbooru-uploader/pipeline/head This commit looks good
This commit is contained in:
50
kapitanbooru_uploader/I18N.py
Normal file
50
kapitanbooru_uploader/I18N.py
Normal file
@ -0,0 +1,50 @@
|
||||
import gettext
|
||||
import locale
|
||||
import os
|
||||
from typing import Dict
|
||||
|
||||
|
||||
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:
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
locale_dir = os.path.join(current_dir, "locales")
|
||||
self.locale_dir = 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()
|
Reference in New Issue
Block a user