Exemplo n.º 1
0
 def test_single_analyze_sentiment_bad_type_credentials(self, resource_group, location, text_analytics_account, text_analytics_account_key):
     with self.assertRaises(TypeError):
         response = single_analyze_sentiment(
             endpoint=text_analytics_account,
             credential=[],
             input_text="I was unhappy with the food at the restaurant.",
         )
    def analyze_sentiment(self):
        # [START single_analyze_sentiment]
        from azure.ai.textanalytics import single_analyze_sentiment, TextAnalyticsApiKeyCredential

        text = "I visited the restaurant last week. The portions were very generous. However, I did not like what " \
               "I ordered."

        result = single_analyze_sentiment(
            endpoint=self.endpoint,
            credential=TextAnalyticsApiKeyCredential(self.key),
            input_text=text,
            language="en"
        )

        print("Overall sentiment: {}".format(result.sentiment))
        print("Overall scores: positive={0:.3f}; neutral={1:.3f}; negative={2:.3f} \n".format(
            result.document_scores.positive,
            result.document_scores.neutral,
            result.document_scores.negative,
        ))

        for idx, sentence in enumerate(result.sentences):
            print("Sentence {} sentiment: {}".format(idx+1, sentence.sentiment))
            print("Offset: {}".format(sentence.offset))
            print("Length: {}".format(sentence.length))
            print("Sentence score: positive={0:.3f}; neutral={1:.3f}; negative={2:.3f} \n".format(
                sentence.sentence_scores.positive,
                sentence.sentence_scores.neutral,
                sentence.sentence_scores.negative,
            ))
def process_results(evt):
    # Check the result
    if evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
        print("Recognized: {}".format(evt.result.text))
        print()

        # Text Analytics, analyze the Speech to Text response in terms of sentiment.
        analytics_response = single_analyze_sentiment(
            endpoint=endpoint,
            credential=subscription_key,
            input_text=evt.result.text)
        print("Document Sentiment: {}".format(analytics_response.sentiment))
        print(
            "Overall scores: positive={0:.3f}; neutral={1:.3f}; negative={2:.3f} \n"
            .format(
                analytics_response.document_scores.positive,
                analytics_response.document_scores.neutral,
                analytics_response.document_scores.negative,
            ))
        return evt.result.text
    elif evt.result.reason == speechsdk.ResultReason.NoMatch:
        print("No speech could be recognized")
        print('Closing...')
        # The stop function is called when silent for 15 seconds.
        return stop_cb(evt)
    elif evt.result.reason == speechsdk.ResultReason.Canceled:
        cancellation_details = evt.result.cancellation_details
        print("Speech Recognition canceled: {}".format(
            cancellation_details.reason))
        if cancellation_details.reason == speechsdk.CancellationReason.Error:
            print("Error details: {}".format(
                cancellation_details.error_details))
Exemplo n.º 4
0
 def test_single_analyze_sentiment_empty_text_input(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=cognitiveservices_account,
             credential=cognitiveservices_account_key,
             input_text="",
         )
Exemplo n.º 5
0
 def test_single_analyze_sentiment_non_text_input(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
     with self.assertRaises(TypeError):
         response = single_analyze_sentiment(
             endpoint=cognitiveservices_account,
             credential=cognitiveservices_account_key,
             input_text={"id": "1", "text": "hello world"}
         )
Exemplo n.º 6
0
 def test_single_analyze_sentiment_none_credentials(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
     with self.assertRaises(ValueError):
         response = single_analyze_sentiment(
             endpoint=cognitiveservices_account,
             credential=None,
             input_text="I was unhappy with the food at the restaurant.",
         )
Exemplo n.º 7
0
 def test_single_analyze_sentiment_non_text_input(self, resource_group, location, text_analytics_account, text_analytics_account_key):
     with self.assertRaises(TypeError):
         response = single_analyze_sentiment(
             endpoint=text_analytics_account,
             credential=TextAnalyticsAPIKeyCredential(text_analytics_account_key),
             input_text={"id": "1", "text": "hello world"}
         )
Exemplo n.º 8
0
 def test_single_analyze_sentiment_bad_credentials(self, resource_group, location, text_analytics_account, text_analytics_account_key):
     with self.assertRaises(ClientAuthenticationError):
         response = single_analyze_sentiment(
             endpoint=text_analytics_account,
             credential=TextAnalyticsAPIKeyCredential("xxxxxxxxxxxx"),
             input_text="I was unhappy with the food at the restaurant.",
         )
Exemplo n.º 9
0
 def test_single_analyze_sentiment_empty_text_input(self, resource_group, location, text_analytics_account, text_analytics_account_key):
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=text_analytics_account,
             credential=TextAnalyticsAPIKeyCredential(text_analytics_account_key),
             input_text="",
         )
Exemplo n.º 10
0
 def test_single_analyze_sentiment_bad_language_hint(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=cognitiveservices_account,
             credential=cognitiveservices_account_key,
             input_text="I was unhappy with the food at the restaurant.",
             language="English"
         )
Exemplo n.º 11
0
 def test_single_analyze_sentiment_bad_language_hint(self, resource_group, location, text_analytics_account, text_analytics_account_key):
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=text_analytics_account,
             credential=TextAnalyticsAPIKeyCredential(text_analytics_account_key),
             input_text="I was unhappy with the food at the restaurant.",
             language="English"
         )
