Skip to main content

Python library for the DeepL API.

Project description

DeepL Python Library

PyPI version Supported Python versions License: MIT

The DeepL API is a language translation API that allows other computer programs to send texts and documents to DeepL's servers and receive high-quality translations. This opens a whole universe of opportunities for developers: any translation product you can imagine can now be built on top of DeepL's best-in-class translation technology.

The DeepL Python library offers a convenient way for applications written in Python to interact with the DeepL API. We intend to support all API functions with the library, though support for new features may be added to the library after they’re added to the API.

Getting an authentication key

To use the DeepL Python Library, you'll need an API authentication key. To get a key, please create an account here. You can translate up to 500,000 characters/month for free.

After you have created an account, you can find your API authentication key on your DeepL Pro Account.

Installation

The library can be installed from PyPI using pip:

pip install --upgrade deepl

If you need to modify this source code, install the dependencies using poetry:

poetry install

Requirements

The library is tested with Python versions 3.6 to 3.10.

The requests module is used to perform HTTP requests; the minimum is version 2.0.

Usage

import deepl

# Create a Translator object providing your DeepL API authentication key.
# Be careful not to expose your key, for example when sharing source code.
auth_key = "f63c02c5-f056-..."  # Replace with your key
translator = deepl.Translator(auth_key)
# This example is for demonstration purposes only. In production code, the
# authentication key should not be hard-coded, but instead fetched from a
# configuration file or environment variable.

# Translate text into a target language, in this case, French
result = translator.translate_text("Hello, world!", target_lang="FR")
print(result)  # "Bonjour, le monde !"
# Note: printing or converting the result to a string uses the output text

# Translate multiple texts into British English
result = translator.translate_text(["お元気ですか?", "¿Cómo estás?"], target_lang="EN-GB")
print(result[0].text)  # "How are you?"
print(result[0].detected_source_lang)  # "JA"
print(result[1].text)  # "How are you?"
print(result[1].detected_source_lang)  # "ES"

# Translate a formal document from English to German 
try:
    translator.translate_document_from_filepath(
        "Instruction Manual.docx",
        "Bedienungsanleitung.docx",
        target_lang="DE",
        formality="more"
    )
except deepl.DocumentTranslationException as error:
    # If an error occurs during translate_document_from_filepath() or
    # translate_document() and after the document was already uploaded, a 
    # DocumentTranslationException is raised. The document_handle property
    # contains the document handle to later retrieve the document or contact
    # DeepL support.
    doc_id = error.document_handle.id
    doc_key = error.document_handle.key
    print(f"Error after uploading document ${error}, id: ${doc_id} key: ${doc_key}")
except deepl.DeepLException as error:
    # Errors during upload raise a DeepLException
    print(error)

# Glossaries allow you to customize your translations
glossary_en_to_de = translator.create_glossary(
    "My glossary",
    source_lang="EN",
    target_lang="DE",
    entries={"artist": "Maler", "prize": "Gewinn"},
)

with_glossary = translator.translate_text_with_glossary(
    "The artist was awarded a prize.", glossary_en_to_de
)
print(with_glossary)  # "Der Maler wurde mit einem Gewinn ausgezeichnet."

without_glossary = translator.translate_text(
    "The artist was awarded a prize.", target_lang="DE"
)
print(without_glossary)  # "Der Künstler wurde mit einem Preis ausgezeichnet."


# Check account usage
usage = translator.get_usage()
if usage.character.limit_exceeded:
    print("Character limit exceeded.")
else:
    print(f"Character usage: {usage.character.count} of {usage.character.limit}")

# Source and target languages
print("Source languages:")
for language in translator.get_source_languages():
    print(f"{language.code} ({language.name})")  # Example: "DE (German)"

print("Target languages:")
for language in translator.get_target_languages():
    if language.supports_formality:
        print(f"{language.code} ({language.name}) supports formality")
    else:
        print(f"{language.code} ({language.name})")

