Skip to content

All changes done, IBM python course #79

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 5 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
39 changes: 39 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer

nltk.download("vader_lexicon", quiet=True) # Download the lexicon if not already available


def emotion_detector(text_to_analyze):
# Handle blank or None input (like API status code 400)
if not text_to_analyze or text_to_analyze.strip() == "":
return {
"anger": None,
"disgust": None,
"fear": None,
"joy": None,
"sadness": None,
"dominant_emotion": None,
}

analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text_to_analyze)

emotion_scores = {
"anger": scores["neg"] * 0.5,
"disgust": scores["neg"] * 0.3 + 0.1 if "disgust" in text_to_analyze.lower() else 0,
"fear": scores["neg"] * 0.3 + 0.1 if "afraid" in text_to_analyze.lower() or "fear" in text_to_analyze.lower() else 0,
"joy": scores["pos"],
"sadness": scores["neg"] * 0.4 + 0.1 if "sad" in text_to_analyze.lower() else 0,
}

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

return {
"anger": emotion_scores["anger"],
"disgust": emotion_scores["disgust"],
"fear": emotion_scores["fear"],
"joy": emotion_scores["joy"],
"sadness": emotion_scores["sadness"],
"dominant_emotion": dominant_emotion,
}
48 changes: 48 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Flask server application for emotion detection.
"""

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

app = Flask(__name__)

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


@app.route("/emotionDetector", methods=["GET", "POST"])
def emotion_analysis():
"""
Handle requests to the /emotionDetector route.
Analyze the input text and return the detected emotions.
"""
if request.method == "GET":
text = request.args.get("textToAnalyze")
else:
text = request.form["text"]

result = emotion_detector(text)

if result["dominant_emotion"] is None:
return "Invalid text! Please try again!"

response = (
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


if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
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_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()