### Run Glossary Management Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the glossary management script. Ensure environment variables for credentials are set. ```bash cd examples python glossaries_management.py ``` -------------------------------- ### Run Audio Translation Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the audio translation script. Ensure environment variables for credentials are set. ```bash cd examples python audio_translation.py ``` -------------------------------- ### Run Document Translation Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the document translation script. Ensure environment variables for credentials are set. ```bash cd examples python document_translation.py ``` -------------------------------- ### Run Language Detection Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the language detection script. Ensure environment variables for credentials are set. ```bash cd examples python language_detection.py ``` -------------------------------- ### Run Image Translation Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the image translation script. Ensure environment variables for credentials are set. ```bash cd examples python image_translation.py ``` -------------------------------- ### Run Translation Memory Management Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the memory management script. Ensure environment variables for credentials are set. ```bash cd examples python memories_management.py ``` -------------------------------- ### Run Text Translation Example Source: https://github.com/translated/lara-python/blob/main/README.md Navigate to the examples directory and run the text translation script. Ensure environment variables for credentials are set. ```bash cd examples python text_translation.py ``` -------------------------------- ### Install Lara Python SDK Source: https://github.com/translated/lara-python/blob/main/README.md Install the Lara SDK using pip. Ensure you are using Python 3.8 or later. ```bash pip install lara-sdk ``` -------------------------------- ### Run Basic Text Translation Example Source: https://github.com/translated/lara-python/blob/main/README.md Execute the basic text translation example script. Ensure you have set your environment variables for API credentials before running this command. ```bash # Run basic text translation example cd examples python text_translation.py ``` -------------------------------- ### Install Lara Python SDK from Source Source: https://github.com/translated/lara-python/blob/main/README.md Clone the Lara Python SDK repository and install it in development mode using pip. This is useful for contributing to the project or using the latest unreleased features. ```bash # Clone the repository git clone https://github.com/translated/lara-python.git cd lara-python # Install in development mode pip install -e . ``` -------------------------------- ### Basic Text Translation with Lara SDK Source: https://github.com/translated/lara-python/blob/main/README.md Perform a simple text translation using the Lara SDK. Set your credentials via environment variables for security. This example translates 'Hello, world!' to French. ```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}") ``` -------------------------------- ### Alternative Translator Constructor Source: https://github.com/translated/lara-python/blob/main/README.md Instantiate the Translator by passing access key ID and secret directly as keyword arguments. Useful for quick setups. ```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.documents.upload() / status() / download() Source: https://context7.com/translated/lara-python/llms.txt Provides granular control over the document translation pipeline: upload the file to get a `Document` object, poll `.status()` for `DocumentStatus` progress, then call `.download()` when status is `TRANSLATED`. ```APIDOC ## Translator.documents.upload() / status() / download() ### Description Provides granular control over the document translation pipeline: upload the file to get a `Document` object, poll `.status()` for `DocumentStatus` progress, then call `.download()` when status is `TRANSLATED`. ### Method ```python import os, time from lara_sdk import AccessKey, Translator, DocumentStatus, LaraApiError lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) # Step 1: Upload document = lara.documents.upload( file_path="manual.pdf", filename="manual.pdf", source="en-US", target="ja-JP", adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], ) print(f"Document ID: {document.id}, Status: {document.status.value}") # Step 2: Poll for completion while True: doc = lara.documents.status(document.id) print(f"Status: {doc.status.value} ({doc.translated_chars}/{doc.total_chars} chars)") if doc.status == DocumentStatus.TRANSLATED: break if doc.status == DocumentStatus.ERROR: raise RuntimeError(f"Translation failed: {doc.error_reason}") time.sleep(5) # Step 3: Download content = lara.documents.download(document.id) with open("manual_ja.pdf", "wb") as f: f.write(content) print("Download complete.") ``` ``` -------------------------------- ### Text Translation Source: https://github.com/translated/lara-python/blob/main/README.md Provides examples for translating single strings, multiple strings, and complex text blocks using the Translator. ```APIDOC ## 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="
", 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 ) ``` ``` -------------------------------- ### Get Glossary Terms Count Source: https://github.com/translated/lara-python/blob/main/README.md Retrieves the number of terms within a specified glossary. ```python # Get glossary terms count counts = lara.glossaries.counts("gls_1A2b3C4d5E6f7G8h9I0jKl") ``` -------------------------------- ### Get Supported Languages in Python Source: https://github.com/translated/lara-python/blob/main/README.md Use the `languages()` method to retrieve a list of all languages supported by the Lara API. This is useful for understanding available translation options. ```python languages = lara.languages() print(f"Supported languages: {', '.join(languages)}") ``` -------------------------------- ### Glossary Management Operations Source: https://context7.com/translated/lara-python/llms.txt Demonstrates various operations for managing glossaries, including importing CSV files, checking import status, exporting glossaries, adding/replacing entries, deleting entries by GUID or term, and deleting an entire glossary. ```APIDOC ## Glossary Import and Status ### Description Import terms into a glossary from a CSV file and monitor the import process. ### Method `lara.glossaries.import_csv(glossary_id, file_path, content_type)` `lara.glossaries.wait_for_import(import_id, max_wait_time)` ### Parameters #### `import_csv` - **glossary_id** (string) - Required - The ID of the glossary to import into. - **file_path** (string) - Required - The path to the CSV file to import. - **content_type** (string) - Required - The content type of the CSV file (e.g., `"csv/table-uni"`). #### `wait_for_import` - **import_id** (string) - Required - The ID returned by `import_csv`. - **max_wait_time** (integer) - Optional - Maximum time in seconds to wait for the import to complete. ### Response Example ```python csv_import = lara.glossaries.import_csv(glossary.id, "terms.csv", content_type="csv/table-uni") completed = lara.glossaries.wait_for_import(csv_import, max_wait_time=60) print(f"Import complete: {completed.progress:.0%}") ``` ``` ```APIDOC ## Glossary Export ### Description Export the terms from a glossary in CSV format. ### Method `lara.glossaries.export(glossary_id, content_type, source)` ### Parameters - **glossary_id** (string) - Required - The ID of the glossary to export. - **content_type** (string) - Required - The desired content type for the export (e.g., `"csv/table-uni"`). - **source** (string) - Required - The source language code for the export (e.g., `"en-US"`). ### Response Example ```python csv_bytes = lara.glossaries.export(glossary.id, content_type="csv/table-uni", source="en-US") with open("exported_terms.csv", "wb") as f: f.write(csv_bytes) ``` ``` ```APIDOC ## Add or Replace Glossary Entry ### Description Adds a new term entry to a glossary or replaces an existing one if a matching GUID is found. ### Method `lara.glossaries.add_or_replace_entry(glossary_id, terms, guid)` ### Parameters - **glossary_id** (string) - Required - The ID of the glossary. - **terms** (list of GlossaryTerm) - Required - A list of `GlossaryTerm` objects, each specifying a language and its corresponding value. - **guid** (string) - Required - A unique identifier for the term entry. ### Request Example ```python lara.glossaries.add_or_replace_entry(glossary.id, [ GlossaryTerm(language="en-US", value="keyboard"), GlossaryTerm(language="it-IT", value="tastiera"), GlossaryTerm(language="fr-FR", value="clavier"), ], guid="term-keyboard") ``` ``` ```APIDOC ## Delete Glossary Entry ### Description Deletes a specific entry from a glossary, either by its GUID or by its term value and language. ### Method `lara.glossaries.delete_entry(glossary_id, guid=None, term=None)` ### Parameters - **glossary_id** (string) - Required - The ID of the glossary. - **guid** (string) - Optional - The GUID of the entry to delete. - **term** (GlossaryTerm) - Optional - A `GlossaryTerm` object specifying the language and value of the entry to delete. Use either `guid` or `term`, not both. ### Request Example (by GUID) ```python lara.glossaries.delete_entry(glossary.id, guid="term-keyboard") ``` ### Request Example (by Term) ```python lara.glossaries.delete_entry(glossary.id, term=GlossaryTerm(language="en-US", value="keyboard")) ``` ``` ```APIDOC ## Delete Glossary ### Description Deletes an entire glossary and all its contents. ### Method `lara.glossaries.delete(glossary_id)` ### Parameters - **glossary_id** (string) - Required - The ID of the glossary to delete. ### Request Example ```python lara.glossaries.delete(glossary.id) ``` ``` -------------------------------- ### Initialize Translator with Credentials Source: https://github.com/translated/lara-python/blob/main/README.md Create a Translator instance using pre-configured credentials. This is a common step before performing translation tasks. ```python # Create translator with credentials lara = Translator(credentials) ``` -------------------------------- ### Authenticate with Access Key and Secret Source: https://github.com/translated/lara-python/blob/main/README.md Initialize credentials using your access key ID and secret. This is required for all SDK operations. ```python from lara_sdk import Credentials, Translator credentials = Credentials("your-access-key-id", "your-access-key-secret") lara = Translator(credentials) ``` -------------------------------- ### Authenticate using Environment Variables Source: https://github.com/translated/lara-python/blob/main/README.md Create credentials by reading the access key ID and secret from environment variables. Ensure these variables are set before execution. ```python import os from lara_sdk import Credentials credentials = Credentials( os.environ['LARA_ACCESS_KEY_ID'], os.environ['LARA_ACCESS_KEY_SECRET'] ) ``` -------------------------------- ### Get Document Translation Status Source: https://github.com/translated/lara-python/blob/main/README.md Check the translation status of an uploaded document using its ID. This is part of the status monitoring workflow. ```python status = lara.documents.status(document.id) ``` -------------------------------- ### Translator Initialization Source: https://github.com/translated/lara-python/blob/main/README.md Shows how to initialize the Translator object with provided credentials. ```APIDOC ## Translator ```python # Create translator with credentials lara = Translator(credentials) ``` ``` -------------------------------- ### Authenticate with AccessKey Source: https://context7.com/translated/lara-python/llms.txt Create an AccessKey object using environment variables for credentials. This is the preferred method for authentication. ```python import os from lara_sdk import AccessKey, Translator credentials = AccessKey( os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"] ) lara = Translator(credentials) ``` -------------------------------- ### Get Audio Translation Status Source: https://github.com/translated/lara-python/blob/main/README.md Monitor the translation progress of an uploaded audio file using its unique ID. Part of the asynchronous translation workflow. ```python status = lara.audio.status(audio.id) ``` -------------------------------- ### Step-by-Step Audio Translation using Python Source: https://context7.com/translated/lara-python/llms.txt Translates an audio file using a multi-step process: upload, poll status, and download. This approach mirrors the document step-by-step API and allows for progress monitoring. ```python import os, time from lara_sdk import AccessKey, Translator, AudioStatus lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) audio = lara.audio.upload( file_path="podcast.mp3", filename="podcast.mp3", source="en-US", target="fr-FR", ) print(f"Audio ID: {audio.id}, Status: {audio.status.value}") while True: audio = lara.audio.status(audio.id) if audio.status == AudioStatus.TRANSLATED: break if audio.status == AudioStatus.ERROR: raise RuntimeError(f"Audio translation failed: {audio.error_reason}") time.sleep(5) content = lara.audio.download(audio.id) with open("podcast_fr.mp3", "wb") as f: f.write(content) ``` -------------------------------- ### Batch Quality Estimation for Translation Pairs Source: https://github.com/translated/lara-python/blob/main/README.md Estimates the quality for multiple translation pairs in a batch. Provide parallel lists of source sentences and their translations to get a score for each pair. ```python # 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] ``` -------------------------------- ### Memory Management Source: https://github.com/translated/lara-python/blob/main/README.md Demonstrates how to create a new translation memory using the SDK. ```APIDOC ### Memory Management ```python # Create memory memory = lara.memories.create("MyMemory") ``` ``` -------------------------------- ### AccessKey Authentication Source: https://context7.com/translated/lara-python/llms.txt Demonstrates how to create an AccessKey object for authenticating the Translator client using environment variables for credentials. ```APIDOC ## AccessKey Authentication ### Description Create an `AccessKey` from your access key ID and secret to authenticate the `Translator`. Store credentials in environment variables rather than hard-coding them. ### Method ```python import os from lara_sdk import AccessKey, Translator credentials = AccessKey( os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"] ) lara = Translator(credentials) ``` ``` -------------------------------- ### Authentication Source: https://github.com/translated/lara-python/blob/main/README.md Demonstrates how to authenticate with the Lara SDK using access keys and secret keys, either directly or via environment variables. ```APIDOC ## 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" ) ``` ``` -------------------------------- ### Create Glossary Source: https://github.com/translated/lara-python/blob/main/README.md Creates a new glossary with a given name. ```python # Create glossary glossary = lara.glossaries.create("MyGlossary") ``` -------------------------------- ### Manage Styleguides with Lara Python SDK Source: https://context7.com/translated/lara-python/llms.txt Shows how to list, retrieve, and apply styleguides during translation using the Lara Python SDK. Ensure your LARA_ACCESS_KEY_ID and LARA_ACCESS_KEY_SECRET environment variables are set. ```python import os from lara_sdk import AccessKey, Translator lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) # List all styleguides guides = lara.styleguides.list() for g in guides: print(f"{g.id}: {g.name}") ``` ```python # Get a specific styleguide guide = lara.styleguides.get("sg_abc123") if guide: print(guide.content) ``` ```python # Apply styleguide during translation result = lara.translate( "Please contact our support team.", source="en-US", target="fr-FR", styleguide_id="sg_abc123", styleguide_reasoning=True, styleguide_explanation_language="en-US", ) print(result.translation) if result.styleguide_results: for change in result.styleguide_results.changes: print(f"Change: {change.original_translation} → {change.refined_translation}") print(f"Reason: {change.explanation}") ``` -------------------------------- ### Translator.audio.upload() / status() / download() Source: https://context7.com/translated/lara-python/llms.txt Step-by-step audio translation mirroring the document step-by-step API. Allows uploading, checking status, and downloading translated audio. ```APIDOC ## Translator.audio.upload() / status() / download() ### Description Step-by-step audio translation mirroring the document step-by-step API. Returns an `Audio` object; poll `.status()` for `AudioStatus` updates, then download when `TRANSLATED`. ### Method `lara.audio.upload()`, `lara.audio.status()`, `lara.audio.download()` ### Parameters #### `upload()` Parameters - **file_path** (string) - Required - Path to the audio file. - **filename** (string) - Required - Name of the audio file. - **source** (string) - Required - Source language code. - **target** (string) - Required - Target language code. #### `status()` Parameters - **audio_id** (string) - Required - The ID of the audio translation job. #### `download()` Parameters - **audio_id** (string) - Required - The ID of the audio translation job. ### Request Example ```python import os, time from lara_sdk import AccessKey, Translator, AudioStatus lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) audio = lara.audio.upload( file_path="podcast.mp3", filename="podcast.mp3", source="en-US", target="fr-FR", ) print(f"Audio ID: {audio.id}, Status: {audio.status.value}") while True: audio = lara.audio.status(audio.id) if audio.status == AudioStatus.TRANSLATED: break if audio.status == AudioStatus.ERROR: raise RuntimeError(f"Audio translation failed: {audio.error_reason}") time.sleep(5) content = lara.audio.download(audio.id) with open("podcast_fr.mp3", "wb") as f: f.write(content) ``` ### Response #### Success Response (`upload()`) - **audio** (`Audio` object) - **id** (string) - **status** (`AudioStatus` enum) #### Success Response (`status()`) - **audio** (`Audio` object) - **id** (string) - **status** (`AudioStatus` enum) - **error_reason** (string, optional) #### Success Response (`download()`) - **content** (bytes) - The translated audio content. #### Response Example (Audio object details for upload/status, binary data for download) ``` -------------------------------- ### Step-by-step document translation with upload, status, and download Source: https://context7.com/translated/lara-python/llms.txt Perform document translation in stages: upload, poll status, and download. This provides granular control over the process. Handles potential errors during translation. ```python import os, time from lara_sdk import AccessKey, Translator, DocumentStatus, LaraApiError lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) # Step 1: Upload document = lara.documents.upload( file_path="manual.pdf", filename="manual.pdf", source="en-US", target="ja-JP", adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], ) print(f"Document ID: {document.id}, Status: {document.status.value}") # Step 2: Poll for completion while True: doc = lara.documents.status(document.id) print(f"Status: {doc.status.value} ({doc.translated_chars}/{doc.total_chars} chars)") if doc.status == DocumentStatus.TRANSLATED: break if doc.status == DocumentStatus.ERROR: raise RuntimeError(f"Translation failed: {doc.error_reason}") time.sleep(5) # Step 3: Download content = lara.documents.download(document.id) with open("manual_ja.pdf", "wb") as f: f.write(content) print("Download complete.") ``` -------------------------------- ### Translator.translate() - Advanced Options Source: https://context7.com/translated/lara-python/llms.txt Demonstrates advanced translation options including translation memories, glossaries, custom instructions, style, and profanity detection. ```APIDOC ## Translator.translate() - Advanced Options ### Description Translates a single string, a list of strings, or a list of `TextBlock` objects. Supports automatic source language detection, translation memories (`adapt_to`), glossaries, custom instructions, profanity handling, styleguide enforcement, and caching controls. Returns a `TextResult` with `.translation` and `.source_language`. ### Method ```python import os from lara_sdk import AccessKey, Translator, TextBlock lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) # Advanced options — memory, glossary, instructions, style, profanity detection result = lara.translate( "Could you send me the report by tomorrow morning?", source="en-US", target="de-DE", adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"], instructions=["Be formal", "Use technical terminology"], style="fluid", # "faithful" | "fluid" | "creative" profanities_detect="target", # "target" | "source_target" profanities_handling="hide", # "hide" | "avoid" | "detect" timeout_ms=10000, no_trace=True, ) print(result.translation) ``` ``` -------------------------------- ### Audio Translation with Status Monitoring Source: https://github.com/translated/lara-python/blob/main/README.md Explains the workflow for uploading audio for translation, monitoring its status, and downloading the translated audio. ```APIDOC ### 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) ``` ``` -------------------------------- ### Upload Audio for Translation Source: https://github.com/translated/lara-python/blob/main/README.md Upload an audio file for translation. This is the initial step for asynchronous audio translation, allowing for status monitoring. ```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 ) ``` -------------------------------- ### Translation Options Source: https://github.com/translated/lara-python/blob/main/README.md Demonstrates various options available for the `translate` function. ```APIDOC ```python result = lara.translate( text, # The text to translate (required) 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 ) ``` ### Description Performs translation with a wide range of customizable options. ### Method lara.translate ### Parameters - **text** (string) - Required - The text to translate. - **target** (string) - Required - The target language code. - **source** (string) - Optional - The source language code. If not provided, it will be auto-detected. - **source_hint** (string) - Optional - A hint to aid in source language detection. - **adapt_to** (list of strings) - Optional - A list of memory IDs to adapt the translation to. - **glossaries** (list of strings) - Optional - A list of glossary IDs to use during translation. - **instructions** (list of strings) - Optional - Specific instructions for the translation process. - **style** (string) - Optional - The desired translation style (e.g., 'fluid', 'faithful', 'creative'). - **content_type** (string) - Optional - The content type of the input text (e.g., 'text/plain', 'text/html'). - **multiline** (boolean) - Optional - Enables translation of multiline text. - **timeout_ms** (integer) - Optional - The timeout for the request in milliseconds. - **no_trace** (boolean) - Optional - Disables request tracing if set to True. - **verbose** (boolean) - Optional - Enables verbose output if set to True. ``` -------------------------------- ### Document Translation with Status Monitoring Source: https://github.com/translated/lara-python/blob/main/README.md Explains the process of uploading a document for translation, monitoring its status, and downloading the translated content. ```APIDOC ### 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) ``` ``` -------------------------------- ### Set Lara API Credentials using Environment Variables Source: https://github.com/translated/lara-python/blob/main/README.md Configure your Lara API access by setting environment variables for your access key ID and secret key. This is the recommended method for providing credentials. ```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" ``` -------------------------------- ### Handle Lara SDK Exceptions Source: https://context7.com/translated/lara-python/llms.txt Illustrates how to catch and handle specific Lara SDK exceptions, including API errors and general SDK errors, as well as timeouts. Ensure your LARA_ACCESS_KEY_ID and LARA_ACCESS_KEY_SECRET environment variables are set. ```python import os from lara_sdk import AccessKey, Translator, LaraApiError, LaraError lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) try: result = lara.translate("Hello", target="fr-FR", source="en-US") print(f"Translation: {result.translation}") except LaraApiError as e: # HTTP-level API error (4xx / 5xx) print(f"API Error [{e.status_code}] {e.type}: {e.message}") if e.status_code == 401: print("Check your API credentials.") elif e.status_code == 429: print("Rate limit reached — back off and retry.") except LaraError as e: # Generic SDK error (e.g., invalid argument) print(f"SDK Error: {e}") except TimeoutError: # Raised by wait_for_import / document.translate / audio.translate print("Operation timed out.") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Set Lara SDK Credentials Source: https://github.com/translated/lara-python/blob/main/README.md Set your Lara API access key ID and secret key as environment variables. This is the recommended method for credential management. ```bash export LARA_ACCESS_KEY_ID="your-access-key-id" export LARA_ACCESS_KEY_SECRET="your-access-key-secret" ``` -------------------------------- ### Styleguide Management Source: https://context7.com/translated/lara-python/llms.txt Operations for listing, retrieving, and applying styleguides to translations. ```APIDOC ## List and Retrieve Styleguides ### Description Manage styleguides associated with your account. Styleguides can be listed, retrieved by ID, and applied during translation to enforce specific writing standards. ### Methods - `lara.styleguides.list()` - `lara.styleguides.get(styleguide_id)` ### Parameters #### `get` - **styleguide_id** (string) - Required - The unique identifier of the styleguide to retrieve. ### Request Example (List Styleguides) ```python guides = lara.styleguides.list() for g in guides: print(f"{g.id}: {g.name}") ``` ### Request Example (Get Specific Styleguide) ```python guide = lara.styleguides.get("sg_abc123") if guide: print(guide.content) ``` ### Applying Styleguide During Translation ```python result = lara.translate( "Please contact our support team.", source="en-US", target="fr-FR", styleguide_id="sg_abc123", styleguide_reasoning=True, styleguide_explanation_language="en-US", ) print(result.translation) if result.styleguide_results: for change in result.styleguide_results.changes: print(f"Change: {change.original_translation} → {change.refined_translation}") print(f"Reason: {change.explanation}") ``` ``` -------------------------------- ### Language Detection with Hint and Passlist Source: https://github.com/translated/lara-python/blob/main/README.md Combines a language hint with a passlist to refine language detection. This provides both a suggestion for the language and a restriction on the possible outcomes. ```python # Combined hint and passlist result = lara.detect( "Buongiorno", hint="it", passlist=["it-IT", "es-ES", "pt-PT"] ) ``` -------------------------------- ### Manage Glossary Entries with Lara Python SDK Source: https://context7.com/translated/lara-python/llms.txt Demonstrates importing, exporting, adding, replacing, and deleting glossary entries using the Lara Python SDK. Ensure you have a glossary ID and the necessary CSV file for import. ```python csv_import = lara.glossaries.import_csv(glossary.id, "terms.csv", content_type="csv/table-uni") completed = lara.glossaries.wait_for_import(csv_import, max_wait_time=60) print(f"Import complete: {completed.progress:.0%}") ``` ```python counts = lara.glossaries.counts(glossary.id) if counts.unidirectional: for lang_pair, count in counts.unidirectional.items(): print(f" {lang_pair}: {count} terms") ``` ```python csv_bytes = lara.glossaries.export(glossary.id, content_type="csv/table-uni", source="en-US") with open("exported_terms.csv", "wb") as f: f.write(csv_bytes) ``` ```python lara.glossaries.add_or_replace_entry(glossary.id, [ GlossaryTerm(language="en-US", value="keyboard"), GlossaryTerm(language="it-IT", value="tastiera"), GlossaryTerm(language="fr-FR", value="clavier"), ], guid="term-keyboard") ``` ```python lara.glossaries.delete_entry(glossary.id, guid="term-keyboard") lara.glossaries.delete_entry(glossary.id, term=GlossaryTerm(language="en-US", value="keyboard")) ``` ```python lara.glossaries.delete(glossary.id) ``` -------------------------------- ### Manage Glossaries using Python Source: https://context7.com/translated/lara-python/llms.txt Enables the creation and management of term glossaries, including CRUD operations, CSV import/export, and individual term management. Glossaries enforce consistent terminology in translations. ```python import os from lara_sdk import AccessKey, Translator, GlossaryTerm lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) # Create & list glossary = lara.glossaries.create("TechGlossary") print(f"Created: {glossary.id}") all_glossaries = lara.glossaries.list() ``` -------------------------------- ### Translate Audio File End-to-End using Python Source: https://context7.com/translated/lara-python/llms.txt Translates an entire audio file and returns the translated audio as bytes. Supports various audio formats and allows specifying voice gender for synthesized output. ```python import os from lara_sdk import AccessKey, Translator, VoiceGender lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) audio_bytes = lara.audio.translate( file_path="interview.mp3", filename="interview.mp3", source="en-US", target="de-DE", adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"], voice_gender=VoiceGender.FEMALE, ) with open("interview_de.mp3", "wb") as f: f.write(audio_bytes) ``` -------------------------------- ### Language Detection with Hint Source: https://github.com/translated/lara-python/blob/main/README.md Performs language detection with a hint for the source language. This can improve accuracy when the input text is short or ambiguous. ```python # Detection with hint result = lara.detect("Hello", hint="en") ``` -------------------------------- ### Score translation quality with quality_estimation Source: https://context7.com/translated/lara-python/llms.txt Use the quality_estimation method to score translation quality for single pairs or in batches. Requires initializing the Translator with access keys. ```python from lara_sdk import AccessKey, Translator import os lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) # 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] ``` -------------------------------- ### Create Memory Source: https://github.com/translated/lara-python/blob/main/README.md Create a new memory with a specified name. Memories can be used to store translation data for adaptation and consistency. ```python # Create memory memory = lara.memories.create("MyMemory") ``` -------------------------------- ### Error Handling with SDK Exceptions Source: https://context7.com/translated/lara-python/llms.txt Details on how to handle API and SDK-level errors using `LaraApiError` and `LaraError`. ```APIDOC ## SDK Exception Types ### Description Understand and handle potential errors during SDK operations. `LaraApiError` provides details from API responses (status code, type, message), while `LaraError` is the base for all SDK-specific errors. ### Exception Types - `LaraApiError`: For HTTP-level API errors (4xx, 5xx). - `LaraError`: Base class for all SDK errors. - `TimeoutError`: For operations that exceed their maximum wait time. ### Usage ```python import os from lara_sdk import AccessKey, Translator, LaraApiError, LaraError lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) try: result = lara.translate("Hello", target="fr-FR", source="en-US") print(f"Translation: {result.translation}") except LaraApiError as e: # HTTP-level API error (4xx / 5xx) print(f"API Error [{e.status_code}] {e.type}: {e.message}") if e.status_code == 401: print("Check your API credentials.") elif e.status_code == 429: print("Rate limit reached — back off and retry.") except LaraError as e: # Generic SDK error (e.g., invalid argument) print(f"SDK Error: {e}") except TimeoutError: # Raised by wait_for_import / document.translate / audio.translate print("Operation timed out.") except Exception as e: print(f"Unexpected error: {e}") ``` ``` -------------------------------- ### Document Translation Source: https://github.com/translated/lara-python/blob/main/README.md Illustrates how to translate documents, including simple translation and translation with advanced options like adapt_to and glossaries. ```APIDOC ## 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" ) ``` ``` -------------------------------- ### Create Memory with External ID Source: https://github.com/translated/lara-python/blob/main/README.md Creates a new memory with an associated external ID. Replace the placeholder with your actual external ID. ```python memory = lara.memories.create("Memory from MyMemory", external_id="aabb1122") # Replace with actual external ID ``` -------------------------------- ### Language Codes Source: https://github.com/translated/lara-python/blob/main/README.md Explanation of supported language code formats. ```APIDOC ## Full language codes (recommended) ```python result = lara.translate("Hello", target="fr-FR", source="en-US") ``` ## Simple language codes ```python result = lara.translate("Hello", target="fr", source="en") ``` ### Description The Lara SDK supports both full language codes (e.g., `en-US`, `fr-FR`) and simple language codes (e.g., `en`, `fr`). Full language codes are recommended for precision. ``` -------------------------------- ### Translator.audio.translate() Source: https://context7.com/translated/lara-python/llms.txt Translate an audio file end-to-end. Uploads an audio file, polls until translation is complete, and returns the translated audio as bytes. ```APIDOC ## Translator.audio.translate() ### Description Translate an audio file end-to-end. Uploads an audio file (`.wav`, `.mp3`, `.opus`, `.ogg`, `.webm`), polls until translation is complete, and returns the translated audio as `bytes`. Supports `voice_gender` to select the synthesized voice. ### Method `lara.audio.translate()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import os from lara_sdk import AccessKey, Translator, VoiceGender lara = Translator(AccessKey(os.environ["LARA_ACCESS_KEY_ID"], os.environ["LARA_ACCESS_KEY_SECRET"])) audio_bytes = lara.audio.translate( file_path="interview.mp3", filename="interview.mp3", source="en-US", target="de-DE", adapt_to=["mem_1A2b3C4d5E6f7G8h9I0jKl"], glossaries=["gls_1A2b3C4d5E6f7G8h9I0jKl"], voice_gender=VoiceGender.FEMALE, ) with open("interview_de.mp3", "wb") as f: f.write(audio_bytes) ``` ### Response #### Success Response (200) - **audio_bytes** (bytes) - The translated audio content. #### Response Example (Binary audio data) ``` -------------------------------- ### Memory Management Source: https://github.com/translated/lara-python/blob/main/README.md Operations for creating memories, adding translations, importing TMX files, and deleting translations. ```APIDOC ## Create memory with external ID ```python memory = lara.memories.create("Memory from MyMemory", external_id="aabb1122") ``` ### Description Creates a new memory with an optional external ID. ### Method lara.memories.create ### Parameters - **name** (string) - Required - The name of the memory. - **external_id** (string) - Optional - An external identifier for the memory. ## Add translation to single memory ```python memory_import = lara.memories.add_translation("mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001") ``` ### Description Adds a translation to a specific memory. If a `tuid` is provided, it updates the existing entry; otherwise, it creates a new one. ### Method lara.memories.add_translation ### Parameters - **memory_id** (string or list) - Required - The ID of the memory or a list of memory IDs. - **source_lang** (string) - Required - The source language code. - **target_lang** (string) - Required - The target language code. - **source_text** (string) - Required - The source text. - **target_text** (string) - Required - The target text. - **tuid** (string) - Optional - The translation unit ID for updating existing entries. - **sentence_before** (string) - Optional - Context sentence before the translation. - **sentence_after** (string) - Optional - Context sentence after the translation. ## TMX import from file ```python memory_import = lara.memories.import_tmx("mem_1A2b3C4d5E6f7G8h9I0jKl", "/path/to/your/memory.tmx") ``` ### Description Imports translation units from a TMX file into a specified memory. ### Method lara.memories.import_tmx ### Parameters - **memory_id** (string) - Required - The ID of the memory to import into. - **file_path** (string) - Required - The path to the TMX file. ## Delete translation ```python delete_job = lara.memories.delete_translation( "mem_1A2b3C4d5E6f7G8h9I0jKl", "en-US", "fr-FR", "Hello", "Bonjour", tuid="greeting_001" ) ``` ### Description Deletes a translation entry from a memory. If `tuid` is omitted, all matching entries will be removed. ### Method lara.memories.delete_translation ### Parameters - **memory_id** (string) - Required - The ID of the memory. - **source_lang** (string) - Required - The source language code. - **target_lang** (string) - Required - The target language code. - **source_text** (string) - Required - The source text. - **target_text** (string) - Required - The target text. - **tuid** (string) - Optional - The translation unit ID to delete. ## Wait for import completion ```python completed_import = lara.memories.wait_for_import(memory_import, max_wait_time=300) ``` ### Description Waits for an ongoing memory import operation to complete. ### Method lara.memories.wait_for_import ### Parameters - **import_job** (object) - Required - The import job object returned by an import function. - **max_wait_time** (integer) - Optional - Maximum time in seconds to wait for completion. ```