Пример #1
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);
            }
        }
Пример #2
0
        private static string TranslateWithToken(string input, string fromLanguage, string toLanguage)
        {
            string token = GenerateTk(input);//LazyGenerateToken(input);

            // There are a lot of url options available, see the following
            // https://github.com/Stichoza/google-translate-php/blob/master/src/GoogleTranslate.php

            input = HttpUtility.UrlEncode(input);
            string url = string.Format("https://translate.google.com/translate_a/single?client=webapp&sl={0}&tl={1}&dt=t&tk={2}&q={3}",
                                       fromLanguage, toLanguage, token, input);

            using (WebClient webClient = new WebClient())
            {
                webClient.Proxy    = null;
                webClient.Encoding = Encoding.UTF8;

                string result = string.Empty;

                string            json     = webClient.DownloadStringAwareOfEncoding(url);
                TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                object[] items = response[0] as object[];
                foreach (object item in items)
                {
                    object[] values = item as object[];
                    result += values[0] as string;
                }

                return(result);
            }
        }
Пример #3
0
        public void Translate_Success_With_Source_Target()
        {
            IClient client = this.CreateClient();

            IRequest request = Substitute.For <IRequest>();

            client.PostAsync(Arg.Any <string>())
            .Returns(request);

            request.WithBody <JObject>(Arg.Any <JObject>(), Arg.Any <MediaTypeHeaderValue>())
            .Returns(request);

            TranslateResponse response = new TranslateResponse()
            {
                Translations = new List <Translations>()
                {
                    new Translations()
                    {
                        Translation = "text translated"
                    }
                }
            };

            request.As <TranslateResponse>()
            .Returns(Task.FromResult(response));

            LanguageTranslatorService service =
                new LanguageTranslatorService(client);

            var translation = service.Translate("source", "target", "text in any language");

            Assert.IsNotNull(translation);
            client.Received().PostAsync(Arg.Any <string>());
            Assert.IsTrue(translation.Translations.Count == 1);
        }
        public async Task <TranslatedResponse> TranslateToShakespearStyleAsync(string pokemonName)
        {
            if (string.IsNullOrWhiteSpace(pokemonName))
            {
                throw new ApplicationException("Pokemon name must be passed in the URI as a parameter.");
            }

            PokemonDetail details = await this.pokemonAPIService.GetPokemanDetailsAsync(pokemonName);

            PokemonSpeciesDetail speciesDetail = await this.pokemonAPIService.GetPokemanSpeciesDetailsAsync(details.Species.Url.PathAndQuery);

            string description = speciesDetail.FlavorTextEntries.FirstOrDefault(x => x.Version.Name == "ruby")?.FlavorText.Replace("\n", "").Replace("\r", "");

            if (string.IsNullOrWhiteSpace(description))
            {
                throw new ApplicationException($"No details found for Pokemon {pokemonName}");
            }

            TranslateResponse translateResponse = await this.translateAPIService.GetShakespeareDescriptionAsync(description);

            TranslatedResponse translatedResponse = this.mapper.Map <TranslatedResponse>(translateResponse);

            translatedResponse.Name = pokemonName;

            return(translatedResponse);
        }
Пример #5
0
        protected override string Translate(string value, string fromLanguage, string toLanguage, string fromApiLanguage, string toApiLanguage)
        {
            TimeSpan elapsedTime = DateTime.Now - lastCookiesTime;

            if (cookies == null || elapsedTime > cookiesExpireTime)
            {
                cookies = GetCookies("https://www.bing.com/translator");
            }
            lastCookiesTime = DateTime.Now;

            try
            {
                using (WebClient webClient = new WebClient())
                {
                    string url = "https://www.bing.com/ttranslate";//?&category=&IG=7206AF8836B34421880FE9079EAE74A9&IID=translator.5034.6

                    webClient.Proxy    = null;
                    webClient.Encoding = Encoding.UTF8;
                    webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8";
                    webClient.Headers[HttpRequestHeader.Cookie]      = cookies;
                    string            json     = webClient.UploadString(url, "text=" + HttpUtility.UrlEncode(value) + "&from=" + fromApiLanguage + "&to=" + toApiLanguage);
                    TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                    return(response.translationResponse);
                }
            }
            catch (Exception e)
            {
                cookies = null;
                throw e;
            }
        }
