public DeepLTranslationProviderConnecter(string key, Formality formality)
        {
            ApiKey     = key;
            _formality = formality;

            try
            {
                // fetch the version of the plugin from the manifest deployed
                var pexecutingAsseblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                pexecutingAsseblyPath = Path.Combine(pexecutingAsseblyPath, "pluginpackage.manifest.xml");
                var doc = new XmlDocument();
                doc.Load(pexecutingAsseblyPath);

                if (doc.DocumentElement == null)
                {
                    return;
                }
                foreach (XmlNode n in doc.DocumentElement.ChildNodes)
                {
                    if (n.Name == "Version")
                    {
                        _pluginVersion = n.InnerText;
                    }
                }
            }
            catch (Exception e)
            {
                // broad catch here, if anything goes wrong with determining the version we don't want the user to be disturbed in any way
                _logger.Error($"{e.Message}\n {e.StackTrace}");
            }
        }
        public string Translate(LanguagePair languageDirection, string sourceText)
        {
            _formality = Helpers.IsLanguageCompatible(languageDirection.TargetCulture) ? _formality : Formality.Default;

            var targetLanguage  = GetLanguage(languageDirection.TargetCulture, SupportedTargetLanguages);
            var sourceLanguage  = GetLanguage(languageDirection.SourceCulture, SupportedSourceLanguages);
            var translatedText  = string.Empty;
            var normalizeHelper = new NormalizeSourceTextHelper();

            try
            {
                sourceText = normalizeHelper.NormalizeText(sourceText);

                using (var httpClient = new HttpClient())
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                    httpClient.Timeout = TimeSpan.FromMinutes(5);
                    var content = new StringContent($"text={sourceText}" +
                                                    $"&source_lang={sourceLanguage}" +
                                                    $"&target_lang={targetLanguage}" +
                                                    $"&formality={_formality.ToString().ToLower()}" +
                                                    "&preserve_formatting=1" +
                                                    "&tag_handling=xml" +
                                                    $"&auth_key={ApiKey}",
                                                    Encoding.UTF8, "application/x-www-form-urlencoded");

                    httpClient.DefaultRequestHeaders.Add("Trace-ID", $"SDL Trados Studio 2021 /plugin {_pluginVersion}");

                    var response = httpClient.PostAsync("https://api.deepl.com/v2/translate", content).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var translationResponse = response.Content?.ReadAsStringAsync().Result;
                        var translatedObject    = JsonConvert.DeserializeObject <TranslationResponse>(translationResponse);

                        if (translatedObject != null && translatedObject.Translations.Any())
                        {
                            translatedText = translatedObject.Translations[0].Text;
                            translatedText = DecodeWhenNeeded(translatedText);
                        }
                    }
                    else
                    {
                        var message =
                            $"HTTP Request to DeepL Translate REST API endpoint failed with status code '{response.StatusCode}'. " +
                            $"Response content: {response.Content?.ReadAsStringAsync().Result}.";
                        _logger.Error(message);
                        throw new HttpRequestException(message);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error($"{e.Message}\n {e.StackTrace}");
                throw;
            }

            return(translatedText);
        }
예제 #3
0
        public DeepLTranslationProviderConnecter(string key, Formality formality)
        {
            ApiKey     = key;
            _formality = formality;

            SupportedTargetLanguagesAndFormalities = Helpers.GetSupportedTargetLanguages(ApiKey);
            SupportedTargetLanguages = SupportedTargetLanguagesAndFormalities.Keys.ToList();
        }
        public string Translate(LanguagePair languageDirection, string sourceText)
        {
            _formality = Helpers.IsLanguageCompatible(languageDirection.TargetCulture) ? _formality : Formality.Default;

            var targetLanguage  = GetLanguage(languageDirection.TargetCulture, SupportedTargetLanguages);
            var sourceLanguage  = GetLanguage(languageDirection.SourceCulture, SupportedSourceLanguages);
            var translatedText  = string.Empty;
            var normalizeHelper = new NormalizeSourceTextHelper();

            try
            {
                sourceText = normalizeHelper.NormalizeText(sourceText);

                var content = new StringContent($"text={sourceText}" +
                                                $"&source_lang={sourceLanguage}" +
                                                $"&target_lang={targetLanguage}" +
                                                $"&formality={_formality.ToString().ToLower()}" +
                                                "&preserve_formatting=1" +
                                                "&tag_handling=xml" +
                                                $"&auth_key={ApiKey}",
                                                Encoding.UTF8, "application/x-www-form-urlencoded");

                var response = DeeplApplicationInitializer.Clinet.PostAsync("https://api.deepl.com/v1/translate", content).Result;
                response.EnsureSuccessStatusCode();

                var translationResponse = response.Content?.ReadAsStringAsync().Result;
                var translatedObject    = JsonConvert.DeserializeObject <TranslationResponse>(translationResponse);

                if (translatedObject != null && translatedObject.Translations.Any())
                {
                    translatedText = translatedObject.Translations[0].Text;
                    translatedText = DecodeWhenNeeded(translatedText);
                }
            }
            catch (AggregateException aEx)
            {
                foreach (var innerEx in aEx.InnerExceptions)
                {
                    _logger.Error(innerEx);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }

            return(translatedText);
        }
 public DeepLTranslationProviderConnecter(string key, Formality formality = Formality.Default)
 {
     ApiKey    = key;
     Formality = formality != Formality.Default ? formality : Formality;
 }
예제 #6
0
        /// <summary>
        /// initialize formality structures
        /// </summary>
        /// <param name="ALanguageCode"></param>
        /// <param name="ACountryCode"></param>
        /// <param name="AAddresseeTypeCode"></param>
        /// <param name="AFormalityLevel"></param>
        /// <param name="ASalutationText"></param>
        /// <param name="AClosingText"></param>
        /// <returns></returns>
        public void AddFormality(String ALanguageCode, String ACountryCode, String AAddresseeTypeCode,
            Int32 AFormalityLevel, String ASalutationText, String AClosingText)
        {
            if (FormalityList == null)
            {
                FormalityList = new List <Formality>();
            }

            Formality NewFormality = new Formality();
            NewFormality.LanguageCode = ALanguageCode;
            NewFormality.CountryCode = ACountryCode;
            NewFormality.AddresseeTypeCode = AAddresseeTypeCode;
            NewFormality.FormalityLevel = AFormalityLevel;
            NewFormality.SalutationText = ASalutationText;
            NewFormality.ClosingText = AClosingText;

            FormalityList.Add(NewFormality);
        }
 public DeepLTranslationProviderConnecter(string key, Formality formality)
 {
     ApiKey     = key;
     _formality = formality;
 }