Spaces:
Sleeping
Sleeping
CamiloVega
commited on
Commit
•
4f6c2c4
1
Parent(s):
30b3065
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import (
|
3 |
+
pipeline,
|
4 |
+
AutoModelForSequenceClassification,
|
5 |
+
AutoTokenizer
|
6 |
+
)
|
7 |
+
import torch
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
# Configurar el dispositivo
|
11 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
12 |
+
|
13 |
+
# === CONFIGURACIÓN DEL CHATBOT ===
|
14 |
+
chat_generator = pipeline(
|
15 |
+
'text-generation',
|
16 |
+
model='microsoft/DialoGPT-small',
|
17 |
+
device=device
|
18 |
+
)
|
19 |
+
|
20 |
+
# === CONFIGURACIÓN DEL ANALIZADOR DE SENTIMIENTOS ===
|
21 |
+
model_name = "nlptown/bert-base-multilingual-uncased-sentiment"
|
22 |
+
sentiment_tokenizer = AutoTokenizer.from_pretrained(model_name)
|
23 |
+
sentiment_model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
24 |
+
sentiment_model.to(device)
|
25 |
+
|
26 |
+
def chatbot(mensaje):
|
27 |
+
if not mensaje.strip():
|
28 |
+
return "Por favor, escribe un mensaje.", None, None
|
29 |
+
|
30 |
+
try:
|
31 |
+
# Generar respuesta del chatbot
|
32 |
+
respuesta = chat_generator(
|
33 |
+
mensaje,
|
34 |
+
max_length=100,
|
35 |
+
temperature=0.7,
|
36 |
+
do_sample=True,
|
37 |
+
top_p=0.95,
|
38 |
+
num_return_sequences=1
|
39 |
+
)[0]['generated_text']
|
40 |
+
|
41 |
+
respuesta = respuesta.replace(mensaje, "").strip()
|
42 |
+
|
43 |
+
# Analizar sentimiento del mensaje del usuario
|
44 |
+
inputs = sentiment_tokenizer(mensaje, return_tensors="pt", truncation=True,
|
45 |
+
max_length=512, padding=True)
|
46 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
47 |
+
|
48 |
+
outputs = sentiment_model(**inputs)
|
49 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
50 |
+
rating = torch.argmax(predictions).item() + 1
|
51 |
+
confidence = predictions[0][rating-1].item()
|
52 |
+
|
53 |
+
if rating <= 2:
|
54 |
+
sentimiento = "Muy Negativo"
|
55 |
+
elif rating == 3:
|
56 |
+
sentimiento = "Neutral"
|
57 |
+
elif rating == 4:
|
58 |
+
sentimiento = "Positivo"
|
59 |
+
else:
|
60 |
+
sentimiento = "Muy Positivo"
|
61 |
+
|
62 |
+
sentimiento_completo = f"{sentimiento} ({rating} estrellas)"
|
63 |
+
confianza = round(confidence * 100, 2)
|
64 |
+
|
65 |
+
return respuesta, sentimiento_completo, confianza
|
66 |
+
|
67 |
+
except Exception as e:
|
68 |
+
return f"Error: {str(e)}", "Error en el análisis", 0.0
|
69 |
+
|
70 |
+
# Crear la interfaz
|
71 |
+
demo = gr.Interface(
|
72 |
+
fn=chatbot,
|
73 |
+
inputs=[
|
74 |
+
gr.Textbox(
|
75 |
+
placeholder="Escribe tu mensaje...",
|
76 |
+
label="Mensaje",
|
77 |
+
lines=3
|
78 |
+
)
|
79 |
+
],
|
80 |
+
outputs=[
|
81 |
+
gr.Textbox(label="Respuesta del Chatbot"),
|
82 |
+
gr.Label(label="Sentimiento de tu mensaje"),
|
83 |
+
gr.Number(label="Confianza del análisis (%)")
|
84 |
+
],
|
85 |
+
title="Chatbot con Análisis de Sentimientos",
|
86 |
+
description="Un chatbot que responde a tus mensajes y analiza el sentimiento de lo que escribes",
|
87 |
+
examples=[
|
88 |
+
["¡Estoy muy feliz hoy!"],
|
89 |
+
["No me gusta nada este servicio, es terrible."],
|
90 |
+
["El día está normal, nada especial que contar."],
|
91 |
+
["¡Me encanta hablar contigo!"],
|
92 |
+
["Estoy un poco decepcionado con los resultados."]
|
93 |
+
],
|
94 |
+
allow_flagging="never",
|
95 |
+
cache_examples=True
|
96 |
+
)
|
97 |
+
|
98 |
+
# Lanzar la interfaz
|
99 |
+
demo.launch(share=True, debug=True)
|