def test_rotate_subscription_key(self, resource_group, location,
                                     text_analytics_account,
                                     text_analytics_account_key):

        credential = AzureKeyCredential(text_analytics_account_key)
        client = TextAnalyticsClient(text_analytics_account, credential)

        docs = [{
            "id": "1",
            "text": "I will go to the park."
        }, {
            "id": "2",
            "text": "I did not like the hotel we stayed at."
        }, {
            "id": "3",
            "text": "The restaurant had really good food."
        }]

        response = client.begin_analyze_healthcare_entities(
            docs, polling_interval=self._interval()).result()
        self.assertIsNotNone(response)

        credential.update("xxx")  # Make authentication fail
        with self.assertRaises(ClientAuthenticationError):
            response = client.begin_analyze_healthcare_entities(
                docs, polling_interval=self._interval()).result()

        credential.update(
            text_analytics_account_key)  # Authenticate successfully again
        response = client.begin_analyze_healthcare_entities(
            docs, polling_interval=self._interval()).result()
        self.assertIsNotNone(response)
    def analyze_healthcare_entities(self):
        # [START analyze_healthcare_entities]
        from azure.core.credentials import AzureKeyCredential
        from azure.ai.textanalytics import TextAnalyticsClient

        endpoint = os.environ["AZURE_TEXT_ANALYTICS_ENDPOINT"]
        key = os.environ["AZURE_TEXT_ANALYTICS_KEY"]

        text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=AzureKeyCredential(key),
        )

        documents = ["Subject is taking 100mg of ibuprofen twice daily"]

        poller = text_analytics_client.begin_analyze_healthcare_entities(
            documents, show_stats=True)
        result = poller.result()

        docs = [doc for doc in result if not doc.is_error]

        print("Results of Healthcare Entities Analysis:")
        for idx, doc in enumerate(docs):
            for entity in doc.entities:
                print("Entity: {}".format(entity.text))
                print("...Category: {}".format(entity.category))
                print("...Subcategory: {}".format(entity.subcategory))
                print("...Offset: {}".format(entity.offset))
                print("...Confidence score: {}".format(
                    entity.confidence_score))
                if entity.data_sources is not None:
                    print("...Data Sources:")
                    for data_source in entity.data_sources:
                        print("......Entity ID: {}".format(
                            data_source.entity_id))
                        print("......Name: {}".format(data_source.name))
                if len(entity.related_entities) > 0:
                    print("...Related Entities:")
                    for related_entity, relation_type in entity.related_entities.items(
                    ):
                        print("......Entity Text: {}".format(
                            related_entity.text))
                        print("......Relation Type: {}".format(relation_type))
            print("------------------------------------------")
