Your Name commited on
Commit
92d4400
1 Parent(s): 0f28564

Merge branch 'master' of https://github.com/ValeriaWong/chatgpt_academic

Browse files
.gitignore CHANGED
@@ -138,4 +138,5 @@ ssr_conf
138
  config_private.py
139
  gpt_log
140
  private.md
141
- private_upload
 
 
138
  config_private.py
139
  gpt_log
140
  private.md
141
+ private_upload
142
+ other_llms
README.md CHANGED
@@ -6,12 +6,13 @@ If you like this project, please give it a Star. If you've come up with more use
6
 
7
  ```
8
  代码中参考了很多其他优秀项目中的设计,主要包括:
9
- # 借鉴项目1:借鉴了mdtex2html中公式处理的方法
10
- https://github.com/polarwinkel/mdtex2html
11
 
12
- # 借鉴项目2:借鉴了ChuanhuChatGPT中读取OpenAI json的方法、记录历史问询记录的方法以及gradio queue的使用技巧
13
  https://github.com/GaiZhenbiao/ChuanhuChatGPT
14
 
 
 
 
15
  项目使用OpenAI的gpt-3.5-turbo模型,期待gpt-4早点放宽门槛😂
16
  ```
17
 
 
6
 
7
  ```
8
  代码中参考了很多其他优秀项目中的设计,主要包括:
 
 
9
 
10
+ # 借鉴项目1:借鉴了ChuanhuChatGPT中读取OpenAI json的方法、记录历史问询记录的方法以及gradio queue的使用技巧
11
  https://github.com/GaiZhenbiao/ChuanhuChatGPT
12
 
13
+ # 借鉴项目2:借鉴了mdtex2html中公式处理的方法
14
+ https://github.com/polarwinkel/mdtex2html
15
+
16
  项目使用OpenAI的gpt-3.5-turbo模型,期待gpt-4早点放宽门槛😂
17
  ```
18
 
check_proxy.py CHANGED
@@ -6,8 +6,11 @@ def check_proxy(proxies):
6
  response = requests.get("https://ipapi.co/json/", proxies=proxies, timeout=4)
7
  data = response.json()
8
  print(f'查询代理的地理位置,返回的结果是{data}')
9
- country = data['country_name']
10
- result = f"代理配置 {proxies_https}, 代理所在地:{country}"
 
 
 
11
  print(result)
12
  return result
13
  except:
@@ -17,6 +20,7 @@ def check_proxy(proxies):
17
 
18
 
19
  if __name__ == '__main__':
 
20
  try: from config_private import proxies # 放自己的秘密如API和代理网址 os.path.exists('config_private.py')
21
  except: from config import proxies
22
  check_proxy(proxies)
 
6
  response = requests.get("https://ipapi.co/json/", proxies=proxies, timeout=4)
7
  data = response.json()
8
  print(f'查询代理的地理位置,返回的结果是{data}')
9
+ if 'country_name' in data:
10
+ country = data['country_name']
11
+ result = f"代理配置 {proxies_https}, 代理所在地:{country}"
12
+ elif 'error' in data:
13
+ result = f"代理配置 {proxies_https}, 代理所在地:未知,IP查询频率受限"
14
  print(result)
15
  return result
16
  except:
 
20
 
21
 
22
  if __name__ == '__main__':
23
+ import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
24
  try: from config_private import proxies # 放自己的秘密如API和代理网址 os.path.exists('config_private.py')
25
  except: from config import proxies
26
  check_proxy(proxies)
config.py CHANGED
@@ -5,15 +5,22 @@ API_URL = "https://api.openai.com/v1/chat/completions"
5
  # 改为True应用代理
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
13
  print('网络代理状态:未配置。无代理状态下很可能无法访问。')
14
 
15
  # 发送请求到OpenAI后,等待多久判定为超时
16
- TIMEOUT_SECONDS = 20
17
 
18
  # 网页的端口, -1代表随机端口
19
  WEB_PORT = -1
@@ -24,6 +31,13 @@ MAX_RETRY = 2
24
  # 选择的OpenAI模型是(gpt4现在只对申请成功的人开放)
25
  LLM_MODEL = "gpt-3.5-turbo"
26
 
 
 
 
 
 
 
27
  # 检查一下是不是忘了改config
28
- if API_KEY == "sk-此处填API秘钥":
29
- assert False, "请在config文件中修改API密钥, 添加海外代理之后再运行"
 
 
5
  # 改为True应用代理
6
  USE_PROXY = False
7
  if USE_PROXY:
8
+
9
+ # 填写格式是 [协议]:// [地址] :[端口] ,
10
+ # 例如 "socks5h://localhost:11284"
11
+ # [协议] 常见协议无非socks5h/http,例如 v2*** 和 s** 的默认本地协议是socks5h,cl**h 的默认本地协议是http
12
+ # [地址] 懂的都懂,不懂就填localhost或者127.0.0.1肯定错不了(localhost意思是代理软件安装在本机上)
13
+ # [端口] 在代理软件的设置里,不同的代理软件界面不一样,但端口号都应该在最显眼的位置上
14
+
15
  # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
16
+ proxies = { "http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", }
17
  print('网络代理状态:运行。')
18
  else:
19
  proxies = None
20
  print('网络代理状态:未配置。无代理状态下很可能无法访问。')
21
 
22
  # 发送请求到OpenAI后,等待多久判定为超时
23
+ TIMEOUT_SECONDS = 25
24
 
25
  # 网页的端口, -1代表随机端口
26
  WEB_PORT = -1
 
31
  # 选择的OpenAI模型是(gpt4现在只对申请成功的人开放)
