Skip to content

Final Project #98

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

Open
wants to merge 10 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 .emotion_detection import emotion_detector
38 changes: 38 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
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 = {
"Content-Type": "application/json",
"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)

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']

scores = {
'anger': emotions.get('anger', 0),
'disgust': emotions.get('disgust', 0),
'fear': emotions.get('fear', 0),
'joy': emotions.get('joy', 0),
'sadness': emotions.get('sadness', 0)
}

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

scores['dominant_emotion'] = dominant_emotion
return scores
38 changes: 38 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Flask web server for emotion detection."""

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

app = Flask(__name__)

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

@app.route('/emotionDetector', methods=['GET'])
def detect_emotion():
"""Handle emotion detection logic and return formatted output or error."""
text = request.args.get('textToAnalyze') # Get the input from the query string
result = emotion_detector(text)

# Error handling for blank input or 400 status from Watson API
if result['dominant_emotion'] is None:
return "Invalid text! Please try again!"

# Create response string for display
response_str = (
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_str

if __name__ == '__main__':
app.run(debug=True)

26 changes: 26 additions & 0 deletions test_emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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()