Exemple #1
0
        public async Task DialogBegin(DialogContext dc, IDictionary <string, object> dialogArgs = null)
        {
            var message = dc.Context.Activity.Text;

            if (!string.IsNullOrEmpty(message))
            {
                ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
                {
                    Endpoint = "https://westeurope.api.cognitive.microsoft.com"
                };


                var result = client.DetectLanguageAsync(new BatchInput(
                                                            new List <Input>()
                {
                    new Input("1", message)
                })).Result;

                foreach (var document in result.Documents)
                {
                    await dc.Context.SendActivity(document.DetectedLanguages[0].Name);
                }

                await dc.End();
            }
            else
            {
                await dc.Context.SendActivity("Введите текст для распознавания языка");
            }
        }
Exemple #2
0
        public static async Task RunAsync(string endpoint, string key)
        {
            var credentials = new ApiKeyServiceClientCredentials(key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = endpoint
            };

            // The documents to be submitted for language detection. The ID can be any value.
            var inputDocuments = new LanguageBatchInput(
                new List <LanguageInput>
            {
                new LanguageInput(id: "1", text: "This is a document written in English."),
                new LanguageInput(id: "2", text: "Este es un document escrito en Español."),
                new LanguageInput(id: "3", text: "这是一个用中文写的文件")
            });

            var langResults = await client.DetectLanguageAsync(false, inputDocuments);

            // Printing detected languages
            foreach (var document in langResults.Documents)
            {
                Console.WriteLine($"Document ID: {document.Id} , Language: {document.DetectedLanguages[0].Name}");
            }
        }
        public async Task DetectLanguageAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            // Instantiate a client that will be used to call the service.
            var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:DetectLanguageAsync
            string document = @"Este documento está escrito en un idioma diferente al Inglés. Tiene como objetivo demostrar
                                cómo invocar el método de Detección de idioma del servicio de Text Analytics en Microsoft Azure.
                                También muestra cómo acceder a la información retornada por el servicio. Esta capacidad es útil
                                para los sistemas de contenido que recopilan texto arbitrario, donde el idioma es desconocido.
                                La característica Detección de idioma puede detectar una amplia gama de idiomas, variantes,
                                dialectos y algunos idiomas regionales o culturales.";

            try
            {
                Response <DetectedLanguage> response = await client.DetectLanguageAsync(document);

                DetectedLanguage language = response.Value;
                Console.WriteLine($"Detected language {language.Name} with confidence score {language.ConfidenceScore}.");
            }
            catch (RequestFailedException exception)
            {
                Console.WriteLine($"Error Code: {exception.ErrorCode}");
                Console.WriteLine($"Message: {exception.Message}");
            }
            #endregion
        }
Exemple #4
0
        public async Task <TextAnalyticsAnalyzeResponse> Analyze(string text, string languageHint)
        {
            var credentials = new ApiKeyServiceClientCredentials(_subscriptionKey);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = _endpoint
            };

            var detectedLanguageResult = await client.DetectLanguageAsync(text, languageHint, true);

            if (string.IsNullOrWhiteSpace(languageHint))
            {
                languageHint = detectedLanguageResult.DetectedLanguages.FirstOrDefault()?.Iso6391Name ?? "";
            }

            var entitiesResult   = client.EntitiesAsync(text, languageHint, true);
            var keyPhrasesResult = client.KeyPhrasesAsync(text, languageHint, true);
            var sentimentResult  = client.SentimentAsync(text, languageHint, true);

            await Task.WhenAll(entitiesResult, keyPhrasesResult, sentimentResult);

            return(new TextAnalyticsAnalyzeResponse
            {
                DetectedLanguage = detectedLanguageResult,
                KeyPhrases = keyPhrasesResult.Result,
                Sentiment = sentimentResult.Result,

                Entities = entitiesResult.Result
            });
        }
Exemple #5
0
        private static async Task <string> DetectLanguage(string text)
        {
            try
            {
                ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
                {
                    Endpoint = "https://westeurope.api.cognitive.microsoft.com"
                }; //Replace 'westus' with the correct region for your Text Analytics subscription

                // Extracting language
                Console.WriteLine("===== LANGUAGE EXTRACTION ======");

                var langResults = await client.DetectLanguageAsync(
                    false,
                    new LanguageBatchInput(
                        new List <LanguageInput>
                {
                    new LanguageInput(id: "1", text: text),
                }));

                return(langResults.Documents.First().DetectedLanguages[0].Iso6391Name);
            }
            catch (Exception ex)
            {
                return("en");

                throw ex;
            }
        }