32
  LLM_MODEL = "gpt-3.5-turbo"
33
 
34
+ # 设置并行使用的线程数
35
+ CONCURRENT_COUNT = 100
36
+
37
+ # 设置用户名和密码
38
+ AUTHENTICATION = [] # [("username", "password"), ("username2", "password2"), ...]
39
+
40
  # 检查一下是不是忘了改config
41
+ if len(API_KEY) != 51:
42
+ assert False, "正确的API_KEY密钥是51位,请在config文件中修改API密钥, 添加海外代理之后再运行。" + \
43
+ "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)"
crazy_functions/代码重写为全英文_多线程.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from predict import predict_no_ui_long_connection
3
+ from toolbox import CatchException, write_results_to_file
4
+
5
+
6
+
7
+ @CatchException
8
+ def 全项目切换英文(txt, top_p, temperature, chatbot, history, sys_prompt, WEB_PORT):
9
+ history = [] # 清空历史,以免输入溢出
10
+ # 集合文件
11
+ import time, glob, os
12
+ os.makedirs('gpt_log/generated_english_version', exist_ok=True)
13
+ os.makedirs('gpt_log/generated_english_version/crazy_functions', exist_ok=True)
14
+ file_manifest = [f for f in glob.glob('./*.py') if ('test_project' not in f) and ('gpt_log' not in f)] + \
15
+ [f for f in glob.glob('./crazy_functions/*.py') if ('test_project' not in f) and ('gpt_log' not in f)]
16
+ i_say_show_user_buffer = []
17
+
18
+ # 随便显示点什么防止卡顿的感觉
19
+ for index, fp in enumerate(file_manifest):
20
+ # if 'test_project' in fp: continue
21
+ with open(fp, 'r', encoding='utf-8') as f:
22
+ file_content = f.read()
23
+ i_say_show_user =f'[{index}/{len(file_manifest)}] 接下来请将以下代码中包含的所有中文转化为英文,只输出代码: {os.path.abspath(fp)}'
24
+ i_say_show_user_buffer.append(i_say_show_user)
25
+ chatbot.append((i_say_show_user, "[Local Message] 等待多线程操作,中间过程不予显示."))
26
+ yield chatbot, history, '正常'
27
+
28
+ # 任务函数
29
+ mutable_return = [None for _ in file_manifest]
30
+ def thread_worker(fp,index):
31
+ with open(fp, 'r', encoding='utf-8') as f:
32
+ file_content = f.read()
33
+ i_say = f'接下来请将以下代码中包含的所有中文转化为英文,只输出代码,文件名是{fp},文件代码是 ```{file_content}```'
34
+ # ** gpt request **
35
+ gpt_say = predict_no_ui_long_connection(inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt)
36
+ mutable_return[index] = gpt_say
37
+
38
+ # 所有线程同时开始执行任务函数
39
+ handles = [threading.Thread(target=thread_worker, args=(fp,index)) for index, fp in enumerate(file_manifest)]
40
+ for h in handles:
41
+ h.daemon = True
42
+ h.start()
43
+ chatbot.append(('开始了吗?', f'多线程操作已经开始'))
44
+ yield chatbot, history, '正常'
45
+
46
+ # 循环轮询各个线程是否执行完毕
47
+ cnt = 0
48
+ while True:
49
+ time.sleep(1)
50
+ th_alive = [h.is_alive() for h in handles]
51
+ if not any(th_alive): break
52
+ stat = ['执行中' if alive else '已完成' for alive in th_alive]
53
+ stat_str = '|'.join(stat)
54
+ cnt += 1
55
+ chatbot[-1] = (chatbot[-1][0], f'多线程操作已经开始,完成情况: {stat_str}' + ''.join(['.']*(cnt%4)))
56
+ yield chatbot, history, '正常'
57
+
58
+ # 把结果写入文件
59
+ for index, h in enumerate(handles):
60
+ h.join() # 这里其实不需要join了,肯定已经都结束了
61
+ fp = file_manifest[index]
62
+ gpt_say = mutable_return[index]
63
+ i_say_show_user = i_say_show_user_buffer[index]
64
+
65
+ where_to_relocate = f'gpt_log/generated_english_version/{fp}'
66
+ with open(where_to_relocate, 'w+', encoding='utf-8') as f: f.write(gpt_say.lstrip('```').rstrip('```'))
67
+ chatbot.append((i_say_show_user, f'[Local Message] 已完成{os.path.abspath(fp)}的转化,\n\n存入{os.path.abspath(where_to_relocate)}'))
68
+ history.append(i_say_show_user); history.append(gpt_say)
69
+ yield chatbot, history, '正常'
70
+ time.sleep(1)
71
+
72
+ # 备份一个文件
73
+ res = write_results_to_file(history)
74
+ chatbot.append(("生成一份任务执行报告", res))
75
+ yield chatbot, history, '正常'
crazy_functions/高级功能函数模板.py CHANGED
@@ -1,16 +1,24 @@
1
- from predict import predict_no_ui
2
- from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
3
- fast_debug = False
4
 
5
  @CatchException
6
  def 高阶功能模板函数(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
7
  history = [] # 清空历史,以免输入溢出
 
 
 
8
  for i in range(5):
9
- i_say = f'我给出一个数字,你给出该数字的平方。我给出数字:{i}'
 
 
10
  chatbot.append((i_say, "[Local Message] waiting gpt response."))
11
  yield chatbot, history, '正常' # 由于请求gpt需要一段时间,我们先及时地做一次状态显示
12
 
13
- gpt_say = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature) # 请求gpt,需要一段时间
 
 
 
14
 
15
  chatbot[-1] = (i_say, gpt_say)
