Skip to content

Repository files navigation

Lara Python SDK

Python VersionLicense

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
  • Image Translation: Translate whole images or extract and translate text blocks
  • Audio Translation: Audio file translation with status monitoring
  • Audio Transcript Translation: Retrieve translated transcripts with per-segment timings
  • Translation Memory: Store and reuse translations for consistency
  • Glossaries: Enforce terminology standards across translations
  • Styleguides: Define tone, voice, and writing style rules for 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

pip install lara-sdk

Basic Usage

importosfromlara_sdkimportCredentials, Translator# Set your credentials using environment variables (recommended)credentials=Credentials(
os.environ.get('LARA_ACCESS_KEY_ID'),
os.environ.get('LARA_ACCESS_KEY_SECRET')
)
# Create translator instancelara=Translator(credentials)
# Simple text translationtry:
result=lara.translate("Hello, world!", target="fr-FR", source="en-US")
print(f"Translation: {result.translation}")
# Output: Translation: Bonjour, le monde !exceptExceptionaserror:
print(f"Translation error: {error}")

📖 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.py - 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
python text_translation.py

Document Translation

  • document_translation.py - Document translation examples
    • Basic document translation
    • Advanced options with memories and glossaries
    • Step-by-step translation with status monitoring
cd examples
python document_translation.py

Image Translation

  • image_translation.py - Image translation examples
    • Full image translation with overlay or inpainting
    • Text-only extraction and translation
    • Style, memories, and glossaries options
cd examples
python image_translation.py

Audio Translation

  • audio_translation.py - Audio translation examples
    • Basic audio translation
    • Advanced options with memories and glossaries
    • Step-by-step translation with status monitoring
cd examples
python audio_translation.py

Audio Transcript Translation

  • audio_transcript_translation.py - Audio transcript translation examples
    • Basic transcript translation
    • Advanced options with memories and glossaries
    • Step-by-step transcript translation with status monitoring
cd examples
python audio_transcript_translation.py

Translation Memory Management

  • memories_management.py - 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
python memories_management.py

Glossary Management

  • glossaries_management.py - 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
python glossaries_management.py

Styleguide Management

  • styleguides_management.py - Styleguide management examples
    • Create, list, get, update, delete styleguides
    • Update name, content, or both at once
    • Handling of non-existent styleguides
cd examples
python styleguides_management.py

Language Detection

  • language_detection.py - Language detection examples
    • Single string detection
    • Multiple strings detection
    • Detection with hint parameter
    • Detection with passlist to restrict languages
    • Combined hint and passlist
cd examples
python language_detection.py

🔧 API Reference

Core Components

🔐 Authentication

The SDK supports authentication via access key and secret:

fromlara_sdkimportCredentials, Translatorcredentials=Credentials("your-access-key-id", "your-access-key-secret")
lara=Translator(credentials)

Environment Variables (Recommended):

export LARA_ACCESS_KEY_ID="your-access-key-id"export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
importosfromlara_sdkimportCredentialscredentials=Credentials(
os.environ['LARA_ACCESS_KEY_ID'],
os.environ['LARA_ACCESS_KEY_SECRET']
)

Alternative Constructor:

# You can also pass credentials directly to Translatorlara=Translator(
access_key_id="your-access-key-id",
access_key_secret="your-access-key-secret"
)

🌍 Translator

# Create translator with credentialslara=Translator(credentials)

Text Translation

# Basic translationresult=lara.translate("Hello", target="fr-FR", source="en-US")
# Multiple stringsresult=lara.translate(["Hello", "World"], target="fr-FR", source="en-US")
# TextBlocks (mixed translatable/non-translatable content)fromlara_sdkimportTextBlocktext_blocks= [
TextBlock(text="Translatable text", translatable=True),
TextBlock(text="<br>", translatable=False), # Non-translatable HTMLTextBlock(text="More translatable text", translatable=True)
]
result=lara.translate(text_blocks, target="fr-FR", source="en-US")
# With advanced optionsresult=lara.translate(
"Hello",
target="fr-FR",
source="en-US",
instructions=["Formal tone"],
adapt_to=["memory-id"], # Replace with actual memory IDsglossaries=["glossary-id"], # Replace with actual glossary IDsstyle="fluid",
timeout_ms=10000
)

📖 Document Translation

Simple document translation

translated_content=lara.documents.translate(
file_path="/path/to/your/document.txt", # Replace with actual file pathfilename="document.txt",
source="en-US",
target="fr-FR"
)
# With optionstranslated_content=lara.documents.translate(
file_path="/path/to/your/document.txt", # Replace with actual file pathfilename="document.txt",
source="en-US",
target="fr-FR",
adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], # Replace with actual memory IDsglossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"], # Replace with actual glossary IDsstyle="fluid"
)

Document translation with status monitoring

Document upload

#Optional: upload optionsdocument=lara.documents.upload(
file_path="/path/to/your/document.txt", # Replace with actual file pathfilename="document.txt",
source="en-US",
target="fr-FR",
adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], # Replace with actual memory IDsglossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"] # Replace with actual glossary IDs
)

