Here - a nice DeepL API client library written in Kotlin

Related tags

Kotlin deepl-jvm
Overview

DeepL Kotlin/JavaVM Library

Maven Central CI Build

Here is s a nice DeepL API client library written in Kotlin! The supported Java runtimes are any OpenJDK distributions and Android runtime.

Getting Started

You can start using this library just by adding deepl-jvm dependency to your project.

For Gradle users:

ext.DeepLSDKVersion = "0.1.2"
dependencies {
  implementation("com.github.seratch:deepl-jvm:${DeepLSDKVersion}")
}

For Maven users:

<properties>
  <deepl-sdk.version>0.1.2deepl-sdk.version>
properties>

<dependencies>
  <dependency>
  <groupId>com.github.seratchgroupId>
  <artifactId>deepl-jvmartifactId>
  <version>${deepl-sdk.version}version>
  dependency>
dependencies>

As this library is in Kotlin, using in the same language is the smoothest :) Let's start with the following code ๐Ÿ‘‹

// ----------------------------- // Usage data val usage = client.getUsage() println(usage.characterCount) // ----------------------------- // Text translation val translation = client.translate( text = "ใ“ใ‚“ใซใกใฏ๏ผ็งใฏๅ…ƒๆฐ—ใงใ™ :wave:", targetLang = TargetLanguage.AmericanEnglish, ) println(translation.translations[0].text) assertEquals("Hello! I am fine :wave:", translation.translations[0].text) // ----------------------------- // Document translation val uploadedDocument = client.uploadDocument( file = File("source.docx"), filename = "source.docx", targetLang = TargetLanguage.Japanese, ) assertNotNull(uploadedDocument.documentId) assertNotNull(uploadedDocument.documentKey) while (true) { val res = client.getDocumentStatus( documentId = uploadedDocument.documentId, documentKey = uploadedDocument.documentKey, ) if (res.status == DocumentStatus.Done || res.status == DocumentStatus.Error) { break } val remainingSeconds: Double = if (res.secondsRemaining != null) res.secondsRemaining!!.toDouble() else 0.0 val secondsToSleep = 1.0.coerceAtLeast((remainingSeconds / 2.0).coerceAtMost(60.0)) Thread.sleep(secondsToSleep.toLong()) } val resultFileContentBytes = client.downloadDocument( documentId = uploadedDocument.documentId, documentKey = uploadedDocument.documentKey, ) File("translation-ja.docx").writeBytes(resultFileContentBytes) // ----------------------------- // Glossaries val newGlossary = client.createGlossary( name = "something-new-${System.currentTimeMillis()}", sourceLang = GlossarySourceLanguage.English, targetLang = GlossaryTargetLanguage.German, entries = mapOf("artist" to "Maler", "prize" to "Gewinn") ) assert(newGlossary.glossary.ready) val glossaryId = newGlossary.glossary.glossaryId val glossaries = client.listGlossaries() assert(glossaries.glossaries.isNotEmpty()) val glossary = client.getGlossary(glossaryId) assertNotNull(glossary) val glossaryEntries = client.listGlossaryEntries(glossaryId) assertNotNull(glossaryEntries) val deletion = client.deleteGlossary(glossaryId) assertNotNull(deletion) } }">
package integration_tests

import deepl.api.v2.DeepLClient
import deepl.api.v2.model.glossaries.GlossarySourceLanguage
import deepl.api.v2.model.glossaries.GlossaryTargetLanguage
import deepl.api.v2.model.translation.TargetLanguage
import deepl.api.v2.model.translation.document.DocumentStatus
import java.io.File
import kotlin.test.assertEquals
import kotlin.test.assertNotNull

