GithubHelp home page GithubHelp logo

deeplcom / deepl-dotnet Goto Github PK

View Code? Open in Web Editor NEW
173.0 13.0 24.0 228 KB

Official .NET library for the DeepL language translation API.

License: MIT License

C# 99.81% Shell 0.19%
dotnet csharp deepl api language translation translator i18n official

deepl-dotnet's Introduction

DeepL .NET Library

NuGet License: MIT .NET

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 .NET library offers a convenient way for applications written in .NET 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 .NET 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.

Installation

Using the .NET Core command-line interface (CLI) tools:

dotnet add package DeepL.net

Using the NuGet Command Line Interface (CLI):

nuget install DeepL.net

Usage

All entities in the DeepL .NET library are in the DeepL namespace:

using DeepL;

Create a Translator object providing your DeepL API authentication key.

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

var authKey = "f63c02c5-f056-..."; // Replace with your key
var translator = new Translator(authKey);

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 options as the second argument, see Configuration for more information.

Translating text

To translate text, call TranslateTextAsync(). The first argument is a string containing the text to translate, or IEnumerable of strings to translate multiple texts.

The second and third arguments are case-insensitive language codes for the source and target language respectively, for example "DE", "FR". The LanguageCode static class defines constants for the currently supported languages, for example LanguageCode.German, LanguageCode.French. To auto-detect the input text language, specify null as the source language.

Additional TextTranslateOptions can also be provided, see Text translation options below.

TranslateTextAsync() returns a TextResult or TextResult array corresponding to the input text(s). The TextResult contains the translated text and detected source language code.

// Translate text into a target language, in this case, French:
var translatedText = await translator.TranslateTextAsync(
      "Hello, world!",
      LanguageCode.English,
      LanguageCode.French);
Console.WriteLine(translatedText); // "Bonjour, le monde !"
// Note: printing or converting the result to a string uses the output text.

// Translate multiple texts into British English:
var translations = await translator.TranslateTextAsync(
      new[] { "お元気ですか?", "¿Cómo estás?" }, null, "EN-GB");
Console.WriteLine(translations[0].Text); // "How are you?"
Console.WriteLine(translations[0].DetectedSourceLanguageCode); // "JA"
Console.WriteLine(translations[1].Text); // "How are you?"
Console.WriteLine(translations[1].DetectedSourceLanguageCode); // "ES"

// Translate into German with less and more Formality:
foreach (var formality in new[] { Formality.Less, Formality.More }) {
  Console.WriteLine(
        await translator.TranslateTextAsync(
              "How are you?",
              null,
              LanguageCode.German,
              new TextTranslateOptions { Formality = formality }));
}
// Will print: "Wie geht es dir?" "Wie geht es Ihnen?"

Text translation options

TextTranslateOptions has the following properties that impact text translation:

  • SentenceSplittingMode: specifies how input text should be split into sentences, default: 'SentenceSplittingMode.All'.
    • 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.
  • PreserveFormatting: controls automatic-formatting-correction. Set to true to prevent automatic-correction of formatting, default: false.
  • Formality: 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.
    • Formality.Default: standard level of formality.
    • Formality.PreferLess: less formality, if available for the specified target language, otherwise default.
    • Formality.PreferMore: more formality, if available for the specified target language, otherwise default.
  • GlossaryId: specifies a glossary to use with translation, as a string containing the glossary ID.
  • Context: specifies additional context to influence translations, that is not translated itself. Characters in the context parameter are not counted toward billing. See the API documentation for more information and example usage.
  • TagHandling: type of tags to parse before translation, options are "html" and "xml".

The following options are only used if TagHandling is set to 'xml':

  • OutlineDetection: set to false to disable automatic tag detection, default is true.
  • SplittingTags: List of XML tags that should be used to split text into sentences. Tags may be specified individually (['tag1', 'tag2']), or a comma-separated list of strings ('tag1,tag2'). The default is an empty list.
  • NonSplittingTags: List of XML tags that should not be used to split text into sentences. Format and default are the same as for splitting tags.
  • IgnoreTags: 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 TranslateDocumentAsync() with the input and output files as FileInfo objects, and provide the source and target language as above.

Additional DocumentTranslateOptions are also available, see Document translation options below. Note that file paths are not accepted as strings, to avoid mixing up the file and language arguments.

// Translate a formal document from English to German
try {
  await translator.TranslateDocumentAsync(
        new FileInfo("Instruction Manual.docx"),
        new FileInfo("Bedienungsanleitung.docx"),
        "EN",
        "DE",
        new DocumentTranslateOptions { Formality = Formality.More });
} catch (DocumentTranslationException exception) {
  // If the error occurs *after* upload, the DocumentHandle will contain the document ID and key
  if (exception.DocumentHandle != null) {
    var handle = exception.DocumentHandle.Value;
    Console.WriteLine($"Document ID: {handle.DocumentId}, Document key: {handle.DocumentKey}");
  } else {
    Console.WriteLine($"Error occurred during document upload: {exception.Message}");
  }
}

Alternatively the input and output files may be provided as Stream objects; in that case the input file name (or extension) is required, so the DeepL API can determine the file type:

...
  await translator.TranslateDocumentAsync(
        new MemoryStream(buffer),
        "Input file.docx", // An extension like ".docx" is also sufficient
        File.OpenWrite(outputDocumentPath),
        "EN",
        "DE",
        new DocumentTranslateOptions { Formality = Formality.More });

TranslateDocumentAsync() manages the upload, wait until translation is complete, and download steps. If your application needs to execute these steps individually, you can instead use the following functions directly:

  • TranslateDocumentUploadAsync(),
  • TranslateDocumentStatusAsync() (or TranslateDocumentWaitUntilDoneAsync()), and
  • TranslateDocumentDownloadAsync()

