private bool CompareTextDocumentInput(TextDocumentInput tdi1, TextDocumentInput tdi2)
 {
     if (!tdi1.Id.Equals(tdi2.Id))
         return false;
     if (!tdi1.Language.Equals(tdi2.Language))
         return false;
     if (!tdi1.Text.Equals(tdi2.Text))
         return false;
     return true;
 }
 private bool CompareTextDocumentInput(TextDocumentInput tdi1, TextDocumentInput tdi2)
 {
     if (!tdi1.Id.Equals(tdi2.Id))
     {
         return(false);
     }
     if (!tdi1.Language.Equals(tdi2.Language))
     {
         return(false);
     }
     if (!tdi1.Text.Equals(tdi2.Text))
     {
         return(false);
     }
     return(true);
 }
        public void ConvertToDocumentInputTest()
        {
            string input = "This is a test";
            var expectedDocument = new TextDocumentInput("0", input)
            {
                Language = "en"
            };

            TextDocumentInput textInput = Client.ConvertToDocumentInput(input, null);
            Assert.IsTrue(CompareTextDocumentInput(expectedDocument, textInput));

            textInput = Client.ConvertToDocumentInput(input, "es");
            expectedDocument.Language = "es";
            Assert.IsTrue(CompareTextDocumentInput(expectedDocument, textInput));

            textInput = Client.ConvertToDocumentInput(input, "es", 2);
            var expectedDocument2 = new TextDocumentInput("2", input)
            {
                Language = "es"
            };
            Assert.IsTrue(CompareTextDocumentInput(expectedDocument2, textInput));
        }
