Skip to content

Instantly share code, notes, and snippets.

@feconroses
Created June 29, 2022 13:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feconroses/0e064f463b9a0227ba73195f6376c8ed to your computer and use it in GitHub Desktop.
Save feconroses/0e064f463b9a0227ba73195f6376c8ed to your computer and use it in GitHub Desktop.
Python code for running sentiment analysis on Zapier using the Inference API
import requests
# Add the model ID and your Hugging Face Token
model = "cardiffnlp/twitter-roberta-base-sentiment-latest"
hf_token = "ADD_YOUR_HUGGING_FACE_TOKEN_HERE"
# Create the API request
API_URL = "https://api-inference.huggingface.co/models/" + model
headers = {"Authorization": "Bearer %s" % (hf_token)}
def analysis(payload):
response = requests.post(API_URL, headers=headers, json=payload)
while "is currently loading" in str(response.json()): # retry request while model loads
print(response.json())
time.sleep(30)
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
# Do the request to the Inference API and process the resutls
result = analysis({"inputs": str(input_data['input_data'])})
negative = result[0][0]['score']
neutral = result[0][1]['score']
positive = result[0][2]['score']
scores = [{'label': 'negative', 'score': negative}, {'label': 'neutral', 'score': neutral}, {'label': 'positive', 'score': positive}]
top_score = max(item['score'] for item in scores)
top_sentiment = next(item for item in scores if item["score"] == top_score)['label']
# Define the output for Zapier
output = [{'sentiment_label': top_sentiment, 'sentiment_score': top_score}]
@AyhamAlom
Copy link

I think Line 26 should be:
top_sentiment = next(item['label'] for item in scores if item["score"] == top_score)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment