or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdexternal-apis.mdindex.mdpackage-management.mdtext-processing.mdtranslation.md
tile.json

translation.mddocs/

Translation

Core translation functionality providing neural machine translation capabilities with support for multiple backends, language detection, translation chaining, and performance optimization through caching.

Capabilities

Simple Text Translation

The primary translation function that converts text from one language to another using installed translation models.

def translate(q: str, from_code: str, to_code: str) -> str:
    """
    Translate text from source language to target language.
    
    Args:
        q (str): Text to translate
        from_code (str): Source language ISO code (e.g., 'en', 'es', 'fr')
        to_code (str): Target language ISO code
        
    Returns:
        str: Translated text
        
    Example:
        >>> translate("Hello world", "en", "es")
        "Hola mundo"
    """

Language Management

Functions for discovering and working with installed languages and their capabilities.

def get_installed_languages() -> list[Language]:
    """
    Get list of all installed languages with translation capabilities.
    
    Returns:
        list[Language]: List of available languages
    """

def get_language_from_code(code: str) -> Language | None:
    """
    Get language object from ISO language code.
    
    Args:
        code (str): ISO language code (e.g., 'en', 'es')
        
    Returns:
        Language | None: Language object or None if not found
    """

def get_translation_from_codes(from_code: str, to_code: str) -> ITranslation | None:
    """
    Get translation object for reusable translation between specific languages.
    
    Args:
        from_code (str): Source language code
        to_code (str): Target language code
        
    Returns:
        ITranslation: Translation object for reuse
    """

Language Object

Represents a translatable language with its capabilities and connections to other languages.

class Language:
    def __init__(self, code: str, name: str):
        """
        Initialize language object.
        
        Args:
            code (str): ISO language code
            name (str): Human-readable language name
        """
    
    code: str  # ISO language code (e.g., 'en', 'es')
    name: str  # Human-readable name (e.g., 'English', 'Spanish')
    translations_from: list[ITranslation]  # Available translations from this language
    translations_to: list[ITranslation]    # Available translations to this language
    
    def get_translation(self, to: Language) -> ITranslation | None:
        """
        Get translation object to another language.
        
        Args:
            to (Language): Target language
            
        Returns:
            ITranslation | None: Translation object or None if unavailable
        """

Translation Interface

Abstract interface for all translation implementations, providing the core translation contract.

class ITranslation:
    """Abstract interface for translation between two languages."""
    
    from_lang: Language  # Source language
    to_lang: Language    # Target language
    
    def translate(self, input_text: str) -> str:
        """
        Translate input text.
        
        Args:
            input_text (str): Text to translate
            
        Returns:
            str: Translated text
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 4) -> list[Hypothesis]:
        """
        Generate multiple translation hypotheses with confidence scores.
        
        Args:
            input_text (str): Text to translate
            num_hypotheses (int): Number of alternative translations to generate
            
        Returns:
            list[Hypothesis]: List of translation hypotheses with scores
        """
    
    @staticmethod
    def split_into_paragraphs(input_text: str) -> list[str]:
        """Split text into paragraphs for processing."""
    
    @staticmethod
    def combine_paragraphs(paragraphs: list[str]) -> str:
        """Combine paragraphs back into single text."""

Translation Hypothesis

Represents a translation result with confidence scoring for quality assessment.

class Hypothesis:
    def __init__(self, value: str, score: float):
        """
        Initialize translation hypothesis.
        
        Args:
            value (str): The translated text
            score (float): Confidence score (higher = better)
        """
    
    value: str   # The translation text
    score: float # Confidence score

Translation Implementations

Different translation backends providing various capabilities and performance characteristics.

Package-Based Translation

Translation using locally installed neural translation models.

class PackageTranslation(ITranslation):
    def __init__(self, from_lang: Language, to_lang: Language, pkg: Package):
        """
        Initialize package-based translation.
        
        Args:
            from_lang (Language): Source language
            to_lang (Language): Target language  
            pkg (Package): Translation package containing the model
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 4) -> list[Hypothesis]:
        """Generate translation hypotheses using neural model."""

Identity Translation

No-operation translation for same-language scenarios.

