示例#1
0
        public async Task CheckBadDirection()
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk();

            wrapper.ApiKey = _apiKey;
            wrapper.IsJson = true;
            string translatedText = await wrapper.TranslateText(_randomEnglishText, "BAD");
        }
示例#2
0
        public async Task CheckBadDirection()
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk();

            wrapper.ApiKey = _apiKey;
            wrapper.IsJson = true;
            await Assert.ThrowsAsync <YandexTranslateException>(() => wrapper.TranslateText(_randomEnglishText, "BAD"));
        }
        public async Task <string> TextTranslate(string text, string lang)
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk
            {
                ApiKey = "[PastApiKey]"
            };

            return(await wrapper.TranslateText(text, lang));
        }
示例#4
0
文件: main.cs 项目: solwllms/quiver
        static async Task <string> TranslateTextAsync(string input, string languagePair)
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk();

            wrapper.ApiKey = "trnsl.1.1.20180719T123308Z.c79b1bb6c241198d.67e7e24df670a3b2cc04cfd53003ccd7cb8b72ca";
            string englishText = input;

            return(await wrapper.TranslateText(englishText, languagePair));
        }
示例#5
0
        public async Task translate(string text, string lang)
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk
            {
                ApiKey = "trnsl.1.1.20180425T020912Z.749ad2de84bbafee.4ad82b8ab6d6f4b37d3d3b49b966ef528e7f73a0"
            };
            string translated = await wrapper.TranslateText(textBoxInput.Text, lang);

            textBoxOutput.Text = translated;
        }
示例#6
0
        public async Task <ActionResult> TranslateYandex(HomeIndexViewModel model)
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk();

            wrapper.ApiKey = "trnsl.1.1.20180301T144418Z.3432b63aad346fb1.472f0a88a08f8da285f3ea90664bf07bda0878f7";
            string englishText    = model.SoursePhrase;
            string translatedText = await wrapper.TranslateText(englishText, $"{model.SourseLng}-{model.DestLng}");

            return(Ok(translatedText));
        }
示例#7
0
        public async Task TranslateJsonTest()
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk();

            wrapper.ApiKey = _apiKey;
            wrapper.IsJson = true;
            string translatedText = await wrapper.TranslateText(_randomEnglishText, "en-ru");

            Console.WriteLine(translatedText);
            Assert.True(!string.IsNullOrEmpty(translatedText));
        }
