Beispiel #1
0
        public void TranslateLargeText()
        {
            GoogleTranslate google = new GoogleTranslate(_apiKey);

            google.PrettyPrint = false;

            //2037 characters long text
            const string text = "Wikipedia was launched in January 2001 by Jimmy Wales and Larry Sanger.[13] Sanger coined the name Wikipedia,[14] which is a portmanteau of wiki (a type of collaborative website, from the Hawaiian word wiki, meaning quick)[15] and encyclopedia. Wikipedia's departure from the expert-driven style of encyclopedia building and the presence of a large body of unacademic content have received extensive attention in print media. In its 2006 Person of the Year article, Time magazine recognized the rapid growth of online collaboration and interaction by millions of people around the world. It cited Wikipedia as an example, in addition to YouTube, MySpace, and Facebook.[16] Wikipedia has also been praised as a news source because of how quickly articles about recent events appear.[17][18] Students have been assigned to write Wikipedia articles as an exercise in clearly and succinctly explaining difficult concepts to an uninitiated audience.[19] Although the policies of Wikipedia strongly espouse verifiability and a neutral point of view, criticisms leveled at Wikipedia include allegations about quality of writing,[20] inaccurate or inconsistent information, and explicit content. Various experts (including Wales and Jonathan Zittrain) have expressed concern over possible (intentional or unintentional) biases.[21][22][23][24] These allegations are addressed by various Wikipedia policies. Other disparagers of Wikipedia simply point out vulnerabilities inherent to any wiki that may be edited by anyone. These critics observe that much weight is given to topics that more editors are likely to know about, like popular culture,[25] and that the site is vulnerable to vandalism,[26][27] though some studies indicate that vandalism is quickly deleted. Critics point out that some articles contain unverified or inconsistent information,[28] though a 2005 investigation in Nature showed that the science articles they compared came close to the level of accuracy of Encyclopædia Britannica and had a similar rate of serious errors";

            //We have not set LargeQuery to true
            Assert.Throws <ArgumentException>(() => google.Translate(Language.English, Language.German, text));

            //We set the LargeQuery to false, so it should still fail
            google.LargeQuery = false;

            Assert.Throws <ArgumentException>(() => google.Translate(Language.English, Language.German, text));

            //We set the LargeQuery to true.
            google.LargeQuery = true;

            //It should still fail when the message is more than 5000 characters.
            Assert.Throws <ArgumentException>(() => google.Translate(Language.English, Language.German, text + text + text + text));

            //Finally we try with the message and it should work
            List <Translation> largeResults = google.Translate(Language.English, Language.German, text);

            Assert.False(string.IsNullOrEmpty(largeResults[0].TranslatedText));
        }
Beispiel #2
0
        private string TranslateWords(string text)
        {
            List <GoogleTranslateNet.Objects.Translation.Translation> result = new List <GoogleTranslateNet.Objects.Translation.Translation>();
            GoogleTranslate google = new GoogleTranslate(Gkey);

            google.PrettyPrint = true;
            if (text.Length > 2000)
            {
                google.LargeQuery = true;
            }
            var language = google.DetectLanguage(text);

            if (language.Count >= 1)
            {
                var lang = language[0].Language;
                if (lang == "en")
                {
                    DetectedLanguageLabel.Text = "English";
                    TranslatedTextLabel.Text   = text;
                }
                else
                {
                    DetectedLanguageLabel.Text = LanguagesName.FindLanguageName(lang);
                }

                result = google.Translate(Language.Automatic, Language.English, text);
                if (result.Count > 0)
                {
                    TranslatedTextLabel.Text = result[0].TranslatedText;
                }
            }
            return(result[0].TranslatedText);
        }
