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

def emotion_detector(text_to_analyze):
if not text_to_analyze.strip():
# Handle blank input (status_code = 400 behavior)
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

# Call Watson NLP API (or your API endpoint)
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"}
input_json = {"raw_document": {"text": text_to_analyze}}

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

# Check for 400 Bad Request (invalid or empty)
if response.status_code == 400:
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

# Normal successful response
response_dict = json.loads(response.text)
emotions = response_dict["emotionPredictions"][0]["emotion"]
dominant_emotion = max(emotions, key=emotions.get)

emotions["dominant_emotion"] = dominant_emotion
return emotions
56 changes: 56 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""
Flask web server for Emotion Detection application.
Handles text input from the user interface and returns emotion analysis results.
"""

from flask import Flask, request, render_template
from EmotionDetection.emotion_detection import emotion_detector

app = Flask(
__name__,
template_folder="/home/project/Final_project/Flask_Emo/templates",
static_folder="/home/project/Final_project/Flask_Emo/static"
)


@app.route("/", methods=["GET"])
def index():
"""
Render the index page for the web application.
"""
return render_template("index.html")


@app.route("/emotionDetector", methods=["GET"])
def emotion_detection():
"""
Handle emotion detection requests from the web interface.

Returns:
str: A formatted message containing emotion scores and dominant emotion,
or an error message for invalid input.
"""
text_to_analyze = request.args.get("textToAnalyze", "")

result = emotion_detector(text_to_analyze)

# Handle invalid or blank text
if result["dominant_emotion"] is None:
return "Invalid text! Please try again!"

# Prepare formatted response
response_text = (
f"For the given statement, the system response is "
f"'anger': {result['anger']}, "
f"'disgust': {result['disgust']}, "
f"'fear': {result['fear']}, "
f"'joy': {result['joy']} and "
f"'sadness': {result['sadness']}. "
f"The dominant emotion is {result['dominant_emotion']}."
)

return response_text


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

class TestEmotionDetection(unittest.TestCase):

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

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

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

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

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

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