Ejemplo n.º 4
0
        public void RecognizeEntitiesBatch()
        {
            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:TextAnalyticsSample4RecognizeEntitiesBatch
            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "A key technology in Text Analytics is Named Entity Recognition (NER).")
                {
                    Language = "en",
                }
            };

            RecognizeEntitiesResultCollection results = client.RecognizeEntitiesBatch(documents, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

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

            foreach (RecognizeEntitiesResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error code: {result.Error.ErrorCode}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"    Recognized the following {result.Entities.Count()} entities:");

                    foreach (CategorizedEntity entity in result.Entities)
                    {
                        Debug.WriteLine($"        Text: {entity.Text}, Offset (in UTF-16 code units): {entity.Offset}, Length (in UTF-16 code units): {entity.Length}");
                        Debug.WriteLine($"        Text: {entity.Text}, Category: {entity.Category}, SubCategory: {entity.SubCategory}, Confidence score: {entity.ConfidenceScore}");
                    }

                    Debug.WriteLine($"    Document statistics:");
                    Debug.WriteLine($"        Character count (in Unicode graphemes): {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("");
        }
Ejemplo n.º 5
0
        public async Task ExtractEntityLinkingBatchAsync()
        {
            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 <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "Pike place market is my favorite Seattle attraction.")
                {
                    Language = "en",
                }
            };

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

            int i = 0;

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

            foreach (RecognizeLinkedEntitiesResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Console.WriteLine($"    Document error code: {result.Error.ErrorCode}.");
                    Console.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Console.WriteLine($"    Extracted the following {result.Entities.Count()} linked entities:");

                    foreach (LinkedEntity linkedEntity in result.Entities)
                    {
                        Console.WriteLine($"    Name: \"{linkedEntity.Name}\", Language: {linkedEntity.Language}, Data Source: {linkedEntity.DataSource}, Url: {linkedEntity.Url.ToString()}, Entity Id in Data Source: \"{linkedEntity.DataSourceEntityId}\"");
                        foreach (LinkedEntityMatch match in linkedEntity.Matches)
                        {
                            Console.WriteLine($"        Match Text: \"{match.Text}\", Offset (in UTF-16 code units): {match.Offset}");
                            Console.WriteLine($"        Confidence score: {match.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("");
        }
Ejemplo n.º 6
0
        public async Task RecognizeEntitiesBatchAsync()
        {
            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 <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "A key technology in Text Analytics is Named Entity Recognition (NER).")
                {
                    Language = "en",
                }
            };

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

            int i = 0;

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

            foreach (RecognizeEntitiesResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Console.WriteLine($"    Document error code: {result.Error.Code}.");
                    Console.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Console.WriteLine($"    Recognized the following {result.Entities.Count()} entities:");

                    foreach (CategorizedEntity entity in result.Entities)
                    {
                        Console.WriteLine($"        Text: {entity.Text}, Category: {entity.Category}, SubCategory: {entity.SubCategory}, Confidence score: {entity.ConfidenceScore}");
                    }

                    Console.WriteLine($"    Document statistics:");
                    Console.WriteLine($"        Character count (in Unicode graphemes): {result.Statistics.GraphemeCount}");
                    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("");
        }
        public async Task ExtractEntityLinkingBatchAsync()
        {
            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 = @"Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends,
                                Steve Ballmer, eventually became CEO after Bill Gates as well.Steve Ballmer eventually stepped
                                down as CEO of Microsoft, and was succeeded by Satya Nadella.
                                Microsoft originally moved its headquarters to Bellevue, Washington in Januaray 1979, but is now
                                headquartered in Redmond";

            string documentB = @"El CEO de Microsoft es Satya Nadella, quien asumió esta posición en Febrero de 2014. Él
                                empezó como Ingeniero de Software en el año 1992.";

            string documentC = @"Microsoft was founded by Bill Gates and Paul Allen on April 4, 1975, to develop and 
                                sell BASIC interpreters for the Altair 8800. During his career at Microsoft, Gates held
                                the positions of chairman chief executive officer, president and chief software architect
                                while also being the largest individual shareholder until May 2014.";

            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", documentA)
                {
                    Language = "en",
                },
                new TextDocumentInput("2", documentB)
                {
                    Language = "es",
                },
                new TextDocumentInput("3", documentC)
                {
                    Language = "en",
                },
                new TextDocumentInput("4", string.Empty)
            };

            var options = new RecognizeLinkedEntitiesOptions {
                IncludeStatistics = true
            };
            Response <RecognizeLinkedEntitiesResultCollection> response = await client.RecognizeLinkedEntitiesBatchAsync(documents, options);

            RecognizeLinkedEntitiesResultCollection entitiesInDocuments = response.Value;

            int i = 0;

            Console.WriteLine($"Results of Azure Text Analytics \"Entity Linking\", version: \"{entitiesInDocuments.ModelVersion}\"");
            Console.WriteLine("");

            foreach (RecognizeLinkedEntitiesResult entitiesInDocument in entitiesInDocuments)
            {
                TextDocumentInput document = documents[i++];

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

                if (entitiesInDocument.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error code: {entitiesInDocument.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {entitiesInDocument.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"Recognized {entitiesInDocument.Entities.Count} entities:");
                    foreach (LinkedEntity linkedEntity in entitiesInDocument.Entities)
                    {
                        Console.WriteLine($"  Name: {linkedEntity.Name}");
                        Console.WriteLine($"  Language: {linkedEntity.Language}");
                        Console.WriteLine($"  Data Source: {linkedEntity.DataSource}");
                        Console.WriteLine($"  URL: {linkedEntity.Url}");
                        Console.WriteLine($"  Entity Id in Data Source: {linkedEntity.DataSourceEntityId}");
                        foreach (LinkedEntityMatch match in linkedEntity.Matches)
                        {
                            Console.WriteLine($"    Match Text: {match.Text}");
                            Console.WriteLine($"    Offset: {match.Offset}");
                            Console.WriteLine($"    Length: {match.Length}");
                            Console.WriteLine($"    Confidence score: {match.ConfidenceScore}");
                        }
                        Console.WriteLine("");
                    }

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

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"  Document count: {entitiesInDocuments.Statistics.DocumentCount}");
            Console.WriteLine($"  Valid document count: {entitiesInDocuments.Statistics.ValidDocumentCount}");
            Console.WriteLine($"  Invalid document count: {entitiesInDocuments.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"  Transaction count: {entitiesInDocuments.Statistics.TransactionCount}");
            Console.WriteLine("");
        }
        public void AnalyzeSentimentBatch()
        {
            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), new TextAnalyticsSubscriptionKeyCredential(subscriptionKey));

            #region Snippet:TextAnalyticsSample2AnalyzeSentimentBatch
            var inputs = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "That was the best day of my life!")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "This food is very bad. Everyone who ate with us got sick.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "I'm not sure how I feel about this product.")
                {
                    Language = "en",
                },
                new TextDocumentInput("4", "Pike Place Market is my favorite Seattle attraction.  We had so much fun there.")
                {
                    Language = "en",
                }
            };

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

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

            foreach (AnalyzeSentimentResult result in results)
            {
                TextDocumentInput document = inputs[i++];

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

                if (result.ErrorMessage != default)
                {
                    Debug.WriteLine($"Document error: {result.ErrorMessage}.");
                }
                else
                {
                    Debug.WriteLine($"Document sentiment is {result.DocumentSentiment.SentimentClass.ToString()}, with scores: ");
                    Debug.WriteLine($"    Positive score: {result.DocumentSentiment.PositiveScore:0.00}.");
                    Debug.WriteLine($"    Neutral score: {result.DocumentSentiment.NeutralScore:0.00}.");
                    Debug.WriteLine($"    Negative score: {result.DocumentSentiment.NegativeScore:0.00}.");

                    Debug.WriteLine($"    Sentence sentiment results:");

                    foreach (TextSentiment sentenceSentiment in result.SentenceSentiments)
                    {
                        Debug.WriteLine($"    On sentence \"{document.Text.Substring(sentenceSentiment.Offset, sentenceSentiment.Length)}\"");

                        Debug.WriteLine($"    Sentiment is {sentenceSentiment.SentimentClass.ToString()}, with scores: ");
                        Debug.WriteLine($"        Positive score: {sentenceSentiment.PositiveScore:0.00}.");
                        Debug.WriteLine($"        Neutral score: {sentenceSentiment.NeutralScore:0.00}.");
                        Debug.WriteLine($"        Negative score: {sentenceSentiment.NegativeScore: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("");
        }
        public void ExtractKeyPhrasesBatch()
        {
            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), new TextAnalyticsSubscriptionKeyCredential(subscriptionKey));

            #region Snippet:TextAnalyticsSample3ExtractKeyPhrasesBatch
            var inputs = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "My cat might need to see a veterinarian.")
                {
                    Language = "en",
                }
            };

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

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

            foreach (ExtractKeyPhrasesResult result in results)
            {
                TextDocumentInput document = inputs[i++];

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

                if (result.ErrorMessage != default)
                {
                    Debug.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\", Text=\"{document.Text}\"):");
                }
                else
                {
                    Debug.WriteLine($"    Extracted the following {result.KeyPhrases.Count()} key phrases:");

                    foreach (string keyPhrase in result.KeyPhrases)
                    {
                        Debug.WriteLine($"        {keyPhrase}");
                    }

                    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("");
        }
Ejemplo n.º 10
0
        public void ExtractKeyPhrasesBatch()
        {
            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:TextAnalyticsSample3ExtractKeyPhrasesBatch
            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "My cat might need to see a veterinarian.")
                {
                    Language = "en",
                }
            };

            ExtractKeyPhrasesResultCollection results = client.ExtractKeyPhrasesBatch(documents, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

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

            foreach (ExtractKeyPhrasesResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error: {result.Error.Code}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"    Extracted the following {result.KeyPhrases.Count()} key phrases:");

                    foreach (string keyPhrase in result.KeyPhrases)
                    {
                        Debug.WriteLine($"        {keyPhrase}");
                    }

                    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 void RecognizePiiEntitiesBatch()
        {
            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), new TextAnalyticsSubscriptionKeyCredential(subscriptionKey));

            #region Snippet:TextAnalyticsSample5RecognizePiiEntitiesBatch
            var inputs = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "A developer with SSN 555-55-5555 whose phone number is 555-555-5555 is building tools with our APIs.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.")
                {
                    Language = "en",
                }
            };

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

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

            foreach (RecognizePiiEntitiesResult result in results)
            {
                TextDocumentInput document = inputs[i++];

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

                if (result.ErrorMessage != default)
                {
                    Debug.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\", Text=\"{document.Text}\"):");
                }
                else
                {
                    Debug.WriteLine($"    Recognized the following {result.NamedEntities.Count()} PII entit{(result.NamedEntities.Count() > 1 ? "ies" : "y ")}:");

                    foreach (NamedEntity entity in result.NamedEntities)
                    {
                        Debug.WriteLine($"        Text: {entity.Text}, Type: {entity.Type}, SubType: {entity.SubType ?? "N/A"}, Score: {entity.Score:0.00}, Offset: {entity.Offset}, Length: {entity.Length}");
                    }

                    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("");
        }
