### Install Dependencies
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/voice/cli/README.md
Installs the necessary dependencies for the CLI example using uv or poetry.
```shell
cd examples/voice/cli
uv sync
# or
poetry install
```
--------------------------------
### Install Microphone Dependencies
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/voice/cli/README.md
Installs the 'mic' dependency group for microphone support, with a note on potential system package requirements.
```shell
uv sync --group mic
# or
poetry install --with mic
```
--------------------------------
### Get help for Mustache translator
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/mustache/README.md
Command to display help information for the Mustache translator script.
```bash
python examples/mustache --help
```
--------------------------------
### Get a glossary
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Examples for retrieving both monolingual and multilingual glossaries.
```python
# monolingual glossary example
created_glossary = deepl_client.create_glossary("My Glossary", "EN", "DE", {"hello": "hallo"})
glossary_info = deepl_client.get_glossary(created_glossary) # GlossaryInfo object
# multilingual glossary example
glossary_dicts = [MultilingualGlossaryDictionaryEntries("EN", "DE", {"hello": "hallo"})]
created_glossary = deepl_client.create_multilingual_glossary("My Glossary", glossary_dicts)
glossary_info = deepl_client.get_multilingual_glossary(created_glossary) # MultilingualGlossaryInfo object
```
--------------------------------
### Get glossary entries
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Examples for retrieving entries from both monolingual and multilingual glossaries.
```python
# monolingual glossary example
created_glossary = deepl_client.create_glossary("My Glossary", "EN", "DE", {"hello": "hallo"})
entries = deepl_client.get_glossary_entries(created_glossary)
print(entries) # 'hello\thallo'
# multilingual glossary example
glossary_dicts = [MultilingualGlossaryDictionaryEntries("EN", "DE", {"hello": "hallo"})]
created_glossary = deepl_client.create_multilingual_glossary("My Glossary", glossary_dicts)
dict_entries = deepl_client.get_multilingual_glossary_entries(created_glossary, "EN", "DE")
print(dict_entries.dictionaries[0].entries) # 'hello\thallo'
```
--------------------------------
### Get help for the JSON translator
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/json/README.md
This command displays the help options for the JSON translator script.
```bash
python examples/json --help
```
--------------------------------
### Keyring Integration Installation
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Install keyring support for secure API key storage.
```bash
# Install keyring support
pip install deepl[keyring]
```
--------------------------------
### Complete Configuration Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
A comprehensive example demonstrating various configuration options for the DeepL Python client.
```python
import deepl
import logging
import os
# Configure logging
logging.basicConfig(level=logging.DEBUG)
# Configure HTTP client
deep.http_client.max_network_retries = 3
deep.http_client.user_agent = "MyTranslationApp/2.1.0"
# Get credentials from environment
auth_key = os.environ.get("DEEPL_AUTH_KEY")
if not auth_key:
raise ValueError("DEEPL_AUTH_KEY not set")
# Create fully configured client
client = deepl.DeepLClient(
auth_key=auth_key,
server_url="https://api.deepl.com",
proxy={
"http": "http://proxy.internal:3128",
"https": "https://proxy.internal:3128"
},
send_platform_info=True,
verify_ssl="/etc/ssl/certs/ca-bundle.crt"
)
# Register application
client.set_app_info("MyTranslationApp", "2.1.0")
# Use client
try:
result = client.translate_text("Hello, world!", target_lang="DE")
print(f"Translation: {result.text}")
except deepl.DeepLException as e:
print(f"Error: {e}")
finally:
client.close()
```
--------------------------------
### Example Debug Output
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Example of detailed debug output from the DeepL Python client.
```text
DEBUG:deepl:Request to DeepL API method=POST url=https://api.deepl.com/v2/translate
DEBUG:deepl:Request details data={} json={'text': ['Hello'], 'target_lang': 'DE', ...}
INFO:deepl:DeepL API response url=https://api.deepl.com/v2/translate status_code=200
DEBUG:deepl:Response details content={"translations": [{"text": "Hallo", ...}]}
```
--------------------------------
### ConnectionException Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example of how to catch and handle a ConnectionException.
```python
try:
result = client.translate_text("Hello", target_lang="DE")
except deepl.ConnectionException as e:
print(f"Connection failed: {e}")
if e.should_retry:
print("Network issue detected, retry recommended")
```
--------------------------------
### Basic Configuration
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Minimal and fully configured client initialization examples.
```python
import deepl
# Minimal configuration (auto-detects API endpoint)
client = deepl.DeepLClient("your-auth-key")
# Fully configured client
client = deepl.DeepLClient(
auth_key="your-auth-key",
server_url="https://api.deepl.com",
proxy="http://proxy.example.com:3128",
send_platform_info=True,
verify_ssl=True,
)
```
--------------------------------
### DeepLClient Initialization Examples
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Examples demonstrating how to initialize the DeepLClient with different configurations, including custom proxies and server URLs, and how to set app information.
```python
import deepl
auth_key = "your-auth-key"
client = deepl.DeepLClient(auth_key)
# With custom proxy
client = deepl.DeepLClient(
auth_key,
proxy="http://user:pass@10.10.1.10:3128"
)
# With custom server URL
client = deepl.DeepLClient(
auth_key,
server_url="http://localhost:3000"
)
# Register app info
client.set_app_info("my_app", "1.0.0")
```
--------------------------------
### Managing custom instructions
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
Provides examples for creating, getting, updating, and deleting custom instructions for a style rule, including setting a label and prompt.
```python
# Create a custom instruction
instruction = deepl_client.create_style_rule_custom_instruction(
"YOUR_STYLE_ID",
label="Formal tone",
prompt="Always use formal language",
)
print(f"Created instruction: {instruction.id}")
# Get a custom instruction
instruction = deepl_client.get_style_rule_custom_instruction(
"YOUR_STYLE_ID", instruction.id
)
# Update a custom instruction
updated = deepl_client.update_style_rule_custom_instruction(
"YOUR_STYLE_ID",
instruction.id,
label="Updated label",
prompt="Use very formal language",
)
# Delete a custom instruction
deep_client.delete_style_rule_custom_instruction(
"YOUR_STYLE_ID", instruction.id
)
```
--------------------------------
### DocumentNotReadyException Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example demonstrating DocumentNotReadyException and how to handle it.
```python
handle = client.translate_document_upload(document, target_lang="DE")
# Check status manually
status = client.translate_document_get_status(handle)
if not status.done:
try:
# Try to download before it's ready
client.translate_document_download(handle, output_file)
except deepl.DocumentNotReadyException as e:
print(f"Document not ready yet: {e}")
# Use wait_until_done instead
status = client.translate_document_wait_until_done(handle)
```
--------------------------------
### GlossaryNotFoundException Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example of how to catch and handle a GlossaryNotFoundException.
```python
try:
glossary = client.get_glossary("nonexistent-id")
except deepl.GlossaryNotFoundException as e:
print(f"Glossary not found: {e}")
glossaries = client.list_glossaries()
print("Available glossaries:")
for g in glossaries:
print(f" - {g.name} ({g.glossary_id})")
```
--------------------------------
### Use with mock server
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Python code example demonstrating how to initialize the DeepL client to use a mock server for testing.
```python
import deepl
# Use with mock server
client = deepl.DeepLClient(
auth_key="test-key",
server_url="http://localhost:3000"
)
# Make requests without consuming quota
result = client.translate_text("Hello", target_lang="DE")
```
--------------------------------
### Show Help
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/voice/cli/README.md
Displays the help message for the command-line arguments.
```shell
uv run python deepl-voice-api-cli.py --help
# or
poetry run python deepl-voice-api-cli.py --help
```
--------------------------------
### Mustache template example
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/mustache/README.md
An example of a Mustache template with embedded HTML tags.
```text
Hello {{name}}. You have just won {{value}} dollars!
```
--------------------------------
### Proxy Configuration - String Format
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Examples of configuring HTTP proxies using a string format.
```python
# Simple proxy
client = deepl.DeepLClient(
auth_key,
proxy="http://proxy.example.com:3128"
)
# Proxy with authentication
client = deepl.DeepLClient(
auth_key,
proxy="http://user:password@proxy.example.com:3128"
)
# HTTPS proxy
client = deepl.DeepLClient(
auth_key,
proxy="https://proxy.example.com:3128"
)
```
--------------------------------
### ValueError Example - Authentication Key
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example of catching a ValueError for an empty authentication key.
```python
try:
client = deepl.DeepLClient("") # Empty auth key
except ValueError as e:
print(f"Invalid parameter: {e}")
```
--------------------------------
### Application Information Registration
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Examples of how to register application information to be sent in the User-Agent header.
```python
import deepl
client = deepl.DeepLClient(auth_key)
# Register application info (sent in User-Agent header)
client.set_app_info("MyApplication", "1.2.3")
# Chaining syntax
client = deepl.DeepLClient(auth_key).set_app_info("MyApp", "1.0.0")
```
--------------------------------
### Multilingual Glossary Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/utilities.md
Example of creating and using a multilingual glossary with multiple language pairs.
```python
import deepl
from deepl import MultilingualGlossaryDictionaryEntries
client = deepl.DeepLClient("auth-key")
# Create glossary with multiple language pairs
en_de_entries = {"hello": "hallo", "goodbye": "auf wiedersehen"}
en_fr_entries = {"hello": "bonjour", "goodbye": "au revoir"}
dicts = [
MultilingualGlossaryDictionaryEntries("EN", "DE", en_de_entries),
MultilingualGlossaryDictionaryEntries("EN", "FR", en_fr_entries)
]
glossary = client.create_multilingual_glossary("Greetings", dicts)
# Translate to German
result_de = client.translate_text(
"Hello world",
source_lang="EN",
target_lang="DE",
glossary=glossary
)
# Translate to French
result_fr = client.translate_text(
"Hello world",
source_lang="EN",
target_lang="FR",
glossary=glossary
)
```
--------------------------------
### Create a glossary
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Examples for creating both monolingual and multilingual glossaries.
```python
# monolingual glossary example
glossary_info = deepl_client.create_glossary("My Glossary", "EN", "DE", {"hello": "hallo"})
# multilingual glossary example
glossary_dicts = [MultilingualGlossaryDictionaryEntries("EN", "DE", {"hello": "hallo"})]
glossary_info = deepl_client.create_multilingual_glossary("My Glossary", glossary_dicts)
```
--------------------------------
### AuthorizationException Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example showing how to catch AuthorizationException and handle authentication failures.
```python
try:
client = deepl.DeepLClient("invalid-key")
client.get_usage()
except deepl.AuthorizationException as e:
print(f"Authorization failed: {e}")
# Handle auth error - check API key configuration
```
--------------------------------
### Enable Certificate Verification (Default)
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Examples showing how to enable SSL certificate verification, which is the default behavior.
```python
# Default behavior - verify SSL certificates
client = deepl.DeepLClient(auth_key)
# Explicitly enable
client = deepl.DeepLClient(auth_key, verify_ssl=True)
```
--------------------------------
### Update Multilingual Glossary Dictionary Example
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Example of how to update or create glossary dictionary entries.
```python
entries = {"artist": "Maler", "hello": "guten tag"}
dictionaries = [MultilingualGlossaryDictionaryEntries("EN", "DE", entries)]
my_glossary = deepl_client.create_multilingual_glossary(
"My glossary",
dictionaries
)
new_entries = {"hello": "hallo", "prize": "Gewinn"}
glossary_dict = MultilingualGlossaryDictionaryEntries("EN", "DE", new_entries)
updated_glossary = deepl_client.update_multilingual_glossary_dictionary(
my_glossary,
glossary_dict
)
entries_response = deepl_client.get_multilingual_glossary_entries(my_glossary, "EN", "DE")
print(entries_response.dictionaries[0]) # "{'artist': 'Maler', 'hello': 'hallo', 'prize': 'Gewinn'}"
```
--------------------------------
### DocumentTranslationException Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example of how to catch and handle a DocumentTranslationException.
```python
try:
status = client.translate_document_from_filepath(
"input.docx",
"output.docx",
target_lang="DE"
)
except deepl.DocumentTranslationException as e:
print(f"Document translation failed: {e}")
handle = e.document_handle
print(f"Document ID: {handle.document_id}")
print(f"Document key: {handle.document_key}")
# Contact support with this information
except deepl.DeepLException as e:
# Handle other errors (upload failure, etc.)
print(f"Error: {e}")
```
--------------------------------
### Proxy Configuration - Dictionary Format
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Examples of configuring HTTP proxies using a dictionary format for different HTTP and HTTPS proxies.
```python
# Different proxies for HTTP and HTTPS
client = deepl.DeepLClient(
auth_key,
proxy={
"http": "http://proxy.example.com:3128",
"https": "https://proxy.example.com:3128"
}
)
# With authentication
client = deepl.DeepLClient(
auth_key,
proxy={
"http": "http://user:pass@proxy.example.com:3128",
"https": "http://user:pass@proxy.example.com:3128"
}
)
```
--------------------------------
### Usage Example for MultilingualGlossaryDictionaryEntriesResponse
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of how to use the MultilingualGlossaryDictionaryEntriesResponse to iterate through glossary entries.
```python
response = client.get_multilingual_glossary_entries(glossary, "EN", "DE")
for dict_entry in response.dictionaries:
for source, target in dict_entry.entries.items():
print(f"{source} → {target}")
```
--------------------------------
### Translate Document Examples
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Examples demonstrating the usage of the translate_document_from_filepath function for simple translation, with source language and formality, and with a timeout.
```python
# Simple document translation
status = client.translate_document_from_filepath(
"document.docx",
"document_de.docx",
target_lang="DE"
)
print(f"Billed characters: {status.billed_characters}")
# With source language and formality
status = client.translate_document_from_filepath(
"input.pdf",
"output.pdf",
source_lang="EN",
target_lang="FR",
formality="more"
)
# With timeout
status = client.translate_document_from_filepath(
"manual.docx",
"manual_es.docx",
target_lang="ES",
timeout_s=300 # Wait up to 5 minutes
)
```
--------------------------------
### QuotaExceededException Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example demonstrating how to catch QuotaExceededException and display usage information.
```python
try:
result = client.translate_text("Large text...", target_lang="DE")
except deepl.QuotaExceededException as e:
print(f"Quota exceeded: {e}")
usage = client.get_usage()
if usage.character.valid:
print(f"Used: {usage.character.count}/{usage.character.limit} characters")
```
--------------------------------
### Basic usage example
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
Import the package and construct a DeepLClient. The first argument is a string containing your API authentication key. Be careful not to expose your key, for example when sharing source code.
```python
import deepl
auth_key = "f63c02c5-f056-..." # Replace with your key
deep_client = deepl.DeepLClient(auth_key)
result = deepl_client.translate_text("Hello, world!", target_lang="FR")
print(result.text) # "Bonjour, le monde !"
```
--------------------------------
### Install the library using pip
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
The library can be installed from PyPI using pip.
```shell
pip install --upgrade deepl
```
--------------------------------
### Manual Server URL Override
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Examples for overriding the server URL for testing or custom deployments.
```python
# Testing with mock server
client = deepl.DeepLClient(
"test-key",
server_url="http://localhost:3000"
)
# Custom proxy server
client = deepl.DeepLClient(
"auth-key",
server_url="http://deepl-proxy.internal:8080"
)
```
--------------------------------
### Run Mustache translator
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/mustache/README.md
Command to run the Mustache translator with a target language and input text.
```bash
python examples/mustache --to de "Hello {{name}}"
```
--------------------------------
### Update Multilingual Glossary Name Example
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Example of how to update the name of an existing glossary.
```python
updated_glossary = deepl_client.update_multilingual_glossary_name("4c81ffb4-2e...", "New Glossary Name")
```
--------------------------------
### Certificate Pinning
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Example of configuring the DeepL client with certificate pinning for enhanced security.
```python
# Download DeepL's certificate
# Place it in your application
cert_path = "/path/to/deepl-cert.pem"
client = deepl.DeepLClient(
auth_key,
verify_ssl=cert_path
)
```
--------------------------------
### Language Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Demonstrates fetching target languages and checking their properties.
```python
languages = client.get_target_languages()
for lang in languages:
print(f"{lang.name} ({lang.code})")
if lang.supports_formality:
print(" - Supports formality")
```
--------------------------------
### DeepLException Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example demonstrating how to catch DeepLException and check its properties like should_retry and http_status_code.
```python
import deepl
try:
result = client.translate_text("Hello", target_lang="INVALID")
except deepl.DeepLException as e:
print(f"Error: {e}")
if e.should_retry:
print("This is a transient error, retry recommended")
if e.http_status_code:
print(f"HTTP status: {e.http_status_code}")
```
--------------------------------
### Custom User-Agent Override
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Example showing how a custom user_agent string overrides the default application info.
```text
deepl-python/1.30.0 (Platform: Linux/Python 3.9) MyApplication/1.2.3
```
```python
deepl.http_client.user_agent = "CustomAgent/1.0"
client = deepl.DeepLClient(auth_key)
client.set_app_info("MyApp", "1.0") # This has no effect now
```
--------------------------------
### ValueError Example - Empty Text
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example of catching a ValueError for empty text to translate.
```python
try:
result = client.translate_text("", target_lang="DE") # Empty text
except ValueError as e:
print(f"Invalid parameter: {e}")
```
--------------------------------
### Update Multilingual Glossary Dictionary from CSV Example
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Example of how to update or create a glossary dictionary using entries in CSV format.
```python
# Replace a glossary dictionary from CSV
# Open the CSV file assuming UTF-8 encoding. If your file contains a BOM,
# consider using encoding='utf-8-sig' instead.
with open('/path/to/glossary_file.csv', 'r', encoding='utf-8') as csv_file:
csv_data = csv_file.read() # Read the file contents as a string
my_csv_glossary = deepl_client.update_multilingual_glossary_dictionary_from_csv(
glossary="4c81ffb4-2e...",
source_lang="EN",
target_lang="DE",
csv_data=csv_data,
)
```
--------------------------------
### Set DeepL auth key environment variable
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/mustache/README.md
How to set the DeepL authentication key as an environment variable.
```bash
export DEEPL_AUTH_KEY=f63c02c5-f056-...
```
--------------------------------
### Usage Example for TranslationMemoryInfo
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of listing translation memories and using one for translation.
```python
memories = client.list_translation_memories()
for tm in memories:
print(f"{tm.name}: {tm.source_language} → {', '.join(tm.target_languages)}")
result = client.translate_text(
"Hello",
target_lang="DE",
translation_memory=tm,
translation_memory_threshold=75
)
```
--------------------------------
### Rephrase Text Examples
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Examples demonstrating the usage of the rephrase_text function for simple improvement, variant conversion, and with style/tone parameters.
```python
# Simple improvement
result = client.rephrase_text("A rainbouw has seven colours.")
print(result.text) # Corrected text
# Variant conversion
result = client.rephrase_text(
"I am on vacation.",
target_lang="EN-GB"
)
# With style
result = client.rephrase_text(
"Hi, how are you?",
style="business"
)
# With tone
result = client.rephrase_text(
"The project is complete.",
tone="enthusiastic"
)
# Multiple texts
results = client.rephrase_text(
["Theres a mispelling.", "I are happy."],
style="casual"
)
```
--------------------------------
### Multilingual Glossary Deletion Example
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Example of how to list and delete a multilingual glossary.
```python
glossaries = deepl_client.list_multilingual_glossaries()
for glossary in glossaries:
if glossary.name == "Old glossary":
deepl_client.delete_multilingual_glossary(glossary)
```
--------------------------------
### DocumentHandle Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Demonstrates uploading a document, checking its status, and downloading the translation.
```python
with open("doc.docx", "rb") as f:
handle = client.translate_document_upload(f, target_lang="DE")
status = client.translate_document_get_status(handle)
if status.done:
client.translate_document_download(handle, open("out.docx", "wb"))
```
--------------------------------
### CLI Text Translation Example
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
Example of translating text using the CLI. Text arguments should be quoted.
```shell
python3 -m deepl --auth-key=YOUR_AUTH_KEY text --to=DE "Text to be translated."
```
--------------------------------
### Monolingual Glossary Deletion Example
Source: https://github.com/deeplcom/deepl-python/blob/main/upgrading_to_multilingual_glossaries.md
Example of how to list and delete a monolingual glossary.
```python
glossaries = deepl_client.list_glossaries()
for glossary in glossaries:
if glossary.name == "Old glossary":
deepl_client.delete_glossary(glossary)
```
--------------------------------
### Run the JSON translator
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/json/README.md
This command runs the JSON translator script with a target language and a JSON input.
```bash
python examples/json --to de '{"greeting": "Hello!"}'
```
--------------------------------
### Install dependencies using poetry
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
If you need to modify this source code, install the dependencies using poetry.
```shell
poetry install
```
--------------------------------
### Example JSON input
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/json/README.md
This JSON object demonstrates the structure and types of values that can be translated.
```json
{
"greeting": "Good morning!",
"messages": [
"This is a message.",
{
"text": "Here is an embedded text.",
"sent": false
},
null
],
"active": true,
"balance": 100.0
}
```
--------------------------------
### Automatic Server URL Detection
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Examples showing how the client automatically detects the server URL based on the authentication key format.
```python
# Free account (key ends with ":fx")
client = deepl.DeepLClient("key:fx")
# Uses: https://api-free.deepl.com
# Pro account (no special suffix)
client = deepl.DeepLClient("key")
# Uses: https://api.deepl.com
```
--------------------------------
### Set DeepL Auth Key
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/voice/cli/README.md
Sets the DeepL authentication key as an environment variable.
```shell
export DEEPL_AUTH_KEY=your-api-key-here
```
--------------------------------
### Create a Style Rule
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
Example of creating a new style rule with a name and language code.
```python
style_rule = deepl_client.create_style_rule(
name="My Style Rule",
language="en",
)
print(f"Created: {style_rule.name} ({style_rule.style_id})")
```
--------------------------------
### TextResult Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Demonstrates how to access properties of a TextResult object.
```python
result = client.translate_text("Hello", target_lang="FR")
print(result.text) # "Bonjour"
print(result.detected_source_lang) # "EN"
print(result.billed_characters) # 5
```
--------------------------------
### Translate Audio File
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/voice/cli/README.md
Translates an audio file to specified target languages using uv or poetry.
```shell
uv run python deepl-voice-api-cli.py audio.mp3 de fr
# or
poetry run python deepl-voice-api-cli.py audio.mp3 de fr
```
--------------------------------
### Live Microphone Translation
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/voice/cli/README.md
Performs live translation from microphone input to a specified target language.
```shell
uv run python deepl-voice-api-cli.py - es
# or
poetry run python deepl-voice-api-cli.py - es
```
--------------------------------
### set_app_info()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Register the client library as being used by an application. Information is sent in the User-Agent header with API requests. Includes an example usage.
```python
def set_app_info(
self,
app_info_name: str,
app_info_version: str
) -> DeepLClient
```
```python
client = deepl.DeepLClient(auth_key).set_app_info("my_app", "1.0.0")
```
--------------------------------
### Custom CA Certificate Bundle
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Example for using a custom CA bundle for SSL certificate verification, useful for self-signed certificates.
```python
# Use custom CA bundle for self-signed certificates
client = deepl.DeepLClient(
auth_key,
verify_ssl="/path/to/ca-bundle.crt"
)
# Or with environment variable
import os
ca_bundle = os.environ.get("REQUESTS_CA_BUNDLE")
client = deepl.DeepLClient(auth_key, verify_ssl=ca_bundle)
```
--------------------------------
### Rate Limiting Configuration
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
The library automatically handles rate limiting with exponential backoff. Example of changing the retry count.
```python
# Default: up to 5 retries
# Change retry count
deep.http_client.max_network_retries = 10
client = deepl.DeepLClient(auth_key)
```
--------------------------------
### TypeError Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Demonstrates handling a TypeError when an incorrect parameter type is provided.
```python
try:
result = client.translate_text(123, target_lang="DE") # Not a string
except TypeError as e:
print(f"Invalid type: {e}")
```
--------------------------------
### Configure client for mock server
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Command-line configuration to point the DeepL client to a local mock server for testing.
```bash
# Start mock server (in separate terminal)
# See: https://github.com/DeepLcom/deepl-mock
# Configure client for mock server
python -m deepl \
--server-url http://localhost:3000 \
text --to=DE "Hello"
```
--------------------------------
### List Glossary Language Pairs
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
Example of listing supported language pairs for glossaries.
```python
glossary_languages = deepl_client.get_glossary_languages()
for language_pair in glossary_languages:
print(f"{language_pair.source_lang} to {language_pair.target_lang}")
# Example: "EN to DE", "DE to EN", etc.
```
--------------------------------
### DocumentStatus Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Shows how to check the status of a document translation and handle potential errors.
```python
status = client.translate_document_wait_until_done(handle)
if status.ok and status.done:
print(f"Billed: {status.billed_characters}")
else:
print(f"Error: {status.error_message}")
```
--------------------------------
### Disable Certificate Verification
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Example for disabling SSL certificate verification. A warning is included about the security implications.
```python
# Disable SSL verification (not recommended for production)
client = deepl.DeepLClient(auth_key, verify_ssl=False)
```
--------------------------------
### WritingTone Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of how to use the WritingTone enum in a rephrase_text call.
```python
result = client.rephrase_text(
"The project was completed.",
tone=WritingTone.ENTHUSIASTIC
)
```
--------------------------------
### WritingStyle Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of how to use the WritingStyle enum in a rephrase_text call.
```python
result = client.rephrase_text(
"Hey, what's up?",
style=WritingStyle.BUSINESS
)
```
--------------------------------
### Mustache template with placeholder XML tags
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/mustache/README.md
The Mustache template modified with placeholder XML tags for translation.
```xml
Hello . You have just won dollars!
```
--------------------------------
### ModelType Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of how to use the ModelType enum in a translate_text call.
```python
result = client.translate_text(
text,
target_lang="EN",
model_type=ModelType.QUALITY_OPTIMIZED
)
print(f"Model used: {result.model_type_used}") # Set if model_type was specified
```
--------------------------------
### SplitSentences Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of how to use the SplitSentences enum in a translate_text call.
```python
result = client.translate_text(
"One sentence.\nAnother sentence.",
target_lang="FR",
split_sentences=SplitSentences.NO_NEWLINES
)
```
--------------------------------
### Keyring Integration with CLI
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Using keyring with the DeepL Python CLI.
```bash
# Store key in keyring
python -c "import keyring; keyring.set_password('deepl', 'DEEPL_AUTH_KEY', 'your-api-key')"
# Use in CLI (if keyring module available)
python -m deepl text --to=DE "Hello"
```
--------------------------------
### Formality Usage Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/types.md
Example of how to use the Formality enum in a translate_text call.
```python
result = client.translate_text(
"How are you?",
target_lang="DE",
formality=Formality.MORE # "Wie geht es Ihnen?"
)
```
--------------------------------
### Citation Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/README.md
Example of how to cite the DeepL Python Library in documentation.
```text
DeepL Python Library Technical Reference v1.30.0
https://github.com/DeepLcom/deepl-python
```
--------------------------------
### Logging Configuration
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Configure logging to see HTTP requests and responses.
```python
import logging
# Set up logging
logging.basicConfig()
logging.getLogger("deepl").setLevel(logging.DEBUG)
# Now create client
client = deepl.DeepLClient(auth_key)
# All requests and responses will be logged
result = client.translate_text("Hello", target_lang="DE")
```
--------------------------------
### Other Environment Variables
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Configuration of other environment variables for proxy and SSL.
```bash
# HTTP proxy configuration (standard for requests library)
export HTTP_PROXY="http://proxy.example.com:3128"
export HTTPS_PROXY="https://proxy.example.com:3128"
# SSL certificate bundle
export REQUESTS_CA_BUNDLE="/path/to/ca-bundle.crt"
# Python logging
export PYTHONUNBUFFERED=1
```
--------------------------------
### German translation of Mustache template
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/mustache/README.md
The German translation of the example Mustache template.
```text
Hallo {{name}}. Sie haben gerade {{value}} Dollar gewonnen!
```
--------------------------------
### TooManyRequestsException Usage Example with Retries
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/errors.md
Example illustrating how to handle TooManyRequestsException with exponential backoff for retries.
```python
import time
import deepl
max_attempts = 3
for attempt in range(max_attempts):
try:
result = client.translate_text(text, target_lang="FR")
break
except deepl.TooManyRequestsException as e:
if attempt < max_attempts - 1:
wait_time = 2 ** attempt # Exponential backoff
print(f"Rate limited, waiting {wait_time}s...")
time.sleep(wait_time)
else:
raise
```
--------------------------------
### HTTP Client Configuration
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Example of configuring automatic retry behavior and connection timeouts for the HTTP client before creating a DeepL client instance.
```python
import deepl
# Configure before creating client
deepL.http_client.max_network_retries = 3
deepL.http_client.min_connection_timeout = 10.0
deepL.http_client.user_agent = "MyApp/1.0"
# Now create client with custom HTTP settings
client = deepl.DeepLClient(auth_key)
```
--------------------------------
### Example JSON output (translated to German)
Source: https://github.com/deeplcom/deepl-python/blob/main/examples/json/README.md
This JSON object shows the result of translating the input JSON to German.
```json
{
"greeting": "Guten Morgen!",
"messages": [
"Dies ist eine Nachricht.",
{
"text": "Hier ist ein Text eingebettet.",
"sent": false
},
null
],
"active": true,
"balance": 100.0
}
```
--------------------------------
### create_multilingual_glossary()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Create a multilingual glossary supporting multiple language pairs.
```python
def create_multilingual_glossary(
self,
name: str,
glossary_dicts: List[MultilingualGlossaryDictionaryEntries],
) -> MultilingualGlossaryInfo:
"""Create a multilingual glossary supporting multiple language pairs."""
pass
```
```python
from deepl import MultilingualGlossaryDictionaryEntries
entries_en_de = {"artist": "Maler", "prize": "Gewinn"}
entries_en_fr = {"artist": "Artiste", "prize": "Prix"}
dicts = [
MultilingualGlossaryDictionaryEntries("EN", "DE", entries_en_de),
MultilingualGlossaryDictionaryEntries("EN", "FR", entries_en_fr)
]
glossary = client.create_multilingual_glossary("My Glossary", dicts)
print(f"Created: {glossary.name} with {len(glossary.dictionaries)} dictionaries")
```
--------------------------------
### create_glossary()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Create a monolingual glossary from a dictionary of entries.
```python
def create_glossary(
self,
name: str,
source_lang: Union[str, Language],
target_lang: Union[str, Language],
entries: Dict[str, str],
) -> GlossaryInfo:
"""Create a monolingual glossary from a dictionary of entries."""
pass
```
```python
entries = {
"artist": "Maler",
"prize": "Gewinn"
}
glossary = client.create_glossary(
"My Glossary",
"EN",
"DE",
entries
)
print(f"Created: {glossary.name} ({glossary.glossary_id})")
```
--------------------------------
### get_glossary_languages()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Get language pairs supported for glossaries.
```python
def get_glossary_languages(self) -> List[GlossaryLanguagePair]:
pass
```
```python
pairs = client.get_glossary_languages()
for pair in pairs:
print(f"{pair.source_lang} → {pair.target_lang}")
```
--------------------------------
### get_source_languages()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Get list of supported source languages.
```python
def get_source_languages(self, skip_cache: bool = False) -> List[Language]:
pass
```
```python
languages = client.get_source_languages()
for lang in languages:
print(f"{lang.name} ({lang.code})") # "German (DE)"
```
--------------------------------
### server_url property
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Get the API server URL being used.
```python
@property
def server_url(self) -> str
```
--------------------------------
### get_usage()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Get current API usage for this billing period.
```python
def get_usage(self) -> Usage:
pass
```
```python
usage = client.get_usage()
if usage.any_limit_reached:
print("Usage limit reached!")
if usage.character.valid:
print(f"Characters: {usage.character.count}/{usage.character.limit}")
if usage.document.valid:
print(f"Documents: {usage.document.count}/{usage.document.limit}")
```
--------------------------------
### get_target_languages()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
Get list of supported target languages with formality support info.
```python
def get_target_languages(self, skip_cache: bool = False) -> List[Language]:
pass
```
```python
languages = client.get_target_languages()
for lang in languages:
if lang.supports_formality:
print(f"{lang.name} supports formality")
```
--------------------------------
### Platform Information Reporting
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Control whether platform information is included in requests.
```python
# Include platform info (default)
client = deepl.DeepLClient(auth_key, send_platform_info=True)
# User-Agent: deepl-python/1.30.0 (Platform: Linux/Python 3.9)
```
```python
# Exclude platform info for privacy
client = deepl.DeepLClient(auth_key, send_platform_info=False)
# User-Agent: deepl-python/1.30.0
```
--------------------------------
### convert_tsv_to_dict() Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/utilities.md
Parses tab-separated values (TSV) into a glossary entries dictionary.
```python
import deepl
tsv_data = """artist\tMaler
prize\tGewinn
exhibition\tAusstellung"""
entries = deepl.convert_tsv_to_dict(tsv_data)
print(entries)
# Output: {'artist': 'Maler', 'prize': 'Gewinn', 'exhibition': 'Ausstellung'}
# With custom separator
csv_data = "artist,Maler\nprize,Gewinn"
entries = deepl.convert_tsv_to_dict(csv_data, term_separator=",")
```
--------------------------------
### Explicit retry handling for your code
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/configuration.md
Demonstrates how to implement explicit retry logic for handling `TooManyRequestsException` when making API calls.
```python
import time
max_attempts = 3
for attempt in range(max_attempts):
try:
result = client.translate_text(text, target_lang="DE")
break
except deepl.TooManyRequestsException:
if attempt < max_attempts - 1:
time.sleep(2 ** attempt)
else:
raise
```
--------------------------------
### validate_glossary_term() Example
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/utilities.md
Validates that a glossary term doesn't contain disallowed characters.
```python
import deepl
# Valid terms
deep.validate_glossary_term("hello") # OK
deep.validate_glossary_term("naïve") # OK with accents
deep.validate_glossary_term("123") # OK with numbers
# Invalid terms
try:
deepl.validate_glossary_term("") # Empty
except ValueError as e:
print(f"Error: {e}") # 'Term "" is not a valid string'
try:
deepl.validate_glossary_term("hello\x00world") # Contains null
except ValueError as e:
print(f"Error: {e}") # Contains invalid character
```
--------------------------------
### Retrieve a Style Rule
Source: https://github.com/deeplcom/deepl-python/blob/main/README.md
Example of retrieving a single style rule by its ID.
```python
# Get a single style rule by ID
style_rule = deepl_client.get_style_rule("YOUR_STYLE_ID")
print(f"{style_rule.name} ({style_rule.language})")
```
--------------------------------
### get_all_style_rules()
Source: https://github.com/deeplcom/deepl-python/blob/main/_autodocs/deepl-client.md
List all style rules with optional pagination. Includes a table detailing parameters and return types.
```python
def get_all_style_rules(
self,
page: Optional[int] = None,
page_size: Optional[int] = None,
detailed: Optional[bool] = None,
) -> List[StyleRuleInfo]
```