Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Importar librerías necesarias
|
2 |
+
import streamlit as st
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
4 |
+
import torch
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
# Pie de página personalizado
|
8 |
+
st.markdown("""
|
9 |
+
<style>
|
10 |
+
body {
|
11 |
+
background-color: #f8f9fa; /* Fondo color pastel claro */
|
12 |
+
color: #4d4d4d; /* Texto en gris oscuro */
|
13 |
+
}
|
14 |
+
.reportview-container {
|
15 |
+
background-color: #fefefa;
|
16 |
+
}
|
17 |
+
.stTextArea label, .stButton button {
|
18 |
+
color: #6c757d; /* Color del texto de entrada */
|
19 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
20 |
+
}
|
21 |
+
.stButton button {
|
22 |
+
background-color: #d4edda; /* Botón en verde pastel */
|
23 |
+
color: #155724; /* Texto del botón */
|
24 |
+
border-radius: 10px;
|
25 |
+
border: none;
|
26 |
+
}
|
27 |
+
.stButton button:hover {
|
28 |
+
background-color: #c3e6cb; /* Botón en hover */
|
29 |
+
}
|
30 |
+
h1, h2, h3 {
|
31 |
+
color: #495057; /* Títulos */
|
32 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
33 |
+
}
|
34 |
+
</style>
|
35 |
+
""", unsafe_allow_html=True)
|
36 |
+
|
37 |
+
# Configuración del título principal
|
38 |
+
st.markdown("""
|
39 |
+
<h1 style='text-align: center; color: #6c757d;'>
|
40 |
+
¿Perdido en tus sentimientos? <br> Te ayudamos a dar el primer paso, identificándolo.
|
41 |
+
</h1>
|
42 |
+
<p style='text-align: center; color: #495057; font-size: 18px;'>
|
43 |
+
Esta aplicación utiliza un modelo preentrenado de BERT para clasificar el sentimiento de un texto en
|
44 |
+
<strong style="color:#28a745;">Positivo</strong>,
|
45 |
+
<strong style="color:#ffc107;">Neutral</strong> o
|
46 |
+
<strong style="color:#dc3545;">Negativo</strong>.
|
47 |
+
</p>
|
48 |
+
""", unsafe_allow_html=True)
|
49 |
+
|
50 |
+
|
51 |
+
# Cargar el modelo BERT preentrenado y el tokenizador
|
52 |
+
MODEL_NAME = "bert-base-uncased"
|
53 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
54 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)
|
55 |
+
|
56 |
+
# Diccionario de palabras clave con sentimientos asociados
|
57 |
+
palabras_clave = {
|
58 |
+
"Positivo": ["feliz", "alegre", "contento", "genial", "maravilloso"],
|
59 |
+
"Negativo": ["triste", "deprimido", "mal", "horrible", "terrible"],
|
60 |
+
"Ambiguo": ["no sé", "confuso", "indeciso", "raro"]
|
61 |
+
}
|
62 |
+
|
63 |
+
# Función para predecir el sentimiento del modelo
|
64 |
+
def predecir_sentimiento(texto):
|
65 |
+
"""
|
66 |
+
Toma un texto de entrada y devuelve la clasificación del sentimiento usando el modelo BERT.
|
67 |
+
Sentimientos posibles: Negativo, Neutral, Positivo.
|
68 |
+
"""
|
69 |
+
# Tokenización del texto
|
70 |
+
entradas = tokenizer(texto, return_tensors="pt", truncation=True, padding=True, max_length=128)
|
71 |
+
# Predicción sin gradientes
|
72 |
+
with torch.no_grad():
|
73 |
+
salidas = model(**entradas)
|
74 |
+
prediccion = np.argmax(salidas.logits.numpy(), axis=1)
|
75 |
+
# Etiquetas posibles
|
76 |
+
etiquetas = ["Negativo", "Neutral", "Positivo"]
|
77 |
+
return etiquetas[prediccion[0]]
|
78 |
+
|
79 |
+
# Función para ajustar el sentimiento con palabras clave
|
80 |
+
def ajustar_sentimiento(texto, sentimiento_modelo):
|
81 |
+
"""
|
82 |
+
Ajusta el sentimiento clasificado por el modelo si se encuentran palabras clave en el texto.
|
83 |
+
"""
|
84 |
+
texto = texto.lower() # Convertir el texto a minúsculas
|
85 |
+
for palabra in palabras_clave["Positivo"]:
|
86 |
+
if palabra in texto:
|
87 |
+
return "Positivo"
|
88 |
+
for palabra in palabras_clave["Negativo"]:
|
89 |
+
if palabra in texto:
|
90 |
+
return "Negativo"
|
91 |
+
for palabra in palabras_clave["Ambiguo"]:
|
92 |
+
if palabra in texto:
|
93 |
+
return "Ambiguo"
|
94 |
+
return sentimiento_modelo # Si no se encuentran palabras clave, devuelve el sentimiento original
|
95 |
+
|
96 |
+
# Configuración de la interfaz Streamlit
|
97 |
+
st.title("¿Perdido en tus sentimientos? Te ayudamos a dar el primer paso, identificándolo")
|
98 |
+
st.write(
|
99 |
+
"Esta aplicación utiliza un modelo preentrenado de BERT para clasificar el sentimiento de un texto en "
|
100 |
+
"**Negativo**, **Neutral** o **Positivo**.\n\n"
|
101 |
+
"Puedes escribir cualquier comentario, pensamiento o frase y te ayudaré a entender su tono general. 😊"
|
102 |
+
)
|
103 |
+
|
104 |
+
# Entrada del usuario
|
105 |
+
texto_usuario = st.text_area("¿Qué te gustaría compartir hoy?", "Cuéntame cómo te sientes...")
|
106 |
+
|
107 |
+
# Botón para analizar el sentimiento
|
108 |
+
if st.button("Analizar Sentimiento"):
|
109 |
+
if texto_usuario.strip(): # Verificar que la entrada no esté vacía
|
110 |
+
# Predecir el sentimiento usando el modelo
|
111 |
+
sentimiento_modelo = predecir_sentimiento(texto_usuario)
|
112 |
+
|
113 |
+
# Ajustar el sentimiento si se detectan palabras clave
|
114 |
+
sentimiento_final = ajustar_sentimiento(texto_usuario, sentimiento_modelo)
|
115 |
+
|
116 |
+
# Mostrar el resultado al usuario
|
117 |
+
st.subheader(f"El sentimiento del texto es: {sentimiento_final}")
|
118 |
+
|
119 |
+
# Respuestas empáticas según el sentimiento
|
120 |
+
if sentimiento_final == "Negativo":
|
121 |
+
st.write("Parece que no estás del todo contento con esto, y está bien no saber cómo sentirse a veces. 😊")
|
122 |
+
elif sentimiento_final == "Neutral":
|
123 |
+
st.write("Hmm, el tono del texto parece neutro. Si necesitas hablar más sobre esto, ¡aquí estoy para escuchar! 🤗")
|
124 |
+
elif sentimiento_final == "Positivo":
|
125 |
+
st.write("¡Qué bien que te sientes positivo! 🌟 Sigue disfrutando esa energía.")
|
126 |
+
|
127 |
+
# Detectar ambigüedad
|
128 |
+
if "no sé" in texto_usuario.lower() or "confundido" in texto_usuario.lower():
|
129 |
+
st.write("Parece que estás un poco indeciso, ¡y eso está bien! A veces los sentimientos son difíciles de descifrar. 😊")
|
130 |
+
else:
|
131 |
+
st.warning("Por favor ingresa un texto válido para analizar.")
|
132 |
+
|
133 |
+
# Pie de página personalizado
|
134 |
+
st.markdown("---")
|
135 |
+
st.markdown(
|
136 |
+
"Grupo 7 - Procesamiento de datos con AI - Especialización de Inteligencia Artificial UAO"
|
137 |
+
)
|