Ejemplo n.º 1
0
        private async void LoadLangs(TranslationClient translationClient, string[] selectedLangCodes)
        {
            // loads supported langs from google
            loadingGrid.Visibility = Visibility.Visible;
            langs = await translationClient.ListLanguagesAsync();

            loadingGrid.Visibility = Visibility.Hidden;

            // fill list boxes
            foreach (var lang in langs)
            {
                if (string.IsNullOrEmpty(lang.Code))
                {
                    continue;
                }
                string content = string.Format("{0} ({1})", new CultureInfo(lang.Code).DisplayName, lang.Code);

                var item1 = new ListBoxItem();
                item1.Content = content;
                item1.Tag     = lang.Code;
                langList1.Items.Add(item1);

                var item2 = new ListBoxItem();
                item2.Content = content;
                item2.Tag     = lang.Code;
                langList2.Items.Add(item2);
            }

            // select langs from settings
            SelectLangs(selectedLangCodes);
        }
Ejemplo n.º 2
0
        public void DetectLanguage_LargeText()
        {
            var client    = TranslationClient.Create();
            var detection = client.DetectLanguage(LargeText);

            Assert.Equal("en", detection.Language);
        }
Ejemplo n.º 3
0
        public TranslatorBot(string botId, LanguageType from, LanguageType to, string credentials)
        {
            this.from = from;
            this.to   = to;

            bot                        = new ICQBotClient(botId);
            bot.OnMessage             += BotOnMessageReceived;
            bot.OnMessageEdited       += BotOnMessageReceived;
            bot.OnReceiveError        += BotOnReceiveError;
            bot.OnReceiveGeneralError += OnReceiveGeneralError;

            if (string.IsNullOrWhiteSpace(credentials))
            {
                translationClient = TranslationClient.Create();
            }
            else
            {
                GoogleCredential credential = null;
                using (var credentialStream = new MemoryStream(Encoding.UTF8.GetBytes(credentials)))
                {
                    credential = GoogleCredential.FromStream(credentialStream);
                }

                translationClient = TranslationClient.Create(credential);
            }
        }
Ejemplo n.º 4
0
        private string Translete(string text, string language)
        {
            TranslationClient client = TranslationClient.Create(GoogleCredential.FromFile("ShopeTools-e74c814eef6c.json"));
            var response             = client.TranslateText(text, language);

            return(response.TranslatedText);
        }
Ejemplo n.º 5
0
        public SyntaxAnalyze(String text)
        {
            InitializeComponent();
            textToAnalyze  = text;
            translate      = TranslationClient.Create();
            syntaxAnalyze  = LanguageServiceClient.Create();
            language       = translate.DetectLanguage(text).Language;
            textLabel.Text = "    Original Text - Language " + language + "\n-" + text + "\n";
            if (language.Equals("en") == false)
            {
                textToAnalyze   = translate.TranslateText(text, LanguageCodes.English).TranslatedText;
                textLabel.Text += "    Translated text:\n-" + textToAnalyze;
            }
            document        = Document.FromPlainText(textToAnalyze);
            response        = syntaxAnalyze.AnalyzeSyntax(document);
            dependence.Text = "";
            lemma.Text      = "";
            string part = response.Tokens[0].PartOfSpeech.ToString();

            part              = part.Replace("\"", "");
            part              = part.Replace("{", "");
            part              = part.Replace("}", "");
            tokenText.Text    = response.Tokens[0].Text.Content;
            partOfSpeech.Text = "-> " + part + "\n";
            string dependences = response.Tokens[tokenIndex].DependencyEdge.ToString();

            dependences = dependences.Replace("\"", "").Replace("{", "").Replace("}", "");
            string[] split = dependences.Split(',');
            foreach (string s in split)
            {
                dependence.Text += "-> " + s + "\n";
            }
            lemma.Text = response.Tokens[tokenIndex].Lemma.ToString().Replace("\"", "").Replace("{", "").Replace("}", "");
        }
Ejemplo n.º 6
0
        private string GetTranslatedText(string text, string localeCode)
        {
            TranslationClient client = TranslationClient.CreateFromApiKey(apiKey: GOOGLE_API_KEY);
            TranslationResult result = client.TranslateText(text, localeCode.Substring(0, 2).ToLower());

            return(result.TranslatedText);
        }
Ejemplo n.º 7
0
        public TranslationClient CreateClient()
        {
            var apiKeyTranslate = _googleTranslateConfig.Value.ApiKey;
            TranslationClient clientTranslate = TranslationClient.CreateFromApiKey(apiKeyTranslate, model: TranslationModel.ServiceDefault);

            return(clientTranslate);
        }
