void TextToSpeech_SpeakCompleted(object sender, BingTranslator.SpeakCompletedEventArgs e)
 {
     try
     {
         if (e.Error != null)
         {
             Debug.WriteLine("TextToSpeech_SpeakCompleted failed: " + e.Error.Message);
             return;
         }
         WebClient client = new WebClient();
         client.OpenReadCompleted += new OpenReadCompletedEventHandler((s, args) =>
         {
             if (args.Error != null)
             {
                 Debug.WriteLine("WebClient.OpenReadCompleted failed:" + args.Error);
                 return;
             }
             TextToSpeech tts = (TextToSpeech)args.UserState;
             tts.SaveAudioFile(args.Result);
             tts.PlayAudioFile();
         });
         client.OpenReadAsync(new Uri(e.Result), sender);
     }
     catch (Exception)
     {
         // currently this fails silently in the background
         // TODO: expose the exception to MainPage (via their chained SpeakCompleted handler?)
     }
 }
Exemplo n.º 2
0
        public void Configure(BingTranslator translator)
        {
            Console.WriteLine("Enter your bing API key:");
            var key = Console.ReadLine().Trim();

            translator.Init(key);
        }
        /// ------------------------------------------------------------------------------------
        private void CreateTranslator()
        {
            var worker = new BackgroundWorker();

            worker.DoWork += delegate { BingTranslator = new BingTranslator(_srcLangId, _tgtLangId); };
            worker.RunWorkerAsync();
        }
Exemplo n.º 4
0
        public static CoreTranslator GetProvider(ILogger logger, Language source, Language target, string query,
                                                 string provider = "google")
        {
            CoreTranslator result = null;

            switch (provider)
            {
            case GlobalConst.GoogleTranslator:
                result = new GoogleTranslator(logger, source, target, query);
                break;

            case GlobalConst.BingTranslator:
                result = new BingTranslator(logger, source, target, query);
                break;

            case GlobalConst.CambridgeTranslator:
                result = new CambridgeDictionaryTranslator(logger, source, target, query);
                break;

            case GlobalConst.OxfordTranslator:
                result = new OxfordDictionaryTranslator(logger, source, target, query);
                break;
            }
            return(result);
        }
        public void Test_BingTranslator()
        {
            var translator = new BingTranslator();

            var originalText = "想要成为";

            var translatedText = translator.Translate(originalText, "zh", "en");

            Assert.AreEqual(translatedText, "Want to be", true, "Not translating correctly.");
        }
Exemplo n.º 6
0
 public SearchController(
     SearchService searchService,
     WWWDbContext dbContext,
     BingTranslator bingTranslator,
     AiurCache cache)
 {
     _searchService  = searchService;
     _dbContext      = dbContext;
     _bingTranslator = bingTranslator;
     _cache          = cache;
 }
Exemplo n.º 7
0
        public TranslateBot(
            BingTranslator bingTranslator,
            BotLogger botLogger)
        {
            _bingTranslator = bingTranslator;
            _botLogger      = botLogger;
            _botLogger.LogWarning("Please enter your bing API key:");
            var key = Console.ReadLine();

            _bingTranslator.Init(key);
        }
Exemplo n.º 8
0
 public static string Translator(string text, string from, string to)
 {
     if (TranslatorUserMethod == 1)
     {
         text = Google.Translate(text, from, to);
     }
     else if (TranslatorUserMethod == 2)
     {
         text = BingTranslator.Translate(text, from, to.ToLower());
     }
     return(text);
 }
Exemplo n.º 9
0
        public void Configure(ILoggerFactory loggerFactory, BingTranslator translator)
        {
            loggerFactory
            .AddConsole(LogLevel.Debug);


            Console.WriteLine("Enter your bing API key:");
            var key = Console.ReadLine().Trim();

            translator
            .Init(key);
        }
