diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..b19325833 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "final_project"] + path = final_project + url = https://github.com/rayoconico/F-Quinteros-final-project-emb-ai.git diff --git a/.theia/launch.json b/.theia/launch.json new file mode 100644 index 000000000..7b4bae022 --- /dev/null +++ b/.theia/launch.json @@ -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 +} diff --git a/.theia/settings.json b/.theia/settings.json new file mode 100644 index 000000000..e9dbffc6b --- /dev/null +++ b/.theia/settings.json @@ -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, +} diff --git a/final_project/EmotionDetection/__init__.py b/final_project/EmotionDetection/__init__.py new file mode 100644 index 000000000..6238ddc87 --- /dev/null +++ b/final_project/EmotionDetection/__init__.py @@ -0,0 +1 @@ +from .emotion_detection import emotion_detector \ No newline at end of file diff --git a/final_project/EmotionDetection/emotion_detection.py b/final_project/EmotionDetection/emotion_detection.py new file mode 100644 index 000000000..3e3d15ec4 --- /dev/null +++ b/final_project/EmotionDetection/emotion_detection.py @@ -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 + } diff --git a/final_project/server.py b/final_project/server.py new file mode 100644 index 000000000..d3d1f0fcf --- /dev/null +++ b/final_project/server.py @@ -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) diff --git a/final_project/setup.py b/final_project/setup.py new file mode 100644 index 000000000..e5901d7e9 --- /dev/null +++ b/final_project/setup.py @@ -0,0 +1,11 @@ +from setuptools import setup, find_packages + +setup( + name='EmotionDetection', + version='0.1', + packages=find_packages(), + install_requires=[ + "requests", + "Flask", + ], +) diff --git a/final_project/test_emotion_detection.py b/final_project/test_emotion_detection.py new file mode 100644 index 000000000..c61c085d2 --- /dev/null +++ b/final_project/test_emotion_detection.py @@ -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() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 000000000..d80d9fc2a --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests==2.32.3