From e0fb961d48468336aa1afb4d4c607fe816f2bd6d Mon Sep 17 00:00:00 2001 From: Muhammad Abdullah Khan Date: Sat, 30 Aug 2025 09:42:32 -0400 Subject: [PATCH] Final Project --- EmotionDetection/__init__.py | 1 + EmotionDetection/emotion_detection.py | 48 ++++++++++++++++++++++++ server.py | 53 +++++++++++++++++++++++++++ test_emotion_detection.py | 32 ++++++++++++++++ 4 files changed, 134 insertions(+) create mode 100644 EmotionDetection/__init__.py create mode 100644 EmotionDetection/emotion_detection.py create mode 100644 server.py create mode 100644 test_emotion_detection.py diff --git a/EmotionDetection/__init__.py b/EmotionDetection/__init__.py new file mode 100644 index 000000000..0b7bf8661 --- /dev/null +++ b/EmotionDetection/__init__.py @@ -0,0 +1 @@ +from .emotion_detection import emotion_detector diff --git a/EmotionDetection/emotion_detection.py b/EmotionDetection/emotion_detection.py new file mode 100644 index 000000000..878d8de20 --- /dev/null +++ b/EmotionDetection/emotion_detection.py @@ -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 + } diff --git a/server.py b/server.py new file mode 100644 index 000000000..86753b6ec --- /dev/null +++ b/server.py @@ -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": ""} + - GET: expects query parameter textToAnalyze= + + 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) diff --git a/test_emotion_detection.py b/test_emotion_detection.py new file mode 100644 index 000000000..c48a7fe2d --- /dev/null +++ b/test_emotion_detection.py @@ -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()