Exemple #6
0
        private static async Task <string> GetSentimentWithCognitiveService(string text, string apiKey)
        {
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(apiKey))
            {
                Endpoint = "https://westus.api.cognitive.microsoft.com"
            }; //Replace 'westus' with the correct region for your Text Analytics subscription

            Console.OutputEncoding = System.Text.Encoding.UTF8;

            // Extract the language
            var result = await client.DetectLanguageAsync(false, new LanguageBatchInput(new List <LanguageInput>()
            {
                new LanguageInput(id: "1", text: text)
            }));

            var language = result.Documents?[0].DetectedLanguages?[0].Iso6391Name;

            // Get the sentiment
            var sentimentResult = await client.SentimentAsync(false,
                                                              new MultiLanguageBatchInput(
                                                                  new List <MultiLanguageInput>()
            {
                new MultiLanguageInput(language, "0", text),
            }));

            return(sentimentResult.Documents?[0].Score?.ToString("#.#"));
        }
        public static async Task <string> DetectLanguageAsync(TextAnalyticsClient client, string content)
        {
            DetectedLanguage detectedLanguage = await client.DetectLanguageAsync(content);

            Console.WriteLine("Language:");
            Console.WriteLine($"\t{detectedLanguage.Name},\tISO-6391: {detectedLanguage.Iso6391Name}\n");
            return(detectedLanguage.Iso6391Name);
        }
        public async Task DetectLanguageWithNoneCountryHintTest()
        {
            TextAnalyticsClient client = GetClient();
            string input = "Este documento está en español";

            DetectedLanguage language = await client.DetectLanguageAsync(input, DetectLanguageInput.None);

            Assert.AreEqual("Spanish", language.Name);
        }
Exemple #9
0
        public async Task DetectLanguageWithNoneCountryHintTest()
        {
            TextAnalyticsClient client = GetClient();
            string document            = SingleSpanish;

            DetectedLanguage language = await client.DetectLanguageAsync(document, DetectLanguageInput.None);

            ValidateInDocumenResult(language);
        }
Exemple #10
0
        public async Task DetectLanguageWithAADTest()
        {
            TextAnalyticsClient client = GetClient(useTokenCredential: true);
            string document            = SingleEnglish;

            DetectedLanguage language = await client.DetectLanguageAsync(document);

            ValidateInDocumenResult(language);
        }
Exemple #11
0
        public async Task DetectLanguageTest()
        {
            TextAnalyticsClient client = GetClient();
            string document            = SingleEnglish;

            DetectedLanguage language = await client.DetectLanguageAsync(document);

            ValidateInDocumenResult(language);
        }
Exemple #12
0
        public async Task DetectLanguageWithCountryHintTest()
        {
            TextAnalyticsClient client = GetClient();
            string input = "Este documento está en español";

            DetectLanguageResult result = await client.DetectLanguageAsync(input, "CO");

            DetectedLanguage language = result.PrimaryLanguage;

            Assert.AreEqual("Spanish", language.Name);
        }
Exemple #13
0
        public async Task DetectLanguageWithAADTest()
        {
            TextAnalyticsClient client = GetClient(useTokenCredential: true);
            string document            = singleEnglish;

            DetectedLanguage language = await client.DetectLanguageAsync(document);

            Assert.IsNotNull(language.Name);
            Assert.IsNotNull(language.Iso6391Name);
            Assert.Greater(language.ConfidenceScore, 0.0);
        }
Exemple #14
0
        public async Task DetectLanguageWithNoneCountryHintTest()
        {
            TextAnalyticsClient client = GetClient();
            string document            = "Este documento está en español";

            DetectedLanguage language = await client.DetectLanguageAsync(document, DetectLanguageInput.None);

            Assert.IsNotNull(language.Name);
            Assert.IsNotNull(language.Iso6391Name);
            Assert.Greater(language.ConfidenceScore, 0.0);
        }
Exemple #15
0
        public async Task DetectLanguageTest()
        {
            TextAnalyticsClient client = GetClient();
            string document            = "This is written in English.";

            DetectedLanguage language = await client.DetectLanguageAsync(document);

            Assert.IsNotNull(language.Name);
            Assert.IsNotNull(language.Iso6391Name);
            Assert.Greater(language.ConfidenceScore, 0.0);
        }
        public async Task DetectLanguageTest()
        {
            TextAnalyticsClient client = GetClient();
            string input = "This is written in English.";

            DetectedLanguage language = await client.DetectLanguageAsync(input);

            Assert.AreEqual("English", language.Name);
            Assert.AreEqual("en", language.Iso6391Name);
            Assert.AreEqual(1.0, language.Score);
        }
