Advertisement
UF6

Emotion Detector In Words

UF6
Jan 29th, 2024
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | Source Code | 0 0
  1. import requests
  2. import json
  3.  
  4. def emotion_detector(text_to_analyze):
  5.     URL = 'https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict'
  6.     header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"}
  7.     input_json = { "raw_document": { "text": text_to_analyze } }
  8.     response = requests.post(URL, json = input_json, headers=header)
  9.     formated_response = json.loads(response.text)
  10.  
  11.     if response.status_code == 200:
  12.         return formated_response
  13.     elif response.status_code == 400:
  14.         formated_response = {
  15.                             'anger': None,
  16.                             'disgust': None,
  17.                             'fear': None,
  18.                             'joy': None,
  19.                             'sadness': None,
  20.                             'dominant_emotion': None}
  21.         return formated_response
  22.  
  23. def emotion_predictor(detected_text):
  24.     if all(value is None for value in detected_text.values()):
  25.         return detected_text
  26.     if detected_text['emotionPredictions'] is not None:
  27.         emotions = detected_text['emotionPredictions'][0]['emotion']
  28.         anger = emotions['anger']
  29.         disgust = emotions['disgust']
  30.         fear = emotions['fear']
  31.         joy = emotions['joy']
  32.         sadness = emotions['sadness']
  33.         max_emotion = max(emotions, key=emotions.get)
  34.         #max_emotion_score = emotions[max_emotion]
  35.         formated_dict_emotions = {
  36.                                 'anger': anger,
  37.                                 'disgust': disgust,
  38.                                 'fear': fear,
  39.                                 'joy': joy,
  40.                                 'sadness': sadness,
  41.                                 'dominant_emotion': max_emotion
  42.                                 }
  43.         return formated_dict_emotions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement