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
- 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'import com.translated.lara.Credentials;
import com.translated.lara.translator.Translator;
import com.translated.lara.translator.TextResult;
import com.translated.lara.errors.LaraException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class Example {
public static void main(String[] args) {
// Set your credentials using environment variables (recommended)
Credentials credentials = new Credentials(
System.getenv("LARA_ACCESS_KEY_ID"),
System.getenv("LARA_ACCESS_KEY_SECRET")
);
// Create translator instance
Translator lara = new Translator(credentials);
try {
// Simple text translation
TextResult result = lara.translate("Hello, world!", "en-US", "fr-FR");
System.out.println("Translation: " + result.getTranslation());
// Output: Translation: Bonjour, le monde !
} catch (LaraException e) {
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
- 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
- Glossary terms count
- Import status checking
cd examples
javac -cp ../target/classes:../target/dependency/* GlossariesManagement.java
java -cp .:../target/classes:../target/dependency/* GlossariesManagementThe SDK supports authentication via access key and secret:
Credentials credentials = new Credentials("your-access-key-id", "your-access-key-secret");
Translator lara = new Translator(credentials);Environment Variables (Recommended):
export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"Credentials credentials = new Credentials(
System.getenv("LARA_ACCESS_KEY_ID"),
System.getenv("LARA_ACCESS_KEY_SECRET")
);// Create translator with credentials
Translator lara = new Translator(credentials);// Basic translation
TextResult result = lara.translate("Hello", "en-US", "fr-FR");
// Multiple strings
String[] texts = {"Hello", "World"};
TextResult result = lara.translate(texts, "en-US", "fr-FR");
// TextBlocks (mixed translatable/non-translatable content)
TextBlock[] textBlocks = {
new TextBlock("Translatable text", true),
new TextBlock("<br>", false), // Non-translatable HTML
new TextBlock("More translatable text", true),
};
TextResult result = lara.translateBlocks(textBlocks, "en-US", "fr-FR");
// With advanced options
TranslateOptions options = new TranslateOptions()
.setInstructions("Formal tone")
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setStyle(TranslationStyle.FLUID)
.setTimeoutMs(10000L);
TextResult result = 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 pair
QualityEstimationResult single = lara.qualityEstimation(
"en-US",
"it-IT",
"Hello, how are you today?",
"Ciao, come stai oggi?"
);
System.out.println(single.getScore()); // e.g. 0.768
// Batch
List<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
TranslateOptions options = new TranslateOptions()
.setProfanitiesDetect(ProfanitiesDetect.SOURCE_TARGET)
.setProfanitiesHandling(ProfanitiesHandling.DETECT);
TextResult result = lara.translate("Don't be such a tool.", "en-US", "it-IT", options);
TextResult.ProfanitiesResult profanities = result.getProfanitiesResult();
// profanities.getTarget() β detection result for the translated text
// profanities.getSource() β detection result for the source text (only with SOURCE_TARGET)File inputFile = new File("/path/to/your/document.txt"); // Replace with actual file path
InputStream fileStream = lara.documents.translate(inputFile, "document.txt", "en-US", "fr-FR");
// With options
DocumentTranslateOptions options = new DocumentTranslateOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setStyle(TranslationStyle.FLUID)
.setNoTrace(false);
InputStream fileStream = lara.documents.translate(inputFile, "document.txt", "en-US", "fr-FR", options);//Optional: upload options
DocumentUploadOptions uploadOptions = new DocumentUploadOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setNoTrace(false);
Document document = lara.documents.upload(inputFile, "document.txt", "en-US", "fr-FR", uploadOptions);String status = lara.documents.status(document.getId());InputStream fileStream = lara.documents.download(document.getId());File inputFile = new File("/path/to/your/audio.mp3");
InputStream audioStream = lara.audio.translate(inputFile, "en-US", "fr-FR");
// With options
AudioUploadOptions options = new AudioUploadOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setStyle(TranslationStyle.FLUID)
.setNoTrace(false);
InputStream audioStream = lara.audio.translate(inputFile, "en-US", "fr-FR", options);AudioUploadOptions uploadOptions = new AudioUploadOptions()
.setAdaptTo("memory-id") // Replace with actual memory IDs
.setGlossaries("glossary-id") // Replace with actual glossary IDs
.setNoTrace(false);
Audio audio = lara.audio.upload(inputFile, "en-US", "fr-FR", uploadOptions);Audio status = lara.audio.status(audio.getId());InputStream audioStream = lara.audio.download(audio.getId());// Create memory
Memory memory = lara.memories.create("MyMemory");
// Create memory with external ID (MyMemory integration)
Memory memory = 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 memory
MemoryImport memoryImport = lara.memories.addTranslation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001");
// Add translation to multiple memories
List<String> memoryIds = Arrays.asList("mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"); // Replace with actual memory IDs
MemoryImport memoryImport = lara.memories.addTranslation(memoryIds, "en-US", "fr-FR", "Hello", "Bonjour", "greeting_002");
// Add with context
MemoryImport memoryImport = lara.memories.addTranslation(
"mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "tuid",
"sentenceBefore", "sentenceAfter"
);
// TMX import from file
File tmxFile = new File("/path/to/your/memory.tmx"); // Replace with actual TMX file path
MemoryImport memoryImport = lara.memories.importTmx("mem_1A2b3C4d5E6f7G8h9I0jKl", tmxFile);
// Delete translation
// Important: if you omit tuid, all entries that match the provided fields will be removed
MemoryImport deleteJob = lara.memories.deleteTranslation(
"mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", "greeting_001"
);
// Wait for import completion (timeout in MILLISECONDS)
MemoryImport completedImport = lara.memories.waitForImport(memoryImport, 300000L); // 5 minutes// Create glossary
Glossary glossary = lara.glossaries.create("MyGlossary");
// Import CSV from file
File csvFile = new File("/path/to/your/glossary.csv"); // Replace with actual CSV file path
GlossaryImport glossaryImport = lara.glossaries.importCsv("gls_1A2b3C4d5E6f7G8h9I0jKl", csvFile);
// Add (or replace) individual terms to glossary
List<Map<String, String>> terms = Arrays.asList(
Map.of("language", "fr-FR", "value", "Bonjour"),
Map.of("language", "es-ES", "value", "Hola")
);
Object addResult = lara.glossaries.addOrReplaceEntry("gls_1A2b3C4d5E6f7G8h9I0jKl", terms, null);
// Remove a specific term from glossary
Map<String, String> termToRemove = Map.of("language", "fr-FR", "value", "Bonjour");
Object removeResult = lara.glossaries.deleteEntry("gls_1A2b3C4d5E6f7G8h9I0jKl", termToRemove, null);
// Check import status
GlossaryImport importStatus = lara.glossaries.getImportStatus("gls_1A2b3C4d5E6f7G8h9I0jKl");
// Wait for import completion
GlossaryImport completedImport = lara.glossaries.waitForImport(glossaryImport, 300000L); // 5 minutes
// Export glossary
String csvData = lara.glossaries.export("gls_1A2b3C4d5E6f7G8h9I0jKl", Glossary.Type.CSV_TABLE_UNI, "en-US");
// Get glossary terms count
GlossaryCounts counts = lara.glossaries.counts("gls_1A2b3C4d5E6f7G8h9I0jKl");Styleguides let you apply custom translation style rules. They can be listed and retrieved through the SDK.
// List all styleguides
List<Styleguide> styleguides = lara.styleguides.list();
// Get a specific styleguide by ID
Styleguide styleguide = lara.styleguides.get("stg_1A2b3C4d5E6f7G8h9I0jKl");TranslateOptions options = new TranslateOptions()
.setStyleguideId("stg_1A2b3C4d5E6f7G8h9I0jKl"); // Replace with actual styleguide ID
TextResult result = lara.translate("Hello, world!", "en-US", "it-IT", options);Enable reasoning to see what the styleguide changed and why:
TranslateOptions options = new TranslateOptions()
.setStyleguideId("stg_1A2b3C4d5E6f7G8h9I0jKl")
.setStyleguideReasoning(true)
.setStyleguideExplanationLanguage("en-US");
TextResult result = lara.translate("Hello, world!", "en-US", "it-IT", options);
StyleguideResults sgResults = result.getStyleguideResults();
if (sgResults != null) {
System.out.println("Original translation: " + sgResults.getOriginalTranslation());
for (StyleguideChange change : sgResults.getChanges()) {
System.out.println("Before: " + change.getOriginalTranslation());
System.out.println("After: " + change.getRefinedTranslation());
System.out.println("Why: " + change.getExplanation());
}
}public class TranslateOptions {
setAdaptTo(String... memoryIds) // Memory IDs to adapt to
setGlossaries(String... glossaryIds) // Glossary IDs to use
setInstructions(String... instructions) // Translation instructions
setStyle(TranslationStyle style) // Translation style (FLUID, FAITHFUL, CREATIVE)
setContentType(String contentType) // Content type (text/plain, text/html, etc.)
setMultiline(Boolean multiline) // Enable multiline translation
setTimeoutMs(Long timeoutMs) // Request timeout in milliseconds
setSourceHint(String sourceHint) // Hint for source language detection
setNoTrace(Boolean noTrace) // Disable request tracing
setVerbose(Boolean verbose) // Enable verbose response
setProfanitiesDetect(ProfanitiesDetect d) // Detect profanities in: TARGET or SOURCE_TARGET
setProfanitiesHandling(ProfanitiesHandling h) // How to handle detected profanities: DETECT, HIDE, or AVOID
setStyleguideId(String id) // Styleguide ID to apply
setStyleguideReasoning(boolean enabled) // Enable styleguide change reasoning
setStyleguideExplanationLanguage(String lang) // 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)
TextResult result = lara.translate("Hello", "en-US", "fr-FR");
// Simple language codes
TextResult result = 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 {
TextResult result = lara.translate("Hello", "en-US", "fr-FR");
System.out.println("Translation: " + result.getTranslation());
} catch (LaraApiException e) {
System.err.println("API Error [" + e.getStatusCode() + "]: " + e.getMessage());
System.err.println("Error type: " + e.getType());
} catch (LaraException e) {
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 example
cd 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! πβ¨