Skip to content

Add final emotion detection + Flask deployment #58

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

def emotion_detector(text_to_analyze):
"""
Sends a POST request to Watson NLP Emotion Detection API and returns the formatted response.
"""
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"}
payload = {"raw_document": {"text": text_to_analyze}}

response = requests.post(url, json=payload, headers=headers)
response_dict = json.loads(response.text) # Convert response to dictionary

# Extract emotion scores
emotions = response_dict.get("emotionPredictions", [{}])[0].get("emotion", {})
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)

# Determine the dominant emotion
dominant_emotion = max(emotions, key=emotions.get, default="unknown")

return {
"anger": anger,
"disgust": disgust,
"fear": fear,
"joy": joy,
"sadness": sadness,
"dominant_emotion": dominant_emotion
}
30 changes: 30 additions & 0 deletions emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import requests

def emotion_detector(text_to_analyze):
"""
Diagnostic version of the emotion_detector function
that prints the entire JSON to identify its structure.
"""
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",
"Content-Type": "application/json"
}
payload = {
"raw_document": {
"text": text_to_analyze
}
}

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

if response.status_code == 200:
try:
response_json = response.json()
# Print the entire response JSON to see its structure
print("DEBUG: Entire Watson Response:", response_json)
return response_json
except ValueError:
return "Error parsing JSON response."
else:
return f"Error: {response.status_code}, {response.text}"
28 changes: 28 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from flask import Flask, request, jsonify
from EmotionDetection import emotion_detector

app = Flask(__name__, template_folder="templates")

@app.route('/')
def home():
return "Emotion Detection API is running! Use /emotionDetector endpoint to analyze text."

@app.route('/emotionDetector', methods=['GET'])
def emotion_detector_endpoint():
text_to_analyze = request.args.get('textToAnalyze', '')

if not text_to_analyze:
return jsonify({"error": "No text provided for analysis."}), 400

response = emotion_detector(text_to_analyze)

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

return formatted_response

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

class TestEmotionDetection(unittest.TestCase):

def test_emotion_detector(self):
# Test for joy
response = emotion_detector("I am glad this happened")
self.assertEqual(response['dominant_emotion'], "joy")

# Test for anger
response = emotion_detector("I am really mad about this")
self.assertEqual(response['dominant_emotion'], "anger")

# Test for disgust
response = emotion_detector("I feel disgusted just hearing about this")
self.assertEqual(response['dominant_emotion'], "disgust")

# Test for sadness
response = emotion_detector("I am so sad about this")
self.assertEqual(response['dominant_emotion'], "sadness")

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

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