Пример #1
0
        public void TranslateTest()
        {
            var request = new TranslateRequest
            {
                Target = "da",
                Qs     = new[] { "Hello World" },
                Key    = this.ApiKey
            };

            var result = GoogleTranslate.Translate.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var translations = result.Data.Translations?.ToArray();

            Assert.IsNotNull(translations);
            Assert.IsNotEmpty(translations);

            var translation = translations.FirstOrDefault();

            Assert.IsNotNull(translation);
            Assert.AreEqual("Hej Verden", translation.TranslatedText);
            Assert.AreEqual("en", translation.DetectedSourceLanguage);
        }
Пример #2
0
        public async Task <string> Translate(string text)
        {
            try
            {
                if (string.IsNullOrEmpty(text))
                {
                    return(string.Empty);
                }

                var requestModel = new TranslateRequest
                {
                    Text    = text,
                    ModelId = "ro-en"
                };
                var response = await _client.PostAsync("",
                                                       new StringContent(JsonConvert.SerializeObject(requestModel), Encoding.UTF8, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    var translateResponse = await response.Content.ReadAsAsync <TranslateResponse>();

                    return(translateResponse.Translations.First().Translation);
                }
            }
            catch { }

            return(null);
        }
        public async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!configuration.IsAppropriateForTranslation(TranslatorType, translateRequest.FromLanguageExtension))
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            var parameter =
                $"sl=auto&text={Uri.EscapeUriString(translateRequest.CurrentText)}&tl={configuration.ToLanguageExtension}";

            var response = await new RestClient(configuration.SesliSozlukUrl)
            {
                Encoding    = Encoding.UTF8,
                CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1))
            }.ExecutePostTaskAsync(
                new RestRequest(Method.POST)
                .AddHeader("accept-language", "en-US,en;q=0.8,tr;q=0.6")
                .AddHeader("accept-encoding", "gzip, deflate")
                .AddHeader("content-type", "application/x-www-form-urlencoded")
                .AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36")
                .AddHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .AddParameter("application/x-www-form-urlencoded", parameter, ParameterType.RequestBody));

            var meanOrganizer = meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType);
            var mean          = await meanOrganizer.OrganizeMean(response.Content);

            return(new TranslateResult(true, mean));
        }
Пример #4
0
        public async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!configuration.IsAppropriateForTranslation(TranslatorType, translateRequest.FromLanguageExtension))
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            var uri = string.Format(configuration.ZarganTranslateUrl, HttpUtility.UrlEncode(translateRequest.CurrentText, Encoding.UTF8));

            var compositeMean = await new RestClient(uri)
            {
                Encoding = Encoding.UTF8
            }
            .ExecuteGetTaskAsync(
                new RestRequest(Method.GET)
                .AddHeader("Accept-Language", "en-US,en;q=0.8,tr;q=0.6")
                .AddHeader("Accept-Encoding", "gzip, deflate, sdch")
                .AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36")
                .AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));

            var organizer = meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType);
            var mean      = await organizer.OrganizeMean(compositeMean.Content, translateRequest.FromLanguageExtension);

            return(new TranslateResult(true, mean));
        }
