lotrlol Eriberto commited on
Commit
ac11393
·
0 Parent(s):

Duplicate from Eriberto/chatGPT

Browse files

Co-authored-by: Do Nascimento <Eriberto@users.noreply.huggingface.co>

Files changed (4) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +307 -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
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: Eriberto/chatGPT
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+ import os, sys, json
4
+ from loguru import logger
5
+ import random
6
+
7
+ openai.api_key = os.environ.get('SessionToken')
8
+ logger.info(f"session_token_: {openai.api_key}")
9
+
10
+ conversation = ""
11
+ user_name = "MH"
12
+ bot_name = "bbDemo"
13
+
14
+ def get_response_from_chatgpt(text):
15
+ #try:
16
+ response_api = openai.Completion.create(engine='text-davinci-003', prompt=str(text), max_tokens=50)
17
+ response_str = response_api["choices"][0]["text"].replace("\n", "")
18
+ response_str = response_str.split(user_name + ": ", 1)[0].split(bot_name + ": ", 1)[0]
19
+ print("RESPONSE response_api", response_api)
20
+ print("RESPONSE response_str ", response_str)
21
+ response = response_str
22
+ logger.info(f"Response: [{response_api}]")
23
+ logger.info(f"conversation_id_: [{response}]")
24
+ #except:
25
+ #response = "I'm so tired. Let me lie down for a few days."
26
+ return response
27
+
28
+ start_work = """async() => {
29
+ function isMobile() {
30
+ try {
31
+ document.createEvent("TouchEvent"); return true;
32
+ } catch(e) {
33
+ return false;
34
+ }
35
+ }
36
+ function getClientHeight()
37
+ {
38
+ var clientHeight=0;
39
+ if(document.body.clientHeight&&document.documentElement.clientHeight) {
40
+ var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
41
+ } else {
42
+ var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
43
+ }
44
+ return clientHeight;
45
+ }
46
+
47
+ function setNativeValue(element, value) {
48
+ const valueSetter = Object.getOwnPropertyDescriptor(element.__proto__, 'value').set;
49
+ const prototype = Object.getPrototypeOf(element);
50
+ const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
51
+
52
+ if (valueSetter && valueSetter !== prototypeValueSetter) {
53
+ prototypeValueSetter.call(element, value);
54
+ } else {
55
+ valueSetter.call(element, value);
56
+ }
57
+ }
58
+ function save_conversation(chatbot) {
59
+ var conversations = new Array();
60
+ for (var i = 0; i < chatbot.children.length; i++) {
61
+ conversations[i] = chatbot.children[i].innerHTML;
62
+ }
63
+ var json_str = JSON.stringify(conversations);
64
+ localStorage.setItem('chatgpt_conversations', json_str);
65
+ }
66
+ function load_conversation(chatbot) {
67
+ var json_str = localStorage.getItem('chatgpt_conversations');
68
+ if (json_str) {
69
+ conversations = JSON.parse(json_str);
70
+ for (var i = 0; i < conversations.length; i++) {
71
+ var new_div = document.createElement("div");
72
+ if((i%2)===0){
73
+ new_div.className = "px-3 py-2 rounded-[22px] rounded-br-none text-white text-sm chat-message svelte-rct66g";
74
+ new_div.style.backgroundColor = "#16a34a";
75
+ } else {
76
+ new_div.className = "px-3 py-2 rounded-[22px] rounded-bl-none place-self-start text-white text-sm chat-message svelte-rct66g";
77
+ new_div.style.backgroundColor = "#2563eb";
78
+ if (conversations[i].indexOf("<img ") == 0) {
79
+ new_div.style.width = "80%";
80
+ new_div.style.padding = "0.2rem";
81
+ }
82
+ }
83
+ new_div.innerHTML = conversations[i];
84
+ chatbot.appendChild(new_div);
85
+ }
86
+ }
87
+ }
88
+ var gradioEl = document.querySelector('body > gradio-app').shadowRoot;
89
+ if (!gradioEl) {
90
+ gradioEl = document.querySelector('body > gradio-app');
91
+ }
92
+
93
+ if (typeof window['gradioEl'] === 'undefined') {
94
+ window['gradioEl'] = gradioEl;
95
+
96
+ const page1 = window['gradioEl'].querySelectorAll('#page_1')[0];
97
+ const page2 = window['gradioEl'].querySelectorAll('#page_2')[0];
98
+
99
+ page1.style.display = "none";
100
+ page2.style.display = "block";
101
+ window['div_count'] = 0;
102
+ window['chat_bot'] = window['gradioEl'].querySelectorAll('#chat_bot')[0];
103
+ window['chat_bot1'] = window['gradioEl'].querySelectorAll('#chat_bot1')[0];
104
+ chat_row = window['gradioEl'].querySelectorAll('#chat_row')[0];
105
+ prompt_row = window['gradioEl'].querySelectorAll('#prompt_row')[0];
106
+ window['chat_bot1'].children[1].textContent = '';
107
+
108
+ clientHeight = getClientHeight();
109
+ if (isMobile()) {
110
+ output_htmls = window['gradioEl'].querySelectorAll('.output-html');
111
+ for (var i = 0; i < output_htmls.length; i++) {
112
+ output_htmls[i].style.display = "none";
113
+ }
114
+ new_height = (clientHeight - 250) + 'px';
115
+ } else {
116
+ new_height = (clientHeight - 350) + 'px';
117
+ }
118
+ chat_row.style.height = new_height;
119
+ window['chat_bot'].style.height = new_height;
120
+ window['chat_bot'].children[2].style.height = new_height;
121
+ window['chat_bot1'].style.height = new_height;
122
+ window['chat_bot1'].children[2].style.height = new_height;
123
+ prompt_row.children[0].style.flex = 'auto';
124
+ prompt_row.children[0].style.width = '100%';
125
+ window['gradioEl'].querySelectorAll('#chat_radio')[0].style.flex = 'auto';
126
+ window['gradioEl'].querySelectorAll('#chat_radio')[0].style.width = '100%';
127
+ prompt_row.children[0].setAttribute('style','flex-direction: inherit; flex: 1 1 auto; width: 100%;border-color: green;border-width: 1px !important;')
128
+ window['chat_bot1'].children[1].setAttribute('style', 'border-bottom-right-radius:0;top:unset;bottom:0;padding-left:0.1rem');
129
+ window['gradioEl'].querySelectorAll('#btns_row')[0].children[0].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
130
+ window['gradioEl'].querySelectorAll('#btns_row')[0].children[1].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
131
+
132
+ load_conversation(window['chat_bot1'].children[2].children[0]);
133
+ window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
134
+
135
+ window['gradioEl'].querySelectorAll('#clear-btn')[0].onclick = function(e){
136
+ if (confirm('Clear all outputs?')==true) {
137
+ window['chat_bot1'].children[2].children[0].innerHTML = '';
138
+ save_conversation(window['chat_bot1'].children[2].children[0]);
139
+ }
140
+ }
141
+
142
+ window['prevPrompt'] = '';
143
+ window['doCheckPrompt'] = 0;
144
+ window['prevImgSrc'] = '';
145
+ window['checkChange'] = function checkChange() {
146
+ try {
147
+ if (window['gradioEl'].querySelectorAll('.gr-radio')[0].checked) {
148
+ if (window['chat_bot'].children[2].children[0].children.length > window['div_count']) {
149
+ new_len = window['chat_bot'].children[2].children[0].children.length - window['div_count'];
150
+ for (var i = 0; i < new_len; i++) {
151
+ new_div = window['chat_bot'].children[2].children[0].children[window['div_count'] + i].cloneNode(true);
152
+ window['chat_bot1'].children[2].children[0].appendChild(new_div);
153
+ }
154
+ window['div_count'] = chat_bot.children[2].children[0].children.length;
155
+ window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
156
+ save_conversation(window['chat_bot1'].children[2].children[0]);
157
+ }
158
+ if (window['chat_bot'].children[0].children.length > 1) {
159
+ window['chat_bot1'].children[1].textContent = window['chat_bot'].children[0].children[1].textContent;
160
+ } else {
161
+ window['chat_bot1'].children[1].textContent = '';
162
+ }
163
+ } else {
164
+ texts = window['gradioEl'].querySelectorAll('textarea');
165
+ text0 = texts[0];
166
+ text1 = texts[1];
167
+ img_index = 0;
168
+ text_value = text1.value;
169
+ if (window['doCheckPrompt'] === 0 && window['prevPrompt'] !== text_value) {
170
+ console.log('_____new prompt___[' + text_value + ']_');
171
+ window['doCheckPrompt'] = 1;
172
+ window['prevPrompt'] = text_value;
173
+
174
+ tabitems = window['gradioEl'].querySelectorAll('.tabitem');
175
+ for (var i = 0; i < tabitems.length; i++) {
176
+ inputText = tabitems[i].children[0].children[1].children[0].querySelectorAll('.gr-text-input')[0];
177
+ setNativeValue(inputText, text_value);
178
+ inputText.dispatchEvent(new Event('input', { bubbles: true }));
179
+ }
180
+ setTimeout(function() {
181
+ btns = window['gradioEl'].querySelectorAll('button');
182
+ for (var i = 0; i < btns.length; i++) {
183
+ if (['Generate image','Run'].includes(btns[i].innerText)) {
184
+ btns[i].click();
185
+ }
186
+ }
187
+ window['doCheckPrompt'] = 0;
188
+ }, 10);
189
+ }
190
+ tabitems = window['gradioEl'].querySelectorAll('.tabitem');
191
+ imgs = tabitems[img_index].children[0].children[1].children[1].querySelectorAll("img");
192
+ if (imgs.length > 0) {
193
+ if (window['prevImgSrc'] !== imgs[0].src) {
194
+ var user_div = document.createElement("div");
195
+ user_div.className = "px-3 py-2 rounded-[22px] rounded-br-none text-white text-sm chat-message svelte-rct66g";
196
+ user_div.style.backgroundColor = "#16a34a";
197
+ user_div.innerHTML = "<p>" + text0.value + "</p>";
198
+ window['chat_bot1'].children[2].children[0].appendChild(user_div);
199
+ var bot_div = document.createElement("div");
200
+ bot_div.className = "px-3 py-2 rounded-[22px] rounded-bl-none place-self-start text-white text-sm chat-message svelte-rct66g";
201
+ bot_div.style.backgroundColor = "#2563eb";
202
+ bot_div.style.width = "80%";
203
+ bot_div.style.padding = "0.2rem";
204
+ bot_div.appendChild(imgs[0].cloneNode(true));
205
+ window['chat_bot1'].children[2].children[0].appendChild(bot_div);
206
+
207
+ window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
208
+ window['prevImgSrc'] = imgs[0].src;
209
+ save_conversation(window['chat_bot1'].children[2].children[0]);
210
+ }
211
+ }
212
+ if (tabitems[img_index].children[0].children[1].children[1].children[0].children.length > 1) {
213
+ window['chat_bot1'].children[1].textContent = tabitems[img_index].children[0].children[1].children[1].children[0].textContent;
214
+ } else {
215
+ window['chat_bot1'].children[1].textContent = '';
216
+ }
217
+ }
218
+
219
+ } catch(e) {
220
+ }
221
+ }
222
+ window['checkChange_interval'] = window.setInterval("window.checkChange()", 500);
223
+ }
224
+
225
+ return false;
226
+ }"""
227
+
228
+ space_ids = {
229
+ "spaces/stabilityai/stable-diffusion":"Stable Diffusion 2.1",
230
+ }
231
+
232
+ tab_actions = []
233
+ tab_titles = []
234
+
235
+ for space_id in space_ids.keys():
236
+ print(space_id, space_ids[space_id])
237
+ try:
238
+ tab = gr.Interface.load(space_id)
239
+ tab_actions.append(tab)
240
+ tab_titles.append(space_ids[space_id])
241
+ except Exception as e:
242
+ logger.info(f"load_fail__{space_id}_{e}")
243
+
244
+ def chat(input0, input1, chat_radio, chat_history):
245
+ out_chat = []
246
+ if chat_history != '':
247
+ out_chat = json.loads(chat_history)
248
+ #if chat_radio == "Talk to chatGPT":
249
+ response = get_response_from_chatgpt(input0)
250
+ out_chat.append((input0, response))
251
+ chat_history = json.dumps(out_chat)
252
+
253
+ logger.info(f"out_chat_input0 and input1 {input0} -- {input1}")
254
+ logger.info(f"chat history {chat_history}")
255
+ return out_chat, input1, chat_history
256
+
257
+ article = """
258
+ <div class="footer">
259
+ <p><a href="https://chat.openai.com/chat" target="_blank">chatGPT</a>
260
+ by <a href="https://openai.com/" style="text-decoration: underline;" target="_blank">OpenAI</a> -
261
+ Gradio Demo by 🤗 <a href="https://www.bb.com.br/site/#/" target="_blank">Eriberto Oliveira & Gustavo Botelho & Joel</a>
262
+ </p>
263
+ </div>
264
+ """
265
+
266
+ with gr.Blocks(title='Talk to chatGPT') as demo:
267
+ gr.HTML("<p> Essa é uma demonstração do model GPT-3 aplicado no context de chatbot. </p>")
268
+ gr.HTML("<p> Faça perguntas e se surprenda com as respostas </p>")
269
+ with gr.Group(elem_id="page_1", visible=True) as page_1:
270
+ with gr.Box():
271
+ with gr.Row():
272
+ start_button = gr.Button("Click aqui para conversar!!", elem_id="start-btn", visible=True)
273
+ start_button.click(fn=None, inputs=[], outputs=[], _js=start_work)
274
+
275
+ with gr.Group(elem_id="page_2", visible=False) as page_2:
276
+ with gr.Row(elem_id="chat_row"):
277
+ chatbot = gr.Chatbot(elem_id="chat_bot", visible=False).style(color_map=("green", "blue"))
278
+ chatbot1 = gr.Chatbot(elem_id="chat_bot1").style(color_map=("green", "blue"))
279
+ with gr.Row(elem_id="prompt_row"):
280
+ prompt_input0 = gr.Textbox(lines=2, label="prompt",show_label=False)
281
+ prompt_input1 = gr.Textbox(lines=4, label="prompt", visible=False)
282
+ chat_history = gr.Textbox(lines=4, label="prompt", visible=False)
283
+ chat_radio = gr.Radio(["Talk to chatGPT", "Text to Image"], elem_id="chat_radio",value="Talk to chatGPT", show_label=False)
284
+ with gr.Row(elem_id="btns_row"):
285
+ with gr.Column(id="submit_col"):
286
+ submit_btn = gr.Button(value = "submit",elem_id="submit-btn").style(
287
+ margin=True,
288
+ rounded=(True, True, True, True),
289
+ width=100
290
+ )
291
+ with gr.Column(id="clear_col"):
292
+ clear_btn = gr.Button(value = "clear outputs", elem_id="clear-btn").style(
293
+ margin=True,
294
+ rounded=(True, True, True, True),
295
+ width=100
296
+ )
297
+
298
+ submit_btn.click(fn=chat,
299
+ inputs=[prompt_input0, prompt_input1, chat_radio, chat_history],
300
+ outputs=[chatbot, prompt_input1, chat_history],
301
+ )
302
+ with gr.Row(elem_id='tab_img', visible=False).style(height=5):
303
+ tab_img = gr.TabbedInterface(tab_actions, tab_titles)
304
+
305
+ gr.HTML(article)
306
+ demo.launch(debug = True)
307
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ openai
2
+ pyChatGPT
3
+ loguru
4
+ paddlepaddle==2.3.2
5
+ paddlehub
6
+ PyVirtualDisplay