DeepL Python Library

repository·main·Indexed 23 days ago

https://github.com/deepl/deepl-python

A client wrapper for the DeepL API (version 1.30.0) that allows Python applications to programmatically translate text and documents, improve or rephrase text via the Write API, and manage multilingual glossaries. It supports advanced features such as JSON structure preservation, XML tag-handling for templates, and a bidirectional streaming workflow for real-time audio translation via the DeepL Voice API.

Tokens
10.9K
Snippets
25
Records
70
Agent score
78%

What's inside deepl-python

  1. Translate Mustache templates using XML tag-handling

    main

    Mustache templates often contain embedded tags (e.g., {{name}}) and HTML tags (e.g., <b>) that should not be translated. This example demonstrates a pattern for translating these templates by using DeepL's XML tag-handling capability.

    To prevent the translation engine from altering the Mustache syntax, the process follows these steps:

    1. Parse the template to separate literal text from Mustache tags.
    2. Replace Mustache tags with unique placeholder XML tags (e.g., <m id=0 />).
    3. Translate the resulting XML string via the DeepL API, which preserves the XML structure.
    4. Parse the translated XML and swap the placeholder tags back for the original Mustache tags.

    This ensures that Hello {{name}}. You have just won <b>{{value}} dollars</b>! becomes Hallo {{name}}. Sie haben gerade <b>{{value}} Dollar</b> gewonnen! in German.

  2. How multilingual glossaries work in DeepL

    main

    DeepL has introduced v3 Glossary APIs that move beyond the monolingual model (where a glossary is tied to a single source_lang and target_lang).

    In the new model, a single glossary contains one or more glossary dictionaries. Each dictionary is a self-contained unit with its own source_lang, target_lang, and set of entries. This allows a single glossary object to manage multiple language pairs simultaneously.

    Key data models:

    • MultilingualGlossaryInfo: The top-level object representing the entire glossary, containing a list of MultilingualGlossaryDictionaryInfo objects.
    • MultilingualGlossaryDictionaryEntries: The object used when creating or defining the contents of a specific dictionary within a glossary.
  3. How the DeepL Voice API streaming workflow works

    main

    The CLI demonstrates a bidirectional streaming workflow using WebSockets:

    1. Request a streaming session: A POST request is sent to the DeepL Voice API to obtain a WebSocket URI and an authentication token. This request specifies the source media type, source language (or auto-detection), and target languages.
    2. Connect via WebSocket: A WebSocket connection is established using the obtained URI.
    3. Stream audio data: Audio chunks (from a file or microphone) are sent to the WebSocket as base64-encoded JSON messages.
    4. Receive transcriptions and translations: The API streams back real-time updates containing both tentative (in-progress) and concluded (finalized) transcriptions in the source language and translations in all requested target languages.
    5. Signal completion: An end_of_source_media message is sent to flush the pipeline, allowing the server to finalize processing and send complete transcripts.
  4. Run the Mustache template translation example

    main

    To run the Mustache translator example, follow these steps:

    1. Install the library: Ensure the deepl Python library is installed.
    2. Set Authentication: Define your DeepL authentication key as the DEEPL_AUTH_KEY environment variable.
    3. Execute: Run the script from the project root, specifying the target language with the --to flag.

    Use the --help flag to see available command-line arguments.

  5. Install the DeepL Voice API CLI

    main

    To use the real-time audio translation CLI, you need to install the dependencies using uv or poetry. If you intend to use live microphone input, you must also install the mic dependency group and ensure your system has the necessary pyaudio system packages (e.g., portaudio19-dev on Debian/Ubuntu or portaudio on MacOS).

    Standard Installation:

    cd examples/voice/cli
    uv sync
    # or
    poetry install

    Installation with Microphone Support:

    uv sync --group mic
    # or
    poetry install --with mic
    uv sync --group mic
  6. Run the JSON translator CLI example

    main

    To use the JSON translation example, ensure you have installed the deepl library and set your DEEPL_AUTH_KEY environment variable. You can then run the script from the terminal, passing the target language with --to and the JSON string as an argument.

    export DEEPL_AUTH_KEY=f63c02c5-f056-...
    python examples/json --to de '{"greeting": "Hello!"}'
  7. Install the DeepL Python library

    main

    You can install the library from PyPI using pip. It is recommended to use the --upgrade flag to ensure you have the latest version.

    If you are developing the library itself and need to manage dependencies, use poetry install.

    pip install --upgrade deepl
  8. Get a DeepL API authentication key

    main
    To use the library, you must have an API authentication key. You can obtain one by creating an account on the DeepL website. A DeepL API Free account allows for up to 500,000 characters per month at no cost.
  9. Initialize the DeepLClient

    main

    To use the DeepL API, import the deepl package and instantiate a DeepLClient using your API authentication key. For production environments, it is recommended to fetch the key from an environment variable or configuration file rather than hard-coding it.

    import deepl
    
    auth_key = "YOUR_AUTH_KEY"
    deepl_client = deepl.DeepLClient(auth_key)
    import deepl
    
    auth_key = "f63c02c5-f056-..."  # Replace with your key
    deepl_client = deepl.DeepLClient(auth_key)
    
    result = deepl_client.translate_text("Hello, world!", target_lang="FR")
    print(result.text)  # "Bonjour, le monde !"
  10. Monitor document translation progress with DocumentHandle and DocumentStatus

    main

    When translating documents, you receive a DocumentHandle to track the request. You can use this handle to check the DocumentStatus.

    DocumentStatus provides:

    • status: The current state (see Status enum).
    • seconds_remaining: Estimated time until completion.
    • billed_characters: Characters billed for the document.
    • error_message: Description of any error encountered.

    Use the .ok property to check if the status is not Status.ERROR, and .done to check if it is Status.DONE.

  11. Configure the DeepLClient

    main

    The DeepLClient can be configured with several parameters during instantiation:

    • server_url: Override the default DeepL API URL (useful for testing).
    • proxy: Configure a proxy (string URL or dictionary compatible with requests).
    • verify_ssl: Boolean to enable/disable SSL certificate verification (defaults to True).
    • send_platform_info: Boolean to opt-out of sending anonymous platform information (defaults to True).

    Global Configuration (via deepl.http_client):

    • max_network_retries: Set the number of automatic retries for failed HTTP requests (default is 5).
    • user_agent: Set a custom User-Agent string.
    • min_connection_timeout: Set connection timeout.