Is there a way to run Googles Perspective API through Python to obatin toxicity, insult, and threat scores of an input text? I am trying to run the perspective API from the perspective v1.0.3 in python. I ran the following code
from perspective import PerspectiveAPI
key = "MY-API-KEY"
p = PerspectiveAPI(key)
result = p.score("This is very bad")
print(result)
print("Toxicity score: " + str(result["TOXICITY"]))
'result' is a dictionary with only scores for toxicity, but I want the 'insult' and 'threat' scores too, How do I get them?
I tried one solution - using this code for the lower version of the perspective library because I found an example using 'Client' to get the 'insult' score, but it throws an error on my system
from perspective import Client, Attributes, utils
# Create the Client object which we will use to make requests with the API key
API_KEY = "AIzaSyC-c9fH6oFtKEAX16kmQKclj8gfc545WPM"
client = Client(token = API_KEY)
# Make a request to Perspective API with a text to analyze and the attributes that you want the text to be analyzed for
response = client.analyze(text = "Hey! How are you?", requestedAttributes = [Attributes.TOXICITY, Attributes.INSULT])
# Print the response as a dictionary
print(response)
# Print the score value of TOXICITY attribute
print(response["TOXICITY"])
print(" ")
# Iterate over the response
for attribute, result in response.items():
print(attribute.capitalize() + ": " + "%.2f" % result + "%")
print(" ")
# Or alternatively, use utils.format_response to print a formatted text of the response which would return almost the same result as the above code
print(utils.format_response(response, align_right=True))
I get the following error
ImportError: cannot import name 'Client' from 'perspective' (/usr/local/lib/python3.10/dist-packages/perspective/__init__.py)
I only ran the lower version of the library because I wanted the 'threat' and 'insult' scores, but the code is not working. PS- I am using Google Colab
Also, is there an easier way to get the 'insult' and 'threat' scores using Google's Perspective API for a data set full of comments?