salmanmapkar AI-DHD commited on
Commit
55f26ab
0 Parent(s):

Duplicate from AI-DHD/chatGPT_voice

Browse files

Co-authored-by: Alexander McLennan <AI-DHD@users.noreply.huggingface.co>

Files changed (4) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +196 -0
  4. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatGPT Voice
3
+ emoji: 📊
4
+ colorFrom: blue
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.12.0
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: AI-DHD/chatGPT_voice
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyChatGPT import ChatGPT
2
+ import gradio as gr
3
+ import os, json
4
+ from loguru import logger
5
+ import random
6
+ from transformers import pipeline
7
+ import torch
8
+
9
+ session_token = os.environ.get('SessionToken')
10
+
11
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
12
+
13
+ whisper_model = pipeline(
14
+ task="automatic-speech-recognition",
15
+ model="openai/whisper-large-v2",
16
+ chunk_length_s=30,
17
+ device=device,
18
+ )
19
+
20
+ all_special_ids = whisper_model.tokenizer.all_special_ids
21
+ transcribe_token_id = all_special_ids[-5]
22
+ translate_token_id = all_special_ids[-6]
23
+
24
+ def get_api():
25
+ api = ChatGPT(session_token)
26
+ return api
27
+
28
+ def translate_or_transcribe(audio, task):
29
+ whisper_model.model.config.forced_decoder_ids = [[2, transcribe_token_id if task=="Transcribe in Spoken Language" else translate_token_id]]
30
+ text = whisper_model(audio)["text"]
31
+ return text
32
+
33
+ def get_response_from_chatbot(api,text):
34
+ if api is None:
35
+ return "Sorry, the chatGPT API has some issues. Please try again later"
36
+ try:
37
+ resp = api.send_message(text)
38
+ api.refresh_auth()
39
+ # api.reset_conversation()
40
+ response = resp['message']
41
+ except:
42
+ response = "Sorry, the chatGPT queue is full. Please try again later"
43
+ return response
44
+
45
+ def chat(api,message, chat_history):
46
+ out_chat = []
47
+ if chat_history != '':
48
+ out_chat = json.loads(chat_history)
49
+ response = get_response_from_chatbot(api,message)
50
+ out_chat.append((message, response))
51
+ chat_history = json.dumps(out_chat)
52
+ logger.info(f"out_chat_: {len(out_chat)}")
53
+ return api,out_chat, chat_history
54
+
55
+ start_work = """async() => {
56
+ function isMobile() {
57
+ try {
58
+ document.createEvent("TouchEvent"); return true;
59
+ } catch(e) {
60
+ return false;
61
+ }
62
+ }
63
+ function getClientHeight()
64
+ {
65
+ var clientHeight=0;
66
+ if(document.body.clientHeight&&document.documentElement.clientHeight) {
67
+ var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
68
+ } else {
69
+ var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
70
+ }
71
+ return clientHeight;
72
+ }
73
+
74
+ function setNativeValue(element, value) {
75
+ const valueSetter = Object.getOwnPropertyDescriptor(element.__proto__, 'value').set;
76
+ const prototype = Object.getPrototypeOf(element);
77
+ const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
78
+
79
+ if (valueSetter && valueSetter !== prototypeValueSetter) {
80
+ prototypeValueSetter.call(element, value);
81
+ } else {
82
+ valueSetter.call(element, value);
83
+ }
84
+ }
85
+ var gradioEl = document.querySelector('body > gradio-app').shadowRoot;
86
+ if (!gradioEl) {
87
+ gradioEl = document.querySelector('body > gradio-app');
88
+ }
89
+
90
+ if (typeof window['gradioEl'] === 'undefined') {
91
+ window['gradioEl'] = gradioEl;
92
+
93
+ const page1 = window['gradioEl'].querySelectorAll('#page_1')[0];
94
+ const page2 = window['gradioEl'].querySelectorAll('#page_2')[0];
95
+
96
+ page1.style.display = "none";
97
+ page2.style.display = "block";
98
+
99
+ window['div_count'] = 0;
100
+ window['chat_bot'] = window['gradioEl'].querySelectorAll('#chat_bot')[0];
101
+ window['chat_bot1'] = window['gradioEl'].querySelectorAll('#chat_bot1')[0];
102
+ chat_row = window['gradioEl'].querySelectorAll('#chat_row')[0];
103
+ prompt_row = window['gradioEl'].querySelectorAll('#prompt_row')[0];
104
+ window['chat_bot1'].children[1].textContent = '';
105
+
106
+ clientHeight = getClientHeight();
107
+ new_height = (clientHeight-300) + 'px';
108
+ chat_row.style.height = new_height;
109
+ window['chat_bot'].style.height = new_height;
110
+ window['chat_bot'].children[2].style.height = new_height;
111
+ window['chat_bot1'].style.height = new_height;
112
+ window['chat_bot1'].children[2].style.height = new_height;
113
+ prompt_row.children[0].style.flex = 'auto';
114
+ prompt_row.children[0].style.width = '100%';
115
+
116
+ window['checkChange'] = function checkChange() {
117
+ try {
118
+ if (window['chat_bot'].children[2].children[0].children.length > window['div_count']) {
119
+ new_len = window['chat_bot'].children[2].children[0].children.length - window['div_count'];
120
+ for (var i = 0; i < new_len; i++) {
121
+ new_div = window['chat_bot'].children[2].children[0].children[window['div_count'] + i].cloneNode(true);
122
+ window['chat_bot1'].children[2].children[0].appendChild(new_div);
123
+ }
124
+ window['div_count'] = chat_bot.children[2].children[0].children.length;
125
+ }
126
+ if (window['chat_bot'].children[0].children.length > 1) {
127
+ window['chat_bot1'].children[1].textContent = window['chat_bot'].children[0].children[1].textContent;
128
+ } else {
129
+ window['chat_bot1'].children[1].textContent = '';
130
+ }
131
+
132
+ } catch(e) {
133
+ }
134
+ }
135
+ window['checkChange_interval'] = window.setInterval("window.checkChange()", 500);
136
+ }
137
+
138
+ return false;
139
+ }"""
140
+
141
+
142
+ with gr.Blocks(title='Talk to chatGPT') as demo:
143
+ gr.Markdown("## Talk to chatGPT with your voice in your native language ! ##")
144
+ gr.HTML("<p>You can duplicate this space and use your own session token: <a style='display:inline-block' href='https://huggingface.co/spaces/yizhangliu/chatGPT?duplicate=true'><img src='https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14' alt='Duplicate Space'></a></p>")
145
+ gr.HTML("<p> Instruction on how to get session token can be seen in video <a style='display:inline-block' href='https://www.youtube.com/watch?v=TdNSj_qgdFk'><font style='color:blue;weight:bold;'>here</font></a>. Add your session token by going to settings and add under secrets. </p>")
146
+ with gr.Group(elem_id="page_1", visible=True) as page_1:
147
+ with gr.Box():
148
+ with gr.Row():
149
+ start_button = gr.Button("Let's talk to chatGPT!", elem_id="start-btn", visible=True)
150
+ start_button.click(fn=None, inputs=[], outputs=[], _js=start_work)
151
+
152
+ with gr.Group(elem_id="page_2", visible=False) as page_2:
153
+ with gr.Row(elem_id="chat_row"):
154
+ chatbot = gr.Chatbot(elem_id="chat_bot", visible=False).style(color_map=("green", "blue"))
155
+ chatbot1 = gr.Chatbot(elem_id="chat_bot1").style(color_map=("green", "blue"))
156
+ with gr.Row():
157
+ prompt_input_audio = gr.Audio(
158
+ source="microphone",
159
+ type="filepath",
160
+ label="Record Audio Input",
161
+
162
+ )
163
+ translate_btn = gr.Button("Check Whisper first ? 👍")
164
+
165
+ whisper_task = gr.Radio(["Translate to English", "Transcribe in Spoken Language"], value="Translate to English", show_label=False)
166
+ with gr.Row(elem_id="prompt_row"):
167
+ prompt_input = gr.Textbox(lines=2, label="Input text",show_label=True)
168
+ chat_history = gr.Textbox(lines=4, label="prompt", visible=False)
169
+ submit_btn = gr.Button(value = "Send to chatGPT",elem_id="submit-btn").style(
170
+ margin=True,
171
+ rounded=(True, True, True, True),
172
+ width=100
173
+ )
174
+
175
+
176
+
177
+ translate_btn.click(fn=translate_or_transcribe,
178
+ inputs=[prompt_input_audio,whisper_task],
179
+ outputs=prompt_input
180
+ )
181
+
182
+ api = gr.State(value=get_api())
183
+ submit_btn.click(fn=chat,
184
+ inputs=[api,prompt_input, chat_history],
185
+ outputs=[api,chatbot, chat_history],
186
+ )
187
+ gr.HTML('''
188
+ <p>Note: Please be aware that audio records from iOS devices will not be decoded as expected by Gradio. For the best experience, record your voice from a computer instead of your smartphone ;)</p>
189
+ <div class="footer">
190
+ <p>Whisper Model by <a href="https://github.com/openai/whisper" style="text-decoration: underline;" target="_blank">OpenAI</a> -
191
+ <a href="https://chat.openai.com/chat" target="_blank">chatGPT</a> by <a href="https://openai.com/" style="text-decoration: underline;" target="_blank">OpenAI</a>
192
+ </p>
193
+ </div>
194
+ ''')
195
+
196
+ demo.launch(debug = True)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai
2
+ pyChatGPT
3
+ loguru
4
+ --extra-index-url https://download.pytorch.org/whl/cu113
5
+ torch
6
+ transformers