CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-rosetta

A Django application that facilitates the translation process of your Django projects

Pending
Overview
Eval results
Files

translation-services.mddocs/

Translation Services Integration

Integration with external translation APIs providing automatic translation suggestions to assist translators. The system supports multiple translation services including DeepL, Google Translate, Azure Translator, and OpenAI, with automatic service selection and error handling.

Capabilities

Main Translation Interface

Central translation function that dispatches to configured translation services.

def translate(text: str, from_language: str, to_language: str) -> str:
    """
    Main translation function supporting multiple services.
    
    Automatically selects appropriate translation service based on
    configured API keys and language support. Tries services in order
    of preference: DeepL, Google, Azure, OpenAI.
    
    Parameters:
    - text: Text to translate
    - from_language: Source language code (ISO 639-1)
    - to_language: Target language code (ISO 639-1)
    
    Returns:
    Translated text string
    
    Raises:
    TranslationException: When translation fails or no service available
    """

class TranslationException(Exception):
    """
    Exception raised by translation services.
    
    Raised when:
    - API key is missing or invalid
    - Network request fails
    - Service returns error response
    - Language pair not supported
    - Text exceeds service limits
    """

DeepL Translation Service

Integration with DeepL API for high-quality translation suggestions.

def translate_by_deepl(text: str, to_language: str, auth_key: str) -> str:
    """
    DeepL API integration for translation suggestions.
    
    Uses DeepL API to translate text with high quality results.
    Automatically handles Django template variable preservation.
    
    Parameters:
    - text: Text to translate (may contain Django template variables)
    - to_language: Target language code (DeepL format: 'EN', 'DE', 'FR', etc.)
    - auth_key: DeepL API authentication key
    
    Returns:
    Translated text with preserved template variables
    
    Raises:
    TranslationException: On API errors or invalid key
    """

def format_text_to_deepl(text: str) -> str:
    """
    Format Django template variables for DeepL API.
    
    Protects Django template variables (%(var)s, {var}) from translation
    by converting them to XML tags that DeepL preserves.
    
    Parameters:
    - text: Text containing Django template variables
    
    Returns:
    Text with variables converted to XML tags
    """

def format_text_from_deepl(text: str) -> str:
    """
    Parse DeepL API response back to Django format.
    
    Converts XML tags back to Django template variables after
    translation, restoring original variable syntax.
    
    Parameters:
    - text: DeepL response with XML-formatted variables
    
    Returns:
    Text with restored Django template variables
    """

Google Translate Service

Integration with Google Cloud Translation API.

def translate_by_google(text: str, input_language: str, output_language: str, credentials_path: str, project_id: str) -> str:
    """
    Google Cloud Translation API integration.
    
    Uses Google Translate API v3 for translation suggestions.
    Requires Google Cloud project with Translation API enabled.
    
    Parameters:
    - text: Text to translate
    - input_language: Source language code (BCP-47: 'en', 'fr', 'de', etc.)
    - output_language: Target language code (BCP-47 format)
    - credentials_path: Path to Google Cloud service account JSON file
    - project_id: Google Cloud project ID
    
    Returns:
    Translated text string
    
    Raises:
    TranslationException: On authentication or API errors
    """

Azure Translator Service

Integration with Microsoft Azure Translator API.

def translate_by_azure(text: str, from_language: str, to_language: str, subscription_key: str) -> str:
    """
    Azure Translator API integration.
    
    Uses Microsoft Azure Cognitive Services Translator API
    for translation suggestions.
    
    Parameters:
    - text: Text to translate
    - from_language: Source language code (ISO 639-1: 'en', 'fr', 'de', etc.)
    - to_language: Target language code (ISO 639-1 format)
    - subscription_key: Azure Translator subscription key
    
    Returns:
    Translated text string
    
    Raises:
    TranslationException: On authentication or API errors
    """

OpenAI Translation Service

Integration with OpenAI API for AI-powered translation suggestions.

def translate_by_openai(text: str, from_language: str, to_language: str, api_key: str) -> str:
    """
    OpenAI API integration for translation suggestions.
    
    Uses OpenAI's language models for translation with customizable
    prompts. Supports context-aware translation and natural language
    handling.
    
    Parameters:
    - text: Text to translate
    - from_language: Source language name (e.g., 'English', 'French')
    - to_language: Target language name (e.g., 'German', 'Spanish')
    - api_key: OpenAI API key
    
    Returns:
    Translated text string
    
    Raises:
    TranslationException: On API errors or quota exceeded
    """

Configuration

Translation services are configured through Django settings:

# Enable translation suggestions
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS: bool = False

# DeepL Configuration
ROSETTA_DEEPL_AUTH_KEY: str = ''
ROSETTA_DEEPL_LANGUAGES: list = ['EN', 'DE', 'FR', 'IT', 'JA', 'ES', 'NL', 'PL', 'PT', 'RU', 'ZH']

# Google Translate Configuration
ROSETTA_GOOGLE_APPLICATION_CREDENTIALS_PATH: str = ''
ROSETTA_GOOGLE_PROJECT_ID: str = ''

# Azure Translator Configuration
ROSETTA_AZURE_CLIENT_SECRET: str = ''

# OpenAI Configuration
ROSETTA_OPENAI_API_KEY: str = ''
ROSETTA_OPENAI_PROMPT_TEMPLATE: str = 'Translate the following text from {from_language} to {to_language}: {text}'