Beispiel #3
0
        /// <summary>
        /// </summary>
        /// <param name="line"></param>
        /// <param name="isJP"></param>
        /// <returns></returns>
        private static GoogleTranslateResult ResolveGoogleTranslateResult(string line, bool isJP)
        {
            GoogleTranslateResult result = null;
            var outLang = GoogleTranslate.Offsets[Settings.Default.TranslateTo].ToString();

            if (Settings.Default.TranslateJPOnly)
            {
                if (isJP)
                {
                    result = GoogleTranslate.Translate(line, "ja", outLang, true);
                }
            }
            else
            {
                result = GoogleTranslate.Translate(
                    line,
                    isJP
                        ? "ja"
                        : "en",
                    outLang,
                    true);
            }

            return(result);
        }
Beispiel #4
0
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Length == 0)
            {
                return;
            }
            char c = textBox1.Text[textBox1.Text.Length - 1];

            if (char.IsWhiteSpace(c))
            {
                textBox2.Text = _t.Translate(textBox1.Text, true);
            }
            else if (Py.Core.Check.IsChinese(textBox1.Text))
            {
                textBox2.Text = _t.Translate(textBox1.Text, true);
            }
        }
Beispiel #5
0
        public static string Translate(string text, params Language[] languages)
        {
            string translatedText = text;

            for (int i = 0; i < languages.Length; i += 2)
            {
                translatedText = sGoogleTranslate.Translate(languages[i], languages[i + 1], translatedText)[0].TranslatedText;
            }

            return(WebUtility.HtmlDecode(translatedText));
        }
Beispiel #6
0
        private static void Main(string[] args)
        {
            GoogleTranslate google = new GoogleTranslate(_key);

            //Notice that we set the source language to Language.Automatic. This means Google Translate automatically detect the source language before translating.
            List <Translation> results = google.Translate(Language.Automatic, Language.German, "Hello there.", "How are you?", "Multiple texts are allowed!");

            foreach (Translation translation in results)
            {
                Console.WriteLine("Detected language: " + translation.DetectedSourceLanguage + " translation: " + translation.TranslatedText);
            }
        }
Beispiel #7
0
        public void TranslateTest()
        {
            GoogleTranslate google = new GoogleTranslate(_apiKey);

            google.PrettyPrint = false;
            List <Translation> results = google.Translate(Language.Automatic, Language.German, "Hello there", "What are you doing?");

            Assert.Equal("Hallo", results[0].TranslatedText);
            Assert.Equal(Language.English.GetStringValue(), results[0].DetectedSourceLanguage);

            Assert.Equal("Was machen Sie?", results[1].TranslatedText);
            Assert.Equal(Language.English.GetStringValue(), results[1].DetectedSourceLanguage);
        }
Beispiel #8
0
        public static string Translate(string src)
        {
            int idx = src.IndexOf(' ');

            if (idx > 0 && idx != src.Length - 1)
            {
                string dst = src.Substring(0, idx);
                if (GoogleTranslate.SupportsLanguage(dst))
                {
                    return(GoogleTranslate.Translate(src.Substring(idx + 1), dst).Result);
                }
            }

            return(GoogleTranslate.Translate(src).Result);
        }
Beispiel #9
0
 public void TestTranslation()
 {
     Assert.AreEqual("This is a translation.", GoogleTranslate.Translate("Dit is een vertaling.").Result);
 }
Beispiel #10
0
 /// <summary>
 /// </summary>
 /// <param name="line"></param>
 /// <param name="outLang"></param>
 /// <param name="isJP"></param>
 /// <returns></returns>
 public static GoogleTranslateResult GetManualResult(string line, string outLang, bool isJP)
 {
     return(GoogleTranslate.Translate(line, "en", outLang, isJP));
 }