16
  history.append(i_say);history.append(gpt_say)
 
1
+ from predict import predict_no_ui_long_connection
2
+ from toolbox import CatchException, report_execption, write_results_to_file
3
+ import datetime
4
 
5
  @CatchException
6
  def 高阶功能模板函数(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
7
  history = [] # 清空历史,以免输入溢出
8
+ chatbot.append(("这是什么功能?", "[Local Message] 请注意,您正在调用一个函数模板,该函数面向希望实现更多有趣功能的开发者,它可以作为创建新功能函数的模板。为了做到简单易读,该函数只有25行代码,不会实时反馈文字流或心跳,请耐心等待程序输出完成。另外您若希望分享新的功能模组,请不吝PR!"))
9
+ yield chatbot, history, '正常' # 由于请求gpt需要一段时间,我们先及时地做一次状态显示
10
+
11
  for i in range(5):
12
+ currentMonth = (datetime.date.today() + datetime.timedelta(days=i)).month
13
+ currentDay = (datetime.date.today() + datetime.timedelta(days=i)).day
14
+ i_say = f'历史中哪些事件发生在{currentMonth}月{currentDay}日?列举两条并发送相关图片。发送图片时,请使用Markdown,将Unsplash API中的PUT_YOUR_QUERY_HERE替换成描述改事件的三个最重要的单词。'
15
  chatbot.append((i_say, "[Local Message] waiting gpt response."))
16
  yield chatbot, history, '正常' # 由于请求gpt需要一段时间,我们先及时地做一次状态显示
17
 
18
+ # history = [] 每次询问不携带之前的询问历史
19
+ gpt_say = predict_no_ui_long_connection(
20
+ inputs=i_say, top_p=top_p, temperature=temperature, history=[],
21
+ sys_prompt="当你想发送一张照片时,请使用Markdown, 并且不要有反斜线, 不要用代码块。使用 Unsplash API (https://source.unsplash.com/1280x720/? < PUT_YOUR_QUERY_HERE >)。") # 请求gpt,需要一段时间
22
 
23
  chatbot[-1] = (i_say, gpt_say)
24
  history.append(i_say);history.append(gpt_say)
functional_crazy.py CHANGED
@@ -8,6 +8,7 @@ def get_crazy_functionals():
8
  from crazy_functions.解析项目源代码 import 解析一个C项目的头文件
9
  from crazy_functions.解析项目源代码 import 解析一个C项目
10
  from crazy_functions.高级功能函数模板 import 高阶功能模板函数
 
11
 
12
  return {
13
  "[实验] 请解析并解构此项目本身": {
@@ -37,37 +38,13 @@ def get_crazy_functionals():
37
  "Color": "stop", # 按钮颜色
38
  "Function": 批量生成函数注释
39
  },
40
- "[实验] 实验功能函数模板": {
41
- "Color": "stop", # 按钮颜色
 
 
42
  "Function": 高阶功能模板函数
43
  },
44
  }
45
 
46
- def on_file_uploaded(files, chatbot, txt):
47
- if len(files) == 0: return chatbot, txt
48
- import shutil, os, time, glob
49
- from toolbox import extract_archive
50
- try: shutil.rmtree('./private_upload/')
51
- except: pass
52
- time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
53
- os.makedirs(f'private_upload/{time_tag}', exist_ok=True)
54
- for file in files:
55
- file_origin_name = os.path.basename(file.orig_name)
56
- shutil.copy(file.name, f'private_upload/{time_tag}/{file_origin_name}')
57
- extract_archive(f'private_upload/{time_tag}/{file_origin_name}',
58
- dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')
59
- moved_files = [fp for fp in glob.glob('private_upload/**/*', recursive=True)]
60
- txt = f'private_upload/{time_tag}'
61
- moved_files_str = '\t\n\n'.join(moved_files)
62
- chatbot.append(['我上传了文件,请查收',
63
- f'[Local Message] 收到以下文件: \n\n{moved_files_str}\n\n调用路径参数已自动修正到: \n\n{txt}\n\n现在您可以直接选择任意实现性功能'])
64
- return chatbot, txt
65
 
66
- def on_report_generated(files, chatbot):
67
- from toolbox import find_recent_files
68
- report_files = find_recent_files('gpt_log')
69
- if len(report_files) == 0: return report_files, chatbot
70
- # files.extend(report_files)
71
- chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。'])
72
- return report_files, chatbot
73
 
 
8
  from crazy_functions.解析项目源代码 import 解析一个C项目的头文件
9
  from crazy_functions.解析项目源代码 import 解析一个C项目
10
  from crazy_functions.高级功能函数模板 import 高阶功能模板函数
11
+ from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文
12
 
13
  return {
14
  "[实验] 请解析并解构此项目本身": {
 
38
  "Color": "stop", # 按钮颜色
39
  "Function": 批量生成函数注释
40
  },
41
+ "[实验] 把本项目源代码切换成全英文(多线程demo)": {
42
+ "Function": 全项目切换英文
43
+ },
44
+ "[实验] 历史上的今天(高阶功能模板函数demo)": {
45
  "Function": 高阶功能模板函数
46
  },
47
  }
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
 
 
 
 
 
 
 
50
 
main.py CHANGED
@@ -1,13 +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
- from config_private import proxies, WEB_PORT, LLM_MODEL
 
8
 
9
  # 如果WEB_PORT是-1, 则随机选取WEB端口
10
  PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
 
11
 
12
  initial_prompt = "Serve me as a writing and programming assistant."
13
  title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
@@ -15,7 +17,7 @@ title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
15
  # 问询记录, python 版本建议3.9+(越新越好)
16
  import logging
17
  os.makedirs('gpt_log', exist_ok=True)
18
- try:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO, encoding='utf-8')
19
  except:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO)
