Skip to main content

A lightweight, zero-dependency Python library for internationalization and translation management.

Project description

๐ŸŒ TransX

English | ็ฎ€ไฝ“ไธญๆ–‡

๐Ÿš€ A lightweight, zero-dependency Python internationalization library that supports Python 2.7 through 3.12.

The API is designed to be DCC-friendly, for example, works with Maya, 3DsMax, Houdini, etc.

Python Version Nox PyPI Version Downloads Downloads Downloads License PyPI Format Maintenance


โœจ Features

TransX provides a comprehensive set of features for internationalization:

  • ๐Ÿš€ Zero Dependencies: No external dependencies required
  • ๐Ÿ Python Support: Full support for Python 2.7-3.12
  • ๐ŸŒ Context-based: Accurate translations with context support
  • ๐Ÿ“ฆ Standard Format: Compatible with gettext .po/.mo files
  • ๐ŸŽฏ Simple API: Clean and intuitive interface
  • ๐Ÿ”„ Auto Management: Automatic translation file handling
  • ๐Ÿ” String Extraction: Built-in source code string extraction
  • ๐ŸŒ Unicode: Complete Unicode support
  • ๐Ÿ”  Parameters: Named, positional and ${var} style parameters
  • ๐Ÿ’ซ Variable Support: Environment variable expansion support
  • โšก Performance: High-speed and thread-safe operations
  • ๐Ÿ›ก๏ธ Error Handling: Comprehensive error management with fallbacks
  • ๐Ÿงช Testing: 100% test coverage with extensive cases
  • ๐ŸŒ Auto Translation: Built-in Google Translate API support
  • ๐ŸŽฅ DCC Support: Tested with Maya, 3DsMax, Houdini, etc.
  • ๐Ÿ”Œ Extensible: Pluggable custom text interpreters system
  • ๐ŸŽจ Flexible Formatting: Support for various string format styles
  • ๐Ÿ”„ Runtime Switching: Dynamic locale switching at runtime
  • ๐Ÿ“ฆ GNU gettext: Full compatibility with GNU gettext standard and tools

GNU gettext Compatibility

TransX is fully compatible with the GNU gettext standard, providing seamless integration with existing translation workflows:

  • Standard Formats: Full support for .po and .mo file formats according to GNU gettext specifications
  • File Structure: Follows the standard locale directory structure (LC_MESSAGES/domain.{po,mo})
  • Header Support: Complete support for gettext headers and metadata
  • Plural Forms: Compatible with gettext plural form expressions and handling
  • Context Support: Full support for msgctxt (message context) using gettext standard separators
  • Encoding: Proper handling of character encodings as specified in PO/MO headers
  • Tools Integration: Works with standard gettext tools (msgfmt, msginit, msgmerge, etc.)
  • Binary Format: Implements the official MO file format specification with both little and big endian support

This means you can:

  • Use existing PO editors like Poedit, Lokalize, or GTranslator
  • Integrate with established translation workflows
  • Migrate existing gettext-based translations seamlessly
  • Use standard gettext tools alongside TransX
  • Maintain compatibility with other gettext-based systems

๐Ÿš€ Quick Start

๐Ÿ“ฅ Installation

pip install transx

๐Ÿ“ Basic Usage

from transx import TransX

# Initialize with locale directory
tx = TransX(locales_root="./locales")

# Basic translation
print(tx.tr("Hello"))  # Output: ไฝ ๅฅฝ

# Translation with parameters
print(tx.tr("Hello {name}!", name="ๅผ ไธ‰"))  # Output: ไฝ ๅฅฝ ๅผ ไธ‰๏ผ

# Context-based translation
print(tx.tr("Open", context="button"))  # ๆ‰“ๅผ€
print(tx.tr("Open", context="menu"))    # ๆ‰“ๅผ€ๆ–‡ไปถ

# Switch language at runtime
tx.switch_locale("ja_JP")
print(tx.tr("Hello"))  # Output: ใ“ใ‚“ใซใกใฏ

๐Ÿ”„ Translation API

TransX provides two main methods for translation with different levels of functionality:

tr() - High-Level Translation API

The tr() method is the recommended high-level API that provides all translation features:

# Basic translation
tx.tr("Hello")  # ไฝ ๅฅฝ

# Translation with parameters
tx.tr("Hello {name}!", name="ๅผ ไธ‰")  # ไฝ ๅฅฝ ๅผ ไธ‰๏ผ

# Context-based translation
tx.tr("Open", context="button")  # ๆ‰“ๅผ€
tx.tr("Open", context="menu")    # ๆ‰“ๅผ€ๆ–‡ไปถ

# Environment variable expansion
tx.tr("Home: $HOME")  # Home: /Users/username

# Dollar sign escaping
tx.tr("Price: $$99.99")  # Price: $99.99

# Complex parameter substitution
tx.tr("Welcome to ${city}, {country}!", city="ๅŒ—ไบฌ", country="ไธญๅ›ฝ")

translate() - Low-Level Translation API

The translate() method is a lower-level API that provides basic translation and parameter substitution:

# Basic translation
tx.translate("Hello")  # ไฝ ๅฅฝ

# Translation with context
tx.translate("Open", context="button")  # ๆ‰“ๅผ€

# Simple parameter substitution
tx.translate("Hello {name}!", name="ๅผ ไธ‰")  # ไฝ ๅฅฝ ๅผ ไธ‰๏ผ

The main differences between tr() and translate():

Feature tr() translate()
Basic Translation โœ… โœ…
Context Support โœ… โœ…
Parameter Substitution โœ… โœ…
Environment Variables โœ… โŒ
${var} Style Variables โœ… โŒ
$$ Escaping โœ… โŒ
Interpreter Chain โœ… โŒ

Choose tr() for full functionality or translate() for simpler use cases where you only need basic translation and parameter substitution.

๐Ÿ”„ Advanced Parameter Substitution

# Named parameters
tx.tr("Welcome to {city}, {country}!", city="ๅŒ—ไบฌ", country="ไธญๅ›ฝ")

# Positional parameters
tx.tr("File {0} of {1}", 1, 10)

# Dollar sign variables (useful in shell-like contexts)
tx.tr("Current user: ${USER}")  # Supports ${var} syntax
tx.tr("Path: $HOME/documents")  # Supports $var syntax

# Escaping dollar signs
tx.tr("Price: $$99.99")  # Outputs: Price: $99.99

๐ŸŒ Available Locales

TransX provides a convenient way to get a list of available locales in your project:

from transx import TransX

tx = TransX(locales_root="./locales")

# Get list of available locales
print(f"Available locales: {tx.available_locales}")  # e.g. ['en_US', 'zh_CN', 'ja_JP']

# Check if a locale is available before switching
if "zh_CN" in tx.available_locales:
    tx.current_locale = "zh_CN"

The available_locales property returns a sorted list of locale codes that:

  • Have a valid locale directory structure (LC_MESSAGES folder)
  • Contain either .po or .mo translation files
  • Are ready to use for translation

This is useful for:

  • Building language selection interfaces
  • Validating locale switches
  • Checking translation file completeness
  • Displaying supported languages to users

๐Ÿ› ๏ธ Command Line Interface

TransX provides a powerful CLI for translation management:

Extract Messages

# Extract from a single file
transx extract app.py -o messages.pot

# Extract from a directory with project info
transx extract ./src -o messages.pot -p "MyProject" -v "1.0"

# Extract and specify languages
transx extract ./src -l "en_US,zh_CN,ja_JP"

Update PO Files

# Update or create PO files for specific languages
transx update messages.pot -l "zh_CN,ja_JP,ko_KR"

# Auto-discover and update all language files
transx update messages.pot

# Update with custom output directory
transx update messages.pot -o ./locales

Compile MO Files

# Compile a single PO file
transx compile path/to/messages.po

# Compile all PO files in a directory
transx compile -d ./locales

# Compile multiple specific files
transx compile file1.po file2.po

List Available Locales

# List all available locales in default directory
transx list

# List locales in a specific directory
transx list -d /path/to/locales

Common Options

  • -d, --directory: Specify working directory
  • -o, --output: Specify output file/directory
  • -l, --languages: Comma-separated list of language codes
  • -p, --project: Project name (for POT generation)
  • -v, --version: Project version (for POT generation)

For detailed help on any command:

transx <command> --help

๐ŸŽฏ Advanced Features

Context-Based Translations

# UI Context
print(tx.tr("Open", context="button"))  # ๆ‰“ๅผ€
print(tx.tr("Open", context="menu"))    # ๆ‰“ๅผ€ๆ–‡ไปถ

# Part of Speech
print(tx.tr("Post", context="verb"))    # ๅ‘ๅธƒ
print(tx.tr("Post", context="noun"))    # ๆ–‡็ซ 

# Scene Context
print(tx.tr("Welcome", context="login")) # ๆฌข่ฟŽ็™ปๅฝ•
print(tx.tr("Welcome", context="home"))  # ๆฌข่ฟŽๅ›žๆฅ

Error Handling

TransX provides comprehensive error handling with fallback mechanisms:

from transx import TransX
from transx.exceptions import LocaleNotFoundError, TranslationError

# Enable strict mode for development
tx = TransX(strict_mode=True)

try:
    tx.load_catalog("invalid_locale")
except LocaleNotFoundError as e:
    print(f"โŒ Locale error: {e.message}")

try:
    result = tx.translate("Hello", target_lang="invalid")
except TranslationError as e:
    print(f"โŒ Translation failed: {e.message}")

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“ Project Structure

transx/
โ”œโ”€โ”€ transx/                 # Main package directory
โ”‚   โ”œโ”€โ”€ api/               # Public API modules
โ”‚   โ”‚   โ”œโ”€โ”€ locale.py      # Locale handling
โ”‚   โ”‚   โ”œโ”€โ”€ mo.py         # MO file operations
โ”‚   โ”‚   โ”œโ”€โ”€ po.py         # PO file operations
โ”‚   โ”‚   โ””โ”€โ”€ translate.py   # Translation services
โ”‚   โ”œโ”€โ”€ core.py           # Core functionality
โ”‚   โ”œโ”€โ”€ cli.py            # Command-line interface
โ”‚   โ”œโ”€โ”€ constants.py       # Constants and configurations
โ”‚   โ””โ”€โ”€ exceptions.py      # Custom exceptions
โ”œโ”€โ”€ tests/                 # Test directory
โ”œโ”€โ”€ examples/              # Example code and usage
โ”œโ”€โ”€ nox_actions/          # Nox automation scripts
โ”œโ”€โ”€ docs/                 # Documentation
โ”œโ”€โ”€ pyproject.toml        # Project configuration
โ””โ”€โ”€ noxfile.py           # Test automation configuration

โšก Performance Features

  • ๐Ÿš€ Uses compiled MO files for optimal speed
  • ๐Ÿ’พ Automatic translation caching
  • ๐Ÿ”’ Thread-safe for concurrent access
  • ๐Ÿ“‰ Minimal memory footprint
  • ๐Ÿ”„ Automatic PO to MO compilation

๐Ÿ”ง Development Setup

  1. Clone the repository:
git clone https://github.com/loonghao/transx.git
cd transx
  1. Install development dependencies:
pip install -r requirements-dev.txt

๐Ÿ”„ Development Workflow

We use Nox to automate development tasks. Here are the main commands:

# Run linting
nox -s lint

# Fix linting issues automatically
nox -s lint-fix

# Run tests
nox -s pytest

๐Ÿงช Running Tests

Tests are written using pytest and can be run using nox:

nox -s pytest

For running specific tests:

# Run a specific test file
nox -s pytest -- tests/test_core.py

# Run tests with specific markers
nox -s pytest -- -m "not integration"

๐Ÿ” Code Quality

We maintain high code quality standards using various tools:

  • Linting: We use ruff and isort for code linting and formatting
  • Type Checking: Static type checking with mypy
  • Testing: Comprehensive test suite with pytest
  • Coverage: Code coverage tracking with coverage.py
  • CI/CD: Automated testing and deployment with GitHub Actions

๐Ÿ“ Documentation

Documentation is written in Markdown and is available in:

  • README.md: Main documentation
  • examples/: Example code and usage
  • API documentation in source code

๐Ÿค Contributing Guidelines

  1. Fork the repository
  2. Create a new branch for your feature
  3. Make your changes
  4. Run tests and linting
  5. Submit a pull request

Please ensure your PR:

  • Passes all tests
  • Includes appropriate documentation
  • Follows our code style
  • Includes test coverage for new features

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

transx-0.5.1.tar.gz (47.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

transx-0.5.1-py2.py3-none-any.whl (51.8 kB view details)

Uploaded Python 2Python 3

File details

Details for the file transx-0.5.1.tar.gz.

File metadata

  • Download URL: transx-0.5.1.tar.gz
  • Upload date:
  • Size: 47.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for transx-0.5.1.tar.gz
Algorithm Hash digest
SHA256 ee48f3115a1d2724db417e1814812747da751a11510eaf0bc085b7d190ae86fd
MD5 b6e23373b0408a73c2560a456d53fcef
BLAKE2b-256 1464886fabb5398fc521be231134c87bf146b3f344f2e1f338f3893f4c95d744

See more details on using hashes here.

Provenance

The following attestation bundles were made for transx-0.5.1.tar.gz:

Publisher: python-publish.yml on loonghao/transx

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file transx-0.5.1-py2.py3-none-any.whl.

File metadata

  • Download URL: transx-0.5.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 51.8 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for transx-0.5.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 37795d34a8ace5ce2c694e1f51e9cfd87f576fa993f616e075cc0da5db94090e
MD5 e8638f4049da54ade40d8945ecb21cfe
BLAKE2b-256 499a861e5a39b18dc5b3373a3d59a5329bac7feefad3c42bf4885ac9e2bf343e

See more details on using hashes here.

Provenance

The following attestation bundles were made for transx-0.5.1-py2.py3-none-any.whl:

Publisher: python-publish.yml on loonghao/transx

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page