Name | transx JSON |
Version |
0.6.1
JSON |
| download |
home_page | None |
Summary | A lightweight, zero-dependency Python library for internationalization and translation management. |
upload_time | 2024-12-12 16:23:11 |
maintainer | None |
docs_url | None |
author | longhao |
requires_python | <4.0,>=2.7 |
license | None |
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">
[](https://img.shields.io/pypi/pyversions/transx)
[](https://github.com/wntrblm/nox)
[](https://pypi.org/project/transx/)
[](https://pepy.tech/project/transx)
[](https://pepy.tech/project/transx)
[](https://pepy.tech/project/transx)
[](https://pypi.org/project/transx/)
[](https://pypi.org/project/transx/)
[](https://github.com/loonghao/transx/graphs/commit-activity)

[](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[](https://img.shields.io/pypi/pyversions/transx)\n[](https://github.com/wntrblm/nox)\n[](https://pypi.org/project/transx/)\n[](https://pepy.tech/project/transx)\n[](https://pepy.tech/project/transx)\n[](https://pepy.tech/project/transx)\n[](https://pypi.org/project/transx/)\n[](https://pypi.org/project/transx/)\n[](https://github.com/loonghao/transx/graphs/commit-activity)\n\n[](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"
}