Skip to content

emotion detection #77

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 4 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
1 change: 1 addition & 0 deletions EmotionDetection/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .emotion_detection import emotion_detector
47 changes: 47 additions & 0 deletions EmotionDetection/emotion_detection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import nltk
from nltk.sentiment import SentimentIntensityAnalyzer

nltk.download("vader_lexicon", quiet=True) # Descarga el léxico si no está disponible


def emotion_detector(text_to_analize):
"""
Detecta emociones en un texto utilizando NLTK VADER.

Args:
text_to_analize (str): El texto para analizar.

Returns:
dict: Un diccionario con las puntuaciones de emoción y la emoción dominante.
"""
if not text_to_analize:
return {
"anger": None,
"disgust": None,
"fear": None,
"joy": None,
"sadness": None,
"dominant_emotion": None,
}

analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores(text_to_analize)

emotion_scores = {
"anger": scores["neg"],
"disgust": scores["neg"] / 2,
"fear": scores["neg"] / 2,
"joy": scores["pos"],
"sadness": scores["neg"],
}

dominant_emotion = max(emotion_scores, key=emotion_scores.get)

return {
"anger": emotion_scores["anger"],
"disgust": emotion_scores["disgust"],
"fear": emotion_scores["fear"],
"joy": emotion_scores["joy"],
"sadness": emotion_scores["sadness"],
"dominant_emotion": dominant_emotion,
}
4 changes: 4 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# config.py
IBM_API_KEY = "tu_clave_api"
IBM_SERVICE_URL = "tu_url_servicio"
OTHER_VAR = "otro_valor"
13 changes: 13 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[project]
name = "oaqjp-final-project-emb-ai"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = [
"flask>=3.1.0",
"ibm-watson>=9.0.0",
"nltk>=3.9.1",
"pylint>=3.3.6",
"requests>=2.32.3",
]
46 changes: 46 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""
Flask application for emotion detection.
"""

from flask import Flask, jsonify, render_template, request

from EmotionDetection import emotion_detector

app = Flask(__name__)


@app.route("/")
def index():
"""Renders the index.html template."""
return render_template("index.html")


@app.route("/emotionDetector", methods=["POST"])
def emotion_detector_endpoint():
"""
Handles emotion detection requests and returns the result.

Returns:
str: The emotion detection result as a string.
"""
text_to_analyze = request.form["text"]
result = emotion_detector(text_to_analyze)

if result["dominant_emotion"] is None:
return "Invalid text! Please try again."

if "error" in result:
return jsonify({"error": result["error"]}), 500

response_text = (
f"For the given statement, the system response is 'anger': {result['anger']}, "
f"'disgust': {result['disgust']}, 'fear': {result['fear']}, "
f"'joy': {result['joy']} and 'sadness': {result['sadness']}. "
f"The dominant emotion is {result['dominant_emotion']}."
)

return response_text


if __name__ == "__main__":
app.run(debug=True)
11 changes: 6 additions & 5 deletions static/mywebscript.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
let RunSentimentAnalysis = ()=>{
textToAnalyze = document.getElementById("textToAnalyze").value;
let RunSentimentAnalysis = () => {
let textToAnalyze = document.getElementById("textToAnalyze").value;

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("system_response").innerHTML = xhttp.responseText;
document.getElementById("system_response").innerHTML = this.responseText;
}
};
xhttp.open("GET", "emotionDetector?textToAnalyze"+"="+textToAnalyze, true);
xhttp.send();
xhttp.open("POST", "/emotionDetector", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("text=" + encodeURIComponent(textToAnalyze));
}
3 changes: 2 additions & 1 deletion templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<body>
<div class="card">
<div class="card-body">
<h1 class="center-heading">NLP - Emotion Detection</h1>
<h1 class="center-heading">NLP - Emotion Detection</h1>
<div style="padding: 25px 25px 25px 25px;">
<h2 class="mb-3">
<label class="form-label">Please enter the text to be analyzed</label>
Expand All @@ -30,3 +30,4 @@ <h2 class="mb-3">
</div>
</div>
</body>
</html>
Empty file added test_emotion_detection.py
Empty file.
392 changes: 392 additions & 0 deletions uv.lock

Large diffs are not rendered by default.