Skip to content
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
42 changes: 37 additions & 5 deletions examples/tone_analyzer_v3.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,13 +1,45 @@
import json
import os
from os.path import join, dirname
from watson_developer_cloud import ToneAnalyzerV3


tone_analyzer = ToneAnalyzerV3(
username='YOUR SERVICE USERNAME',
password='YOUR SERVICE PASSWORD',
version='2016-02-11')

print(json.dumps(tone_analyzer.tone(text='I am very happy'), indent=2))
version='2016-05-19')

utterances = [{'text': 'I am very happy', 'user': 'glenn'}]
print("\ntone_chat() example 1:\n")
utterances = [{'text': 'I am very happy.', 'user': 'glenn'},
{'text': 'It is a good day.', 'user': 'glenn'}]
print(json.dumps(tone_analyzer.tone_chat(utterances), indent=2))

print("\ntone() example 1:\n")
print(json.dumps(tone_analyzer.tone(text='I am very happy. It is a good day.'),
indent=2))

print("\ntone() example 2:\n")
with open(join(dirname(__file__),
'../resources/tone-example.json')) as tone_json:
tone = tone_analyzer.tone(json.load(tone_json)['text'], 'emotion')
print(json.dumps(tone, indent=2))

print("\ntone() example 3:\n")
with open(join(dirname(__file__),
'../resources/tone-example.json')) as tone_json:
tone = tone_analyzer.tone(json.load(tone_json)['text'], 'emotion',
True, 'text/plain')
print(json.dumps(tone, indent=2))

print("\ntone() example 4:\n")
with open(join(dirname(__file__),
'../resources/tone-example.json')) as tone_json:
tone = tone_analyzer.tone(json.load(tone_json), 'emotion',
content_type='application/json', )
print(json.dumps(tone, indent=2))

print("\ntone() example 5:\n")
with open(join(dirname(__file__),
'../resources/tone-example-html.json')) as tone_json:
tone = tone_analyzer.tone(json.load(tone_json)['text'], 'emotion',
content_type='text/html')
print(json.dumps(tone, indent=2))
3 changes: 3 additions & 0 deletions resources/tone-example-html.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"text": "<p>Team, I know that times are tough!</p> <p>Product sales have been disappointing for the past three quarters.</p> <p>We have a competitive product, but <b>we need to do a better job of selling it!</b></p>"
}
3 changes: 3 additions & 0 deletions resources/tone-example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"text": "Team, I know that times are tough! Product sales have been disappointing for the past three quarters. We have a competitive product, but we need to do a better job of selling it!"
}
30 changes: 29 additions & 1 deletion test/test_tone_analyzer_v3.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,35 @@ def test_tone_with_args():
username="username", password="password")
tone_analyzer.tone(tone_text.read(), tones="social", sentences=False)

assert responses.calls[0].request.url.split('?')[0] == tone_url
# Compare args. Order is not deterministic!
actualArgs = {}
for arg in responses.calls[0].request.url.split('?')[1].split('&'):
actualArgs[arg.split('=')[0]] = arg.split('=')[1]
assert actualArgs == tone_args
assert responses.calls[0].response.text == tone_response
assert len(responses.calls) == 1


@responses.activate
## Invoking tone() with some modifiers specified as positional parameters: tones are emotion and social, and sentences is false
def test_tone():
tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone'
tone_args = { 'version': '2016-05-19', 'tones': 'emotion%2Csocial', 'sentences': 'false' }
tone_response = None
with open(os.path.join(os.path.dirname(__file__), '../resources/tone-v3-expect1.json')) as response_json:
tone_response = response_json.read()

responses.add(responses.POST, tone_url,
body=tone_response, status=200,
content_type='application/json')

with open(os.path.join(os.path.dirname(__file__), '../resources/personality.txt')) as tone_text:
tone_analyzer = watson_developer_cloud.ToneAnalyzerV3("2016-05-19",
username="username", password="password")
tone_analyzer.tone(tone_text.read(), 'emotion,social', False)

assert responses.calls[0].request.url.split('?')[0] == tone_url
assert responses.calls[0].request.url.split('?')[0] == tone_url
# Compare args. Order is not deterministic!
actualArgs = {}
for arg in responses.calls[0].request.url.split('?')[1].split('&'):
Expand All @@ -55,6 +82,7 @@ def test_tone_with_args():
assert responses.calls[0].response.text == tone_response
assert len(responses.calls) == 1


@responses.activate
## Invoking tone_chat()
def test_tone_chat():
Expand Down
52 changes: 36 additions & 16 deletions watson_developer_cloud/tone_analyzer_v3.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@

from .watson_developer_cloud_service import WatsonDeveloperCloudService


class ToneAnalyzerV3(WatsonDeveloperCloudService):
"""Client for the ToneAnalyzer service."""

Expand All @@ -44,27 +43,48 @@ def __init__(self, version, url=default_url, **kwargs):
# tone
#########################

def tone(self, text, tones=None, sentences=None):
def tone(self, text, tones=None, sentences=None, content_type='text/plain'):
"""
The tone API is the main API call: it analyzes the "tone" of a piece
of text. The message is analyzed from
several tones (social tone, emotional tone, writing tone), and for
each of them various traits are derived
(such as conscientiousness, agreeableness, openness).
:param text: Text to analyze
:param sentences: If "false", sentence-level analysis is omitted
:param tones: Can be one or more of 'social', 'language', 'emotion';
comma-separated.
The general purpose tone API analyzes the "tone" of input text.
The message is analyzed for several tones (social, emotional, and
writing), with various characteristics derived for each tone.
:param text: The input content to analyze.
:param sentences: If false, sentence-level analysis is omitted; by
default (or if true), each sentence is analyzed.
:param tones: A comma-separated list of one or more of the following
tones for which to analyze the input text, 'social', 'language', and
'emotion'; the default is all tones.
:param content_type: The type of the input content: "text/plain"
(the default), "text/html", or "application/json".
"""

params = {'version': self.version}
if tones is not None:
params['tones'] = tones
if sentences is not None:
params['sentences'] = str(
sentences).lower() # Cast boolean to "false" / "true"
data = {'text': text}
return self.request(method='POST', url='/v3/tone', params=params,
json=data, accept_json=True)
# Cast boolean to "false" / "true"
params['sentences'] = str(sentences).lower()
if content_type == 'text/plain':
text = {'text': text}
content_type = 'application/json'
headers = {'content-type': content_type}

if content_type == 'application/json':
return self.request(
method='POST', headers=headers, url='/v3/tone', params=params,
json=text, accept_json=True)

# Use the equivalent of an 'else' rather than checking for explicit
# 'text/html' so that the call is made and returns a meaningful error
# for an invalid content type.
if content_type != 'application/json':
return self.request(
method='POST', headers=headers, url='/v3/tone', params=params,
data=text, accept_json=True)

#########################
# tone_chat
#########################

def tone_chat(self, utterances):
"""
Expand Down