mindw96 commited on
Commit
2510877
β€’
1 Parent(s): 01b6e84

Upload 3 files

Browse files
Files changed (3) hide show
  1. .env +1 -0
  2. chatif.py +93 -0
  3. temp.mp3 +0 -0
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ OPENAI_API_KEY=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
chatif.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
3
+ from dotenv import load_dotenv
4
+ import os
5
+
6
+ load_dotenv()
7
+
8
+ client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
9
+
10
+ def play_tts(x: gr.LikeData):
11
+ response = client.audio.speech.create(
12
+ model="tts-1",
13
+ voice="alloy",
14
+ input=x.value
15
+ )
16
+ response.stream_to_file('temp.mp3')
17
+ f = gr.Audio('temp.mp3', streaming=True, elem_id='audio')
18
+ print(f'"{x.value}" saved temp.mp3 file')
19
+
20
+ return f
21
+
22
+
23
+ def answer(state, state_chatbot, text):
24
+ messages = state + [{
25
+ 'role': 'user',
26
+ 'content': text
27
+ }]
28
+
29
+ res = client.chat.completions.create(
30
+ model='gpt-4',
31
+ messages=messages
32
+ )
33
+
34
+ msg = res.choices[0].message.content
35
+
36
+ new_state = [{
37
+ 'role': 'user',
38
+ 'content': text
39
+ }, {
40
+ 'role': 'assistant',
41
+ 'content': msg
42
+ }]
43
+
44
+ state = state + new_state
45
+ state_chatbot = state_chatbot + [(text, msg)]
46
+
47
+ print(state)
48
+
49
+ return state, state_chatbot, state_chatbot
50
+
51
+
52
+ with gr.Blocks() as demo:
53
+ with gr.Row():
54
+ gr.HTML("""<div style="text-align: center; max-width: 500px; margin: 0 auto;">
55
+ <div>
56
+ <h1>Dongwook's ChatBot with TTS</h1>
57
+ <h2>μž¬μƒμ„ μ›ν•˜λŠ” 뢀뢄을 ν΄λ¦­ν•˜μ„Έμš” </h2>
58
+ </div>
59
+ </div>""")
60
+ with gr.Row():
61
+ audios = gr.Audio('temp.mp3', streaming=True, elem_id='audio')
62
+
63
+ state = gr.State([{
64
+ 'role': 'system',
65
+ 'content': 'You are a helpful assistant.'
66
+ }])
67
+ state_chatbot = gr.State([])
68
+
69
+ with gr.Row():
70
+ chatbot = gr.Chatbot(
71
+ [],
72
+ elem_id="chatbot",
73
+ bubble_full_width=False,
74
+ show_copy_button=True,
75
+ likeable=False,
76
+ )
77
+ chatbot.select(play_tts, None, outputs=audios)
78
+ # chatbot.click(fn=print_play, inputs=None,outputs=None)
79
+
80
+ with gr.Row():
81
+ txt = gr.Textbox(
82
+ scale=4,
83
+ show_label=False,
84
+ placeholder="Enter text and press enter",
85
+ container=False,
86
+ )
87
+
88
+ txt_msg = txt.submit(answer, [state, state_chatbot, txt], [state, state_chatbot, chatbot])
89
+ txt_msg.then(lambda: '', None, txt, queue=False)
90
+
91
+ demo.queue()
92
+ if __name__ == "__main__":
93
+ demo.launch(share=True)
temp.mp3 ADDED
Binary file (40.8 kB). View file