0
votes

I have the following code with the username, password, and URL values updated to those which I copied directly from the IBM Watson Service credentials. For some reason I get the error below.

Code:

import requests
import json

def analyze_tone(text):
    username = 'username-copied-from-watson'
    password = 'service-password-copied-from-watson'
    watsonUrl = 'https://gateway.watsonplatform.net/tone-analyzer/api'
    headers = {"content-type": "text/plain"}
    data = text
    try:
        r = requests.post(watsonUrl, auth=(username,password),headers = headers,
         data=data)
        return r.text
    except:
        return False

def welcome():
    message = "Welcome to the IBM Watson Tone Analyzer\n"
    print(message + "-" * len(message) + "\n")
    message = "How it works"
    print(message)
    message = "Perhaps a bit too aggressive in your emails? Are your blog posts a little too friendly? Tone Analyzer might be able to help. The service uses linguistic analysis to detect and interpret emotional, social, and writing cues found in text."
    print(message)
    print()
    print("Have fun!\n")

def display_results(data):
    data = json.loads(str(data))
    print(data)
    for i in data['document_tone']['tone_categories']:
        print(i['category_name'])
        print("-" * len(i['category_name']))
        for j in i['tones']:
            print(j['tone_name'].ljust(20),(str(round(j['score'] * 100,1)) + "%").rjust(10))
        print()
    print()

def main():
    welcome()

    data = input("Enter some text to be analyzed for tone analysis by IBM Watson (Q to quit):\n")
    if len(data) >= 1:
        if data == 'q'.lower():
            exit
        results = analyze_tone(data)
        if results != False:
            display_results(results)
            exit
        else:
            print("Something went wrong")

main()

Error:

Enter some text to be analyzed for tone analysis by IBM Watson (Q to quit):
"I love hate you"
{u'sub_code': u'C00010', u'code': 404, u'error': u'Not Found'}
Traceback (most recent call last):
  File "test.py", line 58, in <module>
    main()
  File "test.py", line 53, in main
display_results(results)
1

1 Answers

1
votes

There seem to be a couple of issues with your code. The API for the Watson Tone Analyzer service lists the following as API endpoint:

https://gateway.watsonplatform.net/tone-analyzer/api/v3/{method}

You are missing the Version 3 v3 and I don't see that you provide any method. You also need to pass in the API version.

I recommend to use the official Python SDK for the IBM Watson services. When you browse that GitHub repo you will find an example for the tone analyzer.