Document translation options

DocumentTranslateOptions has the following properties that impact text translation:

Glossaries

Glossaries allow you to customize your translations using defined terms. Multiple glossaries can be stored with your account, each with a user-specified name and a uniquely-assigned ID.

Creating a glossary

You can create a glossary with your desired terms and name using CreateGlossaryAsync(). Each glossary applies to a single source-target language pair. Note: Glossaries are only supported for some language pairs, see Listing available glossary languages for more information. The entries should be specified as a Dictionary.

If successful, the glossary is created and stored with your DeepL account, and a GlossaryInfo object is returned including the ID, name, languages and entry count.

// Create an English to German glossary with two terms:
var entriesDictionary = new Dictionary<string, string>{{"artist", "Maler"}, {"prize", "Gewinn"}};
var glossaryEnToDe = await translator.CreateGlossaryAsync(
    "My glossary", "EN", "DE",
    new GlossaryEntries(entriesDictionary));

Console.WriteLine($"Created {glossaryEnToDe.Name}' ({glossaryEnToDe.GlossaryId}) " +
    $"{glossaryEnToDe.SourceLanguageCode}->{glossaryEnToDe.TargetLanguageCode} " +
    $"containing {glossaryEnToDe.EntryCount} entries"
);
// Example: Created 'My glossary' (559192ed-8e23-...) en->de containing 2 entries

You can also upload a glossary downloaded from the DeepL website using CreateGlossaryFromCsvAsync(). Instead of supplying the entries as a dictionary, specify the CSV data as a Stream containing file content:

var csvStream =  File.OpenRead("myGlossary.csv");
var csvGlossary = await translator.CreateGlossaryFromCsvAsync("My CSV glossary", "EN", "DE", csvStream);

The API documentation explains the expected CSV format in detail.

Getting, listing and deleting stored glossaries

Functions to get, list, and delete stored glossaries are also provided:

  • GetGlossaryAsync() takes a glossary ID and returns a GlossaryInfo object for a stored glossary, or raises an exception if no such glossary is found.
  • ListGlossariesAsync() returns a List of GlossaryInfo objects corresponding to all of your stored glossaries.
  • DeleteGlossaryAsync() takes a glossary ID or GlossaryInfo object and deletes the stored glossary from the server, or raises an exception if no such glossary is found.
// Retrieve a stored glossary using the ID
var myGlossary = await translator.GetGlossaryAsync("559192ed-8e23-...");

// Find and delete glossaries named 'Old glossary'
var glossaries = await translator.ListGlossariesAsync();
foreach (var glossaryInfo in glossaries) {
  if (glossaryInfo.Name == "Old glossary")
    await translator.DeleteGlossaryAsync(glossaryInfo);
}

Listing entries in a stored glossary

The GlossaryInfo object does not contain the glossary entries, but instead only the number of entries in the EntryCount property.

To list the entries contained within a stored glossary, use GetGlossaryEntriesAsync() providing either the GlossaryInfo object or glossary ID:

var entries = translator.GetGlossaryEntriesAsync(myGlossary);

foreach (KeyValuePair<string, string> entry in entries.ToDictionary()) {
  Console.WriteLine($"{entry.Key}: {entry.Value}");
}
// prints:
//   artist: Maler
//   prize: Gewinn

Using a stored glossary

You can use a stored glossary for text (or document) translation by setting the TextTranslationOptions (or DocumentTranslationOptions) GlossaryId property to the glossary ID. You must also specify the source_lang argument (it is required when using a glossary):

var resultWithGlossary = await translator.TranslateTextAsync(
    "The artist was awarded a prize.",
    "EN",
    "DE",
    new TextTranslateOptions { GlossaryId = glossaryEnToDe.GlossaryId });
// resultWithGlossary.Text == "Der Maler wurde mit einem Gewinn ausgezeichnet."
// Without using a glossary: "Der Künstler wurde mit einem Preis ausgezeichnet."

Check account usage

var usage = await translator.GetUsageAsync();
if (usage.AnyLimitReached) {
  Console.WriteLine("Translation limit exceeded.");
} else if (usage.Character != null) {
  Console.WriteLine($"Character usage: {usage.Character}");
} else {
  Console.WriteLine($"{usage}");
}

Listing available languages

You can request the list of languages supported by DeepL for text and documents using the GetSourceLanguagesAsync() and GetTargetLanguagesAsync() 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.

// Source and target languages
var sourceLanguages = await translator.GetSourceLanguagesAsync();
foreach (var lang in sourceLanguages) {
  Console.WriteLine($"{lang.Name} ({lang.Code})"); // Example: "English (EN)"
}
var targetLanguages = await translator.GetTargetLanguagesAsync();
foreach (var lang in targetLanguages) {
  if (lang.SupportsFormality ?? false) {
    Console.WriteLine($"{lang.Name} ({lang.Code}) supports formality");
     // Example: "German (DE) supports formality"
  }
}

Listing available glossary languages

Glossaries are supported for a subset of language pairs. To retrieve those languages use the GetGlossaryLanguagesAsync() function, which returns an array of GlossaryLanguagePair objects. Use the SourceLanguage and TargetLanguage properties to check the pair of language codes supported.

// Glossary languages
var glossaryLanguages = await translator.GetGlossaryLanguagesAsync();
foreach (var languagePair in glossaryLanguages) {
  Console.WriteLine($"{languagePair.SourceLanguage} to {languagePair.TargetLanguage}");
  // Example: "EN to DE", "DE to EN", etc.
}