Exemplo n.º 12
0
 def test_single_analyze_sentiment_bad_model_version(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=cognitiveservices_account,
             credential=cognitiveservices_account_key,
             input_text="Microsoft was founded by Bill Gates.",
             language="en",
             model_version="old"
         )
Exemplo n.º 13
0
 def test_single_analyze_sentiment_too_many_chars(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
     text = ""
     for _ in range(5121):
         text += "x"
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=cognitiveservices_account,
             credential=cognitiveservices_account_key,
             input_text=text,
         )
Exemplo n.º 14
0
 def test_single_analyze_sentiment_too_many_chars(self, resource_group, location, text_analytics_account, text_analytics_account_key):
     text = ""
     for _ in range(5121):
         text += "x"
     with self.assertRaises(HttpResponseError):
         response = single_analyze_sentiment(
             endpoint=text_analytics_account,
             credential=TextAnalyticsAPIKeyCredential(text_analytics_account_key),
             input_text=text,
         )
Exemplo n.º 15
0
    def test_successful_single_analyze_sentiment(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
        response = single_analyze_sentiment(
            endpoint=cognitiveservices_account,
            credential=cognitiveservices_account_key,
            input_text="I was unhappy with the food at the restaurant.",
            language="en"
        )

        self.assertIsNotNone(response.id)
        self.assertEqual(response.sentiment, "negative")
        self.assertIsNotNone(response.document_scores)
        self.assertIsNotNone(response.sentences)
Exemplo n.º 16
0
    def test_single_analyze_sentiment_default_language(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
        def callback(resp):
            language_str = "\"language\": \"en\""
            language = resp.http_request.body.count(language_str)
            self.assertEqual(language, 1)

        response = single_analyze_sentiment(
            endpoint=cognitiveservices_account,
            credential=cognitiveservices_account_key,
            input_text="Este es un document escrito en Español.",
            response_hook=callback
        )
Exemplo n.º 17
0
    def test_single_analyze_sentiment_response_hook(self, resource_group, location, cognitiveservices_account, cognitiveservices_account_key):
        def callback(resp):
            self.assertIsNotNone(resp.statistics)
            self.assertIsNotNone(resp.model_version)

        response = single_analyze_sentiment(
            endpoint=cognitiveservices_account,
            credential=cognitiveservices_account_key,
            input_text="I was unhappy with the food at the restaurant.",
            show_stats=True,
            model_version="latest",
            response_hook=callback
        )
Exemplo n.º 18
0
    def test_single_analyze_sentiment_given_language(self, resource_group, location, text_analytics_account, text_analytics_account_key):
        def callback(resp):
            language_str = "\"language\": \"es\""
            language = resp.http_request.body.count(language_str)
            self.assertEqual(language, 1)

        response = single_analyze_sentiment(
            endpoint=text_analytics_account,
            credential=TextAnalyticsAPIKeyCredential(text_analytics_account_key),
            input_text="Este es un document escrito en Español.",
            language="es",
            response_hook=callback
        )
Exemplo n.º 19
0
def sent_analysis(tweets):
    # Check the data for the correct language
    concat_tweets = ""  # A long string containing all the tweet text, so that it only takes one call to analyze
    for tweet in tweets:

        concat_tweets += (tweet + " ")

    slicer = int((len(concat_tweets)) / 2)
    one = concat_tweets[0:slicer]
    two = concat_tweets[slicer:]

    # Performing analysis of all the text through ACS
    resp = single_analyze_sentiment(endpoint=ep,
                                    credential=key,
                                    input_text=one)
    resp2 = single_analyze_sentiment(endpoint=ep,
                                     credential=key,
                                     input_text=two)

    # Getting raw scores for the entire population of tweets (double)
    pop_pos = (resp.document_scores.positive +
               resp2.document_scores.positive) / 2
    pop_neg = (resp.document_scores.negative +
               resp2.document_scores.negative) / 2
    pop_neu = (resp.document_scores.neutral +
               resp2.document_scores.neutral) / 2
    pop_overall = resp.sentiment  # The overall sentiment is  a string, positive/neutral/negative
    # Converting the raw score to a percentage
    pop_pos_per = pop_pos * 100
    pop_neg_per = pop_neg * 100

    sentiments = {
        "sentiment": pop_overall,
        "positive": pop_pos,
        "negative": pop_neg,
        "neutral": pop_neu
    }
    return sentiments