or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

api-client.mdfree-client.mdindex.mdlanguages.mdresponses.md
tile.json

api-client.mddocs/

API Key Translation Client

The ApiKeyTranslate class provides enterprise-grade translation functionality using Google Cloud Translation API. This client requires a valid API key but offers reliable service, batch processing, language enumeration, and comprehensive language detection capabilities.

Capabilities

Client Initialization

Creates a new API key-based translation client with Google Cloud Translation API authentication and configurable translation settings.

def __init__(
    self,
    api_key: str,
    target: str = "zh-CN",
    source: str = None,
    fmt: str = "html", 
    model: str = "nmt",
    proxies: dict = None,
    timeout=None,
    trust_env=False
):
    """
    Initialize API key translation client.
    
    Parameters:
    - api_key (str): Google Cloud Translation API key (required)
    - target (str): Default target language code (default: "zh-CN")
    - source (str): Default source language code (default: None for auto-detection)
    - fmt (str): Text format - "text" or "html" (default: "html")
    - model (str): Translation model - "nmt" (Neural) or "pbmt" (Phrase-based) (default: "nmt")
    - proxies (dict): Proxy configuration {'https': 'http://localhost:10809'}
    - timeout (int): Request timeout in seconds
    - trust_env (bool): Trust environment variables for proxy config
    """

Usage Example:

from pygtrans import ApiKeyTranslate

# Basic configuration
client = ApiKeyTranslate(api_key='your-google-cloud-api-key')

# Advanced configuration
client = ApiKeyTranslate(
    api_key='your-api-key',
    target='en',
    fmt='text',
    model='nmt',
    timeout=30
)

Language Support Query

Retrieves the list of languages supported by Google Cloud Translation API for the specified target language and model.

def languages(
    self, 
    target: str = None, 
    model: str = None, 
    timeout=...
) -> Union[List[LanguageResponse], Null]:
    """
    Get list of supported languages.
    
    Parameters:
    - target (str, optional): Target language for language names (default: instance default)
    - model (str, optional): Translation model "nmt" or "pbmt" (default: instance default)
    - timeout (int, optional): Request timeout in seconds
    
    Returns:
    - List[LanguageResponse]: List of supported languages with codes and names
    - Null: Error response if request fails
    """

Usage Example:

# Get all supported languages (names in Chinese)
languages = client.languages(target='zh-CN')
if isinstance(languages, list):
    for lang in languages[:5]:  # Show first 5
        print(f"{lang.language}: {lang.name}")
        # Output: en: 英语, fr: 法语, es: 西班牙语, ...

# Get supported languages for NMT model (names in English)
languages = client.languages(target='en', model='nmt')

Language Detection

Detects the language of input text with support for both single strings and batch processing.

def detect(
    self, 
    q: Union[str, List[str]], 
    timeout=...
) -> Union[DetectResponse, List[DetectResponse], Null]:
    """
    Detect language of input text with batch support.
    
    Parameters:
    - q (str or List[str]): Text to detect language for (single string or list)
    - timeout (int, optional): Request timeout in seconds
    
    Returns:
    - DetectResponse: Single detection result (when q is str)
    - List[DetectResponse]: List of detection results (when q is List[str])
    - Null: Error response if detection fails
    """

Usage Examples:

# Single text detection
result = client.detect('Hello, world!')
if isinstance(result, DetectResponse):
    print(f"Language: {result.language}")  # 'en'
    print(f"Confidence: {result.confidence}")  # 1.0
    print(f"Reliable: {result.isReliable}")  # True

# Batch detection
texts = ['Hello', 'Bonjour', 'Hola', '你好']
results = client.detect(texts)
if isinstance(results, list):
    for i, result in enumerate(results):
        print(f"'{texts[i]}' -> {result.language}")
        # 'Hello' -> en, 'Bonjour' -> fr, 'Hola' -> es, '你好' -> zh

Text Translation

Translates text with comprehensive parameter control, supporting both single strings and batch processing with automatic chunking for large datasets.

