Skip to content

Instantly share code, notes, and snippets.

@feconroses
Created August 11, 2021 13:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feconroses/3476a91dc524fdb930a726b3894a1d08 to your computer and use it in GitHub Desktop.
Save feconroses/3476a91dc524fdb930a726b3894a1d08 to your computer and use it in GitHub Desktop.
Python code for running sentiment analysis on Zapier
import requests
API_URL = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment"
headers = {"Authorization": "Bearer <YOUR HUGGINGFACE API KEY>"}
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response.json()
result = query({"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']
output = [{'sentiment_label': top_sentiment, 'sentiment_score': top_score}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment