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

            Assert.False(google.PrettyPrint.HasValue);
            Assert.False(google.LargeQuery.HasValue);
        }
Beispiel #2
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 #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
        public void BwApp_DoWork(object sender, DoWorkEventArgs e)
        {
            GoogleTranslateInfo gti = e.Argument as GoogleTranslateInfo;

            gti      = new GoogleTranslate(Config.APIKey).TranslateText(gti);
            e.Result = gti;
        }
Beispiel #5
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 #6
0
        void work_DoWork(object sender, DoWorkEventArgs e)
        {
            object transLate = new Object();
            Type   type      = null;

            switch (TeanslateApi)
            {
            case "百度Baidu":
                transLate = new BaiduTranslate();
                type      = typeof(BaiduTranslate);
                break;

            case "谷歌Google":
                transLate = new GoogleTranslate();
                type      = typeof(GoogleTranslate);
                break;

            case "腾讯Tencent":
                transLate = new TencentTranslate();
                type      = typeof(TencentTranslate);
                break;

            case "必应Bing":
                translation = (new BingTranslate()).必应Bing(textBox1.Text);
                return;
            }
            string 原文语言 = TDictionary.langDic[TeanslateApi][label2.Text];

            lanTo = TDictionary.langDic[TeanslateApi][label4.Text];
            MethodInfo mt = type.GetMethod(TeanslateApi);

            translation = (string)mt.Invoke(transLate, new object[] { textBox1.Text, 原文语言, lanTo });
        }
        public string GetTK(string text, string tkk)
        {
            string result = GoogleTranslate.GetTK(text, tkk);

            return(result);
            // TODO: 将断言添加到 方法 GoogleTranslateTest.GetTK(String, String)
        }
Beispiel #8
0
        public ActionResult Program(string id, string lang)
        {
            var plan = RavenSession.Query <Program>().FirstOrDefault(p => p.ShortUrl == id);

            if (plan == null)
            {
                return(HttpNotFound("Program not found"));
            }

            SaveView(plan);

            if (!string.IsNullOrWhiteSpace(lang))
            {
                GoogleTranslate.TranslateExercise(plan, lang);
            }

            var clinic  = RavenSession.Load <Clinic>("clinics/" + plan.ClinicId);
            var user    = RavenSession.Load <User>("users/" + plan.UserId);
            var account = RavenSession.Load <Account>("accounts/" + plan.AccountId);

            var vm = new PublicProgramViewModel()
            {
                Program = plan, From = user, Clinic = clinic, Settings = account.Settings
            };

            return(View(vm));
        }
Beispiel #9
0
 public GUI(DataFaucet <AudioBuffer> df, AggregateDump dump, GoogleASR asr, GoogleTranslate gt)
 {
     Speak = false;
     InitializeComponent();
     this.faucet    = df;
     this.dump      = dump;
     this.speechRec = asr;
     this.translate = gt;
     System.Timers.Timer myTimer = new System.Timers.Timer();
 }
Beispiel #10
0
        public void SupportedLanaugesTest()
        {
            GoogleTranslate google = new GoogleTranslate(_apiKey);

            google.PrettyPrint = false;
            List <TranslationLanaguage> results = google.GetSupportedLanguages();

            //We know that english and german is in the list. So they should be there
            Assert.Contains(results, lang => lang.Language == Language.English.GetStringValue());
            Assert.Contains(results, lang => lang.Language == Language.German.GetStringValue());
        }
Beispiel #11
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 #12
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);
        }
        public void TranslateAsync(GoogleTranslateInfo info)
        {
            btnTranslate.Enabled   = false;
            btnTranslateTo.Enabled = false;

            TaskEx.Run(() =>
            {
                info = new GoogleTranslate(Config.APIKey).TranslateText(info);
            },
                       () =>
            {
                UpdateGoogleTranslateGUI(info);
            });
        }
