toolkit / utils /i18n_utils.py
k4d3's picture
renames
12d27fb
raw
history blame
2.47 kB
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Internationalization utilities for the project.
This module provides centralized internationalization (i18n) functionality using Python's gettext.
It helps maintain consistent translation handling across all scripts in the project by:
1. Setting up the locale based on the system's settings
2. Loading the appropriate translation files (.mo) for each script
3. Providing a fallback to English if translations are unavailable
The translation files should be organized as:
project_root/
└── utils/
└── locales/
└── [language_code]/
└── LC_MESSAGES/
└── [domain].mo
Usage:
from i18n_utils import setup_i18n
# Initialize translation for your script
_ = setup_i18n('your_script_name')
# Use translation in your code
print(_("This text will be translated"))
print(_("Hello {}").format(name))
Note:
The .mo files must be compiled from .po files using msgfmt before they can be used.
Use the compile_translations script to generate .mo files from .po files.
"""
import gettext
import locale
from pathlib import Path
def setup_i18n(domain):
"""Set up internationalization for a specific translation domain.
This function:
1. Attempts to set the locale based on system settings
2. Loads translation files for the specified domain
3. Falls back to untranslated text if translations are unavailable
Args:
domain (str): The translation domain (usually the script name without extension).
This should match the name of your .po/.mo files.
Returns:
callable: A translation function. Pass strings to this function to get translations.
If no translation is found, returns the original string.
Example:
_ = setup_i18n('nocap')
print(_("Hello world")) # Will print "γ“γ‚“γ«γ‘γ―δΈ–η•Œ" if Japanese locale is active
"""
try:
locale.setlocale(locale.LC_ALL, '')
current_locale = locale.getlocale()[0]
if current_locale is None:
current_locale = 'en_US'
locale_path = Path(__file__).parent / 'locales'
trans = gettext.translation(domain, locale_path, languages=[current_locale], fallback=True)
trans.install()
return trans.gettext
except:
return gettext.gettext