public async Task HealthcareBatchConvenience() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:TextAnalyticsSampleHealthcareBatchConvenience 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 <string> batchInput = new List <string>() { document1, document2, }; AnalyzeHealthcareEntitiesOperation healthOperation = client.StartAnalyzeHealthcareEntities(batchInput); 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(""); } } }
public async Task AnalyzeHealthcareEntitiesPagination() { TextAnalyticsClient client = GetClient(); AnalyzeHealthcareEntitiesOperation operation = await client.StartAnalyzeHealthcareEntitiesAsync(s_batchDocuments); Assert.IsFalse(operation.HasCompleted); Assert.IsFalse(operation.HasValue); Assert.ThrowsAsync <InvalidOperationException>(async() => await Task.Run(() => operation.Value)); Assert.Throws <InvalidOperationException>(() => operation.GetValues()); await operation.WaitForCompletionAsync(); Assert.IsTrue(operation.HasCompleted); Assert.IsTrue(operation.HasValue); ValidateOperationProperties(operation); // try async //There most be 1 page List <AnalyzeHealthcareEntitiesResultCollection> asyncPages = operation.Value.ToEnumerableAsync().Result; Assert.AreEqual(1, asyncPages.Count); // First page should have 2 results Assert.AreEqual(2, asyncPages[0].Count); // try sync //There most be 1 page List <AnalyzeHealthcareEntitiesResultCollection> pages = operation.GetValues().AsEnumerable().ToList(); Assert.AreEqual(1, pages.Count); // First page should have 2 results Assert.AreEqual(2, pages[0].Count); }
public async Task GetValuesSample() { #region Snippet:PageableOperationGetValues // create a client var client = new TextAnalyticsClient(new Uri("http://example.com"), new DefaultAzureCredential()); var document = new List <string>() { "document with information" }; // Start the operation AnalyzeHealthcareEntitiesOperation healthOperation = client.StartAnalyzeHealthcareEntities(document); await healthOperation.WaitForCompletionAsync(); foreach (AnalyzeHealthcareEntitiesResultCollection documentsInPage in healthOperation.GetValues()) { foreach (HealthcareEntity entity in documentsInPage[0].Entities) { Console.WriteLine($" Entity: {entity.Text}"); } } #endregion }
public async Task Sample7_AnalyzeHealthcareEntitiesBatchConvenience() { // 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:Sample7_AnalyzeHealthcareEntitiesBatchConvenience // 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 = client.StartAnalyzeHealthcareEntities(batchInput, "en", options); await healthOperation.WaitForCompletionAsync(); Console.WriteLine($"AnalyzeHealthcareEntities operation was completed"); // 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}"); // view operation results 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) { 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:"); // 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(""); } } Console.WriteLine(""); } } } }
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 static async Task RunAsync([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log) { //Extracting content type and url of the blob triggering the function var jsondata = JsonConvert.SerializeObject(eventGridEvent.Data); var tmp = new { contentType = "", url = "" }; var data = JsonConvert.DeserializeAnonymousType(jsondata, tmp); //Checking if the trigger was iniatiated for a WAV File. if (data.contentType == "audio/wav") { var audioUrl = data.url; string blobName = audioUrl.Split('/').Last(); string contosoStorageConnectionString = System.Environment.GetEnvironmentVariable("ContosoStorageConnectionString", EnvironmentVariableTarget.Process); string speechRegion = System.Environment.GetEnvironmentVariable("SpeechRegion", EnvironmentVariableTarget.Process); string speechKey = System.Environment.GetEnvironmentVariable("SpeechKey", EnvironmentVariableTarget.Process); string translatorKey = System.Environment.GetEnvironmentVariable("TranslatorKey", EnvironmentVariableTarget.Process); string translatorEndpoint = System.Environment.GetEnvironmentVariable("TranslatorEndpoint", EnvironmentVariableTarget.Process); string translatorLocation = System.Environment.GetEnvironmentVariable("TranslatorLocation", EnvironmentVariableTarget.Process); string cosmosEndpointUrl = System.Environment.GetEnvironmentVariable("CosmosDBEndpointUrl", EnvironmentVariableTarget.Process); string cosmosPrimaryKey = System.Environment.GetEnvironmentVariable("CosmosDBPrimaryKey", EnvironmentVariableTarget.Process); string textAnalyticsKey = System.Environment.GetEnvironmentVariable("TextAnalyticsKey", EnvironmentVariableTarget.Process); string textAnalyticsEndpoint = System.Environment.GetEnvironmentVariable("TextAnalyticsEndpoint", EnvironmentVariableTarget.Process); // Download audio file to a local temp directory var tempPath = System.IO.Path.GetTempFileName(); BlobContainerClient container = new BlobContainerClient(contosoStorageConnectionString, "audiorecordings"); BlobClient blob = container.GetBlobClient(blobName); await blob.DownloadToAsync(tempPath); var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion); speechConfig.SetProperty(PropertyId.SpeechServiceConnection_SingleLanguageIdPriority, "Latency"); // Audio Language Identification // Considering only two languages: English and Spanish // Languages supported for language detection : https://docs.microsoft.com/azure/cognitive-services/speech-service/language-support var autoDetectSourceLanguageConfig = AutoDetectSourceLanguageConfig.FromLanguages(new string[] { "en-US", "es-MX" }); string languageDetected = "en-US"; using (var audioInput = AudioConfig.FromWavFileInput(tempPath)) { using (var recognizer = new SourceLanguageRecognizer(speechConfig, autoDetectSourceLanguageConfig, audioInput)) { var result = await recognizer.RecognizeOnceAsync().ConfigureAwait(false); if (result.Reason == ResultReason.RecognizedSpeech) { var lidResult = AutoDetectSourceLanguageResult.FromResult(result); languageDetected = lidResult.Language; } } } speechConfig.SpeechRecognitionLanguage = languageDetected; // Audio Transcription StringBuilder sb = new StringBuilder(); using var audioConfig = AudioConfig.FromWavFileInput(tempPath); { using var recognizer = new SpeechRecognizer(speechConfig, audioConfig); { var stopRecognition = new TaskCompletionSource <int>(); recognizer.SessionStopped += (s, e) => { stopRecognition.TrySetResult(0); }; recognizer.Canceled += (s, e) => { stopRecognition.TrySetResult(0); }; recognizer.Recognized += (s, e) => { if (e.Result.Reason == ResultReason.RecognizedSpeech) { sb.Append(e.Result.Text); } else if (e.Result.Reason == ResultReason.NoMatch) { log.LogInformation($"NOMATCH: Speech could not be recognized."); } }; await recognizer.StartContinuousRecognitionAsync(); Task.WaitAny(new[] { stopRecognition.Task }); } } string transcribedText = sb.ToString(); // If transcription is in Spanish we will translate it to English if (!languageDetected.Contains("en")) { string route = $"/translate?api-version=3.0&to=en"; string textToTranslate = sb.ToString(); object[] body = new object[] { new { Text = textToTranslate } }; var requestBody = JsonConvert.SerializeObject(body); using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { request.Method = HttpMethod.Post; request.RequestUri = new Uri(translatorEndpoint + route); request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); request.Headers.Add("Ocp-Apim-Subscription-Key", translatorKey); request.Headers.Add("Ocp-Apim-Subscription-Region", translatorLocation); HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); var responseBody = await response.Content.ReadAsStringAsync(); List <Model.TranslatorService.Root> translatedDocuments = JsonConvert.DeserializeObject <List <Model.TranslatorService.Root> >(responseBody); transcribedText = translatedDocuments.FirstOrDefault().Translations.FirstOrDefault().Text; } } //Azure Text Analytics for Healthcare List <string> healthDocuments = new List <string> { transcribedText }; var textAnalyticsClient = new TextAnalyticsClient(new Uri(textAnalyticsEndpoint), new AzureKeyCredential(textAnalyticsKey)); AnalyzeHealthcareEntitiesOperation healthOperation = textAnalyticsClient.StartAnalyzeHealthcareEntities(healthDocuments, "en", new AnalyzeHealthcareEntitiesOptions { }); await healthOperation.WaitForCompletionAsync(); AnalyzeHealthcareEntitiesResult healthcareResult = healthOperation.GetValues().FirstOrDefault().FirstOrDefault(); //Insert documents into CosmosDB var cosmosClient = new CosmosClient(cosmosEndpointUrl, cosmosPrimaryKey); var cosmosDatabase = (await cosmosClient.CreateDatabaseIfNotExistsAsync("Contoso")).Database; var cosmosContainer = (await cosmosDatabase.CreateContainerIfNotExistsAsync("Transcriptions", "/id")).Container; Model.Transcription newTranscription = new Model.Transcription(); newTranscription.Id = Guid.NewGuid().ToString(); newTranscription.DocumentDate = new DateTime(int.Parse(blobName.Substring(0, 4)), int.Parse(blobName.Substring(4, 2)), int.Parse(blobName.Substring(6, 2))); newTranscription.FileName = blobName; newTranscription.TranscribedText = transcribedText; foreach (var item in healthcareResult.Entities) { newTranscription.HealthcareEntities.Add(new Model.HealthcareEntity() { Category = item.Category, Text = item.Text }); } try { ItemResponse <Model.Transcription> cosmosResponse = await cosmosContainer.CreateItemAsync(newTranscription, new PartitionKey(newTranscription.Id)); } catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.Conflict) { //Conflicting documents are silently ignored for demo purposes. } System.IO.File.Delete(tempPath); log.LogInformation(eventGridEvent.Data.ToString()); } }