Exemple #17
0
        public async Task DetectLanguageWithCountryHintTest()
        {
            TextAnalyticsClient client = GetClient();
            string document            = singleSpanish;

            DetectedLanguage language = await client.DetectLanguageAsync(document, "CO");

            Assert.IsNotNull(language.Name);
            Assert.IsNotNull(language.Iso6391Name);
            Assert.Greater(language.ConfidenceScore, 0.0);
        }
        private static async Task <bool> IsSpanishAsync(string document, TextAnalyticsClient client, CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                DetectedLanguage language = await client.DetectLanguageAsync(document);

                return(language.Iso6391Name == "es");
            }

            cancellationToken.ThrowIfCancellationRequested();
            return(false);
        }
Exemple #19
0
        private static async Task DetectFaces(TextAnalyticsClient client, string phrase)
        {
            var inputs = new List <Input>()
            {
                new Input("id", phrase)
            };
            var result = await client.DetectLanguageAsync(new BatchInput(inputs));

            string name = result.Documents[0].DetectedLanguages[0].Name;

            Console.WriteLine($"Detected Language: {name}");
        }
        public async Task RotateApiKey()
        {
            // Instantiate a client that will be used to call the service.
            string apiKey              = Recording.GetVariableFromEnvironment(ApiKeyEnvironmentVariable);
            var    credential          = new TextAnalyticsApiKeyCredential(apiKey);
            TextAnalyticsClient client = GetClient(credential);

            string input = "Este documento está en español.";

            // Verify the credential works (i.e., doesn't throw)
            await client.DetectLanguageAsync(input);

            // Rotate the API key to an invalid value and make sure it fails
            credential.UpdateCredential("Invalid");
            Assert.ThrowsAsync <RequestFailedException>(
                async() => await client.DetectLanguageAsync(input));

            // Re-rotate the API key and make sure it succeeds again
            credential.UpdateCredential(apiKey);
            await client.DetectLanguageAsync(input);
        }
        public async Task DetectLanguageWithNoneDefaultCountryHintTest()
        {
            var options = new TextAnalyticsClientOptions()
            {
                DefaultCountryHint = DetectLanguageInput.None
            };

            TextAnalyticsClient client = GetClient(options: options);
            string input = "Este documento está en español";

            DetectedLanguage language = await client.DetectLanguageAsync(input, DetectLanguageInput.None);

            Assert.AreEqual("Spanish", language.Name);
        }
        public async Task RotateSubscriptionKey()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            // Instantiate a client that will be used to call the service.
            var credential = new TextAnalyticsSubscriptionKeyCredential(subscriptionKey);
            var client     = new TextAnalyticsClient(new Uri(endpoint), credential);

            string input = "Este documento está en español.";

            // Verify the credential works (i.e., doesn't throw)
            await client.DetectLanguageAsync(input);

            // Rotate the subscription key to an invalid value and make sure it fails
            credential.UpdateCredential("Invalid");
            Assert.ThrowsAsync <RequestFailedException>(
                async() => await client.DetectLanguageAsync(input));

            // Re-rotate the subscription key and make sure it succeeds again
            credential.UpdateCredential(subscriptionKey);
            await client.DetectLanguageAsync(input);
        }
Exemple #23
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] SantaLetter theLetter,
            ILogger log)
        {
            SantaResults result;

            try
            {
                // Get the languages
                var detectedLanguages = await textClient.DetectLanguageAsync(
                    inputText : theLetter.LetterText,
                    countryHint : ""
                    );

                if (!string.IsNullOrEmpty(detectedLanguages.ErrorMessage))
                {
                    return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
                }

                // Grab the top scoring one
                var theLanguage = detectedLanguages.DetectedLanguages.OrderByDescending(i => i.Score).First();

                // Get the sentiment
                var detectedSentiments = await textClient.SentimentAsync(
                    inputText : theLetter.LetterText,
                    language : theLanguage.Iso6391Name
                    );

                if (!string.IsNullOrEmpty(detectedSentiments.ErrorMessage))
                {
                    return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
                }

                result = new SantaResults
                {
                    DetectedLanguage = theLanguage.Name,
                    KidName          = theLetter.KidName,
                    LetterText       = theLetter.LetterText,
                    SentimentScore   = detectedSentiments.Score.Value
                };
            }
            catch (Exception ex)
            {
                log.LogError(ex.ToString());

                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }

            return(new OkObjectResult(result));
        }
