Official Java library for the DeepL language translation API.

Overview

DeepL Java Library

Maven Central 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 Java library offers a convenient way for applications written in Java to interact with the DeepL API. Currently, the library only supports text and document translation; we intend to add support for glossary management soon.

Getting an authentication key

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

Requirements

Java 1.8 or later.

Installation

Gradle users

Add this dependency to your project's build file:

implementation "com.deepl.api:deepl-java:0.2.0"

Maven users

Add this dependency to your project's POM:

<dependency>
  <groupId>com.deepl.api</groupId>
  <artifactId>deepl-java</artifactId>
  <version>0.2.0</version>
</dependency>

Usage

Import the package and construct a Translator. The first argument is a string containing your API authentication key as found in your DeepL Pro Account.

Be careful not to expose your key, for example when sharing source code.

import com.deepl.api.*;

class Example {
    public String basicTranslationExample() throws Exception {
        String authKey = "f63c02c5-f056-...";  // Replace with your key
        Translator translator = new Translator(authKey);
        TextResult result =
                translator.translateText("Hello, world!", null, "fr");
        return result.getText(); // "Bonjour, le monde !"
    }
}

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.

Translator accepts additional options, see Configuration for more information.

Translating text

To translate text, call translateText(). The first argument is a string containing the text you want to translate, or an iterable of strings if you want to translate multiple texts.

sourceLang and targetLang specify the source and target language codes respectively. The sourceLang is optional, if it is null the source language will be auto-detected.

Language codes are case-insensitive strings according to ISO 639-1, for example 'de', 'fr', 'ja''. Some target languages also include the regional variant according to ISO 3166-1, for example 'en-US', or 'pt-BR'. The full list of supported languages is in the API documentation.

There are additional optional arguments to control translation, see Text translation options below.

translateText() returns a TextResult, or a List of TextResults corresponding to your input text(s). TextResult has two accessors: getText() returns the translated text, and getDetectedSourceLanguage() returns the detected source language code.

class Example {
    public void textTranslationExamples() throws Exception {
        // Translate text into a target language, in this case, French:
        TextResult result =
                translator.translateText("Hello, world!", null, "fr");
        System.out.println(result.getText()); // "Bonjour, le monde !"

        // Translate multiple texts into British English
        List<TextResult> results =
                translator.translateText(List.of("お元気ですか?", "¿Cómo estás?"),
                                         null,
                                         "en-GB");
        System.out.println(results.get(0).getText()); // "How are you?"
        System.out.println(results.get(0).getDetectedSourceLanguage()); // "ja" the language code for Japanese
        System.out.println(results.get(1).getText()); // "How are you?"
        System.out.println(results.get(1).getDetectedSourceLanguage()); // "es" the language code for Spanish

        // Translate into German with less and more Formality:
        System.out.println(translator.translateText("How are you?",
                                                    null,
                                                    "de",
                                                    new TextTranslationOptions().setFormality(
                                                            Formality.Less)).getText());  // 'Wie geht es dir?'
        System.out.println(translator.translateText("How are you?",
                                                    null,
                                                    "de",
                                                    new TextTranslationOptions().setFormality(
                                                            Formality.More)).getText());  // 'Wie geht es Ihnen?'
    }
}

Text translation options

In addition to the input text(s) argument, a translateText() overload accepts a TextTranslationOptions, with the following setters:

  • setSentenceSplittingMode(): specify how input text should be split into sentences, default: 'on'.
    • SentenceSplittingMode.All: input text will be split into sentences using both newlines and punctuation.
    • SentenceSplittingMode.Off: input text will not be split into sentences. Use this for applications where each input text contains only one sentence.
    • SentenceSplittingMode.NoNewlines: input text will be split into sentences using punctuation but not newlines.
  • setPreserveFormatting(): controls automatic-formatting-correction. Set to True to prevent automatic-correction of formatting, default: false.
  • setFormality(): controls whether translations should lean toward informal or formal language. This option is only available for some target languages, see Listing available languages.
    • Formality.Less: use informal language.
    • Formality.More: use formal, more polite language.
  • setGlossaryId(): specifies a glossary to use with translation, as a string containing the glossary ID.
  • setTagHandling(): type of tags to parse before translation, options are "html" and "xml".

