I would recommend to use the NLU module directly. If you go to the REST API documentation for NLU Tone, on the right you can see sample code you can use.
It also explains in a link how to use the Tone model that replaces Tone Analyzer.
Basically you need to reference the model tone-classifications-XX-v1
where XX is either en
or fr
.
Here is some sample code and output based off of the documentation.
Change API
and URL
to the values in the NLU instance service page-> Manage tab.
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 import Features, ClassificationsOptions
apikey = 'APIKEY'
url = 'URL'
# Only 'en' and 'fr' available at the time of writing this.
language = 'en'
tone_model = f'tone-classifications-{language}-v1'
text = 'This is awesome! Thanks a lot! I am so happy this solved my problem.'
authenticator = IAMAuthenticator(apikey)
nlu = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
nlu.set_service_url(url)
response = nlu.analyze(
text=text,
features=Features(classifications=ClassificationsOptions(model=tone_model))).get_result()
print(json.dumps(response, indent=2))
This should generate something like this:
{
"usage": {
"text_units": 1,
"text_characters": 68,
"features": 1
},
"language": "en",
"classifications": [
{
"confidence": 0.867106,
"class_name": "satisfied"
},
{
"confidence": 0.729703,
"class_name": "excited"
},
{
"confidence": 0.283219,
"class_name": "polite"
},
{
"confidence": 0.154289,
"class_name": "sympathetic"
},
{
"confidence": 0.029122,
"class_name": "sad"
},
{
"confidence": 0.013206,
"class_name": "frustrated"
},
{
"confidence": 0.005977,
"class_name": "impolite"
}
]
}