class IdentityTranslation(ITranslation):
    def __init__(self, lang: Language):
        """
        Initialize identity translation (same language).
        
        Args:
            lang (Language): The language (both source and target)
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 4) -> list[Hypothesis]:
        """Return input text as single hypothesis with perfect score."""

Composite Translation

Chains two translations together for indirect translation paths (pivoting).

class CompositeTranslation(ITranslation):
    def __init__(self, t1: ITranslation, t2: ITranslation):
        """
        Initialize composite translation (pivoting through intermediate language).
        
        Args:
            t1 (ITranslation): First translation (source -> intermediate)
            t2 (ITranslation): Second translation (intermediate -> target)
        """
    
    t1: ITranslation  # First translation step
    t2: ITranslation  # Second translation step
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 4) -> list[Hypothesis]:
        """Perform chained translation through intermediate language."""

Cached Translation

Performance-optimized translation with result caching.

class CachedTranslation(ITranslation):
    def __init__(self, underlying: ITranslation):
        """
        Initialize cached translation wrapper.
        
        Args:
            underlying (ITranslation): The translation to cache
        """
    
    underlying: ITranslation  # The wrapped translation
    cache: dict              # Translation result cache
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 4) -> list[Hypothesis]:
        """Perform translation with caching for repeated requests."""

Remote Translation

Translation via external LibreTranslate API services.

class RemoteTranslation(ITranslation):
    def __init__(self, from_lang: Language, to_lang: Language, api):
        """
        Initialize remote API translation.
        
        Args:
            from_lang (Language): Source language
            to_lang (Language): Target language
            api: LibreTranslate API client
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 1) -> list[Hypothesis]:
        """Perform translation via remote API."""

Few-Shot Translation

Translation using large language models with few-shot prompting.

class FewShotTranslation(ITranslation):
    def __init__(self, from_lang: Language, to_lang: Language, language_model: ILanguageModel):
        """
        Initialize few-shot language model translation.
        
        Args:
            from_lang (Language): Source language
            to_lang (Language): Target language
            language_model (ILanguageModel): Language model for translation
        """
    
    def hypotheses(self, input_text: str, num_hypotheses: int = 1) -> list[Hypothesis]:
        """Perform translation using language model with few-shot prompting."""

Translation Cache Management

Global storage and caching system for translation instances.

class InstalledTranslate:
    """Global storage for cached translation instances."""
    
    package_key: str                    # Unique package identifier
    cached_translation: CachedTranslation  # Cached translation instance

# Global list of installed translation cache instances
installed_translates: List[InstalledTranslate]

Advanced Translation Functions

Specialized functions for working with translation packages and processing.

def apply_packaged_translation(
    pkg: Package, 
    input_text: str, 
    translator: Translator, 
    num_hypotheses: int = 4
) -> list[Hypothesis]:
    """
    Apply translation using a specific package.
    
    Args:
        pkg (Package): Translation package to use
        input_text (str): Text to translate
        translator: Translation engine
        num_hypotheses (int): Number of hypotheses to generate
        
    Returns:
        list[Hypothesis]: Translation hypotheses
    """

Deprecated Functions

def load_installed_languages() -> list[Language]:
    """
    DEPRECATED: Use get_installed_languages() instead.
    Load list of installed languages.
    """

Usage Examples

Basic Translation

from argostranslate import translate

# Simple translation
result = translate.translate("Good morning", "en", "fr")
print(result)  # "Bonjour"

# Check available languages
languages = translate.get_installed_languages()
for lang in languages:
    print(f"{lang.code}: {lang.name}")

Advanced Translation with Hypotheses

from argostranslate import translate

# Get translation object for reuse
translation = translate.get_translation_from_codes("en", "de")

if translation:
    # Get multiple translation options
    hypotheses = translation.hypotheses("The weather is nice today", num_hypotheses=3)
    
    for i, hyp in enumerate(hypotheses):
        print(f"Option {i+1}: {hyp.value} (score: {hyp.score:.3f})")

Language Detection and Fallback

from argostranslate import translate

# Get language object and check capabilities
source_lang = translate.get_language_from_code("en")
target_lang = translate.get_language_from_code("ja")

if source_lang and target_lang:
    translation = source_lang.get_translation(target_lang)
    if translation:
        result = translation.translate("Hello, how are you?")
        print(result)
    else:
        print("Direct translation not available")

Working with Different Translation Types

from argostranslate import translate
from argostranslate.translate import CachedTranslation, CompositeTranslation

# Get base translation
base_translation = translate.get_translation_from_codes("en", "es")

if base_translation:
    # Wrap with caching for better performance
    cached_translation = CachedTranslation(base_translation)
    
    # Use cached translation
    result = cached_translation.translate("This will be cached")
    result2 = cached_translation.translate("This will be cached")  # Cache hit