Beispiel #11
0
        public void process()
        {
            if (jtProc == null)
            {
                return;
            }
            string modName  = MainForm.Normilize(mod.Name);
            string filename = MainForm.Normilize(Path.GetFileNameWithoutExtension(jsonPath));
            Dictionary <string, string> replaced = new Dictionary <string, string>();

            jtProc.proc(modName, filename, ref content, replaced, false);
            foreach (var replacements in replaced)
            {
                //if (debugCounter > debugCounterMax) { break; }
                if (string.IsNullOrEmpty(replacements.Value) == false)
                {
                    CustomTranslation.TranslateRecord nTr = new CustomTranslation.TranslateRecord();
                    nTr.FileName = jsonPath.Substring(basePath.Length);
                    nTr.Name     = replacements.Key;
                    nTr.Original = replacements.Value;
                    //nTr.Localization.Add(Localize.Strings.Culture.CULTURE_EN_US, replacements.Value);
                    foreach (Localize.Strings.Culture locLang in cultures)
                    {
                        string val  = replacements.Value;
                        string nval = MainForm.Normilize(val);
                        if (locLang == Localize.Strings.Culture.CULTURE_RU_RU)
                        {
                            if (val.Length > 30)
                            {
                                if (locCache.ContainsKey(nval) == false)
                                {
                                    //statistics.Add(val);
                                    //MessageBox.Show(val);
                                    val = GoogleTranslate.Translate(val);
                                    locCache.Add(nval, val);
                                    System.Threading.Thread.Sleep(1000);
                                    Log.Debug?.Write(0, "'" + replacements.Value + "' - '" + val + "'\n", true);
                                    //MessageBox.Show(val);
                                    //++debugCounter;
                                }
                                else
                                {
                                    val = locCache[nval];
                                }
                            }
                        }
                        nTr.Localization.Add(locLang, val);
                    }
                    locFile.Merge(nTr);
                    updated = true;
                }
                else
                {
                    if (locFile.map.ContainsKey(replacements.Key))
                    {
                        string original = locFile.map[replacements.Key].Original;
                        if (string.IsNullOrEmpty(original))
                        {
                            original = locFile.map[replacements.Key].Localization[Localize.Strings.Culture.CULTURE_EN_US];
                        }
                        if (string.IsNullOrEmpty(original) == false)
                        {
                            CustomTranslation.TranslateRecord nTr = new CustomTranslation.TranslateRecord();
                            nTr.FileName = jsonPath.Substring(basePath.Length);;
                            nTr.Name     = replacements.Key;
                            nTr.Original = original;
                            foreach (Localize.Strings.Culture locLang in cultures)
                            {
                                if (locFile.map[replacements.Key].Localization.ContainsKey(locLang) == false)
                                {
                                    string val  = original;
                                    string nval = MainForm.Normilize(val);
                                    //statistics.Add(val);
                                    if (locLang == Localize.Strings.Culture.CULTURE_RU_RU)
                                    {
                                        if (val.Length > 30)
                                        {
                                            if (locCache.ContainsKey(nval) == false)
                                            {
                                                //statistics.Add(val);
                                                //MessageBox.Show(val);
                                                val = GoogleTranslate.Translate(val);
                                                locCache.Add(nval, val);
                                                System.Threading.Thread.Sleep(1000);
                                                Log.Debug?.Write(0, "'" + replacements.Value + "' - '" + val + "'\n", true);
                                                //MessageBox.Show(val);
                                                //++debugCounter;
                                            }
                                            else
                                            {
                                                val = locCache[nval];
                                            }
                                        }
                                    }
                                    nTr.Localization.Add(locLang, val);
                                }
                            }
                            locFile.Merge(nTr);
                        }
                    }
                }
            }
        }
Beispiel #12
0
 private void button1_Click(object sender, EventArgs e)
 {
     textBox2.Text = string.Empty;
     textBox2.Text = googleTranslate.Translate(textBox1.Text, "en", "ru");
     label1.Text   = googleTranslate.URL.ToString();
 }