The following options are only used if setTagHandling() is set to 'xml':

  • setOutlineDetection(): specify false to disable automatic tag detection, default is true.
  • setSplittingTags(): list of XML tags that should be used to split text into sentences. Tags may be specified as an array of strings (['tag1', 'tag2']), or a comma-separated list of strings ('tag1,tag2'). The default is an empty list.
  • setNonSplittingTags(): list of XML tags that should not be used to split text into sentences. Format and default are the same as for splitting tags.
  • setIgnoreTags(): list of XML tags that containing content that should not be translated. Format and default are the same as for splitting tags.

For a detailed explanation of the XML handling options, see the API documentation.

Translating documents

To translate documents, call translateDocument() File objects. The first and second arguments correspond to the input and output files respectively.

Just as for the translateText() function, the sourceLang and targetLang arguments specify the source and target language codes.

There are additional optional arguments to control translation, see Document translation options below.

class Example {
    public void documentTranslationExamples() throws Exception {
        // Translate a formal document from English to German
        File inputFile = new File("/path/to/Instruction Manual.docx");
        File outputFile = new File("/path/to/Bedienungsanleitung.docx");
        try {
            translator.translateDocument(inputFile, outputFile, "en", "de");
        } catch (DocumentTranslationException exception) {
            // If an error occurs during document translation after the document was
            // already uploaded, a DocumentTranslationException is thrown. The
            // document_handle property contains the document handle that may be used to
            // later retrieve the document from the server, or contact DeepL support.
            DocumentHandle handle = exception.getHandle();
            System.out.printf(
                    "Error after uploading %s, document handle: id: %s key: %s",
                    exception.getMessage(),
                    handle.getDocumentId(),
                    handle.getDocumentKey());
        }
    }
}

translateDocument() is a convenience function that wraps multiple API calls: uploading, polling status until the translation is complete, and downloading. If your application needs to execute these steps individually, you can instead use the following functions directly:

  • translateDocumentUpload(),
  • translateDocumentGetStatus() (or translateDocumentWaitUntilDone()), and
  • translateDocumentDownload()

Document translation options

In addition to the input file, output file, sourceLang and targetLang arguments, the available translateDocument() setters are:

Checking account usage

To check account usage, use the getUsage() function.

The returned Usage object contains three usage subtypes: character, document and teamDocument. Depending on your account type, some usage subtypes may be null. For API accounts:

  • usage.character is non-null,
  • usage.document and usage.teamDocument are null.

Each usage subtype (if valid) has count and limit properties giving the amount used and maximum amount respectively, and the limit_reached property that checks if the usage has reached the limit. The top level Usage object has the any_limit_reached property to check all usage subtypes.

class Example {
    public void getUsageExample() throws Exception {
        Usage usage = translator.getUsage();
        if (usage.anyLimitReached()) {
            System.out.println("Translation limit reached.");
        }
        if (usage.getCharacter() != null) {
            System.out.printf("Character usage: %d of %d%n",
                              usage.getCharacter().getCount(),
                              usage.getCharacter().getLimit());
        }
        if (usage.getDocument() != null) {
            System.out.printf("Document usage: %d of %d%n",
                              usage.getDocument().getCount(),
                              usage.getDocument().getLimit());
        }
    }
}

Listing available languages

You can request the list of languages supported by DeepL for text and documents using the getSourceLanguages() and getTargetLanguages() functions. They both return a list of Language objects.

The name property gives the name of the language in English, and the code property gives the language code. The supportsFormality property only appears for target languages, and indicates whether the target language supports the optional formality parameter.