20
  print('所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!')
21
 
@@ -24,7 +26,7 @@ from functional import get_functionals
24
  functional = get_functionals()
25
 
26
  # 对一些丧心病狂的实验性功能模块进行测试
27
- from functional_crazy import get_crazy_functionals, on_file_uploaded, on_report_generated
28
  crazy_functional = get_crazy_functionals()
29
 
30
  # 处理markdown文本格式的转变
@@ -34,6 +36,7 @@ gr.Chatbot.postprocess = format_io
34
  from theme import adjust_theme
35
  set_theme = adjust_theme()
36
 
 
37
  with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
38
  gr.HTML(title_html)
39
  with gr.Row():
@@ -42,14 +45,15 @@ with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
42
  chatbot.style(height=1000)
43
  chatbot.style()
44
  history = gr.State([])
45
- TRUE = gr.State(True)
46
- FALSE = gr.State(False)
47
  with gr.Column(scale=1):
48
  with gr.Row():
49
  with gr.Column(scale=12):
50
  txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
51
  with gr.Column(scale=1):
52
- submitBtn = gr.Button("提交", variant="primary")
 
 
 
53
  with gr.Row():
54
  from check_proxy import check_proxy
55
  statusDisplay = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行. \nNetwork: {check_proxy(proxies)}\nModel: {LLM_MODEL}")
@@ -67,36 +71,43 @@ with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
67
  gr.Markdown("上传本地文件供上面的实验性功能调用.")
68
  with gr.Row():
69
  file_upload = gr.Files(label='任何文件,但推荐上传压缩文件(zip, tar)', file_count="multiple")
70
-
71
- systemPromptTxt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt).style(container=True)
72
- #inputs, top_p, temperature, top_k, repetition_penalty
73
  with gr.Accordion("arguments", open=False):
74
  top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
75
- temperature = gr.Slider(minimum=-0, maximum=5.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
 
 
 
76
 
77
- txt.submit(predict, [txt, top_p, temperature, chatbot, history, systemPromptTxt], [chatbot, history, statusDisplay])
78
- submitBtn.click(predict, [txt, top_p, temperature, chatbot, history, systemPromptTxt], [chatbot, history, statusDisplay], show_progress=True)
 
 
 
79
  for k in functional:
80
- functional[k]["Button"].click(predict,
81
- [txt, top_p, temperature, chatbot, history, systemPromptTxt, TRUE, gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)
 
82
  file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
83
  for k in crazy_functional:
84
- click_handle = crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],
85
- [txt, top_p, temperature, chatbot, history, systemPromptTxt, gr.State(PORT)], [chatbot, history, statusDisplay]
86
  )
87
  try: click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
88
  except: pass
 
 
89
 
90
-
91
- # 延迟函数, 做一些准备工作, 最后尝试打开浏览器
92
  def auto_opentab_delay():
93
  import threading, webbrowser, time
94
  print(f"URL http://localhost:{PORT}")
95
- def open(): time.sleep(2)
96
- webbrowser.open_new_tab(f'http://localhost:{PORT}')
 
97
  t = threading.Thread(target=open)
98
  t.daemon = True; t.start()
99
 
100
  auto_opentab_delay()
101
  demo.title = "ChatGPT 学术优化"
102
- 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, on_file_uploaded, on_report_generated
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
 
 
26
  functional = get_functionals()
27
 
28
  # 对一些丧心病狂的实验性功能模块进行测试
29
+ from functional_crazy import get_crazy_functionals
30
  crazy_functional = get_crazy_functionals()
31
 
32
  # 处理markdown文本格式的转变
 
36
  from theme import adjust_theme
37
  set_theme = adjust_theme()
38
 
39
+ cancel_handles = []
40
  with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
41
  gr.HTML(title_html)
42
  with gr.Row():
 
45
  chatbot.style(height=1000)
46
  chatbot.style()
47
  history = gr.State([])
 
 
48
  with gr.Column(scale=1):
49
  with gr.Row():
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
+ with gr.Row():
54
+ resetBtn = gr.Button("重置", variant="secondary")
55
+ submitBtn = gr.Button("提交", variant="primary")
56
+ stopBtn = gr.Button("停止", variant="stop")
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}")
 
71
  gr.Markdown("上传本地文件供上面的实验性功能调用.")
72
  with gr.Row():
73
  file_upload = gr.Files(label='任何文件,但推荐上传压缩文件(zip, tar)', file_count="multiple")
74
+ system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt).style(container=True)
 
 
75
  with gr.Accordion("arguments", open=False):
76
  top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
77
+ temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
78
+
79
+ predict_args = dict(fn=predict, inputs=[txt, top_p, temperature, chatbot, history, system_prompt], outputs=[chatbot, history, statusDisplay], show_progress=True)
80
+ empty_txt_args = dict(fn=lambda: "", inputs=[], outputs=[txt]) # 用于在提交后清空输入栏
81
 
82
+ cancel_handles.append(txt.submit(**predict_args))
83
+ # txt.submit(**empty_txt_args) 在提交后清空输入栏
84
+ cancel_handles.append(submitBtn.click(**predict_args))
85
+ # submitBtn.click(**empty_txt_args) 在提交后清空输入栏
86
+ resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, statusDisplay])
87
  for k in functional:
