goober/modules/translations.py

40 lines
1.6 KiB
Python
Raw Normal View History

2025-06-20 23:48:10 +02:00
import os
import json
import pathlib
from modules.globalvars import RED, RESET
2025-06-20 23:48:10 +02:00
def load_translations():
"""
Loads all translation JSON files from the 'locales' directory.
Returns a dictionary mapping language codes to their translation dictionaries.
"""
2025-06-20 23:48:10 +02:00
translations = {}
# Get the path to the 'locales' directory (one level up from this file)
2025-06-20 23:48:10 +02:00
translations_dir = pathlib.Path(__file__).parent.parent / 'locales'
# Iterate over all files in the 'locales' directory
2025-06-20 23:48:10 +02:00
for filename in os.listdir(translations_dir):
if filename.endswith(".json"):
# Extract language code from filename (e.g., 'en' from 'en.json')
2025-06-20 23:48:10 +02:00
lang_code = filename.replace(".json", "")
# Open and load the JSON file
2025-06-20 23:48:10 +02:00
with open(os.path.join(translations_dir, filename), "r", encoding="utf-8") as f:
translations[lang_code] = json.load(f)
return translations
# Load all translations at module import
2025-06-20 23:48:10 +02:00
translations = load_translations()
def get_translation(lang: str, key: str):
"""
Retrieves the translation for a given key and language.
Falls back to English if the language is not found.
Prints a warning if the key is missing.
"""
# Get translations for the specified language, or fall back to English
2025-06-20 23:48:10 +02:00
lang_translations = translations.get(lang, translations["en"])
if key not in lang_translations:
# Print a warning if the key is missing in the selected language
2025-06-20 23:48:10 +02:00
print(f"{RED}Missing key: {key} in language {lang}{RESET}")
# Return the translation if found, otherwise return the key itself
2025-06-20 23:48:10 +02:00
return lang_translations.get(key, key)