コード例 #1
0
        public async Task DetectLanguageBatchTest()
        {
            TextAnalyticsClient client = GetClient();
            var inputs = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("2", "Bonjour tout le monde")
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("3", "Hola mundo")
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = "us",
                }
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(inputs);

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
            Assert.AreEqual("English", results[3].PrimaryLanguage.Name);
        }
        public void DetectLanguageBatchConvenience()
        {
            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));

            var inputs = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo",
                ":) :( :D",
            };

            Debug.WriteLine($"Detecting language for inputs:");
            foreach (string input in inputs)
            {
                Debug.WriteLine($"    {input}");
            }

            #region Snippet:TextAnalyticsSample1DetectLanguagesConvenience
            DetectLanguageResultCollection results = client.DetectLanguageBatch(inputs);
            #endregion

            int i = 0;
            foreach (DetectLanguageResult result in results)
            {
                Debug.WriteLine($"On document {inputs[i++]}:");
                Debug.WriteLine($"Detected language: {result.PrimaryLanguage.Name}, with confidence {result.PrimaryLanguage.Score}.");
            }
        }
コード例 #3
0
        public async Task DetectLanguageBatchConvenienceWithStatisticsTest()
        {
            TextAnalyticsClient client = GetClient();
            var documents = new List <string>
            {
                "Hello world",
                "This is a test"
            };

            var options = new TextAnalyticsRequestOptions()
            {
                IncludeStatistics = true,
                ModelVersion      = "2019-10-01"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, "us", options);

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("English", results[1].PrimaryLanguage.Name);

            Assert.IsNotNull(results.Statistics);
            Assert.Greater(results.Statistics.DocumentCount, 0);
            Assert.Greater(results.Statistics.TransactionCount, 0);
            Assert.GreaterOrEqual(results.Statistics.InvalidDocumentCount, 0);
            Assert.GreaterOrEqual(results.Statistics.ValidDocumentCount, 0);

            Assert.IsNotNull(results[0].Statistics);
            Assert.Greater(results[0].Statistics.CharacterCount, 0);
            Assert.Greater(results[0].Statistics.TransactionCount, 0);
        }
コード例 #4
0
        public void DetectLanguageBatchConvenience()
        {
            string endpoint        = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT");
            string subscriptionKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_SUBSCRIPTION_KEY");

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

            var inputs = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo",
                ":) :( :D",
            };

            Debug.WriteLine($"Detecting language for inputs:");
            foreach (string input in inputs)
            {
                Debug.WriteLine($"    {input}");
            }

            #region Snippet:TextAnalyticsSample1DetectLanguagesConvenience
            DetectLanguageResultCollection results = client.DetectLanguages(inputs);
            #endregion

            Debug.WriteLine($"Detected languages are:");
            foreach (DetectLanguageResult result in results)
            {
                Debug.WriteLine($"    {result.PrimaryLanguage.Name}, with confidence {result.PrimaryLanguage.Score:0.00}.");
            }
        }
コード例 #5
0
        public async Task DetectLanguageBatchTest()
        {
            TextAnalyticsClient client = GetClient();
            var documents = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("2", "Bonjour tout le monde")
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("3", "Hola mundo")
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = "us",
                }
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, options : new TextAnalyticsRequestOptions()
            {
                ModelVersion = "2019-10-01"
            });

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
            Assert.AreEqual("(Unknown)", results[3].PrimaryLanguage.Name);
        }