88
+ click_handle = functional[k]["Button"].click(predict,
89
+ [txt, top_p, temperature, chatbot, history, system_prompt, gr.State(True), gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)
90
+ cancel_handles.append(click_handle)
91
  file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
92
  for k in crazy_functional:
93
+ click_handle = crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],
94
+ [txt, top_p, temperature, chatbot, history, system_prompt, gr.State(PORT)], [chatbot, history, statusDisplay]
95
  )
96
  try: click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
97
  except: pass
98
+ cancel_handles.append(click_handle)
99
+ stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
100
 
101
+ # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
 
102
  def auto_opentab_delay():
103
  import threading, webbrowser, time
104
  print(f"URL http://localhost:{PORT}")
105
+ def open():
106
+ time.sleep(2)
107
+ webbrowser.open_new_tab(f'http://localhost:{PORT}')
108
  t = threading.Thread(target=open)
109
  t.daemon = True; t.start()
110
 
111
  auto_opentab_delay()
112
  demo.title = "ChatGPT 学术优化"
113
+ demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=True, server_port=PORT, auth=AUTHENTICATION)
predict.py CHANGED
@@ -1,5 +1,16 @@
1
  # 借鉴了 https://github.com/GaiZhenbiao/ChuanhuChatGPT 项目
2
 
 
 
 
 
 
 
 
 
 
 
 
3
  import json
4
  import gradio as gr
5
  import logging
@@ -25,7 +36,7 @@ def get_full_error(chunk, stream_response):
25
  break
26
  return chunk
27
 
28
- def predict_no_ui(inputs, top_p, temperature, history=[]):
29
  """
30
  发送至chatGPT,等待回复,一次性完成,不显示中间过程。
31
  predict函数的简化版。
@@ -36,7 +47,7 @@ def predict_no_ui(inputs, top_p, temperature, history=[]):
36
  history 是之前的对话列表
37
  (注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误,然后raise ConnectionAbortedError)
38
  """
39
- headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt="", stream=False)
40
 
41
  retry = 0
42
  while True:
@@ -47,8 +58,8 @@ def predict_no_ui(inputs, top_p, temperature, history=[]):
47
  except requests.exceptions.ReadTimeout as e:
48
  retry += 1
49
  traceback.print_exc()
50
- if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
51
  if retry > MAX_RETRY: raise TimeoutError
 
52
 
53
  try:
54
  result = json.loads(response.text)["choices"][0]["message"]["content"]
@@ -58,6 +69,41 @@ def predict_no_ui(inputs, top_p, temperature, history=[]):
58
  raise ConnectionAbortedError("Json解析不合常规,可能是文本过长" + response.text)
59
 
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt='',
62
  stream = True, additional_fn=None):
63
  """
@@ -130,7 +176,7 @@ def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt=''
130
  chunk = get_full_error(chunk, stream_response)
131
  error_msg = chunk.decode()
132
  if "reduce the length" in error_msg:
133
- chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refleshing this page.")
134
  history = []
135
  elif "Incorrect API key" in error_msg:
136
  chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")
 
1
  # 借鉴了 https://github.com/GaiZhenbiao/ChuanhuChatGPT 项目
2
 
3
+ """
4
+ 该文件中主要包含三个函数
5
+
6
+ 不具备多线程能力的函数:
7
+ 1. predict: 正常对话时使用,具备完备的交互功能,不可多线程
8
+
9
+ 具备多线程调用能力的函数
10
+ 2. predict_no_ui:高级实验性功能模块调用,不会实时显示在界面上,参数简单,可以多线程并行,方便实现复杂的功能逻辑
11
+ 3. predict_no_ui_long_connection:在实验过程中发现调用predict_no_ui处理长文档时,和openai的连接容易断掉,这个函数用stream的方式解决这个问题,同样支持多线程
12
+ """
13
+
14
  import json
15
  import gradio as gr
16
  import logging
 
36
  break
37
  return chunk
38
 
39
+ def predict_no_ui(inputs, top_p, temperature, history=[], sys_prompt=""):
40
  """
41
  发送至chatGPT,等待回复,一次性完成,不显示中间过程。
42
  predict函数的简化版。
 
47
  history 是之前的对话列表
48
  (注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误,然后raise ConnectionAbortedError)
49
  """
50
+ headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=False)
51
 
52
  retry = 0
53
  while True:
 
58
  except requests.exceptions.ReadTimeout as e:
59
  retry += 1
60
  traceback.print_exc()
 
61
  if retry > MAX_RETRY: raise TimeoutError
62
+ if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
63
 
64
  try:
65
  result = json.loads(response.text)["choices"][0]["message"]["content"]
 
69
  raise ConnectionAbortedError("Json解析不合常规,可能是文本过长" + response.text)
70
 
71
 
72
+ def predict_no_ui_long_connection(inputs, top_p, temperature, history=[], sys_prompt=""):
73
+ """
74
+ 发送至chatGPT,等待回复,一次性完成,不显示中间过程。但内部用stream的方法避免有人中途掐网线。
75
+ """
76
+ headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=True)
77
+
78
+ retry = 0
79
+ while True:
80
+ try:
81
+ # make a POST request to the API endpoint, stream=False
82
+ response = requests.post(API_URL, headers=headers, proxies=proxies,
83
+ json=payload, stream=True, timeout=TIMEOUT_SECONDS); break
84
+ except requests.exceptions.ReadTimeout as e:
85
+ retry += 1
86
+ traceback.print_exc()
87
+ if retry > MAX_RETRY: raise TimeoutError
88
+ if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
89
+
90
+ stream_response = response.iter_lines()
91
+ result = ''
92
+ while True:
93
+ try: chunk = next(stream_response).decode()
94
+ except StopIteration: break
95
+ if len(chunk)==0: continue
96
+ if not chunk.startswith('data:'):
97
+ chunk = get_full_error(chunk.encode('utf8'), stream_response)
98
+ raise ConnectionAbortedError("OpenAI拒绝了请求:" + chunk.decode())
99
+ delta = json.loads(chunk.lstrip('data:'))['choices'][0]["delta"]
100
+ if len(delta) == 0: break
101
+ if "role" in delta: continue
102
+ if "content" in delta: result += delta["content"]; print(delta["content"], end='')
103
+ else: raise RuntimeError("意外Json结构:"+delta)
104
+ return result
105
+
106
+
107
  def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt='',
108
  stream = True, additional_fn=None):
109
  """
 
