0
# Googletrans
1
2
An unofficial Google Translate API for Python that provides free and unlimited text translation capabilities without requiring API keys. Built on top of httpx with HTTP/2 support, it reverse-engineers Google's web translation service to enable automatic language detection, text translation between 450+ languages, batch operations, and includes a command-line interface.
3
4
## Package Information
5
6
- **Package Name**: googletrans
7
- **Package Type**: pypi
8
- **Language**: Python 3.8+
9
- **Installation**: `pip install googletrans`
10
11
## Core Imports
12
13
```python
14
from googletrans import Translator
15
```
16
17
For language constants:
18
19
```python
20
from googletrans import LANGUAGES, LANGCODES
21
```
22
23
For full typing support:
24
25
```python
26
import typing
27
from typing import Dict, List, Tuple, Union, Optional
28
from httpx import Timeout
29
from httpx._types import ProxyTypes
30
```
31
32
## Basic Usage
33
34
```python
35
import asyncio
36
from googletrans import Translator
37
38
async def basic_translation():
39
async with Translator() as translator:
40
# Simple translation (auto-detect source language)
41
result = await translator.translate('안녕하세요.')
42
print(f"{result.text} (detected: {result.src})")
43
# Output: Hello. (detected: ko)
44
45
# Specify source and destination languages
46
result = await translator.translate('Hello world', src='en', dest='es')
47
print(result.text) # Hola mundo
48
49
# Language detection
50
detected = await translator.detect('Bonjour le monde')
51
print(f"Language: {detected.lang}, Confidence: {detected.confidence}")
52
# Language: fr, Confidence: 0.85
53
54
asyncio.run(basic_translation())
55
```
56
57
## Architecture
58
59
The googletrans library follows an async-first design:
60
61
- **Translator Class**: Main client that manages HTTP connections and translation requests
62
- **Async Context Manager**: Handles HTTP client lifecycle with proper resource cleanup
63
- **Token System**: Automatically manages Google Translate authorization tokens
64
- **Batch Processing**: Concurrent translation of multiple texts with configurable limits
65
- **HTTP/2 Support**: Uses modern HTTP protocol for improved performance
66
- **Proxy Support**: Full proxy configuration via httpx integration
67
68
## Capabilities
69
70
### Translation
71
72
Translate text between any of 450+ supported languages with automatic source language detection, batch processing capabilities, and comprehensive metadata including pronunciation guides.
73
74
```python { .api }
75
async def translate(
76
self,
77
text: typing.Union[str, typing.List[str]],
78
dest: str = "en",
79
src: str = "auto",
80
**kwargs: typing.Any
81
) -> typing.Union[Translated, typing.List[Translated]]:
82
"""
83
Translate text from source language to destination language.
84
85
Args:
86
text: Source text(s) to translate. Supports batch via list input.
87
dest: Destination language code (e.g., 'en', 'es', 'fr')
88
src: Source language code or 'auto' for detection
89
**kwargs: Additional options including list_operation_max_concurrency
90
91
Returns:
92
Translated object or list of Translated objects for batch input
93
"""
94
```
95
96
Usage examples:
97
98
```python
99
async with Translator() as translator:
100
# Single translation
101
result = await translator.translate('Hello', dest='es')
102
print(result.text) # Hola
103
104
# Batch translation
105
texts = ['Hello', 'Goodbye', 'Thank you']
106
results = await translator.translate(texts, dest='fr')
107
for result in results:
108
print(f"{result.origin} -> {result.text}")
109
110
# Control concurrency for large batches
111
results = await translator.translate(
112
large_text_list,
113
dest='de',
114
list_operation_max_concurrency=5
115
)
116
```
117
118
### Language Detection
119
120
Detect the language of input text with confidence scores, supporting both single texts and batch processing for efficient language identification.
121
122
```python { .api }
123
async def detect(
124
self,
125
text: typing.Union[str, typing.List[str]],
126
**kwargs: typing.Any
127
) -> typing.Union[Detected, typing.List[Detected]]:
128
"""
129
Detect language of input text(s).
130
131
Args:
132
text: Text(s) for language detection. Supports batch via list input.
133
**kwargs: Additional options including list_operation_max_concurrency
134
135
Returns:
136
Detected object or list of Detected objects for batch input
137
"""
138
```
139
140
Usage examples:
141
142
```python
143
async with Translator() as translator:
144
# Single detection
145
detected = await translator.detect('Hola mundo')
146
print(f"Language: {detected.lang}, Confidence: {detected.confidence}")
147
148
# Batch detection
149
texts = ['Hello', 'Bonjour', 'Hola', 'Guten Tag']
150
results = await translator.detect(texts)
151
for i, result in enumerate(results):
152
print(f"'{texts[i]}' -> {result.lang}")
153
```
154
155
### Configuration
156
157
Customize translator behavior including service URLs, proxy settings, HTTP/2 support, timeout configuration, and error handling preferences.
158
159
```python { .api }
160
def __init__(
161
self,
162
service_urls: typing.Sequence[str] = DEFAULT_CLIENT_SERVICE_URLS,
163
user_agent: str = DEFAULT_USER_AGENT,
164
raise_exception: bool = DEFAULT_RAISE_EXCEPTION,
165
proxy: typing.Optional[ProxyTypes] = None,
166
timeout: typing.Optional[Timeout] = None,
167
http2: bool = True,
168
list_operation_max_concurrency: int = 2
169
):
170
"""
171
Initialize Translator with custom configuration.
172
173
Args:
174
service_urls: Google Translate URLs (randomly selected)
175
user_agent: Custom User-Agent header
176
raise_exception: Whether to raise exceptions on errors
177
proxy: HTTP proxy configuration
178
timeout: Request timeout settings
179
http2: Enable HTTP/2 support
180
list_operation_max_concurrency: Max concurrent batch operations
181
"""
182
```
183
184
Usage examples:
185
186
```python
187
from httpx import Timeout
188
189
# Custom configuration
190
translator = Translator(
191
service_urls=['translate.google.com', 'translate.google.co.kr'],
192
proxy='http://proxy.example.com:8080',
193
timeout=Timeout(30.0),
194
raise_exception=True,
195
list_operation_max_concurrency=5
196
)
197
198
async with translator:
199
result = await translator.translate('Hello', dest='ja')
200
```
201
202
### Language Constants
203
204
Access comprehensive language code mappings for all 450+ supported languages, enabling validation and conversion between language codes and human-readable names.
205
206
```python { .api }
207
# Language code to name mapping
208
LANGUAGES: Dict[str, str]
209
210
# Language name to code mapping
211
LANGCODES: Dict[str, str]
212
```
213
214
Usage examples:
215
216
```python
217
from googletrans import LANGUAGES, LANGCODES
218
219
# Check supported languages
220
print(LANGUAGES['ko']) # korean
221
print(LANGCODES['french']) # fr
222
223
# Validate language codes
224
if 'zh-cn' in LANGUAGES:
225
print("Chinese (Simplified) is supported")
226
227
# List all supported languages
228
for code, name in LANGUAGES.items():
229
print(f"{code}: {name}")
230
```
231
232
### Command Line Interface
233
234
The package includes a CLI script that provides command-line access to translation functionality, though the current implementation has compatibility issues with the async API.
235
236
```bash
237
# Basic translation (auto-detect source)
238
translate "Hello world" --dest es
239
240
# Specify source and destination
241
translate "Hello world" --src en --dest fr
242
243
# Language detection only
244
translate "Bonjour le monde" --detect
245
```
246
247
**Note**: The CLI script (`translate`) currently calls async methods synchronously, which may cause runtime errors. The script would need to be updated to properly handle the async API using `asyncio.run()`.
248
249
## Types
250
251
```python { .api }
252
class Translator:
253
"""Main translation client with async context manager support."""
254
255
def __init__(self, **config): ...
256
async def translate(self, text, dest="en", src="auto", **kwargs): ...
257
async def detect(self, text, **kwargs): ...
258
async def __aenter__(self): ...
259
async def __aexit__(self, exc_type, exc_val, exc_tb): ...
260
261
class Translated:
262
"""Translation result with source text, translated text, and metadata."""
263
264
src: str # Source language code
265
dest: str # Destination language code
266
origin: str # Original input text
267
text: str # Translated text
268
pronunciation: str # Pronunciation guide
269
extra_data: dict | None # Additional data (synonyms, definitions, etc.)
270
271
class Detected:
272
"""Language detection result with detected language and confidence."""
273
274
lang: str # Detected language code
275
confidence: float # Detection confidence (0.0 to 1.0)
276
277
# Configuration constants
278
DEFAULT_CLIENT_SERVICE_URLS: Tuple[str, ...]
279
DEFAULT_USER_AGENT: str
280
DEFAULT_RAISE_EXCEPTION: bool
281
282
# Language mapping constants
283
LANGUAGES: Dict[str, str] # Language code -> name mapping
284
LANGCODES: Dict[str, str] # Language name -> code mapping
285
```
286
287
## Error Handling
288
289
The library handles errors gracefully with configurable exception behavior:
290
291
```python
292
# Default: returns dummy data on errors
293
translator = Translator(raise_exception=False) # Default
294
result = await translator.translate("text") # Returns fallback on error
295
296
# Strict mode: raises exceptions
297
translator = Translator(raise_exception=True)
298
try:
299
result = await translator.translate("text")
300
except Exception as e:
301
print(f"Translation failed: {e}")
302
```
303
304
Common errors include network connectivity issues, invalid language codes, and Google service limitations. The library includes automatic token refresh and retry logic for transient failures.