fun main() {
  val client = DeepLClient(token = System.getenv("DEEPL_AUTH_KEY"))
  client.use { client ->
    // -----------------------------
    // Usage data
    val usage = client.getUsage()
    println(usage.characterCount)

    // -----------------------------
    // Text translation
    val translation = client.translate(
      text = "ใ“ใ‚“ใซใกใฏ๏ผ็งใฏๅ…ƒๆฐ—ใงใ™ :wave:",
      targetLang = TargetLanguage.AmericanEnglish,
    )
    println(translation.translations[0].text)
    assertEquals("Hello! I am fine :wave:", translation.translations[0].text)

    // -----------------------------
    // Document translation
    val uploadedDocument = client.uploadDocument(
      file = File("source.docx"),
      filename = "source.docx",
      targetLang = TargetLanguage.Japanese,
    )
    assertNotNull(uploadedDocument.documentId)
    assertNotNull(uploadedDocument.documentKey)

    while (true) {
      val res = client.getDocumentStatus(
        documentId = uploadedDocument.documentId,
        documentKey = uploadedDocument.documentKey,
      )
      if (res.status == DocumentStatus.Done || res.status == DocumentStatus.Error) {
        break
      }
      val remainingSeconds: Double = if (res.secondsRemaining != null) res.secondsRemaining!!.toDouble() else 0.0
      val secondsToSleep = 1.0.coerceAtLeast((remainingSeconds / 2.0).coerceAtMost(60.0))
      Thread.sleep(secondsToSleep.toLong())
    }

    val resultFileContentBytes = client.downloadDocument(
      documentId = uploadedDocument.documentId,
      documentKey = uploadedDocument.documentKey,
    )
    File("translation-ja.docx").writeBytes(resultFileContentBytes)

    // -----------------------------
    // Glossaries
    val newGlossary = client.createGlossary(
      name = "something-new-${System.currentTimeMillis()}",
      sourceLang = GlossarySourceLanguage.English,
      targetLang = GlossaryTargetLanguage.German,
      entries = mapOf("artist" to "Maler", "prize" to "Gewinn")
    )
    assert(newGlossary.glossary.ready)
    val glossaryId = newGlossary.glossary.glossaryId

    val glossaries = client.listGlossaries()
    assert(glossaries.glossaries.isNotEmpty())

    val glossary = client.getGlossary(glossaryId)
    assertNotNull(glossary)

    val glossaryEntries = client.listGlossaryEntries(glossaryId)
    assertNotNull(glossaryEntries)

    val deletion = client.deleteGlossary(glossaryId)
    assertNotNull(deletion)
  }
}

Using in Java

Even when you use this SDK in Java and other languages, all the classes/methods should be accessible. If you find issues, please let us know in this project's issue tracker.

entries = new HashMap<>(); entries.put("artist", "Maler"); entries.put("prize", "Gewinn"); GlossaryCreationResponse newGlossary = client.createGlossary(new GlossaryCreationRequest( "something-new-" + System.currentTimeMillis(), GlossarySourceLanguage.English, GlossaryTargetLanguage.German, entries )); assert (newGlossary.getGlossary().getReady()); String glossaryId = newGlossary.getGlossary().getGlossaryId(); GlossariesResponse glossaries = client.listGlossaries(); assert (glossaries.getGlossaries().size() > 0); GlossaryResponse glossary = client.getGlossary(glossaryId); assertNotNull(glossary); GlossaryEntriesResponse glossaryEntries = client.listGlossaryEntries(glossaryId); assertNotNull(glossaryEntries); GlossaryDeletionResponse deletion = client.deleteGlossary(glossaryId); assertNotNull(deletion); } } }">
import deepl.api.v2.DeepLClient;
import deepl.api.v2.model.glossaries.GlossarySourceLanguage;
import deepl.api.v2.model.glossaries.GlossaryTargetLanguage;
import deepl.api.v2.model.translation.TargetLanguage;
import deepl.api.v2.model.translation.document.DocumentStatus;
import deepl.api.v2.request.glossaries.GlossaryCreationRequest;
import deepl.api.v2.request.glossaries.GlossaryDeletionRequest;
import deepl.api.v2.request.glossaries.GlossaryEntriesRequest;
import deepl.api.v2.request.glossaries.GlossaryRequest;
import deepl.api.v2.request.translation.document.DocumentDownloadRequest;
import deepl.api.v2.request.translation.document.DocumentStatusRequest;
import deepl.api.v2.request.translation.document.DocumentUploadRequest;
import deepl.api.v2.request.translation.text.TextTranslationRequest;
import deepl.api.v2.response.glossaries.*;
import deepl.api.v2.response.translation.document.DocumentStatusResponse;
import deepl.api.v2.response.translation.document.DocumentUploadResponse;
import deepl.api.v2.response.translation.text.TextTranslationResponse;
import deepl.api.v2.response.usage.UsageResponse;