Пример #6
0
    public static async Task <TranslateResponse> TranslateText(string input, lang langInput = lang.auto, lang langOutput = lang.zh_CN)
    {
        var res = new TranslateResponse();

        try
        {
            var          client   = new HttpClient();
            const string sl       = "auto";
            var          tl       = langOutput.ToString().Replace("_", "-");
            var          hl       = langInput.ToString().Replace("_", "-");
            var          url      = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={sl}&tl={tl}&hl={hl}&dt=t&dt=bd&dj=1&source=input&tk=501776.501776&q={input}";
            var          response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var text = await response.Content.ReadAsStringAsync();

                var translateResult = JsonConvert.DeserializeObject <TranslateResult>(text);
                res.IsSuccess = true;
                res.Result    = translateResult;
                res.Response  = text;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("GoogleTranslateLib.Translate [error] = " + ex);
            res.IsSuccess    = false;
            res.Exception    = ex;
            res.MessageError = ex.Message;
        }
        return(res);
    }
Пример #7
0
        public HttpResponseMessage TransalteGoogle([FromBody] TranslateRequest jsonbody)
        {
            String            title = "";
            TranslateResponse trans = new TranslateResponse();

            try
            {
                title = TranslateUtils.TranslateText(jsonbody.text);
            }
            catch { }
            trans.title = title;
            return(Request.CreateResponse(HttpStatusCode.OK, trans));
        }
Пример #8
0
        protected override string Translate(string value, string fromLanguage, string toLanguage, string fromApiLanguage, string toApiLanguage)
        {
            TimeSpan elapsedTime = DateTime.Now - lastCookiesTime;

            if (cookies == null || elapsedTime > cookiesExpireTime)
            {
                cookies = GetCookies("https://fanyi.baidu.com");

                // The request requires cookies to get a valid token
                string html;
                cookies = GetCookies("https://fanyi.baidu.com", cookies, out html);

                string tokenPrefix = "token: '";
                string gtkPrefix   = "gtk = '";
                int    tokenIndex  = html.IndexOf(tokenPrefix);
                int    gtkIndex    = html.IndexOf(gtkPrefix);
                if (tokenIndex >= 0 && gtkIndex >= 0)
                {
                    token = html.Substring(tokenIndex + tokenPrefix.Length);
                    token = token.Substring(0, token.IndexOf('\''));

                    gtk = html.Substring(gtkIndex + gtkPrefix.Length);
                    gtk = gtk.Substring(0, gtk.IndexOf('\''));
                }
                else
                {
                    cookies = null;
                    token   = null;
                    gtk     = null;
                }
            }
            lastCookiesTime = DateTime.Now;

            using (WebClient webClient = new WebClient())
            {
                string url = "https://fanyi.baidu.com/v2transapi";

                string sign = GetSign(value, gtk);

                webClient.Proxy    = null;
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.Cookie]      = cookies;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8";
                string json = webClient.UploadString(url, string.Format("from={0}&to={1}&query={2}&transtype=realtime&token={3}&sign={4}",
                                                                        fromApiLanguage, toApiLanguage, HttpUtility.UrlEncode(value), token, sign));
                TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                return(response.trans_result.data[0].dst);
            }
        }