Пример #5
0
        public void TranslateWhenAsyncTest()
        {
            var request = new TranslateRequest
            {
                Key    = this.ApiKey,
                Source = Language.English,
                Target = Language.Danish,
                Qs     = new[] { "Hello World" }
            };

            var result = GoogleTranslate.Translate.QueryAsync(request).Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var translations = result.Data.Translations?.ToArray();

            Assert.IsNotNull(translations);
            Assert.IsNotEmpty(translations);

            var translation = translations.FirstOrDefault();

            Assert.IsNotNull(translation);
            Assert.AreEqual("Hej Verden", translation.TranslatedText);
            Assert.AreEqual(Model.Base, translation.Model);
            Assert.IsNull(translation.DetectedSourceLanguage);
        }
        public async Task <string> TranslateAsync(string text)
        {
            var languages              = _translationConfig.Value.Languages;
            var textToTranslate        = text;
            var detectLanguageResponse = await _client.DetectLanguageAsync(new DetectLanguageRequest
            {
                Text = text
            });

            var sourceLanguage = detectLanguageResponse.LanguageCode;

            foreach (var targetLanguage in languages.Append(sourceLanguage))
            {
                var request = new TranslateRequest
                {
                    Format             = TranslateRequest.Types.Format.PlainText,
                    SourceLanguageCode = sourceLanguage,
                    TargetLanguageCode = targetLanguage,
                    Texts = { textToTranslate }
                };
                var translationResponse = await _client.TranslateAsync(request);

                textToTranslate = translationResponse.Translations[0].Text;
                sourceLanguage  = targetLanguage;
            }
            return(textToTranslate);
        }
        public async Task <TranslateResult> Translate(TranslateRequest translateRequest,
                                                      CancellationToken cancellationToken)
        {
            var uri = new Uri(this.tureng.Url + translateRequest.CurrentText);

            HttpClient httpClient = this.clientFactory.CreateClient(TranslatorClient.Name)
                                    .With(client => { client.BaseAddress = uri; });

            var req = new HttpRequestMessage {
                Method = HttpMethod.Get
            };

            req.Headers.Add(Headers.UserAgent, UserAgent);
            req.Headers.Add(Headers.AcceptLanguage, AcceptLanguage);

            HttpResponseMessage response = await httpClient.SendAsync(req, cancellationToken);

            var mean = string.Empty;

            if (response.IsSuccessStatusCode)
            {
                mean = OrganizeMean(await response.Content.ReadAsStringAsync(cancellationToken),
                                    translateRequest.FromLanguageExtension);
            }

            return(new TranslateResult(true, mean));
        }
        protected override async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            var uri = new Uri(string.Format(Configuration.Url,
                                            translateRequest.CurrentText,
                                            translateRequest.FromLanguageExtension + _applicationConfiguration.ToLanguage.Extension)
                              );

            IRestResponse response = await _restClient
                                     .Manipulate(client =>
            {
                client.BaseUrl     = uri;
                client.Encoding    = Encoding.UTF8;
                client.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1));
            }).ExecuteGetTaskAsync(
                new RestRequest(Method.GET)
                .AddHeader(Headers.UserAgent, UserAgent)
                .AddHeader(Headers.AcceptLanguage, AcceptLanguage));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                mean = await MeanOrganizer.OrganizeMean(response.Content, translateRequest.FromLanguageExtension);
            }

            return(new TranslateResult(true, mean));
        }
Пример #9
0
        public void TranslateWhenAsyncAndTimeoutTest()
        {
            var request = new TranslateRequest
            {
                Key    = this.ApiKey,
                Source = Language.English,
                Target = Language.Danish,
                Qs     = new[] { "Hello World" }
            };

            var exception = Assert.Throws <AggregateException>(() =>
            {
                var result = GoogleTranslate.Translate.QueryAsync(request, TimeSpan.FromMilliseconds(1)).Result;
                Assert.IsNull(result);
            });

            Assert.IsNotNull(exception);
            Assert.AreEqual(exception.Message, "One or more errors occurred.");

            var innerException = exception.InnerException;

            Assert.IsNotNull(innerException);
            Assert.AreEqual(innerException.GetType(), typeof(TaskCanceledException));
            Assert.AreEqual(innerException.Message, "A task was canceled.");
        }
 private void ModifyRequest(TranslateRequest request, TranslateTextRequest body, string sourceLanguage, string format, TranslationModel?model)
 {
     request.ModifyRequest += _versionHeaderAction;
     body.Source            = sourceLanguage;
     body.Format            = format;
     body.Model             = GetEffectiveModelName(model);
 }
        protected override async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            string parameter = $"sl=auto&text={Uri.EscapeUriString(translateRequest.CurrentText)}&tl={_applicationConfiguration.ToLanguage.Extension}";

            IRestResponse response = await _restClient.Manipulate(client =>
            {
                client.BaseUrl     = Configuration.Url.ToUri();
                client.Encoding    = Encoding.UTF8;
                client.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1));
            }).ExecutePostTaskAsync(
                new RestRequest(Method.POST)
                .AddHeader(Headers.AcceptLanguage, AcceptLanguage)
                .AddHeader(Headers.AcceptEncoding, AcceptEncoding)
                .AddHeader(Headers.ContentType, ContentType)
                .AddHeader(Headers.UserAgent, UserAgent)
                .AddHeader(Headers.Accept, Accept)
                .AddParameter(ContentType, parameter, ParameterType.RequestBody));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                mean = await MeanOrganizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
