Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing analyze sentiment method and helpers in language #2189

Merged
merged 3 commits into from
Aug 26, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/language-responses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,10 @@ Entity
.. automodule:: gcloud.language.entity
:members:
:show-inheritance:

Sentiment
~~~~~~~~~

.. automodule:: gcloud.language.sentiment
:members:
:show-inheritance:
17 changes: 17 additions & 0 deletions gcloud/language/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""

from gcloud.language.entity import Entity
from gcloud.language.sentiment import Sentiment


DEFAULT_LANGUAGE = 'en-US'
Expand Down Expand Up @@ -146,3 +147,19 @@ def analyze_entities(self):
method='POST', path='analyzeEntities', data=data)
return [Entity.from_api_repr(entity)
for entity in api_response['entities']]

def analyze_sentiment(self):
"""Analyze the sentiment in the current document.

.. _analyzeSentiment: https://cloud.google.com/natural-language/\
reference/rest/v1beta1/documents/analyzeSentiment

See `analyzeSentiment`_.

:rtype: :class:`.Sentiment`
:returns: The sentiment of the current document.
"""
data = {'document': self._to_dict()}
api_response = self.client.connection.api_request(
method='POST', path='analyzeSentiment', data=data)
return Sentiment.from_api_repr(api_response['documentSentiment'])
58 changes: 58 additions & 0 deletions gcloud/language/sentiment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Definition for Google Cloud Natural Language API sentiment.

Sentiment is the response to an ``analyzeSentiment`` request.
"""


class Sentiment(object):
"""A Google Cloud Natural Language API sentiment object.

.. _Sentiment message: https://cloud.google.com/natural-language/\
reference/rest/v1beta1/Sentiment
.. _Sentiment basics: https://cloud.google.com/natural-language/\
docs/basics#sentiment-analysis-values

See `Sentiment message`_ and `Sentiment basics`_.


:type polarity: float
:param polarity: Polarity of the sentiment in the ``[-1.0, 1.0]`` range.
Larger numbers represent more positive sentiments.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


:type magnitude: float
:param magnitude: A non-negative number in the ``[0, +inf)`` range, which
represents the absolute magnitude of sentiment
regardless of polarity (positive or negative).
"""

def __init__(self, polarity, magnitude):
self.polarity = polarity
self.magnitude = magnitude

@classmethod
def from_api_repr(cls, payload):
"""Convert an Sentiment from the JSON API into a :class:`Sentiment`.

:param payload: dict
:type payload: The value from the backend.

:rtype: :class:`Sentiment`
:returns: The sentiment parsed from the API representation.
"""
polarity = payload['polarity']
magnitude = payload['magnitude']
return cls(polarity, magnitude)
28 changes: 28 additions & 0 deletions gcloud/language/test_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,34 @@ def test_analyze_entities(self):
self.assertEqual(req['path'], 'analyzeEntities')
self.assertEqual(req['method'], 'POST')

def test_analyze_sentiment(self):
from gcloud.language.sentiment import Sentiment

content = 'All the pretty horses.'
polarity = 1
magnitude = 0.6
response = {
'documentSentiment': {
'polarity': polarity,
'magnitude': magnitude,
},
'language': 'en',
}
connection = _Connection(response)
client = _Client(connection=connection)
document = self._makeOne(client, content)

sentiment = document.analyze_sentiment()
self.assertIsInstance(sentiment, Sentiment)
self.assertEqual(sentiment.polarity, polarity)
self.assertEqual(sentiment.magnitude, magnitude)

# Verify the request.
self.assertEqual(len(connection._requested), 1)
req = connection._requested[0]
self.assertEqual(req['path'], 'analyzeSentiment')
self.assertEqual(req['method'], 'POST')


class _Connection(object):

Expand Down
44 changes: 44 additions & 0 deletions gcloud/language/test_sentiment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest


class TestSentiment(unittest.TestCase):

def _getTargetClass(self):
from gcloud.language.sentiment import Sentiment
return Sentiment

def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)

def test_constructor(self):
polarity = 1
magnitude = 2.3
sentiment = self._makeOne(polarity, magnitude)
self.assertEqual(sentiment.polarity, polarity)
self.assertEqual(sentiment.magnitude, magnitude)

def test_from_api_repr(self):
klass = self._getTargetClass()
polarity = -1
magnitude = 5.55
payload = {
'polarity': polarity,
'magnitude': magnitude,
}
sentiment = klass.from_api_repr(payload)
self.assertEqual(sentiment.polarity, polarity)
self.assertEqual(sentiment.magnitude, magnitude)
7 changes: 7 additions & 0 deletions system_tests/language.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,10 @@ def test_analyze_entities_from_blob(self):
document = Config.CLIENT.document_from_url(gcs_url)
entities = document.analyze_entities()
self._check_analyze_entities_result(entities)

def test_analyze_sentiment(self):
positive_msg = 'Jogging is fun'
document = Config.CLIENT.document_from_text(positive_msg)
sentiment = document.analyze_sentiment()
self.assertEqual(sentiment.polarity, 1)
self.assertTrue(0.5 < sentiment.magnitude < 1.5)

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.