Ejemplo n.º 12
0
        public void AnalyzeSentimentBatch()
        {
            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:TextAnalyticsSample2AnalyzeSentimentBatch
            string documentA = @"The food and service were unacceptable, but the concierge were nice.
                                After talking to them about the quality of the food and the process
                                to get room service they refunded the money we spent at the restaurant and
                                gave us a voucher for nearby restaurants.";

            string documentB = @"Nos hospedamos en el Hotel Foo la semana pasada por nuestro aniversario. La gerencia
                                sabía de nuestra celebración y me ayudaron a tenerle una sorpresa a mi pareja.
                                La habitación estaba limpia y decorada como yo había pedido. Una gran experiencia.
                                El próximo año volveremos.";

            string documentC = @"The rooms were beautiful. The AC was good and quiet, which was key for us as outside
                                it was 100F and our baby was getting uncomfortable because of the heat. The breakfast
                                was good too with good options and good servicing times.
                                The thing we didn't like was that the toilet in our bathroom was smelly.
                                It could have been that the toilet was not cleaned before we arrived.
                                Either way it was very uncomfortable. Once we notified the staff, they came and cleaned
                                it and left candles.";

            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", documentA)
                {
                    Language = "en",
                },
                new TextDocumentInput("2", documentB)
                {
                    Language = "es",
                },
                new TextDocumentInput("3", documentC)
                {
                    Language = "en",
                },
                new TextDocumentInput("4", string.Empty)
            };

            var options = new AnalyzeSentimentOptions {
                IncludeStatistics = true
            };

            Response <AnalyzeSentimentResultCollection> response = client.AnalyzeSentimentBatch(documents, options);
            AnalyzeSentimentResultCollection            sentimentPerDocuments = response.Value;

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

            foreach (AnalyzeSentimentResult sentimentInDocument in sentimentPerDocuments)
            {
                TextDocumentInput document = documents[i++];

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

                if (sentimentInDocument.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error: {sentimentInDocument.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {sentimentInDocument.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"Document sentiment is {sentimentInDocument.DocumentSentiment.Sentiment}, with confidence scores: ");
                    Console.WriteLine($"  Positive confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Positive}.");
                    Console.WriteLine($"  Neutral confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Neutral}.");
                    Console.WriteLine($"  Negative confidence score: {sentimentInDocument.DocumentSentiment.ConfidenceScores.Negative}.");
                    Console.WriteLine("");
                    Console.WriteLine($"  Sentence sentiment results:");

                    foreach (SentenceSentiment sentimentInSentence in sentimentInDocument.DocumentSentiment.Sentences)
                    {
                        Console.WriteLine($"  For sentence: \"{sentimentInSentence.Text}\"");
                        Console.WriteLine($"  Sentiment is {sentimentInSentence.Sentiment}, with confidence scores: ");
                        Console.WriteLine($"    Positive confidence score: {sentimentInSentence.ConfidenceScores.Positive}.");
                        Console.WriteLine($"    Neutral confidence score: {sentimentInSentence.ConfidenceScores.Neutral}.");
                        Console.WriteLine($"    Negative confidence score: {sentimentInSentence.ConfidenceScores.Negative}.");
                        Console.WriteLine("");
                    }

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

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"  Document count: {sentimentPerDocuments.Statistics.DocumentCount}");
            Console.WriteLine($"  Valid document count: {sentimentPerDocuments.Statistics.ValidDocumentCount}");
            Console.WriteLine($"  Invalid document count: {sentimentPerDocuments.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"  Transaction count: {sentimentPerDocuments.Statistics.TransactionCount}");
            #endregion
        }
        public async Task Sample7_AnalyzeHealthcareEntitiesBatchAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:TextAnalyticsSampleHealthcareBatchAsync
            string document1 = @"RECORD #333582770390100 | MH | 85986313 | | 054351 | 2/14/2001 12:00:00 AM | CORONARY ARTERY DISEASE | Signed | DIS |
                                Admission Date: 5/22/2001 Report Status: Signed Discharge Date: 4/24/2001 ADMISSION DIAGNOSIS: CORONARY ARTERY DISEASE.
                                HISTORY OF PRESENT ILLNESS: The patient is a 54-year-old gentleman with a history of progressive angina over the past several months.
                                The patient had a cardiac catheterization in July of this year revealing total occlusion of the RCA and 50% left main disease ,\
                                with a strong family history of coronary artery disease with a brother dying at the age of 52 from a myocardial infarction and \
                                another brother who is status post coronary artery bypass grafting. The patient had a stress echocardiogram done on July , 2001 , \
                                which showed no wall motion abnormalities , but this was a difficult study due to body habitus. The patient went for six minutes with \
                                minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent. Due to the patient's \
                                increased symptoms and family history and history left main disease with total occasional of his RCA was referred for revascularization with open heart surgery.";

            string document2 = "Prescribed 100mg ibuprofen, taken twice daily.";

            List <TextDocumentInput> batchInput = new List <TextDocumentInput>()
            {
                new TextDocumentInput("1", document1)
                {
                    Language = "en"
                },
                new TextDocumentInput("2", document2)
                {
                    Language = "en"
                },
                new TextDocumentInput("3", string.Empty)
            };

            AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions()
            {
                IncludeStatistics = true
            };

            AnalyzeHealthcareEntitiesOperation healthOperation = await client.StartAnalyzeHealthcareEntitiesAsync(batchInput, options);

            await healthOperation.WaitForCompletionAsync();

            Console.WriteLine($"AnalyzeHealthcareEntities operation was completed");

            Console.WriteLine($"Created On   : {healthOperation.CreatedOn}");
            Console.WriteLine($"Expires On   : {healthOperation.ExpiresOn}");
            Console.WriteLine($"Id           : {healthOperation.Id}");
            Console.WriteLine($"Status       : {healthOperation.Status}");
            Console.WriteLine($"Last Modified: {healthOperation.LastModified}");

            foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in healthOperation.GetValues())
            {
                Console.WriteLine($"Results of Azure Text Analytics \"Healthcare\" Model, version: \"{documentsInPage.ModelVersion}\"");
                Console.WriteLine("");

                int i = 0;

                foreach (AnalyzeHealthcareEntitiesResult result in documentsInPage)
                {
                    TextDocumentInput document = batchInput[i++];

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

                    if (result.HasError)
                    {
                        Console.WriteLine("  Error!");
                        Console.WriteLine($"  Document error code: {result.Error.ErrorCode}.");
                        Console.WriteLine($"  Message: {result.Error.Message}");
                    }
                    else
                    {
                        Console.WriteLine($"    Recognized the following {result.Entities.Count} healthcare entities:");

                        foreach (HealthcareEntity entity in result.Entities)
                        {
                            Console.WriteLine($"    Entity: {entity.Text}");
                            Console.WriteLine($"    Category: {entity.Category}");
                            Console.WriteLine($"    Offset: {entity.Offset}");
                            Console.WriteLine($"    Length: {entity.Length}");
                            Console.WriteLine($"    NormalizedText: {entity.NormalizedText}");
                            Console.WriteLine($"    Links:");

                            foreach (EntityDataSource entityDataSource in entity.DataSources)
                            {
                                Console.WriteLine($"        Entity ID in Data Source: {entityDataSource.EntityId}");
                                Console.WriteLine($"        DataSource: {entityDataSource.Name}");
                            }
                            if (entity.Assertion != null)
                            {
                                Console.WriteLine($"    Assertions:");

                                if (entity.Assertion?.Association != null)
                                {
                                    Console.WriteLine($"        Association: {entity.Assertion?.Association}");
                                }

                                if (entity.Assertion?.Certainty != null)
                                {
                                    Console.WriteLine($"        Certainty: {entity.Assertion?.Certainty}");
                                }
                                if (entity.Assertion?.Conditionality != null)
                                {
                                    Console.WriteLine($"        Conditionality: {entity.Assertion?.Conditionality}");
                                }
                            }
                        }

                        Console.WriteLine($"    We found {result.EntityRelations.Count} relations in the current document:");
                        Console.WriteLine("");

                        foreach (HealthcareEntityRelation relations in result.EntityRelations)
                        {
                            Console.WriteLine($"        Relation: {relations.RelationType}");
                            Console.WriteLine($"        For this relation there are {relations.Roles.Count} roles");

                            foreach (HealthcareEntityRelationRole role in relations.Roles)
                            {
                                Console.WriteLine($"            Role Name: {role.Name}");

                                Console.WriteLine($"            Associated Entity Text: {role.Entity.Text}");
                                Console.WriteLine($"            Associated Entity Category: {role.Entity.Category}");

                                Console.WriteLine("");
                            }

                            Console.WriteLine("");
                        }

                        Console.WriteLine("");
                    }

                    Console.WriteLine($"Batch operation statistics:");
                    Console.WriteLine($"  Document count: {result.Statistics.CharacterCount}");
                    Console.WriteLine($"  Valid document count: {result.Statistics.TransactionCount}");
                    Console.WriteLine("");
                }

                Console.WriteLine($"Batch operation statistics:");
                Console.WriteLine($"  Document count: {documentsInPage.Statistics.DocumentCount}");
                Console.WriteLine($"  Valid document count: {documentsInPage.Statistics.ValidDocumentCount}");
                Console.WriteLine($"  Invalid document count: {documentsInPage.Statistics.InvalidDocumentCount}");
                Console.WriteLine($"  Transaction count: {documentsInPage.Statistics.TransactionCount}");
                Console.WriteLine("");
            }
        }
        public void RecognizeEntitiesBatch()
        {
            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), new TextAnalyticsSubscriptionKeyCredential(subscriptionKey));

            #region Snippet:TextAnalyticsSample4RecognizeEntitiesBatch
            var inputs = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "A key technology in Text Analytics is Named Entity Recognition (NER).")
                {
                    Language = "en",
                }
            };

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

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

            foreach (RecognizeEntitiesResult result in results)
            {
                TextDocumentInput document = inputs[i++];

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

                if (result.ErrorMessage != default)
                {
                    Debug.WriteLine($"    Document error: {result.ErrorMessage}.");
                }
                else
                {
                    Debug.WriteLine($"    Recognized the following {result.NamedEntities.Count()} entities:");

                    foreach (NamedEntity entity in result.NamedEntities)
                    {
                        Debug.WriteLine($"        Text: {entity.Text}, Type: {entity.Type}, SubType: {entity.SubType}, Score: {entity.Score:0.00}, Offset: {entity.Offset}, Length: {entity.Length}");
                    }

                    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("");
        }
Ejemplo n.º 15
0
        public void ExtractEntityLinkingBatch()
        {
            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:TextAnalyticsSample6RecognizeLinkedEntitiesBatch
            var inputs = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "Pike place market is my favorite Seattle attraction.")
                {
                    Language = "en",
                }
            };

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

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

            foreach (RecognizeLinkedEntitiesResult result in results)
            {
                TextDocumentInput document = inputs[i++];

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

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error code: {result.Error.Code}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"    Extracted the following {result.Entities.Count()} linked entities:");

                    foreach (LinkedEntity linkedEntity in result.Entities)
                    {
                        Debug.WriteLine($"    Name: \"{linkedEntity.Name}\", Language: {linkedEntity.Language}, Data Source: {linkedEntity.DataSource}, Url: {linkedEntity.Url.ToString()}, Entity Id in Data Source: \"{linkedEntity.DataSourceEntityId}\"");
                        foreach (LinkedEntityMatch match in linkedEntity.Matches)
                        {
                            Debug.WriteLine($"        Match Text: \"{match.Text}\", Score: {match.Score:0.00}, Offset: {match.Offset}, Length: {match.Length}.");
                        }
                    }

                    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("");
        }
