Exemple #1
0
        private void BgWorkerClean_DoWork(object sender, DoWorkEventArgs e)
        {
            DictionaryData BGWorkerData = (DictionaryData)e.Argument;

            TranslationClient client = TranslationClient.Create();


            //selects the text encoding based on user selection
            Encoding InputSelectedEncoding  = null;
            Encoding OutputSelectedEncoding = null;

            this.Invoke((MethodInvoker) delegate()
            {
                InputSelectedEncoding  = Encoding.GetEncoding(InputEncodingDropdown.SelectedItem.ToString());
                OutputSelectedEncoding = Encoding.GetEncoding(OutputEncodingDropdown.SelectedItem.ToString());
            });



            //get the list of files
            var SearchDepth = SearchOption.TopDirectoryOnly;

            if (ScanSubfolderCheckbox.Checked)
            {
                SearchDepth = SearchOption.AllDirectories;
            }
            var files = Directory.EnumerateFiles(BGWorkerData.TextFileFolder, BGWorkerData.FileExtension, SearchDepth);



            try {
                foreach (string fileName in files)
                {
                    if (e.Cancel)
                    {
                        break;
                    }



                    //set up our variables to report
                    string Filename_Clean = Path.GetFileName(fileName);

                    string SubDirStructure = Path.GetDirectoryName(fileName).Replace(BGWorkerData.TextFileFolder, "").TrimStart('\\');


                    //creates subdirs if they don't exist
                    string Output_Location = BGWorkerData.OutputFileLocation + '\\' + SubDirStructure;

                    if (!Directory.Exists(Output_Location))
                    {
                        Directory.CreateDirectory(Output_Location);
                    }

                    Output_Location = Path.Combine(Output_Location, Path.GetFileName(fileName));

                    //report what we're working on
                    FilenameLabel.Invoke((MethodInvoker) delegate
                    {
                        FilenameLabel.Text = "Processing: " + Filename_Clean;
                        FilenameLabel.Invalidate();
                        FilenameLabel.Update();
                        FilenameLabel.Refresh();
                        Application.DoEvents();
                    });



                    // __        __    _ _          ___        _               _
                    // \ \      / / __(_) |_ ___   / _ \ _   _| |_ _ __  _   _| |_
                    //  \ \ /\ / / '__| | __/ _ \ | | | | | | | __| '_ \| | | | __|
                    //   \ V  V /| |  | | ||  __/ | |_| | |_| | |_| |_) | |_| | |_
                    //    \_/\_/ |_|  |_|\__\___|  \___/ \__,_|\__| .__/ \__,_|\__|
                    //                                            |_|


                    using (StreamReader inputfile = new StreamReader(fileName, InputSelectedEncoding))
                    {
                        if (e.Cancel)
                        {
                            break;
                        }

                        string readText = inputfile.ReadToEnd();

                        string[] readText_Chunked = new string[0];

                        if (!string.IsNullOrWhiteSpace(readText))
                        {
                            readText_Chunked = SplitStringByLength(readText, BGWorkerData.MaxCharsPerRequest);
                        }

                        StringBuilder TranslatedText_Output = new StringBuilder();

                        for (int i = 0; i < readText_Chunked.Length; i++)
                        {
                            if (e.Cancel)
                            {
                                break;
                            }

                            try
                            {
                                if (e.Cancel)
                                {
                                    break;
                                }

                                StatusLabel.Invoke((MethodInvoker) delegate
                                {
                                    StatusLabel.Text = "Status: Sending request " + (i + 1).ToString() + "/" + readText_Chunked.Length.ToString() + " to API...";
                                    StatusLabel.Invalidate();
                                    StatusLabel.Update();
                                    StatusLabel.Refresh();
                                    Application.DoEvents();
                                });

                                var response = client.TranslateText(readText_Chunked[i],
                                                                    sourceLanguage: BGWorkerData.InputLang,
                                                                    targetLanguage: BGWorkerData.OutputLang);

                                TranslatedText_Output.Append(response.TranslatedText + " ");
                            }
                            catch (Google.GoogleApiException ex)
                            {
                                if (e.Cancel)
                                {
                                    break;
                                }

                                if (ex.Error.Code == 403)
                                {
                                    if (ex.Error.Message.Contains("Daily Limit Exceeded"))
                                    {
                                        //report what we're working on
                                        StatusLabel.Invoke((MethodInvoker) delegate
                                        {
                                            StatusLabel.Text = "Status: " + ex.Error.Message;
                                            StatusLabel.Invalidate();
                                            StatusLabel.Update();
                                            StatusLabel.Refresh();
                                            Application.DoEvents();
                                        });

                                        MessageBox.Show("The Google Translate API reports that you have exceeded your daily use limit. You will need to visit the \"Quotas\" section of the Google Cloud Dashboard to increase your limits or, alternatively, wait until midnight for your quota to reset.", "Daily Limit Exceeded", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                        e.Cancel = true;
                                        break;
                                    }

                                    else
                                    {
                                        if (e.Cancel)
                                        {
                                            break;
                                        }

                                        int retry_counter = 0;
                                        while (retry_counter < BGWorkerData.MaxRetries)
                                        {
                                            retry_counter++;

                                            int      TimerCounter = 0;
                                            DateTime d            = DateTime.Now;

                                            while (TimerCounter < BGWorkerData.DurationLength + 2)
                                            {
                                                TimeSpan ts = DateTime.Now.Subtract(d);
                                                if (ts.Seconds >= 1)
                                                {
                                                    //do some work
                                                    TimerCounter += ts.Seconds;
                                                    d             = DateTime.Now;

                                                    //report what we're working on
                                                    StatusLabel.Invoke((MethodInvoker) delegate
                                                    {
                                                        StatusLabel.Text = "Status: Rate limit reached. Sleeping for " + (BGWorkerData.DurationLength - TimerCounter + 1).ToString() + "...";
                                                        StatusLabel.Invalidate();
                                                        StatusLabel.Update();
                                                        StatusLabel.Refresh();
                                                        Application.DoEvents();
                                                    });
                                                }
                                            }

                                            try
                                            {
                                                //report what we're working on
                                                StatusLabel.Invoke((MethodInvoker) delegate
                                                {
                                                    StatusLabel.Text = "Status: Sending request " + (i + 1).ToString() + "/" + readText_Chunked.Length.ToString() + " to API... Retry #" + retry_counter.ToString();
                                                    StatusLabel.Invalidate();
                                                    StatusLabel.Update();
                                                    StatusLabel.Refresh();
                                                    Application.DoEvents();
                                                });

                                                var response = client.TranslateText(readText_Chunked[i],
                                                                                    sourceLanguage: BGWorkerData.InputLang,
                                                                                    targetLanguage: BGWorkerData.OutputLang);

                                                TranslatedText_Output.Append(response.TranslatedText + " ");

                                                retry_counter = BGWorkerData.MaxRetries;
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                }

                                else if (ex.Error.Code == 429 || (ex.Error.Code >= 500 && ex.Error.Code < 600))
                                {
                                    int retry_counter = 0;
                                    while (retry_counter < BGWorkerData.MaxRetries)
                                    {
                                        retry_counter++;

                                        int      TimerCounter = 0;
                                        DateTime d            = DateTime.Now;

                                        while (TimerCounter < System.Math.Pow(retry_counter, 2))
                                        {
                                            TimeSpan ts = DateTime.Now.Subtract(d);
                                            if (ts.Seconds >= 1)
                                            {
                                                //do some work
                                                TimerCounter += ts.Seconds;
                                                d             = DateTime.Now;

                                                //report what we're working on
                                                StatusLabel.Invoke((MethodInvoker) delegate
                                                {
                                                    StatusLabel.Text = "Status: Error " + ex.Error.Code.ToString() + "; " + ex.Error.Message + " -- Retrying in " + (BGWorkerData.DurationLength - TimerCounter + 1).ToString() + "...";
                                                    StatusLabel.Invalidate();
                                                    StatusLabel.Update();
                                                    StatusLabel.Refresh();
                                                    Application.DoEvents();
                                                });
                                            }
                                        }

                                        try
                                        {
                                            //report what we're working on
                                            StatusLabel.Invoke((MethodInvoker) delegate
                                            {
                                                StatusLabel.Text = "Status: Sending request " + (i + 1).ToString() + "/" + readText_Chunked.Length.ToString() + " to API... Retry #" + retry_counter.ToString();
                                                StatusLabel.Invalidate();
                                                StatusLabel.Update();
                                                StatusLabel.Refresh();
                                                Application.DoEvents();
                                            });

                                            var response = client.TranslateText(readText_Chunked[i],
                                                                                sourceLanguage: BGWorkerData.InputLang,
                                                                                targetLanguage: BGWorkerData.OutputLang);

                                            TranslatedText_Output.Append(response.TranslatedText + " ");

                                            retry_counter = BGWorkerData.MaxRetries;
                                        }
                                        catch
                                        {
                                        }
                                    }
                                }

                                else
                                {
                                    //report what we're working on
                                    StatusLabel.Invoke((MethodInvoker) delegate
                                    {
                                        StatusLabel.Text = "Status: " + ex.Error.Message;
                                        StatusLabel.Invalidate();
                                        StatusLabel.Update();
                                        StatusLabel.Refresh();
                                        Application.DoEvents();
                                    });
                                }
                            }
                        }



                        //open up the output file
                        using (StreamWriter outputFile = new StreamWriter(new FileStream(Output_Location, FileMode.Create), OutputSelectedEncoding))
                        {
                            outputFile.Write(TranslatedText_Output.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Transmogrifier encountered an issue somewhere while trying to translate your texts. The most common cause of this is trying to open your output file(s) while the program is still running. Did any of your input files move, or is your output file being opened/modified by another application? " +
                                "After clicking the \"OK\" Button, you will receive an error code. Please write down this error code (or take a screenshot) and contact the software's author ([email protected]) for additional help.", "Error while translating", MessageBoxButtons.OK, MessageBoxIcon.Error);

                MessageBox.Show(ex.ToString(), "Error Code", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #2
0
        private void BGWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BgWorkerInformation BgData = (BgWorkerInformation)e.Argument;

            string[] VarLines = BgData.VarText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);


            int           NumVars         = 0;
            List <string> VarPlaceholders = new List <string>();

            //get all of the split out info into a list
            List <Array> VarList = new List <Array>();

            for (int i = 0; i < VarLines.Length; i++)
            {
                string[] VarList_Split = (VarLines[i].Trim().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries));
                if (VarList_Split.Length > 1)
                {
                    NumVars++;
                    VarList.Add(VarList_Split.ToList().GetRange(1, VarList_Split.Length - 1).ToArray());
                    VarPlaceholders.Add(VarList_Split[0]);
                }
            }


            try {
                StatusLabel.Invoke((MethodInvoker) delegate
                {
                    StatusLabel.Text = "Recursing variable combinations... This might take a while...";
                });

                //Set up our code


                List <string> RecursedVars = Recursion(0, VarList).Distinct().ToList();


                using (StreamWriter outputFile = new StreamWriter(new FileStream(BgData.FileOutputLocation, FileMode.Create, FileAccess.Write), Encoding.UTF8))
                {
                    outputFile.WriteLine("Input Variable Data:");
                    outputFile.WriteLine(BgData.VarText + "\r\n\r\n");
                    outputFile.WriteLine("Input Code Data:");
                    outputFile.WriteLine(BgData.CodeText + "\r\n\r\n");
                    outputFile.WriteLine("Code Output:\r\n");

                    int LineCount = RecursedVars.Count;
                    LineCountString = LineCount.ToString();

                    for (int i = 0; i < LineCount; i++)
                    {
                        StringBuilder OutputCode = new StringBuilder();
                        OutputCode.Append(BgData.CodeText);

                        StatusLabel.Invoke((MethodInvoker) delegate {
                            StatusLabel.Text = "Writing line " + (i + 1).ToString() + " of " + LineCountString;
                            StatusLabel.Invalidate();
                            StatusLabel.Update();
                            StatusLabel.Refresh();
                            Application.DoEvents();
                        });

                        string[] Var_Replacements = RecursedVars[i].Split(' ');
                        for (int j = 0; j < NumVars; j++)
                        {
                            OutputCode.Replace(VarPlaceholders[j], Var_Replacements[j]);
                        }

                        outputFile.WriteLine(OutputCode.ToString());
                    }
                }


                e.Result = BgData.FileOutputLocation;
            }
            catch
            {
                MessageBox.Show("An error occurred while building your code.", "Ruh-roh!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Result = null;
            }
        }
Exemple #3
0
 private void StatusMessage(string text)
 {
     StatusLabel.Text = text;
     StatusLabel.Invalidate();
 }