|
|
|
import streamlit as st
|
|
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
|
import torch
|
|
import numpy as np
|
|
|
|
|
|
MODEL_NAME = "bert-base-uncased"
|
|
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
|
model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=3)
|
|
|
|
|
|
palabras_clave = {
|
|
"Positivo": ["feliz", "alegre", "contento", "genial", "maravilloso"],
|
|
"Negativo": ["triste", "deprimido", "mal", "horrible", "terrible"],
|
|
"Ambiguo": ["no sé", "confuso", "indeciso", "raro"]
|
|
}
|
|
|
|
|
|
def predecir_sentimiento(texto):
|
|
"""
|
|
Toma un texto de entrada y devuelve la clasificación del sentimiento usando el modelo BERT.
|
|
Sentimientos posibles: Negativo, Neutral, Positivo.
|
|
"""
|
|
entradas = tokenizer(texto, return_tensors="pt", truncation=True, padding=True, max_length=128)
|
|
with torch.no_grad():
|
|
salidas = model(**entradas)
|
|
prediccion = np.argmax(salidas.logits.numpy(), axis=1)
|
|
etiquetas = ["Negativo", "Neutral", "Positivo"]
|
|
return etiquetas[prediccion[0]]
|
|
|
|
|
|
def ajustar_sentimiento(texto, sentimiento_modelo):
|
|
"""
|
|
Ajusta el sentimiento clasificado por el modelo si se encuentran palabras clave en el texto.
|
|
"""
|
|
texto = texto.lower()
|
|
for palabra in palabras_clave["Positivo"]:
|
|
if palabra in texto:
|
|
return "Positivo"
|
|
for palabra in palabras_clave["Negativo"]:
|
|
if palabra in texto:
|
|
return "Negativo"
|
|
for palabra in palabras_clave["Ambiguo"]:
|
|
if palabra in texto:
|
|
return "Ambiguo"
|
|
return sentimiento_modelo
|
|
|
|
|
|
st.markdown("""
|
|
<style>
|
|
body {
|
|
background-color: #fdfdff;
|
|
color: #4d4d4d;
|
|
}
|
|
.reportview-container {
|
|
background-color: #f8f9fa;
|
|
}
|
|
h1, h2, h3 {
|
|
color: #6c757d;
|
|
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
|
}
|
|
.stTextArea label {
|
|
font-size: 18px;
|
|
color: #6c757d;
|
|
}
|
|
.stButton button {
|
|
background-color: #d1e7dd;
|
|
color: #155724;
|
|
border-radius: 12px;
|
|
font-weight: bold;
|
|
border: none;
|
|
}
|
|
.stButton button:hover {
|
|
background-color: #badbcc;
|
|
}
|
|
</style>
|
|
""", unsafe_allow_html=True)
|
|
|
|
|
|
st.markdown("""
|
|
<h1 style='text-align: center; color: #6c757d;'>
|
|
¿Confundido con tus sentimientos? <br> Identifiquémoslo juntos.
|
|
</h1>
|
|
""", unsafe_allow_html=True)
|
|
|
|
|
|
st.write("""
|
|
Esta aplicación utiliza un modelo preentrenado de **BERT** para clasificar el sentimiento de un texto en
|
|
**Positivo**, **Neutral** o **Negativo**.\n\n
|
|
Escribe cualquier comentario, pensamiento o frase y te ayudaré a entender su tono general. 😊
|
|
""")
|
|
|
|
|
|
texto_usuario = st.text_area("¿Qué te gustaría compartir hoy?", placeholder="Cuéntame cómo te sientes...")
|
|
|
|
|
|
if st.button("Analizar Sentimiento"):
|
|
if texto_usuario.strip():
|
|
|
|
sentimiento_modelo = predecir_sentimiento(texto_usuario)
|
|
|
|
|
|
sentimiento_final = ajustar_sentimiento(texto_usuario, sentimiento_modelo)
|
|
|
|
|
|
st.subheader(f"El sentimiento del texto es: {sentimiento_final}")
|
|
|
|
|
|
if sentimiento_final == "Negativo":
|
|
st.write("Parece que no estás del todo contento con esto, y está bien no saber cómo sentirse a veces. 😊")
|
|
elif sentimiento_final == "Neutral":
|
|
st.write("Hmm, el tono del texto parece neutro. Si necesitas hablar más sobre esto, ¡aquí estoy para escuchar! 🤗")
|
|
elif sentimiento_final == "Positivo":
|
|
st.write("¡Qué bien que te sientes positivo! 🌟 Sigue disfrutando esa energía.")
|
|
else:
|
|
st.warning("Por favor ingresa un texto válido para analizar.")
|
|
|
|
|
|
st.markdown("---")
|
|
st.markdown("""
|
|
<p style='text-align: center; color: #6c757d; font-size: 14px;'>
|
|
Desarrollado por <strong> Grupo 7 - Procesamiento de datos con AI - Especialización en Inteligencia Artificial UAO </strong> | Proyecto del Taller Final - Módulo 2 🚀
|
|
</p>
|
|
""", unsafe_allow_html=True) |