-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextTranslation.java
More file actions
348 lines (307 loc) · 16.8 KB
/
TextTranslation.java
File metadata and controls
348 lines (307 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import com.translated.lara.Credentials;
import com.translated.lara.errors.LaraException;
import com.translated.lara.translator.*;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
/**
* Complete text translation examples for the Lara Java SDK
*
* This example demonstrates:
* - Single string translation
* - Multiple strings translation
* - Translation with instructions
* - TextBlocks translation (mixed translatable/non-translatable content)
* - Auto-detect source language
* - Advanced options
* - Translation with styleguides
* - Get available languages
*/
public class TextTranslation {
public static void main(String[] args) {
// Set your credentials here
String accessKeyId = "your-access-key-id";
String accessKeySecret = "your-access-key-secret";
Credentials credentials = new Credentials(accessKeyId, accessKeySecret);
Translator lara = new Translator(credentials);
// Example 1: Basic single string translation
System.out.println("=== Basic Single String Translation ===");
try {
TextResult result = lara.translate("Hello, world!", "en-US", "fr-FR");
System.out.println("Original: Hello, world!");
System.out.println("French: " + result.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error translating text: " + e.getMessage() + "\n");
return;
}
// Example 2: Multiple strings translation
System.out.println("=== Multiple Strings Translation ===");
try {
String[] texts = {"Hello", "How are you?", "Goodbye"};
TextResult result = lara.translate(texts, "en-US", "es-ES");
System.out.println("Original: " + Arrays.toString(texts));
System.out.println("Spanish: " + result.getTranslations() + "\n");
} catch (LaraException e) {
System.out.println("Error translating multiple texts: " + e.getMessage() + "\n");
return;
}
// Example 3: TextBlocks translation (mixed translatable/non-translatable content)
System.out.println("=== TextBlocks Translation ===");
try {
TextBlock[] textBlocks = {
new TextBlock("Adventure novels, mysteries, cookbooks—wait, who packed those?", true),
new TextBlock("<br>", false), // Non-translatable HTML
new TextBlock("Suddenly, it doesn't feel so deserted after all.", true),
new TextBlock("<div class=\"separator\"></div>", false), // Non-translatable HTML
new TextBlock("Every page you turn is a new journey, and the best part?", true)
};
TextResult result = lara.translateBlocks(textBlocks, "en-US", "it-IT");
List<TextBlock> translations = result.getTranslationBlocks();
System.out.println("Original TextBlocks: " + textBlocks.length + " blocks");
System.out.println("Translated blocks: " + translations.size());
for (int i = 0; i < translations.size(); i++) {
System.out.println("Block " + (i + 1) + ": " + translations.get(i).getText());
}
System.out.println();
} catch (LaraException e) {
System.out.println("Error with TextBlocks translation: " + e.getMessage() + "\n");
return;
}
// Example 4: Translation with instructions
System.out.println("=== Translation with Instructions ===");
try {
TranslateOptions options = new TranslateOptions()
.setInstructions("Be formal", "Use technical terminology");
TextResult result = lara.translate("Could you send me the report by tomorrow morning?", "en-US", "de-DE", options);
System.out.println("Original: Could you send me the report by tomorrow morning?");
System.out.println("German (formal): " + result.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error with instructed translation: " + e.getMessage() + "\n");
return;
}
// Example 5: Auto-detecting source language
System.out.println("=== Auto-detect Source Language ===");
try {
TextResult result = lara.translate("Bonjour le monde!", null, "en-US");
System.out.println("Original: Bonjour le monde!");
System.out.println("Detected source: " + result.getSourceLanguage());
System.out.println("English: " + result.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error with auto-detection: " + e.getMessage() + "\n");
return;
}
// Example 6: Advanced options with comprehensive settings
System.out.println("=== Translation with Advanced Options ===");
try {
TranslateOptions options = new TranslateOptions()
.setAdaptTo("mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn") // Replace with actual memory IDs
.setGlossaries("gls_1A2b3C4d5E6f7G8h9I0jKl", "gls_2XyZ9AbC8dEf7GhI6jKlMn") // Replace with actual glossary IDs
.setInstructions("Be professional")
.setStyle(TranslationStyle.FLUID)
.setContentType("text/plain")
.setTimeoutMs(10000L);
TextResult result = lara.translate("This is a comprehensive translation example", "en-US", "it-IT", options);
System.out.println("Original: This is a comprehensive translation example");
System.out.println("Italian (with all options): " + result.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error with advanced translation: " + e.getMessage() + "\n");
return;
}
// Example 7: Translation with profanity filter
System.out.println("=== Translation with Profanity Filter ===");
try {
String profanityText = "Don't be such a tool.";
TranslateOptions detectOptions = new TranslateOptions()
.setProfanityFilter(ProfanityFilter.DETECT);
TextResult detectResult = lara.translate(profanityText, "en-US", "it-IT", detectOptions);
System.out.println("Original: " + profanityText);
System.out.println("Detect mode: " + detectResult.getTranslation());
if (detectResult.getProfanities() != null) {
System.out.println("Masked text: " + detectResult.getProfanities().getMaskedText());
System.out.println("Profanities found: " + detectResult.getProfanities().getProfanities().size());
}
TranslateOptions hideOptions = new TranslateOptions()
.setProfanityFilter(ProfanityFilter.HIDE);
TextResult hideResult = lara.translate(profanityText, "en-US", "it-IT", hideOptions);
System.out.println("Hide mode: " + hideResult.getTranslation());
TranslateOptions avoidOptions = new TranslateOptions()
.setProfanityFilter(ProfanityFilter.AVOID);
TextResult avoidResult = lara.translate(profanityText, "en-US", "it-IT", avoidOptions);
System.out.println("Avoid mode: " + avoidResult.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error with profanity filter: " + e.getMessage() + "\n");
return;
}
// Example 8: Translation with reasoning
System.out.println("=== Translation with Reasoning ===");
try {
TranslateOptions reasoningOptions = new TranslateOptions()
.setReasoning(true);
System.out.println("Original: Wonderful cavernous interior in a central but quiet and private area!");
System.out.println("Streaming partial results:");
Consumer<TextResult> streamingCallback = partialResult -> {
System.out.println("Partial result: " + partialResult.getTranslation());
};
TextResult finalResult = lara.translate("Wonderful cavernous interior in a central but quiet and private area!", "en-US", "it-IT", reasoningOptions, streamingCallback);
System.out.println("Final result: " + finalResult.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error with reasoning translation: " + e.getMessage() + "\n");
return;
}
// Example 9: List available styleguides
System.out.println("=== List Available Styleguides ===");
String styleguideId = null;
try {
List<Styleguide> styleguides = lara.styleguides.list();
System.out.println("Total styleguides: " + styleguides.size());
for (Styleguide sg : styleguides) {
System.out.println(" - " + sg.getName() + " (ID: " + sg.getId() + ")");
}
if (!styleguides.isEmpty()) {
styleguideId = styleguides.get(0).getId();
}
System.out.println();
} catch (LaraException e) {
System.out.println("Error listing styleguides: " + e.getMessage() + "\n");
}
// Example 10: Get a specific styleguide by ID
if (styleguideId != null) {
System.out.println("=== Get Styleguide Details ===");
try {
Styleguide styleguide = lara.styleguides.get(styleguideId);
if (styleguide != null) {
System.out.println("Name: " + styleguide.getName());
System.out.println("ID: " + styleguide.getId());
System.out.println("Owner: " + styleguide.getOwnerId());
System.out.println("Created: " + styleguide.getCreatedAt());
System.out.println("Updated: " + styleguide.getUpdatedAt());
}
System.out.println();
} catch (LaraException e) {
System.out.println("Error getting styleguide: " + e.getMessage() + "\n");
}
}
// Example 11: Translate with a styleguide
if (styleguideId != null) {
System.out.println("=== Translate with Styleguide ===");
try {
TranslateOptions options = new TranslateOptions()
.setStyleguideId(styleguideId);
TextResult result = lara.translate(
"Our team is excited to announce that the new feature is now available for all users.",
"en-US", "it-IT", options
);
System.out.println("Original: Our team is excited to announce that the new feature is now available for all users.");
System.out.println("Italian (with styleguide): " + result.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error translating with styleguide: " + e.getMessage() + "\n");
}
}
// Example 12: Translate with styleguide reasoning
if (styleguideId != null) {
System.out.println("=== Translate with Styleguide Reasoning ===");
try {
TranslateOptions options = new TranslateOptions()
.setStyleguideId(styleguideId)
.setStyleguideReasoning(true)
.setStyleguideExplanationLanguage("en-US");
TextResult result = lara.translate(
"Please submit the required documentation before the deadline.",
"en-US", "it-IT", options
);
System.out.println("Original: Please submit the required documentation before the deadline.");
System.out.println("Italian (with styleguide): " + result.getTranslation());
StyleguideResults sgResults = result.getStyleguideResults();
if (sgResults != null) {
System.out.println("Original translation (before styleguide): " + sgResults.getOriginalTranslation());
List<StyleguideChange> changes = sgResults.getChanges();
if (changes != null && !changes.isEmpty()) {
System.out.println("Changes applied: " + changes.size());
for (StyleguideChange change : changes) {
System.out.println(" Change ID: " + change.getId());
System.out.println(" Before: " + change.getOriginalTranslation());
System.out.println(" After: " + change.getRefinedTranslation());
System.out.println(" Why: " + change.getExplanation());
}
} else {
System.out.println("No changes were needed — translation already matches the styleguide.");
}
}
System.out.println();
} catch (LaraException e) {
System.out.println("Error with styleguide reasoning: " + e.getMessage() + "\n");
}
}
// Example 13: Get available languages
System.out.println("=== Available Languages ===");
try {
List<String> languages = lara.getLanguages();
System.out.print("Supported languages: [" + languages + "]");
} catch (LaraException e) {
System.out.println("Error getting languages: " + e.getMessage());
return;
}
// Example 14: Detect language of a given text
System.out.println("=== Language Detection ===");
try {
DetectResult detectResult = lara.detect("Hola, ¿cómo estás?");
System.out.println("Text: Hola, ¿cómo estás?");
System.out.println("Detected Language: " + detectResult.getLanguage());
} catch (LaraException e) {
System.out.println("Error detecting language: " + e.getMessage());
return;
}
// Example 15: Detect languages with hint and passlist
System.out.println("=== Language Detection with Hint and Passlist ===");
try {
DetectResult detectResult = lara.detect("Hola, ¿cómo estás?", "es", new String[]{"es", "pt", "it"});
System.out.println("Text: Hola, ¿cómo estás?");
System.out.println("Detected Language: " + detectResult.getLanguage());
} catch (LaraException e) {
System.out.println("Error detecting language with hint/passlist: " + e.getMessage());
return;
}
// Example 16: Quality estimation for a single sentence pair
System.out.println("=== Quality Estimation: single sentence ===");
try {
QualityEstimationResult qeSingle = lara.qualityEstimation(
"en-US", "it-IT",
"Hello, how are you today?",
"Ciao, come stai oggi?"
);
System.out.println("Score: " + qeSingle.getScore() + "\n");
} catch (LaraException e) {
System.out.println("Error in quality estimation (single): " + e.getMessage() + "\n");
return;
}
// Example 17: Quality estimation for a batch of sentence pairs
System.out.println("=== Quality Estimation: batch ===");
try {
List<QualityEstimationResult> qeBatch = lara.qualityEstimation(
"en-US", "it-IT",
Arrays.asList("Good morning.", "The weather is nice."),
Arrays.asList("Buongiorno.", "Il tempo è bello.")
);
System.out.println("Scores: " + qeBatch.stream().map(r -> Double.toString(r.getScore())).reduce((a, b) -> a + ", " + b).orElse("") + "\n");
} catch (LaraException e) {
System.out.println("Error in quality estimation (batch): " + e.getMessage() + "\n");
return;
}
// Example 18: Translation with reasoning (streaming)
System.out.println("=== Translation with Reasoning ===");
try {
TranslateOptions reasoningOptions = new TranslateOptions()
.setReasoning(true);
System.out.println("Original: Wonderful cavernous interior in a central but quiet and private area!");
System.out.println("Streaming partial results:");
Consumer<TextResult> streamingCallback = partialResult -> {
System.out.println("Partial result: " + partialResult.getTranslation());
};
TextResult finalResult = lara.translate("Wonderful cavernous interior in a central but quiet and private area!", "en-US", "it-IT", reasoningOptions, streamingCallback);
System.out.println("Final result: " + finalResult.getTranslation() + "\n");
} catch (LaraException e) {
System.out.println("Error with reasoning translation: " + e.getMessage() + "\n");
return;
}
}
}