Google Translate library with support for free and API key-based translation services
—
pygtrans uses structured response objects to provide consistent access to translation results, language detection outcomes, language information, and error responses. These objects encapsulate the data returned by both free and API-based translation services.
Contains the results of text translation operations, including the translated text, detected source language, and translation model information.
class TranslateResponse:
def __init__(
self,
translatedText: str,
detectedSourceLanguage: str = None,
model: str = None
):
"""
Translation result container.
Parameters:
- translatedText (str): The translated text result
- detectedSourceLanguage (str, optional): Auto-detected source language code
- model (str, optional): Translation model used ('nmt', 'pbmt', or None)
"""
# Public attributes:
translatedText: str # The translated text
detectedSourceLanguage: str # Detected source language (if auto-detected)
model: str # Translation model usedUsage Examples:
from pygtrans import Translate
client = Translate(proxies={'https': 'http://localhost:10809'})
result = client.translate('Hello, world!', target='zh-CN')
# Access translation result
print(result.translatedText) # '你好世界!'
print(result.detectedSourceLanguage) # 'en' (auto-detected)
print(result.model) # None (not available in free version)
# Batch results
results = client.translate(['Hello', 'Goodbye'], target='zh-CN')
for result in results:
print(f"'{result.translatedText}' (from {result.detectedSourceLanguage})")API Key Client Results:
from pygtrans import ApiKeyTranslate
client = ApiKeyTranslate(api_key='your-key')
result = client.translate('Hello, world!', target='zh-CN')
print(result.translatedText) # '你好世界!'
print(result.detectedSourceLanguage) # 'en'
print(result.model) # 'nmt'Contains language detection results with the detected language code and confidence metrics.
class DetectResponse:
def __init__(
self,
language: str,
isReliable: bool = True,
confidence: float = 1.0
):
"""
Language detection result container.
Parameters:
- language (str): Detected language code (e.g., 'en', 'zh-CN', 'fr')
- isReliable (bool): Detection reliability indicator (deprecated)
- confidence (float): Detection confidence score 0.0-1.0 (deprecated)
"""
# Public attributes:
language: str # Detected language code
isReliable: bool # Reliability indicator (deprecated, always True)
confidence: float # Confidence score (deprecated, always 1.0)Usage Examples:
# Free client detection
client = Translate(proxies={'https': 'http://localhost:10809'})
result = client.detect('Bonjour le monde')
print(result.language) # 'fr'
print(result.isReliable) # True
print(result.confidence) # 1.0
# API client detection (single)
api_client = ApiKeyTranslate(api_key='your-key')
result = api_client.detect('Hello, world!')
print(result.language) # 'en'
# API client detection (batch)
results = api_client.detect(['Hello', 'Bonjour', 'Hola'])
for i, result in enumerate(results):
print(f"Text {i+1}: {result.language}")
# Text 1: en, Text 2: fr, Text 3: esContains information about supported languages, including language codes and human-readable names.
class LanguageResponse:
def __init__(self, language: str, name: str = None):
"""
Language information container.
Parameters:
- language (str): Language code (e.g., 'en', 'zh-CN', 'fr')
- name (str, optional): Human-readable language name
"""
# Public attributes:
language: str # Language code
name: str # Human-readable language nameUsage Examples:
from pygtrans import ApiKeyTranslate
client = ApiKeyTranslate(api_key='your-key')
# Get supported languages with Chinese names
languages = client.languages(target='zh-CN')
for lang in languages[:5]: # First 5 languages
print(f"{lang.language}: {lang.name}")
# en: 英语
# fr: 法语
# es: 西班牙语
# de: 德语
# it: 意大利语
# Get supported languages with English names
languages = client.languages(target='en')
for lang in languages[:3]:
print(f"{lang.language}: {lang.name}")
# en: English
# fr: French
# es: SpanishError response container that holds information about failed requests, including the original HTTP response and formatted error message.
class Null:
def __init__(self, response: requests.Response):
"""
Error response container for failed requests.
Parameters:
- response (requests.Response): The failed HTTP response object
"""
# Public attributes:
response: requests.Response # The failed HTTP response
msg: str # Formatted error message with status code and textUsage Examples:
from pygtrans import Translate, Null
# Example with invalid configuration (no proxy for non-Chinese users)
client = Translate() # Missing required proxy
result = client.translate('Hello')
if isinstance(result, Null):
print(f"Request failed: {result.msg}")
print(f"Status code: {result.response.status_code}")
print(f"Response headers: {result.response.headers}")
print(f"Response text: {result.response.text}")
# Example with API key client and invalid key
from pygtrans import ApiKeyTranslate
api_client = ApiKeyTranslate(api_key='invalid-key')
result = api_client.translate('Hello')
if isinstance(result, Null):
print(f"API request failed: {result}")
# Will show formatted error with status code and detailsAlways check response types before accessing attributes to handle potential errors:
from pygtrans import TranslateResponse, DetectResponse, LanguageResponse, Null
# Translation result checking
result = client.translate('Hello')
if isinstance(result, TranslateResponse):
print(f"Success: {result.translatedText}")
elif isinstance(result, Null):
print(f"Error: {result.msg}")
# Batch result checking
results = client.translate(['Hello', 'World'])
if isinstance(results, list):
for result in results:
if isinstance(result, TranslateResponse):
print(result.translatedText)
elif isinstance(results, Null):
print(f"Batch translation failed: {results.msg}")
# Detection result checking
detection = client.detect('Bonjour')
if isinstance(detection, DetectResponse):
print(f"Detected: {detection.language}")
elif isinstance(detection, Null):
print(f"Detection failed: {detection.msg}")
# Language list checking
languages = api_client.languages()
if isinstance(languages, list):
print(f"Found {len(languages)} supported languages")
for lang in languages[:5]:
if isinstance(lang, LanguageResponse):
print(f"{lang.language}: {lang.name}")
elif isinstance(languages, Null):
print(f"Language query failed: {languages.msg}")All response objects provide meaningful string representations:
# TranslateResponse representation
result = client.translate('Hello')
print(repr(result))
# TranslateResponse(translatedText='你好', detectedSourceLanguage='en', model=None)
# DetectResponse representation
detection = client.detect('Hello')
print(repr(detection))
# DetectResponse(language='en', isReliable=True, confidence=1.0)
# LanguageResponse representation (note: has bug in source - shows language twice)
lang = languages[0]
print(repr(lang))
# LanguageResponse(language='en', name='en') # Bug: shows language instead of name
# Null representation shows error message
error = Null(some_failed_response)
print(repr(error))
# Shows formatted error message with status code and response textInstall with Tessl CLI
npx tessl i tessl/pypi-pygtrans