Пример #12
0
        public void TranslateWhenModelIsNmtAndDetectedSourceLanguageTest()
        {
            var request = new TranslateRequest
            {
                Key    = this.ApiKey,
                Target = Language.German,
                Model  = Model.Nmt,
                Qs     = new[] { "Hello my friend" }
            };

            var result = GoogleTranslate.Translate.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var translations = result.Data.Translations?.ToArray();

            Assert.IsNotNull(translations);
            Assert.IsNotEmpty(translations);

            var translation = translations.FirstOrDefault();

            Assert.IsNotNull(translation);
            Assert.AreEqual("Hallo, mein Freund", translation.TranslatedText);
            Assert.AreEqual(Model.Nmt, translation.Model);
            Assert.AreEqual(Language.English, translation.DetectedSourceLanguage);
        }
        public async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!_googleConfiguration.CanSupport() || !_googleConfiguration.IsActive())
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            string uri = string.Format(
                _googleConfiguration.Url,
                _applicationConfiguration.ToLanguage.Extension,
                _applicationConfiguration.ToLanguage.Extension,
                HttpUtility.UrlEncode(translateRequest.CurrentText, Encoding.UTF8));

            IRestResponse response = await _restClient.Manipulate(client =>
            {
                client.BaseUrl  = uri.ToUri();
                client.Encoding = Encoding.UTF8;
            })
                                     .ExecuteGetTaskAsync(
                new RestRequest(Method.GET)
                .AddHeader(Headers.AcceptLanguage, AcceptLanguage)
                .AddHeader(Headers.AcceptEncoding, AcceptEncoding)
                .AddHeader(Headers.UserAgent, UserAgent)
                .AddHeader(Headers.Accept, Accept));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                IMeanOrganizer organizer = _meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType);
                mean = await organizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
Пример #14
0
        protected override async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            string uri = string.Format(
                Configuration.Url,
                _applicationConfiguration.ToLanguage.Extension,
                _applicationConfiguration.ToLanguage.Extension,
                HttpUtility.UrlEncode(translateRequest.CurrentText, Encoding.UTF8));

            IRestResponse response = await _restClient.Manipulate(client =>
            {
                client.BaseUrl  = uri.ToUri();
                client.Encoding = Encoding.UTF8;
            })
                                     .ExecuteGetTaskAsync(
                new RestRequest(Method.GET)
                .AddHeader(Headers.AcceptLanguage, AcceptLanguage)
                .AddHeader(Headers.AcceptEncoding, AcceptEncoding)
                .AddHeader(Headers.UserAgent, UserAgent)
                .AddHeader(Headers.Accept, Accept));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                mean = await MeanOrganizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
Пример #15
0
        public async Task <TranslateResponse> Translate(TranslateRequest translateRequest)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(translateRequest.Meta.From))
                {
                    var language = await GetLanguageDetectorClient(translateRequest.Meta.Vendor).GetLanguage(translateRequest.Items.First().Value);

                    translateRequest.Meta.From = language;
                }

                return(await GetResponse(translateRequest));
            }
            catch (Exception e)
            {
                return(new TranslateResponse()
                {
                    Errors = new List <Error>()
                    {
                        new Error()
                        {
                            Message = e.Message
                        }
                    }
                });
            }
        }
