CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pygtrans

Google Translate library with support for free and API key-based translation services

Pending
Overview
Eval results
Files

free-client.mddocs/

Free Translation Client

The Translate class provides free access to Google Translate functionality using the web interface. This client supports language detection, text translation, batch processing, and text-to-speech capabilities but requires proxy configuration for users outside China.

Capabilities

Client Initialization

Creates a new free translation client with configurable settings for target language, proxy, timeout, and domain preferences.

def __init__(
    self,
    target: str = "zh-CN",
    source: str = "auto", 
    fmt="html",
    user_agent: str = None,
    domain: str = "com",
    proxies: dict = None,
    timeout: int = None,
    trust_env=False
):
    """
    Initialize free translation client.
    
    Parameters:
    - target (str): Default target language code (default: "zh-CN")
    - source (str): Default source language code (default: "auto" for auto-detection)
    - fmt (str): Text format - "text" or "html" (default: "html")
    - user_agent (str): Custom user agent string (default: auto-generated)
    - domain (str): Google domain - "com", "cn", etc. (default: "com")
    - 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 Translate

# Basic configuration with proxy (required for non-Chinese users)
client = Translate(
    target='en',
    proxies={'https': 'http://localhost:10809'}
)

# Advanced configuration
client = Translate(
    target='zh-CN',
    source='auto',
    fmt='text',
    domain='cn',
    proxies={'https': 'socks5://localhost:10808'},
    timeout=30
)

Language Detection

Detects the language of input text using Google's language detection capabilities.

def detect(self, q: str, timeout=...) -> Union[DetectResponse, Null]:
    """
    Detect the language of input text.
    
    Parameters:
    - q (str): Text to detect language for (single string only)
    - timeout (int, optional): Request timeout in seconds
    
    Returns:
    - DetectResponse: Language detection result with .language attribute
    - Null: Error response if detection fails
    """

Usage Example:

# Detect language
result = client.detect('Hello, world!')
if isinstance(result, DetectResponse):
    print(result.language)  # 'en'
else:
    print(f"Detection failed: {result}")

Text Translation

Translates text from source to target language with support for both single strings and batch processing.

def translate(
    self,
    q: Union[str, List[str]],
    target: str = None,
    source: str = None, 
    fmt: str = None,
    timeout=...
) -> Union[TranslateResponse, List[TranslateResponse], Null]:
    """
    Translate text to target language.
    
    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")
    - fmt (str, optional): Text format "text" or "html" (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
    """

Usage Examples:

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

# Batch translation
texts = ['Good morning', 'How are you?', 'See you later']
results = client.translate(texts, target='zh-CN')
if isinstance(results, list):
    for result in results:
        print(result.translatedText)
        
# Custom source language
result = client.translate('Bonjour', source='fr', target='en')
print(result.translatedText)  # 'Hello'

# HTML content translation
html_text = '<p>Hello <strong>world</strong>!</p>'
result = client.translate(html_text, fmt='html', target='zh-CN')
print(result.translatedText)  # '<p>你好<strong>世界</strong>!</p>'

Text-to-Speech

Generates MP3 audio data for text using Google's text-to-speech service.

def tts(self, q: str, target: str = None, timeout=...) -> Union[bytes, Null]:
    """
    Generate speech audio for text.
    
    Parameters:
    - q (str): Text to convert to speech (short phrases work best)
    - target (str, optional): Target language code for pronunciation
    - timeout (int, optional): Request timeout in seconds
    
    Returns:
    - bytes: MP3 audio data
    - Null: Error response if TTS fails
    """

Usage Example:

# Generate speech audio
audio_data = client.tts('你好,世界!', target='zh-CN')
if isinstance(audio_data, bytes):
    with open('greeting.mp3', 'wb') as f:
        f.write(audio_data)
    print("Audio file saved as greeting.mp3")
else:
    print(f"TTS failed: {audio_data}")

# English TTS
audio_data = client.tts('Hello, world!', target='en')
with open('hello_en.mp3', 'wb') as f:
    f.write(audio_data)

Error Handling

All methods return Null objects on failure, which contain the original HTTP response and formatted error message:

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

Best Practices

Proxy Configuration

For users outside China, proxy configuration is essential:

# HTTP proxy
client = Translate(proxies={'https': 'http://localhost:10809'})

# SOCKS5 proxy  
client = Translate(proxies={'https': 'socks5://localhost:10808'})

Batch Processing

Use batch translation for better performance:

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

# Inefficient - individual requests
results = [client.translate(text) for text in texts]

Rate Limiting

Handle 429 (Too Many Requests) errors by using batch processing and reasonable delays between requests. The client automatically retries with exponential backoff for 429 errors.

Install with Tessl CLI

npx tessl i tessl/pypi-pygtrans

docs

api-client.md

free-client.md

index.md

languages.md

responses.md

tile.json