Пример #9
0
        protected override string Translate(string value, string fromLanguage, string toLanguage, string fromApiLanguage, string toApiLanguage)
        {
            TranslateRequest request = new TranslateRequest()
            {
                dirCode       = fromApiLanguage + "-" + toApiLanguage,
                template      = "General",
                text          = WebUtils.FormatJson(value),
                lang          = fromApiLanguage,
                limit         = 3000,
                useAutoDetect = false,
                key           = string.Empty,
                ts            = "MainSite",
                tid           = string.Empty,
                IsMobile      = true
            };
            string requestJson = JSONSerializer <TranslateRequest> .Serialize(request);

            string url = "http://www.online-translator.com/services/TranslationService.asmx/GetTranslateNew";

            using (WebClient webClient = new WebClient())
            {
                webClient.Proxy    = null;
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json; charset=UTF-8";

                string json = webClient.UploadString(url, requestJson);

                // Lazy hack, find the correct way to handle "__type"
                json = json.Replace("__type", "__nype__");

                TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                string result = response.d.result;
                if (!string.IsNullOrEmpty(result) && result.StartsWith("<style"))
                {
                    result = HttpUtility.HtmlDecode(result);

                    string resultHeader = "ref_result";
                    int    resultOffset = result.IndexOf(resultHeader) + resultHeader.Length;
                    result = result.Substring(resultOffset);
                    result = result.Substring(result.IndexOf('>') + 1);
                    result = result.Substring(0, result.IndexOf('<')).Trim();
                    return(result);
                }
                else
                {
                    return(result);
                }
            }
        }
Пример #10
0
        protected override string Translate(string value, string fromLanguage, string toLanguage, string fromApiLanguage, string toApiLanguage)
        {
            TimeSpan elapsedTime = DateTime.Now - lastSessionIdTime;

            if (sessionId == null || elapsedTime > sessionIdExpireTime)
            {
                sessionId = GetSessionId();
            }

            lastSessionIdTime = DateTime.Now;

            try
            {
                using (WebClient webClient = new WebClient())
                {
                    string formattedValue = HttpUtility.UrlEncode(value);

                    //Alternative: 2-0
                    string url = string.Format("https://translate.yandex.net/api/v1/tr.json/translate?id={0}-0-0&srv=tr-text&lang={1}-{2}", sessionId, fromApiLanguage, toApiLanguage);
                    if (!usePost)
                    {
                        url += "&text=" + formattedValue;
                    }

                    webClient.Proxy    = null;
                    webClient.Encoding = Encoding.UTF8;

                    string json = null;
                    if (usePost)
                    {
                        webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8";
                        json = webClient.UploadString(url, "text=" + formattedValue);
                    }
                    else
                    {
                        webClient.Headers[HttpRequestHeader.ContentType] = "application/json; charset=UTF-8";
                        json = webClient.DownloadStringAwareOfEncoding(url);
                    }
                    TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                    return(response.text[0]);
                }
            }
            catch (Exception e)
            {
                sessionId = null;
                throw e;
            }
        }
Пример #11
0
        public static TranslateResponse Unmarshall(UnmarshallerContext context)
        {
            TranslateResponse translateResponse = new TranslateResponse();

            translateResponse.HttpResponse = context.HttpResponse;
            translateResponse.RequestId    = context.StringValue("Translate.RequestId");
            translateResponse.Code         = context.IntegerValue("Translate.Code");
            translateResponse.Message      = context.StringValue("Translate.Message");

            TranslateResponse.Translate_Data data = new TranslateResponse.Translate_Data();
            data.Translated        = context.StringValue("Translate.Data.Translated");
            translateResponse.Data = data;

            return(translateResponse);
        }
Пример #12
0
        public HttpResponseMessage Post([FromBody] TranslateRequest jsonbody)
        {
            String            title = "";
            TranslateResponse trans = new TranslateResponse();

            try
            {
                TranslateClient client = new TranslateClient("");
                Language        lang1  = Language.Japanese;
                Language        lang2  = Language.Vietnamese;
                title = client.Translate(jsonbody.text, "ja", "vi");
            }
            catch { }
            trans.title = title;
            return(Request.CreateResponse(HttpStatusCode.OK, trans));
        }
Пример #13
0
        public string TranslateMsg(string msg)
        {
            if (msg.ContainsUnicode() == false)
            {
                return(msg);
            }

            try
            {
                TranslateResponse translateResponse = LanguageTranslator.Translate(From, To, msg);
                return(translateResponse?.Translations?.First()?.Translation);
            }
            catch (Exception exp)
            {
                OnError?.Invoke(msg, exp);
                return(null);
            }
        }