import java.io.File;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

public class Readme {
  public static void main(String[] args) throws Exception {
    try (DeepLClient client = new DeepLClient(System.getenv("DEEPL_AUTH_KEY"))) {
      // -----------------------------
      // Usage data
      UsageResponse usage = client.getUsage();
      System.out.println(usage.getCharacterCount());
      assertThat(usage.getCharacterCount(), is(notNullValue()));

      // -----------------------------
      // Text translation
      TextTranslationResponse translation = client.translate(new TextTranslationRequest(
        "ใ“ใ‚“ใซใกใฏ๏ผ็งใฏๅ…ƒๆฐ—ใงใ™ :wave:",
        TargetLanguage.AmericanEnglish
      ));
      System.out.println(translation.getTranslations().get(0).getText());
      String result = translation.getTranslations().get(0).getText();
      assertThat(result, is("Hello! I am fine :wave:"));

      // -----------------------------
      // Document translation
      DocumentUploadResponse uploadedDocument = client.uploadDocument(new DocumentUploadRequest(
        new File("core/src/test/resources/test-en.docx"),
        TargetLanguage.Japanese
      ));
      assertNotNull(uploadedDocument.getDocumentId());
      assertNotNull(uploadedDocument.getDocumentKey());

      while (true) {
        DocumentStatusResponse res = client.getDocumentStatus(
          uploadedDocument.getDocumentId(),
          uploadedDocument.getDocumentKey()
        );
        if (res.getStatus() == DocumentStatus.Done.Done || res.getStatus() == DocumentStatus.Error) {
          break;
        }
        Double remainingSeconds = 0.0D;
        if (res.getSecondsRemaining() != null) {
          remainingSeconds = res.getSecondsRemaining().doubleValue();
        }
        Double secondsToSleep = Math.max(1.0, Math.min(remainingSeconds, 60.0));
        Thread.sleep(secondsToSleep.longValue());
      }

      byte[] resultFileContentBytes = client.downloadDocument(
        uploadedDocument.getDocumentId(),
        uploadedDocument.getDocumentKey()
      );
      File jaFile = new File("core/src/test/resources/test-ja.docx");
      Files.write(jaFile.toPath(), resultFileContentBytes);

      // -----------------------------
      // Glossaries
      Map<String, String> entries = new HashMap<>();
      entries.put("artist", "Maler");
      entries.put("prize", "Gewinn");
      GlossaryCreationResponse newGlossary = client.createGlossary(new GlossaryCreationRequest(
        "something-new-" + System.currentTimeMillis(),
        GlossarySourceLanguage.English,
        GlossaryTargetLanguage.German,
        entries
      ));
      assert (newGlossary.getGlossary().getReady());
      String glossaryId = newGlossary.getGlossary().getGlossaryId();

      GlossariesResponse glossaries = client.listGlossaries();
      assert (glossaries.getGlossaries().size() > 0);

      GlossaryResponse glossary = client.getGlossary(glossaryId);
      assertNotNull(glossary);

      GlossaryEntriesResponse glossaryEntries = client.listGlossaryEntries(glossaryId);
      assertNotNull(glossaryEntries);

      GlossaryDeletionResponse deletion = client.deleteGlossary(glossaryId);
      assertNotNull(deletion);
    }
  }
}

Supported Java Runtimes

  • OpenJDK 8 or newer
  • All Android runtime versions supported by Kotlin 1.6

License

The MIT License

You might also like...
A property/method accessor library for the JVM, written in Kotlin

