File size: 4,942 Bytes
f1cf8a0
 
 
 
 
 
 
 
 
 
 
 
 
 
e301fb7
f1cf8a0
 
 
 
2ae53dc
0b2dc93
2ae53dc
 
0b2dc93
2ae53dc
0b2dc93
f1cf8a0
9f9f985
865bf54
 
9f9f985
f1cf8a0
 
 
 
 
 
 
 
 
9f9f985
 
f1cf8a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
962e849
f1cf8a0
 
 
865bf54
f1cf8a0
 
 
 
2ae53dc
0b2dc93
2ae53dc
 
 
9f9f985
 
f1cf8a0
 
 
 
 
 
 
 
 
 
 
9f9f985
 
f1cf8a0
a627b01
 
2ae53dc
f1cf8a0
 
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import os
import openai
from transformers import pipeline, Conversation
import gradio as gr
import json
from dotenv import load_dotenv

# Load environment variables from the .env file de forma local
load_dotenv()
import base64

with open("Iso_Logotipo_Ceibal.png", "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read()).decode()

openai.api_key = os.environ['apikey']

def clear_chat(message, chat_history):
     return "", []

def hide_fn():
    return gr.Textbox.update(visible=False)

def show_fn():
    return gr.Textbox.update(visible=True)

def add_new_message(message,person,chat_history):
     new_chat = []
     
     #new_chat.append({"role": "system", "content": 'Sos {} y tendrás que responder preguntas que te harán niños de escuela, las respuestas tienen que ser cómo si hablaras con {} y con la información de su vida. Las respuestas tienen que estar orientadas a niños entre 9 y 10 años. No respondas preguntas hasta que el usuario te pregunte sobre algún tema.'.format(person,person)})
     new_chat.append({"role": "system", "content": 'Sos {} y tendrás que responder preguntas que te harán niños de escuela (entre 6 y 9 años).El objetivo de los niños es adivinar quién sos, pero no se los podés decir si te lo preguntan. Tus respuestas tiene que ser cómo si hablaras con {} y con la información de su vida, sin decir tu nombre. Las respuestas tienen que estar orientadas a niños, por lo tanto debes cuidar el lenguaje y tratar de hablar de forma sencilla. No respondas preguntas hasta que el usuario te pregunte sobre algún tema.'.format(person,person)})
   
     for turn in chat_history:
          user, bot = turn
          new_chat.append({"role": "user", "content": user})
          new_chat.append({"role": "assistant","content":bot})
     new_chat.append({"role": "user","content":message})
     return new_chat
    
          

def respond(message, person, chat_history):
    prompt = add_new_message(message, person, chat_history)
    # stream = client.generate_stream(prompt,
    #                                   max_new_tokens=1024,
    #                                   stop_sequences=["\nUser:", "<|endoftext|>"],
    #                                   temperature=temperature)
    #                                   #stop_sequences to not generate the user answer
    # acc_text = ""
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages= prompt,
        temperature=0.5,
        max_tokens=1000,
        stream=True,
        )#.choices[0].message.content
    #chat_history.append((message, response))

    token_counter = 0 
    partial_words = "" 

    counter=0
    for chunk in response:
        chunk_message = chunk['choices'][0]['delta']
        if(len(chat_history))<1:
            # print("entró acaá")
            partial_words += chunk_message.content
            chat_history.append([message,chunk_message.content])
        else:
            # print("antes", chat_history)
            if(len(chunk_message)!=0):
                if(len(chunk_message)==2):
                    partial_words += chunk_message.content
                    chat_history.append([message,chunk_message.content])
                else:
                    partial_words += chunk_message.content
                    chat_history[-1] =([message,partial_words])
        yield "",chat_history


with gr.Blocks() as demo:
    gr.Markdown("""
    <center>
    <h1>
    Adivina el personaje usando un chatbot con Inteligencia Artificial.
    </h1>
    <img src='data:image/jpg;base64,{}' width=200px>
    <h3>
    Con este espacio puedes jugar a adivinar el personaje famoso o conocido. Primero una persona debe introducir el nombre y luego puede ocultarlo, para que al chatear no se vea con quién se está hablando. ¡Mucha suerte!
    </h3>
    </center>
    """.format(encoded_image))
    with gr.Row():
        with gr.Column(scale=4):
            person = gr.Textbox(label="Escribí el nombre del personaje famoso:")
        with gr.Column(scale=1):
            hide_button = gr.Button(value="No mostrar")
            show_button = gr.Button(value="Mostrar")
    with gr.Row():
        chatbot = gr.Chatbot( height=550) #just to fit the notebook
    with gr.Row():
        with gr.Row():
            with gr.Column(scale=4):
                msg = gr.Textbox(label="Texto de entrada")
            with gr.Column(scale=1):
                btn = gr.Button("Enviar")
                clear = gr.ClearButton(components=[msg, chatbot], value="Borrar chat")

   


    btn.click(respond, inputs=[msg,person, chatbot], outputs=[msg, chatbot])
    msg.submit(respond, inputs=[msg, person,chatbot], outputs=[msg, chatbot]) #Press enter to submit
    clear.click(clear_chat,inputs=[msg, chatbot], outputs=[msg, chatbot])
    hide_button.click(hide_fn,outputs=[person])
    show_button.click(show_fn,outputs=[person])
    
demo.queue()
demo.launch()