Files changed (1) hide show
  1. app.py +41 -72
app.py CHANGED
@@ -5,7 +5,7 @@ import gradio as gr
5
 
6
  from loguru import logger
7
  import paddlehub as hub
8
- import random, re
9
  from encoder import get_encoder
10
 
11
  openai.api_key = os.getenv("OPENAI_API_KEY")
@@ -96,10 +96,6 @@ start_work = """async() => {
96
  img.style.height = img.offsetWidth + 'px';
97
  }
98
  function load_conversation(chatbot) {
99
- var my_prompt_system_value = localStorage.getItem('my_prompt_system');
100
- if (typeof my_prompt_system_value !== 'undefined') {
101
- setNativeValue(window['my_prompt_system'], my_prompt_system_value);
102
- }
103
  var json_str = localStorage.getItem('chatgpt_conversations');
104
  if (json_str) {
105
  var conversations_clear = new Array();
@@ -191,7 +187,6 @@ start_work = """async() => {
191
  window['chat_bot1'].style.height = new_height;
192
  window['chat_bot1'].children[1].style.height = new_height;
193
  window['chat_bot1'].children[0].style.top = (parseInt(window['chat_bot1'].style.height)-window['chat_bot1'].children[0].offsetHeight-2) + 'px';
194
-
195
  prompt_row.children[0].style.flex = 'auto';
196
  prompt_row.children[0].style.width = '100%';
197
  window['gradioEl'].querySelectorAll('#chat_radio')[0].style.flex = 'auto';
@@ -200,8 +195,7 @@ start_work = """async() => {
200
  window['chat_bot1'].children[1].setAttribute('style', 'border-bottom-right-radius:0;top:unset;bottom:0;padding-left:0.1rem');
201
  window['gradioEl'].querySelectorAll('#btns_row')[0].children[0].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
202
  window['gradioEl'].querySelectorAll('#btns_row')[0].children[1].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
203
- window['my_prompt_system'] = window['gradioEl'].querySelectorAll('#my_prompt_system')[0].querySelectorAll('textarea')[0];
204
-
205
  load_conversation(window['chat_bot1'].children[1].children[0]);
206
  window['chat_bot1'].children[1].scrollTop = window['chat_bot1'].children[1].scrollHeight;
207
 
@@ -239,7 +233,6 @@ start_work = """async() => {
239
  try {
240
  if (window['chat_radio_0'].checked) {
241
  dot_flashing = window['chat_bot'].children[1].children[0].querySelectorAll('.dot-flashing');
242
-
243
  if (window['chat_bot'].children[1].children[0].children.length > window['div_count'] && dot_flashing.length == 0) {
244
  new_len = window['chat_bot'].children[1].children[0].children.length - window['div_count'];
245
  for (var i = 0; i < new_len; i++) {
@@ -261,7 +254,6 @@ start_work = """async() => {
261
  img_index = 0;
262
  draw_prompt_en = window['my_prompt_en'].value;
263
  if (window['doCheckPrompt'] == 0 && window['prevPrompt'] != draw_prompt_en) {
264
-
265
  console.log('_____draw_prompt_en___[' + draw_prompt_en + ']_');
266
  window['doCheckPrompt'] = 1;
267
  window['prevPrompt'] = draw_prompt_en;
@@ -292,7 +284,6 @@ start_work = """async() => {
292
  user_div.dataset.testid = 'user';
293
  user_div.innerHTML = "<p>δ½œη”»: " + window['draw_prompt'] + "</p><img></img>";
294
  window['chat_bot1'].children[1].children[0].appendChild(user_div);
295
-
296
  var bot_div = document.createElement("div");
297
  bot_div.className = "message bot svelte-134zwfa";
298
  bot_div.style.backgroundColor = "#2563eb";
@@ -327,7 +318,7 @@ start_work = """async() => {
327
  window['chat_bot1'].children[0].textContent = '';
328
  }
329
  }
330
- localStorage.setItem('my_prompt_system', window['my_prompt_system'].value);
331
  } catch(e) {
332
  }
333
  }
@@ -364,96 +355,76 @@ def set_openai_api_key(api_key):
364
  if api_key and api_key.startswith("sk-") and len(api_key) > 50:
365
  openai.api_key = api_key
366
 
367
- def get_response_from_openai(input, prompt_system, chat_history, model_radio, temperature=0.0):
368
  error_1 = 'You exceeded your current quota, please check your plan and billing details.'
369
- def openai_create(input_list, prompt_system, model_radio):
370
  try:
 
371
  input_list_len = len(input_list)
372
  out_prompt = ''
373
  messages = []
374
- prompt_system_token = prompt_system
375
- if model_radio in ['GPT-3.0']:
376
- out_prompt += 'AI:'
377
- if prompt_system != '':
378
- prompt_system_token = f'Human:{prompt_system}'
379
  for i in range(input_list_len):
380
  input = input_list[input_list_len-i-1].replace("<br>", '\n\n')
381
  if input.startswith("Openai said:"):
382
- input = "☝:"
 
383
  if input.startswith("☝:"):
384
- if model_radio in ['GPT-3.0']:
385
  out_prompt = input.replace("☝:", "AI:") + '\n' + out_prompt
386
  else:
387
  out_prompt = input.replace("☝:", "") + out_prompt
388
  messages.insert(0, {"role": "assistant", "content": input.replace("☝:", "")})
389
  elif input.startswith("☟:"):
390
- if model_radio in ['GPT-3.0']:
391
  out_prompt = input.replace("☟:", "Human:") + '\n' + out_prompt
392
  else:
393
  out_prompt = input.replace("☟:", "") + out_prompt
394
  messages.insert(0, {"role": "user", "content": input.replace("☟:", "")})
395
- tokens = token_encoder.encode(out_prompt + prompt_system_token)
396
- if model_radio in ['GPT-4.0']:
397
- if len(tokens) > max_input_tokens + total_tokens:
398
- break
399
- else:
400
- if len(tokens) > max_input_tokens:
401
- break
402
 
403
- if prompt_system != '':
404
- if model_radio in ['GPT-3.0']:
405
- out_prompt = prompt_system_token + out_prompt
406
- else:
407
- out_prompt += prompt_system
408
- messages.insert(0, {"role": "system", "content": prompt_system})
409
-
410
- if model_radio in ['GPT-3.0']:
411
- print(f'response_3.0_out_prompt__:{out_prompt}')
412
  response = openai.Completion.create(
413
  model="text-davinci-003",
414
  prompt=out_prompt,
415
- temperature=temperature,
416
  max_tokens=max_output_tokens,
417
  top_p=1,
418
  frequency_penalty=0,
419
  presence_penalty=0,
420
  stop=[" Human:", " AI:"]
421
  )
422
- print(f'response_3.0_response__:{response}')
423
  ret = response.choices[0].text
424
  else:
425
- print(f'response_{model_radio}_messages__:{messages}')
426
- if model_radio in ['GPT-3.5']:
427
- model_name = "gpt-3.5-turbo"
428
- else:
429
- model_name = "gpt-4"
430
  response = openai.ChatCompletion.create(
431
- model=model_name,
432
  messages=messages,
433
- temperature=temperature,
434
  max_tokens=max_output_tokens,
435
  top_p=1,
436
  frequency_penalty=0,
437
  presence_penalty=0,
438
  stop=[" Human:", " AI:"]
439
- )
440
- print(f'response_{model_radio}_response__:{response}')
441
  ret = response.choices[0].message['content']
442
-
443
  if ret.startswith("\n\n"):
444
  ret = ret.replace("\n\n", '')
445
  ret = ret.replace('\n', '<br>')
446
- ret = re.sub(r"```(.*?)```", r"<pre style='background-color: #ddd;margin-left:20px;padding-left:10px;'>\1</pre>", ret)
447
- ret = re.sub(r"<pre style='background-color: #ddd;margin-left:20px;padding-left:10px;'>(.*?)</pre>", lambda m: "<pre style='background-color: #ddd; color:#000; margin-left:20px;padding-left:10px;'>" + m.group(1).replace('<br>', '\n') + '</pre>', ret)
448
- # logger.info(f'ret_2_={ret}')
449
  if ret == '':
450
- ret = f"Openai said: I'm too tired."
451
  return ret, response.usage
452
  except Exception as e:
453
  logger.info(f"openai_create_error__{e}")
454
  ret = f"Openai said: {e} Perhaps enter your OpenAI API key."
455
  return ret, {"completion_tokens": -1, "prompt_tokens": -1, "total_tokens": -1}
456
-
457
  # logger.info(f'chat_history = {chat_history}')
458
  chat_history_list = []
459
  chat_history = chat_history.replace("<p>", "").replace("</p>", "")
@@ -461,11 +432,11 @@ def get_response_from_openai(input, prompt_system, chat_history, model_radio, te
461
  chat_history_list = json.loads(chat_history)
462
  chat_history_list.append(f'☟:{input}')
463
 
464
- output, response_usage = openai_create(chat_history_list, prompt_system, model_radio)
465
  logger.info(f'response_usage={response_usage}')
466
  return output
467
 
468
- def chat(input0, input1, prompt_system, chat_radio, model_radio, all_chat_history, chat_history):
469
  all_chat = []
470
  if all_chat_history != '':
471
  all_chat = json.loads(all_chat_history)
@@ -474,7 +445,7 @@ def chat(input0, input1, prompt_system, chat_radio, model_radio, all_chat_histor
474
  return all_chat, json.dumps(all_chat), input0, input1
475
 
476
  if chat_radio == "Talk to chatGPT":
477
- response = get_response_from_openai(input0, prompt_system, chat_history, model_radio)
478
  all_chat.append((input0, response))
479
  return all_chat, json.dumps(all_chat), '', input1
480
  else:
@@ -483,9 +454,9 @@ def chat(input0, input1, prompt_system, chat_radio, model_radio, all_chat_histor
483
 
484
  def chat_radio_change(chat_radio):
485
  if chat_radio == "Talk to chatGPT":
486
- return gr.Radio.update(visible=True), gr.Text.update(visible=True), gr.Textbox.update(visible=True)
487
  else:
488
- return gr.Radio.update(visible=False), gr.Text.update(visible=False), gr.Textbox.update(visible=False)
489
 
490
  with gr.Blocks(title='Talk to chatGPT') as demo:
491
  with gr.Row(elem_id="page_0", visible=False) as page_0:
@@ -494,21 +465,20 @@ with gr.Blocks(title='Talk to chatGPT') as demo:
494
  with gr.Box():
495
  with gr.Row():
496
  start_button = gr.Button("Let's talk to chatGPT!", elem_id="start-btn", visible=True)
497
- start_button.click(fn=None, inputs=[], outputs=[], _js=start_work)
 
498
  with gr.Row(elem_id="page_2", visible=False) as page_2:
499
  with gr.Row(elem_id="chat_row"):
500
  chatbot = gr.Chatbot(elem_id="chat_bot", visible=False).style(color_map=("green", "blue"))
501
  chatbot1 = gr.Chatbot(elem_id="chat_bot1").style(color_map=("green", "blue"))
502
- with gr.Row(elem_id="system_prompt_row"):
503
- prompt_system = gr.Textbox(lines=2, label="system prompt:", elem_id="my_prompt_system", visible=True, show_label=True)
504
  with gr.Row(elem_id="prompt_row"):
505
  prompt_input0 = gr.Textbox(lines=2, label="input", elem_id="my_prompt", show_label=True)
506
  prompt_input1 = gr.Textbox(lines=4, label="prompt", elem_id="my_prompt_en", visible=False)
507
  chat_history = gr.Textbox(lines=4, label="chat_history", elem_id="chat_history", visible=False)
508
- all_chat_history = gr.Textbox(lines=4, label="contexts:", elem_id="all_chat_history", visible=False)
509
 
510
  chat_radio = gr.Radio(["Talk to chatGPT", "Text to Image"], elem_id="chat_radio",value="Talk to chatGPT", show_label=False, visible=True)
511
- model_radio = gr.Radio(["GPT-3.0", "GPT-3.5", "GPT-4.0"], elem_id="model_radio", value="GPT-3.5",
512
  label='GPT model: ', show_label=True,interactive=True, visible=True)
513
  openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...) and hit Enter",
514
  show_label=False, lines=1, type='password')
@@ -525,14 +495,13 @@ with gr.Blocks(title='Talk to chatGPT') as demo:
525
  rounded=(True, True, True, True),
526
  width=100
527
  )
528
-
 
 
 
529
  with gr.Row(elem_id='tab_img', visible=False).style(height=5):
530
  tab_img = gr.TabbedInterface(tab_actions, tab_titles)
531
 
532
- submit_btn.click(fn=chat,
533
- inputs=[prompt_input0, prompt_input1, prompt_system, chat_radio, model_radio, all_chat_history, chat_history],
534
- outputs=[chatbot, all_chat_history, prompt_input0, prompt_input1],
535
- )
536
  openai_api_key_textbox.change(set_openai_api_key,
537
  inputs=[openai_api_key_textbox],
538
  outputs=[])
@@ -541,7 +510,7 @@ with gr.Blocks(title='Talk to chatGPT') as demo:
541
  outputs=[])
542
  chat_radio.change(fn=chat_radio_change,
543
  inputs=[chat_radio],
544
- outputs=[model_radio, openai_api_key_textbox, prompt_system],
545
  )
546
 
547
- demo.launch(server_name='0.0.0.0', debug = True)
 
5
 
6
  from loguru import logger
7
  import paddlehub as hub
8
+ import random
9
  from encoder import get_encoder
10
 
11
  openai.api_key = os.getenv("OPENAI_API_KEY")
 
96
  img.style.height = img.offsetWidth + 'px';
97
  }
98
  function load_conversation(chatbot) {
 
 
 
 
99
  var json_str = localStorage.getItem('chatgpt_conversations');
100
  if (json_str) {
101
  var conversations_clear = new Array();
 
187
  window['chat_bot1'].style.height = new_height;
188
  window['chat_bot1'].children[1].style.height = new_height;
189
  window['chat_bot1'].children[0].style.top = (parseInt(window['chat_bot1'].style.height)-window['chat_bot1'].children[0].offsetHeight-2) + 'px';
 
190
  prompt_row.children[0].style.flex = 'auto';
191
  prompt_row.children[0].style.width = '100%';
192
  window['gradioEl'].querySelectorAll('#chat_radio')[0].style.flex = 'auto';
 
195
  window['chat_bot1'].children[1].setAttribute('style', 'border-bottom-right-radius:0;top:unset;bottom:0;padding-left:0.1rem');
196
  window['gradioEl'].querySelectorAll('#btns_row')[0].children[0].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
197
  window['gradioEl'].querySelectorAll('#btns_row')[0].children[1].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
198
+
 
199
  load_conversation(window['chat_bot1'].children[1].children[0]);
200
  window['chat_bot1'].children[1].scrollTop = window['chat_bot1'].children[1].scrollHeight;
201
 
 
233
  try {
234
  if (window['chat_radio_0'].checked) {
235
  dot_flashing = window['chat_bot'].children[1].children[0].querySelectorAll('.dot-flashing');
 
236
  if (window['chat_bot'].children[1].children[0].children.length > window['div_count'] && dot_flashing.length == 0) {
237
  new_len = window['chat_bot'].children[1].children[0].children.length - window['div_count'];
238
  for (var i = 0; i < new_len; i++) {
 
254
  img_index = 0;
255
  draw_prompt_en = window['my_prompt_en'].value;
256
  if (window['doCheckPrompt'] == 0 && window['prevPrompt'] != draw_prompt_en) {
 
257
  console.log('_____draw_prompt_en___[' + draw_prompt_en + ']_');
258
  window['doCheckPrompt'] = 1;
259
  window['prevPrompt'] = draw_prompt_en;
 
284
  user_div.dataset.testid = 'user';
285
  user_div.innerHTML = "<p>δ½œη”»: " + window['draw_prompt'] + "</p><img></img>";
286
  window['chat_bot1'].children[1].children[0].appendChild(user_div);
 
287
  var bot_div = document.createElement("div");
288
  bot_div.className = "message bot svelte-134zwfa";
289
  bot_div.style.backgroundColor = "#2563eb";
 
318
  window['chat_bot1'].children[0].textContent = '';
319
  }
320
  }
321
+
322
  } catch(e) {
323
  }
324
  }
 
355
  if api_key and api_key.startswith("sk-") and len(api_key) > 50:
356
  openai.api_key = api_key
357
 
358
+ def get_response_from_openai(input, chat_history, model_radio):
359
  error_1 = 'You exceeded your current quota, please check your plan and billing details.'
360
+ def openai_create(input_list, model_radio):
361
  try:
362
+ # print(f'input_list={input_list}')
363
  input_list_len = len(input_list)
364
  out_prompt = ''
365
  messages = []
366
+ if model_radio == 'GPT-3.0':
367
+ out_prompt = 'AI:'
 
 
 
368
  for i in range(input_list_len):
369
  input = input_list[input_list_len-i-1].replace("<br>", '\n\n')
370
  if input.startswith("Openai said:"):
371
+ input = "☝:"
372
+
373
  if input.startswith("☝:"):
374
+ if model_radio == 'GPT-3.0':
375
  out_prompt = input.replace("☝:", "AI:") + '\n' + out_prompt
376
  else:
377
  out_prompt = input.replace("☝:", "") + out_prompt
378
  messages.insert(0, {"role": "assistant", "content": input.replace("☝:", "")})
379
  elif input.startswith("☟:"):
380
+ if model_radio == 'GPT-3.0':
381
  out_prompt = input.replace("☟:", "Human:") + '\n' + out_prompt
382
  else:
383
  out_prompt = input.replace("☟:", "") + out_prompt
384
  messages.insert(0, {"role": "user", "content": input.replace("☟:", "")})
385
+ tokens = token_encoder.encode(out_prompt)
386
+ if len(tokens) > max_input_tokens:
387
+ break
 
 
 
 
388
 
389
+ if model_radio == 'GPT-3.0':
390
+ # print(out_prompt)
 
 
 
 
 
 
 
391
  response = openai.Completion.create(
392
  model="text-davinci-003",
393
  prompt=out_prompt,
394
+ temperature=0.7,
395
  max_tokens=max_output_tokens,
396
  top_p=1,
397
  frequency_penalty=0,
398
  presence_penalty=0,
399
  stop=[" Human:", " AI:"]
400
  )
401
+ # print(f'response_3.0__:{response}')
402
  ret = response.choices[0].text
403
  else:
404
+ # print(messages)
 
 
 
 
405
  response = openai.ChatCompletion.create(
406
+ model="gpt-3.5-turbo",
407
  messages=messages,
408
+ temperature=0.7,
409
  max_tokens=max_output_tokens,
410
  top_p=1,
411
  frequency_penalty=0,
412
  presence_penalty=0,
413
  stop=[" Human:", " AI:"]
414
+ )
415
+ # print(f'response_3.5__:{response}')
416
  ret = response.choices[0].message['content']
 
417
  if ret.startswith("\n\n"):
418
  ret = ret.replace("\n\n", '')
419
  ret = ret.replace('\n', '<br>')
 
 
 
420
  if ret == '':
421
+ ret = f"Openai said: I'm too tired."
422
  return ret, response.usage
423
  except Exception as e:
424
  logger.info(f"openai_create_error__{e}")
425
  ret = f"Openai said: {e} Perhaps enter your OpenAI API key."
426
  return ret, {"completion_tokens": -1, "prompt_tokens": -1, "total_tokens": -1}
427
+
428
  # logger.info(f'chat_history = {chat_history}')
429
  chat_history_list = []
430
  chat_history = chat_history.replace("<p>", "").replace("</p>", "")
 
432
  chat_history_list = json.loads(chat_history)
433
  chat_history_list.append(f'☟:{input}')
434
 
435
+ output, response_usage = openai_create(chat_history_list, model_radio)
436
  logger.info(f'response_usage={response_usage}')
437
  return output
438
 
439
+ def chat(input0, input1, chat_radio, model_radio, all_chat_history, chat_history):
440
  all_chat = []
441
  if all_chat_history != '':
442
  all_chat = json.loads(all_chat_history)
 
445
  return all_chat, json.dumps(all_chat), input0, input1
446
 
447
  if chat_radio == "Talk to chatGPT":
448
+ response = get_response_from_openai(input0, chat_history, model_radio)
449
  all_chat.append((input0, response))
450
  return all_chat, json.dumps(all_chat), '', input1
451
  else:
 
454
 
455
  def chat_radio_change(chat_radio):
456
  if chat_radio == "Talk to chatGPT":
457
+ return gr.Radio.update(visible=True), gr.Text.update(visible=True)
458
  else:
459
+ return gr.Radio.update(visible=False), gr.Text.update(visible=False)
460
 
461
  with gr.Blocks(title='Talk to chatGPT') as demo:
462
  with gr.Row(elem_id="page_0", visible=False) as page_0:
 
465
  with gr.Box():
466
  with gr.Row():
467
  start_button = gr.Button("Let's talk to chatGPT!", elem_id="start-btn", visible=True)
468
+ start_button.click(fn=None, inputs=[], outputs=[], _js=start_work)
469
+
470
  with gr.Row(elem_id="page_2", visible=False) as page_2:
471
  with gr.Row(elem_id="chat_row"):
472
  chatbot = gr.Chatbot(elem_id="chat_bot", visible=False).style(color_map=("green", "blue"))
473
  chatbot1 = gr.Chatbot(elem_id="chat_bot1").style(color_map=("green", "blue"))
 
 
474
  with gr.Row(elem_id="prompt_row"):
475
  prompt_input0 = gr.Textbox(lines=2, label="input", elem_id="my_prompt", show_label=True)
476
  prompt_input1 = gr.Textbox(lines=4, label="prompt", elem_id="my_prompt_en", visible=False)
477
  chat_history = gr.Textbox(lines=4, label="chat_history", elem_id="chat_history", visible=False)
478
+ all_chat_history = gr.Textbox(lines=4, label="δΌšθ―δΈŠδΈ‹ζ–‡οΌš", elem_id="all_chat_history", visible=False)
479
 
480
  chat_radio = gr.Radio(["Talk to chatGPT", "Text to Image"], elem_id="chat_radio",value="Talk to chatGPT", show_label=False, visible=True)
481
+ model_radio = gr.Radio(["GPT-3.0", "GPT-3.5"], elem_id="model_radio", value="GPT-3.5",
482
  label='GPT model: ', show_label=True,interactive=True, visible=True)
483
  openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key (sk-...) and hit Enter",
484
  show_label=False, lines=1, type='password')
 
495
  rounded=(True, True, True, True),
496
  width=100
497
  )
498
+ submit_btn.click(fn=chat,
499
+ inputs=[prompt_input0, prompt_input1, chat_radio, model_radio, all_chat_history, chat_history],
500
+ outputs=[chatbot, all_chat_history, prompt_input0, prompt_input1],
501
+ )
502
  with gr.Row(elem_id='tab_img', visible=False).style(height=5):
503
  tab_img = gr.TabbedInterface(tab_actions, tab_titles)
504
 
 
 
 
 
505
  openai_api_key_textbox.change(set_openai_api_key,
506
  inputs=[openai_api_key_textbox],
507
  outputs=[])
 
510
  outputs=[])
511
  chat_radio.change(fn=chat_radio_change,
512
  inputs=[chat_radio],
513
+ outputs=[model_radio, openai_api_key_textbox],
514
  )
515
 
516
+ demo.launch(debug = True)