unlok - unlock your JVM a property/method accessor library for the JVM, written in Kotlin. how to import you can import unlok from maven central just

Server Sent Events (SSE) client multiplatform library made with Kotlin and backed by coroutines

OkSSE OkSSE is an client for Server Sent events protocol written in Kotlin Multiplatform. The implementation is written according to W3C Recommendatio

io.github.jakob.AgonesClient - Kotlin client library for sdk.proto

io.github.jakob.AgonesClient - Kotlin client library for sdk.proto Requires Kotlin 1.3.41 Gradle 4.9 Build First, create the gradle wrapper script: gr

RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.
RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.

RoomJetpackCompose is an app written in Kotlin and shows a simple solution to perform CRUD operations in the Room database using Kotlin Flow in clean architecture.

API-Annotate - Single annotation to mark API elements

API-Annotate A single annotation for annotating externally-consumed elements in

API-Request - Android app that makes API Request

API-Request Android project using Retrofit and Ktor for Http Requests, built wit

Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Practical Kotlin Multiplatform on the Web ๋ณธ ์ €์žฅ์†Œ๋Š” ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ ๊ธฐ๋ฐ˜ ์›น ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์›Œํฌ์ˆ(๊ฐ•์ขŒ)์„ ์œ„ํ•ด ์ž‘์„ฑ๋œ ํ…œํ”Œ๋ฆฟ ํ”„๋กœ์ ํŠธ๊ฐ€ ์žˆ๋Š” ๊ณณ์ž…๋‹ˆ๋‹ค. ์›Œํฌ์ˆ ๊ณผ์ •์—์„œ ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํ”„๋ก ํŠธ์—”๋“œ(front-end)๋Š” Ko

Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client
Create an application with Kotlin/JVM and Kotlin/JS, and explore features around code sharing, serialization, server- and client

Building a Full Stack Web App with Kotlin Multiplatform ๋ณธ ์ €์žฅ์†Œ๋Š” INFCON 2022์—์„œ ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ ๊ธฐ๋ฐ˜ ์›น ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํ•ธ์ฆˆ์˜จ๋žฉ์„ ์œ„ํ•ด ์ž‘์„ฑ๋œ ํ…œํ”Œ๋ฆฟ ํ”„๋กœ์ ํŠธ๊ฐ€ ์žˆ๋Š” ๊ณณ์ž…๋‹ˆ๋‹ค. ํ•ธ์ฆˆ์˜จ ๊ณผ์ •์—์„œ ์ฝ”ํ‹€๋ฆฐ ๋ฉ€ํ‹ฐํ”Œ๋žซํผ์„

Android To-Do MVVM Architecture App written in Kotlin.(ViewModel, ROOM, Livedata, Coroutines)

MVVM-To-Do-App A To-Do application written in kotlin using Android Architectural components What's new? Room + Coroutines - Upgraded Room to v2.1. Roo

