Skip to content
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

Updated Final Project #53

Closed
wants to merge 19 commits into from
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ ipython_config.py
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
Expand Down
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
32 changes: 32 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import requests
import json

def emotion_detector(text_to_analyse):
url = 'https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict'
header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"}
myobj = {"raw_document": {"text": text_to_analyse}}
response = requests.post(url, json=myobj, headers=header)

# Handle blank entry (status_code = 400)
if response.status_code == 400:
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

formatted_response = json.loads(response.text)
emotion_scores = formatted_response['emotionPredictions'][0]['emotion']
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
}
41 changes: 40 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,40 @@
# Repository for final project
# Emotion Detection Flask Application

A lightweight Flask-based web application that analyzes user-provided text to detect emotions such as anger, disgust, fear, joy, and sadness. The application uses a pre-trained emotion detection model and provides detailed emotion scores along with the dominant emotion.

## Features

- Analyze text to predict emotions (anger, disgust, fear, joy, sadness).
- Returns emotion scores and identifies the dominant emotion.
- Handles blank or invalid text inputs with proper error messages.
- Easy-to-deploy Flask application for local or cloud hosting.

## Installation

1. Clone the repository:
```bash
git clone https://github.com/athrocks/Emotion-Detection-Flask-Application/
cd emotion-detection-flask
```
2. Install dependencies:

3. Start the Flask server:
```bash
python3.11 server.py
```

4. Access the application in your browser:
Visit http://127.0.0.1:5005.


#### Response
```
{
"anger": 0.0136,
"disgust": 0.0017,
"fear": 0.0089,
"joy": 0.9719,
"sadness": 0.0552,
"dominant_emotion": "joy"
}
```
55 changes: 55 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
This module implements a Flask web server for emotion detection.
It uses a predefined emotion detection function to analyze text input
and returns the corresponding emotion scores and dominant emotion.
"""

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

app = Flask("Emotion Detector")

@app.route("/emotionDetector")
def sent_detector():
"""
Handle the emotion detection request.

Expects a query parameter 'textToAnalyze'.
Validates the input and calls the emotion_detector function.

Returns:
JSON response:
- If input is valid: Emotion scores and the dominant emotion.
- If input is invalid or empty: Error message with status 400.
"""
text_to_analyze = request.args.get('textToAnalyze', "").strip()

if not text_to_analyze:
return jsonify({"message": "Invalid text! Please try again!"}), 400

response = emotion_detector(text_to_analyze)

if response['dominant_emotion'] is None:
return jsonify({"message": "Invalid text! Please try again!"}), 400

return jsonify({
"anger": response['anger'],
"disgust": response['disgust'],
"fear": response['fear'],
"joy": response['joy'],
"sadness": response['sadness'],
"dominant_emotion": response['dominant_emotion']
}), 200

@app.route("/")
def render_index_page():
"""
Render the index page for the application.

Returns:
Rendered HTML content from the index.html template.
"""
return render_template('index.html')

if __name__ == "__main__":
app.run(host="0.0.0.0", port=5005)
1 change: 1 addition & 0 deletions static/mywebscript.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ let RunSentimentAnalysis = ()=>{
xhttp.open("GET", "emotionDetector?textToAnalyze"+"="+textToAnalyze, true);
xhttp.send();
}

2 changes: 1 addition & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ <h2 class="mb-3">
</div>
<div style="padding: 25px 25px 25px 25px;"></div>
<h2 class="mb-3">
<label class="form-label">Result of Emotion Detection</label>
<label class="form-label">Result of Emotion Detection:</label>
</h2>

<div id="system_response" style="padding: 25px 25px 25px 25px;"></div>
Expand Down
22 changes: 22 additions & 0 deletions test_emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from EmotionDetection.emotion_detection import emotion_detector
import unittest

class TestEmotionDetector(unittest.TestCase):
def test_emotion_detector(self):

result_1 = emotion_detector('I am glad this happened')
self.assertEqual(result_1['dominant_emotion'], 'joy')

result_2 = emotion_detector('I am really mad about this ')
self.assertEqual(result_2['dominant_emotion'], 'anger')

result_3 = emotion_detector('I feel disgusted just hearing about this ')
self.assertEqual(result_3['dominant_emotion'], 'disgust')

result_4 = emotion_detector('I am so sad about this')
self.assertEqual(result_4['dominant_emotion'], 'sadness')

result_5 = emotion_detector('I am really afraid that this will happen ')
self.assertEqual(result_5['dominant_emotion'], 'fear')

unittest.main()