Пример #16
0
        protected override string Translate(string value, string fromLanguage, string toLanguage, string fromApiLanguage, string toApiLanguage)
        {
            if (string.IsNullOrEmpty(tracking))
            {
                tracking = GetTracking();
            }

            TranslateRequest request = new TranslateRequest()
            {
                text = WebUtils.FormatJson(value),
                from = fromApiLanguage,
                to   = toApiLanguage
            };
            string requestJson = JSONSerializer <TranslateRequest> .Serialize(request);

            using (WebClient webClient = new WebClient())
            {
                string url = "https://www.freetranslation.com/gw-mt-proxy-service-web/mt-translation";

                webClient.Proxy    = null;
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json; charset=UTF-8";
                webClient.Headers["Tracking"] = tracking;
                string            json     = webClient.UploadString(url, requestJson);
                TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                return(response.translation);
            }
        }
        /// <summary>
        /// Translate. Translates the input text from the source language to the target language.
        /// </summary>
        /// <param name="request">The translate request containing the text, and either a model ID or source and target language pair.</param>
        /// <param name="customData">Custom data object to pass data including custom request headers.</param>
        /// <returns><see cref="TranslationResult" />TranslationResult</returns>
        public TranslationResult Translate(TranslateRequest request, Dictionary <string, object> customData = null)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            TranslationResult result = null;

            try
            {
                IClient client;
                client = this.Client.WithAuthentication(this.UserName, this.Password);
                var restRequest = client.PostAsync($"{this.Endpoint}/v2/translate");

                restRequest.WithBody <TranslateRequest>(request);
                if (customData != null)
                {
                    restRequest.WithCustomData(customData);
                }
                result = restRequest.As <TranslationResult>().Result;
                if (result == null)
                {
                    result = new TranslationResult();
                }
                result.CustomData = restRequest.CustomData;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
        public async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!_sesliSozlukConfiguration.CanSupport() || !_sesliSozlukConfiguration.IsActive())
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            string parameter = $"sl=auto&text={Uri.EscapeUriString(translateRequest.CurrentText)}&tl={_applicationConfiguration.ToLanguage.Extension}";

            var response = await new RestClient(_sesliSozlukConfiguration.Url)
            {
                Encoding    = Encoding.UTF8,
                CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1))
            }.ExecutePostTaskAsync(
                new RestRequest(Method.POST)
                .AddHeader(Headers.AcceptLanguage, AcceptLanguage)
                .AddHeader(Headers.AcceptEncoding, AcceptEncoding)
                .AddHeader(Headers.ContentType, ContentType)
                .AddHeader(Headers.UserAgent, UserAgent)
                .AddHeader(Headers.Accept, Accept)
                .AddParameter(ContentType, parameter, ParameterType.RequestBody));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                var meanOrganizer = _meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType);
                mean = await meanOrganizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
        protected override async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            string uri = string.Format(Configuration.Url,
                                       HttpUtility.UrlEncode(translateRequest.CurrentText, Encoding.UTF8));

            IRestResponse response = await new RestClient(uri)
            {
                Encoding = Encoding.UTF8
            }
            .ExecuteGetTaskAsync(
                new RestRequest(Method.GET)
                .AddHeader("Accept-Language", "en-US,en;q=0.8,tr;q=0.6")
                .AddHeader("Accept-Encoding", "gzip, deflate, sdch")
                .AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36")
                .AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                mean = await MeanOrganizer.OrganizeMean(response.Content, translateRequest.FromLanguageExtension);
            }

            return(new TranslateResult(true, mean));
        }
