Skip to content

Master #64

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
5 changes: 5 additions & 0 deletions EmotionDetection/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

from .emotion_detection import emotion_detector



Binary file not shown.
Binary file not shown.
57 changes: 57 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import requests
import json

def emotion_detector(text_to_analyze):
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}}

# Verificar si el texto está vacío
if not text_to_analyze.strip():
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

response = requests.post(url, headers=headers, json=payload)

# Manejo de error si el servidor responde con un código 400
if response.status_code == 400:
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

response_data = response.json()
emotions = response_data.get("emotionPredictions", [])[0].get("emotion", {})

if not emotions:
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

# Encontrar la emoción dominante
dominant_emotion = max(emotions, key=emotions.get)

return {
'anger': emotions.get('anger'),
'disgust': emotions.get('disgust'),
'fear': emotions.get('fear'),
'joy': emotions.get('joy'),
'sadness': emotions.get('sadness'),
'dominant_emotion': dominant_emotion
}

Binary file added __pycache__/emotion_detection.cpython-311.pyc
Binary file not shown.
1 change: 1 addition & 0 deletions oaqjp-final-project-emb-ai
Submodule oaqjp-final-project-emb-ai added at 3e0458
45 changes: 45 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from flask import Flask, request, jsonify, render_template
from EmotionDetection import emotion_detector # Import the function

app = Flask(__name__)

# Route to serve the web application
@app.route("/")
def home():
return render_template("index.html")

# Route to handle emotion detection
@app.route("/emotionDetector", methods=["POST"])
def detect_emotion():
try:
# Get text input from request
data = request.get_json()
text_to_analyze = data.get("text", "")

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

# Call the emotion detection function
result = emotion_detector(text_to_analyze)

# Check if dominant_emotion is None
if result.get('dominant_emotion') is None:
return jsonify({"error": "Invalid text! Please try again!"}), 400

# Format the response as requested
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']} and "
f"'sadness': {result['sadness']}. The dominant emotion is {result['dominant_emotion']}."
)

return jsonify({"message": response_text})

except Exception as e:
return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
app.run(debug=True, host="127.0.0.1", port=5000)


40 changes: 40 additions & 0 deletions test_emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import unittest
from EmotionDetection import emotion_detector

class TestEmotionDetector(unittest.TestCase):
"""Pruebas unitarias para la función emotion_detector."""

def test_joy(self):
"""Prueba si la emoción dominante es 'joy'."""
result = emotion_detector("I am glad this happened")
self.assertIn("dominant_emotion", result)
self.assertEqual(result["dominant_emotion"], "joy")

def test_anger(self):
"""Prueba si la emoción dominante es 'anger'."""
result = emotion_detector("I am really mad about this")
self.assertIn("dominant_emotion", result)
self.assertEqual(result["dominant_emotion"], "anger")

def test_disgust(self):
"""Prueba si la emoción dominante es 'disgust'."""
result = emotion_detector("I feel disgusted just hearing about this")
self.assertIn("dominant_emotion", result)
self.assertEqual(result["dominant_emotion"], "disgust")

def test_sadness(self):
"""Prueba si la emoción dominante es 'sadness'."""
result = emotion_detector("I am so sad about this")
self.assertIn("dominant_emotion", result)
self.assertEqual(result["dominant_emotion"], "sadness")

def test_fear(self):
"""Prueba si la emoción dominante es 'fear'."""
result = emotion_detector("I am really afraid that this will happen")
self.assertIn("dominant_emotion", result)
self.assertEqual(result["dominant_emotion"], "fear")

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