Hello everyone,
This is my custom sentiment analysis component:
from rasa.nlu.components import Component
from rasa.nlu import utils
from rasa.nlu.model import Metadata
from rasa_sdk import Tracker
from rasa_sdk.events import SlotSet
import requests
import os
class SentimentAnalyzer(Component):
"""A pre-trained sentiment component"""
name = "sentiment"
provides = ["entities"]
requires = []
defaults = {}
language_list = ["en", "el"]
def __init__(self, component_config=None):
super(SentimentAnalyzer, self).__init__(component_config)
def train(self, training_data, cfg, **kwargs):
"""Not needed, because the the model is pretrained"""
pass
def convert_to_rasa(self, value, confidence):
"""Convert model output into the Rasa NLU compatible output format."""
entity = {
"value": value,
"confidence": confidence,
"entity": "sentiment",
"extractor": "sentiment_extractor",
}
return entity
def process(self, message, **kwargs):
"""Retrieve the text message, pass it to the classifier
and append the prediction results to the message class."""
try:
str = message.data['text']
data = {"text": str}
response = requests.post(
"http://url/classes", json=data
)
resp = response.json() # This returns {"sentiment_classes":[{"sentiment_class":"positive","sentiment_score":<score>}, {"sentiment_class":"neutral","sentiment_score":<score>}, {"sentiment_class":"negative","sentiment_score":<score>}]}
classes = resp.get("sentiment_classes")
score = 0
sentiment = None
for i in range(3):
if classes[i].get("sentiment_score") > score:
score = classes[i].get("sentiment_score")
sentiment = classes[i].get("sentiment_class")
if sentiment == "positive":
sentiment = "pos"
elif sentiment == "negative":
sentiment = "neg"
else:
sentiment = "neu"
entity = self.convert_to_rasa(sentiment, score)
message.set("entities", [entity], add_to_output=True)
except KeyError:
pass
def persist(self, file_name, dir_name):
"""Pass because a pre-trained model is already persisted"""
pass
Besides the sentiment extraction I want to store the POST’s response to a slot like below:
resp = response.json() # This returns {"sentiment_classes":[{"sentiment_class":"positive","sentiment_score":<score>}, {"sentiment_class":"neutral","sentiment_score":<score>}, {"sentiment_class":"negative","sentiment_score":<score>}]}
SlotSet(key=classes, value=str(resp))
“Classes” is a slot defined on my domain file. But this doesn’t work. Is there any way to make it work? I have read two similar posts but I do not know how to implement these solutions