You can also find the list of supported glossary language pairs in the API documentation.

Note that glossaries work for all target regional-variants: a glossary for the target language English ("EN") supports translations to both American English ("EN-US") and British English ("EN-GB").

Exceptions

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

Writing a Plugin

If you use this library in an application, please identify the application with TranslatorOptions.appInfo, which needs the name and version of the app:

var options = new TranslatorOptions {
  appInfo =  new AppInfo { AppName = "my-dotnet-test-app", AppVersion = "1.2.3"}
};
var translator = new Translator(AuthKey, options);

This information is passed along when the library makes calls to the DeepL API. Both name and version are required. Please note that setting the User-Agent header via TranslatorOptions.Headers will override this setting, if you need to use this, please manually identify your Application in the User-Agent header.

Configuration

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

var options = new TranslatorOptions {
      MaximumNetworkRetries = 5,
      PerRetryConnectionTimeout = TimeSpan.FromSeconds(10),
};
var translator = new Translator(authKey, options);

See the TranslatorOptions class for details about the available options.

Proxy configuration

To use the library with a proxy, override the ClientFactory with a function returning a custom HttpClient:

var proxyUrl = "http://localhost:3001";
var handler = new System.Net.Http.HttpClientHandler {
      Proxy = new System.Net.WebProxy(proxyUrl), UseProxy = true,
};
var options = new TranslatorOptions {
      ClientFactory = () => new HttpClientAndDisposeFlag {
            HttpClient = new HttpClient(handler), DisposeClient = true,
      }
};
var translator = new Translator(authKey, options);

Anonymous platform information

By default, we send some basic information about the platform the client library is running on with each request, see here for an explanation. This data is completely anonymous and only used to improve our product, not track any individual users. If you do not wish to send this data, you can opt-out when creating your Translator object by setting the sendPlatformInfo flag in the TranslatorOptions to false like so:

var options = new TranslatorOptions { sendPlatformInfo = false };
var translator = new Translator(authKey, options);

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 dotnet 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 dotnet test with the DEEPL_MOCK_SERVER_PORT and DEEPL_SERVER_URL environment variables defined referring to the mock-server.

deepl-dotnet's People

Contributors

daniel-jones-deepl avatar daniel-jones-dev avatar deejaytc avatar dieter-enns-deepl avatar janebbing avatar mike-winters-deepl 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  avatar  avatar

deepl-dotnet's Issues

Getting "Authorization failure, check AuthKey" when trying to actually upload a file

Basically, I tried to throw a basic app together to test the new API (thanks for releasing an official library btw!)
I did hard-code my API key as a String, instead of just using the default Environment.GetEnvironmentVariable. (1)

  • I have a Pro auth key, account.
  • I can issue any other call, like check usage, and it works just fine.
  • If I mess up the key, I get the wrong API key, so the key is fine I think.
  • Only has an error when I actually try to upload.

(1) - Maybe the actual TranslateDocumentAsync method uses the Environment.GetEnvironmentVariable call?

