0
# Response Objects
1
2
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.
3
4
## Capabilities
5
6
### TranslateResponse
7
8
Contains the results of text translation operations, including the translated text, detected source language, and translation model information.
9
10
```python { .api }
11
class TranslateResponse:
12
def __init__(
13
self,
14
translatedText: str,
15
detectedSourceLanguage: str = None,
16
model: str = None
17
):
18
"""
19
Translation result container.
20
21
Parameters:
22
- translatedText (str): The translated text result
23
- detectedSourceLanguage (str, optional): Auto-detected source language code
24
- model (str, optional): Translation model used ('nmt', 'pbmt', or None)
25
"""
26
27
# Public attributes:
28
translatedText: str # The translated text
29
detectedSourceLanguage: str # Detected source language (if auto-detected)
30
model: str # Translation model used
31
```
32
33
**Usage Examples:**
34
35
```python
36
from pygtrans import Translate
37
38
client = Translate(proxies={'https': 'http://localhost:10809'})
39
result = client.translate('Hello, world!', target='zh-CN')
40
41
# Access translation result
42
print(result.translatedText) # '你好世界!'
43
print(result.detectedSourceLanguage) # 'en' (auto-detected)
44
print(result.model) # None (not available in free version)
45
46
# Batch results
47
results = client.translate(['Hello', 'Goodbye'], target='zh-CN')
48
for result in results:
49
print(f"'{result.translatedText}' (from {result.detectedSourceLanguage})")
50
```
51
52
**API Key Client Results:**
53
54
```python
55
from pygtrans import ApiKeyTranslate
56
57
client = ApiKeyTranslate(api_key='your-key')
58
result = client.translate('Hello, world!', target='zh-CN')
59
60
print(result.translatedText) # '你好世界!'
61
print(result.detectedSourceLanguage) # 'en'
62
print(result.model) # 'nmt'
63
```
64
65
### DetectResponse
66
67
Contains language detection results with the detected language code and confidence metrics.
68
69
```python { .api }
70
class DetectResponse:
71
def __init__(
72
self,
73
language: str,
74
isReliable: bool = True,
75
confidence: float = 1.0
76
):
77
"""
78
Language detection result container.
79
80
Parameters:
81
- language (str): Detected language code (e.g., 'en', 'zh-CN', 'fr')
82
- isReliable (bool): Detection reliability indicator (deprecated)
83
- confidence (float): Detection confidence score 0.0-1.0 (deprecated)
84
"""
85
86
# Public attributes:
87
language: str # Detected language code
88
isReliable: bool # Reliability indicator (deprecated, always True)
89
confidence: float # Confidence score (deprecated, always 1.0)
90
```
91
92
**Usage Examples:**
93
94
```python
95
# Free client detection
96
client = Translate(proxies={'https': 'http://localhost:10809'})
97
result = client.detect('Bonjour le monde')
98
99
print(result.language) # 'fr'
100
print(result.isReliable) # True
101
print(result.confidence) # 1.0
102
103
# API client detection (single)
104
api_client = ApiKeyTranslate(api_key='your-key')
105
result = api_client.detect('Hello, world!')
106
print(result.language) # 'en'
107
108
# API client detection (batch)
109
results = api_client.detect(['Hello', 'Bonjour', 'Hola'])
110
for i, result in enumerate(results):
111
print(f"Text {i+1}: {result.language}")
112
# Text 1: en, Text 2: fr, Text 3: es
113
```
114
115
### LanguageResponse
116
117
Contains information about supported languages, including language codes and human-readable names.
118
119
```python { .api }
120
class LanguageResponse:
121
def __init__(self, language: str, name: str = None):
122
"""
123
Language information container.
124
125
Parameters:
126
- language (str): Language code (e.g., 'en', 'zh-CN', 'fr')
127
- name (str, optional): Human-readable language name
128
"""
129
130
# Public attributes:
131
language: str # Language code
132
name: str # Human-readable language name
133
```
134
135
**Usage Examples:**
136
137
```python
138
from pygtrans import ApiKeyTranslate
139
140
client = ApiKeyTranslate(api_key='your-key')
141
142
# Get supported languages with Chinese names
143
languages = client.languages(target='zh-CN')
144
for lang in languages[:5]: # First 5 languages
145
print(f"{lang.language}: {lang.name}")
146
# en: 英语
147
# fr: 法语
148
# es: 西班牙语
149
# de: 德语
150
# it: 意大利语
151
152
# Get supported languages with English names
153
languages = client.languages(target='en')
154
for lang in languages[:3]:
155
print(f"{lang.language}: {lang.name}")
156
# en: English
157
# fr: French
158
# es: Spanish
159
```
160
161
### Null
162
163
Error response container that holds information about failed requests, including the original HTTP response and formatted error message.
164
165
```python { .api }
166
class Null:
167
def __init__(self, response: requests.Response):
168
"""
169
Error response container for failed requests.
170
171
Parameters:
172
- response (requests.Response): The failed HTTP response object
173
"""
174
175
# Public attributes:
176
response: requests.Response # The failed HTTP response
177
msg: str # Formatted error message with status code and text
178
```
179
180
**Usage Examples:**
181
182
```python
183
from pygtrans import Translate, Null
184
185
# Example with invalid configuration (no proxy for non-Chinese users)
186
client = Translate() # Missing required proxy
187
result = client.translate('Hello')
188
189
if isinstance(result, Null):
190
print(f"Request failed: {result.msg}")
191
print(f"Status code: {result.response.status_code}")
192
print(f"Response headers: {result.response.headers}")
193
print(f"Response text: {result.response.text}")
194
195
# Example with API key client and invalid key
196
from pygtrans import ApiKeyTranslate
197
198
api_client = ApiKeyTranslate(api_key='invalid-key')
199
result = api_client.translate('Hello')
200
201
if isinstance(result, Null):
202
print(f"API request failed: {result}")
203
# Will show formatted error with status code and details
204
```
205
206
## Response Type Checking
207
208
Always check response types before accessing attributes to handle potential errors:
209
210
```python
211
from pygtrans import TranslateResponse, DetectResponse, LanguageResponse, Null
212
213
# Translation result checking
214
result = client.translate('Hello')
215
if isinstance(result, TranslateResponse):
216
print(f"Success: {result.translatedText}")
217
elif isinstance(result, Null):
218
print(f"Error: {result.msg}")
219
220
# Batch result checking
221
results = client.translate(['Hello', 'World'])
222
if isinstance(results, list):
223
for result in results:
224
if isinstance(result, TranslateResponse):
225
print(result.translatedText)
226
elif isinstance(results, Null):
227
print(f"Batch translation failed: {results.msg}")
228
229
# Detection result checking
230
detection = client.detect('Bonjour')
231
if isinstance(detection, DetectResponse):
232
print(f"Detected: {detection.language}")
233
elif isinstance(detection, Null):
234
print(f"Detection failed: {detection.msg}")
235
236
# Language list checking
237
languages = api_client.languages()
238
if isinstance(languages, list):
239
print(f"Found {len(languages)} supported languages")
240
for lang in languages[:5]:
241
if isinstance(lang, LanguageResponse):
242
print(f"{lang.language}: {lang.name}")
243
elif isinstance(languages, Null):
244
print(f"Language query failed: {languages.msg}")
245
```
246
247
## String Representation
248
249
All response objects provide meaningful string representations:
250
251
```python
252
# TranslateResponse representation
253
result = client.translate('Hello')
254
print(repr(result))
255
# TranslateResponse(translatedText='你好', detectedSourceLanguage='en', model=None)
256
257
# DetectResponse representation
258
detection = client.detect('Hello')
259
print(repr(detection))
260
# DetectResponse(language='en', isReliable=True, confidence=1.0)
261
262
# LanguageResponse representation (note: has bug in source - shows language twice)
263
lang = languages[0]
264
print(repr(lang))
265
# LanguageResponse(language='en', name='en') # Bug: shows language instead of name
266
267
# Null representation shows error message
268
error = Null(some_failed_response)
269
print(repr(error))
270
# Shows formatted error message with status code and response text
271
```