Beispiel #14
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 #15
0
        public static void TextToSpeech([DI] SocketMessage msg, string src)
        {
            byte[] bytes;
            string lang;
            int    idx = src.IndexOf(' ');

            if (idx > 0 && idx != src.Length - 1 && GoogleTranslate.SupportsLanguage(lang = src.Substring(0, idx)))
            {
                bytes = GoogleTranslate.TextToSpeech(src.Substring(idx + 1), lang).Result;
            }
            else
            {
                bytes = GoogleTranslate.TextToSpeech(src).Result;
            }

            msg.Channel.SendFileAsync(new MemoryStream(bytes), "audio.mp3").Wait();
        }
        public async Task <IActionResult> Create([Bind("TranslationID,Danish,Swedish,Norwegian,English,German,Spanish,Italian,Croatian")] Translation translation)
        {
            var googleTranslate = new GoogleTranslate();

            if (String.IsNullOrEmpty(translation.Swedish))
            {
                translation.Swedish = googleTranslate.TranslateText(translation.Danish, "sv");
            }
            if (String.IsNullOrEmpty(translation.Norwegian))
            {
                translation.Norwegian = googleTranslate.TranslateText(translation.Danish, "no");
            }
            if (String.IsNullOrEmpty(translation.German))
            {
                translation.German = googleTranslate.TranslateText(translation.Danish, "de");
            }
            if (String.IsNullOrEmpty(translation.Spanish))
            {
                translation.Spanish = googleTranslate.TranslateText(translation.Danish, "es");
            }
            if (String.IsNullOrEmpty(translation.Italian))
            {
                translation.Italian = googleTranslate.TranslateText(translation.Danish, "it");
            }
            if (String.IsNullOrEmpty(translation.Croatian))
            {
                translation.Croatian = googleTranslate.TranslateText(translation.Danish, "hr");
            }
            if (String.IsNullOrEmpty(translation.English))
            {
                translation.English = googleTranslate.TranslateText(translation.Danish, "en");
            }



            if (ModelState.IsValid)
            {
                _context.Add(translation);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(translation));
        }
Beispiel #17
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);
        }
        public ICollection <VideoPhraseModel> GetAll(int videoId)
        {
            var phrases =
                Context.VideoPhrases.Where(p => p.Video == Context.Videos.FirstOrDefault(v => v.Id == videoId))
                .ToList();

            var models = phrases.Select(_videoPhraseModelBuilder.Build).ToList();


            foreach (var model in models)
            {
                if (string.IsNullOrEmpty(model.PhraseTranslated) && !string.IsNullOrEmpty(model.Phrase))
                {
                    model.TranslatedByGoogle = true;
                    model.PhraseTranslated   = GoogleTranslate.TranslateText(model.Phrase, "en", "ro");
                }
            }


            return(models);
        }
        static void Main(string[] args)
        {
            using (Pipeline pipeline = Pipeline.Create())
            {
                WaveFormat waveFormat = WaveFormat.Create16kHz1Channel16BitPcm();

                IProducer <AudioBuffer> audioInput = new AudioCapture(pipeline, new AudioCaptureConfiguration()
                {
                    OutputFormat = waveFormat
                });
                DataFaucet <AudioBuffer> df = new DataFaucet <AudioBuffer>(pipeline);
                audioInput.PipeTo(df);
                AggregateDump dump = new AggregateDump(pipeline);
                df.PipeTo(dump);
                GoogleASR gsr = new GoogleASR(pipeline, "en");                   //gsr for google speech recognition
                dump.PipeTo(gsr);
                GoogleTranslate gt = new GoogleTranslate(pipeline, "en", "de");  //gt for google translate
                gsr.PipeTo(gt);
                GoogleSpeak gs = new GoogleSpeak(pipeline, waveFormat, "de-DE"); //gs for google speak
                gt.PipeTo(gs);
                AudioOutput aOut = new AudioOutput(pipeline);                    //aOut for audio out
                gs.PipeTo(aOut);

                ActiveMQ rasa = new ActiveMQ(pipeline, "rasa.PSI", "rasa.PYTHON");
                gsr.PipeTo(rasa);

                GUI    gui    = new GUI(df, dump, gsr, gt);
                Thread thread = new Thread(() =>
                {
                    gui.ShowDialog();
                });
                thread.Start();

                pipeline.RunAsync();

                Console.ReadKey(true);
            }
        }
Beispiel #20
0
        private static void Interpreter()
        {
            #region Interpreter

            ITranslator translator = new GoogleTranslate();

            Contexto contexto = new Contexto("Sabedoria");
            Tradutor tradutor = new TradutorParaIngles(translator);
            tradutor.Interpretador(contexto);
            GerenciadorSaida.SaidaConsole.EscreverTexto($"{contexto.EntradaTexto} = {contexto.Traduzido}");
            GerenciadorSaida.SaidaConsole.EscreverTexto(Environment.NewLine);

            tradutor = new TradutorParaEspanhol(translator);
            tradutor.Interpretador(contexto);
            GerenciadorSaida.SaidaConsole.EscreverTexto($"{contexto.EntradaTexto} = {contexto.Traduzido}");
            GerenciadorSaida.SaidaConsole.EscreverTexto(Environment.NewLine);

            tradutor = new TradutorParaFrances(translator);
            tradutor.Interpretador(contexto);
            GerenciadorSaida.SaidaConsole.EscreverTexto($"{contexto.EntradaTexto} = {contexto.Traduzido}");
            GerenciadorSaida.SaidaConsole.EscreverTexto(Environment.NewLine);

            #endregion Interpreter
        }