Exemplo n.º 10
0
        private async Task SetTranslator()
        {
            if (Downloader == null)
            {
                Debug.Assert(false);
                return;
            }

            if (Config.TranslatorType == TranslatorType.GSheet)
            {
                var translator = new GSheetsTranslator();
                await translator.InitializeService().ConfigureAwait(false);

                Translator = translator;
            }
            else if (Config.TranslatorType == TranslatorType.Google)
            {
                var translator = new GoogleTranslator();

                Translator = translator;
            }
            else if (Config.TranslatorType == TranslatorType.Papago)
            {
                var translator = new PapagoTranslator();

                Translator = translator;
            }
            else if (Config.TranslatorType == TranslatorType.EZTrans)
            {
                var translator = new EZTranslator();

                Translator = translator;
            }
            else if (Config.TranslatorType == TranslatorType.Bing)
            {
                var translator = new BingTranslator();

                Translator = translator;
            }
            else
            {
                Translator = null;
            }

            Downloader.SetTranslator(Translator);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Uses given translation provider and source and target languages to translate data
        /// </summary>
        public static void Translate(List <AbstractTranslateInfoItem> dict, TRANSLATE_PROVIDER provider, string from, string to)
        {
            AbstractTranslatorService service = null;

            // get translation service
            switch (provider)
            {
            case TRANSLATE_PROVIDER.BING:
                service = BingTranslator.GetService(SettingsObject.Instance.BingAppId);
                break;

            case TRANSLATE_PROVIDER.MYMEMORY:
                service = MyMemoryTranslator.GetService();
                break;

            case TRANSLATE_PROVIDER.GOOGLE:
                service = GoogleTranslator.GetService();
                break;
            }
            if (service == null)
            {
                throw new Exception("Cannot resolve translation provider!");
            }
            else
            {
                try {
                    ProgressBarHandler.StartDeterminate(dict.Count, "Translating...");

                    int completed = 0;
                    // use the service to translate texts
                    foreach (AbstractTranslateInfoItem item in dict)
                    {
                        string oldValue = item.Value;
                        item.Value = service.Translate(from, to, oldValue, SettingsObject.Instance.OptimizeSpecialSequencesInTranslation);
                        completed++;

                        VLOutputWindow.VisualLocalizerPane.WriteLine("Translated \"{0}\" as \"{1}\" ", oldValue, item.Value);
                        ProgressBarHandler.SetDeterminateProgress(completed, "Translating...");
                    }
                } finally {
                    ProgressBarHandler.StopDeterminate("Translation finished", "Ready");
                }
            }
        }
Exemplo n.º 12
0
        public void TranslateTest()
        {
            BingTranslator target = new BingTranslator();

            target.AppId = "BTOQcgIba2dKND+yD1r4o+Ye8rScsr8do+xOO9u+C04=";                                // testing AppId

            string fromLanguage     = string.Empty;                                                       // set the source language
            string toLanguage       = "en";                                                               // set the target language
            string untranslatedText = "Tohle je testovací překlad.\nDalší řádek.";                        // text to translate
            string expected         = "This is a test translation.\nThe next line.";                      // expected result
            string actual           = target.Translate(fromLanguage, toLanguage, untranslatedText, true); // run translation

            Assert.AreEqual(expected, actual);

            fromLanguage = "cs"; // try the same with specifying source language
            actual       = target.Translate(fromLanguage, toLanguage, untranslatedText, true);

            Assert.AreEqual(expected, actual);
        }
        /// ------------------------------------------------------------------------------------
        private void HandleTanslateItems(object sender, DoWorkEventArgs e)
        {
            var worker           = sender as BackgroundWorker;
            var nodesToTranslate = e.Argument as IDictionary <int, LocTreeNode <T> >;
            int i = 0;

            foreach (var kvp in nodesToTranslate)
            {
                var node    = kvp.Value;
                var locInfo = new LocalizingInfo(node.Id);
                locInfo.UpdateFields = UpdateFields.None;
                locInfo.LangId       = TgtLangId;

                var text = node.GetText(SrcLangId);
                if (!string.IsNullOrEmpty(text))
                {
                    text = (BingTranslator.TranslateText(text) ?? string.Empty).Trim();
                    if (text != string.Empty)
                    {
                        locInfo.Text          = text;
                        locInfo.UpdateFields |= UpdateFields.Text;
                    }
                }

                text = node.GetToolTip(SrcLangId);
                if (!string.IsNullOrEmpty(text))
                {
                    text = (BingTranslator.TranslateText(text) ?? string.Empty).Trim();
                    if (text != string.Empty)
                    {
                        locInfo.ToolTipText   = text;
                        locInfo.UpdateFields |= UpdateFields.ToolTip;
                    }
                }

                if (locInfo.UpdateFields != UpdateFields.None)
                {
                    SaveChangesInMemory(node, locInfo);
                    worker.ReportProgress(++i, kvp.Key);
                }
            }
        }
Exemplo n.º 14
0
        public void AuthenticateToRemoteMachine(string RemoteMcIp, string UserName, string Password)
        {
            // `net use \\\\$RemoteMcIp /user:$UserName $Passwd`;
            Generic        GenericObj  = new Generic();
            Logger         NewLogObj   = new Logger();
            FileOperations FileObj     = new FileOperations();
            string         LogFilePath = NewLogObj.GetLogFilePath();
            // string AuthenticateCmd = "net use \\\\" + RemoteMcIp+" /user:"******" "+Password ;
            string AuthenticateCmd = "net use " + RemoteMcIp + " /user:"******" " + Password;
            String CmdResult       = GenericObj.StartCmdExecutionAndWaitForCompletion(AuthenticateCmd);

            string SystemLocale        = GenericObj.GetSystemLocale();
            string TranslatedCmdResult = null;

            NewLogObj.WriteLogFile(LogFilePath, "AuthenticateToRemoteMachine Result: " + RemoteMcIp + " " + CmdResult, "info");
            if (!Regex.IsMatch(SystemLocale, "en-US"))
            {
                BingTranslator MyBingObj = new BingTranslator();
                string         Locale    = MyBingObj.DecideLanguageBasedOnLocale(SystemLocale);
                //TranslatedCmdResult = MyBingObj.TranslateString(CmdResult, "English");
                TranslatedCmdResult = MyBingObj.GenerateAccessTokenAndStartTranslation(CmdResult, Locale, "en");
                //TranslatedCmdResult = MyBingObj.GenerateAccessTokenAndStartTranslation(CmdResult, "de", "en");
            }
            else
            {
                TranslatedCmdResult = CmdResult;
            }

            NewLogObj.WriteLogFile(LogFilePath, "AuthenticateToRemoteMachine Result after translation: " + RemoteMcIp + " " + TranslatedCmdResult, "info");
            //CmdResult = "The command completed successfully.\r\n\r\n"
            // if (Regex.IsMatch(TranslatedCmdResult, "command completed successfully",RegexOptions.IgnoreCase))
            if (Regex.IsMatch(TranslatedCmdResult, "successfully", RegexOptions.IgnoreCase))
            {
                NewLogObj.WriteLogFile(LogFilePath, "AuthenticateToRemoteMachine : " + RemoteMcIp + " success ", "info");
            }
            else
            {
                NewLogObj.WriteLogFile(LogFilePath, "AuthenticateToRemoteMachine : " + RemoteMcIp + " failed ", "warn");
            }
        }
Exemplo n.º 15
0
        void Application_Idle(object sender, EventArgs e)
        {
            Application.Idle -= new EventHandler(Application_Idle);
            var translator = new BingTranslator("en", _requestedCulture.TwoLetterISOLanguageName);

            try
            {
                var s = translator.TranslateText(string.Format(_originalMessageTemplate, _requestedCulture.EnglishName, _requestedCulture.NativeName));
                if (!string.IsNullOrEmpty(s))
                {
                    _messageLabel.Text = s;
                    // In general, we will be able to translate OK and the title bar text iff we were able to translate
                    // the message.  This assumption saves a few processor cycles and prevents disappearing text when
                    // a language has not been localized (as is likely the case when we display this dialog).
                    _OKButton.Text = translator.TranslateText("OK");
                    Text           = translator.TranslateText(Text);
                }
            }
            catch (Exception)
            {
                //swallow
            }
        }
Exemplo n.º 16
0
 public TranslateBot(BingTranslator bingTranslator)
 {
     _bingTranslator = bingTranslator;
 }
Exemplo n.º 17
0
        public int WaitTillSystemIsUp(string SystemIP, int WaitTimeOutInMins)
        {
            Generic        GenericObj  = new Generic();
            Logger         NewLogObj   = new Logger();
            FileOperations FileObj     = new FileOperations();
            string         LogFilePath = NewLogObj.GetLogFilePath();
            string         PingCmd     = "ping " + SystemIP;

            NewLogObj.WriteLogFile(LogFilePath, "ping cmd : " + PingCmd, "info");

            String CmdResult  = GenericObj.StartCmdExecutionAndWaitForCompletion(PingCmd);
            Regex  RegPattern = new Regex("\r\n");

            //Replace the newlines
            //CmdResult = RegPattern.Replace(CmdResult, " ");
            string [] TempList = RegPattern.Split(CmdResult);
            CmdResult = TempList[8];
            //foreach (string temp in TempList)
            //{
            //    CmdResult = CmdResult + temp + " ";
            //}
            string SystemLocale        = GenericObj.GetSystemLocale();
            string TranslatedCmdResult = null;

            NewLogObj.WriteLogFile(LogFilePath, "Ping Result: " + CmdResult, "info");

            if (!Regex.IsMatch(SystemLocale, "en-US"))
            {
                //BingTranslator MyBingObj = new BingTranslator();
                BingTranslator MyBingObj = new BingTranslator();
                //string BingLanguage = MyBingObj.DecideLanguageBasedOnLocale(SystemLocale);
                //TranslatedCmdResult = MyBingObj.TranslateString(CmdResult, "english");
                string Locale = MyBingObj.DecideLanguageBasedOnLocale(SystemLocale);
                //Antwort von 10.105.74.7: Bytes=32 Zeit<1ms TTL=63
                TranslatedCmdResult = MyBingObj.GenerateAccessTokenAndStartTranslation(CmdResult, Locale, "en");
            }
            else
            {
                TranslatedCmdResult = CmdResult;
            }
            TranslatedCmdResult = TranslatedCmdResult.ToLower();
            TranslatedCmdResult = Regex.Replace(TranslatedCmdResult, "\\s", "");
            //int PingStats = FileObj.CheckStringForPattern(TranslatedCmdResult, "Packets: Sent = 4, Received = 4, Lost = 0", null);
            // int PingStats = FileObj.CheckStringForPattern(TranslatedCmdResult, "packets:sent=4,received=4,lost=0", null);
            int PingStats = FileObj.CheckStringForPattern(TranslatedCmdResult, "packets:sent=4,received=4", null);

            //int PingStats = FileObj.CheckStringForPattern(CmdResult, TranslatedCmdResult, null);
            //int PingStats = FileObj.CheckUnicodeStringForPattern(CmdResult, TranslatedCmdResult, null);
            if (PingStats == 1)
            {
                NewLogObj.WriteLogFile(LogFilePath, "System " + SystemIP + " is up", "info");
                return(1);
            }
            int Timer = 0;
            int WaitTimeOutInMilliSecs = WaitTimeOutInMins * 60 * 1000;

            while (PingStats == -1 && Timer < WaitTimeOutInMilliSecs)
            {
                CmdResult = GenericObj.StartCmdExecutionAndWaitForCompletion(PingCmd);

                TempList  = RegPattern.Split(CmdResult);
                CmdResult = TempList[8];
                if (!Regex.IsMatch(SystemLocale, "en-US"))
                {
                    BingTranslator MyBingObj = new BingTranslator();
                    //string BingLanguage = MyBingObj.DecideLanguageBasedOnLocale(SystemLocale);
                    //TranslatedCmdResult = MyBingObj.TranslateString(CmdResult, "english");
                    string Locale = MyBingObj.DecideLanguageBasedOnLocale(SystemLocale);
                    TranslatedCmdResult = MyBingObj.GenerateAccessTokenAndStartTranslation(CmdResult, Locale, "en");
                }
                else
                {
                    TranslatedCmdResult = CmdResult;
                }
                //PingStats = FileObj.CheckStringForPattern(CmdResult, "Packets: Sent = 4, Received = 4, Lost = 0", null);
                //PingStats = FileObj.CheckStringForPattern(CmdResult, TranslatedCmdResult, null);
                TranslatedCmdResult = TranslatedCmdResult.ToLower();
                TranslatedCmdResult = Regex.Replace(TranslatedCmdResult, "\\s", "");
                //PingStats = FileObj.CheckStringForPattern(TranslatedCmdResult, "Packets: Sent = 4, Received = 4, Lost = 0", null);
                //PingStats = FileObj.CheckStringForPattern(TranslatedCmdResult, "packets:sent=4,received=4,lost=0", null);
                PingStats = FileObj.CheckStringForPattern(TranslatedCmdResult, "packets:sent=4,received=4", null);
                if (PingStats == 1)
                {
                    NewLogObj.WriteLogFile(LogFilePath, "System " + SystemIP + " is up", "info");
                    return(1);
                }
                Thread.Sleep(10000);
                Timer = Timer + 10000;
            }
            if (PingStats == -1 && Timer >= WaitTimeOutInMilliSecs)
            {
                NewLogObj.WriteLogFile(LogFilePath, "Timeout waiting for System " + SystemIP + " to be up", "info");
                return(-1);
            }
            return(-1);
        }