Beispiel #1
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 #2
0
        public void DetectLanguagesTest()
        {
            GoogleTranslate google = new GoogleTranslate(_apiKey);

            google.PrettyPrint = false;
            List <LanguageDetection> results = google.DetectLanguage("Hallo gibt es");

            //There has to be at least 1 result
            Assert.True(results.Count >= 1);

            //It should detect german
            Assert.Equal(Language.German.GetStringValue(), results[0].Language);

            //It has to have a confidence of more than 0
            Assert.True(results[0].Confidence > 0.0f);

            //Too small of a text to be reliable
            Assert.False(results[0].IsReliable);
        }
Beispiel #3
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();
                }
            }
        }