Juliofc commited on
Commit
df42594
·
verified ·
1 Parent(s): 0bf6c87

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -16
app.py CHANGED
@@ -32,31 +32,52 @@ CHAT_TEMPLATE= """{% for message in messages %}
32
  {% endfor %}""" # Asegúrate de usar tu CHAT_TEMPLATE aquí
33
  tokenizer.chat_template = CHAT_TEMPLATE
34
 
 
 
 
 
 
 
35
  # Función para generar respuestas del modelo
36
  def generate_response(user_input, chat_history):
37
  # Preparar el input agregando el historial de chat
38
- mensajes = [{"content": user_input, "role": "user"}]
39
- user_input = tokenizer.apply_chat_template(mensajes, tokenize=False)
40
- input_with_history = chat_history + user_input
41
 
42
- input_tokens = tokenizer(input_with_history, return_tensors='pt', padding=True, truncation=True, max_length=1024).to(device)
 
 
43
 
44
  # Generar la respuesta
45
  output_tokens = model_with_adapter.generate(**input_tokens, max_length=1024, pad_token_id=tokenizer.eos_token_id, top_k=50, top_p=0.95, temperature=0.7)
46
  generated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
 
 
 
 
 
 
47
 
48
- # Actualizar el historial del chat
49
- new_chat_history = chat_history + "\n" + generated_text
50
- return generated_text, new_chat_history
 
 
 
 
 
 
 
 
51
 
52
- # Gradio interface
53
- def chat_interface(user_input, chat_history=""):
54
- response, new_chat_history = generate_response(user_input, chat_history)
55
- return response, new_chat_history
 
 
 
 
56
 
57
- iface = gr.Interface(fn=chat_interface,
58
- inputs=[gr.inputs.Textbox(lines=2, label="Tu Mensaje"), gr.inputs.Textbox(lines=10, label="Historial de Chat", default="")],
59
- outputs=[gr.outputs.Textbox(label="Respuesta del Modelo"), gr.outputs.Textbox(label="Nuevo Historial de Chat")],
60
- description="Chat con tu Modelo")
61
 
62
- iface.launch()
 
32
  {% endfor %}""" # Asegúrate de usar tu CHAT_TEMPLATE aquí
33
  tokenizer.chat_template = CHAT_TEMPLATE
34
 
35
+ # Función para generar respuestas del modelo
36
+ import gradio as gr
37
+
38
+ # Asume que todas tus importaciones previas y configuraciones del modelo están aquí
39
+
40
+ # Aquí deberías tener definida la función `generate_response` tal como la compartiste
41
  # Función para generar respuestas del modelo
42
  def generate_response(user_input, chat_history):
43
  # Preparar el input agregando el historial de chat
44
+ chat_history.append({"content": user_input, "role": "user"})
 
 
45
 
46
+ user_input = tokenizer.apply_chat_template(chat_history, tokenize=False)
47
+
48
+ input_tokens = tokenizer(user_input, return_tensors='pt', padding=True, truncation=True, max_length=1024).to(device)
49
 
50
  # Generar la respuesta
51
  output_tokens = model_with_adapter.generate(**input_tokens, max_length=1024, pad_token_id=tokenizer.eos_token_id, top_k=50, top_p=0.95, temperature=0.7)
52
  generated_text = tokenizer.decode(output_tokens[0], skip_special_tokens=True)
53
+
54
+ last_us = generated_text.rfind("</user>") + len("</user>")
55
+ last_as = generated_text.rfind("</assistant>")
56
+ generated_text = generated_text[last_us:last_as].strip()
57
+ chat_history.append({"content": generated_text, "role": "assistant"})
58
+ return generated_text, chat_history
59
 
60
+ # Inicializa el historial de la conversación como una lista vacía
61
+ historial_de_chat = []
62
+
63
+ # Define la función que será llamada por la interfaz de Gradio
64
+ def chatbot_interface(pregunta):
65
+ global historial_de_chat
66
+ # Genera la respuesta utilizando tu modelo
67
+ respuesta, historial_de_chat = generate_response(pregunta, historial_de_chat)
68
+ # Prepara el historial de chat para mostrarlo en la interfaz
69
+ historial_para_mostrar = "\n".join([f"{m['role'].capitalize()}: {m['content']}" for m in historial_de_chat])
70
+ return historial_para_mostrar
71
 
72
+ with gr.Blocks() as app:
73
+ with gr.Row():
74
+ gr.Markdown("### Chat de WhatsApp Simulado")
75
+ with gr.Row():
76
+ chatbox = gr.Textbox(label="Escribe tu pregunta aquí", placeholder="Hola, ¿cómo estás?")
77
+ with gr.Row():
78
+ boton_enviar = gr.Button("Enviar")
79
+ historial = gr.Textbox(label="Historial de Chat", lines=20, interactive=False, placeholder="Aquí aparecerán tus mensajes y las respuestas.")
80
 
81
+ boton_enviar.click(fn=chatbot_interface, inputs=chatbox, outputs=historial)
 
 
 
82
 
83
+ app.launch()