Exemple #24
0
        public async Task DetectLanguageWithNoneDefaultCountryHintTest()
        {
            var options = new TextAnalyticsClientOptions()
            {
                DefaultCountryHint = DetectLanguageInput.None
            };

            TextAnalyticsClient client = GetClient(options: options);
            string document            = SingleSpanish;

            DetectedLanguage language = await client.DetectLanguageAsync(document, DetectLanguageInput.None);

            ValidateInDocumenResult(language);
        }
Exemple #25
0
        private static async Task LanguageDetectionExampleAsync(TextAnalyticsClient client)
        {
            WriteLine("****** Language detection ******");
            WriteLine();

            var document = "Ce document est rédigé en Français.";

            WriteLine($"Document: {document}");

            DetectedLanguage detectedLanguage = await client.DetectLanguageAsync(document);

            WriteLine("Language:");
            WriteLine($"\t{detectedLanguage.Name},\tISO-6391: {detectedLanguage.Iso6391Name}\n");

            WriteLine();
        }
        public async Task DetectLanguageWithNoneDefaultCountryHintTest()
        {
            var options = new TextAnalyticsClientOptions(_serviceVersion)
            {
                DefaultCountryHint = DetectLanguageInput.None
            };

            TextAnalyticsClient client = GetClient(options: options);
            string document            = "Este documento está en español";

            DetectedLanguage language = await client.DetectLanguageAsync(document, DetectLanguageInput.None);

            Assert.IsNotNull(language.Name);
            Assert.IsNotNull(language.Iso6391Name);
            Assert.Greater(language.ConfidenceScore, 0.0);
        }
        public async Task DetectLanguageAsync()
        {
            string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string apiKey   = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_API_KEY");

            // Instantiate a client that will be used to call the service.
            var client = new TextAnalyticsClient(new Uri(endpoint), new TextAnalyticsApiKeyCredential(apiKey));

            #region Snippet:DetectLanguageAsync
            string input = "Este documento está en español.";

            DetectedLanguage language = await client.DetectLanguageAsync(input);

            Console.WriteLine($"Detected language {language.Name} with confidence {language.Score}.");
            #endregion
        }
        public async Task DetectLanguageAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            // Instantiate a client that will be used to call the service.
            var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:DetectLanguageAsync
            string document = "Este documento está en español.";

            DetectedLanguage language = await client.DetectLanguageAsync(document);

            Console.WriteLine($"Detected language {language.Name} with confidence score {language.ConfidenceScore}.");
            #endregion
        }
        private static string GetVoice(string input)
        {
            // Full list of languages and voices here: https://docs.microsoft.com/azure/cognitive-services/speech-service/language-support
            // Suggestion: get the preferred language and voice from your user
            Dictionary <string, string> voicesDictionary = new Dictionary <string, string>
            {
                { "it", "it-IT, it-IT, Cosimo, Apollo" },
                { "de", "de-DE, Hedda" },
                { "el", "el-GR, Stefanos" },
                { "es", "es-ES, Pablo, Apollo" },
                { "fr", "fr-FR, fr-FR, Julie, Apollo" },
                { "nl", "da-DK, HelleRUS" },
                { "pt", "pt-PT, HeliaRUS" },
                { "ru", "ru-RU, ru-RU, Pavel, Apollo" },
                { "sv", "sv-SE, HedvigRUS" },
                { "ko", "ko-KR, HeamiRUS" },
                { "zh", "zh-CN, Kangkang, Apollo" },
                { "ja", "ja-JP, Ichiro, Apollo" },
            };

            // Your Text Analytics subscription key.
            string CSSubscriptionKey = Environment.GetEnvironmentVariable("TEXTANALYTICS_KEY");

            // Create a TA client.
            ITextAnalyticsClient client = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(CSSubscriptionKey));

            client.Endpoint = Constants.AzureBaseURLWithRegion;

            var resultLanguage = client.DetectLanguageAsync(new BatchInput(new List <Input>()
            {
                new Input("1", input)
            })).Result;
            var detectedLanguage = resultLanguage.Documents[0].DetectedLanguages[0];

            if (detectedLanguage != null)
            {
                string lang = detectedLanguage.Iso6391Name;

                if (voicesDictionary.ContainsKey(lang))
                {
                    return(voicesDictionary[lang]);
                }
            }

            return(null);
        }
Exemple #30
0
        public async Task DetectLanguageAsync()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

            var client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);

            #region Snippet:DetectLanguageAsync
            string input = "Este documento está en español.";

            DetectLanguageResult result = await client.DetectLanguageAsync(input);

            DetectedLanguage language = result.PrimaryLanguage;

            Console.WriteLine($"Detected language {language.Name} with confidence {language.Score:0.00}.");
            #endregion
        }