Document translation status monitoring

status=lara.documents.status(document.id)

Download translated document

translated_content=lara.documents.download(document.id)

🖼️ Image Translation

Simple image translation

translated_image=lara.images.translate(
source="en-US",
target="fr-FR",
image_path="/path/to/your/image.png", # Replace with actual file pathmodel="overlay"
)

Text-only image translation

text_results=lara.images.translate_text(
source="en-US",
target="es-ES",
image_path="/path/to/your/image.png"# Replace with actual file path
)

🎵 Audio Translation

Simple audio translation

audio_content=lara.audio.translate(
file_path="/path/to/your/audio.mp3", # Replace with actual file pathfilename="audio.mp3",
source="en-US",
target="fr-FR"
)
# With optionsaudio_content=lara.audio.translate(
file_path="/path/to/your/audio.mp3", # Replace with actual file pathfilename="audio.mp3",
source="en-US",
target="fr-FR",
adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], # Replace with actual memory IDsglossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"] # Replace with actual glossary IDs
)

Audio translation with status monitoring

Audio upload

# Optional: upload optionsaudio=lara.audio.upload(
file_path="/path/to/your/audio.mp3", # Replace with actual file pathfilename="audio.mp3",
source="en-US",
target="fr-FR",
adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], # Replace with actual memory IDsglossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"] # Replace with actual glossary IDs
)

Audio translation status monitoring

status=lara.audio.status(audio.id)

Download translated audio

audio_content=lara.audio.download(audio.id)

🎙️ Audio Transcript Translation

Simple transcript translation

result=lara.audio.translate_transcript(
file_path="/path/to/your/audio.mp3", # Replace with actual file pathfilename="audio.mp3",
source="en-US",
target="fr-FR"
)
# With optionsresult=lara.audio.translate_transcript(
file_path="/path/to/your/audio.mp3", # Replace with actual file pathfilename="audio.mp3",
source="en-US",
target="fr-FR",
adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], # Replace with actual memory IDsglossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"] # Replace with actual glossary IDs
)

Transcript translation with status monitoring

Upload for transcription

audio=lara.audio.upload_for_transcription(
file_path="/path/to/your/audio.mp3", # Replace with actual file pathfilename="audio.mp3",
source="en-US",
target="fr-FR"
)

Transcript status monitoring

status=lara.audio.status(audio.id)

Retrieve translated transcript

result=lara.audio.get_translated_transcript(audio.id)

🧠 Memory Management

# Create memorymemory=lara.memories.create("MyMemory")
# Create memory with external ID (MyMemory integration)memory=lara.memories.create("Memory from MyMemory", external_id="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 memorymemory_import=lara.memories.add_translation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001")
# Add translation to multiple memoriesmemory_import=lara.memories.add_translation(["mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"], "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_002")
# Add with contextmemory_import=lara.memories.add_translation(
"mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="tuid", sentence_before="sentenceBefore", sentence_after="sentenceAfter"
)
# TMX import from filememory_import=lara.memories.import_tmx("mem_1A2b3C4d5E6f7G8h9I0jKl", "/path/to/your/memory.tmx") # Replace with actual TMX file path# TMX import with gzip compressionmemory_import=lara.memories.import_tmx(
"mem_1A2b3C4d5E6f7G8h9I0jKl",
"/path/to/your/memory.tmx",
gzip=True
)
# TMX import with a callback URL (notified when the import completes)memory_import=lara.memories.import_tmx(
"mem_1A2b3C4d5E6f7G8h9I0jKl",
"/path/to/your/memory.tmx",
callback_url="https://your-server.example.com/lara/import-callback"
)
# TMX import with both gzip compression and a callback URLmemory_import=lara.memories.import_tmx(
"mem_1A2b3C4d5E6f7G8h9I0jKl",
"/path/to/your/memory.tmx",
gzip=True,
callback_url="https://your-server.example.com/lara/import-callback"
)
# Async memory export - returns a job_id; the result is delivered to your callback URL when readymemory_export=lara.memories.export_async(
"mem_1A2b3C4d5E6f7G8h9I0jKl",
callback_url="https://your-server.example.com/lara/export-callback",
format="tmx"# optional, defaults to the server-side default ("tmx" or "jtm")
)
job_id=memory_export.job_id# Delete translation# Important: if you omit tuid, all entries that match the provided fields will be removeddelete_job=lara.memories.delete_translation(
"mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001"
)
# Wait for import completioncompleted_import=lara.memories.wait_for_import(memory_import, max_wait_time=300) # 5 minutes

📚 Glossary Management

