Skip to content

translated/lara-swift

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Lara Swift SDK

Swift Version License

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.

🌍 Features:

  • Text Translation: Single strings, multiple strings, and complex text blocks
  • Document Translation: Word, PDF, and other document formats with status monitoring
  • Translation Memory: Store and reuse translations for consistency
  • Glossaries: Enforce terminology standards across translations
  • Language Detection: Automatic source language identification
  • Advanced Options: Translation instructions and more

πŸ“š Documentation

Lara's SDK full documentation is available at https://developers.laratranslate.com/

πŸš€ Quick Start

Installation

Add the dependency to your Package.swift:

dependencies: [
    .package(url: "https://github.com/translated/lara-swift.git", from: "1.0.0")
]

Basic Usage

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 !
}

πŸ“– Examples

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

  • 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
    • Get available languages
cd examples
swift run text_translation.swift

Document Translation

  • 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

Translation Memory Management

  • 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

Glossary Management

  • glossaries_management.swift - Glossary management examples
    • Create, list, update, delete glossaries
    • CSV import with status monitoring
    • Glossary export
    • Glossary terms count
    • Import status checking
cd examples
swift run glossaries_management.swift

πŸ”§ API Reference

Core Components

πŸ” Authentication

The 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"]!
)

🌍 Translator

// Create translator with credentials
let lara = Translator(credentials: credentials)

Text Translation

// 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)

πŸ“– Document Translation

Simple document translation

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
)

Document translation with status monitoring

Document upload

//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
)

Document translation status monitoring

let status = try await lara.documents.status(id: documentId)

Download translated document

let downloadedData = try await lara.documents.download(id: documentId)

🧠 Memory Management

// 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"
)

πŸ“š Glossary Management

// 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)

// 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")

Translation Options

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
)

Language Codes

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")

🌐 Supported Languages

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: ", "))")

βš™οΈ Configuration

Error Handling

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)")
}

πŸ“‹ Requirements

  • Swift 5.5 or higher
  • iOS 13.0+, macOS 10.15+, or other supported platforms
  • Valid Lara API credentials

πŸ§ͺ Testing

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

πŸ—οΈ Building from Source

# Clone the repository
git clone https://github.com/translated/lara-swift.git
cd lara-swift

# Build with Swift Package Manager
swift build

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Happy translating! 🌍✨

About

Lara Swift Library

Resources

License

Stars

Watchers

Forks

Packages

No packages published