Пример #20
0
        public void TranslateWhenMultipleQsTest()
        {
            var request = new TranslateRequest
            {
                Key    = this.ApiKey,
                Target = Language.Danish,
                Qs     = new[] { "Hello World", "Once upon a time" }
            };

            var result = GoogleTranslate.Translate.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var translations = result.Data.Translations?.ToArray();

            Assert.IsNotNull(translations);
            Assert.IsNotEmpty(translations);
            Assert.AreEqual(2, translations.Length);

            var translation1 = translations[0];

            Assert.IsNotNull(translation1);
            Assert.AreEqual("Hej Verden", translation1.TranslatedText);
            Assert.AreEqual(Language.English, translation1.DetectedSourceLanguage);

            var translation2 = translations[1];

            Assert.IsNotNull(translation2);
            Assert.AreEqual("Der var engang", translation2.TranslatedText);
            Assert.AreEqual(Language.English, translation2.DetectedSourceLanguage);
        }
        protected override async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            var requestObject = new
            {
                languageFrom = _applicationConfiguration.FromLanguage.Name.ToLower(),
                languageTo   = _applicationConfiguration.ToLanguage.Name.ToLower(),
                txtTrans     = translateRequest.CurrentText
            };

            IRestResponse response = await _restClient
                                     .Manipulate(client => client.BaseUrl = Configuration.Url.ToUri())
                                     .ExecutePostTaskAsync(
                new RestRequest(Method.POST)
                .AddHeader(ContentTypeName, ContentType)
                .AddParameter(ContentType, requestObject.ToJsonString(true), ParameterType.RequestBody)
                );

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                mean = await MeanOrganizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
Пример #22
0
        static List <Translations> Translate(RestClient restClient, List <string> text)
        {
            bool retry = true;
            IRestResponse <TranslateData> response = null;

            while (retry)
            {
                retry = false;
                var request = new RestRequest();
                request.Method        = Method.POST;
                request.Resource      = "https://translation.googleapis.com/language/translate/v2?key=AIzaSyAq4YjOz-ulbEsEkYi6eqKBY0Usks8fLtk";
                request.RequestFormat = DataFormat.Json;
                var data = new TranslateRequest
                {
                    q      = text,
                    target = "es"
                };

                request.AddJsonBody(data);

                response = restClient.Post <TranslateData>(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Console.WriteLine($"Error: {JsonConvert.SerializeObject(response.Data)}");
                    Console.WriteLine($"Retry in 10 seconds...");
                    retry = true;
                    Thread.Sleep(10000);
                }
            }

            return(response?.Data?.data?.translations);
        }
Пример #23
0
        public async Task <HttpResponseMessage> Translate([FromBody] TranslateRequest translateRequest)
        {
            gitHubService.CloneProject(translateRequest.repositoryLink);
            var checkBranch = gitHubService.CheckBranch();

            if (!checkBranch)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Brach with name 'InternationalizationApp' does not exist"));
            }

            var result = await fileService.CheckAllFiles(translateRequest.to, translateRequest.from);

            if (!result)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Something went wrong please try again later."));
            }

            var changesPushed = gitHubService.PushChanges();

            if (changesPushed)
            {
                fileService.DeleteWorkingFiles();
                return(Request.CreateResponse(HttpStatusCode.OK, "your project has been succesfully translated and internationalized."));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.OK, "Something went wrong. Could not push to GitHubRepository"));
            }
        }
Пример #24
0
        public async Task <TranslateResult> Translate(TranslateRequest request, CancellationToken cancellationToken)
        {
            if (!this.google.CanSupport() || !this.google.IsActive())
            {
                return(new TranslateResult());
            }

            string uri = string.Format(this.google.Url, this.applicationConfiguration.ToLanguage.Extension,
                                       this.applicationConfiguration.ToLanguage.Extension,
                                       HttpUtility.UrlEncode(request.CurrentText, Encoding.UTF8));

            HttpClient httpClient = this.httpClientFactory.CreateClient("translator").With(client =>
            {
                client.BaseAddress = uri.ToUri();
            });

            var req = new HttpRequestMessage {
                Method = HttpMethod.Get
            };

            req.Headers.Add(Headers.AcceptLanguage, AcceptLanguage);
            req.Headers.Add(Headers.AcceptEncoding, AcceptEncoding);
            req.Headers.Add(Headers.UserAgent, UserAgent);
            req.Headers.Add(Headers.Accept, Accept);
            HttpResponseMessage response = await httpClient.SendAsync(req, cancellationToken);

            var mean = string.Empty;

            if (response.IsSuccessStatusCode)
            {
                mean = MakeMeaningful(await response.Content.ReadAsStringAsync(cancellationToken));
            }

            return(new TranslateResult(true, mean));
        }
        public async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!_turengConfiguration.CanSupport())
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            if (!_turengConfiguration.IsActive())
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            var uri = new Uri(_turengConfiguration.Url + translateRequest.CurrentText);

            IRestResponse response = await _restClient
                                     .Manipulate(client =>
            {
                client.BaseUrl     = uri;
                client.Encoding    = Encoding.UTF8;
                client.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1));
            }).ExecuteGetTaskAsync(
                new RestRequest(Method.GET)
                .AddHeader(Headers.UserAgent, UserAgent)
                .AddHeader(Headers.AcceptLanguage, AcceptLanguage));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                IMeanOrganizer organizer = _meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType);
                mean = await organizer.OrganizeMean(response.Content, translateRequest.FromLanguageExtension);
            }

            return(new TranslateResult(true, mean));
        }
        public async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!_bingConfiguration.CanSupport() || !_bingConfiguration.IsActive())
            {
                return(new TranslateResult(false, new Maybe <string>()));
            }

            var requestObject = new
            {
                from = _applicationConfiguration.FromLanguage.Name.ToLower(),
                to   = _applicationConfiguration.ToLanguage.Name.ToLower(),
                text = translateRequest.CurrentText
            };

            IRestResponse response = await _restClient
                                     .Manipulate(client => client.BaseUrl = _bingConfiguration.Url.ToUri())
                                     .ExecutePostTaskAsync(new RestRequest(Method.POST)
                                                           .AddHeader(ContentTypeName, ContentType)
                                                           .AddParameter(ContentType, requestObject.ToJsonString(true), ParameterType.RequestBody)
                                                           );

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                IMeanOrganizer meanOrganizer = _meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType);
                mean = await meanOrganizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
