diff --git a/EmotionDetection/__init__.py b/EmotionDetection/__init__.py new file mode 100644 index 000000000..83599eb9d --- /dev/null +++ b/EmotionDetection/__init__.py @@ -0,0 +1,2 @@ +from . import emotion_detection + diff --git a/EmotionDetection/emotion_detection.py b/EmotionDetection/emotion_detection.py new file mode 100644 index 000000000..20f5c8c8f --- /dev/null +++ b/EmotionDetection/emotion_detection.py @@ -0,0 +1,25 @@ +import json +import requests + + +def emotion_detector(text_to_analyse): + url = 'https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict' + myobj = { "raw_document": { "text": text_to_analyse } } + header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"} + response = requests.post(url, json = myobj, headers=header) + json_str = response.text + data = json.loads(json_str) + emotion_scores = data['emotionPredictions'][0]['emotion'] + dominant_emotion = max(emotion_scores, key=emotion_scores.get) + emotion_scores['dominant_emotion'] = dominant_emotion + + return(emotion_scores) + + + + + + + + + \ No newline at end of file diff --git a/server.py b/server.py new file mode 100644 index 000000000..2e657eeba --- /dev/null +++ b/server.py @@ -0,0 +1,17 @@ +from flask import Flask, request, render_template +from EmotionDetection.emotion_detection import emotion_detector + +app = Flask(__name__) + +@app.route('/emotionDetector', methods=['POST', 'GET']) # Changed route name here +def emotions_route(): + if request.method == 'POST': + text = request.form.get('text') + if not text or text.strip() == '': + return render_template('index.html', error="Invalid text! Please try again!") + result = emotion_detector(text) + return render_template('index.html', result=result, input_text=text) + return render_template('index.html') + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=500, debug=True) \ No newline at end of file diff --git a/test_emotion_detection.py b/test_emotion_detection.py new file mode 100644 index 000000000..ca9dd32d6 --- /dev/null +++ b/test_emotion_detection.py @@ -0,0 +1,22 @@ +from EmotionDetection.emotion_detection import emotion_detector +import unittest + +class TestEmotionDetector(unittest.TestCase): + def test_emotion_detector(self): + result1 = emotion_detector("I am glad this happened") + self.assertEqual(result1, 'joy') + + result2 = emotion_detector("I am really mad about this") + self.assertEqual(result2, 'anger') + + result3 = emotion_detector("I feel disgusted just hearing about this") + self.assertEqual(result3, 'disgust') + + result4 = emotion_detector("I am so sad about this") + self.assertEqual(result4, 'sadness') + + result5 = emotion_detector("I am really afraid this will happen") + self.assertEqual(result5, 'fear') + + +unittest.main() \ No newline at end of file