コード例 #6
0
        public async Task DetectLanguageBatchWithStatisticsTest()
        {
            TextAnalyticsClient client = GetClient();
            var inputs = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("2", "Bonjour tout le monde")
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("3", "Hola mundo")
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = "us",
                }
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(inputs, new TextAnalyticsRequestOptions { IncludeStatistics = true });

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
            Assert.AreEqual("English", results[3].PrimaryLanguage.Name);
            Assert.IsNotNull(results[0].Statistics);
            Assert.IsNotNull(results[0].Statistics.CharacterCount);
            Assert.IsNotNull(results[0].Statistics.TransactionCount);
        }
        public void DetectLanguageBatchConvenience()
        {
            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));

            var documents = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo",
                ":) :( :D",
            };

            Debug.WriteLine($"Detecting language for documents:");
            foreach (string document in documents)
            {
                Debug.WriteLine($"    {document}");
            }

            #region Snippet:TextAnalyticsSample1DetectLanguagesConvenience
            DetectLanguageResultCollection results = client.DetectLanguageBatch(documents);
            #endregion

            int i = 0;
            foreach (DetectLanguageResult result in results)
            {
                Debug.WriteLine($"On document {documents[i++]}:");
                Debug.WriteLine($"Detected language: {result.PrimaryLanguage.Name}, with confidence score {result.PrimaryLanguage.ConfidenceScore}.");
            }
        }
        public async Task DetectLanguageBatchConvenienceAsync()
        {
            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 AzureKeyCredential(apiKey));

            var documents = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo",
                ":) :( :D",
            };

            Console.WriteLine($"Detecting language for documents:");
            foreach (string document in documents)
            {
                Debug.WriteLine($"    {document}");
            }

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents);

            int i = 0;

            foreach (DetectLanguageResult result in results)
            {
                Console.WriteLine($"On document {documents[i++]}:");
                Console.WriteLine($"Detected language: {result.PrimaryLanguage.Name}, with confidence {result.PrimaryLanguage.Score}.");
            }
        }
コード例 #9
0
        public void DetectLanguageBatch()
        {
            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 client = new TextAnalyticsClient(new Uri(endpoint), subscriptionKey);

            var inputs = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo",
                ":) :( :D",
            };

            Debug.WriteLine($"Detecting language for inputs:");
            foreach (var input in inputs)
            {
                Debug.WriteLine($"    {input}");
            }
            DetectLanguageResultCollection results = client.DetectLanguages(inputs);

            Debug.WriteLine($"Detected languages are:");
            foreach (DetectLanguageResult result in results)
            {
                Debug.WriteLine($"    {result.PrimaryLanguage.Name}, with confidence {result.PrimaryLanguage.Score:0.00}.");
            }
        }
コード例 #10
0
        public async Task DetectLanguageBatchTest()
        {
            TextAnalyticsClient        client    = GetClient();
            List <DetectLanguageInput> documents = batchDocuments;

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, options : new TextAnalyticsRequestOptions()
            {
                ModelVersion = "2019-10-01"
            });

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
            Assert.AreEqual("(Unknown)", results[3].PrimaryLanguage.Name);
        }
コード例 #11
0
        public async Task DetectLanguageBatchConvenienceTest()
        {
            TextAnalyticsClient client = GetClient();
            var inputs = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(inputs);

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
        }
コード例 #12
0
        public async Task DetectLanguageBatchConvenienceTest()
        {
            TextAnalyticsClient client    = GetClient();
            List <string>       documents = batchConvenienceDocuments;

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, options : new TextAnalyticsRequestOptions()
            {
                ModelVersion = "2019-10-01"
            });

            ValidateBatchDocumentsResult(results);

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
        }
