Skip to content

Initial Commit #66

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 2 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 . import emotion_detection
64 changes: 64 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -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)
36 changes: 36 additions & 0 deletions emotion_detection.py
Original file line number Diff line number Diff line change
@@ -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)
48 changes: 48 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -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)
26 changes: 19 additions & 7 deletions static/mywebscript.js
Original file line number Diff line number Diff line change
@@ -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);
};
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_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()