Beispiel #13
0
        static void Main(string[] args)
        {
            if (Debugger.IsAttached)
            {
                args = new string[]
                {
                    "Hello World!",
                    //"-f",
                    //"en",
                    "-t",
                    "ru",
                    //"-s",
                    //"D:\\Temp\\en.TXT",
                    //@"D:\Source\Svn\GO.Desktop\GO.Library\GO.Res\Resources.resx",
                    //@"D:\Source\Svn\GO.Desktop\GO.Library\GO.Res\Resources.xlsx",
                    //"-d",
                    //"D:\\Temp\\fi.txt",
                    //@"D:\Source\Svn\GO.Desktop\GO.Library\GO.Res\Resources.fi.resx",
                    //@"D:\Source\Svn\GO.Desktop\GO.Library\GO.Res\Resources.fi.xlsx",
                    //"--take",
                    //"10",
                    //"вторник"
                    "-apikey",
                    File.ReadAllText("D:\\Frontmatec\\Bin\\babelfish.apikey"),
                };
            }

            try
            {
                if (args == null || !args.Any())
                {
                    throw new Exception("");
                }

                var fromCultureName     = string.Empty;
                var toCultureName       = string.Empty;
                var sourceFileName      = string.Empty;
                var destinationFileName = string.Empty;
                var take     = 0;
                var apiKey   = string.Empty;
                var showHelp = false;
                var options  = new OptionSet {
                    { "f|from=", "from language.", a => fromCultureName = a },
                    { "t|to=", "to language.", a => toCultureName = a },
                    { "s|source=", "specifies the file to be translated.", a => sourceFileName = a },
                    { "d|destination=", "specifies the file for the translated file.", a => destinationFileName = a },
                    { "take=", "specified the number or lines to translate.", a => take = int.Parse(a) },
                    { "apikey=", "specifies the google api key.", a => apiKey = a },
                    { "h|help", "shows this message.", a => showHelp = a != null },
                };
                var unprocessedArgs = options.Parse(args)?.ToArray();
                var sourceText      = string.Join(" ", unprocessedArgs);

                if (showHelp)
                {
                    ShowHelp(options);
                    return;
                }

                if (!string.IsNullOrWhiteSpace(sourceFileName) && string.IsNullOrWhiteSpace(destinationFileName))
                {
                    var fileExtension = Path.GetExtension(sourceFileName);
                    if (".xlsx".Equals(fileExtension, StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (string.IsNullOrWhiteSpace(fromCultureName))
                        {
                            fromCultureName = "en";
                        }

                        if (string.IsNullOrWhiteSpace(toCultureName))
                        {
                            using (var workbook = new XLWorkbook(sourceFileName))
                                toCultureName = workbook.Worksheets.FirstOrDefault()?.Name ?? string.Empty;
                        }

                        destinationFileName = sourceFileName;
                    }
                }

                var sourceLanguage = !string.IsNullOrWhiteSpace(fromCultureName) ? ParseLanguage(fromCultureName) : Language.Unknown;
                if (sourceLanguage == Language.Unknown && !string.IsNullOrWhiteSpace(sourceFileName))
                {
                    throw new Exception("from not specified.");
                }

                if (string.IsNullOrWhiteSpace(toCultureName) && string.IsNullOrWhiteSpace(sourceFileName))
                {
                    toCultureName = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
                }

                var destinationLanguage = !string.IsNullOrWhiteSpace(toCultureName) ? ParseLanguage(toCultureName) : Language.Unknown;
                if (destinationLanguage == Language.Unknown)
                {
                    throw new Exception("to not specified.");
                }

                var resources = !string.IsNullOrWhiteSpace(sourceFileName) ? ReadFile(sourceFileName, fromCultureName) : new Resource[] { new Resource {
                                                                                                                                              SourceText = sourceText
                                                                                                                                          } };
                if (resources == null)
                {
                    resources = new Resource[0];
                }

                if (take > 0)
                {
                    resources = resources.Take(take).ToArray();
                }

                if (!string.IsNullOrWhiteSpace(destinationFileName) && File.Exists(destinationFileName) && !destinationFileName.Equals(sourceFileName))
                {
                    Console.Write($"{Path.GetFileName(destinationFileName)} already exists. Do you want to replace it? [Y/n]");
                    if (Console.ReadLine().Equals("n", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return;
                    }
                    File.Delete(destinationFileName);
                }

                if (string.IsNullOrWhiteSpace(apiKey) && File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "babelfish.apikey")))
                {
                    apiKey = File.ReadAllText(Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "babelfish.apikey")));
                }
                if (string.IsNullOrWhiteSpace(apiKey))
                {
                    throw new Exception("apikey not specified.");
                }

                var useProgressBar = !string.IsNullOrWhiteSpace(destinationFileName) && resources.Length > 3;
                var google         = new GoogleTranslate(apiKey);
                for (var i = 0; i < resources.Length; i++)
                {
                    var resource = resources[i];

                    if (!string.IsNullOrWhiteSpace(resource.SourceText))
                    {
                        if (sourceLanguage == Language.Unknown)
                        {
                            sourceLanguage = ParseLanguage(google.DetectLanguage(resource.SourceText)[0].Language);
                        }
                        resource.DestinationText = HttpUtility.HtmlDecode(google.Translate(sourceLanguage, destinationLanguage, resource.SourceText)[0].TranslatedText);
                    }

                    if (useProgressBar)
                    {
                        Console.CursorLeft = 0;
                        Console.Write($"Translating: {(i + 1).ToString().PadLeft(resources.Length.ToString().Length)}/{resources.Length} [{new string('#', ((int)100.0 * (i + 1) / resources.Length) / 2).PadRight(50, '.')}]");
                    }
                }

                if (useProgressBar)
                {
                    Console.WriteLine();
                }

                WriteFile(destinationFileName, fromCultureName, toCultureName, resources);
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrWhiteSpace(ex.Message))
                {
                    Console.WriteLine(ex.Message);
                }
                Console.WriteLine("Try 'babelfish --help' for more information.");
            }
            finally
            {
                if (Debugger.IsAttached)
                {
                    Console.ReadLine();
                }
            }
        }
