or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

free-client.mddocs/

0

# Free Translation Client

1

2

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.

3

4

## Capabilities

5

6

### Client Initialization

7

8

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

9

10

```python { .api }

11

def __init__(

12

self,

13

target: str = "zh-CN",

14

source: str = "auto",

15

fmt="html",

16

user_agent: str = None,

17

domain: str = "com",

18

proxies: dict = None,

19

timeout: int = None,

20

trust_env=False

21

):

22

"""

23

Initialize free translation client.

24

25

Parameters:

26

- target (str): Default target language code (default: "zh-CN")

27

- source (str): Default source language code (default: "auto" for auto-detection)

28

- fmt (str): Text format - "text" or "html" (default: "html")

29

- user_agent (str): Custom user agent string (default: auto-generated)

30

- domain (str): Google domain - "com", "cn", etc. (default: "com")

31

- proxies (dict): Proxy configuration {'https': 'http://localhost:10809'}

32

- timeout (int): Request timeout in seconds

33

- trust_env (bool): Trust environment variables for proxy config

34

"""

35

```

36

37

**Usage Example:**

38

39

```python

40

from pygtrans import Translate

41

42

# Basic configuration with proxy (required for non-Chinese users)

43

client = Translate(

44

target='en',

45

proxies={'https': 'http://localhost:10809'}

46

)

47

48

# Advanced configuration

49

client = Translate(

50

target='zh-CN',

51

source='auto',

52

fmt='text',

53

domain='cn',

54

proxies={'https': 'socks5://localhost:10808'},

55

timeout=30

56

)

57

```

58

59

### Language Detection

60

61

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

62

63

```python { .api }

64

def detect(self, q: str, timeout=...) -> Union[DetectResponse, Null]:

65

"""

66

Detect the language of input text.

67

68

Parameters:

69

- q (str): Text to detect language for (single string only)

70

- timeout (int, optional): Request timeout in seconds

71

72

Returns:

73

- DetectResponse: Language detection result with .language attribute

74

- Null: Error response if detection fails

75

"""

76

```

77

78

**Usage Example:**

79

80

```python

81

# Detect language

82

result = client.detect('Hello, world!')

83

if isinstance(result, DetectResponse):

84

print(result.language) # 'en'

85

else:

86

print(f"Detection failed: {result}")

87

```

88

89

### Text Translation

90

91

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

92

93

```python { .api }

94

def translate(

95

self,

96

q: Union[str, List[str]],

97

target: str = None,

98

source: str = None,

99

fmt: str = None,

100

timeout=...

101

) -> Union[TranslateResponse, List[TranslateResponse], Null]:

102

"""

103

Translate text to target language.

104

105

Parameters:

106

- q (str or List[str]): Text to translate (single string or list of strings)

107

- target (str, optional): Target language code (default: instance default)

108

- source (str, optional): Source language code (default: "auto")

109

- fmt (str, optional): Text format "text" or "html" (default: instance default)

110

- timeout (int, optional): Request timeout in seconds

111

112

Returns:

113

- TranslateResponse: Single translation result (when q is str)

114

- List[TranslateResponse]: List of translation results (when q is List[str])

115

- Null: Error response if translation fails

116

"""

117

```

118

119

**Usage Examples:**

120

121

```python

122

# Single translation

123

result = client.translate('Hello, world!', target='zh-CN')

124

if isinstance(result, TranslateResponse):

125

print(result.translatedText) # '你好世界!'

126

127

# Batch translation

128

texts = ['Good morning', 'How are you?', 'See you later']

129

results = client.translate(texts, target='zh-CN')

130

if isinstance(results, list):

131

for result in results:

132

print(result.translatedText)

133

134

# Custom source language

135

result = client.translate('Bonjour', source='fr', target='en')

136

print(result.translatedText) # 'Hello'

137

138

# HTML content translation

139

html_text = '<p>Hello <strong>world</strong>!</p>'

140

result = client.translate(html_text, fmt='html', target='zh-CN')

141

print(result.translatedText) # '<p>你好<strong>世界</strong>!</p>'

142

```

143

144

### Text-to-Speech

145

146

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

147

148

```python { .api }

149

def tts(self, q: str, target: str = None, timeout=...) -> Union[bytes, Null]:

150

"""

151

Generate speech audio for text.

152

153

Parameters:

154

- q (str): Text to convert to speech (short phrases work best)

155

- target (str, optional): Target language code for pronunciation

156

- timeout (int, optional): Request timeout in seconds

157

158

Returns:

159

- bytes: MP3 audio data

160

- Null: Error response if TTS fails

161

"""

162

```

163

164

**Usage Example:**

165

166

```python

167

# Generate speech audio

168

audio_data = client.tts('你好,世界!', target='zh-CN')

169

if isinstance(audio_data, bytes):

170

with open('greeting.mp3', 'wb') as f:

171

f.write(audio_data)

172

print("Audio file saved as greeting.mp3")

173

else:

174

print(f"TTS failed: {audio_data}")

175

176

# English TTS

177

audio_data = client.tts('Hello, world!', target='en')

178

with open('hello_en.mp3', 'wb') as f:

179

f.write(audio_data)

180

```

181

182

## Error Handling

183

184

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

185

186

```python

187

result = client.translate('Hello')

188

if isinstance(result, Null):

189

print(f"Translation failed: {result.msg}")

190

print(f"Status code: {result.response.status_code}")

191

```

192

193

## Best Practices

194

195

### Proxy Configuration

196

197

For users outside China, proxy configuration is essential:

198

199

```python

200

# HTTP proxy

201

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

202

203

# SOCKS5 proxy

204

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

205

```

206

207

### Batch Processing

208

209

Use batch translation for better performance:

210

211

```python

212

# Efficient - batch processing

213

texts = ['Text 1', 'Text 2', 'Text 3']

214

results = client.translate(texts)

215

216

# Inefficient - individual requests

217

results = [client.translate(text) for text in texts]

218

```

219

220

### Rate Limiting

221

222

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.