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
- Image Translation: Translate images or text within images
- Audio Translation: MP3, WAV, and other audio formats 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 and more
Lara's SDK full documentation is available at https://developers.laratranslate.com/
Add the dependency to your Package.swift:
dependencies: [
.package(url: "https://github.com/translated/lara-swift.git", from: "1.0.0")
]import Lara
// Set your credentials using environment variables (recommended)
let credentials = Credentials(
accessKeyId: ProcessInfo.processInfo.environment["LARA_ACCESS_KEY_ID"]!,
accessKeySecret: ProcessInfo.processInfo.environment["LARA_ACCESS_KEY_SECRET"]!
)
// Create translator instance
let lara = Translator(credentials: credentials)
// Simple text translation
let translation = try await lara.translate(text: "Hello, world!", source: "en", target: "fr")
if let translations = try? translation.translation.getTranslations() {
print("Translation: \(translations.first ?? "No translation")")
// Output: Translation: Bonjour, le monde !
}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"- text_translation.swift - 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
- Language Detection
cd examples
swift run text_translation.swift- document_translation.swift - Document translation examples
- Basic document translation
- Advanced options with memories and glossaries
- Step-by-step translation with status monitoring
cd examples
swift run document_translation.swift- image_translation.swift - Complete image translation examples
- Basic image translation with text overlay
- Advanced options with memories, glossaries, and inpainting
- Extract and translate text from images
cd examples
swift run image_translation.swift- audio_translation.swift - Audio translation examples
- Basic audio translation
- Advanced options with memories and glossaries
- Step-by-step translation with status monitoring
cd examples
swift run audio_translation.swift- memories_management.swift - 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
swift run memories_management.swift- glossaries_management.swift - Glossary management examples
- Create, list, update, delete glossaries
- Individual term management (add/remove terms)
- CSV import with status monitoring
- Glossary export
- Glossary terms count
- Import status checking
cd examples
swift run glossaries_management.swiftThe SDK supports authentication via access key and secret:
import Lara
let credentials = Credentials(accessKeyId: "your-access-key-id", accessKeySecret: "your-access-key-secret")
let lara = Translator(credentials: credentials)Environment Variables (Recommended):
export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"import Lara
let credentials = Credentials(
accessKeyId: ProcessInfo.processInfo.environment["LARA_ACCESS_KEY_ID"]!,
accessKeySecret: ProcessInfo.processInfo.environment["LARA_ACCESS_KEY_SECRET"]!
)// Create translator with credentials
let lara = Translator(credentials: credentials)// Basic translation
let translation = try await lara.translate(text: "Hello", source: "en", target: "fr")
// Multiple strings
let texts = ["Hello", "World"]
let translations = try await lara.translate(text: texts, source: "en", target: "fr")
// TextBlocks (mixed translatable/non-translatable content)
let textBlocks = [
TextBlock(text: "Translatable text", translatable: true),
TextBlock(text: "<br>", translatable: false), // Non-translatable HTML
TextBlock(text: "More translatable text", translatable: true)
]
let textBlockTranslations = try await lara.translate(text: textBlocks, source: "en", target: "fr")
// With advanced options
let options = TranslateOptions(
instructions: ["Formal tone"],
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
style: .fluid,
timeoutMs: 10000
)
let advancedTranslation = try await lara.translate(text: "Hello", source: "en", target: "fr", options: 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 arrays to get one result per pair.
// Single pair
let single = try await lara.qualityEstimation(
source: "en-US",
target: "it-IT",
sentence: "Hello, how are you today?",
translation: "Ciao, come stai oggi?"
)
print(single.score) // e.g. 0.768
// Batch
let batch = try await lara.qualityEstimation(
source: "en-US",
target: "it-IT",
sentence: ["Good morning.", "The weather is nice."],
translation: ["Buongiorno.", "Il tempo Γ¨ bello."]
)
print(batch.map(\.score)) // e.g. [0.751, 0.713]import Foundation
// Replace with your actual file path
let fileURL = URL(fileURLWithPath: "/path/to/your/document.txt")
let fileData = try Data(contentsOf: fileURL)
let translatedData = try await lara.documents.translate(
data: fileData,
filename: "document.txt",
source: "en",
target: "fr"
)
// With options
let options = DocumentTranslateOptions(
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
style: .fluid
)
let translatedDataWithOptions = try await lara.documents.translate(
data: fileData,
filename: "document.txt",
source: "en",
target: "fr",
options: options
)//Optional: upload options
let uploadOptions = DocumentUploadOptions(
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
noTrace: true,
style: .fluid
)
let document = try await lara.documents.upload(
data: fileData,
filename: "document.txt",
source: "en",
target: "fr",
options: uploadOptions
)let status = try await lara.documents.status(id: documentId)let downloadedData = try await lara.documents.download(id: documentId)import Foundation
// Load image data
let imageURL = URL(fileURLWithPath: "/path/to/your/image.jpg")
let imageData = try Data(contentsOf: imageURL)
// Create MultipartFile
let file = MultipartFile(filename: "image.jpg", data: imageData)
// Basic image translation
let translatedImageData = try await lara.images.translate(
file: file,
source: "en",
target: "fr",
options: ImageTranslationOptions(textRemoval: .overlay)
)
// Extract and translate text from image
let textResults = try await lara.images.translateText(
file: file,
source: "en",
target: "fr",
options: ImageTextTranslationOptions(
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Memory IDs
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"] // Glossary IDs
)
)import Foundation
// Replace with your actual file path
let fileURL = URL(fileURLWithPath: "/path/to/your/audio.mp3")
let fileData = try Data(contentsOf: fileURL)
let translatedData = try await lara.audio.translate(
data: fileData,
filename: "audio.mp3",
source: "en",
target: "fr"
)
// With options
let options = AudioUploadOptions(
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
style: .fluid
)
let translatedDataWithOptions = try await lara.audio.translate(
data: fileData,
filename: "audio.mp3",
source: "en",
target: "fr",
options: options
)//Optional: upload options
let uploadOptions = AudioUploadOptions(
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual memory IDs
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Replace with actual glossary IDs
noTrace: true,
style: .fluid
)
let audio = try await lara.audio.upload(
data: fileData,
filename: "audio.mp3",
source: "en",
target: "fr",
options: uploadOptions
)let status = try await lara.audio.status(id: audioId)let downloadedData = try await lara.audio.download(id: audioId)// Create memory
let memory = try await lara.memories.create(name: "MyMemory")
// Create memory with external ID (MyMemory integration)
let memoryWithExternalId = try await lara.memories.create(name: "Memory from MyMemory", externalId: "aabb1122")
// 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
let memoryImport = try await lara.memories.addTranslation(
id: "mem_1A2b3C4d5E6f7G8h9I0jKl",
source: "en",
target: "fr",
sentence: "Hello",
translation: "Bonjour",
tuid: "greeting_001"
)
// Add translation to multiple memories
let memoryIds = ["mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"]
let bulkMemoryImport = try await lara.memories.addTranslation(
ids: memoryIds,
source: "en",
target: "fr",
sentence: "Hello",
translation: "Bonjour",
tuid: "greeting_002"
)
// Add with context
let memoryImportWithContext = try await lara.memories.addTranslation(
id: "mem_1A2b3C4d5E6f7G8h9I0jKl",
source: "en",
target: "fr",
sentence: "Hello",
translation: "Bonjour",
tuid: "tuid",
sentenceBefore: "sentenceBefore",
sentenceAfter: "sentenceAfter"
)
// TMX import from file URL
let tmxFileURL = URL(fileURLWithPath: "/path/to/your/memory.tmx")
let tmxData = try Data(contentsOf: tmxFileURL)
let tmxImport = try await lara.memories.importTmx(id: "mem_1A2b3C4d5E6f7G8h9I0jKl", tmx: tmxData)
// Wait for import completion (timeout in SECONDS)
let completedImport = try await lara.memories.waitForImport(tmxImport, maxWaitTime: 300) // 5 minutes
// Delete translation
// Important: if you omit tuid, all entries that match the provided fields will be removed
let deleteResult = try await lara.memories.deleteTranslation(
id: "mem_1A2b3C4d5E6f7G8h9I0jKl",
source: "en",
target: "fr",
sentence: "Hello",
translation: "Bonjour",
tuid: "greeting_001"
)// Create glossary
let glossary = try await lara.glossaries.create(name: "MyGlossary")
// Import CSV from file URL
let csvFileURL = URL(fileURLWithPath: "/path/to/your/glossary.csv")
let csvData = try Data(contentsOf: csvFileURL)
let glossaryImport = try await lara.glossaries.importCsv(id: "gls_1A2b3C4d5E6f7G8h9I0jKl", csv: csvData)
// Add (or replace) individual terms to glossary
let terms = [
["language": "fr-FR", "value": "Bonjour"],
["language": "es-ES", "value": "Hola"]
]
_ = try await lara.glossaries.addOrReplaceEntry(glossaryId: "gls_1A2b3C4d5E6f7G8h9I0jKl", terms: terms, guid: nil)
// Remove a specific term from glossary
let termToRemove = ["language": "fr-FR", "value": "Bonjour"]
_ = try await lara.glossaries.deleteEntry(glossaryId: "gls_1A2b3C4d5E6f7G8h9I0jKl", term: termToRemove, guid: nil)
// Check import status
let importStatus = try await lara.glossaries.getImportStatus(id: "gls_1A2b3C4d5E6f7G8h9I0jKl")
// Wait for import completion
let completedGlossaryImport = try await lara.glossaries.waitForImport(glossaryImport, maxWaitTime: 300) // 5 minutes
// Export glossary
let csvExport = try await lara.glossaries.export(id: "gls_1A2b3C4d5E6f7G8h9I0jKl", source: "en")
// Get glossary terms count
let termCounts = try await lara.glossaries.counts(id: "gls_1A2b3C4d5E6f7G8h9I0jKl")Styleguides let you apply custom translation style rules. They can be listed and retrieved through the SDK.
// List all styleguides
let styleguides = try await lara.styleguides.list()
// Get a specific styleguide by ID
let styleguide = try await lara.styleguides.get(id: "stg_1A2b3C4d5E6f7G8h9I0jKl")let options = TranslateOptions(styleguideId: "stg_1A2b3C4d5E6f7G8h9I0jKl") // Replace with actual styleguide ID
let result = try await lara.translate(text: "Hello, world!", source: "en-US", target: "it-IT", options: options)Enable reasoning to see what the styleguide changed and why:
let options = TranslateOptions(
styleguideId: "stg_1A2b3C4d5E6f7G8h9I0jKl",
styleguideReasoning: true,
styleguideExplanationLanguage: "en-US"
)
let result = try await lara.translate(text: "Hello, world!", source: "en-US", target: "it-IT", options: options)
if let sgResults = result.styleguideResults {
if let origTranslation = try? sgResults.originalTranslation.getTranslation() {
print("Original translation: \(origTranslation)")
}
for change in sgResults.changes {
print("Before: \(change.originalTranslation)")
print("After: \(change.refinedTranslation)")
print("Why: \(change.explanation)")
}
}let options = TranslateOptions(
adaptTo: ["mem_1A2b3C4d5E6f7G8h9I0jKl"], // Memory IDs to adapt to
glossaries: ["gls_1A2b3C4d5E6f7G8h9I0jKl"], // Glossary IDs to use
instructions: ["instruction"], // Translation instructions
style: .fluid, // Translation style (.fluid, .faithful, .creative)
contentType: "text/plain", // Content type (text/plain, text/html, etc.)
multiline: true, // Enable multiline translation
timeoutMs: 10000, // Request timeout in milliseconds
noTrace: false, // Disable request tracing
verbose: false, // Enable verbose response
profanitiesDetect: .target, // Detect profanities in: .target or .sourceTarget
profanitiesHandling: .detect // How to handle profanities: .detect, .hide, or .avoid
styleguideId: "stg_id", // Styleguide ID to apply
styleguideReasoning: true, // Enable styleguide change reasoning
styleguideExplanationLanguage: "en-US" // Language for change explanations
)Use profanitiesDetect and profanitiesHandling together to control how profanities are detected and handled.
.targetβ detect profanities in the translated text only.sourceTargetβ detect in both source and target text.detectβ report profanities without modifying the translation.hideβ replace detected profanities with asterisks (default when detect is set).avoidβ instruct the model not to generate profanities
let options = TranslateOptions(
profanitiesDetect: .sourceTarget,
profanitiesHandling: .detect
)
let result = try await lara.translate(text: "Don't be such a tool.", source: "en-US", target: "it-IT", options: options)
let profanities = result.profanities
// profanities?.target β detection result for the translated text
// profanities?.source β detection result for the source text (only with .sourceTarget)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)
let translation = try await lara.translate(text: "Hello", source: "en-US", target: "fr-FR")
// Simple language codes
let translation2 = try await lara.translate(text: "Hello", source: "en", target: "fr")The SDK supports all languages available in the Lara API. Use the getLanguages() method to get the current list:
let languages = try await lara.getLanguages()
print("Supported languages: \(languages.joined(separator: ", "))")The SDK provides detailed error information:
do {
let translation = try await lara.translate(text: "Hello", source: "en", target: "fr")
if let translations = try? translation.translation.getTranslations() {
print("Translation: \(translations.first ?? "No translation")")
}
} catch let error as NSError where error.domain == "LaraApiError" {
print("API Error [\(error.code)]: \(error.localizedDescription)")
print("Error type: \(error.userInfo["type"] ?? "Unknown")")
} catch {
print("SDK Error: \(error.localizedDescription)")
}- Swift 5.5 or higher
- iOS 15.0+, macOS 10.15+, or other supported platforms
- 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"# Run basic text translation example
cd examples
swift run text_translation.swift# Clone the repository
git clone https://github.com/translated/lara-swift.git
cd lara-swift
# Build with Swift Package Manager
swift buildThis project is licensed under the MIT License - see the LICENSE file for details.
Happy translating! πβ¨