コード例 #13
0
        public async Task DetectLanguageBatchConvenienceWithStatisticsTest()
        {
            TextAnalyticsClient client = GetClient();
            var inputs = new List <string>
            {
                "Hello world",
                "This is a test"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(inputs, "us", new TextAnalyticsRequestOptions { IncludeStatistics = true });

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("English", results[1].PrimaryLanguage.Name);
            Assert.IsNotNull(results[0].Statistics);
            Assert.IsNotNull(results[0].Statistics.CharacterCount);
            Assert.IsNotNull(results[0].Statistics.TransactionCount);
        }
コード例 #14
0
        public async Task DetectLanguageBatchWithErrorTest()
        {
            TextAnalyticsClient client = GetClient();
            var inputs = new List <string>
            {
                "Hello world",
                "",
                "Hola mundo"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(inputs);

            Assert.IsTrue(!results[0].HasError);
            Assert.IsTrue(!results[2].HasError);

            Assert.IsTrue(results[1].HasError);
            Assert.Throws <InvalidOperationException>(() => results[1].PrimaryLanguage.GetType());
        }
コード例 #15
0
        public async Task DetectLanguageBatchWithNullTextTest()
        {
            TextAnalyticsClient client = GetClient();
            var documents = new List <DetectLanguageInput> {
                new DetectLanguageInput("1", null)
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, options : new TextAnalyticsRequestOptions()
            {
                ModelVersion = "2019-10-01"
            });

            var exceptionMessage = "Cannot access result for document 1, due to error InvalidDocument: Document text is empty.";

            Assert.IsTrue(results[0].HasError);
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => results[0].PrimaryLanguage.GetType());

            Assert.AreEqual(exceptionMessage, ex.Message);
        }
コード例 #16
0
        public async Task DetectedLanguageNullIso6391Name()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""kind"": ""LanguageDetectionResults"",
                    ""results"": {
                        ""documents"": [
                        {
                            ""id"": ""1"",
                            ""detectedLanguage"": {
                                ""name"": ""English"",
                                ""iso6391Name"": null,
                                ""confidenceScore"": 1
                                },
                                ""warnings"": []
                            }
                        ],
                        ""errors"": [],
                        ""modelVersion"": ""2020 -07-01""
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

            var mockTransport = new MockTransport(new[] { mockResponse });
            var client        = CreateTestClient(mockTransport);

            var documents = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                }
            };

            DetectLanguageResultCollection response = await client.DetectLanguageBatchAsync(documents);

            Assert.IsNotNull(response.FirstOrDefault().PrimaryLanguage.Name);
            Assert.IsNull(response.FirstOrDefault().PrimaryLanguage.Iso6391Name);
        }
コード例 #17
0
        public async Task DetectLanguageBatchWithStatisticsTest()
        {
            TextAnalyticsClient        client    = GetClient();
            List <DetectLanguageInput> documents = batchDocuments;

            var options = new TextAnalyticsRequestOptions()
            {
                IncludeStatistics = true,
                ModelVersion      = "2019-10-01"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, options : options);

            ValidateBatchDocumentsResult(results, includeStatistics: true);

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);
            Assert.AreEqual("(Unknown)", results[3].PrimaryLanguage.Name);
        }
コード例 #18
0
        private void ValidateBatchDocumentsResult(DetectLanguageResultCollection results, bool includeStatistics = default)
        {
            Assert.That(results.ModelVersion, Is.Not.Null.And.Not.Empty);

            if (includeStatistics)
            {
                Assert.IsNotNull(results.Statistics);
                Assert.Greater(results.Statistics.DocumentCount, 0);
                Assert.Greater(results.Statistics.TransactionCount, 0);
                Assert.GreaterOrEqual(results.Statistics.InvalidDocumentCount, 0);
                Assert.GreaterOrEqual(results.Statistics.ValidDocumentCount, 0);
            }
            else
            {
                Assert.IsNull(results.Statistics);
            }

            Assert.Greater(results.Count, 0);
            foreach (DetectLanguageResult languageInDocument in results)
            {
                Assert.That(languageInDocument.Id, Is.Not.Null.And.Not.Empty);
                Assert.False(languageInDocument.HasError);

                //Even though statistics are not asked for, TA 5.0.0 shipped with Statistics default always present.
                Assert.IsNotNull(languageInDocument.Statistics);

                if (includeStatistics)
                {
                    Assert.GreaterOrEqual(languageInDocument.Statistics.CharacterCount, 0);
                    Assert.Greater(languageInDocument.Statistics.TransactionCount, 0);
                }
                else
                {
                    Assert.AreEqual(0, languageInDocument.Statistics.CharacterCount);
                    Assert.AreEqual(0, languageInDocument.Statistics.TransactionCount);
                }

                ValidateInDocumenResult(languageInDocument.PrimaryLanguage);
            }
        }
コード例 #19
0
        public async Task DetectLanguageBatchWithErrorTest()
        {
            TextAnalyticsClient client = GetClient();
            var inputs = new List <string>
            {
                "Hello world",
                "",
                "Hola mundo"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(inputs);

            Assert.IsTrue(!results[0].HasError);
            Assert.IsTrue(!results[2].HasError);

            var exceptionMessage = "Cannot access result for document 1, due to error InvalidDocument: Document text is empty.";

            Assert.IsTrue(results[1].HasError);
            InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => results[1].PrimaryLanguage.GetType());

            Assert.AreEqual(exceptionMessage, ex.Message);
        }
コード例 #20
0
        public async Task DetectLanguageBatchConvenienceTest()
        {
            TextAnalyticsClient client = GetClient();
            var documents = new List <string>
            {
                "Hello world",
                "Bonjour tout le monde",
                "Hola mundo"
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, options : new TextAnalyticsRequestOptions()
            {
                ModelVersion = "2019-10-01"
            });

            Assert.AreEqual("English", results[0].PrimaryLanguage.Name);
            Assert.AreEqual("French", results[1].PrimaryLanguage.Name);
            Assert.AreEqual("Spanish", results[2].PrimaryLanguage.Name);

            Assert.AreEqual(0, results[0].Statistics.CharacterCount);
            Assert.AreEqual(0, results[0].Statistics.TransactionCount);
            Assert.IsNull(results.Statistics);
        }
コード例 #21
0
        public void DetectLanguageBatch()
        {
            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 AzureKeyCredential(apiKey));

            #region Snippet:TextAnalyticsSample1DetectLanguageBatch
            var inputs = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("2", "Bonjour tout le monde")
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("3", "Hola mundo")
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = DetectLanguageInput.None,
                }
            };

            DetectLanguageResultCollection results = client.DetectLanguageBatch(inputs, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

            int i = 0;
            Debug.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{results.ModelVersion}\"");
            Debug.WriteLine("");

            foreach (DetectLanguageResult result in results)
            {
                DetectLanguageInput document = inputs[i++];

                Debug.WriteLine($"On document (Id={document.Id}, CountryHint=\"{document.CountryHint}\", Text=\"{document.Text}\"):");

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error code: {result.Error.Code}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"    Detected language {result.PrimaryLanguage.Name} with confidence {result.PrimaryLanguage.Score}.");

                    Debug.WriteLine($"    Document statistics:");
                    Debug.WriteLine($"        Character count (in Unicode graphemes): {result.Statistics.GraphemeCount}");
                    Debug.WriteLine($"        Transaction count: {result.Statistics.TransactionCount}");
                    Debug.WriteLine("");
                }
            }

            Debug.WriteLine($"Batch operation statistics:");
            Debug.WriteLine($"    Document count: {results.Statistics.DocumentCount}");
            Debug.WriteLine($"    Valid document count: {results.Statistics.ValidDocumentCount}");
            Debug.WriteLine($"    Invalid document count: {results.Statistics.InvalidDocumentCount}");
            Debug.WriteLine($"    Transaction count: {results.Statistics.TransactionCount}");
            Debug.WriteLine("");
        }
        public async Task DetectLanguageBatchConvenienceAsync()
        {
            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));

            string documentA = @"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.";

            string documentB = @"This document is written in a language different than Spanish. It's objective is to demonstrate
                                how to call the Detect Language method from the Microsoft Azure Text Analytics service.
                                It also shows how to access the information returned from the service. This capability is useful
                                for content stores that collect arbitrary text, where language is unknown.
                                The Language Detection feature can detect a wide range of languages, variants, dialects, and some
                                regional or cultural languages.";

            string documentC = @"Ce document est rédigé dans une langue différente de l'espagnol. Son objectif est de montrer comment
                                appeler la méthode Detect Language à partir du service Microsoft Azure Text Analytics.
                                Il montre également comment accéder aux informations renvoyées par le service. Cette capacité est
                                utile pour les magasins de contenu qui collectent du texte arbitraire dont la langue est inconnue.
                                La fonctionnalité Détection de langue peut détecter une grande variété de langues, de variantes,
                                de dialectes, et certaines langues régionales ou de culture.";

            string documentD = string.Empty;

            var documents = new List <string>
            {
                documentA,
                documentB,
                documentC,
                documentD
            };

            Response <DetectLanguageResultCollection> response = await client.DetectLanguageBatchAsync(documents);

            DetectLanguageResultCollection documentsLanguage = response.Value;

            int i = 0;

            Console.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{documentsLanguage.ModelVersion}\"");
            Console.WriteLine("");

            foreach (DetectLanguageResult documentLanguage in documentsLanguage)
            {
                Console.WriteLine($"On document with Text: \"{documents[i++]}\"");
                Console.WriteLine("");
                if (documentLanguage.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error code: {documentLanguage.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {documentLanguage.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"  Detected language: {documentLanguage.PrimaryLanguage.Name}");
                    Console.WriteLine($"  Confidence score: {documentLanguage.PrimaryLanguage.ConfidenceScore}");
                }
                Console.WriteLine("");
            }
        }
