diff --git a/EmotionDetection/__init__.py b/EmotionDetection/__init__.py new file mode 100644 index 000000000..1727e5ed8 --- /dev/null +++ b/EmotionDetection/__init__.py @@ -0,0 +1 @@ +from . import emotion_detection diff --git a/EmotionDetection/emotion_detection.py b/EmotionDetection/emotion_detection.py new file mode 100644 index 000000000..be2b05b37 --- /dev/null +++ b/EmotionDetection/emotion_detection.py @@ -0,0 +1,64 @@ +import requests +import json + +def emotion_detector(text_to_analyze): + """Function to analyze emotions in text using Watson NLP and handle errors properly.""" + + if not text_to_analyze.strip(): # Check if input is empty or contains only spaces + return { + 'anger': None, + 'disgust': None, + 'fear': None, + 'joy': None, + 'sadness': None, + 'dominant_emotion': None + } + + 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) + + if response.status_code == 200: + formatted_response = json.loads(response.text) + + if 'emotionPredictions' not in formatted_response: + return { + 'anger': None, + 'disgust': None, + 'fear': None, + 'joy': None, + 'sadness': None, + 'dominant_emotion': None + } + + emotions = formatted_response['emotionPredictions'][0]['emotion'] + + return { + '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(emotions, key=emotions.get) + } + + elif response.status_code == 400: # Handle bad request errors + return { + 'anger': None, + 'disgust': None, + 'fear': None, + 'joy': None, + 'sadness': None, + 'dominant_emotion': None + } + + else: + return {"error": f"Request failed with status code {response.status_code}"} + +# Example usage +if __name__ == "__main__": + text = " " + result = emotion_detector(text) + print(result) diff --git a/emotion_detection.py b/emotion_detection.py new file mode 100644 index 000000000..e75047ed0 --- /dev/null +++ b/emotion_detection.py @@ -0,0 +1,36 @@ +import requests +import json + +def emotion_detector(text_to_analyze): + """Function to analyze emotions in text using Watson NLP and format the output""" + + 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) + + if response.status_code == 200: + formatted_response = json.loads(response.text) # Ensure JSON parsing using json library + + if 'emotionPredictions' not in formatted_response: + return {"error": "No emotions detected in the response."} + + emotions = formatted_response['emotionPredictions'][0]['emotion'] + + return { + '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(emotions, key=emotions.get) + } + else: + return {"error": f"Request failed with status code {response.status_code}"} + +# Example usage +if __name__ == "__main__": + text = "I am so happy I am doing this." + result = emotion_detector(text) + print(result) diff --git a/server.py b/server.py new file mode 100644 index 000000000..c1ad3d8b9 --- /dev/null +++ b/server.py @@ -0,0 +1,48 @@ +""" +Flask server for emotion detection API. +""" + +from flask import Flask, request, jsonify, render_template +from EmotionDetection import emotion_detection + +app = Flask(__name__) + +@app.route('/') +def home(): + """ + Renders the home page. + """ + return render_template('index.html') + +@app.route('/emotionDetector', methods=['POST']) +def emotion_detector_api(): + """ + Handles POST requests for emotion detection. + + Expects JSON data with a "text" key. + Returns a JSON response containing emotion scores + and the dominant emotion. + """ + data = request.json + text_to_analyze = data.get("text", "").strip() + + if not text_to_analyze: + return jsonify({"error": "Invalid text! Please try again!"}), 400 + + result = emotion_detection.emotion_detector(text_to_analyze) + + if result["dominant_emotion"] is None: + return jsonify({"error": "Invalid text! Please try again!"}), 400 + + response_text = ( + f"For the given statement, the system response is " + f"'anger': {result['anger']}, 'disgust': {result['disgust']}, " + f"'fear': {result['fear']}, 'joy': {result['joy']}, " + f"and 'sadness': {result['sadness']}. " + f"The dominant emotion is {result['dominant_emotion']}." + ) + + return jsonify({"response": response_text, "data": result}) + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=7000, debug=True) diff --git a/static/mywebscript.js b/static/mywebscript.js index 53d424977..5aadcc299 100644 --- a/static/mywebscript.js +++ b/static/mywebscript.js @@ -1,12 +1,24 @@ -let RunSentimentAnalysis = ()=>{ - textToAnalyze = document.getElementById("textToAnalyze").value; +let RunSentimentAnalysis = () => { + let textToAnalyze = document.getElementById("textToAnalyze").value.trim(); let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { - if (this.readyState == 4 && this.status == 200) { - document.getElementById("system_response").innerHTML = xhttp.responseText; + if (this.readyState == 4) { + let response = JSON.parse(this.responseText); + + if (this.status == 200) { + document.getElementById("system_response").innerHTML = response.response; + } else if (this.status == 400) { // Handling empty input case + document.getElementById("system_response").innerHTML = response.error; + } else { + document.getElementById("system_response").innerHTML = "An unexpected error occurred."; + } } }; - xhttp.open("GET", "emotionDetector?textToAnalyze"+"="+textToAnalyze, true); - xhttp.send(); -} + + xhttp.open("POST", "/emotionDetector", true); + xhttp.setRequestHeader("Content-Type", "application/json"); + + let data = JSON.stringify({ text: textToAnalyze }); + xhttp.send(data); +}; diff --git a/test_emotion_detection.py b/test_emotion_detection.py new file mode 100644 index 000000000..41f05b27e --- /dev/null +++ b/test_emotion_detection.py @@ -0,0 +1,27 @@ +import unittest +from EmotionDetection import emotion_detection + +class TestEmotionDetector(unittest.TestCase): + + def test_joy(self): + result = emotion_detection.emotion_detector("I am glad this happened") + self.assertEqual(result['dominant_emotion'], 'joy') + + def test_anger(self): + result = emotion_detection.emotion_detector("I am really mad about this") + self.assertEqual(result['dominant_emotion'], 'anger') + + def test_disgust(self): + result = emotion_detection.emotion_detector("I feel disgusted just hearing about this") + self.assertEqual(result['dominant_emotion'], 'disgust') + + def test_sadness(self): + result = emotion_detection.emotion_detector("I am so sad about this") + self.assertEqual(result['dominant_emotion'], 'sadness') + + def test_fear(self): + result = emotion_detection.emotion_detector("I am really afraid that this will happen") + self.assertEqual(result['dominant_emotion'], 'fear') + +if __name__ == "__main__": + unittest.main()