Comments
  • Nullpointer on Java 8

    Nullpointer on Java 8

    i just try the lib today and i got a NullPointer :( can you help me please ?
    
    try (DeepLClient client = new DeepLClient("")) {
    
    		TextTranslationResponse translation = client
    				.translate(new TextTranslationRequest("droite", TargetLanguage.AmericanEnglish));
    		System.err.println(translation.getTranslations().get(0).getText());
    		String result = translation.getTranslations().get(0).getText();
    

    2022-08-09T10:05:24.874+02:00 DEBUG deepl.api.v2.logging.StdoutDeepLLogger - Sending a request: POST https://api-free.deepl.com/v2/translate body &text=droite&target_lang=EN-US 2022-08-09T10:05:25.427+02:00 DEBUG deepl.api.v2.logging.StdoutDeepLLogger - Received a response (1440 millis): status 200 body
    Exception in thread "main" java.lang.NullPointerException: gson.fromJson(body, Textโ€ฆtionResponse::class.java) must not be null at deepl.api.v2.json.GsonDeepLJsonSerializer.toTextTranslationResponse(GsonDeepLJsonSerializer.kt:33) at deepl.api.v2.endpoint.TextTranslation$DefaultImpls.translate(TextTranslation.kt:94) at deepl.api.v2.DeepLClient.translate(DeepLClient.kt:12) at com.senefsoft.traductor.external.Translator.main(Translator.java:15)

    opened by slasherbane 4
Owner
Kazuhiro Sera
Slack Bolt Framework / SDK Developer
Kazuhiro Sera
Minecraft Server Software specially designed for Thicc SMP. Here on GitHub without the private patches, just a normal hybrid JettPack-Pufferfish-Empirecraft fork

AlynaaMC A private, custom server software for Thicc SMP and a fork of Pufferfish. Here on GitHub with patches from JettPack, Airplane and Pufferfish

ThiccMC 14 Dec 31, 2021
A beautiful Fashion Store like Android App Mock built on Jetpack Compose with compose navigation, hilt, dark theme support and google's app architecture found on uplabs Here

A beautiful Fashion Store like Android App Mock built on Jetpack Compose with compose navigation, hilt, dark theme support and google's app architecture found on uplabs Here

Puncz 87 Nov 30, 2022
A nice weather that helps you get all information including: current weather, hourly weather and also forecasts for 16 days

WeatherForecast This is an ongoing project where I fetch all the weather data using Retrofit and Kotlin Coroutines over two APIs containing both curre

null 2 Jul 26, 2022
Kotlin-client-dsl - A kotlin-based dsl project for a (Client) -> (Plugin) styled program

kotlin-client-dsl a kotlin-based dsl project for a (Client) -> (Plugin) styled p

jackson 3 Dec 10, 2022
Mobile client for official Nextcloud News App written as Kotlin Multiplatform Project

Newsout Android and iOS mobile client for Nextcloud news App. The Android client is already available to download in the Play Store. F-Droid and Apple

Simon Schubert 118 Oct 3, 2022
GBooks - A simple android app written in Kotlin to read books from the Google Book Api

G-Books A simple android app written in Kotlin to read books from the Google Boo

Google Developer Student Clubs - Baba Banda Singh Bahadur Engineering College 10 Nov 7, 2022
A lightweight cache library written in Kotlin

[NEW] Released to Maven Central: 'com.github.yundom:kache:1.x.x' Kache A runtime in-memory cache. Installation Put this in your build.gradle implemen

Dennis 22 Nov 19, 2022
Android AsyncTask wrapper library, written in Kotlin

KillerTask This is a Kotlin Android library to create async background tasks. Inspired by TinyTask, but more beautiful and easy to use for Kotlin Andr

Inaka 26 Oct 3, 2022
A fast, lightweight, entity component system library written in Kotlin.

Fleks A fast, lightweight, entity component system library written in Kotlin. Motivation When developing my hobby games using LibGDX, I always used As

Simon 66 Dec 28, 2022
Sample Code for fake Kotlin library written in Java

Jatlin ใ“ใฎใƒชใƒใ‚ธใƒˆใƒชใฏ ใƒ–ใƒญใ‚ฐ่จ˜ไบ‹ ใฎใŸใ‚ใฎใ‚ตใƒณใƒ—ใƒซใ‚ณใƒผใƒ‰ใงใ™ใ€‚่ฉณ็ดฐใฏ่จ˜ไบ‹ใ‚’ใ”่ฆงใใ ใ•ใ„ใ€‚ ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใƒˆๆง‹ๆˆ :java-lib ใซKotlinใซๅฝ่ฃ…ใ—ใŸJavaใƒ•ใ‚กใ‚คใƒซใŒๅซใพใ‚Œใพใ™ใ€‚ :kotlin-lib ใฏ :java-lib ใ‚’ใƒ“ใƒซใƒ‰ใ—ใŸJARใƒ•ใ‚กใ‚คใƒซใ‚’Kotlinใ‹ใ‚‰่ชญใฟ่พผใ‚“ใงๅฎŸ่กŒ

Takaki Hoshikawa 3 Dec 10, 2021