Skip to content
Open
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "final_project"]
path = final_project
url = https://github.com/rayoconico/F-Quinteros-final-project-emb-ai.git
12 changes: 12 additions & 0 deletions .theia/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
"version": "0.2.0",
<<<<<<< HEAD
"configurations": []
=======
"configurations": [

]
>>>>>>> fe5311dee5d7aa23c2b5ffb2543e29c634742265
}
8 changes: 8 additions & 0 deletions .theia/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"php.suggest.basic": false,
"java.errors.incompleteClasspath.severity": "ignore",
"security.workspace.trust.enabled": true,
"security.workspace.trust.startupPrompt": "never",
"security.workspace.trust.untrustedFiles": "open",
"liveServer.settings.donotShowInfoMsg": false,
}
1 change: 1 addition & 0 deletions final_project/EmotionDetection/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .emotion_detection import emotion_detector
52 changes: 52 additions & 0 deletions final_project/EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import requests
import json

def emotion_detector(text_to_analyze):
# Si el texto está vacío o tiene solo espacios, devolvemos un diccionario con None
if not text_to_analyze.strip():
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}

# El resto del código sigue igual:
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
}
}

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

if response.status_code == 200:
response_data = response.json()
emotions = response_data['emotionPredictions'][0]['emotion']
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
}
else:
return {
'anger': None,
'disgust': None,
'fear': None,
'joy': None,
'sadness': None,
'dominant_emotion': None
}
59 changes: 59 additions & 0 deletions final_project/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
server.py

Este archivo contiene el servidor Flask que maneja las peticiones POST a la ruta '/emotionDetector'.
Utiliza la función 'emotion_detector' para detectar emociones en un texto dado.

Dependencias:
- Flask
- EmotionDetection (función emotion_detector)
- requests (para manejar errores de conexión)

Funciones:
- detect_emotion: Maneja las peticiones POST y devuelve las emociones detectadas.
"""
from flask import Flask, request, jsonify
from EmotionDetection.emotion_detection import emotion_detector
import requests # Aquí importamos 'requests'

app = Flask(__name__)

@app.route("/emotionDetector", methods=["POST"])
def detect_emotion():
"""
Recibe un texto por POST y detecta la emoción dominante utilizando el modelo de Watson NLP.

Retorna:
dict: Un diccionario con las emociones detectadas y la emoción dominante.
"""
try:
data = request.get_json()
text_to_analyze = data.get("text", "")

if not text_to_analyze.strip():
return jsonify(message="¡Texto inválido! ¡Por favor, intenta de nuevo!"), 400

emotions = emotion_detector(text_to_analyze)

if emotions["dominant_emotion"] is None:
return jsonify(message="¡Texto inválido! ¡Por favor, intenta de nuevo!"), 400

response_message = (
f"Para la declaración dada, la respuesta del sistema es "
f"'anger': {emotions['anger']}, "
f"'disgust': {emotions['disgust']}, "
f"'fear': {emotions['fear']}, "
f"'joy': {emotions['joy']}, "
f"'sadness': {emotions['sadness']}. "
f"La emoción dominante es {emotions['dominant_emotion']}."
)

return jsonify(message=response_message)

except (requests.exceptions.RequestException, ValueError) as e:
# Captura excepciones más específicas
print(f"Error: {e}")
return jsonify(message="¡Ocurrió un error en el servidor!"), 500

if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
11 changes: 11 additions & 0 deletions final_project/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from setuptools import setup, find_packages

setup(
name='EmotionDetection',
version='0.1',
packages=find_packages(),
install_requires=[
"requests",
"Flask",
],
)
37 changes: 37 additions & 0 deletions final_project/test_emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import unittest
from EmotionDetection.emotion_detection import emotion_detector

class TestEmotionDetection(unittest.TestCase):

def test_joy_emotion(self):
"""Test that joy is correctly detected as the dominant emotion"""
result = emotion_detector("I am glad this happened")
print(result)
self.assertEqual(result["dominant_emotion"], "joy")

def test_anger_emotion(self):
"""Test that anger is correctly detected as the dominant emotion"""
result = emotion_detector("I am really angry about this")
print(result)
self.assertEqual(result["dominant_emotion"], "anger")

def test_disgust_emotion(self):
"""Test that disgust is correctly detected as the dominant emotion"""
result = emotion_detector("I feel disgusted just hearing about this")
print(result)
self.assertEqual(result["dominant_emotion"], "disgust")

def test_sadness_emotion(self):
"""Test that sadness is correctly detected as the dominant emotion"""
result = emotion_detector("I am so sad about this")
print(result)
self.assertEqual(result["dominant_emotion"], "sadness")

def test_fear_emotion(self):
"""Test that fear is correctly detected as the dominant emotion"""
result = emotion_detector("I am very afraid this will happen")
print(result)
self.assertEqual(result["dominant_emotion"], "fear")

if __name__ == "__main__":
unittest.main()
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
requests==2.32.3