Git Product home page Git Product logo

deepl-translator's Introduction

deepl-translator

Coverage Status Build Status Known Vulnerabilities npm version styled with prettier

This unofficial node module provides promised methods for detecting language and translating text using DeepL Translator (https://www.deepl.com/translator) undocumented API.

DeepL has done a great job with their deep learning translation model which outperforms the competition by a wide margin. An excerpt from their page on that topic:

Blind test

100 sentences were translated by DeepL Translator, Google Translate, Microsoft Translator, and Facebook. Professional translators assessed the translations, without knowing which system produced which results. The translators preferred our translations over the competition's by a factor of 3:1. Here are the results of a test run in August 2017:

Stats

Supported languages:

Language code Language
EN English
DE German
FR French
ES Spanish
IT Italian
NL Dutch
PL Polish

Install

yarn add deepl-translator

This package can also be used on the client since it provides an XHR shim for the HTTP request helper implementation. The shim is defined as a mapping in the browser property of the package.json so it should be picked up automatically by most of the popular bundlers.

Usage

const { translate, detectLanguage, wordAlternatives, translateWithAlternatives } = require('deepl-translator');

// Translate text with explicit source and target languages
translate('Die Übersetzungsqualität von deepl ist erstaunlich!', 'EN', 'DE')
  .then(res => console.log(`Translation: ${res.translation}`))
  .catch(console.error);

// Translate short text with this method to get a few translation alternatives
translateWithAlternatives(
  'Die Übersetzungsqualität von deepl ist erstaunlich!',
  'EN'
)
  .then(res =>
    console.log(
      `Translation alternatives: ${res.translationAlternatives.join(', ')}`
    )
  )
  .catch(console.error);

// Leave out the source language or specify 'auto' to autodetect the input
translate('This is a representative chunk of text in english.', 'DE')
  .then(res => console.log(`Translation: ${res.translation}`))
  .catch(console.error);

// Detect the text language without giving back the translation
detectLanguage('Deepl también puede detectar un idioma. ¿Qué idioma es este?')
  .then(res => console.log(`Detected language: ${res.languageName}`))
  .catch(console.error);

// Multi-line translations work as well, even with different source languages mixed in
translate(
  `Das ist der erste Satz... Das der zweite.

  C'est la troisième phrase.


  Y ese es el cuarto.
  I piąta.`,
  'EN'
)
  .then(res => console.log(`Translation: ${res.translation}, Resolved languages: ${res.resolvedSourceLanguage}`))
  .catch(console.error);

  // This method allows for tweaking the translation. By providing a beginning, we define a word or a phrase
  // for which we want alternative translations within the context of a larger body of text (a sentence).
  // One of the returned alternatives can then be selected and passed into translateWithAlternatives
  // as an overriding word/phrase for the beginning of the whole translation.
  {
    const text = 'Die Übersetzungsqualität von deepl ist erstaunlich!';
    // Translates to: 'The translation quality of deepl is amazing!'
    wordAlternatives(text, 'EN', 'DE', 'The translation')
      .then(res => {
        console.log(`3 Alternative beginnings:`);
        res.alternatives.slice(0, 3).forEach(alt => console.log(alt));
        // Choose the third alternetive
        return res.alternatives[2];
      })
      .then(beginning => {
        // Request translation with selected alternative beginning
        return translateWithAlternatives(text, 'EN', 'DE', beginning);
      })
      .then(res => console.log(`Alternative: ${res.translation}`));
  }

API

translate(text, targetLanguage, sourceLanguage) -> object

This method translates the input text into a specified target language. Source language can be autodetected. Multi-line text translation is possible with line breaks preserved.

text (string) Input text to be translated

targetLanguage (string) Language code of the language to translate to

sourceLanguage (string) Language code of the input text language. Can be left out or set to auto for automatic language detection.

Returns

{
  targetLanguage: 'XY', // Language code(s) of the language that was translate to
  resolvedSourceLanguage: 'YZ', // Language code(s) of the input language (resolved automatically for autodetect)
  translation: 'Translated text' // Translated text
}

translateWithAlternatives(text, targetLanguage, sourceLanguage, beginning) -> object

This method translates the input text into a specified target language. Source language can be autodetected. Optionally, a sentence beginning override can be given (should be used in conjunction with wordAlternatives which gives contextual phrase/word translations).

text (string) Input text to be translated

targetLanguage (string) Language code of the language to translate to

sourceLanguage (string) Language code of the input text language. Can be left out or set to auto for automatic language detection.

beginning (string) Override of the translation beginning

Returns

{
  targetLanguage: 'XY', // Language code of the language that was translate to
  resolvedSourceLanguage: 'YZ', // Language code of the input language (resolved automatically for autodetect)
  translation: 'Translated text', // Translated text
  translationAlternatives: ['First translated alternative', 'Second translated alternative']
}

detectLanguage(text) -> object

This method detects the language of the input text.

text (string) Input text to detect the language on

Returns

{
  languageCode: 'XY', // Language code of the input text
  languageName: 'Some language', // Language name (in English) of the input text
}

wordAlternatives(text, targetLanguage, sourceLanguage, beginning) -> object

This method suggests alternative wordings for a subset of the beginning input text. This means we get alternative translations for the given word or a phrase within a context of the larger body of text (the input text). Languages cannot be autodetected.

text (string) Input text to be translated

targetLanguage (string) Language code of the language to translate to

sourceLanguage (string) Language code of the input text language

beginning (string) Subset of the translation of text for which the contextual alternatives will be provided

Returns

{
  targetLanguage: 'XY', // Language code of the language that was translate to
  resolvedSourceLanguage: 'YZ', // Language code of the input language
  alternatives: ['An alternative', 'Yet another alternative'], // Array of alternative sentence beginnings
}

License

Apache License 2.0

deepl-translator's People

Contributors

lixissimus avatar vsetka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

deepl-translator's Issues

[BUG] Rate limit always hit

The problem

As reported here, all requests to the jsonrpc API are failing with

{
  "jsonrpc": "2.0",
  "error": { "code": 1042902, "message": "Too many requests." }
}

The problem is probably due to the same id being used in each request.

What is the current behavior?

Any request for translation fails.

What is the expected behavior?

Requests do not trigger rate limit IP blocks unless a specific client makes too many requests in a given time frame.

Environment

All versions.

Request limit

The API is currently limited. I still have to figure out if they put a hard limit on the absolute request count from an IP or are just limiting the number of requests within a certain timespan.

Error message: Server side error during DeepLy API call: HTTP code 429, message: "{"jsonrpc": "2.0","error":{"code":1042901,"message":"Too many requests."}}"

[FR] Translating by uploading PO files

Feature request:
I'm currently translating my third project with Poedit, but most of the times, Deepl already gave the perfect translation (with is great). Now I was thinking if you could add an option to upload PO (translation file) or POT (template for translation) files to Deepl to decrease the amount of work on translating projects.
The layout of a PO file is quite simple:

a few comment lines
msgid ""
msgstr ""
"a lot of nonsens about who made the translation, etc."

#: location/of/the/file.xxx:438 (line number)
msgid: "Phrase to translate"
msgstr: "Translated phrase"

#: location/of/the/file.xxx:465
msgid: "Phrase to translate"
msgstr: "Translated phrase"
etc.

Hope this will be implemented. My coding skills are fine for some Arduino stuff, but not good enough to write a script to automate this.

Regards,
Simon

Outdated

NOTE: Before creating an issue please make sure you are using the latest version of deepl-translator.

The problem

Bug / Outdated after deepL API updated

What is the current behavior?

You can't translate anything.

`undefined:1

^

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at IncomingMessage.res.on (E:\Bibliothek\Dokumente\Atom\Node\DeepL\node_modules\deepl-translator\src\request-helper.js:10:40)
at IncomingMessage.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1090:12)
at process._tickCallback (internal/process/next_tick.js:63:19)`

Environment

Node v10.3.0
deepL-translator 1.2.0

translate() always auto-detecting the source language

I noticed an unwanted behavior in the "translate()" method: it always autodetects the source language even when you specify a valid source language. To fix this I changed the resolvedSourceLanguage variable specified at line 63 of deepl-translator.js with sourceLanguage and now it works as expected (using the chosen source language or autodetecting it when not specified).

I try any of the examples but it doesn't work

node version: v12.17.0
SO: Windows 10

TypeError: Cannot read property 'source_lang' of undefined
at D:\deepl-translator-node\node_modules\deepl-translator\src\deepl-translator.js:101:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.