File size: 2,476 Bytes
fc3cf6d
 
7ec5fdb
a8a26fe
fc3cf6d
 
a8a26fe
fc3cf6d
 
 
a8a26fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609cccb
a8a26fe
 
 
609cccb
a8a26fe
 
fc3cf6d
a8a26fe
 
 
 
 
 
 
 
 
 
 
fc3cf6d
a8a26fe
fc3cf6d
a8a26fe
 
 
fc3cf6d
a8a26fe
 
fc3cf6d
a8a26fe
 
 
 
 
7ec5fdb
a8a26fe
7ec5fdb
a8a26fe
 
fc3cf6d
 
 
 
 
a8a26fe
 
fc3cf6d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import random

# Cargar el modelo y el tokenizador
model_name = "microsoft/DialoGPT-small"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

# Caché simple para respuestas frecuentes
response_cache = {}

# Lista de respuestas predefinidas para variar la conversación
fallback_responses = [
    "Interesante. ¿Puedes decirme más sobre eso?",
    "Entiendo. ¿Cómo te hace sentir eso?",
    "¿Qué te llevó a pensar en eso?",
    "Es una perspectiva interesante. ¿Has considerado otras alternativas?",
    "Me gustaría saber más. ¿Puedes elaborar un poco?",
]

def get_response(input_text, conversation_history):
    # Verificar si la respuesta está en caché
    if input_text in response_cache:
        return response_cache[input_text]
    
    # Limitar la longitud de la conversación
    if len(conversation_history) > 5:
        conversation_history = conversation_history[-5:]
    
    # Preparar el input para el modelo
    bot_input_ids = tokenizer.encode(conversation_history + input_text + tokenizer.eos_token, return_tensors='pt')
    
    # Generar respuesta
    chat_response_ids = model.generate(
        bot_input_ids, 
        max_length=1000, 
        pad_token_id=tokenizer.eos_token_id,
        no_repeat_ngram_size=3,
        do_sample=True,
        top_k=100,
        top_p=0.7,
        temperature=0.8
    )
    
    chat_response = tokenizer.decode(chat_response_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
    
    # Si la respuesta es vacía o muy corta, usar una respuesta predefinida
    if not chat_response or len(chat_response.split()) < 3:
        chat_response = random.choice(fallback_responses)
    
    # Guardar en caché
    response_cache[input_text] = chat_response
    
    return chat_response

def chatbot(input_text, history):
    history = history or []
    conversation_history = " ".join([f"{h[0]} {h[1]}" for h in history])
    
    response = get_response(input_text, conversation_history)
    
    history.append((input_text, response))
    return history, history

iface = gr.Interface(
    fn=chatbot,
    inputs=["text", "state"],
    outputs=["chatbot", "state"],
    title="Tu Compañero AI Mejorado",
    description="Un chatbot de IA diseñado para simular conversaciones personales de manera rápida y coherente.",
)

iface.launch()