class Example {
    public void getLanguagesExample() throws Exception {
        List<Language> sourceLanguages = translator.getSourceLanguages();
        List<Language> targetLanguages = translator.getTargetLanguages();
        System.out.println("Source languages:");
        for (Language language : sourceLanguages) {
          System.out.printf("%s (%s)%n",
                            language.getName(),
                            language.getCode()); // Example: "German (de)"
        }

        System.out.println("Target languages:");
        for (Language language : targetLanguages) {
            if (language.getSupportsFormality()) {
                System.out.printf("%s (%s) supports formality%n",
                                  language.getName(),
                                  language.getCode()); // Example: "Italian (it) supports formality"

          } else {
                System.out.printf("%s (%s)%n",
                                  language.getName(),
                                  language.getCode()); // Example: "Lithuanian (lt)"
          }
        }
    }
}

Exceptions

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

Configuration

The Translator constructor accepts TranslatorOptions as a second argument, for example:

class Example {
    public void configurationExample() throws Exception {
        TranslatorOptions options =
                new TranslatorOptions().setMaxRetries(1).setTimeout(Duration.ofSeconds(
                        1));
        Translator translator = new Translator(authKey, options);
    }
}

The available options setters are:

  • setMaxRetries(): maximum number of failed HTTP requests to retry, the default is 5. Note: only failures due to transient conditions are retried e.g. timeouts or temporary server overload.
  • setTimeout(): connection timeout for each HTTP request.
  • setProxy(): provide details about a proxy to use for all HTTP requests to DeepL.
  • setHeaders(): additional HTTP headers to attach to all requests.
  • setServerUrl(): base URL for DeepL API, may be overridden for testing purposes. By default, the correct DeepL API (Free or Pro) is automatically selected.

Issues

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

Development

We welcome Pull Requests, please read the contributing guidelines.

Tests

Execute the tests using ./gradlew test. 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 ./gradlew test with the DEEPL_MOCK_SERVER_PORT and DEEPL_SERVER_URL environment variables defined referring to the mock-server.

You might also like...

MFP (Mathematic language For Parallel computing) Android library

MFPAndroLib This is MFP (Mathematic language For Parallel computing) Android library project. MFP is a novel scripting programming language designed a

Sep 5, 2022

Very spicy additions to the Java programming language.

Project Lombok Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another g

Dec 30, 2022

A list of direct references to classes and interfaces in the Java Language Specification (3d Ed.)

A list of direct references to classes and interfaces in the Java Language Specification (3d Ed.) and a program to compute the indirectly required classes and interfaces

Jun 3, 2022

A dubbo gateway based Java language.

A dubbo gateway based Java language.

Sep 24, 2022

Java Compiler for the MiniJava language

Java Compiler for the MiniJava language Setup Our project requires the following tools with the specified versions. Tool Version Java = 14 Maven 3 Th

Dec 5, 2022

Scripting language written in, and, designed to communicate with, java

Scripting language written in, and, designed to communicate with, java

mi-lang Scripting language designed to communicate with java, to allow for easy plugins, addons, etc in any project, all without having to create an e

Dec 17, 2022

Representational State Transfer + Structured Query Language(RSQL): Demo application using RSQL parser to filter records based on provided condition(s)

Representational State Transfer + Structured Query Language: RSQL Demo application using RSQL parser to filter records based on provided condition(s)

Nov 23, 2022

Metremenqeemi - Android/iOS app to teach the Coptic Language

ⲙⲉⲧⲣⲉⲙⲛ̀ⲭⲏⲙⲓ The Open Source Android/iOS app to learn how to read and understand the Coptic Language Join our Discord Channel About the Curriculum The

Aug 30, 2022

Unofficial community-built app for the Japanese language learning tool jpdb.io.

jpdb-android Unofficial community-built app for the Japanese language learning tool jpdb.io. While the web app works in most scenarios, the goal with