Please don't shoot me if I messed up something.
(I used C# 6.0 with Visual Studio 2022 Community.)

incompatible Security Protocol

Hi, allthough the .NET API seems to work fine in testing mode, my vb.net client app (win10, Word/VSTO) cannot succesfully create a translator instance untilI set the SecurityProtocol option: to Tls12 (using the system default Tls30 does not work.

With this setting it runs sweet!

    ' DeepL API only works when using TLS 1.2 (system default is Tls30)
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
     _translator = New Translator(myAddinSettings.TranslateDeepLAuthKey)

I could not find anything in the documentation so please consider adding this.

regards, Klaas

Error translating the word 'Coelho' from PT to EN-US.

Describe the bug
Hello everyone, I'm using the DeepL.net package in 1.9.0 version and the result of translate is not expected.

Expected behavior
The expected behavior when I'm translating from PT to EN-US for the word Coelho is Rabbit

Screenshots or sample code
Unexpected behavior for EN-US language
error-enus

The expected behavior for the EN-US language should be the same when I'm using the EN-GB language
expected-engb

Translate string literals with programming logic

Currently I am developing a tool that extracts all string literals that are enclosed in double quotes from a file, the problem is that these string literals have programming logic as escape sequences and Deepl is not able to maintain that logic, this is an example of a string literal containing Russian characters that I want to translate into Spanish

"{ffffff}Дом {ffff00}№%d\n
{ffffff}Стартовая цена аукциона: {ffff00}%d BTC\n
{ffffff}Минимальная ставка: {ffff00}%d BTC\n
Завершение аукциона через: {ffff00}%s\n\n
{cccccc}%s - %d BTC\n\n
{ffffff}Укажите сумму вашей ставки:"

How should I approach this situation?

Xamarin app with NetStandard 2.1 getting System.Text.Json Exception Constructor not found

Description

Im making a simple Xamarin mobile app that is based on NetStandard 2.1:
I tried to use the basic code from the ReadMe in Usage section
image
text is a standard string that contains some words that could be easily translated in standalone DeepL client - for example Dark red Borscht with Eastern spices

Everytime I try to translate a string I see that my usage goes up but Im getting a exception on TranslateTextAsync:
Constructor on type 'System.Text.Json.Serialization.Converters.ArrayConverter 2[[DeepL.Model.TextResult[], DeepL.net, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a2d79e62551bd3c],[DeepL.Model.TextResult, DeepL.net, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9a2d79e62551bd3c]]' not found.

Im getting the same error while using git and nuget version.

I've spotted that it goes without issue up to
image
In JsonUtils.cs class at line 41

and it will throw a exception before it will reach
image
in JsonSerializer in System.Text.Json namespace at line 38

Am I missing something?

Missing in the .NET library the parameter "output_format" ("docx" for translating a PDF file into a Word document)

Missing in the .NET DeepL library the parameter "output_format" ("docx" for translating a PDF file into a Word document).

output_format
type of string: File extension of desired format of translated file, for example: docx.
If unspecified, by default the translated file will be in the same format as the input file.

This option is supported by the DeepL API Pro interface but seems to not be yet implemented in some DeepL libraries (PHP, .NET, ...).

I would be very pleased if you could add this feature in this library.

Thank you verys much in advance for your efforts.

Best regards
Régis Barbier

how can I use the DeepL Features for XML like "tag_handling=xml" and "non_splitting_tags" in deepl-dotnet

I'm trying to use "tag_handling=xml" but it is not working.

I'm using the Translator object as described in the documentation. I use the Translator object to pass xhtml snippets to DeepL:

var translatedText = await translator.TranslateTextAsync (
new string[] {"<p>Das <a href=\"LinkToAnotherFile.htm#Lesezeichen\">ist</a> ein einfacher Satz.</p>" },
LanguageCode.German, LanguageCode.EnglishAmerican,
new TextTranslateOptions { TagHandling = "xml" });
string t = translatedText.ToString();
I want DeepL to translate exclusively the text nodes in my xml code, leaving alone the markup. But although I pass the TagHandling=xml option to the server it would recognize the bookmark "#Lesezeichen" in the above snippet as a german word and translate it, because it still parses the snippet as plain text rather than an xml snippet.
I also tried using the DocumentTranslateAsync function passing
new DocumentTranslateOptions { tag_handling = "xml" });
But I get the same result.

Judging from
usage = await translator.GetUsageAsync();
I assume that DeepL also counts all other markup as translatable text - leaving it untouched only, because it doesn't recognize it as german expressions.

When I look into the implementation of the TextTranslateOptions class, it looks like options as TagHandling or NonSplittingTags are only Initialized, but no functionality is available yet.

I have to admit that my programming knowledge is insufficient to work on decompiled assemblies as it would be required here. Any help available?

Nothing is happening

I am new to asynchronous programming in .net so I'm hoping that I am making an obvious mistake here. Nothing is happening when I Await Translator

Dim AuthKey As String = "01234567-89ab-cdef-0123-456789abcdef:fx" ' Free API Key
Dim Translator As New Translator(AuthKey)
Dim Options As New TextTranslateOptions With {
    .Formality = Formality.More,
    .TagHandling = "html",
    .SentenceSplittingMode = SentenceSplittingMode.NoNewlines
}

Dim TranslatedText = Await Translator.TranslateTextAsync(
    TextToTranslate,
    FormMain.Settings.LanguageSource.DeepLLanguageCode,
    FormMain.Settings.LanguageTarget.DeepLLanguageCode,
    Options
)

EDIT: To clarify, I literally mean nothing, there is no error and the code also doesn't continue to execute. It just waits forever after that call.

Please advise. Thanks!
- Jay

Translator exception

If I use the example code given in the readme then I get an error that the language code "en" is deprecated and to use "en-GB" instead, however, if I try and change to this then my program hangs indefinitely.

Steps to reproduce the behavior:

  1. Use the following as a translation function:
       static public async Task<TextResult> TranslateText(string originalText)
        {
            return await translator.TranslateTextAsync(originalText, LanguageCode.Norwegian, LanguageCode.English);
        }
  1. Call the translation function as follows:
    TextResult t= TranslateText(speech.OriginalText).Result;

  2. Receive error "One or more errors occurred. (targetLanguageCode="en" is deprecated, please use "en-GB" or "en-US" instead)"

I have tried changing my translation function as follows:
return await translator.TranslateTextAsync(originalText, LanguageCode.Norwegian, "en-GB");
And this causes the program to hang indefinitely.

Inconsistent translation result with glossaries

Hi, first of all I'm really happy with the DeepL translation and the API. Recently I've started using the glossary function and the results are inconsistent. As I am using your API (v1.2) I assume the issue is not on my side.

I've attached a screen shot of the glossary (EN-DE) and the text source text in ENGLISH and the translation to GERMAN with and without use of glossary (with glossary using a PRO account, without glossary using a FREE account). The ID of the glossary is a0f05fa1-c5b5-45b7-824c-222a540168c1.

In yellow I have highlighted where the glossary has not been applied and in red the weird behavior where the changing the first character of the ENGLISH source to a capital affects the translation to GERMAN but at least the translation is more similar to the glossary (though not fully).
Inconsistent application of glossary

Any clue?

regards, Klaas

How to use this behind a proxy

Hi,

I wrote a simple application that made use of this great package.
The application was working great until I plugged my laptop into the company network.

Is there a way to specify the proxy?

Issues with the HttpClient wrapped inside DeepLClient

Describe the bug
Hey there! I wanted to let you know about a potential issue with how our application is set up.

Basically, the way HttpClient is being used by default can be a bit confusing for consumers, and the way it's documented isn't super clear. Specifically, if you're creating many ITranslator objects and disposing them you can create socket exhaustion issues in high throughput systems. This is because a new HttpClient is created with each ITranslator object.

To make things worse, there's another issue with long-running systems that use a singleton HttpClient, that requires pooling and timing the internal message handlers used by the HttpCleint. This is because the HttpHandler doesn't really respect DNS TTL, which can be a problem. So, it's generally recommended to use either the client with the PooledConnectionLifetime property or use IHttpClientFactory to help avoid these issues.

Even if you try to use a factory-created client in the options, you might still run into problems with polly policies being overridden, so a consumer would require setting up new Polly policies which may not be intended, and also not documented, which can be a pain to deal with.

Anyway, I just wanted to bring this to your attention so it can hopefully be sorted out.

HTTP Error 502.3 - Bad Gateway

Hi,
I just installed DeepL on an existing NET Core 2.2 project. When I run the project in debug (F5) I get this error message:
HTTP Error 502.3 - Bad Gateway
The project was working fine before and it is still working as soon as I remove the DeepL reference.
Thank you in advance for any advice.

Usage API

Describe the bug
The JSON (the props) of the useage API have been changed and running _translator.GetUsageAsync() only returns
{"Character":null,"Document":null,"TeamDocument":null,"AnyLimitReached":false}

To Reproduce
Steps to reproduce the behavior:

  1. _translator.GetUsageAsync()
  2. check result, will be null

Expected behavior
I expect Character to be correctly filled with a value.

Additional context
Currently SDK uses characterCount new API name is character_count

Is it meant to be used in dependency injection or not?

Hello there, I was just wondering if it makes sense to create one Translator and use dependency injection to get it to the classes it's needed in or if there should be a new Translator each time it is needed?

Best regards,
tasutafat

Optimum length to detect the Language of a text

As using the language autodetect function is counting in the usage of the api I was just wondering (based on a comment in this issue #23) what the optimum length of a text is to confidently get the language.

Use Case for this is the demand to get the language for 6000 individual texts. Sending 5.000.000 Characters when 500.000 would achieve the same result is businesswise a good descission.

Nothinng hapeens

I wrote simple script but nothing happens.
Anyone know why?

using System;
using System.Threading.Tasks;
using DeepL;

namespace translate
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("非同期作業を開始します。");
            await DoWorkAsync();
            Console.WriteLine("非同期作業が完了しました。");
        }

        static async Task DoWorkAsync()
        {
            var authKey = "";
            var translator = new Translator(authKey);

            var translatedText = await translator.TranslateTextAsync(
                  "Hello, world!",
                  LanguageCode.English,
                  LanguageCode.French);
            Console.WriteLine(translatedText);
        }
    }
}

