This SDK empowers you to build your own branded translation AI leveraging our translation fine-tuned language model.
All major translation features are accessible, making it easy to integrate and customize for your needs.
- Text Translation: Single strings, multiple strings, and complex text blocks
- Document Translation: Word, PDF, and other document formats with status monitoring
- Audio Translation: Audio files with status monitoring
- Translation Memory: Store and reuse translations for consistency, with async import/export
- Glossaries: Enforce terminology standards across translations
- Styleguides: Apply custom translation style rules with detailed change reasoning
- Language Detection: Automatic source language identification
- Profanity Detection & Handling: Detect profanities in source and/or target text, and hide or avoid them in translation
- Advanced Options: Translation instructions, reasoning, and more
Lara's SDK full documentation is available at https://developers.laratranslate.com/
Add the dependency to your pom.xml:
<dependency>
<groupId>com.translated.lara</groupId>
<artifactId>lara-sdk</artifactId>
<version>1.4.2</version>
</dependency>Or for Gradle, add to your build.gradle:
implementation 'com.translated.lara:lara-sdk:1.4.2'importcom.translated.lara.Credentials;
importcom.translated.lara.translator.Translator;
importcom.translated.lara.translator.TextResult;
importcom.translated.lara.errors.LaraException;
importjava.util.Arrays;
importjava.util.List;
importjava.util.Map;
publicclassExample {
publicstaticvoidmain(String[] args) {
// Set your credentials using environment variables (recommended)Credentialscredentials = newCredentials(
System.getenv("LARA_ACCESS_KEY_ID"),
System.getenv("LARA_ACCESS_KEY_SECRET")
);
// Create translator instanceTranslatorlara = newTranslator(credentials);
try {
// Simple text translationTextResultresult = lara.translate("Hello, world!", "en-US", "fr-FR");
System.out.println("Translation: " + result.getTranslation());
// Output: Translation: Bonjour, le monde !
} catch (LaraExceptione) {
System.err.println("Translation error: " + e.getMessage());
}
}
}The examples/ directory contains comprehensive examples for all SDK features.
All examples use environment variables for credentials, so set them first:
export LARA_ACCESS_KEY_ID="your-access-key-id"export LARA_ACCESS_KEY_SECRET="your-access-key-secret"- TextTranslation.java - Complete text translation examples
- Single string translation
- Multiple strings translation
- Translation with instructions
- TextBlocks translation (mixed translatable/non-translatable content)
- Auto-detect source language
- Advanced translation options
- Profanity detection and handling
- Translation with styleguides
- Get available languages
- Detect language
cd examples
javac -cp ../target/classes:../target/dependency/* TextTranslation.java
java -cp .:../target/classes:../target/dependency/* TextTranslation- DocumentTranslation.java - Document translation examples
- Basic document translation
- Advanced options with memories and glossaries
- Step-by-step translation with status monitoring
cd examples
javac -cp ../target/classes:../target/dependency/* DocumentTranslation.java
java -cp .:../target/classes:../target/dependency/* DocumentTranslation- AudioTranslation.java - Audio translation examples
- Basic audio translation
- Advanced options with memories and glossaries
- Step-by-step translation with status monitoring
cd examples
javac -cp ../target/classes:../target/dependency/* AudioTranslation.java
java -cp .:../target/classes:../target/dependency/* AudioTranslation- MemoriesManagement.java - Memory management examples
- Create, list, update, delete memories
- Add individual translations
- Multiple memory operations
- TMX file import with progress monitoring
- Async TMX import with callback URL
- Async memory export with callback URL
- Translation deletion
- Translation with TUID and context
cd examples
javac -cp ../target/classes:../target/dependency/* MemoriesManagement.java
java -cp .:../target/classes:../target/dependency/* MemoriesManagement- GlossariesManagement.java - Glossary management examples
- Create, list, update, delete glossaries
- CSV import with status monitoring
- Glossary export (sync and async)
- Glossary terms count
- Import status checking
cd examples
javac -cp ../target/classes:../target/dependency/* GlossariesManagement.java
java -cp .:../target/classes:../target/dependency/* GlossariesManagement- StyleguidesManagement.java - Styleguide CRUD examples
- Create, list, get, update, delete styleguides
cd examples
export LARA_ACCESS_KEY_ID="your-access-key-id"export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
javac -cp ../target/classes:../target/dependency/* StyleguidesManagement.java
java -cp .:../target/classes:../target/dependency/* StyleguidesManagementThe SDK supports authentication via access key and secret:
Credentialscredentials = newCredentials("your-access-key-id", "your-access-key-secret");
Translatorlara = newTranslator(credentials);Environment Variables (Recommended):
export LARA_ACCESS_KEY_ID="your-access-key-id"export LARA_ACCESS_KEY_SECRET="your-access-key-secret"Credentialscredentials = newCredentials(
System.getenv("LARA_ACCESS_KEY_ID"),
System.getenv("LARA_ACCESS_KEY_SECRET")
);// Create translator with credentialsTranslatorlara = newTranslator(credentials);// Basic translationTextResultresult = lara.translate("Hello", "en-US", "fr-FR");
// Multiple stringsString[] texts = {"Hello", "World"};
TextResultresult = lara.translate(texts, "en-US", "fr-FR");
// TextBlocks (mixed translatable/non-translatable content)TextBlock[] textBlocks = {
newTextBlock("Translatable text", true),
newTextBlock("<br>", false), // Non-translatable HTMLnewTextBlock("More translatable text", true),
};
TextResultresult = lara.translateBlocks(textBlocks, "en-US", "fr-FR");
// With advanced optionsTranslateOptionsoptions = newTranslateOptions()
.setInstructions("Formal tone")
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setStyle(TranslationStyle.FLUID)
.setTimeoutMs(10000L);
TextResultresult = lara.translate("Hello", "en-US", "fr-FR", options);Use qualityEstimation() to score how well a translation matches its source. Pass a single sentence/translation pair to get a single result, or two parallel lists to get one result per pair.
// Single pairQualityEstimationResultsingle = lara.qualityEstimation(
"en-US",
"it-IT",
"Hello, how are you today?",
"Ciao, come stai oggi?"
);
System.out.println(single.getScore()); // e.g. 0.768// BatchList<QualityEstimationResult> batch = lara.qualityEstimation(
"en-US",
"it-IT",
Arrays.asList("Good morning.", "The weather is nice."),
Arrays.asList("Buongiorno.", "Il tempo è bello.")
);
System.out.println(batch.stream().map(QualityEstimationResult::getScore).collect(java.util.stream.Collectors.toList())); // e.g. [0.751, 0.713]Use setProfanitiesDetect and setProfanitiesHandling together to control how profanities are detected and handled.
ProfanitiesDetect.TARGET— detect profanities in the translated text onlyProfanitiesDetect.SOURCE_TARGET— detect in both source and target textProfanitiesHandling.DETECT— report profanities without modifying the translationProfanitiesHandling.HIDE— replace detected profanities with asterisks (default when detect is set)ProfanitiesHandling.AVOID— instruct the model not to generate profanities
TranslateOptionsoptions = newTranslateOptions()
.setProfanitiesDetect(ProfanitiesDetect.SOURCE_TARGET)
.setProfanitiesHandling(ProfanitiesHandling.DETECT);
TextResultresult = lara.translate("Don't be such a tool.", "en-US", "it-IT", options);
TextResult.ProfanitiesResultprofanities = result.getProfanitiesResult();
// profanities.getTarget() — detection result for the translated text// profanities.getSource() — detection result for the source text (only with SOURCE_TARGET)FileinputFile = newFile("/path/to/your/document.txt"); // Replace with actual file pathInputStreamfileStream = lara.documents.translate(inputFile, "document.txt", "en-US", "fr-FR");
// With optionsDocumentTranslateOptionsoptions = newDocumentTranslateOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setStyle(TranslationStyle.FLUID)
.setNoTrace(false);
InputStreamfileStream = lara.documents.translate(inputFile, "document.txt", "en-US", "fr-FR", options);//Optional: upload optionsDocumentUploadOptionsuploadOptions = newDocumentUploadOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setNoTrace(false);
Documentdocument = lara.documents.upload(inputFile, "document.txt", "en-US", "fr-FR", uploadOptions);Stringstatus = lara.documents.status(document.getId());InputStreamfileStream = lara.documents.download(document.getId());Fileimage = newFile("/path/to/your/image.png"); // Replace with actual file path// Translate image and receive a translated image streamImageTranslateOptionsoptions = newImageTranslateOptions()
.setModel(ImageTranslationModel.INPAINTING)
.setStyle(TranslationStyle.FAITHFUL);
InputStreamtranslatedImageStream = lara.images.translate(image, "en", "fr", options);
// Extract and translate text blocks from an imageImageTextTranslateOptionstextOptions = newImageTextTranslateOptions()
.setAdaptTo("mem_1A2b3C4d5E6f7G8h9I0jKl") // Replace with actual memory IDs
.setGlossaries("gls_1A2b3C4d5E6f7G8h9I0jKl"); // Replace with actual glossary IDsImageTextResulttextBlocks = lara.images.translateText(image, "en", "fr", textOptions);FileinputFile = newFile("/path/to/your/audio.mp3");
InputStreamaudioStream = lara.audio.translate(inputFile, "en-US", "fr-FR");
// With optionsAudioUploadOptionsoptions = newAudioUploadOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setStyle(TranslationStyle.FLUID)
.setNoTrace(false);
InputStreamaudioStream = lara.audio.translate(inputFile, "en-US", "fr-FR", options);AudioUploadOptionsuploadOptions = newAudioUploadOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setNoTrace(false);
Audioaudio = lara.audio.upload(inputFile, "en-US", "fr-FR", uploadOptions);Audiostatus = lara.audio.status(audio.getId());InputStreamaudioStream = lara.audio.download(audio.getId());// Create memoryMemorymemory = lara.memories.create("MyMemory");
// Create memory with external ID (MyMemory integration)Memorymemory = lara.memories.create("Memory from MyMemory", "aabb1122"); // Replace with actual external ID// Important: To update/overwrite a translation unit you must provide a tuid. Calls without a tuid always create a new unit and will not update existing entries.// Add translation to single memoryMemoryImportmemoryImport = lara.memories.addTranslation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001");
// Add translation to multiple memoriesList<String> memoryIds = Arrays.asList("mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"); // Replace with actual memory IDsMemoryImportmemoryImport = lara.memories.addTranslation(memoryIds, "en-US", "fr-FR", "Hello", "Bonjour", "greeting_002");
// Add with contextMemoryImportmemoryImport = lara.memories.addTranslation(
"mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "tuid", "sentenceBefore", "sentenceAfter"
);
// TMX import from fileFiletmxFile = newFile("/path/to/your/memory.tmx"); // Replace with actual TMX file pathMemoryImportmemoryImport = lara.memories.importTmx("mem_1A2b3C4d5E6f7G8h9I0jKl", tmxFile);
// Delete translation// Important: if you omit tuid, all entries that match the provided fields will be removedMemoryImportdeleteJob = lara.memories.deleteTranslation(
"mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001"
);
// Wait for import completion (timeout in MILLISECONDS)MemoryImportcompletedImport = lara.memories.waitForImport(memoryImport, 300000L); // 5 minutes// TMX import with callback URL (async notification instead of polling)MemoryImportasyncImport = lara.memories.importTmx("mem_1A2b3C4d5E6f7G8h9I0jKl", tmxFile, "https://your-server.example.com/callback");
// Async memory export — result delivered to callback URLMemoryExportexportJob = lara.memories.exportAsync("mem_1A2b3C4d5E6f7G8h9I0jKl", "https://your-server.example.com/callback");
// Async export with specific formatMemoryExportexportTmxJob = lara.memories.exportAsync("mem_1A2b3C4d5E6f7G8h9I0jKl", "https://your-server.example.com/callback", Memory.ExportFormat.TMX);// Create glossaryGlossaryglossary = lara.glossaries.create("MyGlossary");
// Import CSV from fileFilecsvFile = newFile("/path/to/your/glossary.csv"); // Replace with actual CSV file pathGlossaryImportglossaryImport = lara.glossaries.importCsv("gls_1A2b3C4d5E6f7G8h9I0jKl", csvFile);
// Add (or replace) individual terms to glossaryList<Map<String, String>> terms = Arrays.asList(
Map.of("language", "fr-FR", "value", "Bonjour"),
Map.of("language", "es-ES", "value", "Hola")
);
ObjectaddResult = lara.glossaries.addOrReplaceEntry("gls_1A2b3C4d5E6f7G8h9I0jKl", terms, null);
// Remove a specific term from glossaryMap<String, String> termToRemove = Map.of("language", "fr-FR", "value", "Bonjour");
ObjectremoveResult = lara.glossaries.deleteEntry("gls_1A2b3C4d5E6f7G8h9I0jKl", termToRemove, null);
// Check import statusGlossaryImportimportStatus = lara.glossaries.getImportStatus("gls_1A2b3C4d5E6f7G8h9I0jKl");
// Wait for import completionGlossaryImportcompletedImport = lara.glossaries.waitForImport(glossaryImport, 300000L); // 5 minutes// Export glossaryStringcsvData = lara.glossaries.export("gls_1A2b3C4d5E6f7G8h9I0jKl", Glossary.Type.CSV_TABLE_UNI, "en-US");
// Async glossary export — returns a jobId; the result is delivered to your callback URL when readyGlossaryExportexportJob = lara.glossaries.exportAsync(
"gls_1A2b3C4d5E6f7G8h9I0jKl",
"https://your-server.example.com/lara/export-callback",
Glossary.Type.CSV_TABLE_UNI,
"en-US");
// Get glossary terms countGlossaryCountscounts = lara.glossaries.counts("gls_1A2b3C4d5E6f7G8h9I0jKl");Styleguides let you apply custom translation style rules. They can be created, listed, retrieved, updated, and deleted through the SDK.
// List all styleguidesList<Styleguide> styleguides = lara.styleguides.list();
// Get a specific styleguide by IDStyleguidestyleguide = lara.styleguides.get("stg_1A2b3C4d5E6f7G8h9I0jKl");
// Create a styleguideStyleguidecreated = lara.styleguides.create("Formal EN", "Use formal register. Avoid contractions.");
// Update: pass null for fields to leave unchangedStyleguiderenamed = lara.styleguides.update(created.getId(), "Formal EN v2");
StyleguidecontentUpdated = lara.styleguides.update(created.getId(), null, "Prefer active voice.");
Styleguideupdated = lara.styleguides.update(created.getId(), "Formal EN v3", "Prefer active voice.");
// Delete a styleguideStyleguidedeleted = lara.styleguides.delete(created.getId());TranslateOptionsoptions = newTranslateOptions()
.setStyleguideId("stg_1A2b3C4d5E6f7G8h9I0jKl"); // Replace with actual styleguide IDTextResultresult = lara.translate("Hello, world!", "en-US", "it-IT", options);Enable reasoning to see what the styleguide changed and why:
TranslateOptionsoptions = newTranslateOptions()
.setStyleguideId("stg_1A2b3C4d5E6f7G8h9I0jKl")
.setStyleguideReasoning(true)
.setStyleguideExplanationLanguage("en-US");
TextResultresult = lara.translate("Hello, world!", "en-US", "it-IT", options);
StyleguideResultssgResults = result.getStyleguideResults();
if (sgResults != null) {
System.out.println("Original translation: " + sgResults.getOriginalTranslation());
for (StyleguideChangechange : sgResults.getChanges()) {
System.out.println("Before: " + change.getOriginalTranslation());
System.out.println("After: " + change.getRefinedTranslation());
System.out.println("Why: " + change.getExplanation());
}
}publicclassTranslateOptions {
setAdaptTo(String... memoryIds) // Memory IDs to adapt tosetGlossaries(String... glossaryIds) // Glossary IDs to usesetInstructions(String... instructions) // Translation instructionssetStyle(TranslationStylestyle) // Translation style (FLUID, FAITHFUL, CREATIVE)setContentType(StringcontentType) // Content type (text/plain, text/html, etc.)setMultiline(Booleanmultiline) // Enable multiline translationsetTimeoutMs(LongtimeoutMs) // Request timeout in millisecondssetSourceHint(StringsourceHint) // Hint for source language detectionsetNoTrace(BooleannoTrace) // Disable request tracingsetVerbose(Booleanverbose) // Enable verbose responsesetProfanitiesDetect(ProfanitiesDetectd) // Detect profanities in: TARGET or SOURCE_TARGETsetProfanitiesHandling(ProfanitiesHandlingh) // How to handle detected profanities: DETECT, HIDE, or AVOIDsetStyleguideId(Stringid) // Styleguide ID to applysetStyleguideReasoning(booleanenabled) // Enable styleguide change reasoningsetStyleguideExplanationLanguage(Stringlang) // Language for change explanations
}The SDK supports full language codes (e.g., en-US, fr-FR, es-ES) as well as simple codes (e.g., en, fr, es):
// Full language codes (recommended)TextResultresult = lara.translate("Hello", "en-US", "fr-FR");
// Simple language codesTextResultresult = lara.translate("Hello", "en", "fr");The SDK supports all languages available in the Lara API. Use the getLanguages() method to get the current list:
List<String> languages = lara.getLanguages();
System.out.println("Supported languages: " + String.join(", ", languages));The SDK provides detailed error information:
try {
TextResultresult = lara.translate("Hello", "en-US", "fr-FR");
System.out.println("Translation: " + result.getTranslation());
} catch (LaraApiExceptione) {
System.err.println("API Error [" + e.getStatusCode() + "]: " + e.getMessage());
System.err.println("Error type: " + e.getType());
} catch (LaraExceptione) {
System.err.println("SDK Error: " + e.getMessage());
}- Java 8 or higher
- Maven or Gradle
- Valid Lara API credentials
Run the examples to test your setup:
# All examples use environment variables for credentials, so set them first:export LARA_ACCESS_KEY_ID="your-access-key-id"export LARA_ACCESS_KEY_SECRET="your-access-key-secret"# Build the project
mvn clean compile dependency:copy-dependencies
# Run basic text translation examplecd examples
javac -cp ../target/classes:../target/dependency/* TextTranslation.java
java -cp .:../target/classes:../target/dependency/* TextTranslation# Clone the repository
git clone https://github.com/translated/lara-java.git
cd lara-java
# Build with Maven
mvn clean installThis project is licensed under the MIT License - see the LICENSE file for details.
Happy translating! 🌍✨