Exceptions

All module functions may raise deepl.DeepLException or one of its subclasses. If invalid arguments are provided, they may raise the standard exceptions ValueError and TypeError.

Configuration

Logging

Logging can be enabled to see the HTTP-requests sent and responses received by the library. Enable and control logging using Python's logging module, for example:

import logging
logging.basicConfig()
logging.getLogger('deepl').setLevel(logging.DEBUG)

Proxy configuration

You can configure a proxy by specifying the proxy argument when creating a deepl.Translator:

proxy = "http://user:pass@10.10.1.10:3128"
translator = deepl.Translator(..., proxy=proxy)

The proxy argument is passed to the underlying requests session, see the documentation here; a dictionary of schemes to proxy URLs is also accepted.

Command Line Interface

The library can be run on the command line supporting all API functions. Use the --help option for usage information:

python3 -m deepl --help

The CLI requires your DeepL authentication key specified either as the DEEPL_AUTH_KEY environment variable, or using the --auth-key option, for example:

python3 -m deepl --auth-key=YOUR_AUTH_KEY usage

Note that the --auth-key argument must appear before the command argument. The recognized commands are:

Command Description
text translate text(s)
document translate document(s)
usage print usage information for the current billing period
languages print available languages
glossary create, list, and remove glossaries

For example, to translate text:

python3 -m deepl --auth-key=YOUR_AUTH_KEY text --to=DE "Text to be translated."

Wrap text arguments in quotes to prevent the shell from splitting sentences into words.

Issues

If you experience problems using the library, or would like to request a new feature, please open an issue.

Development

We are currently unable to accept Pull Requests. If you would like to suggest changes, please open an issue instead.

Tests

Execute the tests using pytest. The tests communicate with the DeepL API using the auth key defined by the DEEPL_AUTH_KEY environment variable.

Be aware that the tests make DeepL API requests that contribute toward your API usage.

The test suite may instead be configured to communicate with the mock-server provided by deepl-mock. Although most test cases work for either, some test cases work only with the DeepL API or the mock-server and will be otherwise skipped. The test cases that require the mock-server trigger server errors and test the client error-handling. To execute the tests using deepl-mock, run it in another terminal while executing the tests. Execute the tests using pytest with the DEEPL_MOCK_SERVER_PORT and DEEPL_SERVER_URL environment variables defined referring to the mock-server.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

deepl-1.5.1.tar.gz (30.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

deepl-1.5.1-py3-none-any.whl (30.6 kB view details)

Uploaded Python 3

File details

Details for the file deepl-1.5.1.tar.gz.

File metadata

  • Download URL: deepl-1.5.1.tar.gz
  • Upload date:
  • Size: 30.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.13 CPython/3.10.4 Linux/5.13.0-30-generic

File hashes

Hashes for deepl-1.5.1.tar.gz
Algorithm Hash digest
SHA256 eb16bb827038331d4c07252aa4caa016aafa27b4a781e041b41f60d1b0fc10e8
MD5 bf947d70785e27db771ef254fb6bf20f
BLAKE2b-256 88623038e0053ec2d8110ebc99b83c794a22fdae092ac7beb36b1509f427c47d

See more details on using hashes here.

File details

Details for the file deepl-1.5.1-py3-none-any.whl.

File metadata

  • Download URL: deepl-1.5.1-py3-none-any.whl
  • Upload date:
  • Size: 30.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.13 CPython/3.10.4 Linux/5.13.0-30-generic

File hashes

Hashes for deepl-1.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a1fb34f16e0cdcf7b14d5ec7df2cec92d0808edc0bf7c93fbbc45502b295e368
MD5 6d8a60751b4b64eb84b93a6d95f6ae69
BLAKE2b-256 da6ee710a13b0dbdf60b92e2918ab481cf3254abfd55164f0ad2015124d31dc3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page