Пример #27
0
        public async Task <TranslateResult> Translate(TranslateRequest request, CancellationToken cancellationToken)
        {
            //TODO: Change URL, it's not working anymore.
            var parameter =
                $"sl=auto&text={Uri.EscapeUriString(request.CurrentText)}&tl={this.applicationConfiguration.ToLanguage.Extension}";

            HttpClient httpClient = this.translatorClient.HttpClient.With(client =>
            {
                client.BaseAddress = this.sesliSozlukTranslatorConfiguration.Url.ToUri();
            });

            var req = new HttpRequestMessage {
                Method = HttpMethod.Post
            };

            //req.Headers.Add(Headers.AcceptLanguage, AcceptLanguage);
            //req.Headers.Add(Headers.AcceptEncoding, AcceptEncoding);
            //req.Headers.Add(Headers.ContentType, ContentType);
            //req.Headers.Add(Headers.UserAgent, UserAgent);
            //req.Headers.Add(Headers.Accept, Accept);
            req.Content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>(ContentType, parameter) });

            HttpResponseMessage response = await httpClient.SendAsync(req, cancellationToken);

            var mean = string.Empty;

            if (response.IsSuccessStatusCode)
            {
                mean = OrganizeMean(await response.Content.ReadAsStringAsync(cancellationToken));
            }

            return(new TranslateResult(true, mean));
        }
Пример #28
0
        public static TranslateRequest CreateTranslateRequest(ISegmentPair segmentPair, EngineMappingDetails engine)
        {
            var translateRequest = new TranslateRequest
            {
                Content = new Content
                {
                    InputFormat = "plain",
                    Text        = new[] { HttpUtility.UrlEncode(segmentPair.Source.ToString()) }
                },
                Definition = new Definition
                {
                    Resources = new List <Resource>()
                },
                LanguagePair = new LanguagePair
                {
                    Source = engine.SourceLang,
                    Target = engine.TargetLang
                }
            };
            var resource = new Resource
            {
                Type       = "MT",
                ResourceId = engine.Id
            };

            translateRequest.Definition.Resources.Add(resource);
            return(translateRequest);
        }
        protected override async Task <TranslateResult> Find(TranslateRequest translateRequest)
        {
            var requestObject = new
            {
                dirCode       = $"{translateRequest.FromLanguageExtension}-{_applicationConfiguration.ToLanguage.Extension}",
                template      = Configuration.Template,
                text          = translateRequest.CurrentText,
                lang          = translateRequest.FromLanguageExtension,
                limit         = Configuration.Limit,
                useAutoDetect = true,
                key           = string.Empty,
                ts            = Configuration.Ts,
                tid           = string.Empty,
                IsMobile      = false
            };

            IRestResponse response = await _restClient
                                     .Manipulate(client => { client.BaseUrl = Configuration.Url.ToUri(); }).ExecutePostTaskAsync(new RestRequest(Method.POST)
                                                                                                                                 .AddHeader(ContentTypeName, ContentType)
                                                                                                                                 .AddParameter(ContentType, requestObject.ToJsonString(false), ParameterType.RequestBody));

            var mean = new Maybe <string>();

            if (response.Ok())
            {
                mean = await MeanOrganizer.OrganizeMean(response.Content);
            }

            return(new TranslateResult(true, mean));
        }