Ejemplo n.º 8
0
        public string DetectLanguage() // https://cloud.google.com/translate/docs/basic/detecting-language
        {
            TranslationClient client = TranslationClient.Create();
            var detection            = client.DetectLanguage(text: text);

            return(detection.Language);
        }
Ejemplo n.º 9
0
 public Form1()
 {
     Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "../../key.json");
     client = TranslationClient.Create();
     InitializeComponent();
     fromText.Select();
 }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            GCloudAuth.AuthImplicit("translationcore");

            string            path   = @"C:\Users\Claudio\Documents\gcloud\translation.json";
            TranslationClient client = TranslationClient.Create();

            using (StreamReader r = new StreamReader(path)) {
                string json = r.ReadToEnd();

                RootObject jDyshon = JsonConvert.DeserializeObject <RootObject>(json);


                foreach (DyshonLanguage dyshon in jDyshon.TranslationTable)
                {
                    if (dyshon.IsValid)
                    {
                        TranslationResult result = client.TranslateText(dyshon.Original, LanguageCodes.Spanish);
                        Console.WriteLine($"Resultado de la traducción con id({dyshon.Id}): {result.TranslatedText}, original: {result.OriginalText}");

                        jDyshon.TranslationTable.FirstOrDefault(k => k.Id == dyshon.Id).Translation = result.TranslatedText;

                        string jsonresult = JsonConvert.SerializeObject(jDyshon);

                        System.IO.File.WriteAllText(@"C:\Users\Claudio\Documents\gcloud\translation_ES.json", jsonresult);
                    }
                }

                Console.WriteLine("Archivo traducido correctamente");
            }
        }
Ejemplo n.º 11
0
        private void translateButton_Click(object sender, EventArgs e)
        {
            int countFileHolder = 0;
            int doneCount       = 0;

            Console.OutputEncoding = System.Text.Encoding.Unicode;
            TranslationClient client = TranslationClient.Create();

            for (int rowIndex = 0; rowIndex < (lineCounter); rowIndex++)
            {
                var response = client.TranslateText(_result[rowIndex, 2], "en");
                _result[rowIndex, 3]      = response.TranslatedText;
                lineHolder.Text           = "Line #" + _result[countFileHolder, 0].ToString();
                lineName.Text             = _result[countFileHolder, 1];
                scriptHolder.Text         = _result[countFileHolder, 2];
                translatedTextHolder.Text = _result[countFileHolder, 3];
                System.Threading.Thread.Sleep(500);
                countFileHolder++;
                doneCount++;
            }
            if (countFileHolder > 0)
            {
                MessageBox.Show("Translations finished!!");
            }
            else
            {
                MessageBox.Show("No text was Translated");
            }
        }
