Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task7 #22

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions EmotionDetection/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import emotion_detection
58 changes: 58 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import requests
import json
import operator

# Define a function named sentiment_analyzer that takes a string input (text_to_analyse)
def emotion_detector(text_to_analyse):

# URL of the sentiment analysis service
url = 'https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict'

# Create a dictionary with the text to be analyzed
myobj = { "raw_document": { "text": text_to_analyse } }

# Set the headers required for the API request
header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"}

# Send a POST request to the API with the text and headers
response = requests.post(url, json = myobj, headers=header)

# Parse the response from the API
formatted_response = json.loads(response.text)

# If the response status code is 200, extract emotion scores from the response
if response.status_code == 200:
anger_score = formatted_response['emotionPredictions'][0]['emotion']['anger']
disgust_score = formatted_response['emotionPredictions'][0]['emotion']['disgust']
fear_score = formatted_response['emotionPredictions'][0]['emotion']['fear']
joy_score = formatted_response['emotionPredictions'][0]['emotion']['joy']
sadness_score = formatted_response['emotionPredictions'][0]['emotion']['sadness']

# If the response status code is 400, set scores to None
elif response.status_code == 400:
anger_score = None
disgust_score = None
fear_score = None
joy_score = None
anger_score = None
sadness_score = None

# Create a Disctionary with emotions and scores
emotions = {'anger': anger_score,
'disgust': disgust_score,
'fear': fear_score,
'joy': joy_score,
'sadness': sadness_score
}

# Calculate the dominant emotion only if the status code is 200
if response.status_code == 200:
dominant_emotion = max(emotions.items(), key=operator.itemgetter(1))[0]
else:
dominant_emotion = None

# Add the dominant emotion to the dictionary
emotions['dominant_emotion'] = dominant_emotion

# Return the label and score in a dictionary
return emotions
36 changes: 36 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from flask import Flask, render_template, request
from EmotionDetection.emotion_detection import emotion_detector

app = Flask("Emotion Detector")

@app.route("/emotionDetector")
def emo_detector():
# Retrieve the text to analyze from the request arguments
text_to_analyze = request.args.get('textToAnalyze')

# Pass the text to the sentiment_analyzer function and store the response
response = emotion_detector(text_to_analyze)

# Extract the emotion and score from the response
anger = response['anger']
disgust = response['disgust']
fear = response['fear']
joy = response['joy']
sadness = response['sadness']
dominant_emotion = response['dominant_emotion']

# Return a formatted string with the emotion response
if anger is None or disgust is None or fear is None or joy is None or sadness is None or dominant_emotion is None:
return "Invalid text! Please try again!"
else:
return "For the given statement, the system response is \
'anger' : {}, 'disgust' : {}, 'fear' : {}, 'joy' : {} and 'sadness' : {}. \
The dominant emotion is <b>{}</b>.".format(anger, disgust, fear, joy, sadness, dominant_emotion)

@app.route("/")
def render_index_page():

return render_template('index.html')

if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
28 changes: 28 additions & 0 deletions test_emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from EmotionDetection.emotion_detection import emotion_detector
import unittest

class TestEmotionDetector(unittest.TestCase):

def test_emotion_detector(self):

# Test case for joy dominant emotion
result_1 = emotion_detector('I am glad this happened')
self.assertEqual(result_1['dominant_emotion'], 'joy')

# Test case for anger dominant emotion
result_2 = emotion_detector('I am really mad about this')
self.assertEqual(result_2['dominant_emotion'], 'anger')

# Test case for disgust dominant emotion
result_3 = emotion_detector('I feel disgusted just hearing about this')
self.assertEqual(result_3['dominant_emotion'], 'disgust')

# Test case for sadness dominant emotion
result_4 = emotion_detector('I am so sad about this')
self.assertEqual(result_4['dominant_emotion'], 'sadness')

# Test case for fear dominant emotion
result_5 = emotion_detector('I am really afraid that this will happen')
self.assertEqual(result_5['dominant_emotion'], 'fear')

unittest.main()