transx


Nametransx JSON
Version 0.6.1 PyPI version JSON
download
home_pageNone
SummaryA lightweight, zero-dependency Python library for internationalization and translation management.
upload_time2024-12-12 16:23:11
maintainerNone
docs_urlNone
authorlonghao
requires_python<4.0,>=2.7
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ๐ŸŒ TransX

English | [็ฎ€ไฝ“ไธญๆ–‡](README_zh.md)

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

The API is designed to be [DCC](https://en.wikipedia.org/wiki/Digital_content_creation)-friendly, for example, works with [Maya](https://www.autodesk.com/products/maya/overview), [3DsMax](https://www.autodesk.com/products/3ds-max/overview), [Houdini](https://www.sidefx.com/products/houdini/), etc.


<div align="center">

[![Python Version](https://img.shields.io/pypi/pyversions/transx)](https://img.shields.io/pypi/pyversions/transx)
[![Nox](https://img.shields.io/badge/%F0%9F%A6%8A-Nox-D85E00.svg)](https://github.com/wntrblm/nox)
[![PyPI Version](https://img.shields.io/pypi/v/transx?color=green)](https://pypi.org/project/transx/)
[![Downloads](https://static.pepy.tech/badge/transx)](https://pepy.tech/project/transx)
[![Downloads](https://static.pepy.tech/badge/transx/month)](https://pepy.tech/project/transx)
[![Downloads](https://static.pepy.tech/badge/transx/week)](https://pepy.tech/project/transx)
[![License](https://img.shields.io/pypi/l/transx)](https://pypi.org/project/transx/)
[![PyPI Format](https://img.shields.io/pypi/format/transx)](https://pypi.org/project/transx/)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/loonghao/transx/graphs/commit-activity)
![Codecov](https://img.shields.io/codecov/c/github/loonghao/transx)
[![Benchmarks](https://img.shields.io/badge/benchmarks-view%20performance-blue)](https://loonghao.github.io/transx-benchmarks/)
</div>

---

## โœจ 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
- ๐ŸŽจ **Flexible Formatting**: Multiple string formatting styles
- ๐Ÿ”„ **Runtime Switching**: Dynamic locale switching at runtime
- ๐Ÿ”ง **Qt Integration**: Built-in support for Qt translations
- ๐Ÿ“ **Message Extraction**: Advanced source code message extraction with context
- ๐ŸŒ **Multi-App Support**: Multiple translation instances for different apps

## 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

```bash
pip install transx
```

### ๐Ÿ“ Basic Usage

```python
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:


```python
# 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:


```python
# 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


```python
# 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:


```python
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 command-line interface for common translation tasks. When no arguments are provided for commands, TransX will use the `./locales` directory in your current working directory as the default path.

```bash
# Extract messages from source files
# Default: Will look for source files in current directory and output to ./locales
transx extract

# Same as:
transx extract . --output ./locales/messages.pot

# Update .po files with new translations
# Default: Will update .po files in ./locales
transx update

# Same as:
transx update ./locales

# Compile .po files to .mo files
# Default: Will compile .po files from ./locales
transx compile

# Same as:
transx compile ./locales
```

The default working directory structure:
```
./
โ””โ”€โ”€ locales/           # Default translation directory
    โ”œโ”€โ”€ messages.pot   # Extracted messages template
    โ”œโ”€โ”€ en/           # English translations
    โ”‚   โ””โ”€โ”€ LC_MESSAGES/
    โ”‚       โ”œโ”€โ”€ messages.po
    โ”‚       โ””โ”€โ”€ messages.mo
    โ””โ”€โ”€ zh_CN/        # Chinese translations
        โ””โ”€โ”€ LC_MESSAGES/
            โ”œโ”€โ”€ messages.po
            โ””โ”€โ”€ messages.mo
```

### Extract Messages
```bash
# 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
```bash
# 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
```bash
# 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
```bash
# 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:
```bash
transx <command> --help
```


## ๐Ÿš€ Advanced Features

### ๐Ÿ–ฅ๏ธ Qt Usage

TransX can be used with Qt applications in two ways:

#### Basic Integration

Use TransX directly in your Qt application:

```python
from PySide2.QtWidgets import QMainWindow
from transx import get_transx_instance

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.tx = get_transx_instance("myapp")

        # Translate window title
        self.setWindowTitle(self.tx.tr("My Application"))

        # Translate menu items
        file_menu = self.menuBar().addMenu(self.tx.tr("&File"))
        file_menu.addAction(self.tx.tr("&Open"))
        file_menu.addAction(self.tx.tr("&Save"))
```

#### Qt Translator Integration

For Qt's built-in translation system, you'll need to:
1. First convert your .po files to .qm format using Qt's lrelease tool
2. Install the .qm files using TransX's Qt extension

```python
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtCore import QTranslator
from transx.extensions.qt import install_qt_translator

app = QApplication([])
translator = QTranslator()

# Install translator for specific locale
# Make sure qt_zh_CN.qm exists in ./translations directory
install_qt_translator(app, translator, "zh_CN", "./translations")

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # Note: Qt's tr() will only work with .qm files
        # For Python strings, use TransX's tr() function
        self.setWindowTitle("My Application")  # This won't be translated
```

Converting .po to .qm files:
```bash
# Using Qt's lrelease tool
lrelease translations/zh_CN/LC_MESSAGES/messages.po -qm translations/qt_zh_CN.qm
```

> Note: The `lrelease` tool is part of Qt's Linguist tools:
> - Windows: Install with Qt installer from [qt.io](https://www.qt.io/download) (Look for Qt Linguist under Tools)
> - Linux: Install via package manager
>   ```bash
>   # Ubuntu/Debian
>   sudo apt-get install qttools5-dev-tools
>
>   # Fedora
>   sudo dnf install qt5-linguist
>
>   # Arch Linux
>   sudo pacman -S qt5-tools
>   ```
> - macOS: Install via Homebrew
>   ```bash
>   brew install qt5
>   ```

The Qt integration supports:
- Loading .qm format translation files
- Multiple translator instances
- Note: Qt's built-in tr() function requires .qm files and won't work with .mo files

### ๐Ÿ” Message Extraction

Extract translatable messages from your source code with powerful context support:

```python
from transx.api.pot import PotExtractor

# Initialize extractor with output file
extractor = PotExtractor(pot_file="messages.pot")

# Add source files or directories to scan
extractor.add_source_file("app.py")
extractor.add_source_file("utils.py")
# Or scan entire directories
extractor.add_source_directory("src")

# Extract messages with project info
extractor.save_pot(
    project="MyApp",
    version="1.0.0",
    copyright_holder="Your Name",
    bugs_address="your.email@example.com"
)
```

### ๐ŸŒ Multi-App Support

Manage multiple translation instances for different applications or components:

```python
from transx import get_transx_instance

# Create instances for different apps or components
app1 = get_transx_instance("app1", default_locale="en_US")
app2 = get_transx_instance("app2", default_locale="zh_CN")

# Each instance has its own:
# - Translation catalog
# - Locale settings
# - Message domains
app1.tr("Hello")  # Uses app1's translations
app2.tr("Hello")  # Uses app2's translations

# Switch locales independently
app1.switch_locale("ja_JP")
app2.switch_locale("ko_KR")
```

Multi-app support features:
- Independent translation catalogs
- Separate locale settings per instance
- Thread-safe operation

### ๐Ÿ”ค Context-Based Translations

```python
# 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:

```python
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}")
```

## ๐Ÿ“„ Performance

TransX is designed with performance in mind. We continuously monitor and optimize its performance through automated benchmarks.

View our performance benchmarks at: [TransX Benchmarks](https://loonghao.github.io/transx-benchmarks/)

Our benchmark suite includes:
- Translation lookup performance
- Parameter substitution performance
- Locale switching performance
- Cache efficiency
- Memory usage
- Concurrent operations
- And more...

## ๐Ÿ› ๏ธ Development

### ๐Ÿ”ง Environment Setup

1. Clone the repository:
```bash
git clone https://github.com/loonghao/transx.git
cd transx
```

2. Install development dependencies:
```bash
pip install -r requirements-dev.txt
```


### ๐Ÿ“ฆ Project Structure

TransX follows a well-organized package structure:

```
transx/
โ”œโ”€โ”€ transx/                  # Main package directory
โ”‚   โ”œโ”€โ”€ __init__.py         # Package initialization
โ”‚   โ”œโ”€โ”€ __version__.py      # Version information
โ”‚   โ”œโ”€โ”€ api/                # Public API modules
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ mo.py          # MO file operations
โ”‚   โ”‚   โ”œโ”€โ”€ po.py          # PO file operations
โ”‚   โ”‚   โ””โ”€โ”€ pot.py         # POT file operations
โ”‚   โ”œโ”€โ”€ app.py             # Application management
โ”‚   โ”œโ”€โ”€ cli.py             # Command-line interface
โ”‚   โ”œโ”€โ”€ constants.py        # Constants and configurations
โ”‚   โ”œโ”€โ”€ context/           # Translation context management
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ manager.py    # Context manager implementation
โ”‚   โ”œโ”€โ”€ core.py            # Core functionality
โ”‚   โ”œโ”€โ”€ exceptions.py       # Custom exceptions
โ”‚   โ”œโ”€โ”€ extensions/        # Framework integrations
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ””โ”€โ”€ qt.py         # Qt support
โ”‚   โ””โ”€โ”€ internal/          # Internal implementation details
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ compat.py     # Python 2/3 compatibility
โ”‚       โ”œโ”€โ”€ filesystem.py # File system operations
โ”‚       โ””โ”€โ”€ logging.py    # Logging utilities
โ”œโ”€โ”€ examples/              # Example code
โ”œโ”€โ”€ locales/              # Translation files
โ”œโ”€โ”€ tests/                # Test suite
โ”œโ”€โ”€ nox_actions/          # Nox automation scripts
โ”œโ”€โ”€ CHANGELOG.md          # Version history
โ”œโ”€โ”€ LICENSE              # MIT License
โ”œโ”€โ”€ README.md            # English documentation
โ”œโ”€โ”€ README_zh.md         # Chinese documentation
โ”œโ”€โ”€ noxfile.py           # Test automation config
โ”œโ”€โ”€ pyproject.toml       # Project configuration
โ”œโ”€โ”€ requirements.txt     # Production dependencies
โ””โ”€โ”€ requirements-dev.txt # Development dependencies
```

### ๐Ÿ”„ Development Workflow

We use [Nox](https://nox.thea.codes/) to automate development tasks. Here are the main commands:


```bash
# 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:


```bash
nox -s pytest
```


For running specific tests:


```bash
# 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](LICENSE) file for details.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "transx",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=2.7",
    "maintainer_email": null,
    "keywords": null,
    "author": "longhao",
    "author_email": "hal.long@outlook.com",
    "download_url": "https://files.pythonhosted.org/packages/b7/ab/ec74017fa6d70e8586ba6ed6846e08a7a23cbe0f64109b29a1376f58492c/transx-0.6.1.tar.gz",
    "platform": null,
    "description": "# \ud83c\udf0f TransX\n\nEnglish | [\u7b80\u4f53\u4e2d\u6587](README_zh.md)\n\n\ud83d\ude80 A lightweight, zero-dependency Python internationalization library that supports Python 2.7 through 3.12.\n\nThe API is designed to be [DCC](https://en.wikipedia.org/wiki/Digital_content_creation)-friendly, for example, works with [Maya](https://www.autodesk.com/products/maya/overview), [3DsMax](https://www.autodesk.com/products/3ds-max/overview), [Houdini](https://www.sidefx.com/products/houdini/), etc.\n\n\n<div align=\"center\">\n\n[![Python Version](https://img.shields.io/pypi/pyversions/transx)](https://img.shields.io/pypi/pyversions/transx)\n[![Nox](https://img.shields.io/badge/%F0%9F%A6%8A-Nox-D85E00.svg)](https://github.com/wntrblm/nox)\n[![PyPI Version](https://img.shields.io/pypi/v/transx?color=green)](https://pypi.org/project/transx/)\n[![Downloads](https://static.pepy.tech/badge/transx)](https://pepy.tech/project/transx)\n[![Downloads](https://static.pepy.tech/badge/transx/month)](https://pepy.tech/project/transx)\n[![Downloads](https://static.pepy.tech/badge/transx/week)](https://pepy.tech/project/transx)\n[![License](https://img.shields.io/pypi/l/transx)](https://pypi.org/project/transx/)\n[![PyPI Format](https://img.shields.io/pypi/format/transx)](https://pypi.org/project/transx/)\n[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/loonghao/transx/graphs/commit-activity)\n![Codecov](https://img.shields.io/codecov/c/github/loonghao/transx)\n[![Benchmarks](https://img.shields.io/badge/benchmarks-view%20performance-blue)](https://loonghao.github.io/transx-benchmarks/)\n</div>\n\n---\n\n## \u2728 Features\n\nTransX provides a comprehensive set of features for internationalization:\n\n- \ud83d\ude80 **Zero Dependencies**: No external dependencies required\n- \ud83d\udc0d **Python Support**: Full support for Python 2.7-3.12\n- \ud83c\udf0d **Context-based**: Accurate translations with context support\n- \ud83d\udce6 **Standard Format**: Compatible with gettext .po/.mo files\n- \ud83c\udfaf **Simple API**: Clean and intuitive interface\n- \ud83d\udd04 **Auto Management**: Automatic translation file handling\n- \ud83d\udd0d **String Extraction**: Built-in source code string extraction\n- \ud83c\udf10 **Unicode**: Complete Unicode support\n- \ud83d\udd20 **Parameters**: Named, positional and ${var} style parameters\n- \ud83d\udcab **Variable Support**: Environment variable expansion support\n- \u26a1 **Performance**: High-speed and thread-safe operations\n- \ud83d\udee1\ufe0f **Error Handling**: Comprehensive error management with fallbacks\n- \ud83e\uddea **Testing**: 100% test coverage with extensive cases\n- \ud83c\udf10 **Auto Translation**: Built-in Google Translate API support\n- \ud83c\udfa5 **DCC Support**: Tested with Maya, 3DsMax, Houdini, etc.\n- \ud83d\udd0c **Extensible**: Pluggable custom text interpreters\n- \ud83c\udfa8 **Flexible Formatting**: Multiple string formatting styles\n- \ud83d\udd04 **Runtime Switching**: Dynamic locale switching at runtime\n- \ud83d\udd27 **Qt Integration**: Built-in support for Qt translations\n- \ud83d\udcdd **Message Extraction**: Advanced source code message extraction with context\n- \ud83c\udf10 **Multi-App Support**: Multiple translation instances for different apps\n\n## GNU gettext Compatibility\n\nTransX is fully compatible with the GNU gettext standard, providing seamless integration with existing translation workflows:\n\n- **Standard Formats**: Full support for `.po` and `.mo` file formats according to GNU gettext specifications\n- **File Structure**: Follows the standard locale directory structure (`LC_MESSAGES/domain.{po,mo}`)\n- **Header Support**: Complete support for gettext headers and metadata\n- **Plural Forms**: Compatible with gettext plural form expressions and handling\n- **Context Support**: Full support for msgctxt (message context) using gettext standard separators\n- **Encoding**: Proper handling of character encodings as specified in PO/MO headers\n- **Tools Integration**: Works with standard gettext tools (msgfmt, msginit, msgmerge, etc.)\n- **Binary Format**: Implements the official MO file format specification with both little and big endian support\n\nThis means you can:\n- Use existing PO editors like Poedit, Lokalize, or GTranslator\n- Integrate with established translation workflows\n- Migrate existing gettext-based translations seamlessly\n- Use standard gettext tools alongside TransX\n- Maintain compatibility with other gettext-based systems\n\n## \ud83d\ude80 Quick Start\n\n### \ud83d\udce5 Installation\n\n```bash\npip install transx\n```\n\n### \ud83d\udcdd Basic Usage\n\n```python\nfrom transx import TransX\n\n# Initialize with locale directory\ntx = TransX(locales_root=\"./locales\")\n\n# Basic translation\nprint(tx.tr(\"Hello\"))  # Output: \u4f60\u597d\n\n# Translation with parameters\nprint(tx.tr(\"Hello {name}!\", name=\"\u5f20\u4e09\"))  # Output: \u4f60\u597d \u5f20\u4e09\uff01\n\n# Context-based translation\nprint(tx.tr(\"Open\", context=\"button\"))  # \u6253\u5f00\nprint(tx.tr(\"Open\", context=\"menu\"))    # \u6253\u5f00\u6587\u4ef6\n\n# Switch language at runtime\ntx.switch_locale(\"ja_JP\")\nprint(tx.tr(\"Hello\"))  # Output: \u3053\u3093\u306b\u3061\u306f\n```\n\n### \ud83d\udd04 Translation API\n\nTransX provides two main methods for translation with different levels of functionality:\n\n\n#### tr() - High-Level Translation API\n\nThe `tr()` method is the recommended high-level API that provides all translation features:\n\n\n```python\n# Basic translation\ntx.tr(\"Hello\")  # \u4f60\u597d\n\n# Translation with parameters\ntx.tr(\"Hello {name}!\", name=\"\u5f20\u4e09\")  # \u4f60\u597d \u5f20\u4e09\uff01\n\n# Context-based translation\ntx.tr(\"Open\", context=\"button\")  # \u6253\u5f00\ntx.tr(\"Open\", context=\"menu\")    # \u6253\u5f00\u6587\u4ef6\n\n# Environment variable expansion\ntx.tr(\"Home: $HOME\")  # Home: /Users/username\n\n# Dollar sign escaping\ntx.tr(\"Price: $$99.99\")  # Price: $99.99\n\n# Complex parameter substitution\ntx.tr(\"Welcome to ${city}, {country}!\", city=\"\u5317\u4eac\", country=\"\u4e2d\u56fd\")\n```\n\n\n#### translate() - Low-Level Translation API\n\nThe `translate()` method is a lower-level API that provides basic translation and parameter substitution:\n\n\n```python\n# Basic translation\ntx.translate(\"Hello\")  # \u4f60\u597d\n\n# Translation with context\ntx.translate(\"Open\", context=\"button\")  # \u6253\u5f00\n\n# Simple parameter substitution\ntx.translate(\"Hello {name}!\", name=\"\u5f20\u4e09\")  # \u4f60\u597d \u5f20\u4e09\uff01\n```\n\n\nThe main differences between `tr()` and `translate()`:\n\n\n| Feature | tr() | translate() |\n|---------|------|------------|\n| Basic Translation | \u2705 | \u2705 |\n| Context Support | \u2705 | \u2705 |\n| Parameter Substitution | \u2705 | \u2705 |\n| Environment Variables | \u2705 | \u274c |\n| ${var} Style Variables | \u2705 | \u274c |\n| $$ Escaping | \u2705 | \u274c |\n| Interpreter Chain | \u2705 | \u274c |\n\n\nChoose `tr()` for full functionality or `translate()` for simpler use cases where you only need basic translation and parameter substitution.\n\n\n### \ud83d\udd04 Advanced Parameter Substitution\n\n\n```python\n# Named parameters\ntx.tr(\"Welcome to {city}, {country}!\", city=\"\u5317\u4eac\", country=\"\u4e2d\u56fd\")\n\n# Positional parameters\ntx.tr(\"File {0} of {1}\", 1, 10)\n\n# Dollar sign variables (useful in shell-like contexts)\ntx.tr(\"Current user: ${USER}\")  # Supports ${var} syntax\ntx.tr(\"Path: $HOME/documents\")  # Supports $var syntax\n\n# Escaping dollar signs\ntx.tr(\"Price: $$99.99\")  # Outputs: Price: $99.99\n```\n\n\n## \ud83c\udf10 Available Locales\n\nTransX provides a convenient way to get a list of available locales in your project:\n\n\n```python\nfrom transx import TransX\n\ntx = TransX(locales_root=\"./locales\")\n\n# Get list of available locales\nprint(f\"Available locales: {tx.available_locales}\")  # e.g. ['en_US', 'zh_CN', 'ja_JP']\n\n# Check if a locale is available before switching\nif \"zh_CN\" in tx.available_locales:\n    tx.current_locale = \"zh_CN\"\n```\n\n\nThe `available_locales` property returns a sorted list of locale codes that:\n- Have a valid locale directory structure (`LC_MESSAGES` folder)\n- Contain either `.po` or `.mo` translation files\n- Are ready to use for translation\n\n\nThis is useful for:\n- Building language selection interfaces\n- Validating locale switches\n- Checking translation file completeness\n- Displaying supported languages to users\n\n\n## \ud83d\udee0\ufe0f Command Line Interface\n\nTransX provides a command-line interface for common translation tasks. When no arguments are provided for commands, TransX will use the `./locales` directory in your current working directory as the default path.\n\n```bash\n# Extract messages from source files\n# Default: Will look for source files in current directory and output to ./locales\ntransx extract\n\n# Same as:\ntransx extract . --output ./locales/messages.pot\n\n# Update .po files with new translations\n# Default: Will update .po files in ./locales\ntransx update\n\n# Same as:\ntransx update ./locales\n\n# Compile .po files to .mo files\n# Default: Will compile .po files from ./locales\ntransx compile\n\n# Same as:\ntransx compile ./locales\n```\n\nThe default working directory structure:\n```\n./\n\u2514\u2500\u2500 locales/           # Default translation directory\n    \u251c\u2500\u2500 messages.pot   # Extracted messages template\n    \u251c\u2500\u2500 en/           # English translations\n    \u2502   \u2514\u2500\u2500 LC_MESSAGES/\n    \u2502       \u251c\u2500\u2500 messages.po\n    \u2502       \u2514\u2500\u2500 messages.mo\n    \u2514\u2500\u2500 zh_CN/        # Chinese translations\n        \u2514\u2500\u2500 LC_MESSAGES/\n            \u251c\u2500\u2500 messages.po\n            \u2514\u2500\u2500 messages.mo\n```\n\n### Extract Messages\n```bash\n# Extract from a single file\ntransx extract app.py -o messages.pot\n\n# Extract from a directory with project info\ntransx extract ./src -o messages.pot -p \"MyProject\" -v \"1.0\"\n\n# Extract and specify languages\ntransx extract ./src -l \"en_US,zh_CN,ja_JP\"\n```\n\n\n### Update PO Files\n```bash\n# Update or create PO files for specific languages\ntransx update messages.pot -l \"zh_CN,ja_JP,ko_KR\"\n\n# Auto-discover and update all language files\ntransx update messages.pot\n\n# Update with custom output directory\ntransx update messages.pot -o ./locales\n```\n\n\n### Compile MO Files\n```bash\n# Compile a single PO file\ntransx compile path/to/messages.po\n\n# Compile all PO files in a directory\ntransx compile -d ./locales\n\n# Compile multiple specific files\ntransx compile file1.po file2.po\n```\n\n\n### List Available Locales\n```bash\n# List all available locales in default directory\ntransx list\n\n# List locales in a specific directory\ntransx list -d /path/to/locales\n```\n\n\n### Common Options\n- `-d, --directory`: Specify working directory\n- `-o, --output`: Specify output file/directory\n- `-l, --languages`: Comma-separated list of language codes\n- `-p, --project`: Project name (for POT generation)\n- `-v, --version`: Project version (for POT generation)\n\n\nFor detailed help on any command:\n```bash\ntransx <command> --help\n```\n\n\n## \ud83d\ude80 Advanced Features\n\n### \ud83d\udda5\ufe0f Qt Usage\n\nTransX can be used with Qt applications in two ways:\n\n#### Basic Integration\n\nUse TransX directly in your Qt application:\n\n```python\nfrom PySide2.QtWidgets import QMainWindow\nfrom transx import get_transx_instance\n\nclass MainWindow(QMainWindow):\n    def __init__(self):\n        super().__init__()\n        self.tx = get_transx_instance(\"myapp\")\n\n        # Translate window title\n        self.setWindowTitle(self.tx.tr(\"My Application\"))\n\n        # Translate menu items\n        file_menu = self.menuBar().addMenu(self.tx.tr(\"&File\"))\n        file_menu.addAction(self.tx.tr(\"&Open\"))\n        file_menu.addAction(self.tx.tr(\"&Save\"))\n```\n\n#### Qt Translator Integration\n\nFor Qt's built-in translation system, you'll need to:\n1. First convert your .po files to .qm format using Qt's lrelease tool\n2. Install the .qm files using TransX's Qt extension\n\n```python\nfrom PySide2.QtWidgets import QApplication, QMainWindow\nfrom PySide2.QtCore import QTranslator\nfrom transx.extensions.qt import install_qt_translator\n\napp = QApplication([])\ntranslator = QTranslator()\n\n# Install translator for specific locale\n# Make sure qt_zh_CN.qm exists in ./translations directory\ninstall_qt_translator(app, translator, \"zh_CN\", \"./translations\")\n\nclass MainWindow(QMainWindow):\n    def __init__(self):\n        super().__init__()\n        # Note: Qt's tr() will only work with .qm files\n        # For Python strings, use TransX's tr() function\n        self.setWindowTitle(\"My Application\")  # This won't be translated\n```\n\nConverting .po to .qm files:\n```bash\n# Using Qt's lrelease tool\nlrelease translations/zh_CN/LC_MESSAGES/messages.po -qm translations/qt_zh_CN.qm\n```\n\n> Note: The `lrelease` tool is part of Qt's Linguist tools:\n> - Windows: Install with Qt installer from [qt.io](https://www.qt.io/download) (Look for Qt Linguist under Tools)\n> - Linux: Install via package manager\n>   ```bash\n>   # Ubuntu/Debian\n>   sudo apt-get install qttools5-dev-tools\n>\n>   # Fedora\n>   sudo dnf install qt5-linguist\n>\n>   # Arch Linux\n>   sudo pacman -S qt5-tools\n>   ```\n> - macOS: Install via Homebrew\n>   ```bash\n>   brew install qt5\n>   ```\n\nThe Qt integration supports:\n- Loading .qm format translation files\n- Multiple translator instances\n- Note: Qt's built-in tr() function requires .qm files and won't work with .mo files\n\n### \ud83d\udd0d Message Extraction\n\nExtract translatable messages from your source code with powerful context support:\n\n```python\nfrom transx.api.pot import PotExtractor\n\n# Initialize extractor with output file\nextractor = PotExtractor(pot_file=\"messages.pot\")\n\n# Add source files or directories to scan\nextractor.add_source_file(\"app.py\")\nextractor.add_source_file(\"utils.py\")\n# Or scan entire directories\nextractor.add_source_directory(\"src\")\n\n# Extract messages with project info\nextractor.save_pot(\n    project=\"MyApp\",\n    version=\"1.0.0\",\n    copyright_holder=\"Your Name\",\n    bugs_address=\"your.email@example.com\"\n)\n```\n\n### \ud83c\udf10 Multi-App Support\n\nManage multiple translation instances for different applications or components:\n\n```python\nfrom transx import get_transx_instance\n\n# Create instances for different apps or components\napp1 = get_transx_instance(\"app1\", default_locale=\"en_US\")\napp2 = get_transx_instance(\"app2\", default_locale=\"zh_CN\")\n\n# Each instance has its own:\n# - Translation catalog\n# - Locale settings\n# - Message domains\napp1.tr(\"Hello\")  # Uses app1's translations\napp2.tr(\"Hello\")  # Uses app2's translations\n\n# Switch locales independently\napp1.switch_locale(\"ja_JP\")\napp2.switch_locale(\"ko_KR\")\n```\n\nMulti-app support features:\n- Independent translation catalogs\n- Separate locale settings per instance\n- Thread-safe operation\n\n### \ud83d\udd24 Context-Based Translations\n\n```python\n# UI Context\nprint(tx.tr(\"Open\", context=\"button\"))  # \u6253\u5f00\nprint(tx.tr(\"Open\", context=\"menu\"))    # \u6253\u5f00\u6587\u4ef6\n\n# Part of Speech\nprint(tx.tr(\"Post\", context=\"verb\"))    # \u53d1\u5e03\nprint(tx.tr(\"Post\", context=\"noun\"))    # \u6587\u7ae0\n\n# Scene Context\nprint(tx.tr(\"Welcome\", context=\"login\")) # \u6b22\u8fce\u767b\u5f55\nprint(tx.tr(\"Welcome\", context=\"home\"))  # \u6b22\u8fce\u56de\u6765\n```\n\n### \u26a0\ufe0f Error Handling\n\nTransX provides comprehensive error handling with fallback mechanisms:\n\n```python\nfrom transx import TransX\nfrom transx.exceptions import LocaleNotFoundError, TranslationError\n\n# Enable strict mode for development\ntx = TransX(strict_mode=True)\n\ntry:\n    tx.load_catalog(\"invalid_locale\")\nexcept LocaleNotFoundError as e:\n    print(f\"\u274c Locale error: {e.message}\")\n\ntry:\n    result = tx.translate(\"Hello\", target_lang=\"invalid\")\nexcept TranslationError as e:\n    print(f\"\u274c Translation failed: {e.message}\")\n```\n\n## \ud83d\udcc4 Performance\n\nTransX is designed with performance in mind. We continuously monitor and optimize its performance through automated benchmarks.\n\nView our performance benchmarks at: [TransX Benchmarks](https://loonghao.github.io/transx-benchmarks/)\n\nOur benchmark suite includes:\n- Translation lookup performance\n- Parameter substitution performance\n- Locale switching performance\n- Cache efficiency\n- Memory usage\n- Concurrent operations\n- And more...\n\n## \ud83d\udee0\ufe0f Development\n\n### \ud83d\udd27 Environment Setup\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/loonghao/transx.git\ncd transx\n```\n\n2. Install development dependencies:\n```bash\npip install -r requirements-dev.txt\n```\n\n\n### \ud83d\udce6 Project Structure\n\nTransX follows a well-organized package structure:\n\n```\ntransx/\n\u251c\u2500\u2500 transx/                  # Main package directory\n\u2502   \u251c\u2500\u2500 __init__.py         # Package initialization\n\u2502   \u251c\u2500\u2500 __version__.py      # Version information\n\u2502   \u251c\u2500\u2500 api/                # Public API modules\n\u2502   \u2502   \u251c\u2500\u2500 __init__.py\n\u2502   \u2502   \u251c\u2500\u2500 mo.py          # MO file operations\n\u2502   \u2502   \u251c\u2500\u2500 po.py          # PO file operations\n\u2502   \u2502   \u2514\u2500\u2500 pot.py         # POT file operations\n\u2502   \u251c\u2500\u2500 app.py             # Application management\n\u2502   \u251c\u2500\u2500 cli.py             # Command-line interface\n\u2502   \u251c\u2500\u2500 constants.py        # Constants and configurations\n\u2502   \u251c\u2500\u2500 context/           # Translation context management\n\u2502   \u2502   \u251c\u2500\u2500 __init__.py\n\u2502   \u2502   \u2514\u2500\u2500 manager.py    # Context manager implementation\n\u2502   \u251c\u2500\u2500 core.py            # Core functionality\n\u2502   \u251c\u2500\u2500 exceptions.py       # Custom exceptions\n\u2502   \u251c\u2500\u2500 extensions/        # Framework integrations\n\u2502   \u2502   \u251c\u2500\u2500 __init__.py\n\u2502   \u2502   \u2514\u2500\u2500 qt.py         # Qt support\n\u2502   \u2514\u2500\u2500 internal/          # Internal implementation details\n\u2502       \u251c\u2500\u2500 __init__.py\n\u2502       \u251c\u2500\u2500 compat.py     # Python 2/3 compatibility\n\u2502       \u251c\u2500\u2500 filesystem.py # File system operations\n\u2502       \u2514\u2500\u2500 logging.py    # Logging utilities\n\u251c\u2500\u2500 examples/              # Example code\n\u251c\u2500\u2500 locales/              # Translation files\n\u251c\u2500\u2500 tests/                # Test suite\n\u251c\u2500\u2500 nox_actions/          # Nox automation scripts\n\u251c\u2500\u2500 CHANGELOG.md          # Version history\n\u251c\u2500\u2500 LICENSE              # MIT License\n\u251c\u2500\u2500 README.md            # English documentation\n\u251c\u2500\u2500 README_zh.md         # Chinese documentation\n\u251c\u2500\u2500 noxfile.py           # Test automation config\n\u251c\u2500\u2500 pyproject.toml       # Project configuration\n\u251c\u2500\u2500 requirements.txt     # Production dependencies\n\u2514\u2500\u2500 requirements-dev.txt # Development dependencies\n```\n\n### \ud83d\udd04 Development Workflow\n\nWe use [Nox](https://nox.thea.codes/) to automate development tasks. Here are the main commands:\n\n\n```bash\n# Run linting\nnox -s lint\n\n# Fix linting issues automatically\nnox -s lint-fix\n\n# Run tests\nnox -s pytest\n```\n\n\n### \ud83e\uddea Running Tests\n\nTests are written using pytest and can be run using nox:\n\n\n```bash\nnox -s pytest\n```\n\n\nFor running specific tests:\n\n\n```bash\n# Run a specific test file\nnox -s pytest -- tests/test_core.py\n\n# Run tests with specific markers\nnox -s pytest -- -m \"not integration\"\n```\n\n\n### \ud83d\udcca Code Quality\n\nWe maintain high code quality standards using various tools:\n\n\n- **Linting**: We use ruff and isort for code linting and formatting\n- **Type Checking**: Static type checking with mypy\n- **Testing**: Comprehensive test suite with pytest\n- **Coverage**: Code coverage tracking with coverage.py\n- **CI/CD**: Automated testing and deployment with GitHub Actions\n\n\n### \ud83d\udcdd Documentation\n\nDocumentation is written in Markdown and is available in:\n- README.md: Main documentation\n- examples/: Example code and usage\n- API documentation in source code\n\n\n### \ud83e\udd1d Contributing Guidelines\n\n1. Fork the repository\n2. Create a new branch for your feature\n3. Make your changes\n4. Run tests and linting\n5. Submit a pull request\n\n\nPlease ensure your PR:\n- Passes all tests\n- Includes appropriate documentation\n- Follows our code style\n- Includes test coverage for new features\n\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A lightweight, zero-dependency Python library for internationalization and translation management.",
    "version": "0.6.1",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a0d813a82b8c9d254f4ce48d202be3c0ebbade9fba9a5e9ce17b6a776ecd8374",
                "md5": "9cb83644848e52602c8ca4a7b99f6f07",
                "sha256": "18b0f209211933c313c99401120dc79bfad49d44c938b9d97e3f145c66774c44"
            },
            "downloads": -1,
            "filename": "transx-0.6.1-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9cb83644848e52602c8ca4a7b99f6f07",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": "<4.0,>=2.7",
            "size": 59251,
            "upload_time": "2024-12-12T16:23:09",
            "upload_time_iso_8601": "2024-12-12T16:23:09.709781Z",
            "url": "https://files.pythonhosted.org/packages/a0/d8/13a82b8c9d254f4ce48d202be3c0ebbade9fba9a5e9ce17b6a776ecd8374/transx-0.6.1-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b7abec74017fa6d70e8586ba6ed6846e08a7a23cbe0f64109b29a1376f58492c",
                "md5": "c9036e7a222fcd2e558c525a31ca33dd",
                "sha256": "335e9d6edcea5957bde5fc0c3ba304ed000fcc114f3ba7fd65aa8bd2e51c41c3"
            },
            "downloads": -1,
            "filename": "transx-0.6.1.tar.gz",
            "has_sig": false,
            "md5_digest": "c9036e7a222fcd2e558c525a31ca33dd",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=2.7",
            "size": 55437,
            "upload_time": "2024-12-12T16:23:11",
            "upload_time_iso_8601": "2024-12-12T16:23:11.281839Z",
            "url": "https://files.pythonhosted.org/packages/b7/ab/ec74017fa6d70e8586ba6ed6846e08a7a23cbe0f64109b29a1376f58492c/transx-0.6.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-12 16:23:11",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "transx"
}
        
Elapsed time: 0.36771s