Beispiel #21
0
 public string Get([FromUri] string phrase)
 {
     return(GoogleTranslate.TranslateText(phrase, "en", "ro"));
 }
Beispiel #22
0
 public void TestTranslation()
 {
     Assert.AreEqual("This is a translation.", GoogleTranslate.Translate("Dit is een vertaling.").Result);
 }
Beispiel #23
0
 public void GenerateToken()
 {
     Assert.AreEqual("783049.878026", GoogleTranslate.GenerateToken("test", "431875.931032818"));
     Assert.AreEqual("661741.823272", GoogleTranslate.GenerateToken("test", "431877.1894360868"));
     Assert.AreEqual("460360.102733", GoogleTranslate.GenerateToken("This is a test.", "431877.1894360868"));
 }
Beispiel #24
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 #25
0
 public Form1()
 {
     InitializeComponent();
     googleTranslate = new GoogleTranslate();
 }
Beispiel #26
0
 /// <summary>
 /// Translates the given text to <paramref name="targetLang"/>. The function detects automatically the souce language
 /// </summary>
 /// <param name="targetLang">The target language</param>
 /// <param name="sourceText">The text to translate</param>
 /// <param name="callback">A callback function invoked after the translation</param>
 public static void Translate(string targetLang, string sourceText, Action <TranslationInfo> callback)
 {
     EditorCoroutine.Start(GoogleTranslate.Process("auto", targetLang, sourceText, callback));
 }