Empty xml description

Describe the bug
Empty description when you try to view any function in Visual Studio (not sure about other IDEs), but the XML docs exist.

To Reproduce

  1. Call any function (for example ITranslator.TranslateTextAsync)
  2. Hover your mouse over any function to see a xml description
  3. See nothing

Expected behavior
Xml docs: summary, params, etc

Screenshots or sample code

var translator = new Translator("my-api-key");
var result = await translator.TranslateTextAsync(
    text: "Hi, how do you do?",
    sourceLanguageCode: "EN",
    targetLanguageCode: "PL"
);

image

Additional context
This happens because the code does not have the GenerateDocumentationFile property. Info about this property here

SecondsRemaining doesn't countdown or is 2147483647

Hi,
I try to display and update the remaining time in seconds while translating a document. I don't know what I'm doing wrong, but the remaining time either never changes or gets 2147483647 (int max) after a while. Note I don't have much experience with the Await/Async features yet.

' Upload
Dim Handle As Model.DocumentHandle = Await O_Translator.TranslateDocumentUploadAsync(New FileInfo(File.SourcePath), SourceLang.Code, TargetLang.Code, DTOptions)

' Get Status every 500ms
Do
    Await Task.Delay(500)
    Dim DocStatus = Await O_Translator.TranslateDocumentStatusAsync(Handle)
    If DocStatus.Status = Model.DocumentStatus.StatusCode.Translating Then
        Debug.WriteLine(DocStatus.SecondsRemaining)
    End If
Loop

' Download
Await O_Translator.TranslateDocumentDownloadAsync(Handle, New FileInfo(File.TargetPath))

This is a typical debug output I get with this code:

8
8
8
8
8
8
8
8
8
8
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647
2147483647

I've tried with PDF. With a larger docx I've got many lines of 49 (without the 2147483647) but still no countdown.

inconsistent no-reply with PDF translation + workaround

hi, to translate documents I use in my code the Await Translator.TranslateDocumentAsync (...) task from your API. This works flawless for DOCX and PPTX but on PDF files it is inconsistent. Regularly there is no completion of the translation task. It is not reproducible and I found no relation to file size, content, name etc.

I then checked the implementation of the task in the DeepL .NET API VS solution and it is this:

        handle = await TranslateDocumentUploadAsync(...).ConfigureAwait(false);
        await TranslateDocumentWaitUntilDoneAsync(handle.Value, cancellationToken).ConfigureAwait(false);
        await TranslateDocumentDownloadAsync(handle.Value, outputFile, cancellationToken).ConfigureAwait(false);

So I replaced Await Translator.TranslateDocumentAsync () with the above, as follows.

Dim docHandle As Model.DocumentHandle = Await _translator.TranslateDocumentUploadAsync(...)
Await _translator.TranslateDocumentWaitUntilDoneAsync(docHandle)
Await _translator.TranslateDocumentDownloadAsync(docHandle, outputFileInfo)

Using these 3 calls separately always work with PDFs and the other file types so I wonder why the single API call 'TranslateDocumentAsync' does not always work for PDFs. The only difference is that I do not use .ConfigureAwait(false) because based on the documentation and other developers, it is not needed.

Can you advise what is going on?

Is total request body size limit handled?

According to the API documentation:

"The total request body size must not exceed 128 KiB (128 · 1024 bytes). Please split up your text into multiple calls if it exceeds this limit."

Is this handled currently?