def translate(
    self,
    q: Union[str, List[str]],
    target: str = None,
    source: str = None,
    fmt: str = None,
    model: str = None,
    timeout=...
) -> Union[TranslateResponse, List[TranslateResponse], Null]:
    """
    Translate text with full API capabilities.
    
    Parameters:
    - q (str or List[str]): Text to translate (single string or list of strings)
    - target (str, optional): Target language code (default: instance default)
    - source (str, optional): Source language code (default: auto-detection)
    - fmt (str, optional): Text format "text" or "html" (default: instance default)
    - model (str, optional): Translation model "nmt" or "pbmt" (default: instance default)
    - timeout (int, optional): Request timeout in seconds
    
    Returns:
    - TranslateResponse: Single translation result (when q is str)
    - List[TranslateResponse]: List of translation results (when q is List[str])
    - Null: Error response if translation fails
    
    Note:
    - Maximum concurrent batch size: 128 items
    - Maximum request body size: 102400 bytes
    - Automatic chunking handles large datasets
    """

Usage Examples:

# Single translation with auto-detection
result = client.translate('Hello, world!', target='zh-CN')
if isinstance(result, TranslateResponse):
    print(result.translatedText)  # '你好世界!'
    print(result.detectedSourceLanguage)  # 'en'
    print(result.model)  # 'nmt'

# Batch translation
texts = [
    'Good morning',
    'How are you?', 
    'See you later'
]
results = client.translate(texts, target='zh-CN')
if isinstance(results, list):
    for i, result in enumerate(results):
        print(f"'{texts[i]}' -> '{result.translatedText}'")

# Explicit source language
result = client.translate(
    'Bonjour le monde', 
    source='fr', 
    target='en'
)
print(result.translatedText)  # 'Hello World'

# HTML content translation
html = '<p>Welcome to our <strong>website</strong>!</p>'
result = client.translate(html, fmt='html', target='zh-CN')
print(result.translatedText)  # '<p>欢迎来到我们的<strong>网站</strong>!</p>'

# Using PBMT model
result = client.translate(
    'Technical documentation',
    target='zh-CN',
    model='pbmt'
)

Large Dataset Handling

The API client automatically handles large datasets by chunking them according to Google Cloud API limits:

# Large batch processing (automatically chunked)
large_dataset = [f"Text {i}" for i in range(1000)]
results = client.translate(large_dataset, target='zh-CN')

# The client automatically:
# - Splits into chunks of max 128 items
# - Ensures each chunk is under 102400 bytes
# - Processes chunks sequentially
# - Returns results in original order

Error Handling

All methods return Null objects on failure:

result = client.translate('Hello')
if isinstance(result, Null):
    print(f"Translation failed: {result.msg}")
    print(f"Status code: {result.response.status_code}")
    print(f"Response text: {result.response.text}")

API Limits and Best Practices

Request Limits

  • Maximum batch size: 128 items per request
  • Maximum request body size: 102400 bytes (100KB)
  • Rate limits: Vary by Google Cloud quota settings

Optimal Usage Patterns

# Efficient: Use batch processing
texts = ['Text 1', 'Text 2', 'Text 3']
results = client.translate(texts)

# Less efficient: Individual requests
results = [client.translate(text) for text in texts]

Model Selection

  • NMT (Neural Machine Translation): Higher quality, supports most language pairs
  • PBMT (Phrase-Based Machine Translation): Fallback for unsupported NMT pairs
# Prefer NMT for better quality
client = ApiKeyTranslate(api_key='key', model='nmt')

# Use PBMT only when NMT is unavailable for specific language pairs
result = client.translate('text', model='pbmt')

Authentication

Ensure your API key has proper permissions:

  • Cloud Translation API must be enabled
  • API key must have Translation API permissions
  • Consider using service account keys for production
# Environment variable approach (recommended)
import os
api_key = os.getenv('GOOGLE_TRANSLATE_API_KEY')
client = ApiKeyTranslate(api_key=api_key)