-
-
Save feconroses/0e064f463b9a0227ba73195f6376c8ed to your computer and use it in GitHub Desktop.
Python code for running sentiment analysis on Zapier using the Inference API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think Line 26 should be:
top_sentiment = next(item['label'] for item in scores if item["score"] == top_score)