diff --git a/emotion_detection.py b/emotion_detection.py new file mode 100644 index 000000000..c371ce1ad --- /dev/null +++ b/emotion_detection.py @@ -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) + + + diff --git a/server.py b/server.py new file mode 100644 index 000000000..140e53f96 --- /dev/null +++ b/server.py @@ -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) diff --git a/setup.py b/setup.py new file mode 100644 index 000000000..aacc3035a --- /dev/null +++ b/setup.py @@ -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="ramirez_edson@hotmail.com", + 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", +) diff --git a/test_emotion_detection.py b/test_emotion_detection.py new file mode 100644 index 000000000..e1d3762bf --- /dev/null +++ b/test_emotion_detection.py @@ -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() +