176
  chunk = get_full_error(chunk, stream_response)
177
  error_msg = chunk.decode()
178
  if "reduce the length" in error_msg:
179
+ chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refreshing this page.")
180
  history = []
181
  elif "Incorrect API key" in error_msg:
182
  chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")
project_self_analysis.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chatgpt-academic项目分析报告
2
+ (Author补充:以下分析均由本项目调用ChatGPT一键生成,如果有不准确的地方全怪GPT)
3
+
4
+ ## [0/10] 程序摘要: check_proxy.py
5
+
6
+ 这个程序是一个用来检查代理服务器是否有效的 Python 程序代码。程序文件名为 check_proxy.py。其中定义了一个函数 check_proxy,该函数接收一个代理配置信息 proxies,使用 requests 库向一个代理服务器发送请求,获取该代理的所在地信息并返回。如果请求超时或者异常,该函数将返回一个代理无效的结果。
7
+
8
+ 程序代码分为两个部分,首先是 check_proxy 函数的定义部分,其次是程序文件的入口部分,在该部分代码中,程序从 config_private.py 文件或者 config.py 文件中加载代理配置信息,然后调用 check_proxy 函数来检测代理服务器是否有效。如果配置文件 config_private.py 存在,则会加载其中的代理配置信息,否则会从 config.py 文件中读取。
9
+
10
+ ## [1/10] 程序摘要: config.py
11
+
12
+ 本程序文件名为config.py,主要功能是存储应用所需的常量和配置信息。
13
+
14
+ 其中,包含了应用所需的OpenAI API密钥、API接口地址、网络代理设置、超时设置、网络端口和OpenAI模型选择等信息,在运行应用前需要进行相应的配置。在未配置网络代理时,程序给出了相应的警告提示。
15
+
16
+ 此外,还包含了一个检查函数,用于检查是否忘记修改API密钥。
17
+
18
+ 总之,config.py文件是应用中的一个重要配置文件,用来存储应用所需的常量和配置信息,需要在应用运行前进行相应的配置。
19
+
20
+ ## [2/10] 程序摘要: config_private.py
21
+
22
+ 该文件是一个配置文件,命名为config_private.py。它是一个Python脚本,用于配置OpenAI的API密钥、模型和其它相关设置。该配置文件还可以设置是否使用代理。如果使用代理,需要设置代理协议、地址和端口。在设置代理之后,该文件还包括一些用于测试代理是否正常工作的代码。该文件还包括超时时间、随机端口、重试次数等设置。在文件末尾,还有一个检查代码,如果没有更改API密钥,则抛出异常。
23
+
24
+ ## [3/10] 程序摘要: functional.py
25
+
26
+ 该程序文件名为 functional.py,其中包含一个名为 get_functionals 的函数,该函数返回一个字典,该字典包含了各种翻译、校对等功能的名称、前缀、后缀以及默认按钮颜色等信息。具体功能包括:英语学术润色、中文学术润色、查找语法错误、中英互译、中译英、学术中译英、英译中、解释代码等。该程序的作用为提供各种翻译、校对等功能的模板,以便后续程序可以直接调用。
27
+
28
+ (Author补充:这个文件汇总了模块化的Prompt调用,如果发现了新的好用Prompt,别藏着哦^_^速速PR)
29
+
30
+
31
+ ## [4/10] 程序摘要: functional_crazy.py
32
+
33
+ 这个程序文件 functional_crazy.py 导入了一些 python 模块,并提供了一个函数 get_crazy_functionals(),该函数返回不同实验功能的描述和函数。其中,使用的的模块包括:
34
+
35
+ - crazy_functions.读文章写摘要 中的 读文章写摘要
36
+ - crazy_functions.生成函数注释 中的 批量生成函数注释
37
+ - crazy_functions.解析项目源代码 中的 解析项目本身、解析一个Python项目、解析一个C项目的头文件、解析一个C项目
38
+ - crazy_functions.高级功能函数模板 中的 高阶功能模板函数
39
+
40
+ 返回的实验功能函数包括:
41
+
42
+ - "[实验] 请解析并解构此项目本身",包含函数:解析项目本身
43
+ - "[实验] 解析整个py项目(配合input输入框)",包含函数:解析一个Python项目
44
+ - "[实验] 解析整个C++项目头文件(配合input输入框)",包含函数:解析一个C项目的头文件
45
+ - "[实验] 解析整个C++项目(配合input输入框)",包含函数:解析一个C项目
46
+ - "[实验] 读tex论文写摘要(配合input输入框)",包含函数:读文章写摘要
47
+ - "[实验] 批量生成函数注释(配合input输入框)",包含函数:批量生成函数注释
48
+ - "[实验] 实验功能函数模板",包含函数:高阶功能模板函数
49
+
50
+ 这些函数用于系统开发和测试,方便开发者进行特定程序语言后台功能开发的测试和实验,增加系统可靠稳定性和用户友好性。
51
+
52
+ (Author补充:这个文件汇总了模块化的函数,如此设计以方便任何新功能的加入)
53
+
54
+ ## [5/10] 程序摘要: main.py
55
+
56
+ 该程序是一个基于Gradio框架的聊天机器人应用程序。用户可以通过输入问题来获取答案,并与聊天机器人进行对话。该应用程序还集成了一些实验性功能模块,用户可以通过上传本地文件或点击相关按钮来使用这些模块。程序还可以生成对话日志,并且具有一些外观上的调整。在运行时,它会自动打开一个网页并在本地启动服务器。
57
+
58
+
59
+ ## [6/10] 程序摘要: predict.py
60
+
61
+ 该程序文件名为predict.py,主要是针对一个基于ChatGPT的聊天机器人进行交互和预测。
62
+
63
+ 第一部分是导入所需的库和配置文件。
64
+
65
+ 第二部分是一个用于获取Openai返回的完整错误信息的函数。
66
+
67
+ 第三部分是用于一次性完成向ChatGPT发送请求和等待回复的函数。
68
+
69
+ 第四部分是用于基础的对话功能的函数,通过stream参数可以选择是否显示中间的过程。
70
+
71
+ 第五部分是用于整合所需信息和选择LLM模型生成的HTTP请求。
72
+
73
+ (Author补充:主要是predict_no_ui和predict两个函数。前者不用stream,方便、高效、易用。后者用stream,展现效果好。)
74
+
75
+ ## [7/10] 程序摘要: show_math.py
76
+
77
+ 这是一个名为show_math.py的Python程序文件,主要用于将Markdown-LaTeX混合文本转换为HTML格式,并包括MathML数学公式。程序使用latex2mathml.converter库将LaTeX公式转换为MathML格式,并使用正则表达式递归地翻译输入的Markdown-LaTeX混合文本。程序包括转换成双美元符号($$)形式、转换成单美元符号($)形式、转换成\[\]形式以及转换成\(\)形式的LaTeX数学公式。如果转换中出现错误,程序将返回相应的错误消息。
78
+
79
+ ## [8/10] 程序摘要: theme.py
80
+
81
+ 这是一个名为theme.py的程序文件,用于设置Gradio界面的颜色和字体主题。该文件中定义了一个名为adjust_theme()的函数,其作用是返回一个Gradio theme对象,设置了Gradio界面的颜色和字体主题。在该函数里面,使用了Graido可用的颜色列表,主要参数包括primary_hue、neutral_hue、font和font_mono等,用于设置Gradio界面的主题色调、字体等。另外,该函数还实现了一些参数的自定义,如input_background_fill_dark、button_transition、button_shadow_hover等,用于设置Gradio界面的渐变、阴影等特效。如果Gradio版本过于陈旧,该函数会抛出异常并返回None。
82
+
83
+ ## [9/10] 程序摘要: toolbox.py
84
+
85
+ 该文件为Python程序文件,文件名为toolbox.py。主要功能包括:
86
+
87
+ 1. 导入markdown、mdtex2html、threading、functools等模块。
88
+ 2. 定义函数predict_no_ui_but_counting_down,用于生成对话。
89
+ 3. 定义函数write_results_to_file,用于将对话记录生成Markdown文件。
90
+ 4. 定义函数regular_txt_to_markdown,将普通文本转换为Markdown格式的文本。
91
+ 5. 定义装饰器函数CatchException,用于捕获函数执行异常并返回生成器。
92
+ 6. 定义函数report_execption,用于向chatbot中添加错误信息。
93
+ 7. 定义函数text_divide_paragraph,用于将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
94
+ 8. 定义函数markdown_convertion,用于将Markdown格式的文本转换为HTML格式。
95
+ 9. 定义函数format_io,用于将输入和输出解析为HTML格式。
96
+ 10. 定义函数find_free_port,用于返回当前系统中可用的未使用端口。
97
+ 11. 定义函数extract_archive,用于解压归档文件。
98
+ 12. 定义函数find_recent_files,用于查找最近创建的文件。
99
+ 13. 定义函数on_file_uploaded,用于处理上传文件的操作。
100
+ 14. 定义函数on_report_generated,用于处理生成报告文件的操作。
101
+
102
+ ## 程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能。
103
+
104
+ 这是一个基于Gradio框架的聊天机器人应用,支持通过文本聊天来获取答案,并可以使用一系列实验性功能模块,例如生成函数注释、解析项目源代码、读取Latex论文写摘要等。 程序架构分为前端和后端两个部分。前端使用Gradio实现,包括用户输入区域、应答区域、按钮、调用方式等。后端使用Python实现,包括聊天机器人模型、实验性功能模块、模板模块、管理模块、主程序模块等。
105
+
106
+ 每个程序文件的功能如下:
107
+
108
+ | 文件名 | 功能描述 |
109
+ |:----:|:----:|
110
+ | check_proxy.py | 检查代理服务器是否有效 |
111
+ | config.py | 存储应用所需的常量和配置信息 |
112
+ | config_private.py | 存储Openai的API密钥、模型和其他相关设置 |
113
+ | functional.py | 提供各种翻译、校对等实用模板 |
114
+ | functional_crazy.py | 提供一些实验性质的高级功能 |
115
+ | main.py | 基于Gradio框架的聊天机器人应用程序的主程序 |
116
+ | predict.py | 用于chatbot预测方案创建,向ChatGPT发送请求和获取回复 |
117
+ | show_math.py | 将Markdown-LaTeX混合文本转换为HTML格式,并包括MathML数学公式 |
118
+ | theme.py | 设置Gradio界面的颜色和字体主题 |
119
+ | toolbox.py | 定义一系列工具函数,用于对输入输出进行格式转换、文件操作、异常捕捉和处理等 |
120
+
121
+ 这些程序文件共同组成了一个聊天机器人应用程序的前端和后端实现,使用户可以方便地进行聊天,并可以使用相应的实验功能模块。
122
+
toolbox.py CHANGED
@@ -2,7 +2,7 @@ import markdown, mdtex2html, threading
2
  from show_math import convert as convert_math