# Create glossaryglossary=lara.glossaries.create("MyGlossary")
# Import CSV from fileglossary_import=lara.glossaries.import_csv("gls_1A2b3C4d5E6f7G8h9I0jKl", "/path/to/your/glossary.csv") # Replace with actual CSV file path# Import CSV with a callback URL (async notification when the import completes)glossary_import=lara.glossaries.import_csv(
"gls_1A2b3C4d5E6f7G8h9I0jKl",
"/path/to/your/glossary.csv",
callback_url="https://your-server.example.com/lara/import-callback"
)
# Check import statusimport_status=lara.glossaries.get_import_status(import_id)
# Wait for import completioncompleted_import=lara.glossaries.wait_for_import(glossary_import, max_wait_time=300) # 5 minutes# Export glossarycsv_data=lara.glossaries.export("gls_1A2b3C4d5E6f7G8h9I0jKl", "csv/table-uni", "en-US")
# Async glossary export - returns a job_id; the result is delivered to your callback URL when readyglossary_export=lara.glossaries.export_async(
"gls_1A2b3C4d5E6f7G8h9I0jKl",
callback_url="https://your-server.example.com/lara/export-callback",
content_type="csv/table-uni",
source="en-US"
)
job_id=glossary_export.job_id# Get glossary terms countcounts=lara.glossaries.counts("gls_1A2b3C4d5E6f7G8h9I0jKl")

📋 Styleguide Management

# Create styleguidestyleguide=lara.styleguides.create("MyStyleguide", "Always use formal language.")
# List all styleguidesstyleguides=lara.styleguides.list()
# Get a specific styleguidestyleguide=lara.styleguides.get("stg_1A2b3C4d5E6f7G8h9I0jKl")
# Update styleguide — pass None for fields you don't want to change# Update only the namestyleguide=lara.styleguides.update("stg_1A2b3C4d5E6f7G8h9I0jKl", "UpdatedStyleguide")
# Update only the contentstyleguide=lara.styleguides.update("stg_1A2b3C4d5E6f7G8h9I0jKl", content="Always use informal language.")
# Update bothstyleguide=lara.styleguides.update("stg_1A2b3C4d5E6f7G8h9I0jKl", "UpdatedStyleguide", "Always use informal language.")
# Delete styleguidestyleguide=lara.styleguides.delete("stg_1A2b3C4d5E6f7G8h9I0jKl")

🌐 Language Detection

# Basic language detectionresult=lara.detect("Hello, world!")
print(f"Detected language: {result.language}")
print(f"Content type: {result.content_type}")
# Detect multiple stringsresult=lara.detect(["Hello", "Bonjour", "Hola"])
# Detection with hintresult=lara.detect("Hello", hint="en")
# Detection with passlist (restrict to specific languages)result=lara.detect(
"Guten Tag",
passlist=["de-DE", "en-US", "fr-FR"]
)
# Combined hint and passlistresult=lara.detect(
"Buongiorno",
hint="it",
passlist=["it-IT", "es-ES", "pt-PT"]
)

🎯 Quality Estimation

Use quality_estimation() 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 pairsingle=lara.quality_estimation(
source="en-US",
target="it-IT",
sentence="Hello, how are you today?",
translation="Ciao, come stai oggi?",
)
print(single.score) # e.g. 0.768# Batchbatch=lara.quality_estimation(
source="en-US",
target="it-IT",
sentence=["Good morning.", "The weather is nice."],
translation=["Buongiorno.", "Il tempo è bello."],
)
print([r.scoreforrinbatch]) # e.g. [0.751, 0.713]

Translation Options

result=lara.translate(
text,
target="fr-FR", # Target language (required)source="en-US", # Source language (optional, auto-detect if None)source_hint="en", # Hint for source language detectionadapt_to=["memory-id"], # Memory IDs to adapt toglossaries=["glossary-id"], # Glossary IDs to useinstructions=["instruction"], # Translation instructionsstyle="fluid", # Translation style (fluid, faithful, creative)content_type="text/plain", # Content type (text/plain, text/html, etc.)multiline=True, # Enable multiline translationtimeout_ms=10000, # Request timeout in millisecondsno_trace=False, # Disable request tracingverbose=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)result=lara.translate("Hello", target="fr-FR", source="en-US")
# Simple language codesresult=lara.translate("Hello", target="fr", source="en")

🌐 Supported Languages

The SDK supports all languages available in the Lara API. Use the languages() method to get the current list:

languages=lara.languages()
print(f"Supported languages: {', '.join(languages)}")

⚙️ Configuration

Error Handling

The SDK provides detailed error information:

fromlara_sdkimportLaraApiError, LaraErrortry:
result=lara.translate("Hello", target="fr-FR", source="en-US")
print(f"Translation: {result.translation}")
exceptLaraApiErroraserror:
print(f"API Error [{error.status_code}]: {error.message}")
print(f"Error type: {error.type}")
exceptLaraErroraserror:
print(f"SDK Error: {error}")
exceptExceptionaserror:
print(f"Unexpected error: {error}")

📋 Requirements

  • Python 3.8 or higher
  • pip
  • 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 examplecd examples
python text_translation.py

🏗️ Building from Source

# Clone the repository
git clone https://github.com/translated/lara-python.git
cd lara-python
# Install in development mode
pip install -e .

📄 License

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

Happy translating! 🌍✨

About

Official Lara SDK for Python

Resources

Stars

9 stars

Watchers

9 watching

Forks

Releases

Packages

Used by

Contributors

Languages