Skip to content

Final Project Emotion Detector #57

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
39 changes: 39 additions & 0 deletions emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
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'
headers = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"}
myobj = {"raw_document": { "text": text_to_analyse }}

try:
response = requests.post(url, json=myobj, headers=headers)
response.raise_for_status() # Lanza una excepción para errores HTTP
res = response.json() # Parsea directamente el JSON de la respuesta

# Extraer emociones relevantes
emotions = res.get('emotionPredictions', [{}])[0].get('emotion', {})
extracted_emotions = {
'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)
}

# Determinar la emoción dominante
dominant_emotion = max(extracted_emotions, key=extracted_emotions.get)
extracted_emotions['dominant_emotion'] = dominant_emotion

return extracted_emotions

except requests.exceptions.RequestException as e:
return {"error": f"Request failed: {e}"}

# Ejemplo de uso
text = "I am extremely happy today!"
result = emotion_detector(text)
print(result)



82 changes: 82 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""
Flask application for detecting emotions from text input using an external API.
"""
from flask import Flask, render_template, request, jsonify
import requests
# Initialize Flask app
app = Flask(__name__)
def emotion_detector(text_to_analyze):
"""
Sends the given text to the Watson Emotion API for analysis and extracts emotions.

Args:
text_to_analyze (str): The text to be analyzed for emotions.

Returns:
dict: Dictionary containing detected emotions and the dominant emotion.
Returns an error message if no emotions are detected or if there is an issue.
"""
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"}
input_json = {"raw_document": {"text": text_to_analyze}}

try:
response = requests.post(url, json=input_json, headers=headers, timeout=10)
response.raise_for_status()
response_data = response.json()

if "emotion_predictions" not in response_data or not response_data["emotion_predictions"]:
return None

emotions = response_data["emotion_predictions"][0]
extracted_emotions = {
"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(extracted_emotions, key=extracted_emotions.get)
extracted_emotions["dominant_emotion"] = dominant_emotion

return extracted_emotions

except requests.exceptions.Timeout:
return {"error": "Request timed out"}
except requests.exceptions.RequestException as err:
return {"error": str(err)}

@app.route('/')
def index():
"""
Serves the index page.
"""
return render_template('index.html')

@app.route('/detect_emotion', methods=['POST'])
def detect_emotion():
"""
API endpoint that receives text input, analyzes its emotions, and returns the results.

Returns:
JSON response containing detected emotions or an error message.
"""
text = request.json.get("text", "").strip()

if not text:
return jsonify({"error": "No text provided"})

result = emotion_detector(text)

if result and result.get("dominant_emotion"):
return jsonify(result)

return jsonify({"error": "Invalid text! Please try again!"})

if __name__ == '__main__':
app.run(debug=True)
20 changes: 20 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from setuptools import setup, find_packages

setup(
name="EmotionDetection",
version="1.0.0",
packages=find_packages(),
install_requires=[
"requests",
],
author="Edson Ramirez",
author_email="[email protected]",
description="A package for detecting emotions from text using Watson API",
url="https://github.com/yourusername/EmotionDetection",
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
)
33 changes: 33 additions & 0 deletions test_emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import unittest
from emotion_detection import emotion_detector

class TestEmotionDetection(unittest.TestCase):

def test_joy(self):
text = "I am glad this happened"
result = emotion_detector(text)
self.assertEqual(result["dominant_emotion"], "joy")

def test_anger(self):
text = "I am really mad about this"
result = emotion_detector(text)
self.assertEqual(result["dominant_emotion"], "anger")

def test_disgust(self):
text = "I feel disgusted just hearing about this"
result = emotion_detector(text)
self.assertEqual(result["dominant_emotion"], "disgust")

def test_sadness(self):
text = "I am so sad about this"
result = emotion_detector(text)
self.assertEqual(result["dominant_emotion"], "sadness")

def test_fear(self):
text = "I am really afraid that this will happen"
result = emotion_detector(text)
self.assertEqual(result["dominant_emotion"], "fear")

if __name__ == "__main__":
unittest.main()