Ejemplo n.º 12
0
        public TranslateService(IWebHostEnvironment env)
        {
            _env = env;
            var credentials = Google.Apis.Auth.OAuth2.GoogleCredential.FromFile($"{_env.ContentRootPath}/My First Project-3447edb7012f.json");

            _client = TranslationClient.Create(credentials);
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Upload(IFormFile file)
        {
            // string es_text = @"Historia social:\nFamilia: Su estado civil es divorciado.\nEducación / Trabajo: Paciente completado\neducación hasta la licenciatura, por ejemplo,\nBA, AB, BS, BBA. Su ocupacion es\nAsistente administrativo. Ella es\nActualmente no funciona. La ultima trabajaba\nen 2009. Ella no está en discapacidad. Ella\nNo está involucrado en acciones legales para el\ndolor. Ella tiene otra legal\nproblemas.\nExperiencias Adversas de la Infancia: Ella no\nexperimentar cualquier trastorno importante antes de\nla edad de 17. Ella experimentó algunos\ntrastorno grave después de la edad de 17 años.\nNo se sintió descuidado como un niño. Ella\nno experimentó dolor crónico como una\nniño. Ella no se siente amenazada en\nsu entorno actual. Ella nunca ha\nHa sido hospitalizado psiquiátricamente.\nSustancia: ella negó fumar. Ella negó\nbebiendo alcohol. Ella negó usar\ndrogas callejeras Ella apoyó a otros piensan\nElla tiene problemas con las drogas o el alcohol.\nElla respaldó haber recibido tratamiento.\npara el uso de sustancias.\n";
            var client      = ImageAnnotatorClient.Create();
            var text        = "";
            var foreignText = "";

            // TextAnnotation response = null;
            // Google.Cloud.Vision.V1.Image image = null;
            using (var reader = new StreamReader(file.OpenReadStream()))
            {
                var image    = Image.FromStream(reader.BaseStream);
                var response = client.DetectDocumentText(image);

                TranslationClient tc = TranslationClient.Create();
                var tcresp           = tc.TranslateText(response.Text, "en");
                var paragraphs       = tcresp.TranslatedText.Split("\n");

                foreach (var p in paragraphs)
                {
                    Console.WriteLine(p);
                }

                text        = tcresp.TranslatedText;
                foreignText = response.Text;
            }

            var delim = new Output()
            {
                Text        = text,
                ForeignText = foreignText
            };

            return(View("Output", delim));
        }
Ejemplo n.º 14
0
        public static async Task <string> TranslateTextAsync(string text, string lang)
        {
            TranslationClient gClient = TranslationClient.CreateFromApiKey((string)Application.Current.Resources["GoogTranslationKey"]);
            TranslationResult result  = await gClient.TranslateTextAsync(text, lang);

            return(result.TranslatedText);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Translate text to the specified language using the Google Translate API
        /// </summary>
        /// <param name="pText">Text to translate</param>
        /// <param name="pLanguage">Language</param>
        /// <returns></returns>
        public string Translate(string pText, string pLanguage)
        {
            TranslationClient client = TranslationClient.Create();
            var response             = client.TranslateText(pText, pLanguage);

            return(response.TranslatedText);
        }
Ejemplo n.º 16
0
        public async Task <string> TranslateAsync(string text)
        {
            TranslationClient client = TranslationClient.Create(_googleCredential);
            var response             = await client.TranslateTextAsync(text, "ru", "en");

            return(response.TranslatedText);
        }
        public IActionResult Post([FromBody] TransImageClass transImage)
        {
            String to_translate = "";

            // Cloud Vision API
            var image    = Image.FromUri(transImage.uri);
            var client   = ImageAnnotatorClient.Create();
            var response = client.DetectText(image);

            foreach (var annotation in response)
            {
                if (annotation.Description != null)
                {
                    to_translate += annotation.Description + " ";
                }
            }
            Console.WriteLine("\nText Detection Image \n --------------\n" + to_translate);

            // Translation API
            TranslationClient translation_client = TranslationClient.Create();
            var trans_response = translation_client.TranslateText(
                text: to_translate,
                targetLanguage: transImage.to_translate,
                sourceLanguage: transImage.from_translate);

            String translated_text = trans_response.TranslatedText;

            Console.WriteLine("\nTranslation Output\n --------------\n" + translated_text);
            return(StatusCode(200, translated_text));
        }
Ejemplo n.º 18
0
        public IActionResult AnalyzeProject([FromBody] string description)
        {
            var credential           = GoogleCredential.FromFile("pms-portal-trans.json");
            TranslationClient client = TranslationClient.Create(credential);

            var category = GetCategoriesFromDescription(client.TranslateText(description, "en").TranslatedText);

            // var projects = context.Projects
            //     .Include (p => p.Groups)
            //     .ThenInclude (g => g.Board)
            //     .Where (p => (p.Groups != null || p.Groups.Count > 0) && p.Groups.Any (g => g.Board.ResultScore == null));

            var projects = context.Projects.ToList();

            var topSimilarity = new List <String> ();
            var similarity    = new Dictionary <Project, double> ();

            foreach (var project in projects)
            {
                var response = client.TranslateText(project.Description, "en");
                if (Similarity(category, GetCategoriesFromDescription(response.TranslatedText)) >= 0.5)
                {
                    similarity.Add(project, Math.Round(Similarity(category, GetCategoriesFromDescription(response.TranslatedText)), 3));
                }
            }

            var top3Project = (from entry in similarity orderby entry.Value descending select entry).ToDictionary(
                pair => pair.Key,
                pair => pair.Value
                ).Take(3);

            return(Ok(top3Project));
        }
Ejemplo n.º 19
0
        public SentimentalAnalyze(String text)
        {
            InitializeComponent();
            String                   textToAnalyze      = text;
            TranslationClient        translate          = TranslationClient.Create();
            LanguageServiceClient    sentimentalAnalyze = LanguageServiceClient.Create();
            AnalyzeSentimentResponse response;
            Document                 document;
            string                   language = translate.DetectLanguage(text).Language;

            textLabel.Text = "    Original Text - Language " + language + "\n-" + text + "\n";
            if (language.Equals("en") == false)
            {
                textToAnalyze   = translate.TranslateText(text, LanguageCodes.English).TranslatedText;
                textLabel.Text += "    Translated text:\n-" + textToAnalyze;
            }
            document = Document.FromPlainText(textToAnalyze);
            response = sentimentalAnalyze.AnalyzeSentiment(document);
            float score     = response.DocumentSentiment.Score;
            float magnitude = response.DocumentSentiment.Magnitude;

            scoreLabel.Text     += score.ToString();
            scoreBar.Width       = Convert.ToInt16((score * 100 + 100) * 2.2);
            magnitudeLabel.Text += magnitude.ToString();
            magnitudeBar.Width   = Convert.ToInt16((magnitude * 100 + 100) * 2.2);
            panel1.AutoScroll    = true;
        }
Ejemplo n.º 20
0
        public async Task Translate(params string[] input)
        {
            TranslationClient client = TranslationClient.Create(Google.Apis.Auth.OAuth2.GoogleCredential.FromFile("service-account-file.json"));

            bool translateTo = false;

            foreach (var l in client.ListLanguages(LanguageCodes.English))
            {
                if (l.Code == input[0] || l.Name.ToLower() == input[0].ToLower())
                {
                    translateTo = true;
                    input[0]    = l.Code;
                }
            }

            TranslationResult result;

            if (translateTo)
            {
                var language = input[0];
                input[0] = "";
                result   = client.TranslateText(string.Join(" ", input), language);
            }
            else
            {
                result = client.TranslateText(string.Join(" ", input), LanguageCodes.English);
            }

            await ReplyAsync(result.TranslatedText);
        }
Ejemplo n.º 21
0
        // Use this for initialization
        void Awake()
        {
            this.speechProcess = new System.Diagnostics.Process();

            this.speechProcess.StartInfo.FileName = Application.dataPath + this.path;

            //this.process.EnableRaisingEvents = true;
            //this.process.Exited += new System.EventHandler(ProcessExit);

            //this.process.StartInfo.RedirectStandardOutput = true;
            //this.process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler);

            //this.process.StartInfo.RedirectStandardError = true;
            //this.process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorOutputHanlder);

            this.speechProcess.StartInfo.CreateNoWindow = true;
            this.speechProcess.StartInfo.WindowStyle    = System.Diagnostics.ProcessWindowStyle.Hidden;

            SIGVerseLogger.Info("Text-To-Speech: " + this.speechProcess.StartInfo.FileName);

            this.ResetNotificationDestinations();

            this.isSpeaking = false;

            try
            {
                this.translationClient = TranslationClient.Create();
            }
            catch (Exception)
            {
                this.translationClient = null;
            }
        }
        private string TranslateTask(string text)
        {
            TranslationClient client = TranslationClient.Create();
            var response             = client.TranslateText(text, toLanguage, fromLanguage);

            return(response.TranslatedText);
        }
Ejemplo n.º 23
0
        private string ConvertToTargetLanguage(string text, string toLang, string fromLang, bool isHtml, bool isMultipleTranslation)
        {
            Database          dbweb             = Database.GetDatabase(CTConfiguration.SitecoreMasterDatabase);
            Item              configurationitem = dbweb.GetItem(new ID(CTConfiguration.ItemId));
            string            Key = configurationitem.Fields[CTConfiguration.AccessKey] != null ? configurationitem.Fields[CTConfiguration.AccessKey].Value : string.Empty;
            TranslationClient translationClient = TranslationClient.CreateFromApiKey(Key);

            TranslationResult result = null;
            IList <Google.Cloud.Translation.V2.Language> response = translationClient.ListLanguages();
            bool IsValidLangCode = response.Any(x => x.Code == toLang);

            if (!IsValidLangCode && !isMultipleTranslation)
            {
                return("translation failure");
            }
            else
            {
                if (IsValidLangCode)
                {
                    if (isHtml)
                    {
                        result = translationClient.TranslateHtml(text, toLang, fromLang);
                    }
                    else
                    {
                        result = translationClient.TranslateText(text, toLang, fromLang);
                    }
                }
                else
                {
                    result = translationClient.TranslateText(text, "en");
                }
                return(result.TranslatedText);
            }
        }
Ejemplo n.º 24
0
        private Program()
        {
            P = this;
            perspectiveApi = File.ReadAllText("Keys/perspectiveAPI.txt");
            client         = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Verbose,
            });
            client.Log   += Utils.Log;
            commands.Log += Utils.LogError;
            string[] request = File.ReadAllLines("Keys/url.txt");
            requestUrlText  = request[0];
            requestUrlImage = request[1];
            requestToken    = request[2];
            rand            = new Random();
            db = new Db();

            string[] websiteInfos = File.ReadAllLines("Keys/website.txt");
            websiteName  = websiteInfos[0];
            websiteToken = websiteInfos[1];

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Keys/imageAPI.json");
            imageClient = ImageAnnotatorClient.Create();

            translationClient = TranslationClient.Create();
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            var client = TranslationClient.Create();
            var result = client.TranslateText("Hello world.", "ru");

            JsonDumper.Dump(result);
        }