Ejemplo n.º 16
0
        public async Task RecognizePiiEntitiesBatchAsync()
        {
            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());

            string documentA = @"Parker Doe has repaid all of their loans as of 2020-04-25.
                                Their SSN is 859-98-0987. To contact them, use their phone number 800-102-1100.
                                They are originally from Brazil and have document ID number 998.214.865-68";

            string documentB = @"Hoy recibí una llamada al medio día del usuario Juanito Perez, quien preguntaba
                                cómo acceder a su nuevo correo electrónico. Este trabaja en Microsoft y su correo es
                                [email protected]. El usuario accedió a compartir su número para futuras comunicaciones.
                                El número es 800-102-1101";

            string documentC = @"Yesterday, Dan Doe was asking where they could find the ABA number. I explained
                                that it is the first 9 digits in the lower left hand corner of their personal check.
                                After looking at their account they confirmed the number was 111000025";

            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", documentA)
                {
                    Language = "en",
                },
                new TextDocumentInput("2", documentB)
                {
                    Language = "es",
                },
                new TextDocumentInput("3", documentC)
                {
                    Language = "en",
                }
            };

            var options = new RecognizePiiEntitiesOptions {
                IncludeStatistics = true
            };
            Response <RecognizePiiEntitiesResultCollection> response = await client.RecognizePiiEntitiesBatchAsync(documents, options);

            RecognizePiiEntitiesResultCollection entititesPerDocuments = response.Value;

            int i = 0;

            Console.WriteLine($"Results of \"PII Entity Recognition\" Model, version: \"{entititesPerDocuments.ModelVersion}\"");
            Console.WriteLine("");

            foreach (RecognizePiiEntitiesResult piiEntititesInDocument in entititesPerDocuments)
            {
                TextDocumentInput document = documents[i++];

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

                if (piiEntititesInDocument.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error code: {piiEntititesInDocument.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {piiEntititesInDocument.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"  Redacted Text: {piiEntititesInDocument.Entities.RedactedText}");
                    Console.WriteLine("");
                    Console.WriteLine($"  Recognized {piiEntititesInDocument.Entities.Count} PII entities:");
                    foreach (PiiEntity piiEntity in piiEntititesInDocument.Entities)
                    {
                        Console.WriteLine($"    Text: {piiEntity.Text}");
                        Console.WriteLine($"    Category: {piiEntity.Category}");
                        if (!string.IsNullOrEmpty(piiEntity.SubCategory))
                        {
                            Console.WriteLine($"    SubCategory: {piiEntity.SubCategory}");
                        }
                        Console.WriteLine($"    Confidence score: {piiEntity.ConfidenceScore}");
                        Console.WriteLine("");
                    }

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

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"  Document count: {entititesPerDocuments.Statistics.DocumentCount}");
            Console.WriteLine($"  Valid document count: {entititesPerDocuments.Statistics.ValidDocumentCount}");
            Console.WriteLine($"  Invalid document count: {entititesPerDocuments.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"  Transaction count: {entititesPerDocuments.Statistics.TransactionCount}");
            Console.WriteLine("");
        }
Ejemplo n.º 17
0
        public void RecognizePiiEntitiesBatch()
        {
            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:TextAnalyticsSample5RecognizePiiEntitiesBatch
            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "A developer with SSN 555-55-5555 whose phone number is 555-555-5555 is building tools with our APIs.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.")
                {
                    Language = "en",
                }
            };

            RecognizePiiEntitiesResultCollection results = client.RecognizePiiEntitiesBatch(documents, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

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

            foreach (RecognizePiiEntitiesResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error code: {result.Error.Code}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"    Recognized the following {result.Entities.Count()} PII entit{(result.Entities.Count() > 1 ? "ies" : "y ")}:");

                    foreach (PiiEntity entity in result.Entities)
                    {
                        Debug.WriteLine($"        Text: {entity.Text}, Category: {entity.Category}, SubCategory: {entity.SubCategory}, Confidence score: {entity.ConfidenceScore}");
                    }

                    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 void RecognizeEntitiesBatch()
        {
            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:TextAnalyticsSample4RecognizeEntitiesBatch
            string documentA = @"We love this trail and make the trip every year. The views are breathtaking and well
                                worth the hike! Yesterday was foggy though, so we missed the spectacular views.
                                We tried again today and it was amazing. Everyone in my family liked the trail although
                                it was too challenging for the less athletic among us.
                                Not necessarily recommended for small children.
                                A hotel close to the trail offers services for childcare in case you want that.";

            string documentB = @"Nos hospedamos en el Hotel Foo la semana pasada por nuestro aniversario. La gerencia
                                sabía de nuestra celebración y me ayudaron a tenerle una sorpresa a mi pareja.
                                La habitación estaba limpia y decorada como yo había pedido. Una gran experiencia.
                                El próximo año volveremos.";

            string documentC = @"That was the best day of my life! We went on a 4 day trip where we stayed at Hotel Foo.
                                They had great amenities that included an indoor pool, a spa, and a bar.
                                The spa offered couples massages which were really good. 
                                The spa was clean and felt very peaceful. Overall the whole experience was great.
                                We will definitely come back.";

            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", documentA)
                {
                    Language = "en",
                },
                new TextDocumentInput("2", documentB)
                {
                    Language = "es",
                },
                new TextDocumentInput("3", documentC)
                {
                    Language = "en",
                },
                new TextDocumentInput("4", string.Empty)
            };

            var options = new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            };
            Response <RecognizeEntitiesResultCollection> response            = client.RecognizeEntitiesBatch(documents, options);
            RecognizeEntitiesResultCollection            entitiesInDocuments = response.Value;

            int i = 0;
            Console.WriteLine($"Results of Azure Text Analytics \"Named Entity Recognition\" Model, version: \"{entitiesInDocuments.ModelVersion}\"");
            Console.WriteLine("");

            foreach (RecognizeEntitiesResult entitiesInDocument in entitiesInDocuments)
            {
                TextDocumentInput document = documents[i++];

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

                if (entitiesInDocument.HasError)
                {
                    Console.WriteLine("  Error!");
                    Console.WriteLine($"  Document error code: {entitiesInDocument.Error.ErrorCode}.");
                    Console.WriteLine($"  Message: {entitiesInDocument.Error.Message}");
                }
                else
                {
                    Console.WriteLine($"  Recognized the following {entitiesInDocument.Entities.Count()} entities:");

                    foreach (CategorizedEntity entity in entitiesInDocument.Entities)
                    {
                        Console.WriteLine($"    Text: {entity.Text}");
                        Console.WriteLine($"    Offset: {entity.Offset}");
                        Console.WriteLine($"    Category: {entity.Category}");
                        if (!string.IsNullOrEmpty(entity.SubCategory))
                        {
                            Console.WriteLine($"    SubCategory: {entity.SubCategory}");
                        }
                        Console.WriteLine($"    Confidence score: {entity.ConfidenceScore}");
                        Console.WriteLine("");
                    }

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

            Console.WriteLine($"Batch operation statistics:");
            Console.WriteLine($"  Document count: {entitiesInDocuments.Statistics.DocumentCount}");
            Console.WriteLine($"  Valid document count: {entitiesInDocuments.Statistics.ValidDocumentCount}");
            Console.WriteLine($"  Invalid document count: {entitiesInDocuments.Statistics.InvalidDocumentCount}");
            Console.WriteLine($"  Transaction count: {entitiesInDocuments.Statistics.TransactionCount}");
            Console.WriteLine("");
            #endregion
        }
        public void AnalyzeSentimentBatch()
        {
            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:TextAnalyticsSample2AnalyzeSentimentBatch
            var documents = new List <TextDocumentInput>
            {
                new TextDocumentInput("1", "That was the best day of my life!")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "This food is very bad. Everyone who ate with us got sick.")
                {
                    Language = "en",
                },
                new TextDocumentInput("3", "I'm not sure how I feel about this product.")
                {
                    Language = "en",
                },
                new TextDocumentInput("4", "Pike Place Market is my favorite Seattle attraction.  We had so much fun there.")
                {
                    Language = "en",
                }
            };

            AnalyzeSentimentResultCollection results = client.AnalyzeSentimentBatch(documents, new TextAnalyticsRequestOptions {
                IncludeStatistics = true
            });
            #endregion

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

            foreach (AnalyzeSentimentResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Debug.WriteLine($"    Document error: {result.Error.Code}.");
                    Debug.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    Debug.WriteLine($"Document sentiment is {result.DocumentSentiment.Sentiment}, with confidence scores: ");
                    Debug.WriteLine($"    Positive confidence score: {result.DocumentSentiment.ConfidenceScores.Positive}.");
                    Debug.WriteLine($"    Neutral confidence score: {result.DocumentSentiment.ConfidenceScores.Neutral}.");
                    Debug.WriteLine($"    Negative confidence score: {result.DocumentSentiment.ConfidenceScores.Negative}.");

                    Debug.WriteLine($"    Sentence sentiment results:");

                    foreach (SentenceSentiment sentenceSentiment in result.DocumentSentiment.Sentences)
                    {
                        Debug.WriteLine($"    Sentiment is {sentenceSentiment.Sentiment}, with confidence scores: ");
                        Debug.WriteLine($"        Positive confidence score: {sentenceSentiment.ConfidenceScores.Positive}.");
                        Debug.WriteLine($"        Neutral confidence score: {sentenceSentiment.ConfidenceScores.Neutral}.");
                        Debug.WriteLine($"        Negative confidence score: {sentenceSentiment.ConfidenceScores.Negative}.");
                    }

                    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("");
        }
Ejemplo n.º 20
0
        public async Task RecognizePiiEntitiesBatchAsync()
        {
            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 <TextDocumentInput>
            {
                new TextDocumentInput("1", "A developer with SSN 859-98-0987 whose phone number is 800-102-1100 is building tools with our APIs.")
                {
                    Language = "en",
                },
                new TextDocumentInput("2", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.")
                {
                    Language = "en",
                }
            };

            RecognizePiiEntitiesResultCollection results = await client.RecognizePiiEntitiesBatchAsync(documents, new RecognizePiiEntitiesOptions { IncludeStatistics = true });

            int i = 0;

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

            foreach (RecognizePiiEntitiesResult result in results)
            {
                TextDocumentInput document = documents[i++];

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

                if (result.HasError)
                {
                    Console.WriteLine($"    Document error code: {result.Error.ErrorCode}.");
                    Console.WriteLine($"    Message: {result.Error.Message}.");
                }
                else
                {
                    if (result.Entities.Count > 0)
                    {
                        Console.WriteLine($"    Redacted Text: {result.Entities.RedactedText}");
                        Console.WriteLine($"    Recognized the following {result.Entities.Count} PII entit{(result.Entities.Count > 1 ? "ies" : "y ")}:");
                        foreach (PiiEntity entity in result.Entities)
                        {
                            Console.WriteLine($"        Text: {entity.Text}, Category: {entity.Category}, SubCategory: {entity.SubCategory}, Confidence score: {entity.ConfidenceScore}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No entities were found.");
                    }

                    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("");
        }