Beispiel #14
0
        private void AddVersionAndCopyItems(Item item, List <Language> targetLanguages, Language sourceLang)
        {
            string _sourceLanguage = sourceLang.CultureInfo.EnglishName.Split(' ')[0];
            string _targetLanguage = null;

            foreach (Language language in targetLanguages)
            {
                Item source = Context.ContentDatabase.GetItem(item.ID, sourceLang);
                Item target = Context.ContentDatabase.GetItem(item.ID, language);

                if (source == null || target == null)
                {
                    return;
                }

                _targetLanguage = language.CultureInfo.EnglishName.Split(' ')[0];

                Sitecore.Diagnostics.Log.Debug("Smart Tools: AddVersionAndCopyItems-SourcePath-" + source.Paths.Path, this);
                Sitecore.Diagnostics.Log.Debug("Smart Tools: AddVersionAndCopyItemsSourceLanguage-" + sourceLang.Name, this);
                Sitecore.Diagnostics.Log.Debug("Smart Tools: AddVersionAndCopyItems-TargetLanguage-" + language.Name, this);

                source = source.Versions.GetLatestVersion();

                // If needed test googleTranslate
                if (bGoogleTranslate && _sourceLanguage != _targetLanguage)
                {
                    if (bUseProxy)
                    {
                        GoogleTranslate.ProxySettings.SetProxy(szProxy, iPort, szUser, szPassword, szPassword);
                    }
                    bool bProxyIsSet = GoogleTranslate.ProxySettings.IsSet;
                    bGoogleTranslate = (GoogleTranslate.Translate("English", "French", "Thank You") == "Merci");
                }

                target.Versions.AddVersion();
                target.Editing.BeginEdit();
                source.Fields.ReadAll();
                foreach (Field field in source.Fields)
                {
                    if (!field.Name.StartsWith("_")) //(!field.Shared)
                    {
                        target[field.Name] = source[field.Name];
                        if (bGoogleTranslate)
                        {
                            if (FieldTypeManager.GetField(field) is TextField && !field.Shared)
                            {
                                //if (bUseProxy)
                                //    GoogleTranslate.ProxySettings.SetProxy(szProxy, iPort, szUser, szPassword, szPassword);

                                target[field.Name] = Sitecore.SharedSource.GoogleTranslate.GoogleTranslate.Translate(
                                    _sourceLanguage,
                                    _targetLanguage,
                                    target[field.Name]
                                    );
                            }
                        }
                    }
                }
                target.Editing.EndEdit();

                Sitecore.Diagnostics.Log.Debug("Smart Tools: AddVersionAndCopyItems-Completed.", this);
            }
        }