コード例 #23
0
        public void DetectLanguageBatch()
        {
            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), CreateSampleOptions());

            #region Snippet:TextAnalyticsSample1DetectLanguageBatch
            string documentA = @"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.";

            string documentB = @"This document is written in a language different than Spanish. It's objective is to demonstrate
                                how to call the Detect Language method from the Microsoft Azure Text Analytics service.
                                It also shows how to access the information returned from the service. This capability is useful
                                for content stores that collect arbitrary text, where language is unknown.
                                The Language Detection feature can detect a wide range of languages, variants, dialects, and some
                                regional or cultural languages.";

            string documentC = @"Ce document est rédigé dans une langue différente de l'espagnol. Son objectif est de montrer comment
                                appeler la méthode Detect Language à partir du service Microsoft Azure Text Analytics.
                                Il montre également comment accéder aux informations renvoyées par le service. Cette capacité est
                                utile pour les magasins de contenu qui collectent du texte arbitraire dont la langue est inconnue.
                                La fonctionnalité Détection de langue peut détecter une grande variété de langues, de variantes,
                                de dialectes, et certaines langues régionales ou de culture.";

            var documents = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", documentA)
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("2", documentB)
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("3", documentC)
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = DetectLanguageInput.None,
                },
                new DetectLanguageInput("5", "")
            };

            var options = new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            };

            Response <DetectLanguageResultCollection> response          = client.DetectLanguageBatch(documents, options);
            DetectLanguageResultCollection            documentsLanguage = response.Value;

            int i = 0;
            Console.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{documentsLanguage.ModelVersion}\"");
            Console.WriteLine("");

            foreach (DetectLanguageResult documentLanguage in documentsLanguage)
            {
                DetectLanguageInput document = documents[i++];

                Console.WriteLine($"On document (Id={document.Id}, CountryHint=\"{document.CountryHint}\"):");

                if (documentLanguage.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error code: {documentLanguage.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {documentLanguage.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"  Detected language: {documentLanguage.PrimaryLanguage.Name}");
                    Console.WriteLine($"  Confidence score: {documentLanguage.PrimaryLanguage.ConfidenceScore}");

                    Console.WriteLine($"  Document statistics:");
                    Console.WriteLine($"    Character count: {documentLanguage.Statistics.CharacterCount}");
                    Console.WriteLine($"    Transaction count: {documentLanguage.Statistics.TransactionCount}");
                }
                Console.WriteLine("");
            }

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"  Document count: {documentsLanguage.Statistics.DocumentCount}");
            Console.WriteLine($"  Valid document count: {documentsLanguage.Statistics.ValidDocumentCount}");
            Console.WriteLine($"  Invalid document count: {documentsLanguage.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"  Transaction count: {documentsLanguage.Statistics.TransactionCount}");
            #endregion
        }
