0
# Translation Services Integration
1
2
Integration with external translation APIs providing automatic translation suggestions to assist translators. The system supports multiple translation services including DeepL, Google Translate, Azure Translator, and OpenAI, with automatic service selection and error handling.
3
4
## Capabilities
5
6
### Main Translation Interface
7
8
Central translation function that dispatches to configured translation services.
9
10
```python { .api }
11
def translate(text: str, from_language: str, to_language: str) -> str:
12
"""
13
Main translation function supporting multiple services.
14
15
Automatically selects appropriate translation service based on
16
configured API keys and language support. Tries services in order
17
of preference: DeepL, Google, Azure, OpenAI.
18
19
Parameters:
20
- text: Text to translate
21
- from_language: Source language code (ISO 639-1)
22
- to_language: Target language code (ISO 639-1)
23
24
Returns:
25
Translated text string
26
27
Raises:
28
TranslationException: When translation fails or no service available
29
"""
30
31
class TranslationException(Exception):
32
"""
33
Exception raised by translation services.
34
35
Raised when:
36
- API key is missing or invalid
37
- Network request fails
38
- Service returns error response
39
- Language pair not supported
40
- Text exceeds service limits
41
"""
42
```
43
44
### DeepL Translation Service
45
46
Integration with DeepL API for high-quality translation suggestions.
47
48
```python { .api }
49
def translate_by_deepl(text: str, to_language: str, auth_key: str) -> str:
50
"""
51
DeepL API integration for translation suggestions.
52
53
Uses DeepL API to translate text with high quality results.
54
Automatically handles Django template variable preservation.
55
56
Parameters:
57
- text: Text to translate (may contain Django template variables)
58
- to_language: Target language code (DeepL format: 'EN', 'DE', 'FR', etc.)
59
- auth_key: DeepL API authentication key
60
61
Returns:
62
Translated text with preserved template variables
63
64
Raises:
65
TranslationException: On API errors or invalid key
66
"""
67
68
def format_text_to_deepl(text: str) -> str:
69
"""
70
Format Django template variables for DeepL API.
71
72
Protects Django template variables (%(var)s, {var}) from translation
73
by converting them to XML tags that DeepL preserves.
74
75
Parameters:
76
- text: Text containing Django template variables
77
78
Returns:
79
Text with variables converted to XML tags
80
"""
81
82
def format_text_from_deepl(text: str) -> str:
83
"""
84
Parse DeepL API response back to Django format.
85
86
Converts XML tags back to Django template variables after
87
translation, restoring original variable syntax.
88
89
Parameters:
90
- text: DeepL response with XML-formatted variables
91
92
Returns:
93
Text with restored Django template variables
94
"""
95
```
96
97
### Google Translate Service
98
99
Integration with Google Cloud Translation API.
100
101
```python { .api }
102
def translate_by_google(text: str, input_language: str, output_language: str, credentials_path: str, project_id: str) -> str:
103
"""
104
Google Cloud Translation API integration.
105
106
Uses Google Translate API v3 for translation suggestions.
107
Requires Google Cloud project with Translation API enabled.
108
109
Parameters:
110
- text: Text to translate
111
- input_language: Source language code (BCP-47: 'en', 'fr', 'de', etc.)
112
- output_language: Target language code (BCP-47 format)
113
- credentials_path: Path to Google Cloud service account JSON file
114
- project_id: Google Cloud project ID
115
116
Returns:
117
Translated text string
118
119
Raises:
120
TranslationException: On authentication or API errors
121
"""
122
```
123
124
### Azure Translator Service
125
126
Integration with Microsoft Azure Translator API.
127
128
```python { .api }
129
def translate_by_azure(text: str, from_language: str, to_language: str, subscription_key: str) -> str:
130
"""
131
Azure Translator API integration.
132
133
Uses Microsoft Azure Cognitive Services Translator API
134
for translation suggestions.
135
136
Parameters:
137
- text: Text to translate
138
- from_language: Source language code (ISO 639-1: 'en', 'fr', 'de', etc.)
139
- to_language: Target language code (ISO 639-1 format)
140
- subscription_key: Azure Translator subscription key
141
142
Returns:
143
Translated text string
144
145
Raises:
146
TranslationException: On authentication or API errors
147
"""
148
```
149
150
### OpenAI Translation Service
151
152
Integration with OpenAI API for AI-powered translation suggestions.
153
154
```python { .api }
155
def translate_by_openai(text: str, from_language: str, to_language: str, api_key: str) -> str:
156
"""
157
OpenAI API integration for translation suggestions.
158
159
Uses OpenAI's language models for translation with customizable
160
prompts. Supports context-aware translation and natural language
161
handling.
162
163
Parameters:
164
- text: Text to translate
165
- from_language: Source language name (e.g., 'English', 'French')
166
- to_language: Target language name (e.g., 'German', 'Spanish')
167
- api_key: OpenAI API key
168
169
Returns:
170
Translated text string
171
172
Raises:
173
TranslationException: On API errors or quota exceeded
174
"""
175
```
176
177
## Configuration
178
179
Translation services are configured through Django settings:
180
181
```python { .api }
182
# Enable translation suggestions
183
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS: bool = False
184
185
# DeepL Configuration
186
ROSETTA_DEEPL_AUTH_KEY: str = ''
187
ROSETTA_DEEPL_LANGUAGES: list = ['EN', 'DE', 'FR', 'IT', 'JA', 'ES', 'NL', 'PL', 'PT', 'RU', 'ZH']
188
189
# Google Translate Configuration
190
ROSETTA_GOOGLE_APPLICATION_CREDENTIALS_PATH: str = ''
191
ROSETTA_GOOGLE_PROJECT_ID: str = ''
192
193
# Azure Translator Configuration
194
ROSETTA_AZURE_CLIENT_SECRET: str = ''
195
196
# OpenAI Configuration
197
ROSETTA_OPENAI_API_KEY: str = ''
198
ROSETTA_OPENAI_PROMPT_TEMPLATE: str = 'Translate the following text from {from_language} to {to_language}: {text}'
199
```
200
201
## Usage Examples
202
203
### Basic Translation Service Setup
204
205
```python
206
# settings.py - Enable DeepL translation suggestions
207
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS = True
208
ROSETTA_DEEPL_AUTH_KEY = 'your-deepl-api-key-here'
209
210
# Now translation suggestions appear in the web interface
211
# Users can click "Suggest" next to translation fields
212
```
213
214
### Multiple Service Configuration
215
216
```python
217
# settings.py - Configure multiple translation services
218
ROSETTA_ENABLE_TRANSLATION_SUGGESTIONS = True
219
220
# Primary service: DeepL (highest quality)
221
ROSETTA_DEEPL_AUTH_KEY = 'your-deepl-key'
222
223
# Fallback service: Google Translate
224
ROSETTA_GOOGLE_APPLICATION_CREDENTIALS_PATH = '/path/to/google-credentials.json'
225
ROSETTA_GOOGLE_PROJECT_ID = 'your-google-project-id'
226
227
# Additional service: Azure
228
ROSETTA_AZURE_CLIENT_SECRET = 'your-azure-key'
229
230
# AI service: OpenAI
231
ROSETTA_OPENAI_API_KEY = 'your-openai-key'
232
ROSETTA_OPENAI_PROMPT_TEMPLATE = 'Please translate this text from {from_language} to {to_language}, maintaining the original tone and context: {text}'
233
```
234
235
### Programmatic Translation Usage
236
237
```python
238
from rosetta.translate_utils import translate, TranslationException
239
240
def get_translation_suggestion(text, source_lang, target_lang):
241
"""Get translation suggestion for user interface."""
242
243
try:
244
translation = translate(text, source_lang, target_lang)
245
return {
246
'success': True,
247
'translation': translation
248
}
249
except TranslationException as e:
250
return {
251
'success': False,
252
'error': str(e)
253
}
254
255
# Usage in views
256
def translation_view(request):
257
if request.method == 'POST':
258
text = request.POST.get('text')
259
result = get_translation_suggestion(text, 'en', 'fr')
260
261
if result['success']:
262
# Use the translation
263
translation = result['translation']
264
else:
265
# Handle error
266
error_message = result['error']
267
268
return render(request, 'template.html')
269
```
270
271
### Service-Specific Usage
272
273
```python
274
from rosetta.translate_utils import (
275
translate_by_deepl,
276
translate_by_google,
277
translate_by_azure,
278
translate_by_openai,
279
TranslationException
280
)
281
282
def compare_translation_services(text):
283
"""Compare results from different translation services."""
284
285
results = {}
286
287
# DeepL translation
288
try:
289
results['deepl'] = translate_by_deepl(text, 'FR', 'your-deepl-key')
290
except TranslationException as e:
291
results['deepl'] = f"Error: {e}"
292
293
# Google translation
294
try:
295
results['google'] = translate_by_google(
296
text, 'en', 'fr',
297
'/path/to/credentials.json',
298
'project-id'
299
)
300
except TranslationException as e:
301
results['google'] = f"Error: {e}"
302
303
# Azure translation
304
try:
305
results['azure'] = translate_by_azure(text, 'en', 'fr', 'azure-key')
306
except TranslationException as e:
307
results['azure'] = f"Error: {e}"
308
309
# OpenAI translation
310
try:
311
results['openai'] = translate_by_openai(text, 'English', 'French', 'openai-key')
312
except TranslationException as e:
313
results['openai'] = f"Error: {e}"
314
315
return results
316
```
317
318
### Django Template Variable Handling
319
320
```python
321
# DeepL automatically handles Django template variables
322
text_with_variables = "Hello %(name)s, you have {count} messages."
323
324
# DeepL preserves variables during translation
325
translated = translate_by_deepl(text_with_variables, 'FR', 'your-key')
326
# Result: "Bonjour %(name)s, vous avez {count} messages."
327
328
# Manual variable formatting (for custom implementations)
329
from rosetta.translate_utils import format_text_to_deepl, format_text_from_deepl
330
331
# Before sending to DeepL
332
formatted_text = format_text_to_deepl("Hello %(name)s!")
333
# Result: "Hello <var1>name</var1>!"
334
335
# After receiving from DeepL
336
restored_text = format_text_from_deepl("Bonjour <var1>name</var1>!")
337
# Result: "Bonjour %(name)s!"
338
```
339
340
### Error Handling and Fallbacks
341
342
```python
343
from rosetta.translate_utils import translate, TranslationException
344
from rosetta.conf import settings as rosetta_settings
345
346
def robust_translation(text, from_lang, to_lang):
347
"""Translation with comprehensive error handling."""
348
349
if not rosetta_settings.ENABLE_TRANSLATION_SUGGESTIONS:
350
return None
351
352
try:
353
# Attempt translation
354
return translate(text, from_lang, to_lang)
355
356
except TranslationException as e:
357
# Log the error for debugging
358
import logging
359
logger = logging.getLogger('rosetta.translation')
360
logger.warning(f"Translation failed: {e}")
361
362
# Return None to indicate no suggestion available
363
return None
364
365
except Exception as e:
366
# Handle unexpected errors
367
import logging
368
logger = logging.getLogger('rosetta.translation')
369
logger.error(f"Unexpected translation error: {e}")
370
return None
371
```
372
373
### Custom Translation Service Integration
374
375
```python
376
# Custom service implementation
377
def translate_by_custom_service(text, from_language, to_language, api_key):
378
"""Custom translation service integration."""
379
380
import requests
381
382
try:
383
response = requests.post(
384
'https://api.custom-translator.com/translate',
385
headers={'Authorization': f'Bearer {api_key}'},
386
json={
387
'text': text,
388
'from': from_language,
389
'to': to_language
390
}
391
)
392
393
if response.status_code == 200:
394
return response.json()['translation']
395
else:
396
raise TranslationException(f"API error: {response.status_code}")
397
398
except requests.RequestException as e:
399
raise TranslationException(f"Network error: {e}")
400
401
# Integrate with main translate function by modifying service priority order
402
```