Beispiel #15
0
        public static void AddNewLocalizationKey()
        {
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                Debug.LogWarning("No internet connection - cannot add new localization key!");
                return;
            }

            CheckAndUpdateCurrentDatabaseSource(() => {
                CommandPaletteArgumentWindow.Show("Set Localization Key", (localizationKey) => {
                    CultureInfo masterCulture = EditorLocalizationConfiguration.GetMasterCulture();
                    CommandPaletteArgumentWindow.Show(string.Format("Set {0} Text", masterCulture.EnglishName), (masterText) => {
                        ITable <GLocalizationMasterRowData> localizationMasterTable = currentDatabaseSource_.LoadLocalizationMasterTable();
                        if (localizationMasterTable == null)
                        {
                            return;
                        }

                        ITable <GLocalizationRowData> localizationEntryTable = currentDatabaseSource_.LoadLocalizationEntriesTable();
                        if (localizationEntryTable == null)
                        {
                            return;
                        }

                        GoogleTranslate translation = GoogleTranslateSource.FindAndCreate();
                        if (translation == null)
                        {
                            return;
                        }

                        bool existingKey = localizationMasterTable.FindAll().Any(r => r.Element.Key == localizationKey);
                        if (existingKey)
                        {
                            Debug.LogWarning("Found existing row for localization key: " + localizationKey + " cannot adding as new!");
                            return;
                        }

                        var rowData = new GLocalizationMasterRowData();
                        rowData.Key = localizationKey;
                        localizationMasterTable.Add(rowData);

                        // NOTE (darren): we don't delete pre-existing entries in case of data loss
                        bool duplicateKey = localizationEntryTable.FindAll().Any(r => r.Element.Key == localizationKey);
                        if (duplicateKey)
                        {
                            Debug.LogWarning("Found pre-existing rows for localization key: " + localizationKey + ", please verify that they are correct - will not be deleted!");
                        }

                        foreach (var supportedCulture in EditorLocalizationConfiguration.GetSupportedCultures())
                        {
                            bool isMasterText = supportedCulture.Equals(masterCulture);
                            string translatedText;
                            if (isMasterText)
                            {
                                translatedText = masterText;
                            }
                            else
                            {
                                translatedText = translation.Translate(masterText, masterCulture.TwoLetterISOLanguageName, supportedCulture.TwoLetterISOLanguageName);
                            }

                            var entryRowData           = new GLocalizationRowData();
                            entryRowData.Key           = localizationKey;
                            entryRowData.LanguageCode  = supportedCulture.Name;
                            entryRowData.LocalizedText = translatedText;
                            entryRowData.SetNeedsUpdating(!isMasterText);
                            localizationEntryTable.Add(entryRowData);
                        }

                        // Cache bundled localization tables after new row
                        LocalizationOfflineCache.CacheBundledLocalizationTables();
                        // Rebake fonts after new translations
                        TMPLocalization.DownloadAndBakeAllUsedLocalizationCharactersIntoFonts();
                        Debug.Log("Finished adding new key: " + localizationKey + " to: " + currentDatabaseSource_.TableKey + "!");
                    });
                });
            });
        }