示例#8
0
        private async void TranslateButton_OnClick(object sender, RoutedEventArgs e)
        {
            LanguageImageAwesome.Spin = true;
            YandexTranslateSdk wrapper = new YandexTranslateSdk();

            wrapper.ApiKey = "trnsl.1.1.20180416T100013Z.1af4661b948d09f6.123be2fc345c3411b70cc3d73e84b563f4345cdb";
            string englishText    = OrginalTextBox.Text;
            string translatedText = await wrapper.TranslateText(englishText, "en-fa");

            TranslatedTextBox.Text    = translatedText;
            LanguageImageAwesome.Spin = false;
        }
 private async void translateButton_Click(object sender, RoutedEventArgs e)
 {
     if (apiKey != null && !string.IsNullOrEmpty(text1.Text))
     {
         wrapper.ApiKey = apiKey;
         string direction = languagesCombo.SelectedValue + "-" + languagesCombo2.SelectedValue;
         try
         {
             text2.Text = await wrapper.TranslateText(text1.Text, direction);
         }
         catch (YandexTranslateException ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
示例#10
0
        public async void Translate_Xml()
        {
            YandexTranslateSdk wrapper = new YandexTranslateSdk
            {
                ApiKey = Api_Key
            };
            XmlDocument XmlDoc = new XmlDocument();

            XmlDoc.Load(English_Xml_Path);
            XmlNodeList NodeLists = XmlDoc.SelectNodes("resources/string");

            method.Insert_Text(textBox1, "<?xml" + @" " + @"version=" + @"""" + "1.0" + @"""" + @" " + "encoding =" + @"""" + "utf-8" + @"""" + "?>");
            method.Insert_Text(textBox1, "<resources>");
            foreach (XmlNode OneNode in NodeLists)
            {
                string English_Xml_Value    = OneNode.InnerText;
                string English_Xml_Name     = OneNode.Attributes["name"].Value;
                Regex  Find_String_Variable = new Regex(@"(\$|%)[0-9A-Za-z]");
                Match  m = Find_String_Variable.Match(English_Xml_Value);
                try
                {
                    if (m.Success)
                    {
                        method.Insert_Text(textBox1, method.Full_Context(English_Xml_Name, English_Xml_Value));
                    }
                    else if (English_Xml_Value == null)
                    {
                        method.Insert_Text(textBox1, method.Full_Context(English_Xml_Name, English_Xml_Value));
                    }
                    else
                    {
                        string TranslatedText = await wrapper.TranslateText(English_Xml_Value, "zh");

                        method.Insert_Text(textBox1, method.Full_Context(English_Xml_Name, method.Taiwan_transle_api(TranslatedText)));
                    }
                }
                catch
                {
                    method.Insert_Text(textBox1, method.Full_Context(English_Xml_Name, English_Xml_Value));
                }
            }
            method.Insert_Text(textBox1, "</resources>");
        }
        public async Task <IActionResult> Translate(TranslateViewModel model)
        {
            if (ModelState.IsValid)
            {
                YandexTranslateSdk wrapper = new YandexTranslateSdk();
                wrapper.ApiKey = model.Key;
                string inputLanguage = await wrapper.DetectLanguage(model.InputText);

                string outputLanguage = model.OutputLanguage;
                string direction      = inputLanguage + "-" + outputLanguage;
                model.OutputText = await wrapper.TranslateText(model.InputText, direction);

                model.Languages = new List <string>(TempData["Languages"] as string[]);

                ModelState.Clear();

                return(View("Index", model));
            }
            return(View("Index", model));
        }
示例#12
0
 static string TranslateRussian(string russian)
 {
     return(wrapper.TranslateText(russian, "ru-en").GetAwaiter().GetResult());
 }
示例#13
0
//        private static async Task TranslatePackAsync(int packId)
//        {
//            var pack = await MongoServiceClient.GetPackAsync(packId);
//            var finalList = new List<(string, string)>();
//
//            foreach (var phrase in pack.Phrases)
//            {
//                var translated = await TranslateAsync(phrase.Phrase);
//                finalList.Add((phrase.Phrase, translated));
//                ConsoleUtilities.WriteGreenLine($"{phrase.Phrase}\t\t{translated}");
//            }
//
//            finalList.ToList().ForEach(action: i => Console.WriteLine("{0,-30}{1,30}", i.Item1, i.Item2));
//        }

        private static Task <string> TranslateAsync(string text) => _translatorWrapper.TranslateText(text, "ru-en");
 public async Task <string> TranslateAsync(string text, Languages lngFrom, Languages lngTo)
 {
     return(await wrapper.TranslateText(text, $"{lngFrom.ToString()}-{lngTo.ToString()}"));
 }
示例#15
0
 public async ValueTask <string> Translate(string text, string direction)
 {
     return(await _translateSdk.TranslateText(text, direction));
 }
 public virtual async Task <string> TranslateTextAsync(string text, string fromIdentifier, string toIdentifier)
 {
     return(await _yandexTranslateSdk.TranslateText(text, $"{fromIdentifier}-{toIdentifier}"));
 }
示例#17
0
        /// <summary>
        /// Downloads and returns translated text.
        /// </summary>
        /// <returns></returns>
        private async Task <string> GetMachineTranslation(string untranslatedText)
        {
            var selectedApi            = (string)this.CboMachine.SelectedItem;
            var selectedTargetLanguage = (string)this.CboMachineLanguage.SelectedItem;

            var targetLanguage = "en";

            switch (selectedTargetLanguage)
            {
            case "Korean":
            {
                switch (selectedApi)
                {
                default:
                case "Google": targetLanguage = "ko"; break;

                case "Baidu": targetLanguage = "kor"; break;

                case "Yandex": targetLanguage = "ko"; break;
                }
                break;
            }

            case "Chinese":
            {
                switch (selectedApi)
                {
                default:
                case "Google": targetLanguage = "zh-CN"; break;

                case "Baidu": targetLanguage = "zh"; break;

                case "Yandex": targetLanguage = "zh"; break;
                }
                break;
            }

            case "Japanese":
            {
                switch (selectedApi)
                {
                default:
                case "Google": targetLanguage = "ja"; break;

                case "Baidu": targetLanguage = "jp"; break;

                case "Yandex": targetLanguage = "ja"; break;
                }
                break;
            }
            }

            string translatedText = null;
            var    translationKey = targetLanguage + " ::::: " + untranslatedText;

            lock (_machineCache)
            {
                if (_machineCache.TryGetValue(translationKey, out translatedText))
                {
                    return(translatedText);
                }
            }

            await Task.Run(() =>
            {
                using (var wc = new WebClient())
                {
                    wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
                    wc.Encoding = Encoding.UTF8;

                    if (selectedApi == "Google")
                    {
                        var text   = HttpUtility.UrlEncode(this.TxtOriginalLine.Text);
                        var url    = string.Format(string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={1}&tl={2}&dt=t&q={0}", text, "auto", targetLanguage));
                        var result = wc.DownloadString(url);
                        var json   = JsonValue.Parse(result);

                        var sb = new StringBuilder();
                        foreach (JsonValue x in json[0])
                        {
                            var str = (string)x[0];
                            sb.Append(str);
                        }

                        translatedText = sb.ToString();
                    }
                    else if (selectedApi == "Baidu")
                    {
                        // Information taken from a public repo,
                        // will presumably quickly reach limits as well.
                        // https://github.com/qianngchn/Desktop-Translator

                        var password = "******";
                        var salt     = DateTime.Now.Millisecond.ToString();
                        var appid    = "20170816000074142";
                        var sign     = GetMd5HashString(appid + untranslatedText + salt + password);
                        var text     = HttpUtility.UrlEncode(this.TxtOriginalLine.Text);
                        var url      = string.Format("http://api.fanyi.baidu.com/api/trans/vip/translate?q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}", text, "auto", targetLanguage, appid, salt, sign);

                        var result = wc.DownloadString(url);
                        if (result.Contains("Please recharge"))
                        {
                            throw new WebException("(429) Too many requests");
                        }

                        var json = (JsonObject)JsonValue.Parse(result);
                        if (!json.TryGetValue("trans_result", out var transResult))
                        {
                            throw new WebException("Baidu result property not found.");
                        }

                        translatedText = transResult[0]["dst"];
                    }
                    else if (selectedApi == "Yandex")
                    {
                        var wrapper    = new YandexTranslateSdk();
                        wrapper.ApiKey = "trnsl.1.1.20190418T085102Z.a126d39de35eb97f.bf9fd00337c90d72172e0f4cd49cc46bb201e96a";
                        translatedText = wrapper.TranslateText(this.TxtOriginalLine.Text, targetLanguage).GetAwaiter().GetResult();
                    }
                    else
                    {
                        throw new InvalidDataException("Unknown translation API.");
                    }
                }
            });

            lock (_machineCache)
                _machineCache[translationKey] = translatedText;

            return(translatedText);
        }