Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Cargar el modelo BERT preentrenado y el tokenizador
|
8 |
+
MODEL_NAME = "bert-base-uncased"
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
10 |
+
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)
|
11 |
+
|
12 |
+
# Diccionario de palabras clave con sentimientos asociados
|
13 |
+
palabras_clave = {
|
14 |
+
"Positivo": ["feliz", "alegre", "contento", "genial", "maravilloso"],
|
15 |
+
"Negativo": ["triste", "deprimido", "mal", "horrible", "terrible"],
|
16 |
+
"Ambiguo": ["no sé", "confuso", "indeciso", "raro"]
|
17 |
+
}
|
18 |
+
|
19 |
+
# Función para predecir el sentimiento del modelo
|
20 |
+
def predecir_sentimiento(texto):
|
21 |
+
"""
|
22 |
+
Toma un texto de entrada y devuelve la clasificación del sentimiento usando el modelo BERT.
|
23 |
+
Sentimientos posibles: Negativo, Neutral, Positivo.
|
24 |
+
"""
|
25 |
+
# Tokenización del texto
|
26 |
+
entradas = tokenizer(texto, return_tensors="pt", truncation=True, padding=True, max_length=128)
|
27 |
+
# Predicción sin gradientes
|
28 |
+
with torch.no_grad():
|
29 |
+
salidas = model(**entradas)
|
30 |
+
prediccion = np.argmax(salidas.logits.numpy(), axis=1)
|
31 |
+
# Etiquetas posibles
|
32 |
+
etiquetas = ["Negativo", "Neutral", "Positivo"]
|
33 |
+
return etiquetas[prediccion[0]]
|
34 |
+
|
35 |
+
# Función para ajustar el sentimiento con palabras clave
|
36 |
+
def ajustar_sentimiento(texto, sentimiento_modelo):
|
37 |
+
"""
|
38 |
+
Ajusta el sentimiento clasificado por el modelo si se encuentran palabras clave en el texto.
|
39 |
+
"""
|
40 |
+
texto = texto.lower() # Convertir el texto a minúsculas
|
41 |
+
for palabra in palabras_clave["Positivo"]:
|
42 |
+
if palabra in texto:
|
43 |
+
return "Positivo"
|
44 |
+
for palabra in palabras_clave["Negativo"]:
|
45 |
+
if palabra in texto:
|
46 |
+
return "Negativo"
|
47 |
+
for palabra in palabras_clave["Ambiguo"]:
|
48 |
+
if palabra in texto:
|
49 |
+
return "Ambiguo"
|
50 |
+
return sentimiento_modelo # Si no se encuentran palabras clave, devuelve el sentimiento original
|
51 |
+
|
52 |
+
# Configuración de la interfaz Streamlit
|
53 |
+
st.title("Análisis de Sentimientos con BERT")
|
54 |
+
st.write(
|
55 |
+
"Esta aplicación utiliza un modelo preentrenado de BERT para clasificar el sentimiento de un texto en "
|
56 |
+
"**Negativo**, **Neutral** o **Positivo**.\n\n"
|
57 |
+
"Puedes escribir cualquier comentario, pensamiento o frase y te ayudaré a entender su tono general. 😊"
|
58 |
+
)
|
59 |
+
|
60 |
+
# Entrada del usuario
|
61 |
+
texto_usuario = st.text_area("¿Qué te gustaría compartir hoy?", "Cuéntame cómo te sientes...")
|
62 |
+
|
63 |
+
# Botón para analizar el sentimiento
|
64 |
+
if st.button("Analizar Sentimiento"):
|
65 |
+
if texto_usuario.strip(): # Verificar que la entrada no esté vacía
|
66 |
+
# Predecir el sentimiento usando el modelo
|
67 |
+
sentimiento_modelo = predecir_sentimiento(texto_usuario)
|
68 |
+
|
69 |
+
# Ajustar el sentimiento si se detectan palabras clave
|
70 |
+
sentimiento_final = ajustar_sentimiento(texto_usuario, sentimiento_modelo)
|
71 |
+
|
72 |
+
# Mostrar el resultado al usuario
|
73 |
+
st.subheader(f"El sentimiento del texto es: {sentimiento_final}")
|
74 |
+
|
75 |
+
# Respuestas empáticas según el sentimiento
|
76 |
+
if sentimiento_final == "Negativo":
|
77 |
+
st.write("Parece que no estás del todo contento con esto, y está bien no saber cómo sentirse a veces. 😊")
|
78 |
+
elif sentimiento_final == "Neutral":
|
79 |
+
st.write("Hmm, el tono del texto parece neutro. Si necesitas hablar más sobre esto, ¡aquí estoy para escuchar! 🤗")
|
80 |
+
elif sentimiento_final == "Positivo":
|
81 |
+
st.write("¡Qué bien que te sientes positivo! 🌟 Sigue disfrutando esa energía.")
|
82 |
+
|
83 |
+
# Detectar ambigüedad
|
84 |
+
if "no sé" in texto_usuario.lower() or "confundido" in texto_usuario.lower():
|
85 |
+
st.write("Parece que estás un poco indeciso, ¡y eso está bien! A veces los sentimientos son difíciles de descifrar. 😊")
|
86 |
+
else:
|
87 |
+
st.warning("Por favor ingresa un texto válido para analizar.")
|