binary-husky commited on
Commit
4e06c35
2 Parent(s): c06c60b 1805f08

Merge pull request #57 from GaiZhenbiao/master

Browse files
Files changed (3) hide show
  1. config.py +9 -3
  2. main.py +20 -21
  3. toolbox.py +4 -4
config.py CHANGED
@@ -6,7 +6,7 @@ API_URL = "https://api.openai.com/v1/chat/completions"
6
  USE_PROXY = False
7
  if USE_PROXY:
8
  # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
9
- proxies = { "http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", }
10
  print('网络代理状态:运行。')
11
  else:
12
  proxies = None
@@ -25,5 +25,11 @@ MAX_RETRY = 2
25
  LLM_MODEL = "gpt-3.5-turbo"
26
 
27
  # 检查一下是不是忘了改config
28
- if API_KEY == "sk-此处填API秘钥":
29
- assert False, "请在config文件中修改API密钥, 添加海外代理之后再运行"
 
 
 
 
 
 
 
6
  USE_PROXY = False
7
  if USE_PROXY:
8
  # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
9
+ proxies = { "http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", }
10
  print('网络代理状态:运行。')
11
  else:
12
  proxies = None
 
25
  LLM_MODEL = "gpt-3.5-turbo"
26
 
27
  # 检查一下是不是忘了改config
28
+ if len(API_KEY) != 51:
29
+ assert False, "请在config文件中修改API密钥, 添加海外代理之后再运行"
30
+
31
+ # 设置并行使用的线程数
32
+ CONCURRENT_COUNT = 100
33
+
34
+ # 设置用户名和密码
35
+ AUTHENTICATION = [] # [("username", "password"), ("username2", "password2"), ...]
main.py CHANGED
@@ -1,14 +1,15 @@
1
  import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
2
- import gradio as gr
3
  from predict import predict
4
  from toolbox import format_io, find_free_port
5
 
6
  # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
7
- try: from config_private import proxies, WEB_PORT, LLM_MODEL
8
- except: from config import proxies, WEB_PORT, LLM_MODEL
9
 
10
  # 如果WEB_PORT是-1, 则随机选取WEB端口
11
  PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
 
12
 
13
  initial_prompt = "Serve me as a writing and programming assistant."
14
  title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
@@ -16,7 +17,7 @@ title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
16
  # 问询记录, python 版本建议3.9+(越新越好)
17
  import logging
18
  os.makedirs('gpt_log', exist_ok=True)
19
- try:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO, encoding='utf-8')
20
  except:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO)
21
  print('所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!')
22
 
@@ -50,7 +51,9 @@ with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
50
  with gr.Column(scale=12):
51
  txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
52
  with gr.Column(scale=1):
53
- submitBtn = gr.Button("提交", variant="primary")
 
 
54
  with gr.Row():
55
  from check_proxy import check_proxy
56
  statusDisplay = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行. \nNetwork: {check_proxy(proxies)}\nModel: {LLM_MODEL}")
@@ -73,31 +76,27 @@ with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
73
  #inputs, top_p, temperature, top_k, repetition_penalty
74
  with gr.Accordion("arguments", open=False):
75
  top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
76
- temperature = gr.Slider(minimum=-0, maximum=5.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
77
 
78
- txt.submit(predict, [txt, top_p, temperature, chatbot, history, systemPromptTxt], [chatbot, history, statusDisplay])
79
- submitBtn.click(predict, [txt, top_p, temperature, chatbot, history, systemPromptTxt], [chatbot, history, statusDisplay], show_progress=True)
 
 
 
 
 
 
80
  for k in functional:
81
- functional[k]["Button"].click(predict,
82
  [txt, top_p, temperature, chatbot, history, systemPromptTxt, TRUE, gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)
83
  file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
84
  for k in crazy_functional:
85
- click_handle = crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],
86
  [txt, top_p, temperature, chatbot, history, systemPromptTxt, gr.State(PORT)], [chatbot, history, statusDisplay]
87
  )
88
  try: click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
89
  except: pass
90
 
91
 
92
- # 延迟函数, 做一些准备工作, 最后尝试打开浏览器
93
- def auto_opentab_delay():
94
- import threading, webbrowser, time
95
- print(f"URL http://localhost:{PORT}")
96
- def open(): time.sleep(2)
97
- webbrowser.open_new_tab(f'http://localhost:{PORT}')
98
- t = threading.Thread(target=open)
99
- t.daemon = True; t.start()
100
-
101
- auto_opentab_delay()
102
  demo.title = "ChatGPT 学术优化"