3
  from functools import wraps
4
 
5
- def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[]):
6
  """
7
  调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断
8
  """
@@ -14,10 +14,10 @@ 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)
21
  break
22
  except ConnectionAbortedError as e:
23
  if len(history) > 0:
@@ -27,7 +27,8 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
27
  i_say = i_say[:len(i_say)//2]
28
  mutable[1] = 'Warning! Input file is too long, cut into half. '
29
  except TimeoutError as e:
30
- mutable[0] = '[Local Message] Failed with timeout'
 
31
  # 创建新线程发出http请求
32
  thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start()
33
  # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成
@@ -39,6 +40,7 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
39
  time.sleep(1)
40
  # 把gpt的输出从mutable中取出来
41
  gpt_say = mutable[0]
 
42
  return gpt_say
43
 
44
  def write_results_to_file(history, file_name=None):
@@ -105,8 +107,8 @@ def text_divide_paragraph(text):
105
  # wtf input
106
  lines = text.split("\n")
107
  for i, line in enumerate(lines):
108
- if i!=0: lines[i] = "<p>"+lines[i].replace(" ", "&nbsp;")+"</p>"
109
- text = "".join(lines)
110
  return text
111
 
112
  def markdown_convertion(txt):
@@ -124,7 +126,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 +146,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 +167,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
@@ -182,6 +184,37 @@ def find_recent_files(directory):
182
  if file_path.endswith('.log'): continue
183
  created_time = os.path.getctime(file_path)
184
  if created_time >= one_minute_ago:
 
185
  recent_files.append(file_path)
186
 
187
- return recent_files
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from show_math import convert as convert_math
3
  from functools import wraps
4
 
5
+ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[], sys_prompt=''):
6
  """
7
  调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断
8
  """
 
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, sys_prompt=sys_prompt)
21
  break
