import requests
import json
import time


def get_toxicity(text, api_key):
    """Gets the toxicity for some text from https://www.perspectiveapi.com

    Parameters
    ----------
    text : str
        Text to evaluate the toxicity
    api_key : str
        API key for perspective

    Returns
    -------
    probability : float
        The probability of the text being toxic.
    """
    url = f"https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key={api_key}"
    data_dict = {"comment": {"text": text},
                 "languages": ["en"],
                 "requestedAttributes": {"TOXICITY": {}}}
    response = requests.post(url=url, data=json.dumps(data_dict))
    response_dict = json.loads(response.content)
    probability = response_dict["attributeScores"]["TOXICITY"]["summaryScore"]["value"]

    # Put to sleep so that Google doesn't bother me
    # with the 1 QPS (queries per second)
    time.sleep(1.3)

    return probability