public void AnalyzeHealthcareEntities() { // create a text analytics client string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey), CreateSampleOptions()); // get input documents 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."; // prepare analyze operation input List <TextDocumentInput> batchInput = new List <TextDocumentInput>() { new TextDocumentInput("1", document1) { Language = "en" }, new TextDocumentInput("2", document2) { Language = "en" }, }; AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions() { IncludeStatistics = true }; // start analysis process AnalyzeHealthcareEntitiesOperation healthOperation = client.StartAnalyzeHealthcareEntities(batchInput, options); // wait for completion with manual polling TimeSpan pollingInterval = new TimeSpan(1000); while (true) { Console.WriteLine($"Status: {healthOperation.Status}"); healthOperation.UpdateStatus(); if (healthOperation.HasCompleted) { break; } Thread.Sleep(pollingInterval); } // view operation status 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}"); // view operation results foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in healthOperation.GetValues()) { Console.WriteLine($"Results of \"Healthcare\" Model, version: \"{documentsInPage.ModelVersion}\""); Console.WriteLine(""); foreach (AnalyzeHealthcareEntitiesResult result in documentsInPage) { Console.WriteLine($" Recognized the following {result.Entities.Count} healthcare entities:"); // view recognized 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:"); // view entity data sources foreach (EntityDataSource entityDataSource in entity.DataSources) { Console.WriteLine($" Entity ID in Data Source: {entityDataSource.EntityId}"); Console.WriteLine($" DataSource: {entityDataSource.Name}"); } // view assertion 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(""); // view recognized healthcare relations foreach (HealthcareEntityRelation relations in result.EntityRelations) { Console.WriteLine($" Relation: {relations.RelationType}"); Console.WriteLine($" For this relation there are {relations.Roles.Count} roles"); // view relation 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(""); } // current document statistics Console.WriteLine($" Document statistics:"); Console.WriteLine($" Character count (in Unicode graphemes): {result.Statistics.CharacterCount}"); Console.WriteLine($" Transaction count: {result.Statistics.TransactionCount}"); Console.WriteLine(""); } // view statistics about documents in current page Console.WriteLine($"Request statistics:"); Console.WriteLine($" Document Count: {documentsInPage.Statistics.DocumentCount}"); Console.WriteLine($" Valid Document Count: {documentsInPage.Statistics.ValidDocumentCount}"); Console.WriteLine($" Transaction Count: {documentsInPage.Statistics.TransactionCount}"); Console.WriteLine($" Invalid Document Count: {documentsInPage.Statistics.InvalidDocumentCount}"); } }
public async Task HealthcareBatch() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:TextAnalyticsSampleHealthcareBatch string document = @"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."; List <string> batchInput = new List <string>() { document, document, }; AnalyzeHealthcareEntitiesOptions options = new AnalyzeHealthcareEntitiesOptions() { IncludeStatistics = true }; AnalyzeHealthcareEntitiesOperation healthOperation = client.StartAnalyzeHealthcareEntities(batchInput, "en", options); await healthOperation.WaitForCompletionAsync(); foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in healthOperation.GetValues()) { Console.WriteLine($"Results of Azure Text Analytics \"Healthcare\" Model, version: \"{documentsInPage.ModelVersion}\""); Console.WriteLine(""); foreach (AnalyzeHealthcareEntitiesResult result in documentsInPage) { 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($" Links:"); foreach (EntityDataSource entityDataSource in entity.DataSources) { Console.WriteLine($" Entity ID in Data Source: {entityDataSource.EntityId}"); Console.WriteLine($" DataSource: {entityDataSource.Name}"); } } 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($"Request statistics:"); Console.WriteLine($" Document Count: {documentsInPage.Statistics.DocumentCount}"); Console.WriteLine($" Valid Document Count: {documentsInPage.Statistics.ValidDocumentCount}"); Console.WriteLine($" Transaction Count: {documentsInPage.Statistics.TransactionCount}"); Console.WriteLine($" Invalid Document Count: {documentsInPage.Statistics.InvalidDocumentCount}"); Console.WriteLine(""); } }
public async Task Sample7_AnalyzeHealthcareEntitiesConvenienceAsync() { // create a text analytics client string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:TextAnalyticsSampleHealthcareConvenienceAnalyzeDocumentsAsync // get input documents 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."; // prepare analyze operation input List <string> batchInput = new List <string>() { document1, document2, string.Empty }; var options = new AnalyzeHealthcareEntitiesOptions { }; // start analysis process AnalyzeHealthcareEntitiesOperation healthOperation = await client.StartAnalyzeHealthcareEntitiesAsync(batchInput, "en", options); await healthOperation.WaitForCompletionAsync(); #endregion #region Snippet:TextAnalyticsSampleHealthcareOperationStatus // view operation status Console.WriteLine($"Created On : {healthOperation.CreatedOn}"); Console.WriteLine($"Expires On : {healthOperation.ExpiresOn}"); Console.WriteLine($"Status : {healthOperation.Status}"); Console.WriteLine($"Last Modified: {healthOperation.LastModified}"); #endregion #region Snippet:TextAnalyticsSampleHealthcareConvenienceAsyncViewResults // view operation results await foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in healthOperation.Value) { Console.WriteLine($"Results of Azure Text Analytics \"Healthcare Async\" Model, version: \"{documentsInPage.ModelVersion}\""); Console.WriteLine(""); foreach (AnalyzeHealthcareEntitiesResult entitiesInDoc in documentsInPage) { if (!entitiesInDoc.HasError) { foreach (var entity in entitiesInDoc.Entities) { // view recognized healthcare 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:"); // view entity data sources foreach (EntityDataSource entityDataSource in entity.DataSources) { Console.WriteLine($" Entity ID in Data Source: {entityDataSource.EntityId}"); Console.WriteLine($" DataSource: {entityDataSource.Name}"); } // view assertion 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 {entitiesInDoc.EntityRelations.Count} relations in the current document:"); Console.WriteLine(""); // view recognized healthcare relations foreach (HealthcareEntityRelation relations in entitiesInDoc.EntityRelations) { Console.WriteLine($" Relation: {relations.RelationType}"); Console.WriteLine($" For this relation there are {relations.Roles.Count} roles"); // view relation 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(""); } } else { Console.WriteLine(" Error!"); Console.WriteLine($" Document error code: {entitiesInDoc.Error.ErrorCode}."); Console.WriteLine($" Message: {entitiesInDoc.Error.Message}"); } Console.WriteLine(""); } } #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 abstract Task <AnalyzeHealthcareEntitiesOperation> StartAnalyzeHealthcareEntitiesAsync(IEnumerable <TextDocumentInput> documents, AnalyzeHealthcareEntitiesOptions options = default, CancellationToken cancellationToken = default);
public abstract AnalyzeHealthcareEntitiesOperation StartAnalyzeHealthcareEntities(IEnumerable <string> documents, string language = default, AnalyzeHealthcareEntitiesOptions options = default, CancellationToken cancellationToken = default);
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext) { string skillName = executionContext.FunctionName; IEnumerable <WebApiRequestRecord> requestRecords = WebApiSkillHelpers.GetRequestRecords(req); if (requestRecords == null) { return(new BadRequestObjectResult($"{skillName} - Invalid request record array.")); } // Get Endpoint and access key from App Settings string apiKey = Environment.GetEnvironmentVariable(textAnalyticsApiKeySetting, EnvironmentVariableTarget.Process); string apiEndpoint = Environment.GetEnvironmentVariable(textAnalyticsApiEndpointSetting, EnvironmentVariableTarget.Process); if (apiKey == null || apiEndpoint == null) { return(new BadRequestObjectResult($"{skillName} - TextAnalyticsForHealth API key or Endpoint is missing. Make sure to set it in the Environment Variables.")); } var client = new TextAnalyticsClient(new Uri(apiEndpoint), new AzureKeyCredential(apiKey)); // Get a custom timeout from the header, if it exists. If not use the default timeout. int timeout; if (!int.TryParse(req.Headers["timeout"].ToString(), out timeout)) { timeout = defaultTimeout; } timeout = Math.Clamp(timeout - timeoutBuffer, 1, maxTimeout - timeoutBuffer); var timeoutMiliseconds = timeout * 1000; var timeoutTask = Task.Delay(timeoutMiliseconds); // Get a custom default language, if none is provided, use english string defaultLanguage = req.Headers.ContainsKey("defaultLanguageCode")? req.Headers["defaultLanguageCode"].ToString(): "en"; WebApiSkillResponse response = await WebApiSkillHelpers.ProcessRequestRecordsAsync(skillName, requestRecords, async (inRecord, outRecord) => { if (timeoutTask.IsCompleted) { // The time limit for all the skills has been met outRecord.Errors.Add(new WebApiErrorWarningContract { Message = "TextAnalyticsForHealth Error: The Text Analysis Operation took too long to complete." }); return(outRecord); } // Prepare analysis operation input if (!inRecord.Data.ContainsKey("text")) { outRecord.Errors.Add(new WebApiErrorWarningContract { Message = "TextAnalyticsForHealth Error: The skill request did not contain 'text' in the input." }); return(outRecord); } var document = inRecord.Data["text"] as string; var language = inRecord.Data.ContainsKey("languageCode") ? inRecord.Data["languageCode"] as string : defaultLanguage; var docInfo = new StringInfo(document); if (docInfo.LengthInTextElements >= maxCharLength) { outRecord.Warnings.Add(new WebApiErrorWarningContract { Message = $"TextAnalyticsForHealth Warning: The submitted document was over {maxCharLength} elements. It has been truncated to fit this requirement." }); document = docInfo.SubstringByTextElements(0, maxCharLength); } var options = new AnalyzeHealthcareEntitiesOptions { }; List <string> batchInput = new List <string>() { document }; // start analysis process var timer = System.Diagnostics.Stopwatch.StartNew(); AnalyzeHealthcareEntitiesOperation healthOperation = await client.StartAnalyzeHealthcareEntitiesAsync(batchInput, language, options); var healthOperationTask = healthOperation.WaitForCompletionAsync().AsTask(); if (await Task.WhenAny(healthOperationTask, timeoutTask) == healthOperationTask) { // Task Completed, now lets process the result. outRecord.Data["status"] = healthOperation.Status.ToString(); if (healthOperation.Status != TextAnalyticsOperationStatus.Succeeded || !healthOperation.HasValue) { // The operation was not a success outRecord.Errors.Add(new WebApiErrorWarningContract { Message = "TextAnalyticsForHealth Error: Health Operation returned a non-succeeded status." }); } else { // The operation was a success, so lets add the results to our output. await ExtractEntityData(healthOperation.Value, outRecord); } } else { // Timeout outRecord.Errors.Add(new WebApiErrorWarningContract { Message = "TextAnalyticsForHealth Error: The Text Analysis Operation took too long to complete." }); } // Record how long this task took to complete. timer.Stop(); var timeToComplete = timer.Elapsed.TotalSeconds; log.LogInformation($"Time to complete request for document with ID {inRecord.RecordId}: {timeToComplete}"); return(outRecord); }); return(new OkObjectResult(response)); }