Feb 15, 2022
Comments
  • About glossary management

    About glossary management

    There seems to be no implementation of glossary management, is there any plan to implement it in the future? Or is it possible to make a contribution?

    openapi has it.

    opened by himeyon 6
  • SentenceSplittingMode.All ignored

    SentenceSplittingMode.All ignored

    As per-title, the only place reading the SentenceSplittingMode ignores the All value, which is useful when setting the tag handing to html.

    https://github.com/DeepLcom/deepl-java/blob/63536dc9d0c21472c8cf20fa1acbd7c8bad1d608/deepl-java/src/main/java/com/deepl/api/Translator.java#L769

    Maybe it's because the default has changed since november 2022 as stated in https://www.deepl.com/docs-api/translate-text/translate-text/:

    The use of nonewlines as the default value for text translations where tag_handling=html is new behavior that was implemented in November 2022, when HTML handling was moved out of beta.

    I have tried to request a translation through a curl request for the same input and the result is just fine.

    opened by nicStuff 3
  • deepl-java-0.2.1 and gson

    deepl-java-0.2.1 and gson

    Hello, Thanks for the 0.2.1 version. I'm integrating your library 0.2.1 in a maven project and here is what I notice :

    • the you cite in the README works but does not automatically include a dependency to gson, which needs to be included by hand with another .
    • deepl-java-0.2.1 doesn't work with last version of gson (2.9.1). I make it work with gson 2.8.5, already used by deepl-java-0.2.0 Thierry
    opened by tig12 1
Releases(v1.0.1)
Owner
DeepL
Helping people overcome communication barriers since 2017.
DeepL
Jamal is a macro language (JAmal MAcro Language)

Jamal Macro Language Jamal is a complex text processor with a wide variety of possible use. The first version of Jamal was developed 20 years ago in P

Peter Verhas 29 Dec 20, 2022
For Jack language. Most of codes were commented with their usage, which can be useful for beginner to realize the running principle of a compiler for object-oriented programming language.

Instructions: Download the Java source codes Store these codes into a local folder and open this folder Click the right key of mouse and click ‘Open i

gooooooood 1.1k Jan 5, 2023
Official Elasticsearch Java Client

Elasticsearch Java Client The official Java client for Elasticsearch. Note: this project is still a work in progress. This client is meant to replace

elastic 230 Jan 8, 2023
Catogram - Experimental telegram client based on official Android sources

Catogram Experimental telegram client based on official Android sources Features: Message translator TGX Style of context menu VKUI Icons and inbuilt

null 188 Dec 17, 2022
ZerotierFix - An unofficial Zerotier Android client patched from official client

Zerotier Fix An unofficial Zerotier Android client patched from official client. Features Self-hosted Moon Support Add custom planet config via file a

KAAAsS 830 Jan 8, 2023
This is the official theme SDK for the FairPlayer Music Player for Android.

FairPlayer - Themes SDK This is the official theme SDK for the FairPlayer Music Player for Android. You can download the most recent version of FairPl

Mark Jivko 0 Jan 31, 2022
Patches for the old minecraft official launcher to add microsoft account support

MSA4Legacy Patches for the old minecraft official launcher to add microsoft account support My code here is quite atrocious in some parts (for example

Nep Nep 26 Nov 3, 2022
Official React Native client for FingerprintJS PRO. 100% accurate device identification for fraud detection.

FingerprintJS PRO React Native Official React Native module for 100% accurate device identification, created for the FingerprintJS Pro Server API. Thi

FingerprintJS 26 Nov 22, 2022
Official Quilt template mod.

Quilt Template Mod The official Quilt template Mod. You can use it as a template for your own mods! Usage In order to use this mod as a template: Crea

null 117 Jan 2, 2023
Official Quilt template mod.

Quilt Template Mod The official Quilt template Mod. You can use it as a template for your own mods! Usage In order to use this mod as a template: Crea

null 32 May 7, 2022