Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
entradas = tokenizer(texto, return_tensors="pt", truncation=True, padding=True, max_length=128)
|
26 |
+
with torch.no_grad():
|
27 |
+
salidas = model(**entradas)
|
28 |
+
prediccion = np.argmax(salidas.logits.numpy(), axis=1)
|
29 |
+
etiquetas = ["Negativo", "Neutral", "Positivo"]
|
30 |
+
return etiquetas[prediccion[0]]
|
31 |
+
|
32 |
+
# Función para ajustar el sentimiento con palabras clave
|
33 |
+
def ajustar_sentimiento(texto, sentimiento_modelo):
|
34 |
+
"""
|
35 |
+
Ajusta el sentimiento clasificado por el modelo si se encuentran palabras clave en el texto.
|
36 |
+
"""
|
37 |
+
texto = texto.lower()
|
38 |
+
for palabra in palabras_clave["Positivo"]:
|
39 |
+
if palabra in texto:
|
40 |
+
return "Positivo"
|
41 |
+
for palabra in palabras_clave["Negativo"]:
|
42 |
+
if palabra in texto:
|
43 |
+
return "Negativo"
|
44 |
+
for palabra in palabras_clave["Ambiguo"]:
|
45 |
+
if palabra in texto:
|
46 |
+
return "Ambiguo"
|
47 |
+
return sentimiento_modelo
|
48 |
+
|
49 |
+
# Estilos personalizados con CSS
|
50 |
+
st.markdown("""
|
51 |
+
<style>
|
52 |
+
body {
|
53 |
+
background-color: #fdfdff;
|
54 |
+
color: #4d4d4d;
|
55 |
+
}
|
56 |
+
.reportview-container {
|
57 |
+
background-color: #f8f9fa;
|
58 |
+
}
|
59 |
+
h1, h2, h3 {
|
60 |
+
color: #6c757d;
|
61 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
62 |
+
}
|
63 |
+
.stTextArea label {
|
64 |
+
font-size: 18px;
|
65 |
+
color: #6c757d;
|
66 |
+
}
|
67 |
+
.stButton button {
|
68 |
+
background-color: #d1e7dd;
|
69 |
+
color: #155724;
|
70 |
+
border-radius: 12px;
|
71 |
+
font-weight: bold;
|
72 |
+
border: none;
|
73 |
+
}
|
74 |
+
.stButton button:hover {
|
75 |
+
background-color: #badbcc;
|
76 |
+
}
|
77 |
+
</style>
|
78 |
+
""", unsafe_allow_html=True)
|
79 |
+
|
80 |
+
# Título de la aplicación
|
81 |
+
st.markdown("""
|
82 |
+
<h1 style='text-align: center; color: #6c757d;'>
|
83 |
+
¿Confundido con tus sentimientos? <br> Identifiquémoslo juntos.
|
84 |
+
</h1>
|
85 |
+
""", unsafe_allow_html=True)
|
86 |
+
|
87 |
+
# Descripción de la aplicación
|
88 |
+
st.write("""
|
89 |
+
Esta aplicación utiliza un modelo preentrenado de **BERT** para clasificar el sentimiento de un texto en
|
90 |
+
**Positivo**, **Neutral** o **Negativo**.\n\n
|
91 |
+
Escribe cualquier comentario, pensamiento o frase y te ayudaré a entender su tono general. 😊
|
92 |
+
""")
|
93 |
+
|
94 |
+
# Entrada del usuario
|
95 |
+
texto_usuario = st.text_area("¿Qué te gustaría compartir hoy?", placeholder="Cuéntame cómo te sientes...")
|
96 |
+
|
97 |
+
# Botón para analizar el sentimiento
|
98 |
+
if st.button("Analizar Sentimiento"):
|
99 |
+
if texto_usuario.strip():
|
100 |
+
# Predecir el sentimiento usando el modelo
|
101 |
+
sentimiento_modelo = predecir_sentimiento(texto_usuario)
|
102 |
+
|
103 |
+
# Ajustar el sentimiento si se detectan palabras clave
|
104 |
+
sentimiento_final = ajustar_sentimiento(texto_usuario, sentimiento_modelo)
|
105 |
+
|
106 |
+
# Mostrar el resultado al usuario
|
107 |
+
st.subheader(f"El sentimiento del texto es: {sentimiento_final}")
|
108 |
+
|
109 |
+
# Respuestas empáticas según el sentimiento
|
110 |
+
if sentimiento_final == "Negativo":
|
111 |
+
st.write("Parece que no estás del todo contento con esto, y está bien no saber cómo sentirse a veces. 😊")
|
112 |
+
elif sentimiento_final == "Neutral":
|
113 |
+
st.write("Hmm, el tono del texto parece neutro. Si necesitas hablar más sobre esto, ¡aquí estoy para escuchar! 🤗")
|
114 |
+
elif sentimiento_final == "Positivo":
|
115 |
+
st.write("¡Qué bien que te sientes positivo! 🌟 Sigue disfrutando esa energía.")
|
116 |
+
else:
|
117 |
+
st.warning("Por favor ingresa un texto válido para analizar.")
|
118 |
+
|
119 |
+
# Pie de página personalizado
|
120 |
+
st.markdown("---")
|
121 |
+
st.markdown("""
|
122 |
+
<p style='text-align: center; color: #6c757d; font-size: 14px;'>
|
123 |
+
Desarrollado por <strong> Grupo 7 - Procesamiento de datos con AI - Especialización en Inteligencia Artificial UAO </strong> | Proyecto del Taller Final - Módulo 2 🚀
|
124 |
+
</p>
|
125 |
+
""", unsafe_allow_html=True)
|