103
- demo.queue().launch(server_name="0.0.0.0", share=True, server_port=PORT)
 
1
  import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
2
+ import gradio as gr
3
  from predict import predict
4
  from toolbox import format_io, find_free_port
5
 
6
  # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
7
+ try: from config_private import proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION
8
+ except: from config import proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION
9
 
10
  # 如果WEB_PORT是-1, 则随机选取WEB端口
11
  PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
12
+ AUTHENTICATION = None if AUTHENTICATION == [] else AUTHENTICATION
13
 
14
  initial_prompt = "Serve me as a writing and programming assistant."
15
  title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
 
17
  # 问询记录, python 版本建议3.9+(越新越好)
18
  import logging
19
  os.makedirs('gpt_log', exist_ok=True)
20
+ try:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO, encoding='utf-8')
21
  except:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO)
22
  print('所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!')
23
 
 
51
  with gr.Column(scale=12):
52
  txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
53
  with gr.Column(scale=1):
54
+ with gr.Row():
55
+ resetBtn = gr.Button("重置", variant="secondary")
56
+ submitBtn = gr.Button("提交", variant="primary")
57
  with gr.Row():
58
  from check_proxy import check_proxy
59
  statusDisplay = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行. \nNetwork: {check_proxy(proxies)}\nModel: {LLM_MODEL}")
 
76
  #inputs, top_p, temperature, top_k, repetition_penalty
77
  with gr.Accordion("arguments", open=False):
78
  top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
79
+ temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
80
 
81
+ predict_args = dict(fn=predict, inputs=[txt, top_p, temperature, chatbot, history, systemPromptTxt], outputs=[chatbot, history, statusDisplay], show_progress=True)
82
+ empty_txt_args = dict(fn=lambda: "", inputs=[], outputs=[txt])
83
+
84
+ txt.submit(**predict_args)
85
+ txt.submit(**empty_txt_args)
86
+ submitBtn.click(**predict_args)
87
+ submitBtn.click(**empty_txt_args)
88
+ resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, statusDisplay])
89
  for k in functional:
90
+ functional[k]["Button"].click(predict,
91
  [txt, top_p, temperature, chatbot, history, systemPromptTxt, TRUE, gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)
92
  file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
93
  for k in crazy_functional:
94
+ click_handle = crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],
95
  [txt, top_p, temperature, chatbot, history, systemPromptTxt, gr.State(PORT)], [chatbot, history, statusDisplay]
96
  )
97
  try: click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
98
  except: pass
99
 
100
 
 
 
 
 
 
 
 
 
 
 
101
  demo.title = "ChatGPT 学术优化"
102
+ demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=True, server_port=PORT, inbrowser=True, auth=AUTHENTICATION)
toolbox.py CHANGED
@@ -14,7 +14,7 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
14
  # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息
15
  mutable = [None, '']
16
  # multi-threading worker
17
- def mt(i_say, history):
18
  while True:
19
  try:
20
  mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history)
@@ -124,7 +124,7 @@ def format_io(self, y):
124
  """
125
  将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。
126
  """
127
- if y is None: return []
128
  i_ask, gpt_reply = y[-1]
129
  i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波
130
  y[-1] = (
@@ -144,7 +144,7 @@ def find_free_port():
144
  s.bind(('', 0))
145
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
146
  return s.getsockname()[1]
147
-
148
 
149
  def extract_archive(file_path, dest_dir):
150
  import zipfile
@@ -165,7 +165,7 @@ def extract_archive(file_path, dest_dir):
165
  print("Successfully extracted tar archive to {}".format(dest_dir))
166
  else:
167
  return
168
-
169
  def find_recent_files(directory):
170
  """
171
  me: find files that is created with in one minutes under a directory with python, write a function
 
14
  # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息
15
  mutable = [None, '']
16
  # multi-threading worker
17
+ def mt(i_say, history):
18
  while True:
19
  try:
20
  mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history)
 
124
  """
125
  将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。
126
  """
127
+ if y is None or y == []: return []
128
  i_ask, gpt_reply = y[-1]
129
  i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波
130
  y[-1] = (
 
144
  s.bind(('', 0))
145
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
146
  return s.getsockname()[1]
147
+
148
 
149
  def extract_archive(file_path, dest_dir):
150
  import zipfile
 
165
  print("Successfully extracted tar archive to {}".format(dest_dir))
166
  else:
167
  return
168
+
169
  def find_recent_files(directory):
170
  """
171
  me: find files that is created with in one minutes under a directory with python, write a function