Пример #30
0
        public void TranslateWhenDetectedSourceLanguageTest()
        {
            var request = new TranslateRequest
            {
                Key    = this.ApiKey,
                Target = Language.Spanish,
                Qs     = new[] { "Hej med dig min ven" }
            };

            var result = GoogleTranslate.Translate.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);

            var translations = result.Data.Translations?.ToArray();

            Assert.IsNotNull(translations);
            Assert.IsNotEmpty(translations);

            var translation = translations.FirstOrDefault();

            Assert.IsNotNull(translation);
            Assert.AreEqual("¿Cómo está usted mi amigo", translation.TranslatedText);
            Assert.AreEqual(Model.Base, translation.Model);
            Assert.AreEqual(Language.Danish, translation.DetectedSourceLanguage);
        }
        public async Task<TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!configuration.IsAppropriateForTranslation(TranslatorType))
                return new TranslateResult(false, new Maybe<string>());

            var address = string.Format(configuration.GoogleTranslateUrl, configuration.ToLanguageExtension, configuration.ToLanguageExtension, translateRequest.CurrentText);

            var client = new RestClient(address);
            var request = new RestRequest(Method.GET);
            var compositeMean = await client.ExecuteGetTaskAsync(request);
            var organizer = meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType.GOOGLE);
            var mean = await organizer.OrganizeMean(compositeMean.Content);

            return new TranslateResult(true, mean);
        }
Пример #32
0
        public async Task<TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!configuration.IsAppropriateForTranslation(TranslatorType))
                return new TranslateResult(false, new Maybe<string>());

            var address = new Uri(
                string.Format(configuration.YandexUrl +
                              $"key={configuration.ApiKey}&lang={translateRequest.FromLanguageExtension}-{configuration.ToLanguageExtension}&text={Uri.EscapeUriString(translateRequest.CurrentText)}"));

            var yandexClient = new WebClient();
            yandexClient.Encoding = Encoding.UTF8;
            yandexClient.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1));

            var compositeMean = await yandexClient.DownloadStringTaskAsync(address);
            var organizer = meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType.YANDEX);
            var mean = await organizer.OrganizeMean(compositeMean);

            return new TranslateResult(true, mean);
        }
Пример #33
0
        public async Task<TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!configuration.IsAppropriateForTranslation(TranslatorType))
                return new TranslateResult(false, new Maybe<string>());

            var address = configuration.TurengUrl;
            var uri = new Uri(address + translateRequest.CurrentText);

            var turenClient = new WebClient();
            turenClient.Encoding = Encoding.UTF8;
            turenClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36");
            turenClient.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8,tr;q=0.6");
            turenClient.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromHours(1));

            var compositeMean = await turenClient.DownloadStringTaskAsync(uri);
            var organizer = meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType.TURENG);
            var mean = await organizer.OrganizeMean(compositeMean);

            return new TranslateResult(true, mean);
        }
        public async Task<TranslateResult> Find(TranslateRequest translateRequest)
        {
            if (!configuration.IsAppropriateForTranslation(TranslatorType))
                return new TranslateResult(false, new Maybe<string>());

            var parameter = $"sl=auto&text={Uri.EscapeUriString(translateRequest.CurrentText)}&tl={configuration.ToLanguageExtension}";
            var client = new RestClient(configuration.SesliSozlukUrl);
            var request = new RestRequest(Method.POST)
                .AddHeader("accept-language", "en-US,en;q=0.8,tr;q=0.6")
                .AddHeader("accept-encoding", "gzip, deflate")
                .AddHeader("content-type", "application/x-www-form-urlencoded")
                .AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36")
                .AddHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .AddParameter("application/x-www-form-urlencoded", parameter, ParameterType.RequestBody);

            var response = await client.ExecuteTaskAsync(request);
            var meanOrganizer = meanOrganizerFactory.GetMeanOrganizers().First(x => x.TranslatorType == TranslatorType.SESLISOZLUK);
            var mean = await meanOrganizer.OrganizeMean(response.Content);

            return new TranslateResult(true, mean);
        }