Beispiel #27
0
        //private void PrepareMods_Click(object sender, EventArgs e) {
        //  saveFileDialog.OverwritePrompt = false;
        //  HashSet<string> statistics = new HashSet<string>();
        //  GoogleTranslate t = new GoogleTranslate();
        //  int debugCounter = 0;
        //  int debugCounterMax = 5;
        //  if (saveFileDialog.ShowDialog() == DialogResult.OK) {
        //    string current_file = string.Empty;
        //    try {
        //      bool fileExists = File.Exists(saveFileDialog.FileName);
        //      string baseFile = saveFileDialog.FileName;
        //      LocalizationFile locFile = new LocalizationFile(saveFileDialog.FileName);
        //      List<ModRecord> mods = modsList.CheckedItems.OfType<ModRecord>().ToList<ModRecord>();
        //      Dictionary<string, string> jsonUpdatedContent = new Dictionary<string, string>();
        //      Dictionary<string, ConversationFile> convUpdatedContent = new Dictionary<string, ConversationFile>();
        //      foreach (ModRecord mod in mods) {
        //        if (debugCounter > debugCounterMax) { break; }
        //        string modName = Normilize(mod.Name);
        //        List<string> jsonsPath = new List<string>();
        //        GetAllJsons(mod.Path, ref jsonsPath, 0);
        //        foreach (string jsonPath in jsonsPath) {
        //          current_file = jsonPath;
        //          bool updated = false;
        //          //MessageBox.Show(jsonPath);
        //          string filename = Normilize(Path.GetFileNameWithoutExtension(jsonPath));
        //          object content = null;
        //          if (Path.GetFileName(jsonPath).ToUpper() == "LOCALIZATION.JSON") { continue; }
        //          if (Path.GetExtension(jsonPath).ToUpper() == ".JSON") {
        //            string jsonCont = File.ReadAllText(jsonPath);
        //            content = JObject.Parse(jsonCont);
        //          } else if (Path.GetExtension(jsonPath).ToUpper() == ".BYTES") {
        //            content = new ConversationFile(jsonPath);
        //          }
        //          foreach (var jtproc in partsList.CheckedItems) {
        //            if (debugCounter > debugCounterMax) { break; }
        //            jtProcGeneric jtProc = jtproc as jtProcGeneric;
        //            if (jtProc == null) { continue; }
        //            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(GameBaseSelector.SelectedPath.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 langsList.CheckedItems.OfType<Localize.Strings.Culture>().ToList<Localize.Strings.Culture>()) {
        //                  string val = replacements.Value;
        //                  string nval = Normilize(val);
        //                  if (locLang == Localize.Strings.Culture.CULTURE_RU_RU) {
        //                    if (val.Length > 30) {
        //                      if (translationCache.ContainsKey(nval) == false) {
        //                        statistics.Add(val);
        //                        MessageBox.Show(val);
        //                        val = GoogleTranslate.Translate(val);
        //                        translationCache.Add(nval, val);
        //                        Log.Debug.Write(0, "'" + replacements.Value + "' - '" + val + "'\n", true);
        //                        MessageBox.Show(val);
        //                        ++debugCounter;
        //                      } else {
        //                        val = translationCache[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(GameBaseSelector.SelectedPath.Length); ;
        //                    nTr.Name = replacements.Key;
        //                    nTr.Original = original;
        //                    foreach (Localize.Strings.Culture locLang in langsList.CheckedItems.OfType<Localize.Strings.Culture>().ToList<Localize.Strings.Culture>()) {
        //                      if (locFile.map[replacements.Key].Localization.ContainsKey(locLang) == false) {
        //                        string val = original;
        //                        string nval = Normilize(val);
        //                        statistics.Add(val);
        //                        if (locLang == Localize.Strings.Culture.CULTURE_RU_RU) {
        //                          if (val.Length > 30) {
        //                            if (translationCache.ContainsKey(nval) == false) {
        //                              statistics.Add(val);
        //                              MessageBox.Show(val);
        //                              val = GoogleTranslate.Translate(val);
        //                              translationCache.Add(nval, val);
        //                              Log.Debug.Write(0, "'" + replacements.Value + "' - '" + val + "'\n", true);
        //                              MessageBox.Show(val);
        //                              ++debugCounter;
        //                            } else {
        //                              val = translationCache[nval];
        //                            }
        //                          }
        //                        }
        //                        nTr.Localization.Add(locLang, val);
        //                      }
        //                    }
        //                    locFile.Merge(nTr);
        //                  }
        //                }
        //              }
        //            }
        //          }
        //          if (updated) {
        //            if (Path.GetExtension(jsonPath).ToUpper() == ".JSON") {
        //              JObject json = content as JObject;
        //              if (json != null) { jsonUpdatedContent.Add(jsonPath, json.ToString(Formatting.Indented)); };
        //            } else if (Path.GetExtension(jsonPath).ToUpper() == ".BYTES") {
        //              ConversationFile cfile = content as ConversationFile;
        //              if (cfile != null) { convUpdatedContent.Add(jsonPath, cfile); };
        //            }
        //          };
        //        }
        //        current_file = string.Empty;
        //      }
        //      if (fileExists == false) {
        //        locFile.Save();
        //      } else {
        //        saveFileDialog.InitialDirectory = Path.GetDirectoryName(baseFile);
        //        if (saveFileDialog.ShowDialog() == DialogResult.OK) {
        //          if (saveFileDialog.FileName == baseFile) {
        //            //MessageBox.Show("Same file");
        //            locFile.Save();
        //          } else {
        //            //MessageBox.Show("Different file");
        //            locFile.filename = saveFileDialog.FileName;
        //            locFile.removeOtherTranslations(langsList.CheckedItems.OfType<Localize.Strings.Culture>().ToList<Localize.Strings.Culture>());
        //            locFile.Save(true);
        //          }
        //        }
        //      }
        //      foreach (var uJsons in jsonUpdatedContent) {
        //        File.WriteAllText(uJsons.Key, uJsons.Value);
        //      }
        //      foreach (var uConv in convUpdatedContent) {
        //        uConv.Value.Save();
        //      }
        //      int overralCharsLength = 0;
        //      foreach (string str in statistics) { overralCharsLength += str.Length; }
        //      MessageBox.Show("Done. Strings: " + statistics.Count + ". Characters:" + overralCharsLength);
        //    } catch (Exception ex) {
        //      MessageBox.Show("in file:" + current_file + "\n" + ex.ToString());
        //    }
        //    string trCache = JsonConvert.SerializeObject(translationCache, Formatting.Indented);
        //    File.WriteAllText(translationCache_filename, trCache);
        //  }
        //}
        private void PrepareMods_Click(object sender, EventArgs e)
        {
            saveFileDialog.OverwritePrompt = false;
            HashSet <string> statistics  = new HashSet <string>();
            GoogleTranslate  t           = new GoogleTranslate();
            int  debugCounter            = 0;
            int  debugCounterMax         = 5;
            bool deleteOtherTranslations = false;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string current_file = string.Empty;
                try {
                    bool             fileExists = File.Exists(saveFileDialog.FileName);
                    LocalizationFile locFile    = new LocalizationFile(saveFileDialog.FileName);
                    if (File.Exists(locFile.filename))
                    {
                        saveFileDialog.InitialDirectory = Path.GetDirectoryName(locFile.filename);
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            if (saveFileDialog.FileName != locFile.filename)
                            {
                                locFile.MergeFile(saveFileDialog.FileName);
                                locFile.filename        = saveFileDialog.FileName;
                                deleteOtherTranslations = true;
                            }
                        }
                    }
                    //locFile.DebugLogDump();
                    //Application.Exit();
                    List <ModRecord>                      mods = modsList.CheckedItems.OfType <ModRecord>().ToList <ModRecord>();
                    Dictionary <string, string>           jsonUpdatedContent = new Dictionary <string, string>();
                    Dictionary <string, ConversationFile> convUpdatedContent = new Dictionary <string, ConversationFile>();
                    List <PrepareRecord>                  prepareRecords     = new List <PrepareRecord>();
                    foreach (ModRecord mod in mods)
                    {
                        if (debugCounter > debugCounterMax)
                        {
                            break;
                        }
                        List <string> jsonsPath = new List <string>();
                        GetAllJsons(mod.Path, ref jsonsPath, 0);
                        foreach (string jsonPath in jsonsPath)
                        {
                            current_file = jsonPath;
                            object content = null;
                            if (Path.GetFileName(jsonPath).ToUpper() == "LOCALIZATION.JSON")
                            {
                                continue;
                            }
                            if (Path.GetExtension(jsonPath).ToUpper() == ".JSON")
                            {
                                string jsonCont = File.ReadAllText(jsonPath);
                                content = JObject.Parse(jsonCont);
                            }
                            else if (Path.GetExtension(jsonPath).ToUpper() == ".BYTES")
                            {
                                content = new ConversationFile(jsonPath);
                            }
                            foreach (var jtproc in partsList.CheckedItems)
                            {
                                if (debugCounter > debugCounterMax)
                                {
                                    break;
                                }
                                jtProcGeneric jtProc = jtproc as jtProcGeneric;
                                if (jtProc == null)
                                {
                                    continue;
                                }
                                prepareRecords.Add(new PrepareRecord(mod, jsonPath, jtProc,
                                                                     langsList.CheckedItems.OfType <Localize.Strings.Culture>().ToList <Localize.Strings.Culture>(), translationCache, content, locFile, GameBaseSelector.SelectedPath
                                                                     ));
                            }
                        }
                        current_file = string.Empty;
                    }
                    ProcessForm processForm = new ProcessForm();
                    processForm.DeleteOtherTranslations = deleteOtherTranslations;
                    processForm.prepareRecords          = prepareRecords;
                    processForm.progressBar.Maximum     = prepareRecords.Count * 2;
                    processForm.backgroundWorker.RunWorkerAsync();
                    processForm.ShowDialog();
                    if (deleteOtherTranslations)
                    {
                        locFile.removeOtherTranslations(langsList.CheckedItems.OfType <Localize.Strings.Culture>().ToList <Localize.Strings.Culture>());
                    }
                    locFile.Save(deleteOtherTranslations);
                    foreach (PrepareRecord pr in prepareRecords)
                    {
                        if (pr.updated)
                        {
                            if (Path.GetExtension(pr.jsonPath).ToUpper() == ".JSON")
                            {
                                JObject json = pr.content as JObject;
                                if (json != null)
                                {
                                    if (jsonUpdatedContent.ContainsKey(pr.jsonPath) == false)
                                    {
                                        jsonUpdatedContent.Add(pr.jsonPath, json.ToString(Formatting.Indented));
                                    }
                                }
                                ;
                            }
                            else if (Path.GetExtension(pr.jsonPath).ToUpper() == ".BYTES")
                            {
                                ConversationFile cfile = pr.content as ConversationFile;
                                if (cfile != null)
                                {
                                    if (convUpdatedContent.ContainsKey(pr.jsonPath) == false)
                                    {
                                        convUpdatedContent.Add(pr.jsonPath, cfile);
                                    }
                                    ;
                                }
                                ;
                            }
                        }
                        ;
                    }
                    foreach (var uJsons in jsonUpdatedContent)
                    {
                        File.WriteAllText(uJsons.Key, uJsons.Value);
                    }
                    foreach (var uConv in convUpdatedContent)
                    {
                        uConv.Value.Save();
                    }
                    MessageBox.Show("Compleete");
                } catch (Exception ex) {
                    MessageBox.Show("in file:" + current_file + "\n" + ex.ToString());
                }
                string trCache = JsonConvert.SerializeObject(translationCache, Formatting.Indented);
                File.WriteAllText(translationCache_filename, trCache);
            }
        }
Beispiel #28
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 #29
0
 public ModeTranslate()
     : base('T')
 {
     translator = new GoogleTranslate();
 }
Beispiel #30
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));
 }