pablo-sampaio commited on
Commit
862d34a
1 Parent(s): b38ac3c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -11
app.py CHANGED
@@ -1,16 +1,85 @@
1
- import gradio as gr
2
- from transformers import pipeline
3
 
4
- pipe = pipeline("image-to-text",
5
- model="Salesforce/blip-image-captioning-base")
6
 
7
- def launch(input):
8
- out = pipe(input)
9
- return out[0]['generated_text']
10
 
11
- iface = gr.Interface(launch,
12
- inputs=gr.Image(type='pil'),
13
- outputs="text")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- iface.launch()
16
 
 
 
 
1
 
2
+ from openai import OpenAI
 
3
 
 
 
 
4
 
5
+ LOAD_SHARED_KEY = True
6
+
7
+ AUDIO_OUTPUT_FILE = "output" # prefixo do nome do arquivo de áudio .wav
8
+
9
+
10
+ OPENAI_CLIENT = None
11
+
12
+
13
+ # Função para converter o histórico de chat para o formato esperado pela API do OpenAI
14
+ def to_openai_chat_history(system_prompt, curr_message, chat_history):
15
+ prompt = [ { 'role': 'system', 'content': system_prompt } ]
16
+ for turn in chat_history:
17
+ user_message, bot_message = turn
18
+ prompt.append( {'role': 'user', 'content' : user_message} )
19
+ prompt.append( {'role': 'assistant', 'content' : bot_message} )
20
+ prompt.append( {'role': 'user', 'content' : curr_message } )
21
+ return prompt
22
+
23
+
24
+ def respond(system_prompt, user_message, chat_history, temperature, voice="echo"):
25
+ openai_history = to_openai_chat_history(system_prompt, user_message, chat_history)
26
+
27
+ bot_response = OPENAI_CLIENT.chat.completions.create(
28
+ messages=openai_history,
29
+ temperature=temperature,
30
+ model="gpt-3.5-turbo")
31
+
32
+ assistant_msg = bot_response.choices[0].message.content
33
+
34
+ # salva o audio
35
+ response = OPENAI_CLIENT.audio.speech.create(
36
+ model="tts-1",
37
+ voice=voice,
38
+ input=assistant_msg
39
+ )
40
+
41
+ output_audio_file = f"{AUDIO_OUTPUT_FILE}-{len(chat_history)+1:03}.wav"
42
+ #response.stream_to_file(output_audio_file)
43
+ response.write_to_file(output_audio_file)
44
+
45
+ # adiciona ao chat, com o tipo de dado esperado pelo Gradio
46
+ chat_history.append( (user_message, assistant_msg) )
47
+
48
+ return "", chat_history, output_audio_file
49
+
50
+
51
+ def reset_and_apply(openai_key):
52
+ global OPENAI_CLIENT
53
+ OPENAI_CLIENT = OpenAI(api_key=openai_key)
54
+ return [("", "Olá, vamos falar de futebol?")], AUDIO_OUTPUT_FILE + "-001.wav"
55
+
56
+
57
+ with gr.Blocks() as demo:
58
+ # aqui, é resetado e instanciado o cliente
59
+ initial_chat_history, initial_audio = reset_and_apply(os.environ['OPENAI_API_KEY'])
60
+
61
+ chatbot = gr.Chatbot(value=initial_chat_history)
62
+ audio_out = gr.Audio(label="Listen to the response", value=initial_audio, autoplay=True, interactive=False)
63
+ user_msg = gr.Textbox(label="Prompt")
64
+
65
+ with gr.Accordion(label="Advanced options",open=False):
66
+ system = gr.Textbox(label="System message", lines=3, value="Você é uma acompanhante de uma criança com idade entre 6 e 8 anos que adora futebol. \
67
+ Fale sobre times do Brasil, Inglaterra e Espanha e sobre seleções. Fale sobre craques do passado e grandes jogos. Fale sobre títulos de Copa do Mundo. Seja divertido e pró-ativo,\
68
+ tentando iniciar novos assuntos. Fale, no máximo, três frases por mensagem. E faça no máximo 1 pergunta por mensagem.")
69
+ openai_key = gr.Textbox(label="OPENAI API key", placeholder="Insert your API key here")
70
+ temperature = gr.Slider(label="temperature", minimum=0.0, maximum=1.0, value=0.5, step=0.1)
71
+ # opções de vozes, de uma lista predefinida
72
+ voice = gr.Dropdown(label="Voice", choices=["echo", "nova", "alloy", "fable", "onyx", "shimmer"], value="echo")
73
+ btnReset = gr.Button("Reset and apply")
74
+ btnReset.click(reset_and_apply, inputs=[openai_key], outputs=[chatbot, audio_out])
75
+
76
+ submit_btn = gr.Button("Submit")
77
+ clear_btn = gr.ClearButton(components=[user_msg, chatbot], value="Clear console")
78
+
79
+ submit_btn.click(respond, inputs=[system, user_msg, chatbot, temperature, voice], outputs=[user_msg, chatbot, audio_out]) # Click on the button
80
+ user_msg.submit( respond, inputs=[system, user_msg, chatbot, temperature, voice], outputs=[user_msg, chatbot, audio_out]) # Press enter to submit - same effect
81
+
82
+
83
+ demo.queue().launch(share=True)
84
 
 
85