コード例 #1
0
def main(config):
    endpoint = config["azure"]["endpoint"]
    key = config["azure"]["key"]

    print("Endpoint: " + endpoint)

    client = TextAnalyticsClient(endpoint=endpoint,
                                 credential=AzureKeyCredential(key),
                                 api_version="v3.1-preview.3")

    #documents = [
    #    {"id":"1", "language":"en" ,"text":"Subject is taking 100mg of ibuprofen twice daily"},
    #]

    # load sample documents from docs folder
    path = os.path.join(os.curdir, 'docs')
    reader = sample_reader.SampleReader(path)
    documents = reader.process()

    poller = client.begin_analyze_healthcare(documents, show_stats=True)
    result = poller.result()

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

    print("Results of Healthcare 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.links is not None:
                print("...Links:")
                for link in entity.links:
                    print("......ID: {}".format(link.id))
                    print("......Data source: {}".format(link.data_source))
        for relation in doc.relations:
            print("Relation:")
            print("...Source: {}".format(relation.source.text))
            print("...Target: {}".format(relation.target.text))
            print("...Type: {}".format(relation.relation_type))
            print("...Bidirectional: {}".format(relation.is_bidirectional))
        print("------------------------------------------")
    def alternative_document_input(self):
        from azure.core.credentials import AzureKeyCredential
        from azure.ai.textanalytics import TextAnalyticsClient
        text_analytics_client = TextAnalyticsClient(
            endpoint=self.endpoint, credential=AzureKeyCredential(self.key))

        documents = [{
            "id": "0",
            "language": "en",
            "text": "I had the best day of my life."
        }, {
            "id":
            "1",
            "language":
            "en",
            "text":
            "This was a waste of my time. The speaker put me to sleep."
        }, {
            "id": "2",
            "language": "es",
            "text": "No tengo dinero ni nada que dar..."
        }, {
            "id":
            "3",
            "language":
            "fr",
            "text":
            "L'hôtel n'était pas très confortable. L'éclairage était trop sombre."
        }]

        result = text_analytics_client.detect_language(documents)

        for idx, doc in enumerate(result):
            if not doc.is_error:
                print("Document text: {}".format(documents[idx]))
                print("Language detected: {}".format(
                    doc.primary_language.name))
                print("ISO6391 name: {}".format(
                    doc.primary_language.iso6391_name))
                print("Confidence score: {}\n".format(
                    doc.primary_language.score))
            if doc.is_error:
                print(doc.id, doc.error)
コード例 #3
0
def sample_detect_language():
    print(
        "In this sample we own a hotel with customers from all around the globe. We want to eventually "
        "translate these reviews into English so our manager can read them. However, we first need to know which language "
        "they are in for more accurate translation. This is the step we will be covering in this sample\n"
    )
    # [START detect_language]
    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 = [
        """
        The concierge Paulette was extremely helpful. Sadly when we arrived the elevator was broken, but with Paulette's help we barely noticed this inconvenience.
        She arranged for our baggage to be brought up to our room with no extra charge and gave us a free meal to refurbish all of the calories we lost from
        walking up the stairs :). Can't say enough good things about my experience!
        """, """
        最近由于工作压力太大,我们决定去富酒店度假。那儿的温泉实在太舒服了,我跟我丈夫都完全恢复了工作前的青春精神!加油!
        """
    ]

    result = text_analytics_client.detect_language(documents)
    reviewed_docs = [doc for doc in result if not doc.is_error]

    print("Let's see what language each review is in!")

    for idx, doc in enumerate(reviewed_docs):
        print("Review #{} is in '{}', which has ISO639-1 name '{}'\n".format(
            idx, doc.primary_language.name, doc.primary_language.iso6391_name))
        if doc.is_error:
            print(doc.id, doc.error)
    # [END detect_language]
    print(
        "When actually storing the reviews, we want to map the review to their ISO639-1 name "
        "so everything is more standardized")

    review_to_language = {}
    for idx, doc in enumerate(reviewed_docs):
        review_to_language[documents[idx]] = doc.primary_language.iso6391_name
コード例 #4
0
    def recognize_entities(self):
        # [START batch_recognize_entities]
        from azure.ai.textanalytics import TextAnalyticsClient
        text_analytics_client = TextAnalyticsClient(endpoint=self.endpoint,
                                                    credential=self.key)
        documents = [
            "Microsoft was founded by Bill Gates and Paul Allen.",
            "I had a wonderful trip to Seattle last week.",
            "I visited the Space Needle 2 times.",
        ]

        result = text_analytics_client.recognize_entities(documents)
        docs = [doc for doc in result if not doc.is_error]

        for idx, doc in enumerate(docs):
            print("\nDocument text: {}".format(documents[idx]))
            for entity in doc.entities:
                print("Entity: \t", entity.text, "\tType: \t", entity.type,
                      "\tConfidence Score: \t", round(entity.score, 3))
コード例 #5
0
    def alternative_scenario_recognize_entities(self):
        """This sample demonstrates how to retrieve batch statistics, the
        model version used, and the raw response returned from the service.

        It additionally shows an alternative way to pass in the input documents
        using a list[TextDocumentInput] and supplying your own IDs and language hints along
        with the text.
        """
        from azure.ai.textanalytics import TextAnalyticsClient, TextAnalyticsAPIKeyCredential
        text_analytics_client = TextAnalyticsClient(
            endpoint=self.endpoint,
            credential=TextAnalyticsAPIKeyCredential(self.key))

        documents = [
            {
                "id": "0",
                "language": "en",
                "text": "Microsoft was founded by Bill Gates and Paul Allen."
            },
            {
                "id": "1",
                "language": "de",
                "text": "I had a wonderful trip to Seattle last week."
            },
            {
                "id": "2",
                "language": "es",
                "text": "I visited the Space Needle 2 times."
            },
        ]

        extras = []

        def callback(resp):
            extras.append(resp.statistics)
            extras.append(resp.model_version)
            extras.append(resp.raw_response)

        result = text_analytics_client.recognize_entities(
            documents,
            show_stats=True,
            model_version="latest",
            response_hook=callback)
コード例 #6
0
    def test_language_kwarg_english(self, resource_group, location,
                                    text_analytics_account,
                                    text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        def callback(response):
            language_str = "\"language\": \"en\""
            self.assertEqual(response.http_request.body.count(language_str), 1)
            self.assertIsNotNone(response.model_version)
            self.assertIsNotNone(response.statistics)

        res = text_analytics.recognize_pii_entities(
            inputs=["Bill Gates is the CEO of Microsoft."],
            model_version="latest",
            show_stats=True,
            language="en",
            raw_response_hook=callback)
コード例 #7
0
    def test_some_errors_extract_key_phrases(self, resource_group, location,
                                             text_analytics_account,
                                             text_analytics_account_key):
        text_analytics = TextAnalyticsClient(text_analytics_account,
                                             text_analytics_account_key)

        docs = [{
            "id": "1",
            "language": "English",
            "text": "Microsoft was founded by Bill Gates and Paul Allen"
        }, {
            "id": "2",
            "language": "es",
            "text": "Microsoft fue fundado por Bill Gates y Paul Allen"
        }]

        response = text_analytics.extract_key_phrases(docs)
        self.assertTrue(response[0].is_error)
        self.assertFalse(response[1].is_error)
コード例 #8
0
    def test_passing_only_string(self, resource_group, location,
                                 text_analytics_account,
                                 text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        docs = [
            u"Microsoft was founded by Bill Gates and Paul Allen.",
            u"I did not like the hotel we stayed at. It was too expensive.",
            u"The restaurant had really good food. I recommend you try it.",
            u""
        ]

        response = text_analytics.analyze_sentiment(docs)
        self.assertEqual(response[0].sentiment, "neutral")
        self.assertEqual(response[1].sentiment, "negative")
        self.assertEqual(response[2].sentiment, "positive")
        self.assertTrue(response[3].is_error)
コード例 #9
0
    def test_passing_only_string(self, resource_group, location,
                                 text_analytics_account,
                                 text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        docs = [
            u"I should take my cat to the veterinarian.",
            u"Este es un document escrito en Español.", u"猫は幸せ",
            u"Fahrt nach Stuttgart und dann zum Hotel zu Fu.", u""
        ]

        response = text_analytics.detect_language(docs)
        self.assertEqual(response[0].primary_language.name, "English")
        self.assertEqual(response[1].primary_language.name, "Spanish")
        self.assertEqual(response[2].primary_language.name, "Japanese")
        self.assertEqual(response[3].primary_language.name, "German")
        self.assertTrue(response[4].is_error)
コード例 #10
0
    def test_input_with_all_errors(self, resource_group, location,
                                   text_analytics_account,
                                   text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        docs = [{
            "id": "1",
            "text": ""
        }, {
            "id": "2",
            "language": "Spanish",
            "text": "Microsoft fue fundado por Bill Gates y Paul Allen"
        }]

        response = text_analytics.recognize_linked_entities(docs)
        self.assertTrue(response[0].is_error)
        self.assertTrue(response[1].is_error)
コード例 #11
0
    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, api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3)

        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(docs, polling_interval=self._interval()).result()
        self.assertIsNotNone(response)

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

        credential.update(text_analytics_account_key)  # Authenticate successfully again
        response = client.begin_analyze_healthcare(docs, polling_interval=self._interval()).result()
        self.assertIsNotNone(response)
コード例 #12
0
    def recognize_pii_entities(self):
        # [START batch_recognize_pii_entities]
        from azure.ai.textanalytics import TextAnalyticsClient, TextAnalyticsApiKeyCredential
        text_analytics_client = TextAnalyticsClient(endpoint=self.endpoint, credential=TextAnalyticsApiKeyCredential(self.key))
        documents = [
            "The employee's SSN is 555-55-5555.",
            "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.",
            "Is 998.214.865-68 your Brazilian CPF number?"
        ]

        result = text_analytics_client.recognize_pii_entities(documents)
        docs = [doc for doc in result if not doc.is_error]

        for idx, doc in enumerate(docs):
            print("Document text: {}".format(documents[idx]))
            for entity in doc.entities:
                print("Entity: {}".format(entity.text))
                print("Category: {}".format(entity.category))
                print("Confidence Score: {}\n".format(entity.score))
コード例 #13
0
    def authentication_with_azure_active_directory(self):
        """DefaultAzureCredential will use the values from the environment
        variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
        """
        # [START create_ta_client_with_aad]
        from azure.ai.textanalytics import TextAnalyticsClient
        from azure.identity import DefaultAzureCredential

        endpoint = os.getenv("AZURE_TEXT_ANALYTICS_ENDPOINT")
        credential = DefaultAzureCredential()

        text_analytics_client = TextAnalyticsClient(endpoint, credential=credential)
        # [END create_ta_client_with_aad]

        doc = ["I need to take my cat to the veterinarian."]
        result = text_analytics_client.detect_language(doc)

        print("Language detected: {}".format(result[0].primary_language.name))
        print("Confidence score: {}".format(result[0].primary_language.score))
コード例 #14
0
    def test_bad_model_version_error(self, resource_group, location,
                                     text_analytics_account,
                                     text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        docs = [{
            "id": "1",
            "language": "english",
            "text": "I did not like the hotel we stayed at."
        }]

        try:
            result = text_analytics.recognize_pii_entities(docs,
                                                           model_version="bad")
        except HttpResponseError as err:
            self.assertEqual(err.error.code, "InvalidRequest")
            self.assertIsNotNone(err.error.message)
コード例 #15
0
 def test_duplicate_ids_error(self, resource_group, location,
                              text_analytics_account,
                              text_analytics_account_key):
     text_analytics = TextAnalyticsClient(
         text_analytics_account,
         TextAnalyticsApiKeyCredential(text_analytics_account_key))
     # Duplicate Ids
     docs = [{
         "id": "1",
         "text": "hello world"
     }, {
         "id": "1",
         "text": "I did not like the hotel we stayed at."
     }]
     try:
         result = text_analytics.recognize_pii_entities(docs)
     except HttpResponseError as err:
         self.assertEqual(err.error.code, "InvalidDocument")
         self.assertIsNotNone(err.error.message)
コード例 #16
0
    def test_some_errors_recognize_linked_entities(self, resource_group,
                                                   location,
                                                   text_analytics_account,
                                                   text_analytics_account_key):
        text_analytics = TextAnalyticsClient(text_analytics_account,
                                             text_analytics_account_key)

        docs = [{
            "id": "1",
            "text": ""
        }, {
            "id": "2",
            "language": "es",
            "text": "Microsoft fue fundado por Bill Gates y Paul Allen"
        }]

        response = text_analytics.recognize_linked_entities(docs)
        self.assertTrue(response[0].is_error)
        self.assertFalse(response[1].is_error)
コード例 #17
0
    def test_all_errors_extract_key_phrases(self, resource_group, location,
                                            cognitiveservices_account,
                                            cognitiveservices_account_key):
        text_analytics = TextAnalyticsClient(cognitiveservices_account,
                                             cognitiveservices_account_key)

        docs = [{
            "id": "1",
            "language": "English",
            "text": "Microsoft was founded by Bill Gates and Paul Allen"
        }, {
            "id": "2",
            "language": "es",
            "text": ""
        }]

        response = text_analytics.extract_key_phrases(docs)
        self.assertTrue(response[0].is_error)
        self.assertTrue(response[1].is_error)
コード例 #18
0
    def test_input_with_all_errors(self, resource_group, location,
                                   text_analytics_account,
                                   text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        docs = [{
            "id": "1",
            "language": "es",
            "text": "hola"
        }, {
            "id": "2",
            "text": ""
        }]

        response = text_analytics.recognize_pii_entities(docs)
        self.assertTrue(response[0].is_error)
        self.assertTrue(response[1].is_error)
コード例 #19
0
    def test_country_hint_kwarg(self, resource_group, location,
                                text_analytics_account,
                                text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        def callback(response):
            country_str = "\"countryHint\": \"ES\""
            self.assertEqual(response.http_request.body.count(country_str), 1)
            self.assertIsNotNone(response.model_version)
            self.assertIsNotNone(response.statistics)

        res = text_analytics.detect_language(
            documents=["this is written in english"],
            model_version="latest",
            show_stats=True,
            country_hint="ES",
            raw_response_hook=callback)
コード例 #20
0
    def alternative_scenario_recognize_pii_entities(self):
        """This sample demonstrates how to retrieve batch statistics, the
        model version used, and the raw response returned from the service.

        It additionally shows an alternative way to pass in the input documents
        using a list[TextDocumentInput] and supplying your own IDs and language hints along
        with the text.
        """
        from azure.ai.textanalytics import TextAnalyticsClient, TextAnalyticsAPIKeyCredential
        text_analytics_client = TextAnalyticsClient(
            endpoint=self.endpoint,
            credential=TextAnalyticsAPIKeyCredential(self.key))

        documents = [{
            "id": "0",
            "language": "en",
            "text": "The employee's SSN is 555-55-5555."
        }, {
            "id":
            "1",
            "language":
            "en",
            "text":
            "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."
        }, {
            "id": "2",
            "language": "en",
            "text": "Is 998.214.865-68 your Brazilian CPF number?"
        }]

        extras = []

        def callback(resp):
            extras.append(resp.statistics)
            extras.append(resp.model_version)
            extras.append(resp.raw_response)

        result = text_analytics_client.recognize_pii_entities(
            documents,
            show_stats=True,
            model_version="latest",
            response_hook=callback)
コード例 #21
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.")
コード例 #22
0
    def analyze_healthcare(self):
        # [START analyze_healthcare]
        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),
            api_version="v3.1-preview.3")

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

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

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

        print("Results of Healthcare 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.links is not None:
                    print("...Links:")
                    for link in entity.links:
                        print("......ID: {}".format(link.id))
                        print("......Data source: {}".format(link.data_source))
            for relation in doc.relations:
                print("Relation:")
                print("...Source: {}".format(relation.source.text))
                print("...Target: {}".format(relation.target.text))
                print("...Type: {}".format(relation.relation_type))
                print("...Bidirectional: {}".format(relation.is_bidirectional))
            print("------------------------------------------")
コード例 #23
0
    def analyze_sentiment(self):
        # [START batch_analyze_sentiment]
        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 = [
            "I had the best day of my life.",
            "This was a waste of my time. The speaker put me to sleep.",
            "No tengo dinero ni nada que dar...",
            "L'hôtel n'était pas très confortable. L'éclairage était trop sombre."
        ]

        result = text_analytics_client.analyze_sentiment(documents)
        docs = [doc for doc in result if not doc.is_error]

        for idx, doc in enumerate(docs):
            print("Document text: {}".format(documents[idx]))
            print("Overall sentiment: {}".format(doc.sentiment))
            # [END batch_analyze_sentiment]
            print(
                "Overall confidence scores: positive={}; neutral={}; negative={} \n"
                .format(
                    doc.confidence_scores.positive,
                    doc.confidence_scores.neutral,
                    doc.confidence_scores.negative,
                ))
            for sentence in doc.sentences:
                print("Sentence '{}' has sentiment: {}".format(
                    sentence.text, sentence.sentiment))
                print(
                    "Sentence confidence scores: positive={}; neutral={}; negative={}"
                    .format(
                        sentence.confidence_scores.positive,
                        sentence.confidence_scores.neutral,
                        sentence.confidence_scores.negative,
                    ))
            print("------------------------------------")
コード例 #24
0
    def test_client_passed_default_country_hint(self, resource_group, location, text_analytics_account, text_analytics_account_key):
        text_analytics = TextAnalyticsClient(text_analytics_account, AzureKeyCredential(text_analytics_account_key), default_country_hint="CA")

        def callback(resp):
            country_str = "\"countryHint\": \"CA\""
            country = resp.http_request.body.count(country_str)
            self.assertEqual(country, 3)

        def callback_2(resp):
            country_str = "\"countryHint\": \"DE\""
            country = resp.http_request.body.count(country_str)
            self.assertEqual(country, 3)

        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 = text_analytics.detect_language(docs, raw_response_hook=callback)
        response = text_analytics.detect_language(docs, country_hint="DE", raw_response_hook=callback_2)
        response = text_analytics.detect_language(docs, raw_response_hook=callback)
コード例 #25
0
    def test_input_with_all_errors(self, resource_group, location,
                                   text_analytics_account,
                                   text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        docs = [{
            "id": "1",
            "language": "English",
            "text": "Microsoft was founded by Bill Gates and Paul Allen"
        }, {
            "id": "2",
            "language": "es",
            "text": ""
        }]

        response = text_analytics.extract_key_phrases(docs)
        self.assertTrue(response[0].is_error)
        self.assertTrue(response[1].is_error)
コード例 #26
0
    def test_active_directory_auth(self):
        token = self.generate_oauth_token()
        endpoint = self.get_oauth_endpoint()
        text_analytics = TextAnalyticsClient(endpoint, token)

        docs = [{
            "id": "1",
            "text": "I should take my cat to the veterinarian."
        }, {
            "id": "2",
            "text": "Este es un document escrito en Español."
        }, {
            "id": "3",
            "text": "猫は幸せ"
        }, {
            "id": "4",
            "text": "Fahrt nach Stuttgart und dann zum Hotel zu Fu."
        }]

        response = text_analytics.detect_language(docs)
コード例 #27
0
    def test_whole_batch_dont_use_country_hint(self, resource_group, location,
                                               cognitiveservices_account,
                                               cognitiveservices_account_key):
        text_analytics = TextAnalyticsClient(cognitiveservices_account,
                                             cognitiveservices_account_key)

        def callback(resp):
            country_str = "\"countryHint\": \"\""
            country = resp.http_request.body.count(country_str)
            self.assertEqual(country, 3)

        docs = [
            u"This was the best day of my life.",
            u"I did not like the hotel we stayed it. It was too expensive.",
            u"The restaurant was not as good as I hoped."
        ]

        response = text_analytics.detect_languages(docs,
                                                   country_hint="",
                                                   response_hook=callback)
コード例 #28
0
    def test_whole_batch_dont_use_language_hint(self, resource_group, location,
                                                text_analytics_account,
                                                text_analytics_account_key):
        text_analytics = TextAnalyticsClient(
            text_analytics_account,
            TextAnalyticsApiKeyCredential(text_analytics_account_key))

        def callback(resp):
            language_str = "\"language\": \"\""
            language = resp.http_request.body.count(language_str)
            self.assertEqual(language, 3)

        docs = [
            u"This was the best day of my life.",
            u"I did not like the hotel we stayed at. It was too expensive.",
            u"The restaurant was not as good as I hoped."
        ]

        response = text_analytics.recognize_pii_entities(
            docs, language="", raw_response_hook=callback)
コード例 #29
0
    def test_whole_batch_language_hint(self, resource_group, location,
                                       cognitiveservices_account,
                                       cognitiveservices_account_key):
        text_analytics = TextAnalyticsClient(cognitiveservices_account,
                                             cognitiveservices_account_key)

        def callback(resp):
            language_str = "\"language\": \"fr\""
            language = resp.http_request.body.count(language_str)
            self.assertEqual(language, 3)

        docs = [
            u"This was the best day of my life.",
            u"I did not like the hotel we stayed it. It was too expensive.",
            u"The restaurant was not as good as I hoped."
        ]

        response = text_analytics.analyze_sentiment(docs,
                                                    language="fr",
                                                    response_hook=callback)
コード例 #30
0
    def test_client_passed_default_language_hint(self, resource_group, location, text_analytics_account, text_analytics_account_key):
        text_analytics = TextAnalyticsClient(text_analytics_account, TextAnalyticsApiKeyCredential(text_analytics_account_key), default_language="es")

        def callback(resp):
            language_str = "\"language\": \"es\""
            language = resp.http_request.body.count(language_str)
            self.assertEqual(language, 3)

        def callback_2(resp):
            language_str = "\"language\": \"en\""
            language = resp.http_request.body.count(language_str)
            self.assertEqual(language, 3)

        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 = text_analytics.analyze_sentiment(docs, raw_response_hook=callback)
        response = text_analytics.analyze_sentiment(docs, language="en", raw_response_hook=callback_2)
        response = text_analytics.analyze_sentiment(docs, raw_response_hook=callback)