Ejemplo n.º 26
0
        // [END translate_text_with_model]
        public static string Translate(string Text, string destinationLanguageCode, string sourceLanguageCode, string JsonCredentialsPath)
        {
            GoogleCredential  credentials = GoogleCredential.FromJson(File.ReadAllText(JsonCredentialsPath));
            TranslationClient client      = TranslationClient.Create(credentials);

            return(client.TranslateText(Text, destinationLanguageCode, sourceLanguageCode).TranslatedText);
        }
Ejemplo n.º 27
0
        public void ApplicationName()
        {
            TranslationClientImpl.ApplicationName = "TestApplication";
            var client = TranslationClient.Create();

            Assert.Equal("TestApplication", client.Service.ApplicationName);
        }
Ejemplo n.º 28
0
        private void btnDetectSrc_Click(object sender, EventArgs e)
        {
            //var client = new RestClient()
            //{
            //    BaseUrl = new Uri(string.Format(AppCache.UrlDetect, AppCache.API, richTextSrc.Text))
            //};
            //var request = new RestRequest()
            //{
            //    Method = Method.GET
            //};
            //var response = responseService(AppCache.UrlDetect);
            //var diction = JsonConvert.DeserializeObject<IDictionary>(response.Content);
            //try
            //{
            //    var statusCode = diction["code"].ToString();

            //    if (statusCode.Equals("200"))
            //    {
            //        txtSrcLang.Text = diction["lang"].ToString();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message.ToString());
            //}// Yandex API

            if (richTextSrc.Text == "")
            {
                MessageBox.Show("Empty Message Please Enter Text", "Empty Text", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                TranslationClient client = TranslationClient.Create();
                var detection            = client.DetectLanguage(richTextSrc.Text);
                switch (detection.Language)
                {
                case "en":
                    txtSrcLang.Text = "English Language";
                    break;

                case "ig":
                    txtSrcLang.Text = "Igbo Language";
                    break;

                case "ha":
                    txtSrcLang.Text = "Hausa Language";
                    break;

                case "fr":
                    txtSrcLang.Text = "French Language";
                    break;

                default:
                    txtSrcLang.Text = "Language not listed";
                    MessageBox.Show("Language not listed bu you can translate anyway.", "Not Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                }
                txtSrcLang.Visible = true;
            }
        }
Ejemplo n.º 29
0
        public void TestTranslateText()
        {
            var pages = System.IO.File.ReadAllLines("de_emendatione_temporum_extracted.txt");

            var translatedText = new List <string>();

            TranslationClient client = TranslationClient.Create();
            int pageNumber           = 0;
            int startPage            = 165;

            for (int i = startPage; i < pages.Length; i++)
            {
                var page = pages[i];
                try
                {
                    if (page.Length > 0)
                    {
                        //var response = client.TranslateText(page, "en");
                        //translatedText.Add(response.TranslatedText);
                        //System.IO.File.WriteAllText("de_emendatione_temporum_translated_" + pageNumber, response.TranslatedText);
                        //System.Threading.Thread.Sleep(3000);
                    }
                }
                catch (Exception)
                {
                }
            }

            System.IO.File.WriteAllLines("de_emendatione_temporum_translated_165_to_500.txt", translatedText.ToArray());
        }
Ejemplo n.º 30
0
        public TranslateService.TranslateResponse.TranslationResult TranslateText(string source, string sourceLanguage, string targetLanguage)
        {
            if (TranslationClient == null)
            {
                return(null);
            }

            if (!IsValidLanguageCode(targetLanguage))
            {
                throw new Exception("Invalid Target Language Code.");
            }
            else if (!IsValidLanguageCode(sourceLanguage))
            {
                throw new Exception("Invalid Source Language Code.");
            }

            var response = TranslationClient.TranslateText(source, targetLanguage, sourceLanguage);
            var result   = new TranslateService.TranslateResponse.TranslationResult
            {
                SourceLanguage      = response.DetectedSourceLanguage,
                SourceText          = source,
                DestinationLanguage = response.TargetLanguage,
                TranslatedText      = TranslateService.FixTranslatedString(response.TranslatedText)
            };

            return(result);
        }