22
  except ConnectionAbortedError as e:
23
  if len(history) > 0:
 
27
  i_say = i_say[:len(i_say)//2]
28
  mutable[1] = 'Warning! Input file is too long, cut into half. '
29
  except TimeoutError as e:
30
+ mutable[0] = '[Local Message] Failed with timeout.'
31
+ raise TimeoutError
32
  # 创建新线程发出http请求
33
  thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start()
34
  # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成
 
40
  time.sleep(1)
41
  # 把gpt的输出从mutable中取出来
42
  gpt_say = mutable[0]
43
+ if gpt_say=='[Local Message] Failed with timeout.': raise TimeoutError
44
  return gpt_say
45
 
46
  def write_results_to_file(history, file_name=None):
 
107
  # wtf input
108
  lines = text.split("\n")
109
  for i, line in enumerate(lines):
110
+ lines[i] = "<p>"+lines[i].replace(" ", "&nbsp;")+"</p>"
111
+ text = "\n".join(lines)
112
  return text
113
 
114
  def markdown_convertion(txt):
 
126
  """
127
  将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。
128
  """
129
+ if y is None or y == []: return []
130
  i_ask, gpt_reply = y[-1]
131
  i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波
132
  y[-1] = (
 
146
  s.bind(('', 0))
147
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
148
  return s.getsockname()[1]
149
+
150
 
151
  def extract_archive(file_path, dest_dir):
152
  import zipfile
 
167
  print("Successfully extracted tar archive to {}".format(dest_dir))
168
  else:
169
  return
170
+
171
  def find_recent_files(directory):
172
  """
173
  me: find files that is created with in one minutes under a directory with python, write a function
 
184
  if file_path.endswith('.log'): continue
185
  created_time = os.path.getctime(file_path)
186
  if created_time >= one_minute_ago:
187
+ if os.path.isdir(file_path): continue
188
  recent_files.append(file_path)
189
 
190
+ return recent_files
191
+
192
+
193
+ def on_file_uploaded(files, chatbot, txt):
194
+ if len(files) == 0: return chatbot, txt
195
+ import shutil, os, time, glob
196
+ from toolbox import extract_archive
197
+ try: shutil.rmtree('./private_upload/')
198
+ except: pass
199
+ time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
200
+ os.makedirs(f'private_upload/{time_tag}', exist_ok=True)
201
+ for file in files:
202
+ file_origin_name = os.path.basename(file.orig_name)
203
+ shutil.copy(file.name, f'private_upload/{time_tag}/{file_origin_name}')
204
+ extract_archive(f'private_upload/{time_tag}/{file_origin_name}',
205
+ dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')
206
+ moved_files = [fp for fp in glob.glob('private_upload/**/*', recursive=True)]
207
+ txt = f'private_upload/{time_tag}'
208
+ moved_files_str = '\t\n\n'.join(moved_files)
209
+ chatbot.append(['我上传了文件,请查收',
210
+ f'[Local Message] 收到以下文件: \n\n{moved_files_str}\n\n调用路径参数已自动修正到: \n\n{txt}\n\n现在您点击任意实验功能时,以上文件将被作为输入参数'])
211
+ return chatbot, txt
212
+
213
+
214
+ def on_report_generated(files, chatbot):
215
+ from toolbox import find_recent_files
216
+ report_files = find_recent_files('gpt_log')
217
+ if len(report_files) == 0: return report_files, chatbot
218
+ # files.extend(report_files)
219
+ chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。'])
220
+ return report_files, chatbot