Usage Examples

Basic Translation Service Setup

# settings.py - Enable DeepL translation suggestions
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS = True
ROSETTA_DEEPL_AUTH_KEY = 'your-deepl-api-key-here'

# Now translation suggestions appear in the web interface
# Users can click "Suggest" next to translation fields

Multiple Service Configuration

# settings.py - Configure multiple translation services
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS = True

# Primary service: DeepL (highest quality)
ROSETTA_DEEPL_AUTH_KEY = 'your-deepl-key'

# Fallback service: Google Translate
ROSETTA_GOOGLE_APPLICATION_CREDENTIALS_PATH = '/path/to/google-credentials.json'
ROSETTA_GOOGLE_PROJECT_ID = 'your-google-project-id'

# Additional service: Azure
ROSETTA_AZURE_CLIENT_SECRET = 'your-azure-key'

# AI service: OpenAI
ROSETTA_OPENAI_API_KEY = 'your-openai-key'
ROSETTA_OPENAI_PROMPT_TEMPLATE = 'Please translate this text from {from_language} to {to_language}, maintaining the original tone and context: {text}'

Programmatic Translation Usage

from rosetta.translate_utils import translate, TranslationException

def get_translation_suggestion(text, source_lang, target_lang):
    """Get translation suggestion for user interface."""
    
    try:
        translation = translate(text, source_lang, target_lang)
        return {
            'success': True,
            'translation': translation
        }
    except TranslationException as e:
        return {
            'success': False,
            'error': str(e)
        }

# Usage in views
def translation_view(request):
    if request.method == 'POST':
        text = request.POST.get('text')
        result = get_translation_suggestion(text, 'en', 'fr')
        
        if result['success']:
            # Use the translation
            translation = result['translation']
        else:
            # Handle error
            error_message = result['error']
    
    return render(request, 'template.html')

Service-Specific Usage

from rosetta.translate_utils import (
    translate_by_deepl, 
    translate_by_google,
    translate_by_azure,
    translate_by_openai,
    TranslationException
)

def compare_translation_services(text):
    """Compare results from different translation services."""
    
    results = {}
    
    # DeepL translation
    try:
        results['deepl'] = translate_by_deepl(text, 'FR', 'your-deepl-key')
    except TranslationException as e:
        results['deepl'] = f"Error: {e}"
    
    # Google translation
    try:
        results['google'] = translate_by_google(
            text, 'en', 'fr', 
            '/path/to/credentials.json', 
            'project-id'
        )
    except TranslationException as e:
        results['google'] = f"Error: {e}"
    
    # Azure translation
    try:
        results['azure'] = translate_by_azure(text, 'en', 'fr', 'azure-key')
    except TranslationException as e:
        results['azure'] = f"Error: {e}"
    
    # OpenAI translation
    try:
        results['openai'] = translate_by_openai(text, 'English', 'French', 'openai-key')
    except TranslationException as e:
        results['openai'] = f"Error: {e}"
    
    return results

Django Template Variable Handling

# DeepL automatically handles Django template variables
text_with_variables = "Hello %(name)s, you have {count} messages."

# DeepL preserves variables during translation
translated = translate_by_deepl(text_with_variables, 'FR', 'your-key')
# Result: "Bonjour %(name)s, vous avez {count} messages."

# Manual variable formatting (for custom implementations)
from rosetta.translate_utils import format_text_to_deepl, format_text_from_deepl

# Before sending to DeepL
formatted_text = format_text_to_deepl("Hello %(name)s!")
# Result: "Hello <var1>name</var1>!"

# After receiving from DeepL
restored_text = format_text_from_deepl("Bonjour <var1>name</var1>!")
# Result: "Bonjour %(name)s!"

Error Handling and Fallbacks

from rosetta.translate_utils import translate, TranslationException
from rosetta.conf import settings as rosetta_settings

def robust_translation(text, from_lang, to_lang):
    """Translation with comprehensive error handling."""
    
    if not rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS:
        return None
    
    try:
        # Attempt translation
        return translate(text, from_lang, to_lang)
        
    except TranslationException as e:
        # Log the error for debugging
        import logging
        logger = logging.getLogger('rosetta.translation')
        logger.warning(f"Translation failed: {e}")
        
        # Return None to indicate no suggestion available
        return None
    
    except Exception as e:
        # Handle unexpected errors
        import logging
        logger = logging.getLogger('rosetta.translation')
        logger.error(f"Unexpected translation error: {e}")
        return None

Custom Translation Service Integration

# Custom service implementation
def translate_by_custom_service(text, from_language, to_language, api_key):
    """Custom translation service integration."""
    
    import requests
    
    try:
        response = requests.post(
            'https://api.custom-translator.com/translate',
            headers={'Authorization': f'Bearer {api_key}'},
            json={
                'text': text,
                'from': from_language,
                'to': to_language
            }
        )
        
        if response.status_code == 200:
            return response.json()['translation']
        else:
            raise TranslationException(f"API error: {response.status_code}")
            
    except requests.RequestException as e:
        raise TranslationException(f"Network error: {e}")

# Integrate with main translate function by modifying service priority order

Install with Tessl CLI

npx tessl i tessl/pypi-django-rosetta

docs

access-control.md

configuration.md

django-signals.md

file-operations.md

index.md

storage-backends.md

template-integration.md

translation-services.md

web-interface.md

tile.json