From 46127a5f8f814ad72515fe98543b83fc791c4e51 Mon Sep 17 00:00:00 2001 From: edsonramirez <111548676+edsonramirez@users.noreply.github.com> Date: Tue, 4 Feb 2025 14:47:51 -0500 Subject: [PATCH 1/2] Add files via upload --- emotion_detection.py | 16 ++++++++ server.py | 82 +++++++++++++++++++++++++++++++++++++++ setup.py | 20 ++++++++++ test_emotion_detection.py | 33 ++++++++++++++++ 4 files changed, 151 insertions(+) create mode 100644 emotion_detection.py create mode 100644 server.py create mode 100644 setup.py create mode 100644 test_emotion_detection.py diff --git a/emotion_detection.py b/emotion_detection.py new file mode 100644 index 000000000..e7c71210a --- /dev/null +++ b/emotion_detection.py @@ -0,0 +1,16 @@ +import requests + +def emotion_detector(text_to_analyse): + url = 'https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict' # URL of the sentiment analysis service + myobj = { "raw_document": { "text": text_to_analyse } } # Create a dictionary with the text to be analyzed + header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"} # Set the headers required for the API request + response = requests.post(url, json = myobj, headers=header) # Send a POST request to the API with the text and headers + return response.text # Return the response text from the API + + +# Test function +text = "I love this new technology." +print(emotion_detector(text)) + + + 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() + From 809ada34f2316252ae8279642a1e996ee3ab19e8 Mon Sep 17 00:00:00 2001 From: edsonramirez <111548676+edsonramirez@users.noreply.github.com> Date: Thu, 6 Feb 2025 17:31:01 -0500 Subject: [PATCH 2/2] Update emotion_detection.py --- emotion_detection.py | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/emotion_detection.py b/emotion_detection.py index e7c71210a..c371ce1ad 100644 --- a/emotion_detection.py +++ b/emotion_detection.py @@ -1,16 +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' # URL of the sentiment analysis service - myobj = { "raw_document": { "text": text_to_analyse } } # Create a dictionary with the text to be analyzed - header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"} # Set the headers required for the API request - response = requests.post(url, json = myobj, headers=header) # Send a POST request to the API with the text and headers - return response.text # Return the response text from the API +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) + } -# Test function -text = "I love this new technology." -print(emotion_detector(text)) + # 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)