예제 #3
0
    def analyze_healthcare_entities_with_cancellation(self):
        # [START analyze_healthcare_entities_with_cancellation]
        from azure.core.credentials import AzureKeyCredential
        from azure.ai.textanalytics import TextAnalyticsClient

        endpoint = os.environ["AZURE_TEXT_ANALYTICS_ENDPOINT"]
        key = os.environ["AZURE_TEXT_ANALYTICS_KEY"]

        text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=AzureKeyCredential(key),
        )

        documents = [
            "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."
        ]

        poller = text_analytics_client.begin_analyze_healthcare_entities(
            documents)

        try:
            cancellation_poller = poller.cancel()
            cancellation_poller.wait()

        except HttpResponseError as e:
            # If the operation has already reached a terminal state it cannot be cancelled.
            print(e)

        else:
            print("Healthcare entities analysis was successfully cancelled.")
    def analyze_healthcare_entities(self):

        print(
            "In this sample we will be combing through the prescriptions our pharmacy has fulfilled "
            "so we can catalog how much inventory we have"
        )
        print(
            "We start out with a list of prescription documents. "
            "To simplify matters, we will assume all dosages are in units of mg."
        )

        # [START analyze_healthcare_entities]
        import re
        from azure.core.credentials import AzureKeyCredential
        from azure.ai.textanalytics import TextAnalyticsClient
        from collections import defaultdict

        endpoint = os.environ["AZURE_TEXT_ANALYTICS_ENDPOINT"]
        key = os.environ["AZURE_TEXT_ANALYTICS_KEY"]

        text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=AzureKeyCredential(key),
        )

        documents = [
            """
            Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take
            10 mg of Zocor.
            """,
            """
            Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.
            """
        ]

        poller = text_analytics_client.begin_analyze_healthcare_entities(documents)
        result = poller.result()

        docs = [doc for doc in result if not doc.is_error]

        print(
            "In order to find the total dosage for every mentioned medication, "
            "let's create a dict, mapping medication name -> total dosage. "
        )

        medication_to_dosage = defaultdict(int)

        print(
            "We will start off by extracting all of the dosage entities."
        )

        dosage_entities = [
            entity
            for doc in docs
            for entity in doc.entities
            if entity.category == "Dosage"
        ]

        print(
            "Now we traverse the related entities of each dosage entity. "
            "We are looking for entities that are related by 'DosageOfMedication'. "
            "After that, we're done!"
        )
        for dosage in dosage_entities:
            dosage_value = int(re.findall(r"\d+", dosage.text)[0]) # we find the numbers in the dosage
            for related_entity, relation_type in dosage.related_entities.items():
                if relation_type == "DosageOfMedication":
                    medication_to_dosage[related_entity.text] += dosage_value

        [
            print("We have fulfilled '{}' total mg of '{}'".format(
                dosage, medication
            ))
            for medication, dosage in medication_to_dosage.items()
        ]
    def analyze_healthcare_entities(self):

        print(
            "In this sample we will be combing through the prescriptions our pharmacy has fulfilled "
            "so we can catalog how much inventory we have")
        print("We start out with a list of prescription documents.")

        # [START analyze_healthcare_entities]
        import os
        from azure.core.credentials import AzureKeyCredential
        from azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelationType, HealthcareEntityRelationRoleType

        endpoint = os.environ["AZURE_TEXT_ANALYTICS_ENDPOINT"]
        key = os.environ["AZURE_TEXT_ANALYTICS_KEY"]

        text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint,
            credential=AzureKeyCredential(key),
        )

        documents = [
            """
            Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take
            10 mg of Zocor.
            """, """
            Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.
            """
        ]

        poller = text_analytics_client.begin_analyze_healthcare_entities(
            documents)
        result = poller.result()

        docs = [doc for doc in result if not doc.is_error]

        print("Let's first visualize the outputted healthcare result:")
        for idx, doc in enumerate(docs):
            for entity in doc.entities:
                print("Entity: {}".format(entity.text))
                print("...Normalized Text: {}".format(entity.normalized_text))
                print("...Category: {}".format(entity.category))
                print("...Subcategory: {}".format(entity.subcategory))
                print("...Offset: {}".format(entity.offset))
                print("...Confidence score: {}".format(
                    entity.confidence_score))
                if entity.data_sources is not None:
                    print("...Data Sources:")
                    for data_source in entity.data_sources:
                        print("......Entity ID: {}".format(
                            data_source.entity_id))
                        print("......Name: {}".format(data_source.name))
                if entity.assertion is not None:
                    print("...Assertion:")
                    print("......Conditionality: {}".format(
                        entity.assertion.conditionality))
                    print("......Certainty: {}".format(
                        entity.assertion.certainty))
                    print("......Association: {}".format(
                        entity.assertion.association))
            for relation in doc.entity_relations:
                print("Relation of type: {} has the following roles".format(
                    relation.relation_type))
                for role in relation.roles:
                    print("...Role '{}' with entity '{}'".format(
                        role.name, role.entity.text))
            print("------------------------------------------")

        print(
            "Now, let's get all of medication dosage relations from the documents"
        )
        dosage_of_medication_relations = [
            entity_relation for doc in docs
            for entity_relation in doc.entity_relations
            if entity_relation.relation_type ==
            HealthcareEntityRelationType.DOSAGE_OF_MEDICATION
        ]
        # [END analyze_healthcare_entities]

        print(
            "Now, I will create a dictionary of medication to total dosage. "
            "I will use a regex to extract the dosage amount. For simplicity sake, I will assume "
            "all dosages are represented with numbers and have mg unit.")
        import re
        from collections import defaultdict

        medication_to_dosage = defaultdict(int)

        for relation in dosage_of_medication_relations:
            # The DosageOfMedication relation should only contain the dosage and medication roles

            dosage_role = next(
                iter(
                    filter(
                        lambda x: x.name == HealthcareEntityRelationRoleType.
                        DOSAGE, relation.roles)))
            medication_role = next(
                iter(
                    filter(
                        lambda x: x.name == HealthcareEntityRelationRoleType.
                        MEDICATION, relation.roles)))

            try:
                dosage_value = int(
                    re.findall(r"\d+", dosage_role.entity.text)
                    [0])  # we find the numbers in the dosage
                medication_to_dosage[
                    medication_role.entity.text] += dosage_value
            except StopIteration:
                # Error handling for if there's no dosage in numbers.
                pass

        for medication, dosage in medication_to_dosage.items():
            print("We have fulfilled '{}' total mg of '{}'".format(
                dosage, medication))