コード例 #24
0
        public void DetectLanguageBatch()
        {
            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:TextAnalyticsSample1DetectLanguagesBatch
            var inputs = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("2", "Bonjour tout le monde")
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("3", "Hola mundo")
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = "us",
                }
            };

            DetectLanguageResultCollection results = client.DetectLanguages(inputs, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

            int i = 0;
            Debug.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{results.ModelVersion}\"");
            Debug.WriteLine("");

            foreach (DetectLanguageResult result in results)
            {
                DetectLanguageInput document = inputs[i++];

                Debug.WriteLine($"On document (Id={document.Id}, CountryHint=\"{document.CountryHint}\", Text=\"{document.Text}\"):");

                if (result.ErrorMessage != default)
                {
                    Debug.WriteLine($"    Document error: {result.ErrorMessage}.");
                }
                else
                {
                    Debug.WriteLine($"    Detected language {result.PrimaryLanguage.Name} with confidence {result.PrimaryLanguage.Score:0.00}.");

                    Debug.WriteLine($"    Document statistics:");
                    Debug.WriteLine($"        Character count: {result.Statistics.CharacterCount}");
                    Debug.WriteLine($"        Transaction count: {result.Statistics.TransactionCount}");
                    Debug.WriteLine("");
                }
            }

            Debug.WriteLine($"Batch operation statistics:");
            Debug.WriteLine($"    Document count: {results.Statistics.DocumentCount}");
            Debug.WriteLine($"    Valid document count: {results.Statistics.ValidDocumentCount}");
            Debug.WriteLine($"    Invalid document count: {results.Statistics.InvalidDocumentCount}");
            Debug.WriteLine($"    Transaction count: {results.Statistics.TransactionCount}");
            Debug.WriteLine("");
        }
コード例 #25
0
        public async Task DetectLanguageBatchAsync()
        {
            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));

            var documents = new List <DetectLanguageInput>
            {
                new DetectLanguageInput("1", "Hello world")
                {
                    CountryHint = "us",
                },
                new DetectLanguageInput("2", "Bonjour tout le monde")
                {
                    CountryHint = "fr",
                },
                new DetectLanguageInput("3", "Hola mundo")
                {
                    CountryHint = "es",
                },
                new DetectLanguageInput("4", ":) :( :D")
                {
                    CountryHint = DetectLanguageInput.None,
                }
            };

            DetectLanguageResultCollection results = await client.DetectLanguageBatchAsync(documents, new TextAnalyticsRequestOptions { IncludeStatistics = true });

            int i = 0;

            Console.WriteLine($"Results of Azure Text Analytics \"Detect Language\" Model, version: \"{results.ModelVersion}\"");
            Console.WriteLine("");

            foreach (DetectLanguageResult result in results)
            {
                DetectLanguageInput document = documents[i++];

                Console.WriteLine($"On document (Id={document.Id}, CountryHint=\"{document.CountryHint}\", Text=\"{document.Text}\"):");

                if (result.HasError)
                {
                    Console.WriteLine($"    Document error code: {result.Error.Code}.");
                    Console.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Console.WriteLine($"    Detected language {result.PrimaryLanguage.Name} with confidence score {result.PrimaryLanguage.ConfidenceScore}.");

                    Console.WriteLine($"    Document statistics:");
                    Console.WriteLine($"        Character count (in Unicode graphemes): {result.Statistics.CharacterCount}");
                    Console.WriteLine($"        Transaction count: {result.Statistics.TransactionCount}");
                    Console.WriteLine("");
                }
            }

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"    Document count: {results.Statistics.DocumentCount}");
            Console.WriteLine($"    Valid document count: {results.Statistics.ValidDocumentCount}");
            Console.WriteLine($"    Invalid document count: {results.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"    Transaction count: {results.Statistics.TransactionCount}");
            Console.WriteLine("");
        }