demo-creator / app.py
vmoras's picture
Fix bugs: name of client, languages saved and missing standalone prompt
797a248
raw
history blame
10.1 kB
import os
from dotenv import load_dotenv
load_dotenv()
import time
from services import utils
from services import chatbot
import gradio as gr
with gr.Blocks() as app:
# ----------------------------------------------- FRONT -------------------------------------------------------
with gr.Tab('General info'):
client = gr.Textbox(
label='Nombre del cliente', placeholder='Inserte el nombre del cliente, por ejemplo Visit Orlando'
)
languages = gr.Checkboxgroup(
choices=['español', 'ingles', 'portugués'], value='español', label='Idiomas', interactive=True,
info='Seleccione todos los idiomas que el chatbot va a hablar (al menos debe tener 1 idioma)'
)
name = gr.Dropdown(
choices=['Bella'], value='Bella', label='Nombre del chatbot',
info='Seleccione el nombre del chatbot, si no se encuentra en la lista, contacte al administrador'
)
max_num_questions = gr.Number(
value=5, minimum=2, maximum=10, label='Número preguntas', interactive=True,
info='Máximo numero de preguntas que puede hacer el usuario.'
)
with gr.Tab('Images'):
base_image = gr.Image(label='Imagen base para los videos', sources=['upload'], type='pil')
with gr.Tab('Greeting and goodbye'):
_ = gr.Markdown(
'Ingrese los saludos, despedidas y mensajes de error que deba usar el chatbot.'
)
with gr.Row():
greet = gr.Textbox(label='Mensaje', info='Ingrese el mensaje a decir por el chatbot.')
type_greet = gr.Dropdown(
choices=['Saludo', 'Despedida', 'Error'], value='Saludo', interactive=True,
info='Seleccione si es saludo, despedida o mensaje de error.', label='Tipo mensaje'
)
language_greet = gr.Dropdown(
choices=['español'], value='español', interactive=True,
info='Seleccione el idioma en el que esta el texto.', label='Idioma'
)
send_greet_button = gr.Button(value='Añadir')
messages_table = gr.DataFrame(
headers=['Eliminar', 'Mensaje', 'Tipo mensaje', 'Idioma'], type='array', interactive=False
)
with gr.Tab('Random data'):
_ = gr.Markdown(
'Si quiere que Bella diga algunos datos random mientras busca la información, ingrese dichos párrafos aca.'
)
with gr.Row():
random_data = gr.Text(
placeholder='Ingrese el dato random', info='Ingrese el mensaje a decir por el chatbot.',
label='Dato random'
)
language_random = gr.Dropdown(
choices=['español'], value='español', interactive=True,
info='Seleccione el idioma en el que esta el texto.', label='Idioma'
)
send_random_button = gr.Button(value='Añadir')
random_table = gr.DataFrame(headers=['Eliminar', 'Dato random', 'Idioma'], type='array', interactive=False)
with gr.Tab('Questions - Context'):
with gr.Row():
question = gr.Text(placeholder='Ingrese su pregunta', label='Pregunta')
context = gr.Text(placeholder='Ingrese el párrafo u oración que contesta dicha pregunta', label='Contexto')
send_question_button = gr.Button(value='Añadir')
questions_table = gr.DataFrame(
headers=['Eliminar', 'Pregunta', 'Contexto'], type='array', interactive=False
)
with gr.Tab('Create chatbot'):
_ = gr.Markdown(
"Asegúrese que toda la información este correcta antes de enviarla."
)
create_chatbot_button = gr.Button(value='Crear chatbot')
with gr.Tab('Prompts'):
general_prompt = gr.Text(
placeholder='Ingrese el prompt general del bot', label='General prompt'
)
context_prompt = gr.Text(
placeholder='Ingrese el prompt usado para encontrar el contexto', label='Standalone prompt'
)
_ = gr.Markdown(
"```\n"
"Recuerde dejar estos formatos en los prompts: \n"
"----------------------- General --------------------------\n"
"=========\n"
"Contexto:\n"
"CONTEXTO\n"
"=========\n"
"\n"
"----------------------- Standalone -----------------------\n"
"You are a standalone question-maker. Given the following chat history and follow-up message, rephrase "
"the follow-up phrase to be a standalone question (sometimes the follow-up is not a question, so create "
"a standalone phrase), in spanish. In the standalone message you must include all the information at the "
"moment that is known about the customer, all the important nouns and what they are looking for. In cases "
"where you think is usefully, include what is the best recommendation for the customer. To give you "
"context, the conversation is about (INGRESE INFORMACIÓN DE LA MARCA, EL NOMBRE Y DE MANERA MUY GENERAL "
"QUE ES LO QUE VENDE).\n"
"There might be moments when there isn't a question in those cases return a standalone phrase: for example "
"if the user says 'hola' (or something similar) then the output would be 'el usuario está saludando', or "
"if the user says 'gracias' or 'es muy util' (or something similar) then the output would be a phrase "
"showing that the user is grateful and what they are grateful for, or if the user say 'si' then it would "
"be a phrase encapsulating the relationship to its previous question or phrase.\n"
"Your response cannot be more than 50 words.\n"
"Chat History:\n"
"\n"
"HISTORY\n"
"Follow-up message: QUESTION\n"
"Standalone message:\n", line_breaks=True
)
with gr.Tab('Test'):
start_test_button = gr.Button(value='Iniciar test')
with gr.Column(visible=False) as chat_row:
chat = gr.Chatbot(label='Chat')
output_audio = gr.Audio(interactive=False, label='Audio', autoplay=True, visible=False)
user_input = gr.Text(label='Escribe tus preguntas')
with gr.Tab('Prompts by languages'):
with gr.Row():
prompt_data = gr.Text(placeholder='Ingrese el prompt', info='Ingrese el prompt.', label='Prompt')
language_prompt = gr.Dropdown(
choices=['español'], value='español', interactive=True,
info='Seleccione el idioma en el que esta el texto.', label='Idioma'
)
send_prompt_button = gr.Button(value='Añadir')
prompts_table = gr.DataFrame(headers=['Eliminar', 'Prompts', 'Idioma'], type='array', interactive=False)
with gr.Tab('Submit'):
_ = gr.Markdown(
"Asegúrese que hizo las suficientes pruebas para aprobar el chatbot."
)
submit_button = gr.Button(value='ENVIAR!')
output_file = gr.File(interactive=False, label='Output file')
# ----------------------------------------------- ACTIONS -----------------------------------------------------
# Update the dataframes based on the languages selected in the first tab
languages.change(
utils.add_language, languages, [language_greet, language_random, language_prompt]
)
# Add info to the tables
send_greet_button.click(
utils.add_data_table,
[messages_table, greet, type_greet, language_greet],
[messages_table, greet, type_greet, language_greet]
)
send_random_button.click(
utils.add_data_table,
[random_table, random_data, language_random],
[random_table, random_data, language_random]
)
send_question_button.click(
utils.add_data_table,
[questions_table, question, context],
[questions_table, question, context]
)
send_prompt_button.click(
utils.add_data_table,
[prompts_table, prompt_data, language_prompt],
[prompts_table, prompt_data, language_prompt]
)
# Remove info from the tables
messages_table.select(
utils.remove_data_table, messages_table, messages_table
)
random_table.select(
utils.remove_data_table, random_table, random_table
)
questions_table.select(
utils.remove_data_table, questions_table, questions_table
)
# Create the chatbot: create media (csv files, audio and video) and vectorstore
create_chatbot_button.click(
lambda: gr.update(value='Creating chatbot...', interactive=False), None, create_chatbot_button
).then(
utils.create_chatbot,
[client, name, messages_table, random_table, questions_table, base_image],
create_chatbot_button
)
# Initialize chat
start_test_button.click(
lambda: gr.update(value='Iniciando chat...'), None, start_test_button
).then(
lambda: time.sleep(1.5), None, None
).then(
chatbot.start_chat, client, [chat, output_audio, chat_row]
).then(
lambda: gr.update(value='Reiniciar chat'), None, start_test_button
)
# Chat with the chatbot
user_input.submit(
chatbot.get_random_data, client, output_audio
).then(
chatbot.get_answer,
[chat, user_input, client, general_prompt, context_prompt],
[chat, user_input, output_audio], show_progress='hidden'
)
# Submit chatbot: save prompts
submit_button.click(
lambda: gr.update(value='Subiendo la información', interactive=False), None, submit_button
).then(
utils.save_prompts, [client, context_prompt, prompts_table]
).then(
utils.generate_json, [client, languages, max_num_questions, name], output_file
).then(
lambda: gr.update(value='Información subida!!', interactive=False), None, submit_button
)
app.launch(debug=True, auth=(os.environ.get('SPACE_USERNAME'), os.environ.get('SPACE_PASSWORD')))