Unit tests with MS Test fail with bad System.Text.Json reference

  • I have written a small wrapper with some XLIFF handling using DeepL.NET.

    • When creating unit test with MS Test, the test failed with a System.IO.FileLoad.Exception for System.Text.Json.
    • When I use the same code in an executable, it worked fine.
  • Next, I have created some code which uses DeepL.NET directly.

    • Again, it works in the executable:
namespace Test_DeepLLibExe
{
  internal class Program
  {
    static async Task Main(string[] args)
    {

      const string ApiKey = "xxxxx";
      try
      {
        using (Translator client = new Translator(ApiKey))
        {
          var languages = await client.GetTargetLanguagesAsync();
        }

      }
      catch (Exception ex)
      {
        Console.WriteLine($"ERROR: {ex.Message}");
      }
. . .
+ => list of 31 languages
  • And fails, when called from a unit test with MS Test:
    [TestMethod]
    public async Task Test_DeepLDirect()
    {
      _logger.Info($"--- Starting {GetCurrentMethod()} ...");
      const string ApiKey = "xxxxx";
      try
      {
        using (Translator client = new Translator(ApiKey))
        {
          var languages = await client.GetTargetLanguagesAsync();
        }
      }
      catch (Exception ex)
      {
        _logger.Error($"Global error in {GetCurrentMethod()}: {ex.Message}");
      }
    }
+ => System.IO.FileLoad.Exception for System.Text.Json 
  + Message: "Could not load file or assembly 'System.Text.Json, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)":"System.Text.Json, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"
  + Source: "DeepL.net"
  + StackTrace: "   at DeepL.Internal.DeepLClient.<CheckStatusCodeAsync>d__10.MoveNext()\r\n   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)\r\n   at DeepL.Internal.DeepLClient.CheckStatusCodeAsync(HttpResponseMessage responseMessage, Boolean usingGlossary, Boolean downloadingDocument)\r\n   at DeepL.Translator.<GetLanguagesAsync>d__30`1.MoveNext()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at DeepL.Translator.<GetTargetLanguagesAsync>d__19.MoveNext()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Test_Kostal.ActivePresenter.DeepLLib.Test_DeepLRunner.<Test_DeepLDirect>d__28.MoveNext() in C:\\Users\\wagner06\\source\\APH\\activepresenterlib\\Test_DeepLLib\\Test_DeepLRunner.cs:line 277"

(screenshots have been inserted and uploaded, but that seems to be blocked)

  • In all cases, the binary folder contains System.Text.Json.dll in version 8.0.123.58001, so I do not understand the reference failure.

Expected behaviour: The code should be testable with MSTest without problems.

  • I have been using
    • VisualStudio 2022 (Version 17.7.0)
    • .NET Framework 4.8.1,
    • MSTest.TestAdapter/TestFramework (V3.2.0),
    • DeepL.net (Version 1.8.0) loaded with nuget and referenced with package references.

Additional info: A colleague from IT meant, that an improper nuget package definition might cause this problem.

Windows Executeable Fails to Launch

My deepL windows application all of a sudden stopped working after it updated. Now the Translate Text screen is blank and in the log it says it keeps trying to restart (infinite loop).
image

I've verified that I'm not having firewall issues since in the log it creates this screen from a URL
[0303/094925.825:INFO:render_frame_host_impl.cc(11654)] RenderFrameHostImpl::MaybeGenerateCrashReport url = https://www.deepl.com/en/windows/translator?windows_app_version=4.5.0.8268&theme=1, status = 0, exit_code = 0
I do not think this is a connection issue since I can open the page just fine in my browser.
image

Application: DeepL.exe
CoreCLR Version: 6.0.1423.7309
.NET Version: 6.0.14
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException: [DIE] This scope "Container" is already disposed, so it can't create a "global::DeepL.Utilities.Scheduling.IHaveMainScheduler" instance anymore.
Object name: 'Container'.
at DeepL.DI.Container.CreateIHaveMainScheduler_27_0()
at DeepL.DI.Container.<GetContainerInstanceApp_8_0>b__14_0()
at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy1.CreateValue() at System.Lazy1.get_Value()
at DeepL.Views.AppContext.Initialize()
at DeepL.Views.App.<>c__DisplayClass21_0.<.ctor>g__OnStartupLocal|4(Object sender, EventArgs e)
at System.Windows.Application.OnStartup(StartupEventArgs e)
at DeepL.Views.App.OnStartup(StartupEventArgs e)
at System.Windows.Application.<.ctor>b__1_0(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run()
at DeepL.Program.RunAsFirstInstance()
at DeepL.Program.Run()
at DeepL.Program.Main(String[] args)

deepl windows and 0install massive windows 10 overload

I dont know where to post this issue that is related to deepl app on Windows 10 and 0install.
I tried to deinstall deepl but this doesn't work either cause it starts running hundreds of 0install processes and overloads 16 GB of RAM.

0install/0install-win#180 (comment)

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Use function '...'
  2. Check the result
  3. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots or sample code
If applicable, add screenshots or sample code to help explain your problem.

Additional context
Add any other context about the problem here.

Prevent Libary users from using the DocumentHandle constructor

As you stated in DeepL.Model.DocumentHandle The constructor for this class (and all other Model classes) should not be used by library users I have questioned myself why you are not making the constructor Obsolete with an explanation or creating an custom converter?

'formality' is not supported for given 'target_lang'

I encountered an error when attempting to use Ukrainian as the target language with the formality option.:

Bad request, message: 'formality' is not supported for given 'target_lang'.

My code is

var options = new TextTranslateOptions { Formality = Formality.Less};
var textResults = await _translator.TranslateTextAsync(text, "en", "uk", options);

Is it possible for this to occur with other languages as well? Is there a way for me to anticipate this issue without having to manually check each language?

Azure Functions - Don't Like System.Text.Json

I have been trying to use deepl in an Azure Function and am battling against errors because of System.Text.Json.

Error:
System.AggregateException: One or more errors occurred. ---> System.IO.FileNotFoundException: Could not load file or assembly 'System.Text.Json, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.

Issue is mentioned in this issue:
Azure/azure-functions-host#5469

What I am wondering, is if it is possible to use Newtonsoft.Json instead of System.Text.Json. Microsoft seem to be moving everything over to Newtonsoft instead.

Unit testability of Package

Describe the bug
I have implemented the deepl translator in my own package for own development. Now i am trying to unit test my own software, which means i want to essentially mock everything the translator performs. However, i can't simply Mock for example the Usage object, because it is a sealed class and it does not have an interface. I'm not sure if there is any other classes like this, but it would be nice to be able to mock these objects for tests.

Ofcourse, i can write my own layer above the translator object and Usage object, so that i can mock it.. but in my opinion this is a responsibility of the delivering library.

So.. sorry, not a bug, more like a feature request that would help every developer trying to integrate this package into their own software :)

If i've missed any approach on how to deal with the sealed classes without interface please let me know! I might have overlooked a easy way to fix the issue..

Screenshots or sample code
Heres an example of the code i would like to have in my tests:

image

Add support for output_format, code included

Describe the bug
The new version of the API https://www.deepl.com/cs/docs-api/documents/translate-document includes support for the optional output_format parameter, but there is no implementation in deepl-dotnet.

To Reproduce
var options = new DocumentTranslateOptions();
options.OutputFormat = "docx";

Expected behavior
DocumentTranslateOptions have an OutputFormat parameter, I can set it to "docx" to change PDF to Word during translation.

Screenshots or sample code
Expected final code:

var translator = new Translator(ServiceApiKey);
var options = new DocumentTranslateOptions();
options.OutputFormat = "docx";
var handle = await translator.TranslateDocumentUploadAsync(filepath, sourceLanguage, targetLanguage, options);

Files to change:

DeepL/DocumentTranslateOptions.cs

    /// <summary>File extension of desired format of translated file, for example: docx.</summary>
    /// If unspecified, by default the translated file will be in the same format as the input file.
    public string? OutputFormat { get; set; }

DeepL/Translator.cs

/// <inheritdoc />
public async Task<DocumentHandle> TranslateDocumentUploadAsync(
      Stream inputFile,
      string inputFileName,
      string? sourceLanguageCode,
      string targetLanguageCode,
      DocumentTranslateOptions? options = null,
      CancellationToken cancellationToken = default) {
  var bodyParams = CreateCommonHttpParams(
        sourceLanguageCode,
        targetLanguageCode,
        options?.Formality,
        options?.GlossaryId);

  if (options?.OutputFormat != null) {
    bodyParams.Add(("output_format", options.OutputFormat));
  }

  using var responseMessage =  
(...)

Translations from German to English generate errors

Hello,

we use version 1.0.4.

If we try to translate "Dog" from english to german like this ...

var translator = new Translator(Settings.DeeplTranslatorTextKey);
TextResult textResult = await translator.TranslateTextAsync("Dog", LanguageCode.EnglishAmerican, LanguageCode.German);

... we get the following error:

Bad request, message: Value for 'source_lang' not supported.

at DeepL.Internal.DeepLClient.d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at DeepL.Translator.d__8.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at DeepL.Translator.<TranslateTextAsync>d__9.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()

If we try to translate "Hund" from german to english, everything works fine.

Inconsistent translation (non-glossary) Dutch to English (British and American)

Hi DeepL team, i'm really happy with your API solution and it's a great boost to our business.

Recently we did a translation of customer document - twice over the span of 3-4 months) and discovered on both occasions a huge variation of the translation of the same original Dutch words.

The words in question are somewhat industry specific so we did not expect a good translation out of the box, but to our suprise the same word got translated in 17 different ways (dito with the plural) - the word mostly occurred in sentences so plenty of context for the DeepL engine we assume. Total document size approx. 70 pages.

Original Dutch word: Dienstindeler
Preferred translation: shift planner
DeepL generated translations: Service Informer, Service User, service marker, service provider, duty manager, duty scheduler, service administrator, Service Inspector, service director, service scheduler, service evaluator, service integrator, service area, service end-user, service end user, service member, service participant

We ended up using our own post-translation glossary fixer to go from 17 variations back to the preferred translation.

I don't assume this is related to #16 but who knows ...

Keep up the good work!

Endpoint detection issue (Free / Paid Deepl API endpoint)

Hi,
the following exception is thrown using a AuthKey from a paid "DeepL API Pro" subscription.

DeepL.AuthorizationException
Authorization failure, check AuthKey, message: Wrong endpoint. Use https://api.deepl.com

The result of [Translator.AuthKeyIsFreeAccount] says that is an free account. Because the AuthKey ends with the ":fx" suffix.

if(Translator.AuthKeyIsFreeAccount("*****:fx") == true) {
     // this should be a AuthKey for a free account use endpoint "https://api-free.deepl.com"
}

public static bool AuthKeyIsFreeAccount(string authKey) => authKey.TrimEnd().EndsWith(":fx");

The docs says 'DeepL API Free authentication keys can be identified easily by the suffix ":fx"'.
https://www.deepl.com/docs-api/accessing-the-api/authentication/

But using the AuthKey ending with suffix ":fx" results in the authorization failure.
Explicit setting the ServerUrl to https://api.deepl.com is a workaround.

But what I'm doing wrong?
Or is the generated key shown on the account page (https://www.deepl.com/de/pro-account/summary) wrong?

"invalid start of a value" when trying to translate

Describe the bug
We've are using the package in our WinForm app using Telerik 2023.2.60653, .Net Framework 4.7.2, package latest 1.7.1
I have developed a feature where a user can select which language it wants to translate to, in our case English or Hungarian
Lets say we have posts, and each post can have comments, when the user wants to translate, we translate all the comments.
When translating to English it goes well, no problem, but when I want to translate to Hungarian (does not matter if the original language is Hungarian or not) I get the error showed below. Whether I translate to English first or second I get the same result
I've been trying to reproduce the problem in a console app, but simply unable to do so, even our users have different experience, some reported that they get the error on the first try.
We use HTML to display the comments, we use CefSharp to display a chromium browser inside the WinForm app.

Update 1:
For me it does not matter if I do translate fast with 1-2 secs between the two requests or wait 1-2 minutes, basically every second request gets this error, whether I start with English or Hungarian.
My colleagues experience difference if they wait a certain amount of time or not.
I've tried to make demos which I could upload here making your jobs easier, but I can not make it fail...
Somehow it fails in our app, but when I make a mini environment which represents our app, with the same code which makes the API call, I cant make it to fail as it does in our app

Expected behavior
We get back the translation no problem

  • Stack trace:

at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.<ReadAsync>d__201.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at DeepL.Internal.JsonUtils.d__41.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at DeepL.Internal.JsonUtils.<DeserializeAsync>d__31.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at DeepL.Translator.d__8.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Our class which inherits from UserControl.d__114.MoveNext() in the line of our cs file

  • Source:

System.Text.Json

  • Path:

$

  • Message:

'<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.

Screenshots or sample code

private void button_click(object sender, EventArgs e)
{
        RadButton translateButton = (RadButton)sender;
        if (translateButton == null) return;

        string targetLanguage = translateButton.Name == "translateToHungarianButton" ? LanguageCode.Hungarian : LanguageCode.EnglishAmerican;
        string sourceLanguage = targetLanguage == LanguageCode.Hungarian ? "EN" : "HU";
        Task.Run(async () => await TranslateText(commentList, sourceLanguage ,targetLanguage ));
}
private async Task TranslateText(string[] textsToTranslate, string sourceLanguage, string targetLanguage)
{
        TextResult[] translatedTexts;
        try
        {
                translatedTexts = await translator.TranslateTextAsync(textsToTranslate, sourceLanguage, targetLanguage, new TextTranslateOptions() { TagHandling = "xml", IgnoreTags = { "a" }, PreserveFormatting = true });
        }
        catch (Exception e)
        {
                MessageBox.Show($"Error: {e}");
                throw;
        }
}

If you guys need any more info please let me know!
The problem could be solved with an easy fix, it might be my lack of knowledge

Incorrect translation from English to Ukrainian if the string contains symbol #

If the string includes the symbol #, the English to Ukrainian translation may not be accurate.
Please see the code below

var translator = new Translator(authKey);

var correctTranslation = await translator.TranslateTextAsync("Test Dress-code", LanguageCode.English, LanguageCode.Ukrainian);
var incorrectTranslation = await translator.TranslateTextAsync("Test Dress-code#", LanguageCode.English, LanguageCode.Ukrainian);
Console.WriteLine(correctTranslation);      //Printed: Тестовий дрес-код - Correct
Console.WriteLine(incorrectTranslation);    //Printed: Тестовий дресс-код## Тестовий дресс-код##. - Incorrect

I checked the text on deepl.com, and the translation is functioning correctly there.

Mocking the Translator

Hello DeepL-Team,

Could you please either introduce an interface ITranslator, or make the methods of the Translator class virtual? We could use this for our unit tests so that we don't have to fall back to mocking the HttpMessageHandler used by the DeepLClient.

Thanks in advance!

Why do I get a CORS error, even though I allowed it with the chrome extension like always?

Hello, I want to develop a Blazor WASM app, and want to use DeepL service. But when I run the translation, I get this:
Access to fetch at 'https://api-free.deepl.com/v2/translate' from origin 'https://localhost:44379' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Any suggestions? When I tried the exact same code in console, it worked without a problem.

Improve the documentation associated with SentenceSplittingMode

Describe the bug
This is an improved documentation suggestion more than a bug.

  1. The expected impact of the enum DeepL.SentenceSplittingMode.cs in DeepL.Translator.TranslateTextAsync is poorly documented.
  2. The expected impact cannot be determined in its corresponding unit test; the tests are poorly implemented as they assert only for a non-exception rather than a positively-expected outcome.

Specifically, if and how a new line character \n may or may not be retained is not explained.

To Reproduce
Steps to reproduce the behavior:

  1. Review the documentation

Enum controlling how input translation text should be split into sentences.

This says nothing for how this input translation text impacts the output translation text.

  1. Review the unit tests
      var translator = CreateTestTranslator();
      const string text = "If the implementation is hard to explain, it's a bad idea.\n" +
                          "If the implementation is easy to explain, it may be a good idea.";

      await translator.TranslateTextAsync(
            text,
            null,
            "DE",
            new TextTranslateOptions { SentenceSplittingMode = SentenceSplittingMode.Off });

Expected behavior

  1. Documentation should be made describing how the enum value impacts our expected output translation text.
  2. Existing unit test should be replaced by unit tests that ensure this expected behaviour is adhered to.

Spanish Auto detection

Hello,
The auto detection works great with a lot of language but I have an issue when I want to auto detect spanish text.
When I use autodetect with Spanish, the result is the same as the source text.

How it's possible to fix it ?

Thanks

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.