예제 #1
0
        /// <summary>
        /// Translates the specified source text.
        /// </summary>
        /// <param name="sourceText">The source text.</param>
        /// <param name="sourceLanguage">The source language.</param>
        /// <param name="targetLanguage">The target language.</param>
        /// <returns>The translation.</returns>
        public async Task <string> TranslateAsync
            (string sourceText,
            string sourceLanguage,
            string targetLanguage)
        {
            // Initialize
            this.Error = null;
            this.TranslationSpeechUrl = null;
            this.TranslationTime      = TimeSpan.Zero;
            DateTime tmStart     = DateTime.Now;
            string   translation = string.Empty;

            try
            {
                // Download translation
                string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
                                           sourceLanguage,
                                           targetLanguage,
                                           HttpUtility.UrlEncode(sourceText));

                string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "XF_Downloads");
                //Directory.CreateDirectory(pathToNewFolder);
                string outputFile = Path.Combine(pathToNewFolder, "json.txt");

                using (WebClient 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.DownloadFile(url, outputFile);

                    await Task.Run(() => { wc.DownloadFile(url, outputFile); });
                }

                // Get translated text
                if (File.Exists(outputFile))
                {
                    // Get phrase collection
                    string text  = File.ReadAllText(outputFile);
                    int    index = text.IndexOf(string.Format(",,\"{0}\"", Translator.LanguageEnumToIdentifier(sourceLanguage)));
                    if (index == -1)
                    {
                        // Translation of single word
                        int startQuote = text.IndexOf('\"');
                        if (startQuote != -1)
                        {
                            int endQuote = text.IndexOf('\"', startQuote + 1);
                            if (endQuote != -1)
                            {
                                translation = text.Substring(startQuote + 1, endQuote - startQuote - 1);
                            }
                        }
                    }
                    else
                    {
                        // Translation of phrase
                        text = text.Substring(0, index);
                        text = text.Replace("],[", ",");
                        text = text.Replace("]", string.Empty);
                        text = text.Replace("[", string.Empty);
                        text = text.Replace("\",\"", "\"");

                        // Get translated phrases
                        string[] phrases = text.Split(new[] { '\"' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i = 0; (i < phrases.Count()); i += 2)
                        {
                            string translatedPhrase = phrases[i];
                            if (translatedPhrase.StartsWith(",,"))
                            {
                                i--;
                                continue;
                            }
                            translation += translatedPhrase + "  ";
                        }
                    }

                    // Fix up translation
                    translation = translation.Trim();
                    translation = translation.Replace(" ?", "?");
                    translation = translation.Replace(" !", "!");
                    translation = translation.Replace(" ,", ",");
                    translation = translation.Replace(" .", ".");
                    translation = translation.Replace(" ;", ";");

                    // And translation speech URL
                    this.TranslationSpeechUrl = string.Format("https://translate.googleapis.com/translate_tts?ie=UTF-8&q={0}&tl={1}&total=1&idx=0&textlen={2}&client=gtx",
                                                              HttpUtility.UrlEncode(translation), Translator.LanguageEnumToIdentifier(targetLanguage), translation.Length);
                }
            }
            catch (Exception ex)
            {
                this.Error = ex;
            }

            // Return result
            this.TranslationTime = DateTime.Now - tmStart;
            return(translation);
        }
예제 #2
0
        /// <summary>
        /// Translates the specified source text.
        /// </summary>
        /// <param name="sourceText">The source text.</param>
        /// <param name="sourceLanguage">The source language.</param>
        /// <param name="targetLanguage">The target language.</param>
        /// <returns>The translation.</returns>
        public string Translate
            (string sourceText,
            string sourceLanguage,
            string targetLanguage)
        {
            // Initialize
            this.Error = null;
            this.TranslationSpeechUrl = null;
            this.TranslationTime      = TimeSpan.Zero;
            DateTime tmStart     = DateTime.Now;
            string   translation = string.Empty;

            try {
                // Download translation
                string translationFromGoogle = "";

                //Using secret translate.googleapis.com API that is internally used by the Google Translate extension for Chrome and requires no authentication
                string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
                                           Translator.LanguageEnumToIdentifier(sourceLanguage),
                                           Translator.LanguageEnumToIdentifier(targetLanguage),
                                           HttpUtility.UrlEncode(sourceText));
                using (WebClient 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           = System.Text.Encoding.UTF8;
                    translationFromGoogle = wc.DownloadString(url);
                }

                // Get translated text
                var json = JsonConvert.DeserializeObject(translationFromGoogle);
                translation = ((((json as JArray).First() as JArray).First() as JArray).First() as JValue).Value.ToString();

                // And translation speech URL

                //Using secret translate.googleapis.com API that is internally used by the Google Translate extension for Chrome and requires no authentication
                this.TranslationSpeechUrl = string.Format("https://translate.googleapis.com/translate_tts?ie=UTF-8&q={0}&tl={1}&total=1&idx=0&textlen={2}&client=gtx",
                                                          HttpUtility.UrlEncode(translation), Translator.LanguageEnumToIdentifier(targetLanguage), translation.Length);
            }
            catch (Exception ex) {
                this.Error = ex;
            }

            // Return result
            this.TranslationTime = DateTime.Now - tmStart;
            return(translation);
        }