Metadata-Version: 2.4
Name: lara-sdk
Version: 1.15.1
Summary: A Python library for Lara's API.
Author-email: Translated <support@laratranslate.com>
Maintainer-email: Translated <support@laratranslate.com>
Project-URL: Homepage, https://laratranslate.com/
Project-URL: Source, https://github.com/translated/lara-python
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests
Dynamic: license-file

# Lara Python SDK

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](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
- **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/](https://developers.laratranslate.com/)

## 🚀 Quick Start

### Installation

```bash
pip install lara-sdk
```

### Basic Usage

```python
import os
from lara_sdk import Credentials, 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 instance
lara = Translator(credentials)

# Simple text translation
try:
  result = lara.translate("Hello, world!", target="fr-FR", source="en-US")
  print(f"Translation: {result.translation}")
  # Output: Translation: Bonjour, le monde !
except Exception as error:
  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:**
```bash
export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
```

### Text Translation
- **[text_translation.py](examples/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

```bash
cd examples
python text_translation.py
```

### Document Translation
- **[document_translation.py](examples/document_translation.py)** - Document translation examples
  - Basic document translation
  - Advanced options with memories and glossaries
  - Step-by-step translation with status monitoring

```bash
cd examples
python document_translation.py
```

### Image Translation
- **[image_translation.py](examples/image_translation.py)** - Image translation examples
  - Full image translation with overlay or inpainting
  - Text-only extraction and translation
  - Editing and rendering supplied translations
  - Style, memories, and glossaries options

```bash
cd examples
python image_translation.py
```

### Audio Translation
- **[audio_translation.py](examples/audio_translation.py)** - Audio translation examples
  - Basic audio translation
  - Advanced options with memories and glossaries
  - Step-by-step translation with status monitoring

```bash
cd examples
python audio_translation.py
```

### Audio Transcript Translation
- **[audio_transcript_translation.py](examples/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

```bash
cd examples
python audio_transcript_translation.py
```

### Translation Memory Management
- **[memories_management.py](examples/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

```bash
cd examples
python memories_management.py
```

### Glossary Management
- **[glossaries_management.py](examples/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

```bash
cd examples
python glossaries_management.py
```

### Styleguide Management
- **[styleguides_management.py](examples/styleguides_management.py)** - Styleguide management examples
  - Create, list, get, update, delete styleguides
  - Update name, content, or both at once
  - Handling of non-existent styleguides

```bash
cd examples
python styleguides_management.py
```

### Language Detection
- **[language_detection.py](examples/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

```bash
cd examples
python language_detection.py
```

## 🔧 API Reference

### Core Components

### 🔐 Authentication

The SDK supports authentication via access key and secret:

```python
from lara_sdk import Credentials, Translator

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

**Environment Variables (Recommended):**
```bash
export LARA_ACCESS_KEY_ID="your-access-key-id"
export LARA_ACCESS_KEY_SECRET="your-access-key-secret"
```

```python
import os
from lara_sdk import Credentials

credentials = Credentials(
    os.environ['LARA_ACCESS_KEY_ID'],
    os.environ['LARA_ACCESS_KEY_SECRET']
)
```

**Alternative Constructor:**
```python
# You can also pass credentials directly to Translator
lara = Translator(
    access_key_id="your-access-key-id",
    access_key_secret="your-access-key-secret"
)
```


### 🌍 Translator

```python
# Create translator with credentials
lara = Translator(credentials)
```

#### Text Translation

```python
# Basic translation
result = lara.translate("Hello", target="fr-FR", source="en-US")

# Multiple strings
result = lara.translate(["Hello", "World"], target="fr-FR", source="en-US")

# TextBlocks (mixed translatable/non-translatable content)
from lara_sdk import TextBlock

text_blocks = [
    TextBlock(text="Translatable text", translatable=True),
    TextBlock(text="<br>", translatable=False),  # Non-translatable HTML
    TextBlock(text="More translatable text", translatable=True)
]
result = lara.translate(text_blocks, target="fr-FR", source="en-US")

# With advanced options

result = lara.translate(
    "Hello",
    target="fr-FR",
    source="en-US",
    instructions=["Formal tone"],
    adapt_to=["memory-id"],  # Replace with actual memory IDs
    glossaries=["glossary-id"],  # Replace with actual glossary IDs
    style="fluid",
    timeout_ms=10000
)
```

### 📖 Document Translation
#### Simple document translation
```python
translated_content = lara.documents.translate(
    file_path="/path/to/your/document.txt",  # Replace with actual file path
    filename="document.txt",
    source="en-US",
    target="fr-FR"
)

# With options
translated_content = lara.documents.translate(
    file_path="/path/to/your/document.txt",  # Replace with actual file path
    filename="document.txt",
    source="en-US",
    target="fr-FR",
    adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"],  # Replace with actual memory IDs
    glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"],  # Replace with actual glossary IDs
    style="fluid"
)
```
### Document translation with status monitoring
#### Document upload
```python
#Optional: upload options
document = lara.documents.upload(
    file_path="/path/to/your/document.txt",  # Replace with actual file path
    filename="document.txt",
    source="en-US",
    target="fr-FR",
    adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"],  # Replace with actual memory IDs
    glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"]  # Replace with actual glossary IDs
)
```
#### Document translation status monitoring
```python
status = lara.documents.status(document.id)
```
#### Download translated document
```python
translated_content = lara.documents.download(document.id)
```

### 🖼️ Image Translation
#### Simple image translation
```python
translated_image = lara.images.translate(
  source="en-US",
  target="fr-FR",
  image_path="/path/to/your/image.png",  # Replace with actual file path
  model="overlay"
)
```

#### Text-only image translation
```python
text_results = lara.images.translate_text(
  source="en-US",
  target="it-IT",
  image_path="/path/to/your/image.png",  # Replace with actual file path
  include_layout=True
)
```

When `include_layout=True`, the result is typed as
`ImageTextResult[ImageLayoutParagraph]`, and every paragraph includes the layout
required by classic rendering models. Pass the paragraphs directly to the renderer:

```python
from lara_sdk import ImageParagraph

# Edit the translation while retaining the layout returned by translate_text.
text_results.paragraphs[0].translation = "Ciao mondo!"

rendered_image = lara.images.render_translated(
    image_path="/path/to/your/image.png",
    source=text_results.source_language,
    target="it-IT",
    paragraphs=text_results.paragraphs,
    model="overlay",
)

# Generative models accept text-only paragraphs. When model is omitted, the
# API uses generative_fast.
text_only_paragraphs = [
    ImageParagraph(text=p.text, translation=p.translation)
    for p in text_results.paragraphs
]
rendered_image = lara.images.render_translated(
    image_path="/path/to/your/image.png",
    source=None,
    target="it-IT",
    paragraphs=text_only_paragraphs,
)
```

`render_translated` renders supplied translations without translating them again. `overlay` and
`inpainting` require every paragraph to be an `ImageLayoutParagraph`, containing `bbox`,
`lines_bboxes`, `text_info`, and `alignment`. `generative`, `generative_fast`, and the omitted-model
default accept either `ImageParagraph` or `ImageLayoutParagraph`. The overloads express these
model-dependent requirements to Python type checkers. Set `no_trace=True` to disable request tracing.

### 🎵 Audio Translation
#### Simple audio translation
```python
audio_content = lara.audio.translate(
    file_path="/path/to/your/audio.mp3",  # Replace with actual file path
    filename="audio.mp3",
    source="en-US",
    target="fr-FR"
)

# With options
audio_content = lara.audio.translate(
    file_path="/path/to/your/audio.mp3",  # Replace with actual file path
    filename="audio.mp3",
    source="en-US",
    target="fr-FR",
    adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"],  # Replace with actual memory IDs
    glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"]  # Replace with actual glossary IDs
)
```
### Audio translation with status monitoring
#### Audio upload
```python
# Optional: upload options
audio = lara.audio.upload(
    file_path="/path/to/your/audio.mp3",  # Replace with actual file path
    filename="audio.mp3",
    source="en-US",
    target="fr-FR",
    adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"],  # Replace with actual memory IDs
    glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"]  # Replace with actual glossary IDs
)
```
#### Audio translation status monitoring
```python
status = lara.audio.status(audio.id)
```
#### Download translated audio
```python
audio_content = lara.audio.download(audio.id)
```

### 🎙️ Audio Transcript Translation
#### Simple transcript translation
```python
result = lara.audio.translate_transcript(
    file_path="/path/to/your/audio.mp3",  # Replace with actual file path
    filename="audio.mp3",
    source="en-US",
    target="fr-FR"
)

# With options
result = lara.audio.translate_transcript(
    file_path="/path/to/your/audio.mp3",  # Replace with actual file path
    filename="audio.mp3",
    source="en-US",
    target="fr-FR",
    adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"],  # Replace with actual memory IDs
    glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"]  # Replace with actual glossary IDs
)
```
### Transcript translation with status monitoring
#### Upload for transcription
```python
audio = lara.audio.upload_for_transcription(
    file_path="/path/to/your/audio.mp3",  # Replace with actual file path
    filename="audio.mp3",
    source="en-US",
    target="fr-FR"
)
```
#### Transcript status monitoring
```python
status = lara.audio.status(audio.id)
```
#### Retrieve translated transcript
```python
result = lara.audio.get_translated_transcript(audio.id)
```

### 🧠 Memory Management

```python
# Create memory
memory = 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 memory
memory_import = lara.memories.add_translation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001")

# Add translation to multiple memories
memory_import = lara.memories.add_translation(["mem_1A2b3C4d5E6f7G8h9I0jKl", "mem_2XyZ9AbC8dEf7GhI6jKlMn"], "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_002")

# Add with context
memory_import = lara.memories.add_translation(
    "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", 
    tuid="tuid", sentence_before="sentenceBefore", sentence_after="sentenceAfter"
)

# TMX import from file
memory_import = lara.memories.import_tmx("mem_1A2b3C4d5E6f7G8h9I0jKl", "/path/to/your/memory.tmx")  # Replace with actual TMX file path

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

# Async memory export - returns a job_id; the result is delivered to your callback URL when ready
memory_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 removed
delete_job = lara.memories.delete_translation(
  "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001"
)

# Wait for import completion
completed_import = lara.memories.wait_for_import(memory_import, max_wait_time=300)  # 5 minutes

# Share with the account or a group; shares can be renamed, listed, and revoked
team_memory = lara.memories.add_account_share("mem_1A2b3C4d5E6f7G8h9I0jKl", "Team memory")
lara.memories.rename_account_share(team_memory.id, "Company memory")
lara.memories.add_group_share(team_memory.id, "grp_1A2b3C4d5E6f7G8h9I0jKl", "Marketing memory")
shares = lara.memories.get_shares(team_memory.id)
lara.memories.revoke_group_share(team_memory.id, "grp_1A2b3C4d5E6f7G8h9I0jKl")
lara.memories.revoke_account_share(team_memory.id)
```

### 📚 Glossary Management

```python
# Create glossary
glossary = lara.glossaries.create("MyGlossary")

# Import a glossary file (use content_type="tbx" for TBX files)
glossary_import = lara.glossaries.import_file("gls_1A2b3C4d5E6f7G8h9I0jKl", "/path/to/your/glossary.csv")

# All options are keyword-only. The default content_type is "csv/table-uni".
# lara.glossaries.import_file(glossary.id, "/path/to/glossary.tbx", content_type="tbx")

# Import CSV with a callback URL (async notification when the import completes)
glossary_import = lara.glossaries.import_file(
    "gls_1A2b3C4d5E6f7G8h9I0jKl",
    "/path/to/your/glossary.csv",
    callback_url="https://your-server.example.com/lara/import-callback"
)

# Check import status
import_status = lara.glossaries.get_import_status(import_id)

# Wait for import completion
completed_import = lara.glossaries.wait_for_import(glossary_import, max_wait_time=300)  # 5 minutes

# Export glossary
csv_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 ready
glossary_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 count
counts = lara.glossaries.counts("gls_1A2b3C4d5E6f7G8h9I0jKl")

# Account and group sharing use the same add, rename, list, and revoke workflow
lara.glossaries.add_account_share(glossary.id, "Team glossary")
glossary_shares = lara.glossaries.get_shares(glossary.id)
lara.glossaries.revoke_account_share(glossary.id)
```

### 📋 Styleguide Management

```python
# Create styleguide
styleguide = lara.styleguides.create("MyStyleguide", "Always use formal language.")

# List all styleguides
styleguides = lara.styleguides.list()

# Get a specific styleguide
styleguide = lara.styleguides.get("stg_1A2b3C4d5E6f7G8h9I0jKl")

# Update styleguide — pass None for fields you don't want to change
# Update only the name
styleguide = lara.styleguides.update("stg_1A2b3C4d5E6f7G8h9I0jKl", "UpdatedStyleguide")

# Update only the content
styleguide = lara.styleguides.update("stg_1A2b3C4d5E6f7G8h9I0jKl", content="Always use informal language.")

# Update both
styleguide = lara.styleguides.update("stg_1A2b3C4d5E6f7G8h9I0jKl", "UpdatedStyleguide", "Always use informal language.")

# Share a styleguide and inspect all visible account, group, and user shares
lara.styleguides.add_group_share(styleguide.id, "grp_1A2b3C4d5E6f7G8h9I0jKl", "Marketing styleguide")
styleguide_shares = lara.styleguides.get_shares(styleguide.id)

# Delete styleguide
styleguide = lara.styleguides.delete("stg_1A2b3C4d5E6f7G8h9I0jKl")
```

### 🌐 Language Detection

```python
# Basic language detection
result = lara.detect("Hello, world!")
print(f"Detected language: {result.language}")
print(f"Content type: {result.content_type}")

# Detect multiple strings
result = lara.detect(["Hello", "Bonjour", "Hola"])

# Detection with hint
result = 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 passlist
result = 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.

```python
# Single pair
single = 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

# Batch
batch = lara.quality_estimation(
    source="en-US",
    target="it-IT",
    sentence=["Good morning.", "The weather is nice."],
    translation=["Buongiorno.", "Il tempo è bello."],
)
print([r.score for r in batch])  # e.g. [0.751, 0.713]
```

### Translation Options

```python
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 detection
    adapt_to=["memory-id"],                  # Memory IDs to adapt to
    glossaries=["glossary-id"],              # Glossary IDs to use
    instructions=["instruction"],            # Translation instructions
    style="fluid",                           # Translation style (fluid, faithful, creative)
    content_type="text/plain",               # Content type (text/plain, text/html, etc.)
    multiline=True,                          # Enable multiline translation
    timeout_ms=10000,                        # Request timeout in milliseconds
    no_trace=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`):

```python
# Full language codes (recommended)
result = lara.translate("Hello", target="fr-FR", source="en-US")

# Simple language codes
result = 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:

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

### Asset permissions

`Memory`, `Glossary`, and `Styleguide` expose `permission_mask: Optional[PermissionMask]`. All existing resource classes and method return types are unchanged. The value is `None` when the API omits the field, including POST, PUT, and DELETE resource responses.

GET list and detail responses contain the combined effective mask from the caller's applicable shares. Resources embedded in GET `/shares` responses contain the selected share's stored mask; individual share entries contain their own stored masks. Masks use read (`r`), write (`w`), export (`e`), and share (`s`) positions, with `-` for absent permissions. Supported values are `r---`, `rw--`, `r-e-`, `r--s`, `rwe-`, `rw-s`, `r-es`, and `rwes`.

Share entries expose a required `permission_mask`, matching the service contract. Resource masks remain optional. The legacy `permissions` field and the `MemorySharePermission`, `GlossarySharePermission`, and `StyleguideSharePermission` aliases have been removed. Use `permission_mask` to inspect the read, write, export, and share bits.

## ⚙️ Configuration
### Error Handling

The SDK provides detailed error information:

```python
from lara_sdk import LaraApiError, LaraError

try:
    result = lara.translate("Hello", target="fr-FR", source="en-US")
    print(f"Translation: {result.translation}")
except LaraApiError as error:
    print(f"API Error [{error.status_code}]: {error.message}")
    print(f"Error type: {error.type}")
except LaraError as error:
    print(f"SDK Error: {error}")
except Exception as error:
    print(f"Unexpected error: {error}")
```

## 📋 Requirements

- Python 3.8 or higher
- pip
- Valid Lara API credentials

## 🧪 Testing

Run the examples to test your setup.

```bash
# 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"
```
```bash
# Run basic text translation example
cd examples
python text_translation.py
```

## 🏗️ Building from Source

```bash
# 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](LICENSE) file for details.

Happy translating! 🌍✨
