Skip to content
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 .emotion_detection import emotion_detector
48 changes: 48 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import requests
import json

def emotion_detector(text_to_analyze):
url = "https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict"
headers = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"}
data = { "raw_document": { "text": text_to_analyze } }

response = requests.post(url, json=data, headers=headers)

if response.status_code == 400:
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

result = json.loads(response.text)

emotions = result['emotionPredictions'][0]['emotion']
anger = emotions['anger']
disgust = emotions['disgust']
fear = emotions['fear']
joy = emotions['joy']
sadness = emotions['sadness']

# Get the dominant emotion
emotion_scores = {
'anger': anger,
'disgust': disgust,
'fear': fear,
'joy': joy,
'sadness': sadness
}

dominant_emotion = max(emotion_scores, key=emotion_scores.get)

return {
'anger': anger,
'disgust': disgust,
'fear': fear,
'joy': joy,
'sadness': sadness,
'dominant_emotion': dominant_emotion
}
53 changes: 53 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Server module for Emotion Detection web application using Flask."""

from flask import Flask, render_template, request, jsonify
from EmotionDetection import emotion_detector

app = Flask(__name__)


@app.route('/emotionDetector', methods=['GET', 'POST'])
@app.route('/emotionDetector', methods=['GET', 'POST'])
def emotion_detector_endpoint():
"""Endpoint for detecting emotions from a given text.

Accepts GET and POST requests:
- POST: expects JSON {"text": "<user_text>"}
- GET: expects query parameter textToAnalyze=<user_text>

Returns:
JSON response containing emotion scores and dominant emotion,
or an error message if the input is invalid.
"""
if request.method == 'POST':
data = request.get_json()
text_to_analyze = data.get('text', '')
else:
text_to_analyze = request.args.get('textToAnalyze', '')

result = emotion_detector(text_to_analyze)

if result['dominant_emotion'] is None:
return jsonify({"message": "Invalid text! Please try again!"})

formatted_response = {
"anger": result['anger'],
"disgust": result['disgust'],
"fear": result['fear'],
"joy": result['joy'],
"sadness": result['sadness'],
"dominant_emotion": result['dominant_emotion']
}

return jsonify(formatted_response)



@app.route('/')
def index():
"""Render the main index page."""
return render_template('index.html')


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

class TestEmotionDetection(unittest.TestCase):

def test_joy(self):
text = "I am glad this happened"
result = emotion_detector(text)
self.assertEqual(result['dominant_emotion'], 'joy')

def test_anger(self):
text = "I am really mad about this"
result = emotion_detector(text)
self.assertEqual(result['dominant_emotion'], 'anger')

def test_disgust(self):
text = "I feel disgusted just hearing about this"
result = emotion_detector(text)
self.assertEqual(result['dominant_emotion'], 'disgust')

def test_sadness(self):
text = "I am so sad about this"
result = emotion_detector(text)
self.assertEqual(result['dominant_emotion'], 'sadness')

def test_fear(self):
text = "I am really afraid that this will happen"
result = emotion_detector(text)
self.assertEqual(result['dominant_emotion'], 'fear')

if __name__ == '__main__':
unittest.main()