Пример #14
0
        private static TranslateResponse GetTranslateResponse(TranslateRequest translateRequest, Dictionary <string, string> results)
        {
            var response = new TranslateResponse
            {
                Meta            = translateRequest.Meta,
                RequestedItems  = translateRequest.Items,
                TranslatedItems = new List <Item>()
            };

            foreach (var(key, value) in results)
            {
                response.TranslatedItems.Add(new Item()
                {
                    Id = key, Value = value
                });
            }

            return(response);
        }
Пример #15
0
        protected override string Translate(string value, string fromLanguage, string toLanguage, string fromApiLanguage, string toApiLanguage)
        {
            using (WebClient webClient = new WebClient())
            {
                string url = string.Format("https://translation.babylon-software.com/translate/babylon.php?v=1.0&q={0}&langpair={1}|{2}&callback=babylonTranslator.callback&context=babylon.0.3._babylon_api_response",
                                           HttpUtility.UrlEncode(value), languageIds[fromApiLanguage], languageIds[toApiLanguage]);

                webClient.Proxy    = null;
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=UTF-8";
                string json = webClient.DownloadStringAwareOfEncoding(url);
                json = json.Substring(json.IndexOf('{'));
                json = json.Substring(0, json.LastIndexOf('}') + 1);
                TranslateResponse response = JSONSerializer <TranslateResponse> .DeSerialize(json);

                string result = HttpUtility.UrlDecode(response.translatedText);
                //string result = HttpUtility.HtmlDecode(response.translatedText);
                return(result);
            }
        }
Пример #16
0
        private TranslateResponse Translate(string modelId, string source, string target, List <string> text)
        {
            TranslateResponse result = null;

            try
            {
                JObject json = null;

                if (!string.IsNullOrEmpty(modelId))
                {
                    json =
                        new JObject(
                            new JProperty("model_id", modelId),
                            new JProperty("text", new JArray(text)));
                }
                else
                {
                    json =
                        new JObject(
                            new JProperty("source", source),
                            new JProperty("target", target),
                            new JProperty("text", new JArray(text)));
                }

                result =
                    this.Client.WithAuthentication(this.UserName, this.Password)
                    .PostAsync(this.Endpoint + PATH_TRANSLATE)
                    .WithBody <JObject>(json, MediaTypeHeaderValue.Parse(HttpMediaType.APPLICATION_JSON))
                    .As <TranslateResponse>()
                    .Result;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
Пример #17
0
        static void Main(string[] args)
        {
            // this will be injectected using auto.fac
            ITranslateDataSource dataSource = new ApiDataSource();
            ITranslateLogic      logic      = new TranslateLogic(dataSource);
            TranslateController  controller = new TranslateController(logic);

            // creat httpClient to our controller for example

            TranslateRequest translateRequest = new TranslateRequest
            {
                MessageToTranslate = "I hope this works",
                SomeMetaData       = "Auth Key: M$#F#*NJLS)S"
            };

            // invoke the httpClient example /api/v1/translate/translatemymessage - with the body
            TranslateResponse response = controller.TranslateMyMessage(translateRequest);

            Console.WriteLine("Starting process...");
            Console.WriteLine(response.TranslatedMessage);
            Console.WriteLine($"UserStats: {response.UserStats}");
            Console.ReadLine();
        }
Пример #18
0
        public EmbedBuilder GetTranslationEmbed(TranslateResponse result)
        {
            if (result.TranslateResult == null)
            {
                return(null);
            }

            var embed = new EmbedBuilder();

            embed.AddField($"Original Message [{result.TranslateResult.SourceLanguage}]", result.TranslateResult.SourceText.FixLength());
            embed.AddField($"Translated Message [{result.TranslateResult.DestinationLanguage}]", result.TranslateResult.TranslatedText.FixLength());

            if (Config.ApiKeyType == TranslateConfig.ApiKey.Yandex)
            {
                embed.AddField("Yandex", $"[Powered by Yandex](http://translate.yandex.com/)");
            }

            embed.Color  = Color.Green;
            embed.Footer = new EmbedFooterBuilder
            {
                Text = $"{result.RemainingUses} Remaining Characters"
            };
            return(embed);
        }