mrhblfx commited on
Commit
26af2b1
2 Parent(s): 20bec70 97385c9

update by pull

Browse files
.gitignore CHANGED
@@ -55,7 +55,6 @@ coverage.xml
55
  *.pot
56
  github
57
  .github
58
- .idea/
59
  TEMP
60
  TRASH
61
 
@@ -144,3 +143,5 @@ private_upload
144
  other_llms
145
  cradle*
146
  debug*
 
 
 
55
  *.pot
56
  github
57
  .github
 
58
  TEMP
59
  TRASH
60
 
 
143
  other_llms
144
  cradle*
145
  debug*
146
+ private*
147
+ crazy_functions/test_project/pdf_and_word
Dockerfile CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  FROM python:3.11
2
 
3
  RUN echo '[global]' > /etc/pip.conf && \
@@ -11,4 +14,7 @@ RUN pip3 install -r requirements.txt
11
 
12
  COPY . .
13
 
 
 
 
14
  CMD ["python3", "-u", "main.py"]
 
1
+ # 此Dockerfile适用于“无本地模型”的环境构建,如果需要使用chatglm等本地模型,请参考 docs/Dockerfile+ChatGLM
2
+ # 如何构建: 先修改 `config.py`, 然后 docker build -t gpt-academic .
3
+ # 如何运行: docker run --rm -it --net=host gpt-academic
4
  FROM python:3.11
5
 
6
  RUN echo '[global]' > /etc/pip.conf && \
 
14
 
15
  COPY . .
16
 
17
+ # 可选步骤,用于预热模块
18
+ RUN python3 -c 'from check_proxy import warm_up_modules; warm_up_modules()'
19
+
20
  CMD ["python3", "-u", "main.py"]
README.md CHANGED
@@ -1,8 +1,10 @@
1
- # ChatGPT 学术优化
 
 
2
 
3
  **如果喜欢这个项目,请给它一个Star;如果你发明了更好用的快捷键或函数插件,欢迎发issue或者pull requests**
4
 
5
- If you like this project, please give it a Star. If you've come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request. We also have a [README in English](img/README_EN.md) translated by this project itself.
6
 
7
  > **Note**
8
  >
@@ -21,7 +23,7 @@ If you like this project, please give it a Star. If you've come up with more use
21
  一键代码解释 | 可以正确显示代码、解释代码
22
  [自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键
23
  [配置代理服务器](https://www.bilibili.com/video/BV1rc411W7Dr) | 支持配置代理服务器
24
- 模块化设计 | 支持自定义高阶的实验性功能与[函数插件],插件支持[热更新](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97)
25
  [自我程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] [一键读懂](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)本项目的源代码
26
  [程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] 一键可以剖析其他Python/C/C++/Java/Lua/...项目树
27
  读论文 | [函数插件] 一键解读latex论文全文并生成摘要
@@ -34,8 +36,7 @@ chat分析报告生成 | [函数插件] 运行后自动生成总结汇报
34
  公式/图片/表格显示 | 可以同时显示公式的tex形式和渲染形式,支持公式、代码高亮
35
  多线程函数插件支持 | 支持多线调用chatgpt,一键处理海量文本或程序
36
  启动暗色gradio[主题](https://github.com/binary-husky/chatgpt_academic/issues/173) | 在浏览器url后面添加```/?__dark-theme=true```可以切换dark主题
37
- [多LLM模型](https://www.bilibili.com/video/BV1EM411K7VH/)支持([v3.1分支](https://github.com/binary-husky/chatgpt_academic/tree/v3.1) | 同时被ChatGPT和[清华ChatGLM](https://github.com/THUDM/ChatGLM-6B)伺候的感觉一定会很不错吧?
38
- 兼容[TGUI](https://github.com/oobabooga/text-generation-webui)接入更多样的语言模型 | 接入opt-1.3b, galactica-1.3b等模型([v3.1分支](https://github.com/binary-husky/chatgpt_academic/tree/v3.0)测试中)
39
  huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/gpt-academic) | 登陆huggingface后复制[此空间](https://huggingface.co/spaces/qingxu98/gpt-academic)
40
  …… | ……
41
 
@@ -68,35 +69,37 @@ huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/
68
  <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
69
  </div>
70
 
71
- - 多种大语言模型混合调用(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4, [v3.1分支](https://github.com/binary-husky/chatgpt_academic/tree/v3.1)测试中)
72
  <div align="center">
73
  <img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
74
  </div>
75
 
76
- v3.1的[huggingface测试版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)(huggingface版不支持chatglm)
77
 
78
 
 
79
 
80
- ## 直接运行 (Windows, Linux or MacOS)
81
 
82
- ### 1. 下载项目
83
  ```sh
84
  git clone https://github.com/binary-husky/chatgpt_academic.git
85
  cd chatgpt_academic
86
  ```
87
 
88
- ### 2. 配置API_KEY和代理设置
89
 
90
  在`config.py`中,配置 海外Proxy 和 OpenAI API KEY,说明如下
91
  ```
92
  1. 如果你在国内,需要设置海外代理才能够顺利使用 OpenAI API,设置方法请仔细阅读config.py(1.修改其中的USE_PROXY为True; 2.按照说明修改其中的proxies)。
93
  2. 配置 OpenAI API KEY。你���要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。
 
94
  3. 与代理网络有关的issue(网络超时、代理不起作用)汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1
95
  ```
96
  (P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控,可以让您的隐私信息更加安全。)
97
 
98
 
99
- ### 3. 安装依赖
100
  ```sh
101
  # (选择一)推荐
102
  python -m pip install -r requirements.txt
@@ -110,27 +113,30 @@ python -m pip install -r requirements.txt
110
  # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
111
  ```
112
 
113
- ### 4. 运行
 
 
 
 
 
114
  ```sh
115
  python main.py
116
  ```
117
 
118
- ### 5. 测试实验性功能
119
  ```
120
- - 测试C++项目头文件分析
121
- input区域 输入 `./crazy_functions/test_project/cpp/libJPG` , 然后点击 "[实验] 解析整个C++项目(input输入项目根路径)"
122
- - 测试给Latex项目写摘要
123
- input区域 输入 `./crazy_functions/test_project/latex/attention` , 然后点击 "[实验] 读tex论文写摘要(input输入项目根路径)"
124
  - 测试Python项目分析
125
- input区域 输入 `./crazy_functions/test_project/python/dqn` , 然后点击 "[实验] 解析整个py项目(input输入项目根路径)"
126
  - 测试自我代码解读
127
- 点击 "[实验] 请解析并解构此项目本身"
128
  - 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
129
- 点击 "[实验] 实验功能函数模板"
 
130
  ```
131
 
132
- ## 使用docker (Linux)
133
 
 
134
  ``` sh
135
  # 下载项目
136
  git clone https://github.com/binary-husky/chatgpt_academic.git
@@ -142,67 +148,70 @@ docker build -t gpt-academic .
142
  # 运行
143
  docker run --rm -it --net=host gpt-academic
144
 
145
- # 测试实验性功能
146
- ## 测试自我代码解读
147
- 点击 "[实验] 请解析并解构此项目本身"
148
- ## 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
149
- 点击 "[实验] 实验功能函数模板"
150
- ##(请注意在docker中运行时,需要额外注意程序的文件访问权限问题)
151
- ## 测试C++项目头文件分析
152
- input区域 输入 ./crazy_functions/test_project/cpp/libJPG , 然后点击 "[实验] 解析整个C++项目(input输入项目根路径)"
153
  ## 测试给Latex项目写摘要
154
- input区域 输入 ./crazy_functions/test_project/latex/attention , 然后点击 "[实验] tex论文写摘要(input输入项目根路径)"
155
  ## 测试Python项目分析
156
- input区域 输入 ./crazy_functions/test_project/python/dqn , 然后点击 "[实验] 解析整个py项目(input输入项目根路径)"
157
 
 
158
  ```
159
 
160
- ## 其他部署方式
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
- - 远程云服务器部署
163
- 请访问[部署wiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
164
 
165
- - 使用WSL2(Windows Subsystem for Linux 子系统)
166
- 请访问[部署wiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
167
 
168
  ## 自定义新的便捷按钮(学术快捷键自定义)
169
  任意文本编辑器打开`core_functional.py`,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。)
170
  例如
171
  ```
172
  "超级英译中": {
173
-
174
  # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等
175
  "Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n",
176
 
177
  # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。
178
  "Suffix": "",
179
-
180
  },
181
  ```
182
  <div align="center">
183
  <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
184
  </div>
185
 
 
186
 
187
- 如果你发明了更好用的快捷键,欢迎发issue或者pull requests!
188
-
189
- ## 配置代理
190
- ### 方法一:常规方法
191
- 在```config.py```中修改端口与代理软件对应
192
 
193
- <div align="center">
194
- <img src="https://user-images.githubusercontent.com/96192199/226571294-37a47cd9-4d40-4c16-97a2-d360845406f7.png" width="500" >
195
- <img src="https://user-images.githubusercontent.com/96192199/226838985-e5c95956-69c2-4c23-a4dd-cd7944eeb451.png" width="500" >
196
- </div>
197
-
198
- 配置完成后,你可以用以下命令测试代理是否工作,如果一切正常,下面的代码将输出你的代理服务器所在地:
199
- ```
200
- python check_proxy.py
201
- ```
202
- ### 方法二:纯新手教程
203
- [纯新手教程](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
204
-
205
- ## 功能测试
206
 
207
  ### 图片显示:
208
 
@@ -256,8 +265,9 @@ python check_proxy.py
256
  </div>
257
 
258
  ## Todo 与 版本规划:
259
-
260
- - version 3.0 (Todo): 优化对chatglm和其他小型llm的支持
 
261
  - version 2.6: 重构了插件结构,提高了交互性,加入更多插件
262
  - version 2.5: 自更新,解决总结大工程源代码时文本过长、token溢出的问题
263
  - version 2.4: (1)新增PDF全文翻译功能; (2)新增输入区切换位置的功能; (3)新增垂直布局选项; (4)多线程函数插件优化。
@@ -267,16 +277,16 @@ python check_proxy.py
267
  - version 2.0: 引入模块化函数插件
268
  - version 1.0: 基础功能
269
 
270
- ## 参考与学习
271
 
 
272
 
273
  ```
274
  代码中参考了很多其他优秀项目中的设计,主要包括:
275
 
276
- # 借鉴项目1:借鉴了ChuanhuChatGPT中读取OpenAI json的方法、记录历史问询记录的方法以及gradio queue的使用技巧
277
  https://github.com/GaiZhenbiao/ChuanhuChatGPT
278
 
279
- # 借鉴项目2:
280
  https://github.com/THUDM/ChatGLM-6B
281
-
282
  ```
 
1
+
2
+
3
+ # <img src="docs/logo.png" width="40" > ChatGPT 学术优化
4
 
5
  **如果喜欢这个项目,请给它一个Star;如果你发明了更好用的快捷键或函数插件,欢迎发issue或者pull requests**
6
 
7
+ If you like this project, please give it a Star. If you've come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request. We also have a README in [English|](docs/README_EN.md)[日本語|](docs/README_JP.md)[Русский|](docs/README_RS.md)[Français](docs/README_FR.md) translated by this project itself.
8
 
9
  > **Note**
10
  >
 
23
  一键代码解释 | 可以正确显示代码、解释代码
24
  [自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键
25
  [配置代理服务器](https://www.bilibili.com/video/BV1rc411W7Dr) | 支持配置代理服务器
26
+ 模块化设计 | 支持自定义高阶的函数插件与[函数插件],插件支持[热更新](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97)
27
  [自我程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] [一键读懂](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)本项目的源代码
28
  [程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] 一键可以剖析其他Python/C/C++/Java/Lua/...项目树
29
  读论文 | [函数插件] 一键解读latex论文全文并生成摘要
 
36
  公式/图片/表格显示 | 可以同时显示公式的tex形式和渲染形式,支持公式、代码高亮
37
  多线程函数插件支持 | 支持多线调用chatgpt,一键处理海量文本或程序
38
  启动暗色gradio[主题](https://github.com/binary-husky/chatgpt_academic/issues/173) | 在浏览器url后面添加```/?__dark-theme=true```可以切换dark主题
39
+ [多LLM模型](https://www.bilibili.com/video/BV1wT411p7yf)支持,[API2D](https://api2d.com/)接口支持 | 同时被GPT3.5、GPT4和[清华ChatGLM](https://github.com/THUDM/ChatGLM-6B)伺候的感觉一定会很不错吧?
 
40
  huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/gpt-academic) | 登陆huggingface后复制[此空间](https://huggingface.co/spaces/qingxu98/gpt-academic)
41
  …… | ……
42
 
 
69
  <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
70
  </div>
71
 
72
+ - 多种大语言模型混合调用(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4
73
  <div align="center">
74
  <img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
75
  </div>
76
 
77
+ 多种大语言模型混合调用[huggingface测试版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)(huggingface版不支持chatglm)
78
 
79
 
80
+ ---
81
 
82
+ ## 安装-方法1:直接运行 (Windows, Linux or MacOS)
83
 
84
+ 1. 下载项目
85
  ```sh
86
  git clone https://github.com/binary-husky/chatgpt_academic.git
87
  cd chatgpt_academic
88
  ```
89
 
90
+ 2. 配置API_KEY和代理设置
91
 
92
  在`config.py`中,配置 海外Proxy 和 OpenAI API KEY,说明如下
93
  ```
94
  1. 如果你在国内,需要设置海外代理才能够顺利使用 OpenAI API,设置方法请仔细阅读config.py(1.修改其中的USE_PROXY为True; 2.按照说明修改其中的proxies)。
95
  2. 配置 OpenAI API KEY。你���要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。
96
+ 3. 支持任意数量的OpenAI的密钥和API2D的密钥共存/负载均衡,多个KEY用英文逗号分隔即可,例如输入 API_KEY="OpenAI密钥1,API2D密钥2,OpenAI密钥3,OpenAI密钥4"
97
  3. 与代理网络有关的issue(网络超时、代理不起作用)汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1
98
  ```
99
  (P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控,可以让您的隐私信息更加安全。)
100
 
101
 
102
+ 3. 安装依赖
103
  ```sh
104
  # (选择一)推荐
105
  python -m pip install -r requirements.txt
 
113
  # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
114
  ```
115
 
116
+ 如果需要支持清华ChatGLM,需要额外安装更多依赖(不熟悉python者、电脑配置不佳者,建议不要尝试):
117
+ ```sh
118
+ python -m pip install -r request_llm/requirements_chatglm.txt
119
+ ```
120
+
121
+ 4. 运行
122
  ```sh
123
  python main.py
124
  ```
125
 
126
+ 5. 测试函数插件
127
  ```
 
 
 
 
128
  - 测试Python项目分析
129
+ input区域 输入 `./crazy_functions/test_project/python/dqn` , 然后点击 "解析整个Python项目"
130
  - 测试自我代码解读
131
+ 点击 "[多线程Demo] 解析此项目本身(源码自译解)"
132
  - 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
133
+ 点击 "[函数插件模板Demo] 历史上的今天"
134
+ - 函数插件区下拉菜单中有更多功能可供选择
135
  ```
136
 
137
+ ## 安装-方法2:使用docker (Linux)
138
 
139
+ 1. 仅ChatGPT(推荐大多数人选择)
140
  ``` sh
141
  # 下载项目
142
  git clone https://github.com/binary-husky/chatgpt_academic.git
 
148
  # 运行
149
  docker run --rm -it --net=host gpt-academic
150
 
151
+ # 测试函数插件
152
+ ## 测试函数插件模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
153
+ 点击 "[函数插件模板Demo] 历史上的今天"
 
 
 
 
 
154
  ## 测试给Latex项目写摘要
155
+ input区域 输入 ./crazy_functions/test_project/latex/attention , 然后点击 "读Tex论文写摘要"
156
  ## 测试Python项目分析
157
+ input区域 输入 ./crazy_functions/test_project/python/dqn , 然后点击 "解析整个Python项目"
158
 
159
+ 函数插件区下拉菜单中有更多功能可供选择
160
  ```
161
 
162
+ 2. ChatGPT+ChatGLM(需要对docker非常熟悉 + 电脑配置足够强)
163
+
164
+ ``` sh
165
+ # 修改dockerfile
166
+ cd docs && nano Dockerfile+ChatGLM
167
+ # How to build | 如何构建 (Dockerfile+ChatGLM在docs路径下,请先cd docs)
168
+ docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
169
+ # How to run | 如何运行 (1) 直接运行:
170
+ docker run --rm -it --net=host --gpus=all gpt-academic
171
+ # How to run | 如何运行 (2) 我想运行之前进容器做一些调整:
172
+ docker run --rm -it --net=host --gpus=all gpt-academic bash
173
+ ```
174
+
175
+
176
+ ## 安装-方法3:其他部署方式
177
+
178
+ 1. 远程云服务器部署
179
+ 请访问[部署wiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
180
+
181
+ 2. 使用WSL2(Windows Subsystem for Linux 子系统)
182
+ 请访问[部署wiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
183
+
184
+
185
+ ## 安装-代理配置
186
+ 1. 常规方法
187
+ [配置代理](https://github.com/binary-husky/chatgpt_academic/issues/1)
188
+
189
+ 2. 纯新手教程
190
+ [纯新手教程](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
191
 
 
 
192
 
193
+ ---
 
194
 
195
  ## 自定义新的便捷按钮(学术快捷键自定义)
196
  任意文本编辑器打开`core_functional.py`,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。)
197
  例如
198
  ```
199
  "超级英译中": {
 
200
  # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等
201
  "Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n",
202
 
203
  # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。
204
  "Suffix": "",
 
205
  },
206
  ```
207
  <div align="center">
208
  <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
209
  </div>
210
 
211
+ ---
212
 
 
 
 
 
 
213
 
214
+ ## 部分功能展示
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
  ### 图片显示:
217
 
 
265
  </div>
266
 
267
  ## Todo 与 版本规划:
268
+ - version 3.2+ (todo): 函数插件支持更多参数接口
269
+ - version 3.1: 支持同时问询多个gpt模型!支持api2d,支持多个apikey负载均衡
270
+ - version 3.0: 对chatglm和其他小型llm的支持
271
  - version 2.6: 重构了插件结构,提高了交互性,加入更多插件
272
  - version 2.5: 自更新,解决总结大工程源代码时文本过长、token溢出的问题
273
  - version 2.4: (1)新增PDF全文翻译功能; (2)新增输入区切换位置的功能; (3)新增垂直布局选项; (4)多线程函数插件优化。
 
277
  - version 2.0: 引入模块化函数插件
278
  - version 1.0: 基础功能
279
 
280
+ chatgpt_academic开发者QQ群:734063350
281
 
282
+ ## 参考与学习
283
 
284
  ```
285
  代码中参考了很多其他优秀项目中的设计,主要包括:
286
 
287
+ # 借鉴项目1:借鉴了ChuanhuChatGPT中诸多技巧
288
  https://github.com/GaiZhenbiao/ChuanhuChatGPT
289
 
290
+ # 借鉴项目2:清华ChatGLM-6B
291
  https://github.com/THUDM/ChatGLM-6B
 
292
  ```
check_proxy.py CHANGED
@@ -103,7 +103,7 @@ def auto_update():
103
  import json
104
  proxies, = get_conf('proxies')
105
  response = requests.get(
106
- "https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=1)
107
  remote_json_data = json.loads(response.text)
108
  remote_version = remote_json_data['version']
109
  if remote_json_data["show_feature"]:
@@ -133,6 +133,13 @@ def auto_update():
133
  except:
134
  print('自动更新程序:已禁用')
135
 
 
 
 
 
 
 
 
136
 
137
  if __name__ == '__main__':
138
  import os
 
103
  import json
104
  proxies, = get_conf('proxies')
105
  response = requests.get(
106
+ "https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=5)
107
  remote_json_data = json.loads(response.text)
108
  remote_version = remote_json_data['version']
109
  if remote_json_data["show_feature"]:
 
133
  except:
134
  print('自动更新程序:已禁用')
135
 
136
+ def warm_up_modules():
137
+ print('正在执行一些模块的预热...')
138
+ from request_llm.bridge_all import model_info
139
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
140
+ enc.encode("模块预热", disallowed_special=())
141
+ enc = model_info["gpt-4"]['tokenizer']
142
+ enc.encode("模块预热", disallowed_special=())
143
 
144
  if __name__ == '__main__':
145
  import os
config.py CHANGED
@@ -1,5 +1,5 @@
1
  # [step 1]>> 例如: API_KEY = "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" (此key无效)
2
- API_KEY = "sk-此处填API密钥"
3
 
4
  # [step 2]>> 改为True应用代理,如果直接在海外服务器部署,此处不修改
5
  USE_PROXY = False
@@ -19,13 +19,12 @@ if USE_PROXY:
19
  else:
20
  proxies = None
21
 
22
- # 多线程函数插件中,默认允许多少路线程同时访问OpenAI。
23
- # Free trial users的限制是每分钟3次,Pay-as-you-go users的限制是每分钟3500次。提高限制请查询:
24
- # https://platform.openai.com/docs/guides/rate-limits/overview
25
  DEFAULT_WORKER_NUM = 3
26
 
27
 
28
- # [step 3]>> 以下配置可以优化体验,但大部分场合下并不需要修改
29
  # 对话窗的高度
30
  CHATBOT_HEIGHT = 1115
31
 
@@ -44,15 +43,16 @@ WEB_PORT = -1
44
  # 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
45
  MAX_RETRY = 2
46
 
47
- # OpenAI模型选择是(gpt4现在只对申请成功的人开放)
48
- LLM_MODEL = "gpt-3.5-turbo"
 
49
 
50
- # OpenAI的API_URL
51
- API_URL = "https://api.openai.com/v1/chat/completions"
52
 
53
- # 设置并行使用的线程数
54
  CONCURRENT_COUNT = 100
55
 
56
- # 设置用户名和密码(相关功能不稳定,与gradio版本和网络都相关,如果本地使用不建议加这个)
57
  # [("username", "password"), ("username2", "password2"), ...]
58
  AUTHENTICATION = []
 
1
  # [step 1]>> 例如: API_KEY = "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" (此key无效)
2
+ API_KEY = "sk-此处填API密钥" # 可同时填写多个API-KEY,用英文逗号分割,例如API_KEY = "sk-openaikey1,sk-openaikey2,fkxxxx-api2dkey1,fkxxxx-api2dkey2"
3
 
4
  # [step 2]>> 改为True应用代理,如果直接在海外服务器部署,此处不修改
5
  USE_PROXY = False
 
19
  else:
20
  proxies = None
21
 
22
+ # [step 3]>> 多线程函数插件中,默认允许多少路线程同时访问OpenAI。Free trial users的限制是每分钟3次,Pay-as-you-go users的限制是每分钟3500次
23
+ # 一言以蔽之:免费用户填3,OpenAI绑了信用卡的用户可以填 16 或者更高。提高限制请查询:https://platform.openai.com/docs/guides/rate-limits/overview
 
24
  DEFAULT_WORKER_NUM = 3
25
 
26
 
27
+ # [step 4]>> 以下配置可以优化体验,但大部分场合下并不需要修改
28
  # 对话窗的高度
29
  CHATBOT_HEIGHT = 1115
30
 
 
43
  # 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
44
  MAX_RETRY = 2
45
 
46
+ # OpenAI模型选择是(gpt4现在只对申请成功的人开放,体验gpt-4可以试试api2d)
47
+ LLM_MODEL = "gpt-3.5-turbo" # 可选 ↓↓↓
48
+ AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "api2d-gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "chatglm"]
49
 
50
+ # 本地LLM模型如ChatGLM的执行方式 CPU/GPU
51
+ LOCAL_MODEL_DEVICE = "cpu" # 可选 "cuda"
52
 
53
+ # 设置gradio的并行线程数(不需要修改)
54
  CONCURRENT_COUNT = 100
55
 
56
+ # 设置用户名和密码(不需要修改)(相关功能不稳定,与gradio版本和网络都相关,如果本地使用不建议加这个)
57
  # [("username", "password"), ("username2", "password2"), ...]
58
  AUTHENTICATION = []
crazy_functional.py CHANGED
@@ -3,7 +3,6 @@ from toolbox import HotReload # HotReload 的意思是热更新,修改函数
3
 
4
  def get_crazy_functions():
5
  ###################### 第一组插件 ###########################
6
- # [第一组插件]: 最早期编写的项目插件和一些demo
7
  from crazy_functions.读文章写摘要 import 读文章写摘要
8
  from crazy_functions.生成函数注释 import 批量生成函数注释
9
  from crazy_functions.解析项目源代码 import 解析项目本身
@@ -16,16 +15,23 @@ def get_crazy_functions():
16
  from crazy_functions.高级功能函数模板 import 高阶功能模板函数
17
  from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文
18
  from crazy_functions.Latex全文润色 import Latex英文润色
 
19
  from crazy_functions.解析项目源代码 import 解析一个Lua项目
20
  from crazy_functions.解析项目源代码 import 解析一个CSharp项目
 
21
  function_plugins = {
22
 
23
  "解析整个Python项目": {
24
  "Color": "stop", # 按钮颜色
25
  "Function": HotReload(解析一个Python项目)
26
  },
 
 
 
 
27
  "解析整个C++项目头文件": {
28
  "Color": "stop", # 按钮颜色
 
29
  "Function": HotReload(解析一个C项目的头文件)
30
  },
31
  "解析整个C++项目(.cpp/.hpp/.c/.h)": {
@@ -81,10 +87,9 @@ def get_crazy_functions():
81
 
82
  }
83
  ###################### 第二组插件 ###########################
84
- # [第二组插件]: 经过充分测试,但功能上距离达到完美状态还差一点点
85
  from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
86
  from crazy_functions.批量总结PDF文档pdfminer import 批量总结PDF文档pdfminer
87
- from crazy_functions.总结word文档 import 总结word文档
88
  from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
89
  from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
90
  from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入
@@ -100,6 +105,10 @@ def get_crazy_functions():
100
  "AsButton": True, # 加入下拉菜单中
101
  "Function": HotReload(批量翻译PDF文档)
102
  },
 
 
 
 
103
  "[测试功能] 批量总结PDF文档": {
104
  "Color": "stop",
105
  "AsButton": False, # 加入下拉菜单中
@@ -116,10 +125,7 @@ def get_crazy_functions():
116
  "AsButton": False, # 加入下拉菜单中
117
  "Function": HotReload(谷歌检索小助手)
118
  },
119
- "批量总结Word文档": {
120
- "Color": "stop",
121
- "Function": HotReload(总结word文档)
122
- },
123
  "理解PDF文档内容 (模仿ChatPDF)": {
124
  # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
125
  "Color": "stop",
 
3
 
4
  def get_crazy_functions():
5
  ###################### 第一组插件 ###########################
 
6
  from crazy_functions.读文章写摘要 import 读文章写摘要
7
  from crazy_functions.生成函数注释 import 批量生成函数注释
8
  from crazy_functions.解析项目源代码 import 解析项目本身
 
15
  from crazy_functions.高级功能函数模板 import 高阶功能模板函数
16
  from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文
17
  from crazy_functions.Latex全文润色 import Latex英文润色
18
+ from crazy_functions.询问多个大语言模型 import 同时问询
19
  from crazy_functions.解析项目源代码 import 解析一个Lua项目
20
  from crazy_functions.解析项目源代码 import 解析一个CSharp项目
21
+ from crazy_functions.总结word文档 import 总结word文档
22
  function_plugins = {
23
 
24
  "解析整个Python项目": {
25
  "Color": "stop", # 按钮颜色
26
  "Function": HotReload(解析一个Python项目)
27
  },
28
+ "批量总结Word文档": {
29
+ "Color": "stop",
30
+ "Function": HotReload(总结word文档)
31
+ },
32
  "解析整个C++项目头文件": {
33
  "Color": "stop", # 按钮颜色
34
+ "AsButton": False, # 加入下拉菜单中
35
  "Function": HotReload(解析一个C项目的头文件)
36
  },
37
  "解析整个C++项目(.cpp/.hpp/.c/.h)": {
 
87
 
88
  }
89
  ###################### 第二组插件 ###########################
90
+ # [第二组插件]: 经过充分测试
91
  from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
92
  from crazy_functions.批量总结PDF文档pdfminer import 批量总结PDF文档pdfminer
 
93
  from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
94
  from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
95
  from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入
 
105
  "AsButton": True, # 加入下拉菜单中
106
  "Function": HotReload(批量翻译PDF文档)
107
  },
108
+ "询问多个GPT模型": {
109
+ "Color": "stop", # 按钮颜色
110
+ "Function": HotReload(同时问询)
111
+ },
112
  "[测试功能] 批量总结PDF文档": {
113
  "Color": "stop",
114
  "AsButton": False, # 加入下拉菜单中
 
125
  "AsButton": False, # 加入下拉菜单中
126
  "Function": HotReload(谷歌检索小助手)
127
  },
128
+
 
 
 
129
  "理解PDF文档内容 (模仿ChatPDF)": {
130
  # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
131
  "Color": "stop",
crazy_functions/Latex全文润色.py CHANGED
@@ -11,9 +11,8 @@ class PaperFileGroup():
11
  self.sp_file_tag = []
12
 
13
  # count_token
14
- import tiktoken
15
- from toolbox import get_conf
16
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
17
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
18
  self.get_token_num = get_token_num
19
 
 
11
  self.sp_file_tag = []
12
 
13
  # count_token
14
+ from request_llm.bridge_all import model_info
15
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
 
16
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
17
  self.get_token_num = get_token_num
18
 
crazy_functions/Latex全文翻译.py CHANGED
@@ -11,9 +11,8 @@ class PaperFileGroup():
11
  self.sp_file_tag = []
12
 
13
  # count_token
14
- import tiktoken
15
- from toolbox import get_conf
16
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
17
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
18
  self.get_token_num = get_token_num
19
 
 
11
  self.sp_file_tag = []
12
 
13
  # count_token
14
+ from request_llm.bridge_all import model_info
15
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
 
16
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
17
  self.get_token_num = get_token_num
18
 
crazy_functions/crazy_functions_test.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 这是什么?
3
+ 这个文件用于函数插件的单元测试
4
+ 运行方法 python crazy_functions/crazy_functions_test.py
5
+ """
6
+
7
+ def validate_path():
8
+ import os, sys
9
+ dir_name = os.path.dirname(__file__)
10
+ root_dir_assume = os.path.abspath(os.path.dirname(__file__) + '/..')
11
+ os.chdir(root_dir_assume)
12
+ sys.path.append(root_dir_assume)
13
+
14
+ validate_path() # validate path so you can run from base directory
15
+
16
+ from toolbox import get_conf, ChatBotWithCookies
17
+ proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \
18
+ get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY')
19
+
20
+ llm_kwargs = {
21
+ 'api_key': API_KEY,
22
+ 'llm_model': LLM_MODEL,
23
+ 'top_p':1.0,
24
+ 'max_length': None,
25
+ 'temperature':1.0,
26
+ }
27
+ plugin_kwargs = { }
28
+ chatbot = ChatBotWithCookies(llm_kwargs)
29
+ history = []
30
+ system_prompt = "Serve me as a writing and programming assistant."
31
+ web_port = 1024
32
+
33
+
34
+ def test_解析一个Python项目():
35
+ from crazy_functions.解析项目源代码 import 解析一个Python项目
36
+ txt = "crazy_functions/test_project/python/dqn"
37
+ for cookies, cb, hist, msg in 解析一个Python项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
38
+ print(cb)
39
+
40
+ def test_解析一个Cpp项目():
41
+ from crazy_functions.解析项目源代码 import 解析一个C项目
42
+ txt = "crazy_functions/test_project/cpp/cppipc"
43
+ for cookies, cb, hist, msg in 解析一个C项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
44
+ print(cb)
45
+
46
+ def test_Latex英文润色():
47
+ from crazy_functions.Latex全文润色 import Latex英文润色
48
+ txt = "crazy_functions/test_project/latex/attention"
49
+ for cookies, cb, hist, msg in Latex英文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
50
+ print(cb)
51
+
52
+ def test_Markdown中译英():
53
+ from crazy_functions.批量Markdown翻译 import Markdown中译英
54
+ txt = "README.md"
55
+ for cookies, cb, hist, msg in Markdown中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
56
+ print(cb)
57
+
58
+ def test_批量翻译PDF文档():
59
+ from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
60
+ txt = "crazy_functions/test_project/pdf_and_word"
61
+ for cookies, cb, hist, msg in 批量翻译PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
62
+ print(cb)
63
+
64
+ def test_谷歌检索小助手():
65
+ from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
66
+ txt = "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=auto+reinforcement+learning&btnG="
67
+ for cookies, cb, hist, msg in 谷歌检索小助手(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
68
+ print(cb)
69
+
70
+ def test_总结word文档():
71
+ from crazy_functions.总结word文档 import 总结word文档
72
+ txt = "crazy_functions/test_project/pdf_and_word"
73
+ for cookies, cb, hist, msg in 总结word文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
74
+ print(cb)
75
+
76
+ def test_下载arxiv论文并翻译摘要():
77
+ from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要
78
+ txt = "1812.10695"
79
+ for cookies, cb, hist, msg in 下载arxiv论文并翻译摘要(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
80
+ print(cb)
81
+
82
+ test_解析一个Python项目()
83
+ test_Latex英文润色()
84
+ test_Markdown中译英()
85
+ test_批量翻译PDF文档()
86
+ test_谷歌检索小助手()
87
+ test_总结word文档()
88
+ test_下载arxiv论文并翻译摘要()
89
+ test_解析一个Cpp项目()
90
+
91
+ input("程序完成,回车退出。")
92
+ print("退出。")
crazy_functions/crazy_utils.py CHANGED
@@ -2,9 +2,9 @@ import traceback
2
  from toolbox import update_ui, get_conf
3
 
4
  def input_clipping(inputs, history, max_token_limit):
5
- import tiktoken
6
  import numpy as np
7
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
 
8
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
9
 
10
  mode = 'input-and-history'
@@ -61,12 +61,12 @@ def request_gpt_model_in_new_thread_with_ui_alive(
61
  """
62
  import time
63
  from concurrent.futures import ThreadPoolExecutor
64
- from request_llm.bridge_chatgpt import predict_no_ui_long_connection
65
  # 用户反馈
66
  chatbot.append([inputs_show_user, ""])
67
  yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
68
  executor = ThreadPoolExecutor(max_workers=16)
69
- mutable = ["", time.time()]
70
  def _req_gpt(inputs, history, sys_prompt):
71
  retry_op = retry_times_at_unknown_error
72
  exceeded_cnt = 0
@@ -105,7 +105,7 @@ def request_gpt_model_in_new_thread_with_ui_alive(
105
  if retry_op > 0:
106
  retry_op -= 1
107
  mutable[0] += f"[Local Message] 重试中,请稍等 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}:\n\n"
108
- if "Rate limit reached" in tb_str:
109
  time.sleep(30)
110
  time.sleep(5)
111
  continue # 返回重试
@@ -167,13 +167,17 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
167
  """
168
  import time, random
169
  from concurrent.futures import ThreadPoolExecutor
170
- from request_llm.bridge_chatgpt import predict_no_ui_long_connection
171
  assert len(inputs_array) == len(history_array)
172
  assert len(inputs_array) == len(sys_prompt_array)
173
  if max_workers == -1: # 读取配置文件
174
  try: max_workers, = get_conf('DEFAULT_WORKER_NUM')
175
  except: max_workers = 8
176
  if max_workers <= 0 or max_workers >= 20: max_workers = 8
 
 
 
 
177
  executor = ThreadPoolExecutor(max_workers=max_workers)
178
  n_frag = len(inputs_array)
179
  # 用户反馈
@@ -230,9 +234,9 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
230
  if retry_op > 0:
231
  retry_op -= 1
232
  wait = random.randint(5, 20)
233
- if "Rate limit reached" in tb_str:
234
  wait = wait * 3
235
- fail_info = "OpenAI请求速率限制 "
236
  else:
237
  fail_info = ""
238
  # 也许等待十几秒后,情况会好转
 
2
  from toolbox import update_ui, get_conf
3
 
4
  def input_clipping(inputs, history, max_token_limit):
 
5
  import numpy as np
6
+ from request_llm.bridge_all import model_info
7
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
8
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
9
 
10
  mode = 'input-and-history'
 
61
  """
62
  import time
63
  from concurrent.futures import ThreadPoolExecutor
64
+ from request_llm.bridge_all import predict_no_ui_long_connection
65
  # 用户反馈
66
  chatbot.append([inputs_show_user, ""])
67
  yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
68
  executor = ThreadPoolExecutor(max_workers=16)
69
+ mutable = ["", time.time(), ""]
70
  def _req_gpt(inputs, history, sys_prompt):
71
  retry_op = retry_times_at_unknown_error
72
  exceeded_cnt = 0
 
105
  if retry_op > 0:
106
  retry_op -= 1
107
  mutable[0] += f"[Local Message] 重试中,请稍等 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}:\n\n"
108
+ if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str):
109
  time.sleep(30)
110
  time.sleep(5)
111
  continue # 返回重试
 
167
  """
168
  import time, random
169
  from concurrent.futures import ThreadPoolExecutor
170
+ from request_llm.bridge_all import predict_no_ui_long_connection
171
  assert len(inputs_array) == len(history_array)
172
  assert len(inputs_array) == len(sys_prompt_array)
173
  if max_workers == -1: # 读取配置文件
174
  try: max_workers, = get_conf('DEFAULT_WORKER_NUM')
175
  except: max_workers = 8
176
  if max_workers <= 0 or max_workers >= 20: max_workers = 8
177
+ # 屏蔽掉 chatglm的多线程,可能会导致严重卡顿
178
+ if not (llm_kwargs['llm_model'].startswith('gpt-') or llm_kwargs['llm_model'].startswith('api2d-')):
179
+ max_workers = 1
180
+
181
  executor = ThreadPoolExecutor(max_workers=max_workers)
182
  n_frag = len(inputs_array)
183
  # 用户反馈
 
234
  if retry_op > 0:
235
  retry_op -= 1
236
  wait = random.randint(5, 20)
237
+ if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str):
238
  wait = wait * 3
239
+ fail_info = "OpenAI绑定信用卡可解除频率限制 "
240
  else:
241
  fail_info = ""
242
  # 也许等待十几秒后,情况会好转
crazy_functions/代码重写为全英文_多线程.py CHANGED
@@ -1,5 +1,5 @@
1
  import threading
2
- from request_llm.bridge_chatgpt import predict_no_ui_long_connection
3
  from toolbox import update_ui
4
  from toolbox import CatchException, write_results_to_file, report_execption
5
  from .crazy_utils import breakdown_txt_to_satisfy_token_limit
@@ -59,9 +59,8 @@ def 全项目切换英文(txt, llm_kwargs, plugin_kwargs, chatbot, history, sys_
59
 
60
  # 第5步:Token限制下的截断与处理
61
  MAX_TOKEN = 3000
62
- import tiktoken
63
- from toolbox import get_conf
64
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
65
  def get_token_fn(txt): return len(enc.encode(txt, disallowed_special=()))
66
 
67
 
 
1
  import threading
2
+ from request_llm.bridge_all import predict_no_ui_long_connection
3
  from toolbox import update_ui
4
  from toolbox import CatchException, write_results_to_file, report_execption
5
  from .crazy_utils import breakdown_txt_to_satisfy_token_limit
 
59
 
60
  # 第5步:Token限制下的截断与处理
61
  MAX_TOKEN = 3000
62
+ from request_llm.bridge_all import model_info
63
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
 
64
  def get_token_fn(txt): return len(enc.encode(txt, disallowed_special=()))
65
 
66
 
crazy_functions/总结word文档.py CHANGED
@@ -8,8 +8,6 @@ def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot
8
  import time, os
9
  # pip install python-docx 用于docx格式,跨平台
10
  # pip install pywin32 用于doc格式,仅支持Win平台
11
-
12
- print('begin analysis on:', file_manifest)
13
  for index, fp in enumerate(file_manifest):
14
  if fp.split(".")[-1] == "docx":
15
  from docx import Document
@@ -29,18 +27,20 @@ def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot
29
  word.Quit()
30
 
31
  print(file_content)
32
-
33
- prefix = "接下来请你逐文件分析下面的论文文件," if index == 0 else ""
34
  # private_upload里面的文件名在解压zip后容易出现乱码(rar和7z格式正常),故可以只分析文章内容,不输入文件名
35
- i_say = prefix + f'请对下面的文章片段用中英文做概述,文件名是{os.path.relpath(fp, project_folder)},' \
36
- f'文章内容是 ```{file_content}```'
37
- i_say_show_user = prefix + f'[{index+1}/{len(file_manifest)}] 假设你是论文审稿专家,请对下面的文章片段做概述: {os.path.abspath(fp)}'
38
- chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
39
- yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
40
-
41
- if not fast_debug:
42
- msg = '正常'
43
- # ** gpt request **
 
 
 
 
44
  gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
45
  inputs=i_say,
46
  inputs_show_user=i_say_show_user,
@@ -48,46 +48,34 @@ def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot
48
  chatbot=chatbot,
49
  history=[],
50
  sys_prompt="总结文章。"
51
- ) # 带超时倒计时
 
52
  chatbot[-1] = (i_say_show_user, gpt_say)
53
- history.append(i_say_show_user)
54
- history.append(gpt_say)
55
- yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
56
- if not fast_debug: time.sleep(2)
57
-
58
- """
59
- # 可按需启用
60
- i_say = f'根据你上述的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一篇英文的。'
61
- chatbot.append((i_say, "[Local Message] waiting gpt response."))
62
- yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- i_say = f'我想让你做一个论文写作导师。您的任务是使用人工智能工具(例如自然语言处理)提供有关如何改进其上述文章的反馈。' \
66
- f'您还应该利用您在有效写作技巧方面的修辞知识和经验来建议作者可以更好地以书面形式表达他们的想法和想法的方法。' \
67
- f'根据你之前的分析,提出建议'
68
- chatbot.append((i_say, "[Local Message] waiting gpt response."))
69
- yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
70
-
71
- """
72
-
73
- if not fast_debug:
74
- msg = '正常'
75
- # ** gpt request **
76
- gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
77
- inputs=i_say,
78
- inputs_show_user=i_say,
79
- llm_kwargs=llm_kwargs,
80
- chatbot=chatbot,
81
- history=history,
82
- sys_prompt="总结文章。"
83
- ) # 带超时倒计时
84
- chatbot[-1] = (i_say, gpt_say)
85
- history.append(i_say)
86
- history.append(gpt_say)
87
- yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
88
  res = write_results_to_file(history)
89
  chatbot.append(("完成了吗?", res))
90
- yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
 
 
 
 
91
 
92
 
93
  @CatchException
@@ -123,11 +111,11 @@ def 总结word文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_pr
123
  return
124
 
125
  # 搜索需要处理的文件清单
126
- file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.docx', recursive=True)] + \
127
- [f for f in glob.glob(f'{project_folder}/**/*.doc', recursive=True)]
128
- # [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \
129
- # [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
130
- # [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
131
 
132
  # 如果没找到任何文件
133
  if len(file_manifest) == 0:
 
8
  import time, os
9
  # pip install python-docx 用于docx格式,跨平台
10
  # pip install pywin32 用于doc格式,仅支持Win平台
 
 
11
  for index, fp in enumerate(file_manifest):
12
  if fp.split(".")[-1] == "docx":
13
  from docx import Document
 
27
  word.Quit()
28
 
29
  print(file_content)
 
 
30
  # private_upload里面的文件名在解压zip后容易出现乱码(rar和7z格式正常),故可以只分析文章内容,不输入文件名
31
+ from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
32
+ from request_llm.bridge_all import model_info
33
+ max_token = model_info[llm_kwargs['llm_model']]['max_token']
34
+ TOKEN_LIMIT_PER_FRAGMENT = max_token * 3 // 4
35
+ paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
36
+ txt=file_content,
37
+ get_token_fn=model_info[llm_kwargs['llm_model']]['token_cnt'],
38
+ limit=TOKEN_LIMIT_PER_FRAGMENT
39
+ )
40
+ this_paper_history = []
41
+ for i, paper_frag in enumerate(paper_fragments):
42
+ i_say = f'请对下面的文章片段用中文做概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{paper_frag}```'
43
+ i_say_show_user = f'请对下面的文章片段做概述: {os.path.abspath(fp)}的第{i+1}/{len(paper_fragments)}个片段。'
44
  gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
45
  inputs=i_say,
46
  inputs_show_user=i_say_show_user,
 
48
  chatbot=chatbot,
49
  history=[],
50
  sys_prompt="总结文章。"
51
+ )
52
+
53
  chatbot[-1] = (i_say_show_user, gpt_say)
54
+ history.extend([i_say_show_user,gpt_say])
55
+ this_paper_history.extend([i_say_show_user,gpt_say])
 
 
 
 
 
 
 
 
56
 
57
+ # 已经对该文章的所有片段总结完毕,如果文章被切分了,
58
+ if len(paper_fragments) > 1:
59
+ i_say = f"根据以上的对话,总结文章{os.path.abspath(fp)}的主要内容。"
60
+ gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
61
+ inputs=i_say,
62
+ inputs_show_user=i_say,
63
+ llm_kwargs=llm_kwargs,
64
+ chatbot=chatbot,
65
+ history=this_paper_history,
66
+ sys_prompt="总结文章。"
67
+ )
68
+
69
+ history.extend([i_say,gpt_say])
70
+ this_paper_history.extend([i_say,gpt_say])
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  res = write_results_to_file(history)
73
  chatbot.append(("完成了吗?", res))
74
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
75
+
76
+ res = write_results_to_file(history)
77
+ chatbot.append(("所有文件都总结完成了吗?", res))
78
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
79
 
80
 
81
  @CatchException
 
111
  return
112
 
113
  # 搜索需要处理的文件清单
114
+ if txt.endswith('.docx') or txt.endswith('.doc'):
115
+ file_manifest = [txt]
116
+ else:
117
+ file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.docx', recursive=True)] + \
118
+ [f for f in glob.glob(f'{project_folder}/**/*.doc', recursive=True)]
119
 
120
  # 如果没找到任何文件
121
  if len(file_manifest) == 0:
crazy_functions/批量Markdown翻译.py CHANGED
@@ -11,9 +11,8 @@ class PaperFileGroup():
11
  self.sp_file_tag = []
12
 
13
  # count_token
14
- import tiktoken
15
- from toolbox import get_conf
16
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
17
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
18
  self.get_token_num = get_token_num
19
 
@@ -51,7 +50,7 @@ def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, ch
51
  pfg.file_contents.append(file_content)
52
 
53
  # <-------- 拆分过长的Markdown文件 ---------->
54
- pfg.run_file_split(max_token_limit=2048)
55
  n_split = len(pfg.sp_file_contents)
56
 
57
  # <-------- 多线程润色开始 ---------->
 
11
  self.sp_file_tag = []
12
 
13
  # count_token
14
+ from request_llm.bridge_all import model_info
15
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
 
16
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
17
  self.get_token_num = get_token_num
18
 
 
50
  pfg.file_contents.append(file_content)
51
 
52
  # <-------- 拆分过长的Markdown文件 ---------->
53
+ pfg.run_file_split(max_token_limit=1500)
54
  n_split = len(pfg.sp_file_contents)
55
 
56
  # <-------- 多线程润色开始 ---------->
crazy_functions/批量翻译PDF文档_多线程.py CHANGED
@@ -68,8 +68,8 @@ def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot,
68
 
69
  # 递归地切割PDF文件
70
  from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
71
- from toolbox import get_conf
72
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
73
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
74
  paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
75
  txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
 
68
 
69
  # 递归地切割PDF文件
70
  from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
71
+ from request_llm.bridge_all import model_info
72
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
73
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
74
  paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
75
  txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
crazy_functions/理解PDF文档内容.py CHANGED
@@ -17,8 +17,8 @@ def 解析PDF(file_name, llm_kwargs, plugin_kwargs, chatbot, history, system_pro
17
  TOKEN_LIMIT_PER_FRAGMENT = 2500
18
 
19
  from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
20
- from toolbox import get_conf
21
- enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
22
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
23
  paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
24
  txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
 
17
  TOKEN_LIMIT_PER_FRAGMENT = 2500
18
 
19
  from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
20
+ from request_llm.bridge_all import model_info
21
+ enc = model_info["gpt-3.5-turbo"]['tokenizer']
22
  def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
23
  paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
24
  txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
crazy_functions/解析项目源代码.py CHANGED
@@ -12,7 +12,7 @@ def 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs,
12
  sys_prompt_array = []
13
  report_part_1 = []
14
 
15
- assert len(file_manifest) <= 1024, "源文件太多(超过1024个), 请缩减输入文件的数量。或者,您也可以选择删除此行警告,并修改代码拆分file_manifest列表,从而实现分批次处理。"
16
  ############################## <第一步,逐个文件分析,多线程> ##################################
17
  for index, fp in enumerate(file_manifest):
18
  # 读取文件
 
12
  sys_prompt_array = []
13
  report_part_1 = []
14
 
15
+ assert len(file_manifest) <= 512, "源文件太多(超过512个), 请缩减输入文件的数量。或者,您也可以选择删除此行警告,并修改代码拆分file_manifest列表,从而实现分批次处理。"
16
  ############################## <第一步,逐个文件分析,多线程> ##################################
17
  for index, fp in enumerate(file_manifest):
18
  # 读取文件
crazy_functions/询问多个大语言模型.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from toolbox import CatchException, update_ui
2
+ from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
3
+ import datetime
4
+ @CatchException
5
+ def 同时问询(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
6
+ """
7
+ txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径
8
+ llm_kwargs gpt模型参数,如温度和top_p等,一般原样传递下去就行
9
+ plugin_kwargs 插件模型的参数,如温度和top_p等,一般原样传递下去就行
10
+ chatbot 聊天显示框的句柄,用于显示给用户
11
+ history 聊天历史,前情提要
12
+ system_prompt 给gpt的静默提醒
13
+ web_port 当前软件运行的端口号
14
+ """
15
+ history = [] # 清空历史,以免输入溢出
16
+ chatbot.append((txt, "正在同时咨询ChatGPT和ChatGLM……"))
17
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新
18
+
19
+ # llm_kwargs['llm_model'] = 'chatglm&gpt-3.5-turbo&api2d-gpt-3.5-turbo' # 支持任意数量的llm接口,用&符号分隔
20
+ llm_kwargs['llm_model'] = 'chatglm&gpt-3.5-turbo' # 支持任意数量的llm接口,用&符号分隔
21
+ gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
22
+ inputs=txt, inputs_show_user=txt,
23
+ llm_kwargs=llm_kwargs, chatbot=chatbot, history=history,
24
+ sys_prompt=system_prompt,
25
+ retry_times_at_unknown_error=0
26
+ )
27
+
28
+ history.append(txt)
29
+ history.append(gpt_say)
30
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新
docs/Dockerfile+ChatGLM ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to build | 如何构建: docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
2
+ # How to run | 如何运行 (1) 直接运行(选择0号GPU): docker run --rm -it --net=host --gpus="0" gpt-academic
3
+ # How to run | 如何运行 (2) 我想运行之前进容器做一些调整: docker run --rm -it --net=host --gpus="0" gpt-academic bash
4
+
5
+ # 从NVIDIA源,从而支持显卡运损(检查宿主的nvidia-smi中的cuda版本必须>=11.3)
6
+ FROM nvidia/cuda:11.3.1-runtime-ubuntu20.04
7
+ ARG useProxyNetwork=''
8
+ RUN apt-get update
9
+ RUN apt-get install -y curl proxychains curl
10
+ RUN apt-get install -y git python python3 python-dev python3-dev --fix-missing
11
+
12
+ # 配置代理网络(构建Docker镜像时使用)
13
+ # # comment out below if you do not need proxy network | 如果不需要翻墙 - 从此行向下删除
14
+ RUN $useProxyNetwork curl cip.cc
15
+ RUN sed -i '$ d' /etc/proxychains.conf
16
+ RUN sed -i '$ d' /etc/proxychains.conf
17
+ RUN echo "socks5 127.0.0.1 10880" >> /etc/proxychains.conf
18
+ ARG useProxyNetwork=proxychains
19
+ # # comment out above if you do not need proxy network | 如果不需要翻墙 - 从此行向上删除
20
+
21
+
22
+ # use python3 as the system default python
23
+ RUN curl -sS https://bootstrap.pypa.io/get-pip.py | python3.8
24
+
25
+ # 下载分支
26
+ WORKDIR /gpt
27
+ RUN $useProxyNetwork git clone https://github.com/binary-husky/chatgpt_academic.git
28
+ WORKDIR /gpt/chatgpt_academic
29
+ RUN $useProxyNetwork python3 -m pip install -r requirements.txt
30
+ RUN $useProxyNetwork python3 -m pip install -r request_llm/requirements_chatglm.txt
31
+ RUN $useProxyNetwork python3 -m pip install torch --extra-index-url https://download.pytorch.org/whl/cu113
32
+
33
+ # 预热CHATGLM参数(非必要 可选步骤)
34
+ RUN echo ' \n\
35
+ from transformers import AutoModel, AutoTokenizer \n\
36
+ chatglm_tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) \n\
37
+ chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float() ' >> warm_up_chatglm.py
38
+ RUN python3 -u warm_up_chatglm.py
39
+
40
+ # 禁用缓存,确保更新代码
41
+ ADD "https://www.random.org/cgi-bin/randbyte?nbytes=10&format=h" skipcache
42
+ RUN $useProxyNetwork git pull
43
+
44
+ # 预热Tiktoken模块
45
+ RUN python3 -c 'from check_proxy import warm_up_modules; warm_up_modules()'
46
+
47
+ # 为chatgpt-academic配置代理和API-KEY (非必要 可选步骤)
48
+ # 可同时填写多个API-KEY,支持openai的key和api2d的key共存,用英文逗号分割,例如API_KEY = "sk-openaikey1,fkxxxx-api2dkey2,........"
49
+ # LLM_MODEL 是选择初始的模型
50
+ # LOCAL_MODEL_DEVICE 是选择chatglm等本地模型运行的设备,可选 cpu 和 cuda
51
+ RUN echo ' \n\
52
+ API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,fkxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \n\
53
+ USE_PROXY = True \n\
54
+ LLM_MODEL = "chatglm" \n\
55
+ LOCAL_MODEL_DEVICE = "cuda" \n\
56
+ proxies = { "http": "socks5h://localhost:10880", "https": "socks5h://localhost:10880", } ' >> config_private.py
57
+
58
+ # 启动
59
+ CMD ["python3", "-u", "main.py"]
docs/README_EN.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > **Note**
2
+ >
3
+ > This English README is automatically generated by the markdown translation plugin in this project, and may not be 100% correct.
4
+ >
5
+
6
+ # <img src="logo.png" width="40" > ChatGPT Academic Optimization
7
+
8
+ **If you like this project, please give it a Star. If you've come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request. We also have a [README in English](docs/README_EN.md) translated by this project itself.**
9
+
10
+ > **Note**
11
+ >
12
+ > 1. Please note that only **functions with red color** supports reading files, some functions are located in the **dropdown menu** of plugins. Additionally, we welcome and prioritize any new plugin PRs with **highest priority**!
13
+ >
14
+ > 2. The functionality of each file in this project is detailed in the self-translation report [`self_analysis.md`](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) of the project. With the iteration of the version, you can also click on the relevant function plugins at any time to call GPT to regenerate the self-analysis report of the project. The FAQ summary is in the [`wiki`](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) section.
15
+ >
16
+
17
+
18
+ <div align="center">
19
+
20
+ Function | Description
21
+ --- | ---
22
+ One-Click Polish | Supports one-click polishing and finding grammar errors in academic papers.
23
+ One-Key Translation Between Chinese and English | One-click translation between Chinese and English.
24
+ One-Key Code Interpretation | Can correctly display and interpret code.
25
+ [Custom Shortcut Keys](https://www.bilibili.com/video/BV14s4y1E7jN) | Supports custom shortcut keys.
26
+ [Configure Proxy Server](https://www.bilibili.com/video/BV1rc411W7Dr) | Supports configuring proxy servers.
27
+ Modular Design | Supports custom high-order function plugins and [function plugins], and plugins support [hot updates](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97).
28
+ [Self-programming Analysis](https://www.bilibili.com/video/BV1cj411A7VW) | [Function Plugin] [One-Key Read] (https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) The source code of this project is analyzed.
29
+ [Program Analysis](https://www.bilibili.com/video/BV1cj411A7VW) | [Function Plugin] One-click can analyze the project tree of other Python/C/C++/Java/Lua/... projects
30
+ Read the Paper | [Function Plugin] One-click interpretation of the full text of latex paper and generation of abstracts
31
+ Latex Full Text Translation, Proofreading | [Function Plugin] One-click translation or proofreading of latex papers.
32
+ Batch Comment Generation | [Function Plugin] One-click batch generation of function comments
33
+ Chat Analysis Report Generation | [Function Plugin] After running, an automatic summary report will be generated
34
+ [Arxiv Assistant](https://www.bilibili.com/video/BV1LM4y1279X) | [Function Plugin] Enter the arxiv article url to translate the abstract and download the PDF with one click
35
+ [Full-text Translation Function of PDF Paper](https://www.bilibili.com/video/BV1KT411x7Wn) | [Function Plugin] Extract the title & abstract of the PDF paper + translate the full text (multithreading)
36
+ [Google Scholar Integration Assistant](https://www.bilibili.com/video/BV19L411U7ia) | [Function Plugin] Given any Google Scholar search page URL, let gpt help you choose interesting articles.
37
+ Formula / Picture / Table Display | Can display both the tex form and the rendering form of formulas at the same time, support formula and code highlighting
38
+ Multithreaded Function Plugin Support | Supports multi-threaded calling chatgpt, one-click processing of massive text or programs
39
+ Start Dark Gradio [Theme](https://github.com/binary-husky/chatgpt_academic/issues/173) | Add ```/?__dark-theme=true``` at the end of the browser url to switch to dark theme
40
+ [Multiple LLM Models](https://www.bilibili.com/video/BV1wT411p7yf) support, [API2D](https://api2d.com/) interface support | It must feel nice to be served by both GPT3.5, GPT4, and [Tsinghua ChatGLM](https://github.com/THUDM/ChatGLM-6B)!
41
+ Huggingface non-Science Net [Online Experience](https://huggingface.co/spaces/qingxu98/gpt-academic) | After logging in to huggingface, copy [this space](https://huggingface.co/spaces/qingxu98/gpt-academic)
42
+ ... | ...
43
+
44
+ </div>
45
+
46
+
47
+ - New interface (switch between "left-right layout" and "up-down layout" by modifying the LAYOUT option in config.py)
48
+ <div align="center">
49
+ <img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
50
+ </div>
51
+
52
+
53
+ - All buttons are dynamically generated by reading functional.py and can add custom functionality at will, freeing up clipboard
54
+ <div align="center">
55
+ <img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
56
+ </div>
57
+
58
+ - Proofreading / correcting
59
+ <div align="center">
60
+ <img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
61
+ </div>
62
+
63
+ - If the output contains formulas, it will be displayed in both the tex form and the rendering form at the same time, which is convenient for copying and reading
64
+ <div align="center">
65
+ <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
66
+ </div>
67
+
68
+ - Don't want to read the project code? Just take the whole project to chatgpt
69
+ <div align="center">
70
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
71
+ </div>
72
+
73
+ - Multiple major language model mixing calls (ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
74
+ <div align="center">
75
+ <img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
76
+ </div>
77
+
78
+ Multiple major language model mixing call [huggingface beta version](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta) (the huggingface version does not support chatglm)
79
+
80
+
81
+ ---
82
+
83
+ ## Installation-Method 1: Run directly (Windows, Linux or MacOS)
84
+
85
+ 1. Download project
86
+ ```sh
87
+ git clone https://github.com/binary-husky/chatgpt_academic.git
88
+ cd chatgpt_academic
89
+ ```
90
+
91
+ 2. Configure API_KEY and proxy settings
92
+
93
+
94
+ In `config.py`, configure the overseas Proxy and OpenAI API KEY as follows:
95
+ ```
96
+ 1. If you are in China, you need to set up an overseas proxy to use the OpenAI API smoothly. Please read config.py carefully for setup details (1. Modify USE_PROXY to True; 2. Modify proxies according to the instructions).
97
+ 2. Configure the OpenAI API KEY. You need to register and obtain an API KEY on the OpenAI website. Once you get the API KEY, you can configure it in the config.py file.
98
+ 3. Issues related to proxy networks (network timeouts, proxy failures) are summarized at https://github.com/binary-husky/chatgpt_academic/issues/1
99
+ ```
100
+ (P.S. When the program runs, it will first check whether there is a private configuration file named `config_private.py` and use the same-name configuration in `config.py` to overwrite it. Therefore, if you can understand our configuration reading logic, we strongly recommend that you create a new configuration file named `config_private.py` next to `config.py` and transfer (copy) the configuration in `config.py` to` config_private.py`. `config_private.py` is not controlled by git and can make your privacy information more secure.))
101
+
102
+
103
+ 3. Install dependencies
104
+ ```sh
105
+ # (Option One) Recommended
106
+ python -m pip install -r requirements.txt
107
+
108
+ # (Option Two) If you use anaconda, the steps are similar:
109
+ # (Option Two.1) conda create -n gptac_venv python=3.11
110
+ # (Option Two.2) conda activate gptac_venv
111
+ # (Option Two.3) python -m pip install -r requirements.txt
112
+
113
+ # Note: Use official pip source or Ali pip source. Other pip sources (such as some university pips) may have problems, and temporary replacement methods are as follows:
114
+ # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
115
+ ```
116
+
117
+ If you need to support Tsinghua ChatGLM, you need to install more dependencies (if you are not familiar with python or your computer configuration is not good, we recommend not to try):
118
+ ```sh
119
+ python -m pip install -r request_llm/requirements_chatglm.txt
120
+ ```
121
+
122
+ 4. Run
123
+ ```sh
124
+ python main.py
125
+ ```
126
+
127
+ 5. Test function plugins
128
+ ```
129
+ - Test Python project analysis
130
+ In the input area, enter `./crazy_functions/test_project/python/dqn`, and then click "Analyze the entire Python project"
131
+ - Test self-code interpretation
132
+ Click "[Multithreading Demo] Interpretation of This Project Itself (Source Code Interpretation)"
133
+ - Test experimental function template function (requires gpt to answer what happened today in history). You can use this function as a template to implement more complex functions.
134
+ Click "[Function Plugin Template Demo] Today in History"
135
+ - There are more functions to choose from in the function plugin area drop-down menu.
136
+ ```
137
+
138
+ ## Installation-Method 2: Use Docker (Linux)
139
+
140
+ 1. ChatGPT only (recommended for most people)
141
+ ``` sh
142
+ # download project
143
+ git clone https://github.com/binary-husky/chatgpt_academic.git
144
+ cd chatgpt_academic
145
+ # configure overseas Proxy and OpenAI API KEY
146
+ Edit config.py with any text editor
147
+ # Install
148
+ docker build -t gpt-academic .
149
+ # Run
150
+ docker run --rm -it --net=host gpt-academic
151
+
152
+ # Test function plug-in
153
+ ## Test function plugin template function (requires gpt to answer what happened today in history). You can use this function as a template to implement more complex functions.
154
+ Click "[Function Plugin Template Demo] Today in History"
155
+ ## Test Abstract Writing for Latex Projects
156
+ Enter ./crazy_functions/test_project/latex/attention in the input area, and then click "Read Tex Paper and Write Abstract"
157
+ ## Test Python Project Analysis
158
+ Enter ./crazy_functions/test_project/python/dqn in the input area and click "Analyze the entire Python project."
159
+
160
+ More functions are available in the function plugin area drop-down menu.
161
+ ```
162
+
163
+ 2. ChatGPT+ChatGLM (requires strong familiarity with docker + strong computer configuration)
164
+
165
+ ``` sh
166
+ # Modify dockerfile
167
+ cd docs && nano Dockerfile+ChatGLM
168
+ # How to build | 如何构建 (Dockerfile+ChatGLM在docs路径下,请先cd docs)
169
+ docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
170
+ # How to run | 如何运行 (1) 直接运行:
171
+ docker run --rm -it --net=host --gpus=all gpt-academic
172
+ # How to run | 如何运行 (2) 我想运行之前进容器做一些调整:
173
+ docker run --rm -it --net=host --gpus=all gpt-academic bash
174
+ ```
175
+
176
+
177
+ ## Installation-Method 3: Other Deployment Methods
178
+
179
+ 1. Remote Cloud Server Deployment
180
+ Please visit [Deployment Wiki-1] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
181
+
182
+ 2. Use WSL2 (Windows Subsystem for Linux)
183
+ Please visit [Deployment Wiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
184
+
185
+
186
+ ## Installation-Proxy Configuration
187
+ ### Method 1: Conventional method
188
+ [Configure Proxy](https://github.com/binary-husky/chatgpt_academic/issues/1)
189
+
190
+ ### Method Two: Step-by-step tutorial for newcomers
191
+ [Step-by-step tutorial for newcomers](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
192
+
193
+ ---
194
+
195
+ ## Customizing Convenient Buttons (Customizing Academic Shortcuts)
196
+ Open `core_functional.py` with any text editor and add an item as follows, then restart the program (if the button has been successfully added and visible, both the prefix and suffix support hot modification without the need to restart the program to take effect). For example:
197
+ ```
198
+ "Super English to Chinese translation": {
199
+ # Prefix, which will be added before your input. For example, to describe your requirements, such as translation, code interpretation, polishing, etc.
200
+ "Prefix": "Please translate the following content into Chinese and use a markdown table to interpret the proprietary terms in the text one by one:\n\n",
201
+
202
+ # Suffix, which will be added after your input. For example, combined with the prefix, you can put your input content in quotes.
203
+ "Suffix": "",
204
+ },
205
+ ```
206
+ <div align="center">
207
+ <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
208
+ </div>
209
+
210
+ ---
211
+
212
+
213
+ ## Some Function Displays
214
+
215
+ ### Image Display:
216
+
217
+
218
+ You are a professional academic paper translator.
219
+
220
+ <div align="center">
221
+ <img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
222
+ </div>
223
+
224
+ ### If a program can understand and analyze itself:
225
+
226
+ <div align="center">
227
+ <img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
228
+ </div>
229
+
230
+ <div align="center">
231
+ <img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
232
+ </div>
233
+
234
+ ### Analysis of any Python/Cpp project:
235
+ <div align="center">
236
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
237
+ </div>
238
+
239
+ <div align="center">
240
+ <img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
241
+ </div>
242
+
243
+ ### One-click reading comprehension and summary generation of Latex papers
244
+ <div align="center">
245
+ <img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
246
+ </div>
247
+
248
+ ### Automatic report generation
249
+ <div align="center">
250
+ <img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
251
+ <img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
252
+ <img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
253
+ </div>
254
+
255
+ ### Modular functional design
256
+ <div align="center">
257
+ <img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
258
+ <img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
259
+ </div>
260
+
261
+ ### Source code translation to English
262
+
263
+ <div align="center">
264
+ <img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
265
+ </div>
266
+
267
+ ## Todo and version planning:
268
+ - version 3.2+ (todo): Function plugin supports more parameter interfaces
269
+ - version 3.1: Support for inquiring multiple GPT models at the same time! Support for api2d, support for multiple apikeys load balancing
270
+ - version 3.0: Support for chatglm and other small llms
271
+ - version 2.6: Refactored the plugin structure, improved interactivity, added more plugins
272
+ - version 2.5: Self-updating, solves the problem of text being too long and token overflowing when summarizing large project source code
273
+ - version 2.4: (1) Added PDF full text translation function; (2) Added function to switch input area position; (3) Added vertical layout option; (4) Multi-threaded function plugin optimization.
274
+ - version 2.3: Enhanced multi-threaded interactivity
275
+ - version 2.2: Function plugin supports hot reloading
276
+ - version 2.1: Foldable layout
277
+ - version 2.0: Introduction of modular function plugins
278
+ - version 1.0: Basic functions
279
+
280
+ ## Reference and learning
281
+
282
+ ```
283
+ The code design of this project has referenced many other excellent projects, including:
284
+
285
+ # Reference project 1: Borrowed many tips from ChuanhuChatGPT
286
+ https://github.com/GaiZhenbiao/ChuanhuChatGPT
287
+
288
+ # Reference project 2: Tsinghua ChatGLM-6B:
289
+ https://github.com/THUDM/ChatGLM-6B
290
+ ```
291
+
docs/README_FR.md ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > **Note**
2
+ >
3
+ > Ce fichier README est généré automatiquement par le plugin de traduction markdown de ce projet et n'est peut - être pas correct à 100%.
4
+ >
5
+
6
+ # <img src="logo.png" width="40" > ChatGPT Optimisation Académique
7
+
8
+ **Si vous aimez ce projet, donnez-lui une étoile; si vous avez inventé des raccourcis académiques plus utiles ou des plugins fonctionnels, n'hésitez pas à ouvrir une demande ou une demande de traction. Nous avons également un fichier README en [anglais|](docs/README_EN.md)[japonais|](docs/README_JP.md)[russe|](docs/README_RS.md)[français](docs/README_FR.md) traduit par ce projet lui-même.**
9
+
10
+ > **Note**
11
+ >
12
+ > 1. Veuillez noter que seuls les plugins de fonction signalés en **rouge** sont capables de lire les fichiers, certains plugins se trouvent dans le **menu déroulant** de la section plugin. Nous sommes également les bienvenus avec la plus haute priorité pour traiter et accepter tout nouveau PR de plugin!
13
+ >
14
+ > 2. Chaque fichier dans ce projet est expliqué en détail dans l'auto-analyse [self_analysis.md](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A). Avec l'itération des versions, vous pouvez également cliquer sur les plugins fonctionnels pertinents pour appeler GPT et générer un rapport d'auto-analyse projet mis à jour. Les questions fréquemment posées sont résumées dans le [wiki](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98).
15
+ >
16
+
17
+ <div align="center">
18
+
19
+ Fonctionnalité | Description
20
+ --- | ---
21
+ Polissage en un clic | Prend en charge la correction en un clic et la recherche d'erreurs de syntaxe dans les documents de recherche.
22
+ Traduction Chinois-Anglais en un clic | Une touche pour traduire la partie chinoise en anglais ou celle anglaise en chinois.
23
+ Explication de code en un clic | Affiche et explique correctement le code.
24
+ [Raccourcis clavier personnalisables](https://www.bilibili.com/video/BV14s4y1E7jN) | Prend en charge les raccourcis clavier personnalisables.
25
+ [Configuration du serveur proxy](https://www.bilibili.com/video/BV1rc411W7Dr) | Prend en charge la configuration du serveur proxy.
26
+ Conception modulaire | Prend en charge la personnalisation des plugins de fonctions et des [plugins] de fonctions hiérarchiques personnalisés, et les plugins prennent en charge [la mise à jour à chaud](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97).
27
+ [Auto-analyse du programme](https://www.bilibili.com/video/BV1cj411A7VW) | [Plugins] [Lire en un clic](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) le code source de ce projet.
28
+ [Analyse de programme](https://www.bilibili.com/video/BV1cj411A7VW) | [Plugins] En un clic, les projets Python/C/C++/Java/Lua/... peuvent être analysés.
29
+ Lire le document de recherche | [Plugins] Lisez le résumé de l'article en latex et générer un résumé.
30
+ Traduction et polissage de l'article complet en LaTeX | [Plugins] Une touche pour traduire ou corriger en LaTeX
31
+ Génération Commentaire de fonction en vrac | [Plugins] Lisez en un clic les fonctions et générez des commentaires de fonction.
32
+ Rapport d'analyse automatique des chats générés | [Plugins] Génère un rapport de synthèse après l'exécution.
33
+ [Assistant arxiv](https://www.bilibili.com/video/BV1LM4y1279X) | [Plugins] Entrez l'url de l'article arxiv pour traduire le résumé + télécharger le PDF en un clic
34
+ [Traduction complète des articles PDF](https://www.bilibili.com/video/BV1KT411x7Wn) | [Plugins] Extraire le titre et le résumé de l'article PDF + Traduire le texte entier (multithread)
35
+ [Aide à la recherche Google Academ](https://www.bilibili.com/video/BV19L411U7ia) | [Plugins] Donnez à GPT l'URL de n'importe quelle page de recherche Google Academ pour vous aider à sélectionner des articles intéressants
36
+ Affichage de formules/images/tableaux | Afficher la forme traduite et rendue d'une formule en même temps, plusieurs formules et surlignage du code prend en charge
37
+ Prise en charge des plugins multithread | Prise en charge de l'appel multithread de chatgpt, traitement en masse de texte ou de programmes en un clic
38
+ Activer le thème Gradio sombre [theme](https://github.com/binary-husky/chatgpt_academic/issues/173) au démarrage | Ajoutez ```/?__dark-theme=true``` à l'URL du navigateur pour basculer vers le thème sombre
39
+ [Prise en charge de plusieurs modèles LLM](https://www.bilibili.com/video/BV1wT411p7yf), [prise en charge de l'interface API2D](https://api2d.com/) | Comment cela serait-il de se faire servir par GPT3.5, GPT4 et la [ChatGLM de Tsinghua](https://github.com/THUDM/ChatGLM-6B) en même temps?
40
+ Expérience en ligne d'huggingface sans science | Après vous être connecté à huggingface, copiez [cet espace](https://huggingface.co/spaces/qingxu98/gpt-academic)
41
+ ... | ...
42
+
43
+ </div>
44
+
45
+
46
+ Vous êtes un traducteur professionnel d'articles universitaires en français.
47
+
48
+ Ceci est un fichier Markdown, veuillez le traduire en français sans modifier les commandes Markdown existantes :
49
+
50
+ - Nouvelle interface (modifiable en modifiant l'option de mise en page dans config.py pour basculer entre les mises en page gauche-droite et haut-bas)
51
+ <div align="center">
52
+ <img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
53
+ </div>
54
+
55
+
56
+ - Tous les boutons sont générés dynamiquement en lisant functional.py, les utilisateurs peuvent ajouter librement des fonctions personnalisées pour libérer le presse-papiers.
57
+ <div align="center">
58
+ <img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
59
+ </div>
60
+
61
+ - Correction/amélioration
62
+ <div align="center">
63
+ <img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
64
+ </div>
65
+
66
+ - Si la sortie contient des formules, elles seront affichées simultanément sous forme de de texte brut et de forme rendue pour faciliter la copie et la lecture.
67
+ <div align="center">
68
+ <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
69
+ </div>
70
+
71
+ - Pas envie de lire le code du projet ? Faites votre propre démo avec ChatGPT.
72
+ <div align="center">
73
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
74
+ </div>
75
+
76
+ - Utilisation combinée de plusieurs modèles de langage sophistiqués (ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
77
+ <div align="center">
78
+ <img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
79
+ </div>
80
+
81
+ Utilisation combinée de plusieurs modèles de langage sophistiqués en version de test [huggingface](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta) (la version huggingface ne prend pas en charge Chatglm).
82
+
83
+
84
+ ---
85
+
86
+ ## Installation - Méthode 1 : Exécution directe (Windows, Linux or MacOS)
87
+
88
+ 1. Téléchargez le projet
89
+ ```sh
90
+ git clone https://github.com/binary-husky/chatgpt_academic.git
91
+ cd chatgpt_academic
92
+ ```
93
+
94
+ 2. Configuration de l'API_KEY et des paramètres de proxy
95
+
96
+ Dans `config.py`, configurez les paramètres de proxy et de clé d'API OpenAI, comme indiqué ci-dessous
97
+ ```
98
+ 1. Si vous êtes en Chine, vous devez configurer un proxy étranger pour utiliser l'API OpenAI en toute transparence. Pour ce faire, veuillez lire attentivement le fichier config.py (1. Modifiez l'option USE_PROXY ; 2. Modifiez les paramètres de proxies comme indiqué dans les instructions).
99
+ 2. Configurez votre clé API OpenAI. Vous devez vous inscrire sur le site web d'OpenAI pour obtenir une clé API. Une fois que vous avez votre clé API, vous pouvez la configurer dans le fichier config.py.
100
+ 3. Tous les problèmes liés aux réseaux de proxy (temps d'attente, non-fonctionnement des proxies) sont résumés dans https://github.com/binary-husky/chatgpt_academic/issues/1.
101
+ ```
102
+ (Remarque : le programme vérifie d'abord s'il existe un fichier de configuration privé nommé `config_private.py`, et utilise les configurations de celui-ci à la place de celles du fichier `config.py`. Par conséquent, si vous comprenez notre logique de lecture de configuration, nous vous recommandons fortement de créer un nouveau fichier de configuration nommé `config_private.py` à côté de `config.py` et de transférer (copier) les configurations de celui-ci dans `config_private.py`. `config_private.py` n'est pas contrôlé par git et rend vos informations personnelles plus sûres.)
103
+
104
+ 3. Installation des dépendances
105
+ ```sh
106
+ # (Option 1) Recommandé
107
+ python -m pip install -r requirements.txt
108
+
109
+ # (Option 2) Si vous utilisez anaconda, les étapes sont similaires :
110
+ # (Option 2.1) conda create -n gptac_venv python=3.11
111
+ # (Option 2.2) conda activate gptac_venv
112
+ # (Option 2.3) python -m pip install -r requirements.txt
113
+
114
+ # note : Utilisez la source pip officielle ou la source pip Alibaba. D'autres sources (comme celles des universités) pourraient poser problème. Pour utiliser temporairement une autre source, utilisez :
115
+ # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
116
+ ```
117
+
118
+ Si vous avez besoin de soutenir ChatGLM de Tsinghua, vous devez installer plus de dépendances (si vous n'êtes pas familier avec Python ou que votre ordinateur n'est pas assez performant, nous vous recommandons de ne pas essayer) :
119
+ ```sh
120
+ python -m pip install -r request_llm/requirements_chatglm.txt
121
+ ```
122
+
123
+ 4. Exécution
124
+ ```sh
125
+ python main.py
126
+ ```
127
+
128
+ 5. Tester les plugins de fonctions
129
+ ```
130
+ - Test Python Project Analysis
131
+ Dans la zone de saisie, entrez `./crazy_functions/test_project/python/dqn`, puis cliquez sur "Parse Entire Python Project"
132
+ - Test d'auto-lecture du code
133
+ Cliquez sur "[Démo multi-thread] Parser ce projet lui-même (auto-traduction de la source)"
134
+ - Test du modèle de fonctionnalité expérimentale (exige une réponse de l'IA à ce qui est arrivé aujourd'hui dans l'histoire). Vous pouvez utiliser cette fonctionnalité comme modèle pour des fonctions plus complexes.
135
+ Cliquez sur "[Démo modèle de plugin de fonction] Histoire du Jour"
136
+ - Le menu déroulant de la zone de plugin de fonctionnalité contient plus de fonctionnalités à sélectionner.
137
+ ```
138
+
139
+ ## Installation - Méthode 2 : Utilisation de docker (Linux)
140
+
141
+
142
+ Vous êtes un traducteur professionnel d'articles académiques en français.
143
+
144
+ 1. ChatGPT seul (recommandé pour la plupart des gens)
145
+ ``` sh
146
+ # Télécharger le projet
147
+ git clone https://github.com/binary-husky/chatgpt_academic.git
148
+ cd chatgpt_academic
149
+ # Configurer le proxy outre-mer et la clé API OpenAI
150
+ Modifier le fichier config.py avec n'importe quel éditeur de texte
151
+ # Installer
152
+ docker build -t gpt-academic .
153
+ # Exécuter
154
+ docker run --rm -it --net=host gpt-academic
155
+
156
+ # Tester les modules de fonction
157
+ ## Tester la fonction modèle des modules (requiert la réponse de GPT à "qu'est-ce qui s'est passé dans l'histoire aujourd'hui ?"), vous pouvez utiliser cette fonction en tant que modèle pour implémenter des fonctions plus complexes.
158
+ Cliquez sur "[Exemple de modèle de module] Histoire d'aujourd'hui"
159
+ ## Tester le résumé écrit pour le projet LaTeX
160
+ Dans la zone de saisie, tapez ./crazy_functions/test_project/latex/attention, puis cliquez sur "Lire le résumé de l'article de recherche LaTeX"
161
+ ## Tester l'analyse du projet Python
162
+ Dans la zone de saisie, tapez ./crazy_functions/test_project/python/dqn, puis cliquez sur "Analyser l'ensemble du projet Python"
163
+
164
+ D'autres fonctions sont disponibles dans la liste déroulante des modules de fonction.
165
+ ```
166
+
167
+ 2. ChatGPT+ChatGLM (nécessite une grande connaissance de docker et une configuration informatique suffisamment puissante)
168
+ ``` sh
169
+ # Modifier le dockerfile
170
+ cd docs && nano Dockerfile+ChatGLM
171
+ # Comment construire | 如何构建 (Dockerfile+ChatGLM在docs路径下,请先cd docs)
172
+ docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
173
+ # Comment exécuter | 如何运行 (1) Directement exécuter :
174
+ docker run --rm -it --net=host --gpus=all gpt-academic
175
+ # Comment exécuter | 如何运行 (2) Je veux effectuer quelques ajustements dans le conteneur avant de lancer :
176
+ docker run --rm -it --net=host --gpus=all gpt-academic bash
177
+ ```
178
+
179
+ ## Installation - Méthode 3 : Autres méthodes de déploiement
180
+
181
+ 1. Déploiement sur un cloud serveur distant
182
+ Veuillez consulter le [wiki de déploiement-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
183
+
184
+ 2. Utilisation de WSL2 (Windows Subsystem for Linux)
185
+ Veuillez consulter le [wiki de déploiement-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
186
+
187
+
188
+ ## Configuration de la procuration de l'installation
189
+ ### Méthode 1 : Méthode conventionnelle
190
+ [Configuration de la procuration](https://github.com/binary-husky/chatgpt_academic/issues/1)
191
+
192
+ ### Méthode 2 : Tutoriel pour débutant pur
193
+ [Tutoriel pour débutant pur](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
194
+
195
+
196
+ ---
197
+
198
+ ## Personnalisation des nouveaux boutons pratiques (personnalisation des raccourcis académiques)
199
+ Ouvrez le fichier `core_functional.py` avec n'importe quel éditeur de texte, ajoutez les éléments suivants, puis redémarrez le programme. (Si le bouton a déjà été ajouté avec succès et est visible, le préfixe et le suffixe pris en charge peuvent être modifiés à chaud sans avoir besoin de redémarrer le programme.)
200
+ Par exemple:
201
+ ```
202
+ "Traduction Français-Chinois": {
203
+ # Préfixe, qui sera ajouté avant votre saisie. Par exemple, pour décrire votre demande, telle que la traduction, le débogage de code, l'amélioration, etc.
204
+ "Prefix": "Veuillez traduire le contenu ci-dessous en chinois, puis expliquer chaque terme propre mentionné dans un tableau Markdown :\n\n",
205
+
206
+ # Suffixe, qui sera ajouté après votre saisie. Par exemple, en combinaison avec un préfixe, vous pouvez mettre le contenu de votre saisie entre guillemets.
207
+ "Suffix": "",
208
+ },
209
+ ```
210
+
211
+ <div align="center">
212
+ <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
213
+ </div>
214
+
215
+ ---
216
+
217
+
218
+ ## Présentation de certaines fonctionnalités
219
+
220
+ ### Affichage des images:
221
+
222
+ <div align="center">
223
+ <img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
224
+ </div>
225
+
226
+
227
+ ### Si un programme peut comprendre et décomposer lui-même :
228
+
229
+ <div align="center">
230
+ <img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
231
+ </div>
232
+
233
+ <div align="center">
234
+ <img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
235
+ </div>
236
+
237
+
238
+ ### Analyse de tout projet Python/Cpp quelconque :
239
+ <div align="center">
240
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
241
+ </div>
242
+
243
+ <div align="center">
244
+ <img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
245
+ </div>
246
+
247
+ ### Lecture et résumé générés automatiquement pour les articles en Latex
248
+ <div align="center">
249
+ <img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
250
+ </div>
251
+
252
+ ### Génération de rapports automatique
253
+ <div align="center">
254
+ <img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
255
+ <img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
256
+ <img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
257
+ </div>
258
+
259
+ ### Conception de fonctionnalités modulaires
260
+ <div align="center">
261
+ <img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
262
+ <img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
263
+ </div>
264
+
265
+
266
+ ### Traduction de code source en anglais
267
+
268
+ <div align="center">
269
+ <img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
270
+ </div>
271
+
272
+ ## À faire et planification de version :
273
+ - version 3.2+ (à faire) : Prise en charge de plus de paramètres d'interface de plugin de fonction
274
+ - version 3.1 : Prise en charge de l'interrogation simultanée de plusieurs modèles GPT ! Prise en charge de l'API2d, prise en charge de la répartition de charge de plusieurs clés API
275
+ - version 3.0 : Prise en charge de chatglm et d'autres petits llm
276
+ - version 2.6 : Réorganisation de la structure du plugin, amélioration de l'interactivité, ajout de plus de plugins
277
+ - version 2.5 : Mise à jour automatique, résolution du problème de dépassement de jeton et de texte trop long lors de la compilation du code source complet
278
+ - version 2.4 : (1) Ajout de la fonctionnalité de traduction intégrale de PDF ; (2) Ajout d'une fonctionnalité de changement de position de zone de saisie ; (3) Ajout d'une option de disposition verticale ; (4) Optimisation du plugin de fonction multi-thread.
279
+ - version 2.3 : Amélioration de l'interactivité multi-thread
280
+ - version 2.2 : Prise en charge du rechargement à chaud du plugin de fonction
281
+ - version 2.1 : Mise en page pliable
282
+ - version 2.0 : Introduction du plugin de fonction modulaire
283
+ - version 1.0 : Fonctionnalité de base
284
+
285
+ ## Références et apprentissage
286
+
287
+ ```
288
+ De nombreux designs d'autres projets exceptionnels ont été utilisés pour référence dans le code, notamment :
289
+
290
+ # Projet 1 : De nombreuses astuces ont été empruntées à ChuanhuChatGPT
291
+ https://github.com/GaiZhenbiao/ChuanhuChatGPT
292
+
293
+ # Projet 2 : ChatGLM-6B de Tsinghua :
294
+ https://github.com/THUDM/ChatGLM-6B
295
+ ```
296
+
docs/README_JP.md ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > **Note**
2
+ >
3
+ > このReadmeファイルは、このプロジェクトのmarkdown翻訳プラグインによって自動的に生成されたもので、100%正確ではない可能性があります。
4
+ >
5
+
6
+ # <img src="logo.png" width="40" > ChatGPT 学術最適化
7
+
8
+ **このプロジェクトが好きだったら、スターをつけてください。もし、より使いやすい学術用のショートカットキーまたはファンクションプラグインを発明した場合は、issueを発行するかpull requestを作成してください。また、このプロジェクト自体によって翻訳されたREADMEは[英語説明書|](docs/README_EN.md)[日本語説明書|](docs/README_JP.md)[ロシア語説明書|](docs/README_RS.md)[フランス語説明書](docs/README_FR.md)もあります。**
9
+
10
+ > **注意事項**
11
+ >
12
+ > 1. **赤色**のラベルが付いているファンクションプラグイン(ボタン)のみファイルを読み込めます。一部のプラグインはプラグインエリアのドロップダウンメニューにあります。新しいプラグインのPRを歓迎いたします!
13
+ >
14
+ > 2. このプロジェクトの各ファイルの機能は`self_analysis.md`(自己解析レポート)で詳しく説明されています。バージョンが追加されると、関連するファンクションプラグインをクリックして、GPTを呼び出して自己解析レポートを再生成することができます。一般的な質問は`wiki`にまとめられています。(`https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98`)
15
+
16
+
17
+ <div align="center">
18
+
19
+ 機能 | 説明
20
+ --- | ---
21
+ ワンクリック整形 | 論文の文法エラーを一括で正確に修正できます。
22
+ ワンクリック日英翻訳 | 日英翻訳には、ワンクリックで対応できます。
23
+ ワンクリックコード説明 | コードの正しい表示と説明が可能です。
24
+ [カスタムショートカットキー](https://www.bilibili.com/video/BV14s4y1E7jN) | カスタムショートカットキーをサポートします。
25
+ [プロキシサーバーの設定](https://www.bilibili.com/video/BV1rc411W7Dr) | プロキシサーバーの設定をサポートします。
26
+ モジュラーデザイン | カスタム高階関数プラグインと[関数プラグイン]、プラグイン[ホット更新]のサポートが可能です。詳細は[こちら](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97)
27
+ [自己プログラム解析](https://www.bilibili.com/video/BV1cj411A7VW) | [関数プラグイン][ワンクリック理解](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)このプロジェクトのソースコード
28
+ [プログラム解析機能](https://www.bilibili.com/video/BV1cj411A7VW) | [関数プラグイン] ワンクリックで別のPython/C/C++/Java/Lua/...プロジェクトツリーを解析できます。
29
+ 論文読解 | [関数プラグイン] LaTeX論文の全文をワンクリックで解読し、要約を生成します。
30
+ LaTeX全文翻訳、整形 | [関数プラグイン] ワンクリックでLaTeX論文を翻訳または整形できます。
31
+ 注釈生成 | [関数プラグイン] ワンクリックで関数の注釈を大量に生成できます。
32
+ チャット分析レポート生成 | [関数プラグイン] 実行後、まとめレポートを自動生成します。
33
+ [arxivヘルパー](https://www.bilibili.com/video/BV1LM4y1279X) | [関数プラグイン] 入力したarxivの記事URLで要約をワンクリック翻訳+PDFダウンロードができます。
34
+ [PDF論文全文翻訳機能](https://www.bilibili.com/video/BV1KT411x7Wn) | [関数プラグイン] PDF論文タイトルと要約を抽出し、全文を翻訳します(マルチスレッド)。
35
+ [Google Scholar Integratorヘルパー](https://www.bilibili.com/video/BV19L411U7ia) | [関数プラグイン] 任意のGoogle Scholar検索ページURLを指定すると、gptが興味深い記事を選択します。
36
+ 数式/画像/テーブル表示 | 数式のTex形式とレンダリング形式を同時に表示できます。数式、コードのハイライトをサポートしています。
37
+ マルチスレッド関数プラグインサポート | ChatGPTをマルチスレッドで呼び出すことができ、大量のテキストやプログラムを簡単に処理できます。
38
+ ダークグラジオ[テーマ](https://github.com/binary-husky/chatgpt_academic/issues/173)の起動 | 「/?__dark-theme=true」というURLをブラウザに追加することで、ダークテーマに切り替えることができます。
39
+ [多数のLLMモデル](https://www.bilibili.com/video/BV1wT411p7yf)をサポート、[API2D](https://api2d.com/)インターフェースをサポート | GPT3.5、GPT4、[清華ChatGLM](https://github.com/THUDM/ChatGLM-6B)による同時サポートは、と���も素晴らしいですね!
40
+ huggingface免科学上网[オンライン版](https://huggingface.co/spaces/qingxu98/gpt-academic) | huggingfaceにログイン後、[このスペース](https://huggingface.co/spaces/qingxu98/gpt-academic)をコピーしてください。
41
+ ...... | ......
42
+
43
+
44
+ </div>
45
+
46
+
47
+ - 新しいインターフェース(config.pyのLAYOUTオプションを変更するだけで、「左右レイアウト」と「上下レイアウト」を切り替えることができます)
48
+ <div align="center">
49
+ <img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
50
+ </div>
51
+
52
+
53
+ - すべてのボタンは、functional.pyを読み込んで動的に生成されます。カスタム機能を自由に追加して、クリップボードを解放します
54
+ <div align="center">
55
+ <img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
56
+ </div>
57
+
58
+ - 色を修正/修正
59
+ <div align="center">
60
+ <img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
61
+ </div>
62
+
63
+ - 出力に数式が含まれている場合、TeX形式とレンダリング形式の両方が表示され、コピーと読み取りが容易になります
64
+ <div align="center">
65
+ <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
66
+ </div>
67
+
68
+ - プロジェクトのコードを見るのが面倒?chatgptに整備されたプロジェクトを直接与えましょう
69
+ <div align="center">
70
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
71
+ </div>
72
+
73
+ - 多数の大規模言語モデルの混合呼び出し(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
74
+ <div align="center">
75
+ <img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
76
+ </div>
77
+
78
+ 多数の大規模言語モデルの混合呼び出し[huggingfaceテスト版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)(huggigface版はchatglmをサポートしていません)
79
+
80
+
81
+ ---
82
+
83
+ ## インストール-方法1:直接運転 (Windows、LinuxまたはMacOS)
84
+
85
+ 1. プロジェクトをダウンロードします。
86
+ ```sh
87
+ git clone https://github.com/binary-husky/chatgpt_academic.git
88
+ cd chatgpt_academic
89
+ ```
90
+
91
+ 2. API_KEYとプロキシ設定を構成する
92
+
93
+ `config.py`で、海外のProxyとOpenAI API KEYを構成して説明します。
94
+ ```
95
+ 1.あなたが中国にいる場合、OpenAI APIをスムーズに使用するには海外プロキシを設定する必要があります。構成の詳細については、config.py(1.その中のUSE_PROXYをTrueに変更し、2.手順に従ってプロキシを変更する)を詳細に読んでください。
96
+ 2. OpenAI API KEYを構成する。OpenAIのウェブサイトでAPI KEYを取得してください。一旦API KEYを手に入れると、config.pyファイルで設定するだけです。
97
+ 3.プロキシネットワークに関連する問題(ネットワークタイムアウト、プロキシが動作しない)をhttps://github.com/binary-husky/chatgpt_academic/issues/1にまとめました。
98
+ ```
99
+ (P.S. プログラム実行時にconfig.pyの隣にconfig_private.pyという名前のプライバシー設定ファイルを作成し、同じ名前の設定を上書きするconfig_private.pyが存在するかどうかを優先的に確認します。そのため、私たちの構成読み取りロジックを理解できる場合は、config.pyの隣にconfig_private.pyという名前の新しい設定ファイルを作成し、その中のconfig.pyから設定を移動してください。config_private.pyはgitで保守されていないため、プライバシー情報をより安全にすることができます。)
100
+
101
+ 3. 依存関係をインストールします。
102
+ ```sh
103
+ # 選択肢があります。
104
+ python -m pip install -r requirements.txt
105
+
106
+
107
+ # (選択肢2) もしAnacondaを使用する場合、手順は同様です:
108
+ # (選択肢2.1) conda create -n gptac_venv python=3.11
109
+ # (選択肢2.2) conda activate gptac_venv
110
+ # (選択肢2.3) python -m pip install -r requirements.txt
111
+
112
+ # 注: 公式のpipソースまたはAlibabaのpipソースを使用してください。 別のpipソース(例:一部の大学のpip)は問題が発生する可能性があります。 一時的なソースの切り替え方法:
113
+ # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
114
+ ```
115
+
116
+ もしあなたが清華ChatGLMをサポートする必要がある場合、さらに多くの依存関係をインストールする必要があります(Pythonに慣れない方やコンピューターの設定が十分でない方は、試みないことをお勧めします):
117
+ ```sh
118
+ python -m pip install -r request_llm/requirements_chatglm.txt
119
+ ```
120
+
121
+ 4. 実行
122
+ ```sh
123
+ python main.py
124
+ ```
125
+
126
+ 5. 関数プラグインのテスト
127
+ ```
128
+ - Pythonプロジェクト分析のテスト
129
+ 入力欄に `./crazy_functions/test_project/python/dqn` と入力し、「Pythonプロジェクト全体の解析」をクリックします。
130
+ - 自己コード解読のテスト
131
+ 「[マルチスレッドデモ] このプロジェクト自体を解析します(ソースを翻訳して解読します)」をクリックします。
132
+ - 実験的な機能テンプレート関数のテスト(GPTが「今日の歴史」に何が起こったかを回答することが求められます)。この関数をテンプレートとして使用して、より複雑な機能を実装できます。
133
+ 「[関数プラグインテンプレートデモ] 今日の歴史」をクリックします。
134
+ - 関数プラグインエリアのドロップダウンメニューには他にも選択肢があります。
135
+ ```
136
+
137
+ ## インストール方法2:Dockerを使用する(Linux)
138
+
139
+ 1. ChatGPTのみ(大多数の人にお勧めです)
140
+ ``` sh
141
+ # プロジェクトのダウンロード
142
+ git clone https://github.com/binary-husky/chatgpt_academic.git
143
+ cd chatgpt_academic
144
+ # 海外プロキシとOpenAI API KEYの設定
145
+ config.pyを任意のテキストエディタで編集する
146
+ # インストール
147
+ docker build -t gpt-academic .
148
+ # 実行
149
+ docker run --rm -it --net=host gpt-academic
150
+
151
+ # 関数プラグインのテスト
152
+ ## 関数プラグインテンプレート関数のテスト(GPTが「今日の歴史」に何が起こったかを回答することが求められます)。この関数をテンプレートとして使用して、より複雑な機能を実装できます。
153
+ 「[関数プラグインテンプレートデモ] 今日の歴史」をクリックします。
154
+ ## Latexプロジェクトの要約を書くテスト
155
+ 入力欄に./crazy_functions/test_project/latex/attentionと入力し、「テックス論文を読んで要約を書く」をクリックします。
156
+ ## Pythonプロジェクト分析のテスト
157
+ 入力欄に./crazy_functions/test_project/python/dqnと入力し、[Pythonプロジェクトの全解析]をクリックします。
158
+
159
+ 関数プラグインエリアのドロップダウンメニューには他にも選択肢があります。
160
+ ```
161
+
162
+ 2. ChatGPT + ChatGLM(Dockerに非常に詳しい人+十分なコンピューター設定が必要)
163
+
164
+
165
+
166
+ ```sh
167
+ # Dockerfileの編集
168
+ cd docs && nano Dockerfile+ChatGLM
169
+ # ビルド方法
170
+ docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
171
+ # 実行方法 (1) 直接実行:
172
+ docker run --rm -it --net=host --gpus=all gpt-academic
173
+ # 実行方法 (2) コンテナに入って調整する:
174
+ docker run --rm -it --net=host --gpus=all gpt-academic bash
175
+ ```
176
+
177
+ ## インストール方法3:その他のデプロイ方法
178
+
179
+ 1. クラウドサーバーデプロイ
180
+ [デプロイwiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
181
+
182
+ 2. WSL2を使用 (Windows Subsystem for Linux)
183
+ [デプロイwiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
184
+
185
+
186
+ ## インストール-プロキシ設定
187
+ 1. 通常の方法
188
+ [プロキシを設定する](https://github.com/binary-husky/chatgpt_academic/issues/1)
189
+
190
+ 2. 初心者向けチュートリアル
191
+ [初心者向けチュートリアル](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
192
+
193
+
194
+ ---
195
+
196
+ ## カスタムボタンの追加(学術ショートカットキー)
197
+
198
+ `core_functional.py`を任意のテキストエディタで開き、以下のエントリーを追加し、プログラムを再起動してください。(ボタンが追加されて表示される場合、前置詞と後置詞はホット編集がサポートされているため、プログラムを再起動せずに即座に有効になります。)
199
+
200
+ 例:
201
+ ```
202
+ "超级英译中": {
203
+ # 前置詞 - あなたの要求を説明するために使用されます。翻訳、コードの説明、編集など。
204
+ "Prefix": "以下のコンテンツを中国語に翻訳して、マークダウンテーブルを使用して専門用語を説明してください。\n\n",
205
+
206
+ # 後置詞 - プレフィックスと共に使用すると、入力内容を引用符で囲むことができます。
207
+ "Suffix": "",
208
+ },
209
+ ```
210
+
211
+ <div align="center">
212
+ <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
213
+ </div>
214
+
215
+
216
+ ---
217
+
218
+ ## いくつかの機能の例
219
+
220
+ ### 画像表示:
221
+
222
+ <div align="center">
223
+ <img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
224
+ </div>
225
+
226
+
227
+ ### プログラムが自己解析できる場合:
228
+
229
+ <div align="center">
230
+ <img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
231
+ </div>
232
+
233
+ <div align="center">
234
+ <img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
235
+ </div>
236
+
237
+ ### 他のPython/Cppプロジェクトの解析:
238
+
239
+ <div align="center">
240
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
241
+ </div>
242
+
243
+ <div align="center">
244
+ <img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
245
+ </div>
246
+
247
+ ### Latex論文の一括読解と要約生成
248
+
249
+ <div align="center">
250
+ <img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
251
+ </div>
252
+
253
+ ### 自動報告生成
254
+
255
+ <div align="center">
256
+ <img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
257
+ <img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
258
+ <img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
259
+ </div>
260
+
261
+ ### モジュール化された機能デザイン
262
+
263
+ <div align="center">
264
+ <img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
265
+ <img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
266
+ </div>
267
+
268
+
269
+ ### ソースコードの英語翻訳
270
+
271
+ <div align="center">
272
+ <img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
273
+ </div>
274
+
275
+ ## Todo およびバージョン計画:
276
+ - version 3.2+ (todo): 関数プラグインがより多くのパラメーターインターフェースをサポートするようになります。
277
+ - version 3.1: 複数のgptモデルを同時にクエリし、api2dをサポートし、複数のapikeyの負荷分散をサポートします。
278
+ - version 3.0: chatglmおよび他の小型llmのサポート
279
+ - version 2.6: プラグイン構造を再構成し、相互作用性を高め、より多くのプラグインを追加しました。
280
+ - version 2.5: 自己更新。総括的な大規模プロジェクトのソースコードをまとめた場合、テキストが長すぎる、トークンがオーバーフローする問題を解決します。
281
+ - version 2.4: (1)PDF全文翻訳機能を追加。(2)入力エリアの位置を切り替える機能を追加。(3)垂直レイアウトオプションを追加。(4)マルチスレッド関数プラグインの最適化。
282
+ - version 2.3: 多スレッドの相互作用性を向上させました。
283
+ - version 2.2: 関数プラグインでホットリロードをサポート
284
+ - version 2.1: 折りたたみ式レイアウト
285
+ - version 2.0: モジュール化された関数プラグインを導入
286
+ - version 1.0: 基本機能
287
+
288
+ ## 参考および学習
289
+
290
+
291
+ 以下は中国語のマークダウンファイルです。日本語に翻訳してください。既存のマークダウンコマンドを変更しないでください:
292
+
293
+ ```
294
+ 多くの優秀なプロジェクトの設計を参考にしています。主なものは以下の通りです:
295
+
296
+ # 参考プロジェクト1:ChuanhuChatGPTから多くのテクニックを借用
297
+ https://github.com/GaiZhenbiao/ChuanhuChatGPT
298
+
299
+ # 参考プロジェクト2:清華ChatGLM-6B:
300
+ https://github.com/THUDM/ChatGLM-6B
301
+ ```
302
+
docs/README_RS.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ > **Note**
2
+ >
3
+ > Этот файл самовыражения автоматически генерируется модулем перевода markdown в этом проекте и может быть не на 100% правильным.
4
+ >
5
+
6
+ # <img src="logo.png" width="40" > ChatGPT Academic Optimization
7
+
8
+ **Если вам понравился этот проект, пожалуйста, поставьте ему звезду. Если вы придумали более полезные академические ярлыки или функциональные плагины, не стесняйтесь создавать запросы на изменение или пул-запросы. Мы также имеем [README на английском языке](docs/README_EN.md), переведенный этим же проектом.
9
+
10
+ > **Примечание**
11
+ >
12
+ > 1. Пожалуйста, обратите внимание, что только функциonal plugins (buttons) с **красным цветом** могут читать файлы, некоторые из которых находятся в **выпадающем меню** плагинов. Кроме того, мы приветствуем и обрабатываем любые новые плагины с **наивысшим приоритетом**!
13
+ >
14
+ > 2. Функции каждого файла в этом проекте подробно описаны в собственном анализе [`self_analysis.md`](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) . При повторных итерациях вы также можете вызывать обновленный отчет функций проекта, щелкнув соответствующий функциональный плагин GPT. Часто задаваемые вопросы собраны в [`wiki`](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98) .
15
+
16
+ <div align="center">
17
+
18
+ Функция | Описание
19
+ --- | ---
20
+ Редактирование одним кликом | Поддержка редактирования одним кликом, поиск грамматических ошибок в академических статьях
21
+ Переключение языков "Английский-Китайский" одним кликом | Одним кликом переключайте языки "Английский-Китайский"
22
+ Разъяснение программного кода одним кликом | Вы можете правильно отобразить и объяснить программный код.
23
+ [Настраиваемые сочетания клавиш](https://www.bilibili.com/video/BV14s4y1E7jN) | Поддержка настраиваемых сочетаний клавиш
24
+ [Настройка сервера-прокси](https://www.bilibili.com/video/BV1rc411W7Dr) | Поддержка настройки сервера-прокси
25
+ Модульный дизайн | Поддержка настраиваемых функциональных плагинов высших порядков и функциональных плагинов, поддерживающих [горячее обновление](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97)
26
+ [Автоанализ программы](https://www.bilibili.com/video/BV1cj411A7VW) | [Функциональный плагин] [Прочтение в один клик](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) кода программы проекта
27
+ [Анализ программы](https://www.bilibili.com/video/BV1cj411A7VW) | [Функциональный плагин] Один клик для проанализирования дерева других проектов Python/C/C++/Java/Lua/...
28
+ Чтение статей| [Функциональный плагин] Одним кликом прочитайте весь латех (LaTex) текст статьи и сгенерируйте краткое описание
29
+ Перевод и редактирование всех статей из LaTex | [Функциональный плагин] Перевод или редактирование LaTex-статьи всего одним нажатием кнопки
30
+ Генерация комментариев в пакетном режиме | [Функциональный плагин] Одним кликом сгенерируйте комментарии к функциям в пакетном режиме
31
+ Генерация отчетов пакета CHAT | [Функциональный плагин] Автоматически создавайте сводные отчеты после выполнения
32
+ [Помощник по arxiv](https://www.bilibili.com/video/BV1LM4y1279X) | [Функциональный плагин] Введите URL статьи arxiv, чтобы легко перевести резюме и загрузить PDF-файл
33
+ [Перевод полного текста статьи в формате PDF](https://www.bilibili.com/video/BV1KT411x7Wn) | [Функциональный плагин] Извлеките заголовок статьи, резюме и переведите весь текст статьи (многопоточно)
34
+ [Помощник интеграции Google Scholar](https://www.bilibili.com/video/BV19L411U7ia) | [Функциональный плагин] Дайте GPT выбрать для вас интересные статьи на любой странице поиска Google Scholar.
35
+ Отображение формул/изображений/таблиц | Одновременно отображается tex-форма и рендер-форма формул, поддержка формул, высокоскоростных кодов
36
+ Поддержка функциональных плагинов многопоточности | Поддержка многопоточной работы с плагинами, обрабатывайте огромные объемы текста или программы одним кликом
37
+ Запуск темной темы gradio[подробнее](https://github.com/binary-husky/chatgpt_academic/issues/173) | Добавьте / ?__dark-theme=true в конец URL браузера, чтобы переключиться на темную тему.
38
+ [Поддержка нескольких моделей LLM](https://www.bilibili.com/video/BV1wT411p7yf), поддержка API2D | Находиться между GPT3.5, GPT4 и [清华ChatGLM](https://github.com/THUDM/ChatGLM-6B) должно быть очень приятно, не так ли?
39
+ Альтернатива huggingface без использования научной сети [Онлайн-эксперимент](https://huggingface.co/spaces/qingxu98/gpt-academic) | Войдите в систему, скопируйте пространство [этот пространственный URL](https://huggingface.co/spaces/qingxu98/gpt-academic)
40
+ …… | ……
41
+
42
+
43
+ </div>
44
+
45
+ - Новый интерфейс (вы можете изменить настройку LAYOUT в config.py, чтобы переключаться между "горизонтальным расположением" и "вертикальным расположением")
46
+ <div align="center">
47
+ <img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
48
+ </div>
49
+
50
+
51
+ Вы профессиональный переводчик научных статей.
52
+
53
+ - Все кнопки генерируются динамически путем чтения functional.py и могут быть легко настроены под пользовательские потребности, освобождая буфер обмена.
54
+ <div align="center">
55
+ <img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
56
+ </div>
57
+
58
+ - Редактирование/корректирование
59
+ <div align="center">
60
+ <img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
61
+ </div>
62
+
63
+ - Если вывод содержит формулы, они отображаются одновременно как в формате tex, так и в рендеринговом формате для удобства копирования и чтения.
64
+ <div align="center">
65
+ <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
66
+ </div>
67
+
68
+ - Лень смотреть код проекта? Просто покажите chatgpt.
69
+ <div align="center">
70
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
71
+ </div>
72
+
73
+ - Несколько моделей больших языковых моделей смешиваются (ChatGLM + OpenAI-GPT3.5 + [API2D] (https://api2d.com/) -GPT4)
74
+ <div align="center">
75
+ <img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
76
+ </div>
77
+
78
+ Несколько моделей больших языковых моделей смешиваются в [бета-версии huggingface] (https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta) (huggingface-версия не поддерживает chatglm).
79
+
80
+
81
+ ---
82
+
83
+ ## Установка - Метод 1: Запуск (Windows, Linux или MacOS)
84
+
85
+ 1. Скачайте проект
86
+ ```sh
87
+ git clone https://github.com/binary-husky/chatgpt_academic.git
88
+ cd chatgpt_academic
89
+ ```
90
+
91
+ 2. Настройка API_KEY и настройки прокси
92
+
93
+ В файле `config.py` настройте зарубежный прокси и OpenAI API KEY, пояснения ниже
94
+ ```
95
+ 1. Если вы находитесь в Китае, вам нужно настроить зарубежный прокси, чтобы использовать OpenAI API. Пожалуйста, внимательно прочитайте config.py для получения инструкций (1. Измените USE_PROXY на True; 2. Измените прокси в соответствии с инструкциями).
96
+ 2. Настройка API KEY OpenAI. Вам необходимо зарегистрироваться на сайте OpenAI и получить API KEY. После получения API KEY настройте его в файле config.py.
97
+ 3. Вопросы, связанные с сетевыми проблемами (тайм-аут сети, прокси не работает), можно найти здесь: https://github.com/binary-husky/chatgpt_academic/issues/1
98
+ ```
99
+ (Примечание: при запуске программы будет проверяться наличие конфиденциального файла конфигурации с именем `config_private.py` и использоваться в нем конфигурация параметров, которая перезаписывает параметры с такими же именами в `config.py`. Поэтому, если вы понимаете логику чтения нашей конфигурации, мы настоятельно рекомендуем вам создать новый файл конфигурации с именем `config_private.py` рядом с `config.py` и переместить (скопировать) настройки из `config.py` в `config_private.py`. `config_private.py` не подвергается контролю git, что делает конфиденциальную информацию более безопасной.)
100
+
101
+
102
+ 3. Установить зависимости
103
+ ```sh
104
+ # (Выбор 1) Рекомендуется
105
+ python -m pip install -r requirements.txt
106
+
107
+ # (Выбор 2) Если вы используете anaconda, то шаги будут аналогичны:
108
+ # (Шаг 2.1) conda create -n gptac_venv python=3.11
109
+ # (Шаг 2.2) conda activate gptac_venv
110
+ # (Шаг 2.3) python -m pip install -r requirements.txt
111
+
112
+ # Примечание: используйте официальный источник pip или источник pip.aliyun.com. Другие источники pip могут вызывать проблемы. временный метод замены источника:
113
+ # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
114
+ ```
115
+
116
+ Если требуется поддержка TUNA ChatGLM, необходимо установить дополнительные зависимости (если вы неудобны с python, необходимо иметь хорошую конфигурацию компьютера):
117
+ ```sh
118
+ python -m pip install -r request_llm/requirements_chatglm.txt
119
+ ```
120
+
121
+ 4. Запустите
122
+ ```sh
123
+ python main.py
124
+ ```
125
+
126
+ 5. Тестовые функции плагина
127
+ ```
128
+ - Тестирвоание анализа проекта Python
129
+ В основной области введите `./crazy_functions/test_project/python/dqn` , а затем нажмите "Анализировать весь проект Python"
130
+ - Тестирование самостоятельного чтения кода
131
+ Щелкните " [Демонстрационный режим многопоточности] Проанализируйте сам проект (расшифровка источника кода)"
132
+ - Тестирование функций шаблонного плагина (вы можете использовать эту функцию как шаблон для более сложных функций, требующих ответа от gpt в связи с тем, что произошло сегодня в истории)
133
+ Щелкните " [Функции шаблонного плагина] День в истории"
134
+ - На нижней панели дополнительные функции для выбора
135
+ ```
136
+
137
+ ## Установка - Метод 2: Использование docker (Linux)
138
+
139
+
140
+ 1. Только ChatGPT (рекомендуется для большинства пользователей):
141
+ ``` sh
142
+ # Скачать проект
143
+ git clone https://github.com/binary-husky/chatgpt_academic.git
144
+ cd chatgpt_academic
145
+ # Настроить прокси за границей и OpenAI API KEY
146
+ Отредактируйте файл config.py в любом текстовом редакторе.
147
+ # Установка
148
+ docker build -t gpt-academic .
149
+ # Запустить
150
+ docker run --rm -it --net=host gpt-academic
151
+
152
+ # Проверка функциональности плагина
153
+ ## Прове��ка шаблонной функции плагина (требуется, чтобы gpt ответил, что произошло "в истории на этот день"), вы можете использовать эту функцию в качестве шаблона для реализации более сложных функций.
154
+ Нажмите "[Шаблонный демонстрационный плагин] История на этот день".
155
+ ## Тест абстрактного резюме для проекта на Latex
156
+ В области ввода введите ./crazy_functions/test_project/latex/attention, а затем нажмите "Чтение реферата о тезисах статьи на LaTeX".
157
+ ## Тестовый анализ проекта на Python
158
+ Введите в область ввода ./crazy_functions/test_project/python/dqn, затем нажмите "Проанализировать весь проект на Python".
159
+
160
+ Выбирайте больше функциональных плагинов в нижнем выпадающем меню.
161
+ ```
162
+
163
+ 2. ChatGPT + ChatGLM (требуется глубокое знание Docker и достаточно мощное компьютерное оборудование):
164
+
165
+ ``` sh
166
+ # Изменение Dockerfile
167
+ cd docs && nano Dockerfile+ChatGLM
168
+ # Как построить | Как запустить (Dockerfile+ChatGLM в пути docs, сначала перейдите в папку с помощью cd docs)
169
+ docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
170
+ # Как запустить | Как запустить (2) я хочу войти в контейнер и сделать какие-то настройки до запуска:
171
+ docker run --rm -it --net=host --gpus=all gpt-academic bash
172
+ ```
173
+
174
+
175
+ ## Установка-Метод 3: Другие способы развертывания
176
+
177
+ 1. Развертывание на удаленном облачном сервере
178
+ Пожалуйста, посетите [Deploy Wiki-1] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
179
+
180
+ 2. Использование WSL2 (Windows Subsystem for Linux)
181
+ Пожалуйста, посетите [Deploy Wiki-2] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
182
+
183
+
184
+ ## Установка-Настройки прокси
185
+ ### Метод 1: Обычный способ
186
+ [Конфигурация прокси] (https://github.com/binary-husky/chatgpt_academic/issues/1)
187
+
188
+ ### Метод 2: Руководство новичка
189
+ [Руководство новичка] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
190
+
191
+
192
+ ---
193
+
194
+ ## Настройка новой удобной кнопки (настройка быстрой клавиши для научной работы)
195
+ Откройте `core_functional.py` любым текстовым редактором, добавьте элементы, как показано ниже, затем перезапустите программу. (Если кнопка уже успешно добавлена и видна, то префикс и суффикс поддерживают горячее изменение, чтобы они оказались в действии, не нужно перезапускать программу.)
196
+ например
197
+ ```
198
+ "Супер анг-рус": {
199
+ # Префикс, будет добавлен перед вашим вводом. Например, используется для описания ваших потребностей, таких как перевод, кодинг, редактирование и т. д.
200
+ "Prefix": "Пожалуйста, переведите этот фрагмент на русский язык, а затем создайте пошаговую таблицу в markdown, чтобы объяснить все специализированные термины, которые встречаются в тексте:\n\n",
201
+
202
+ # Суффикс, будет добавлен после вашего ввода. Например, совместно с префиксом можно обрамить ваш ввод в кавычки.
203
+ "Suffix": "",
204
+ },
205
+ ```
206
+ <div align="center">
207
+ <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
208
+ </div>
209
+
210
+ ---
211
+
212
+
213
+ ## Демонстрация некоторых возможностей
214
+
215
+ ### Отображение изображений:
216
+
217
+ <div align="center">
218
+ <img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
219
+ </div>
220
+
221
+
222
+ ### Если программа может понимать и разбирать сама себя:
223
+
224
+ <div align="center">
225
+ <img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
226
+ </div>
227
+
228
+ <div align="center">
229
+ <img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
230
+ </div>
231
+
232
+
233
+ ### Анализ других проектов на Python/Cpp:
234
+ <div align="center">
235
+ <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
236
+ </div>
237
+
238
+ <div align="center">
239
+ <img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
240
+ </div>
241
+
242
+ ### Генерация понимания и абстрактов с помощью Латех статей в один клик
243
+ <div align="center">
244
+ <img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
245
+ </div>
246
+
247
+ ### Автоматическое создание отчетов
248
+ <div align="center">
249
+ <img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
250
+ <img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
251
+ <img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
252
+ </div>
253
+
254
+ ### Модульный дизайн функций
255
+ <div align="center">
256
+ <img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
257
+ <img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
258
+ </div>
259
+
260
+
261
+ ### Трансляция исходного кода на английский язык
262
+
263
+ <div align="center">
264
+ <img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
265
+ </div>
266
+
267
+ ## Todo и планирование версий:
268
+ - version 3.2+ (todo): функция плагины поддерживают более многочисленные интерфейсы параметров
269
+ - version 3.1: поддержка одновременного опроса нескольких моделей gpt! Поддержка api2d, поддержка балансировки нагрузки множества apikey.
270
+ - version 3.0: поддержка chatglm и других маленьких llm
271
+ - version 2.6: реструктурировал структуру плагинов, повысил интерактивность, добавил больше плагинов
272
+ - version 2.5: само обновление, решение проблемы слишком длинного текста и переполнения токена при переводе всего проекта исходного кода
273
+ - version 2.4: (1) добавлена функция перевода всего PDF-документа; (2) добавлена функция изменения положения входной области; (3) добавлена опция вертикального макета; (4) оптимизация функций многопоточности плагина.
274
+ - version 2.3: улучшение многопоточной интерактивности
275
+ - version 2.2: функция плагинов поддерживает горячую перезагрузку
276
+ - version 2.1: блочная раскладка
277
+ - version 2.0: модульный дизайн функций плагина
278
+ - version 1.0: основные функции
279
+
280
+ ## Ссылки на изучение и обучение
281
+
282
+ ```
283
+ В коде использовано много хороших дизайнерских решений из других отличных проектов, в том числе:
284
+
285
+ # Project1: использование многих приемов из ChuanhuChatGPT
286
+ https://github.com/GaiZhenbiao/ChuanhuChatGPT
287
+
288
+ # Project2: ChatGLM-6B в Тхуде:
289
+ https://github.com/THUDM/ChatGLM-6B
290
+ ```
291
+
{img → docs}/demo.jpg RENAMED
File without changes
{img → docs}/demo2.jpg RENAMED
File without changes
docs/logo.png ADDED
docs/self_analysis.md ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chatgpt-academic项目自译解报告
2
+ (Author补充:以下分析均由本项目调用ChatGPT一键生成,如果有不准确的地方,全怪GPT😄)
3
+
4
+ ## 对程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能。
5
+
6
+ 整体概括:
7
+
8
+ 该程序是一个基于自然语言处理和机器学习的科学论文辅助工具,主要功能包括聊天机器人、批量总结PDF文档、批量翻译PDF文档、生成函数注释、解析项目源代码等。程序基于 Gradio 构建 Web 服务,并集成了代理和自动更新功能,提高了用户的使用体验。
9
+
10
+ 文件功能表格:
11
+
12
+ | 文件名 | 文件功能 |
13
+ | --- | --- |
14
+ | check_proxy.py | 用于检查代理的正确性和可用性 |
15
+ | colorful.py | 包含不同预设置颜色的常量,并用于多种UI元素 |
16
+ | config.py | 用于全局配置的类 |
17
+ | config_private.py | 与config.py文件一起使用的另一个配置文件,用于更改私密信息 |
18
+ | core_functional.py | 包含一些TextFunctional类和基础功能函数 |
19
+ | crazy_functional.py | 包含大量高级功能函数和实验性的功能函数 |
20
+ | main.py | 程序的主入口,包含GUI主窗口和主要的UI管理功能 |
21
+ | theme.py | 包含一些预设置主题的颜色 |
22
+ | toolbox.py | 提供了一些有用的工具函数 |
23
+ | crazy_functions\crazy_utils.py | 包含一些用于实现高级功能的辅助函数 |
24
+ | crazy_functions\Latex全文润色.py | 实现了对LaTeX文件中全文的润色和格式化功能 |
25
+ | crazy_functions\Latex全文翻译.py | 实现了对LaTeX文件中的内容进行翻译的功能 |
26
+ | crazy_functions\_\_init\_\_.py | 用于导入crazy_functional.py中的功能函数 |
27
+ | crazy_functions\下载arxiv论文翻译摘要.py | 从Arxiv上下载论文并提取重要信息 |
28
+ | crazy_functions\代码重写为全英文_多线程.py | 针对中文Python文件,将其翻译为全英文 |
29
+ | crazy_functions\总结word文档.py | 提取Word文件的重要内容来生成摘要 |
30
+ | crazy_functions\批量Markdown翻译.py | 批量翻译Markdown文件 |
31
+ | crazy_functions\批量总结PDF文档.py | 批量从PDF文件中提取摘要 |
32
+ | crazy_functions\批量总结PDF文档pdfminer.py | 批量从PDF文件中提取摘要 |
33
+ | crazy_functions\批量翻译PDF文档_多线程.py | 批量翻译PDF文件 |
34
+ | crazy_functions\理解PDF文档内容.py | 批量分析PDF文件并提取摘要 |
35
+ | crazy_functions\生成函数注释.py | 自动生成Python文件中函数的注释 |
36
+ | crazy_functions\解析项目源代码.py | 解析并分析给定项目的源代码 |
37
+ | crazy_functions\询问多个大语言模型.py | 向多个大语言模型询问输入文本并进行处理 |
38
+ | crazy_functions\读文献写摘要.py | 根据用户输入读取文献内容并生成摘要 |
39
+ | crazy_functions\谷歌检索小助手.py | 利用谷歌学术检索用户提供的论文信息并提取相关信息 |
40
+ | crazy_functions\高级功能函数模板.py | 实现高级功能的模板函数 |
41
+ | request_llm\bridge_all.py | 处理与LLM的交互 |
42
+ | request_llm\bridge_chatglm.py | 使用ChatGLM模型进行聊天 |
43
+ | request_llm\bridge_chatgpt.py | 实现对话生成的各项功能 |
44
+ | request_llm\bridge_tgui.py | 在Websockets中与用户进行交互并生成文本输出 |
45
+
46
+
47
+
48
+ ## [0/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\check_proxy.py
49
+
50
+ 该文件主要包括四个函数:check_proxy、backup_and_download、patch_and_restart 和 auto_update。其中,check_proxy 函数用于检查代理是否可用;backup_and_download 用于进行一键更新备份和下载;patch_and_restart 是一键更新协议的重要函数,用于覆盖和重启;auto_update 函数用于查询版本和用户意见,并自动进行一键更新。该文件主要使用了 requests、json、shutil、zipfile、distutils、subprocess 等 Python 标准库和 toolbox 和 colorful 两个第三方库。
51
+
52
+ ## [1/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\colorful.py
53
+
54
+ 该程序文件实现了一些打印文本的函数,使其具有不同的颜色输出。当系统为Linux时直接跳过,否则使用colorama库来实现颜色输出。程序提供了深色和亮色两种颜色输出方式,同时也提供了对打印函数的别名。对于不是终端输出的情况,对所有的打印函数进行重复定义,以便在重定向时能够避免打印错误日志。
55
+
56
+ ## [2/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\config.py
57
+
58
+ 该程序文件是一个配置文件,其主要功能是提供使用API密钥等信息,以及对程序的体验进行优化,例如定义对话框高度、布局等。还包含一些其他的设置,例如设置并行使用的线程数、重试次数限制等等。
59
+
60
+ ## [3/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\config_private.py
61
+
62
+ 这是一个名为config_private.py的Python文件,它用于配置API_KEY和代理信息。API_KEY是一个私密密钥,用于访���某些受保护的API。USE_PROXY变量设置为True以应用代理,proxies变量配置了代理网络的地址和协议。在使用该文件时,需要填写正确的API_KEY和代理信息。
63
+
64
+ ## [4/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\core_functional.py
65
+
66
+ 该文件是一个Python模块,名为"core_functional.py"。模块中定义了一个字典,包含了各种核心功能的配置信息,如英语学术润色、中文学术润色、查找语法错误等。每个功能都包含一些前言和后语,在前言中描述了该功能的任务和要求,在后语中提供一些附加信息。此外,有些功能还定义了一些特定的处理函数和按钮颜色。
67
+
68
+ ## [5/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functional.py
69
+
70
+ 这是一个Python程序文件,文件名是crazy_functional.py。它导入了一个名为HotReload的工具箱,并定义了一个名为get_crazy_functions()的函数。这个函数包括三个部分的插件组,分别是已经编写完成的第一组插件、已经测试但距离完美状态还差一点点的第二组插件和尚未充分测试的第三组插件。每个插件都有一个名称、一个按钮颜色、一个函数和一个是否加入下拉菜单中的标志位。这些插件提供了多种功能,包括生成函数注释、解析项目源代码、批量翻译PDF文档、谷歌检索、PDF文档内容理解和Latex文档的全文润色、翻译等功能。其中第三组插件可能还存在一定的bug。
71
+
72
+ ## [6/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\main.py
73
+
74
+ 该Python脚本代码实现了一个用于交互式对话的Chatbot机器人。它使用了Gradio框架来构建一个Web界面,并在此基础之上嵌入了一个文本输入框和与Chatbot进行交互的其他控件,包括提交、重置、停止和清除按钮、选择框和滑块等。此外,它还包括了一些类和函数和一些用于编程分析的工具和方法。整个程序文件的结构清晰,注释丰富,并提供了很多技术细节,使得开发者可以很容易地在其基础上进行二次开发、修改、扩展和集成。
75
+
76
+ ## [7/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\theme.py
77
+
78
+ 该程序文件名为theme.py,主要功能为调节Gradio的全局样式。在该文件中,调节了Gradio的主题颜色、字体、阴影、边框、渐变等等样式。同时,该文件还添加了一些高级CSS样式,比如调整表格单元格的背景和边框,设定聊天气泡的圆角、最大宽度和阴影等等。如果CODE_HIGHLIGHT为True,则还进行了代码高亮显示。
79
+
80
+ ## [8/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\toolbox.py
81
+
82
+ 这是一个名为`toolbox.py`的源代码文件。该文件包含了一系列工具函数和装饰器,用于聊天Bot的开发和调试。其中有一些功能包括将输入参数进行重组、捕捉函数中的异常并记录到历史记录中、生成Markdown格式的聊天记录报告等。该文件中还包含了一些与转换Markdown文本相关的函数。
83
+
84
+ ## [9/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\crazy_utils.py
85
+
86
+ 这是一个Python程序文件 `crazy_utils.py`,它包含了两个函数:
87
+
88
+ - `input_clipping(inputs, history, max_token_limit)`:这个函数接收三个参数,inputs 是一个字符串,history 是一个列表,max_token_limit 是一个整数。它使用 `tiktoken` 、`numpy` 和 `toolbox` 模块,处理输入文本和历史记录,将其裁剪到指定的最大标记数,避免输入过长导致的性能问题。如果 inputs 长度不超过 max_token_limit 的一半,则只裁剪历史;否则,同时裁剪输入和历史。
89
+ - `request_gpt_model_in_new_thread_with_ui_alive(inputs, inputs_show_user, llm_kwargs, chatbot, history, sys_prompt, refresh_interval=0.2, handle_token_exceed=True, retry_times_at_unknown_error=2)`:这个函数接收八个参数,其中后三个是列表类型,其他为标量或句柄等。它提供对话窗口和刷新控制,执行 `predict_no_ui_long_connection` 方法,将输入数据发送至 GPT 模型并获取结果,如果子任务出错,返回相应的错误信息,否则返回结果。
90
+
91
+ ## [10/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\Latex全文润色.py
92
+
93
+ 这是一个名为"crazy_functions\Latex全文润色.py"的程序文件,其中包含了两个函数"Latex英文润色"和"Latex中文润色",以及其他辅助函数。这些函数能够对 Latex 项目进行润色处理,其中 "多文件润色" 函数是一个主要函数,它调用了其他辅助函数用于读取和处理 Latex 项目中的文件。函数使用了多线程和机器学习模型进行自然语言处理,对文件进行简化和排版来满足学术标准。注释已删除并可以在函数内部查找。
94
+
95
+ ## [11/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\Latex全文翻译.py
96
+
97
+ 这个程序文件包括一个用于对整个Latex项目进行翻译的函数 `Latex英译中` 和一个用于将中文翻译为英文的函数 `Latex中译英`。这两个函数都会尝试导入依赖库 tiktoken, 若无法导入则会提示用户安装。`Latex英译中` 函数会对 Latex 项目中的文件进行分离并去除注释,然后运行多线程翻译。`Latex中译英` 也做同样的事情,只不过是将中文翻译为英文。这个程序文件还包括其他一些帮助函数。
98
+
99
+ ## [12/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\__init__.py
100
+
101
+ 这是一个 Python 包,包名为 `crazy_functions`,在 `__init__.py` 文件中定义了一些函数,包含以下函数:
102
+
103
+ - `crazy_addition(a, b)`:对两个数进行加法运算,并将结果返回。
104
+ - `crazy_multiplication(a, b)`:对两个数进行乘法运算,并将结果返回。
105
+ - `crazy_subtraction(a, b)`:对两个数进行减法运算,并将结果返回。
106
+ - `crazy_division(a, b)`:对两个数进行除法运算,并将结果返回。
107
+ - `crazy_factorial(n)`:计算 `n` 的阶乘并返回结果。
108
+
109
+ 这些函数可能会有一些奇怪或者不符合常规的实现方式(由函数名可以看出来),所以这个包的名称为 `crazy_functions`,可能是暗示这些函数会有一些“疯狂”的实现方式。
110
+
111
+ ## [13/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\下载arxiv论文翻译摘要.py
112
+
113
+ 该程序实现了一个名为“下载arxiv论文并翻译摘要”的函数插件,作者是“binary-husky”。该函数的功能是,在输入一篇arxiv论文的链接后,提取摘要、下载PDF文档、翻译摘要为中文,并将翻译结果保存到文件中。程序使用了一些Python库,如requests、pdfminer和beautifulsoup4等。程序入口是名为“下载arxiv论文并翻译摘要”的函数,其中使用了自定义的辅助函数download_arxiv_和get_name。程序中还使用了其他非函数的辅助函数和变量,如update_ui、CatchException、report_exception和get_conf等。
114
+
115
+ ## [14/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\代码重写为全英文_多线程.py
116
+
117
+ 该文件是一个多线程Python脚本,包含多个函数和利用第三方库进行的API请求。主要功能是将给定文件夹内的Python代码文件中所有中文转化为英文,然后输出转化后的英文代码。重要的功能和步骤包括:
118
+
119
+ 1. 清空历史,以免输入溢出
120
+ 2. 尝试导入依赖,如果缺少依赖,则给出安装建议
121
+ 3. 集合文件
122
+ 4. 显示随意内容以防卡顿的感觉
123
+ 5. Token限制下的截断与处理
124
+ 6. 多线程操作请求转换中文变为英文的代码
125
+ 7. 所有线程同时开始执行任务函数
126
+ 8. 循环轮询各个线程是否执行完毕
127
+ 9. 把结果写入文件
128
+ 10. 备份一个文件
129
+
130
+ ## [15/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\总结word文档.py
131
+
132
+ 这是一个名为"总结word文档.py"的程序文件,使用python编写。该文件导入了"toolbox"和"crazy_utils"模块,实现了解析docx格式和doc格式的文件的功能。该文件包含了一个名为"解析docx"的函数,通过对文件内容应用自然语言处理技术,生成文章片段的中英文概述。具体实现过程中,该函数使用了"docx"模块和"win32com.client"模块来实现对docx和doc格式文件的解析,同时使用了"request_gpt_model_in_new_thread_with_ui_alive"函数来向GPT模型发起请求。最后,该文件还实现了一个名为"总结word文档"的函数来批量总结Word文档。
133
+
134
+ ## [16/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量Markdown翻译.py
135
+
136
+ 这个程序文件实现了一个批量Markdown翻译功能,可以将一个源代码项目中的Markdown文本翻译成指定语言(目前支持中<-英和英<-中)。程序主要分为三个函数,`PaperFileGroup`类用于处理长文本的拆分,`多文件翻译`是主要函数调用了`request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency`函数进行多线程翻译并输出结果,`Markdown英译中`和`Markdown中译外`分别是英译中和中译英的入口函数,用于解析项目路径和调用翻译函数。程序依赖于tiktoken等库实现。
137
+
138
+ ## [17/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量总结PDF文档.py
139
+
140
+ 这是一个名为“批量总结PDF文档”的Python脚本,包含了多个函数。其中有一个函数名为“clean_text”,可以对PDF提取出的原始文本进行清洗和格式化处理,将连字转换为其基本形式,并根据heuristic规则判断换行符是否是段落分隔,并相应地进行替换。另一个函数名为“解析PDF”,可以接收一个PDF文件清单,并对清单中的每一个PDF进行解析,提取��文本并调用“clean_text”函数进行清洗和格式化处理,然后向用户发送一个包含文章简介信息的问题并等待用户回答。最后,该脚本也包含一个名为“批量总结PDF文档”的主函数,其中调用了“解析PDF”函数来完成对PDF文件的批量处理。
141
+
142
+ ## [18/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量总结PDF文档pdfminer.py
143
+
144
+ 这个文件是一个Python模块,文件名为pdfminer.py,它定义了一个函数批量总结PDF文档。该函数接受一些参数,然后尝试导入pdfminer和beautifulsoup4库。该函数将读取pdf文件或tex文件中的内容,对其进行分析,并使用GPT模型进行自然语言摘要。文件中还有一个辅助函数readPdf,用于读取pdf文件中的内容。
145
+
146
+ ## [19/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量翻译PDF文档_多线程.py
147
+
148
+ 这是一个Python脚本,文件名是crazy_functions\批量翻译PDF文档_多线程.py。该脚本提供了一个名为“批量翻译PDF文档”的函数,可以批量翻译PDF文件并生成报告文件。该函数使用了多个模块和函数(如toolbox、crazy_utils、update_ui等),使用了Python的异常处理和多线程功能,还使用了一些文本处理函数和第三方库(如fitz和tiktoken)。在函数执行过程中,它会进行一些参数检查、读取和清理PDF文本、递归地切割PDF文件、获取文章meta信息、多线程翻译、整理报告格式等操作,并更新UI界面和生成报告文件。
149
+
150
+ ## [20/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\理解PDF文档内容.py
151
+
152
+ 这是一个解析PDF文件内容的Python程序,程序文件名为"理解PDF文档内容.py",程序主要由5个步骤组成:第0步是切割PDF文件;第1步是从摘要中提取高价值信息,放到history中;第2步是迭代地历遍整个文章,提取精炼信息;第3步是整理history;第4步是设置一个token上限,防止回答时Token溢出。程序主要用到了Python中的各种模块和函数库,如:toolbox, tiktoken, pymupdf等。
153
+
154
+ ## [21/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\生成函数注释.py
155
+
156
+ 这是一个名为"生成函数注释"的函数,带有一个装饰器"@CatchException",可以捕获异常。该函数接受文件路径、参数和聊天机器人等参数,用于对多个Python或C++文件进行函数注释,使用了"toolbox"和"crazy_utils"模块中的函数。该函数会逐个读取指定文件中的内容,并使用聊天机器人进行交互,向用户请求注释信息,然后将生成的注释与原文件内容一起输出到一个markdown表格中。最后,该函数返回一个字符串,指示任务是否已完成。另外还包含一个名为"批量生成函数注释"的函数,它与"生成函数注释"函数一起用于批量处理多个文件。
157
+
158
+ ## [22/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\解析项目源代码.py
159
+
160
+ 这个程序文件实现了对一个源代码项目进行分析的功能。其中,函数`解析项目本身`、`解析一个Python项目`、`解析一个C项目的头文件`、`解析一个C项目`、`解析一个Java项目`和`解析一个Rect项目`分别用于解析不同类型的项目。函数`解析源代码新`实现了对每一个源代码文件的分析,并将分析结果汇总,同时还实现了分组和迭代处理,提高了效率。最后,函数`write_results_to_file`将所有分析结果写入文件。中间,还用到了`request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency`和`request_gpt_model_in_new_thread_with_ui_alive`来完成请求和响应,并用`update_ui`实时更新界面。
161
+
162
+ ## [23/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\询问多个大语言模型.py
163
+
164
+ 这是一个Python程序,文件名为"crazy_functions\询问多个大语言模型.py"。该程序实现了一个同时向多个大语言模型询问的功能,接收用户输入文本以及模型参数,向ChatGPT和ChatGLM模型发出请求,并将对话记录显示在聊天框中,同时刷新界面。
165
+
166
+ ## [24/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\读文章写摘要.py
167
+
168
+ 该程序文件是一个Python模块,文件名为"读文章写摘要.py",主要包含两个函数:"解析Paper"和"读文章写摘要"。其中,"解析Paper"函数接受文件路径、参数等参数,逐个打印文件内容并使用GPT模型生成对该文件的摘要;"读文章写摘要"函数则接受一段文本内容和参数,将该文本内容及其所有.tex文件逐个传递给"解析Paper"函数进行处理,并使用GPT模型生成文章的中英文摘要。文件还导入了一些工具函数,如异常处理、信息上报和文件写入等。
169
+
170
+ ## [25/31] 请对下面��程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\谷歌检索小助手.py
171
+
172
+ 该文件代码包含了一个名为`get_meta_information`的函数和一个名为`谷歌检索小助手`的装饰器函数,用于从谷歌学术中抓取文章元信息,并从用户提供的搜索页面中分析所有文章的相关信息。该文件使用了许多第三方库,如requests、arxiv、BeautifulSoup等。其中`get_meta_information`函数中还定义了一个名为`string_similar`的辅助函数,用于比较字符串相似度。
173
+
174
+ ## [26/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\高级功能函数模板.py
175
+
176
+ 该程序文件是一个 Python 模块,包含一个名为“高阶功能模板函数”的函数。该函数接受多个参数,其中包括输入文本、GPT 模型参数、插件模型参数、聊天显示框、聊天历史等。 该函数的主要功能是根据输入文本,使用 GPT 模型生成一些问题,并等待用户回答这些问题(使用 Markdown 格式),然后将用户回答加入到聊天历史中,并更新聊天显示框。该函数还包含了一些异常处理和多线程的相关操作。该程序文件还引用了另一个 Python 模块中的两个函数,分别为“CatchException”和“update_ui”,并且还引用了一个名为“request_gpt_model_in_new_thread_with_ui_alive”的自定义函数。
177
+
178
+ ## [27/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_all.py
179
+
180
+ 这个文件是用来处理与LLM的交互的。包含两个函数,一个是 predict_no_ui_long_connection 用来处理长文本的输出,可以多线程调用;另一个是 predict 用来处理基础的对话功能。这个文件会导入其他文件中定义的方法进行调用,具体调用哪个方法取决于传入的参数。函数中还有一些装饰器和管理多线程的逻辑。
181
+
182
+ ## [28/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_chatglm.py
183
+
184
+ 这个程序文件实现了一个使用ChatGLM模型进行聊天的功能。具体实现过程是:首先进行初始化,然后使用GetGLMHandle类进行ChatGLM模型的加载和运行。predict_no_ui_long_connection函数用于多线程聊天,而predict函数用于单线程聊天,它们的不同之处在于前者不会更新UI界面,后者会。这个文件还导入了其他模块和库,例如transformers、time、importlib等,并使用了多进程Pipe。
185
+
186
+ ## [29/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_chatgpt.py
187
+
188
+ 这个程序文件是用于对话生成的,主要包含三个函数:predict、predict_no_ui、predict_no_ui_long_connection。其中,predict是用于普通对话的函数,具备完备的交互功能,但不具备多线程能力;predict_no_ui是高级实验性功能模块调用的函数,参数简单,可以多线程并行,方便实现复杂的功能逻辑;predict_no_ui_long_connection解决了predict_no_ui在处理长文档时容易断开连接的问题,同样支持多线程。程序中还包含一些常量和工具函数,用于整合信息,选择LLM模型,生成http请求,发送请求,接收响应等。它需要配置一个config文件,包含代理网址、API等敏感信息。
189
+
190
+ ## [30/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_tgui.py
191
+
192
+ 该程序文件实现了一个基于Websockets的文本生成服务和对话功能。其中,有三个函数:`run()`、`predict()`和`predict_no_ui_long_connection()`。`run()`函数用于连接到Websocket服务并生成文本结果;`predict()`函数用于将用户输入作为文本生成的输入,同时在UI上显示对话历史记录,并在不断更新UI的过程中不断更新生成的文本输出;`predict_no_ui_long_connection()`函数与`predict()`函数类似,但没有UI,并在一段时间内返回单个生成的文本。整个程序还引入了多个Python模块来完成相关功能,例如`asyncio`、`websockets`、`json`等等。
193
+
194
+ ## 根据以上分析,对程序的整体功能和构架重新做出概括。然后用一张markdown表格整理每个文件的功能(包括check_proxy.py, colorful.py, config.py, config_private.py, core_functional.py, crazy_functional.py, main.py, theme.py, toolbox.py, crazy_functions\crazy_utils.py, crazy_functions\Latex全文润色.py, crazy_functions\Latex全文翻译.py, crazy_functions\__init__.py, crazy_functions\下载arxiv论文翻译摘要.py, crazy_functions\代码重写为全英文_多线程.py, crazy_functions\总结word文档.py)。
195
+
196
+ 程序功能概括:该程序是一个聊天机器人,可以通过 Web 界面与用户进行交互。它包含了丰富的功能,如文本润色、翻译、代码重写、在线查找等,并且支持多线程处理。用户可以通过 Gradio 框架提供的 Web 界面进行交互,程序还提供了一些调试工具,如toolbox 模块,方便程序开发和调试。
197
+
198
+ ���表概述了每个文件的功能:
199
+
200
+ | 文件名 | 功能 |
201
+ | ----------------------------------------------------------- | ------------------------------------------------------------ |
202
+ | check_proxy.py | 检查代理是否可用 |
203
+ | colorful.py | 用于打印文本的字体颜色输出模块 |
204
+ | config.py | 用于程序中的各种设置,如并行线程数量和重试次数的限制等 |
205
+ | config_private.py | 配置API_KEY和代理信息的文件 |
206
+ | core_functional.py | 包含具体的文本处理功能的模块 |
207
+ | crazy_functional.py | 包括各种插件函数的模块,提供了多种文本处理功能 |
208
+ | main.py | 包含 Chatbot 机器人主程序的模块 |
209
+ | theme.py | 用于调节全局样式的模块 |
210
+ | toolbox.py | 包含工具函数和装饰器,用于聊天Bot的开发和调试 |
211
+ | crazy_functions\crazy_utils.py | 包含一些辅助函数,如文本裁剪和消息捕捉等 |
212
+ | crazy_functions\Latex全文润色.py | 对 Latex 项目进行润色处理的功能模块 |
213
+ | crazy_functions\Latex全文翻译.py | 对 Latex 项目进行翻译的功能模块 |
214
+ | crazy_functions\__init__.py | 定义一些奇特的数学函数等 |
215
+ | crazy_functions\下载arxiv论文翻译摘要.py | 下载 Arxiv 论文并翻译摘要的功能模块 |
216
+ | crazy_functions\代码重写为全英文_多线程.py | 将Python程序中所有中文转化为英文的功能模块 |
217
+ | crazy_functions\总结word文档.py | 解析 docx 和 doc 格式的文件,生成文章片段的中英文概述的功能模块 |
218
+
219
+ ## 根据以上分析,对程序的整体功能和构架重新做出概括。然后用一张markdown表格整理每个文件的功能(包括check_proxy.py, colorful.py, config.py, config_private.py, core_functional.py, crazy_functional.py, main.py, theme.py, toolbox.py, crazy_functions\crazy_utils.py, crazy_functions\Latex全文润色.py, crazy_functions\Latex全文翻译.py, crazy_functions\__init__.py, crazy_functions\下载arxiv论文翻译摘要.py, crazy_functions\代码重写为全英文_多线程.py, crazy_functions\总结word文档.py, crazy_functions\批量Markdown翻译.py, crazy_functions\批量总结PDF文档.py, crazy_functions\批量总结PDF文档pdfminer.py, crazy_functions\批量翻译PDF文档_多线程.py, crazy_functions\理解PDF文档内容.py, crazy_functions\生成函数注释.py, crazy_functions\解析项目源代码.py, crazy_functions\询问多个大语言模型.py, crazy_functions\读文章写摘要.py, crazy_functions\谷歌检索小助手.py, crazy_functions\高级功能函数模板.py, request_llm\bridge_all.py, request_llm\bridge_chatglm.py, request_llm\bridge_chatgpt.py, request_llm\bridge_tgui.py)。
220
+
221
+ 根据以上分析,整个程序是一个集成了多个有用工具和功能的文本处理和生成工具,提供了多种在不同场景下使用的功能,包括但不限于对话生成、文本摘要、PDF文件批量处理、代码翻译和实用工具等。主要的Python模块包括"toolbox.py"、"config.py"、"core_functional.py"和"crazy_functional.py"等,并且还使用了许多第三方库和模块实现相关功能。以下是每个程序文件的功能:
222
+
223
+ | 文件名 | 文件功能 |
224
+ | --- | --- |
225
+ | check_proxy.py | 用于检查代理的正确性和可用性 |
226
+ | colorful.py | 包含不同预设置颜色的常量,并用于多种UI元素 |
227
+ | config.py | 用于全局配置的类 |
228
+ | config_private.py | 与config.py文件一起使用的另一个配置文件,用于更改私密信息 |
229
+ | core_functional.py | 包含一些TextFunctional类和基础功能函数 |
230
+ | crazy_functional.py | 包含大量高级功能函数和实验性的功能函数 |
231
+ | main.py | 程序的主入口,包含GUI主窗口和主要的UI管理功能 |
232
+ | theme.py | 包含一些预设置主题的颜色 |
233
+ | toolbox.py | 提供了一些有用的工具函数 |
234
+ | crazy_functions\crazy_utils.py | 包含一些用于实现高级功能的辅助函数 |
235
+ | crazy_functions\Latex全文润色.py | 实现了对LaTeX文件中全文的润色和格式化功能 |
236
+ | crazy_functions\Latex全文翻译.py | 实现了对LaTeX文件中的内容进行翻译的功能 |
237
+ | crazy_functions\_\_init\_\_.py | 用于导入crazy_functional.py中的功能函数 |
238
+ | crazy_functions\下载arxiv论文翻译摘要.py | 从Arxiv上下载论文并提取重要信息 |
239
+ | crazy_functions\代码重写为全英文_多线程.py | 针对中文Python文件,将其翻译为全英文 |
240
+ | crazy_functions\总结word文档.py | 提取Word文件的重要内容来生成摘要 |
241
+ | crazy_functions\批量Markdown翻译.py | 批量翻译Markdown文件 |
242
+ | crazy_functions\批量总结PDF文档.py | 批量从PDF文件中提取摘要 |
243
+ | crazy_functions\批量总结PDF文档pdfminer.py | 批量从PDF文件中提取摘要 |
244
+ | crazy_functions\批量翻译PDF文档_多线程.py | 批量翻译PDF文件 |
245
+ | crazy_functions\理解PDF文档内容.py | 批量分析PDF文件并提取摘要 |
246
+ | crazy_functions\生成函数注释.py | 自动生成Python文件中函数的注释 |
247
+ | crazy_functions\解析项目源代码.py | 解析并分析给定项目的源代码 |
248
+ | crazy_functions\询问多个大语言模型.py | 向多个大语言模型询问输入文本并进行处理 |
249
+ | crazy_functions\读文献写摘要.py | 根据用户输入读取文献内容并生成摘要 |
250
+ | crazy_functions\谷歌检索小助手.py | 利用谷歌学术检索用户提供的论文信息并提取相关信息 |
251
+ | crazy_functions\高级功能函数模板.py | 实现高级功能的模板函数 |
252
+ | request_llm\bridge_all.py | 处理与LLM的交互 |
253
+ | request_llm\bridge_chatglm.py | 使用ChatGLM模型进行聊天 |
254
+ | request_llm\bridge_chatgpt.py | 实现对话生成的各项功能 |
255
+ | request_llm\bridge_tgui.py | 在Websockets中与用户进行交互并生成文本输出 |
256
+
img/README_EN.md DELETED
@@ -1,294 +0,0 @@
1
- # ChatGPT Academic Optimization
2
- > **Note**
3
- >
4
- > This English readme is automatically generated by the markdown translation plugin in this project, and may not be 100% correct.
5
- >
6
-
7
-
8
- **If you like this project, please give it a star. If you have come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request (to the `dev` branch).**
9
-
10
- > **Note**
11
- >
12
- > 1. Please note that only function plugins (buttons) marked in **red** support reading files, and some plugins are located in the **dropdown menu** in the plugin area. Additionally, we welcome and process PRs for any new plugins with the **highest priority**!
13
- >
14
- > 2. The functions of each file in this project are detailed in the self-translation report [self_analysis.md](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A). With the version iteration, you can click on a relevant function plugin at any time to call GPT to regenerate the self-analysis report for the project. Commonly asked questions are summarized in the [`wiki`](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98).
15
- >
16
- > 3. If you are not used to the function, comments or interface with some Chinese names, you can click on the relevant function plugin at any time to call ChatGPT to generate the source code of the project in English.
17
-
18
- <div align="center">
19
-
20
- Function | Description
21
- --- | ---
22
- One-click refinement | Supports one-click refinement, one-click searching for grammatical errors in papers.
23
- One-click translation between Chinese and English | One-click translation between Chinese and English.
24
- One-click code interpretation | Can correctly display and interpret the code.
25
- [Custom shortcuts](https://www.bilibili.com/video/BV14s4y1E7jN) | Supports custom shortcuts.
26
- [Configure proxy server](https://www.bilibili.com/video/BV1rc411W7Dr) | Supports configuring proxy server.
27
- Modular design | Supports custom high-order experimental features and [function plug-ins], and plug-ins support [hot update](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97).
28
- [Self-program analysis](https://www.bilibili.com/video/BV1cj411A7VW) | [Function Plug-in] [One-Key Understanding](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A) the source code of this project.
29
- [Program analysis](https://www.bilibili.com/video/BV1cj411A7VW) | [Function Plug-in] One-click can analyze other Python/C/C++/Java/Golang/Lua/Rect project trees.
30
- Read papers | [Function Plug-in] One-click reads the full text of a latex paper and generates an abstract.
31
- Latex full-text translation/refinement | [Function Plug-in] One-click translates or refines a latex paper.
32
- Batch annotation generation | [Function Plug-in] One-click generates function annotations in batches.
33
- Chat analysis report generation | [Function Plug-in] Automatically generate summary reports after running.
34
- [Arxiv assistant](https://www.bilibili.com/video/BV1LM4y1279X) | [Function Plug-in] Enter the arxiv paper url and you can translate the abstract and download the PDF with one click.
35
- [PDF paper full-text translation function](https://www.bilibili.com/video/BV1KT411x7Wn) | [Function Plug-in] Extract title and abstract of PDF papers + translate full text (multi-threaded).
36
- [Google Scholar integration assistant](https://www.bilibili.com/video/BV19L411U7ia) (Version>=2.45) | [Function Plug-in] Given any Google Scholar search page URL, let GPT help you choose interesting articles.
37
- Formula display | Can simultaneously display the tex form and rendering form of formulas.
38
- Image display | Can display images in Markdown.
39
- Multithreaded function plug-in support | Supports multi-threaded calling of chatgpt, one-click processing of massive texts or programs.
40
- Support for markdown tables output by GPT | Can output markdown tables that support GPT.
41
- Start dark gradio theme [theme](https://github.com/binary-husky/chatgpt_academic/issues/173) | Add ```/?__dark-theme=true``` to the browser URL to switch to the dark theme.
42
- Huggingface free scientific online experience](https://huggingface.co/spaces/qingxu98/gpt-academic) | After logging in to Huggingface, copy [this space](https://huggingface.co/spaces/qingxu98/gpt-academic).
43
- [Mixed support for multiple LLM models](https://www.bilibili.com/video/BV1EM411K7VH/) ([v3.0 branch](https://github.com/binary-husky/chatgpt_academic/tree/v3.0) in testing) | It must feel great to be served by both ChatGPT and [Tsinghua ChatGLM](https://github.com/THUDM/ChatGLM-6B)!
44
- Compatible with [TGUI](https://github.com/oobabooga/text-generation-webui) to access more language models | Access to opt-1.3b, galactica-1.3b and other models ([v3.0 branch](https://github.com/binary-husky/chatgpt_academic/tree/v3.0) under testing).
45
- … | ...
46
-
47
- </div>
48
-
49
- <!-- - New interface (left: master branch, right: dev development frontier) -->
50
- - New interface (modify the `LAYOUT` option in `config.py` to switch between "left and right layout" and "up and down layout").
51
- <div align="center">
52
- <img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
53
- </div>
54
-
55
- - All buttons are dynamically generated by reading `functional.py`, and custom functions can be added freely, freeing up the clipboard.
56
- <div align="center">
57
- <img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
58
- </div>
59
-
60
- - Refinement/Correction
61
- <div align="center">
62
- <img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
63
- </div>
64
-
65
- - Supports markdown tables output by GPT.
66
- <div align="center">
67
- <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
68
- </div>
69
-
70
- - If the output contains formulas, both the tex form and the rendering form are displayed simultaneously for easy copying and reading.
71
- <div align="center">
72
- <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
73
- </div>
74
-
75
- - Don't want to read project code? Let chatgpt boast about the whole project.
76
- <div align="center">
77
- <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
78
- </div>
79
-
80
- - Multiple large language models mixed calling. ([v3.0 branch](https://github.com/binary-husky/chatgpt_academic/tree/v3.0) in testing)
81
-
82
-
83
- ## Running Directly (Windows, Linux or MacOS)
84
-
85
- ### 1. Download the Project
86
- ```sh
87
- git clone https://github.com/binary-husky/chatgpt_academic.git
88
- cd chatgpt_academic
89
- ```
90
-
91
- ### 2. Configure API_KEY and Proxy Settings
92
-
93
- In `config.py`, configure the overseas Proxy and OpenAI API KEY, as follows:
94
- ```
95
- 1. If you are in China, you need to set an overseas proxy to use the OpenAI API smoothly. Please read the instructions in config.py carefully (1. Modify the USE_PROXY to True; 2. Modify the proxies according to the instructions).
96
- 2. Configure OpenAI API KEY. You need to register on the OpenAI official website and obtain an API KEY. Once you get the API KEY, configure it in the config.py file.
97
- 3. Issues related to proxy network (network timeout, proxy not working) are summarized to https://github.com/binary-husky/chatgpt_academic/issues/1
98
- ```
99
- (Note: When the program is running, it will first check whether there is a private configuration file named `config_private.py`, and use the configuration in it to overwrite the same name configuration in `config.py`. Therefore, if you can understand our configuration reading logic, we strongly recommend that you create a new configuration file next to `config.py` named `config_private.py` and transfer (copy) the configuration in `config.py` to `config_private.py`. `config_private.py` is not managed by Git, which can make your privacy information more secure.)
100
-
101
- ### 3. Install Dependencies
102
- ```sh
103
- # (Option 1) Recommended
104
- python -m pip install -r requirements.txt
105
-
106
- # (Option 2) If you use anaconda, the steps are also similar:
107
- # (Option 2.1) conda create -n gptac_venv python=3.11
108
- # (Option 2.2) conda activate gptac_venv
109
- # (Option 2.3) python -m pip install -r requirements.txt
110
-
111
- # Note: Use the official pip source or the Ali pip source. Other pip sources (such as some university pips) may have problems. Temporary substitution method:
112
- # python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
113
- ```
114
-
115
- ### 4. Run
116
- ```sh
117
- python main.py
118
- ```
119
-
120
- ### 5. Test Experimental Features
121
- ```
122
- - Test C++ Project Header Analysis
123
- In the input area, enter `./crazy_functions/test_project/cpp/libJPG` , and then click "[Experiment] Parse the entire C++ project (input inputs the root path of the project)"
124
- - Test Writing Abstracts for Latex Projects
125
- In the input area, enter `./crazy_functions/test_project/latex/attention` , and then click "[Experiment] Read the tex paper and write an abstract (input inputs the root path of the project)"
126
- - Test Python Project Analysis
127
- In the input area, enter `./crazy_functions/test_project/python/dqn` , and then click "[Experiment] Parse the entire py project (input inputs the root path of the project)"
128
- - Test Self-code Interpretation
129
- Click "[Experiment] Please analyze and deconstruct this project itself"
130
- - Test Experimental Function Template (asking GPT what happened in history today), you can implement more complex functions based on this template function
131
- Click "[Experiment] Experimental function template"
132
- ```
133
-
134
- ## Use Docker (Linux)
135
-
136
- ``` sh
137
- # Download Project
138
- git clone https://github.com/binary-husky/chatgpt_academic.git
139
- cd chatgpt_academic
140
- # Configure Overseas Proxy and OpenAI API KEY
141
- Configure config.py with any text editor
142
- # Installation
143
- docker build -t gpt-academic .
144
- # Run
145
- docker run --rm -it --net=host gpt-academic
146
-
147
- # Test Experimental Features
148
- ## Test Self-code Interpretation
149
- Click "[Experiment] Please analyze and deconstruct this project itself"
150
- ## Test Experimental Function Template (asking GPT what happened in history today), you can implement more complex functions based on this template function
151
- Click "[Experiment] Experimental function template"
152
- ## (Please note that when running in docker, you need to pay extra attention to file access rights issues of the program.)
153
- ## Test C++ Project Header Analysis
154
- In the input area, enter ./crazy_functions/test_project/cpp/libJPG , and then click "[Experiment] Parse the entire C++ project (input inputs the root path of the project)"
155
- ## Test Writing Abstracts for Latex Projects
156
- In the input area, enter ./crazy_functions/test_project/latex/attention , and then click "[Experiment] Read the tex paper and write an abstract (input inputs the root path of the project)"
157
- ## Test Python Project Analysis
158
- In the input area, enter ./crazy_functions/test_project/python/dqn , and then click "[Experiment] Parse the entire py project (input inputs the root path of the project)"
159
-
160
- ```
161
-
162
- ## Other Deployment Methods
163
- - Use WSL2 (Windows Subsystem for Linux subsystem)
164
- Please visit [Deploy Wiki-1] (https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
165
-
166
- - nginx remote deployment
167
- Please visit [Deploy Wiki-2] (https://github.com/binary-husky/chatgpt_academic/wiki/%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E7%9A%84%E6%8C%87%E5%AF%BC)
168
-
169
-
170
- ## Customizing New Convenient Buttons (Academic Shortcut Key Customization)
171
- Open functional.py and add the entry as follows, and then restart the program. (If the button has been successfully added and is visible, both the prefix and suffix support hot modification and take effect without restarting the program.)
172
-
173
- For example,
174
- ```
175
- "Super English to Chinese Translation": {
176
-
177
- # Prefix, which will be added before your input. For example, it is used to describe your requirements, such as translation, code interpretation, polishing, etc.
178
- "Prefix": "Please translate the following content into Chinese, and then use a markdown table to explain each proprietary term in the text:\n\n",
179
-
180
- # Suffix, which will be added after your input. For example, in conjunction with the prefix, you can bracket your input in quotes.
181
- "Suffix": "",
182
-
183
- },
184
- ```
185
- <div align="center">
186
- <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
187
- </div>
188
-
189
-
190
- If you invent a more user-friendly academic shortcut key, welcome to post an issue or pull request!
191
-
192
- ## Configure Proxy
193
- ### Method 1: General Method
194
- Modify the port and proxy software corresponding in ```config.py```
195
-
196
- <div align="center">
197
- <img src="https://user-images.githubusercontent.com/96192199/226571294-37a47cd9-4d40-4c16-97a2-d360845406f7.png" width="500" >
198
- <img src="https://user-images.githubusercontent.com/96192199/226838985-e5c95956-69c2-4c23-a4dd-cd7944eeb451.png" width="500" >
199
- </div>
200
-
201
-
202
- After configuring, you can use the following command to test whether the proxy works. If everything is normal, the code below will output the location of your proxy server:
203
-
204
- ```
205
- python check_proxy.py
206
- ```
207
-
208
- ### Method Two: Pure Beginner Tutorial
209
- [Pure Beginner Tutorial](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
210
-
211
- ## Compatibility Testing
212
-
213
- ### Image Display:
214
-
215
- <div align="center">
216
- <img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
217
- </div>
218
-
219
-
220
- ### If the program can read and analyze itself:
221
-
222
- <div align="center">
223
- <img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
224
- </div>
225
-
226
- <div align="center">
227
- <img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
228
- </div>
229
-
230
- ### Any other Python/Cpp project analysis:
231
- <div align="center">
232
- <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
233
- </div>
234
-
235
- <div align="center">
236
- <img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
237
- </div>
238
-
239
- ### Latex paper reading comprehension and abstract generation with one click
240
- <div align="center">
241
- <img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
242
- </div>
243
-
244
- ### Automatic Report Generation
245
- <div align="center">
246
- <img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
247
- <img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
248
- <img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
249
- </div>
250
-
251
- ### Modular Function Design
252
- <div align="center">
253
- <img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
254
- <img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
255
- </div>
256
-
257
-
258
- ### Translating source code to English
259
-
260
- <div align="center">
261
- <img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
262
- </div>
263
-
264
- ## Todo and Version Planning:
265
-
266
- - version 3 (Todo):
267
- - - Support for gpt4 and other llm
268
- - version 2.4+ (Todo):
269
- - - Summary of long text and token overflow problems in large project source code
270
- - - Implementation of project packaging and deployment
271
- - - Function plugin parameter interface optimization
272
- - - Self-updating
273
- - version 2.4: (1) Added PDF full-text translation function; (2) Added input area switching function; (3) Added vertical layout option; (4) Optimized multi-threaded function plugin.
274
- - version 2.3: Enhanced multi-threaded interactivity
275
- - version 2.2: Function plug-in supports hot reloading
276
- - version 2.1: Collapsible layout
277
- - version 2.0: Introduction of modular function plugins
278
- - version 1.0: Basic functions
279
-
280
- ## References and Learning
281
-
282
-
283
- ```
284
- The code refers to the design of many other excellent projects, mainly including:
285
-
286
- # Reference Project 1: Referenced the method of reading OpenAI json, recording historical inquiry records, and using gradio queue in ChuanhuChatGPT
287
- https://github.com/GaiZhenbiao/ChuanhuChatGPT
288
-
289
- # Reference Project 2:
290
- https://github.com/THUDM/ChatGLM-6B
291
-
292
- ```
293
-
294
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py CHANGED
@@ -1,188 +1,202 @@
1
  import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
2
- import gradio as gr
3
- from request_llm.bridge_chatgpt import predict
4
- from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, DummyWith
5
 
6
- # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
7
- proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \
8
- get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY')
 
 
 
 
9
 
10
- # 如果WEB_PORT是-1, 则随机选取WEB端口
11
- PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
12
- if not AUTHENTICATION: AUTHENTICATION = None
13
 
14
- from check_proxy import get_current_version
15
- initial_prompt = "Serve me as a writing and programming assistant."
16
- title_html = f"<h1 align=\"center\">ChatGPT 学术优化 {get_current_version()}</h1>"
17
- description = """代码开源和更新[地址🚀](https://github.com/binary-husky/chatgpt_academic),感谢热情的[开发者们❤️](https://github.com/binary-husky/chatgpt_academic/graphs/contributors)"""
18
 
19
- # 问询记录, python 版本建议3.9+(越新越好)
20
- import logging
21
- os.makedirs("gpt_log", exist_ok=True)
22
- try:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO, encoding="utf-8")
23
- except:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO)
24
- print("所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!")
25
 
26
- # 一些普通功能模块
27
- from core_functional import get_core_functions
28
- functional = get_core_functions()
29
 
30
- # 高级函数插件
31
- from crazy_functional import get_crazy_functions
32
- crazy_fns = get_crazy_functions()
33
 
34
- # 处理markdown文本格式的转变
35
- gr.Chatbot.postprocess = format_io
36
 
37
- # 做一些外观色彩上的调整
38
- from theme import adjust_theme, advanced_css
39
- set_theme = adjust_theme()
40
 
41
- # 代理与自动更新
42
- from check_proxy import check_proxy, auto_update
43
- proxy_info = check_proxy(proxies)
44
 
45
- gr_L1 = lambda: gr.Row().style()
46
- gr_L2 = lambda scale: gr.Column(scale=scale)
47
- if LAYOUT == "TOP-DOWN":
48
- gr_L1 = lambda: DummyWith()
49
- gr_L2 = lambda scale: gr.Row()
50
- CHATBOT_HEIGHT /= 2
51
 
52
- cancel_handles = []
53
- with gr.Blocks(title="ChatGPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
54
- gr.HTML(title_html)
55
- cookies = gr.State({'api_key': API_KEY, 'llm_model': LLM_MODEL})
56
- with gr_L1():
57
- with gr_L2(scale=2):
58
- chatbot = gr.Chatbot()
59
- chatbot.style(height=CHATBOT_HEIGHT)
60
- history = gr.State([])
61
- with gr_L2(scale=1):
62
- with gr.Accordion("输入区", open=True) as area_input_primary:
63
- with gr.Row():
64
- txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
65
- with gr.Row():
66
- submitBtn = gr.Button("提交", variant="primary")
67
- with gr.Row():
68
- resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
69
- stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
70
- with gr.Row():
71
- status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}")
72
- with gr.Accordion("基础功能区", open=True) as area_basic_fn:
73
- with gr.Row():
74
- for k in functional:
75
- variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
76
- functional[k]["Button"] = gr.Button(k, variant=variant)
77
- with gr.Accordion("函数插件区", open=True) as area_crazy_fn:
78
- with gr.Row():
79
- gr.Markdown("注意:以下“红颜色”标识的函数插件需从输入区读取路径作为参数.")
80
- with gr.Row():
81
- for k in crazy_fns:
82
- if not crazy_fns[k].get("AsButton", True): continue
83
- variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
84
- crazy_fns[k]["Button"] = gr.Button(k, variant=variant)
85
- crazy_fns[k]["Button"].style(size="sm")
86
- with gr.Row():
87
- with gr.Accordion("解析任意code项目", open=True):
88
- gr.Markdown("输入时用逗号隔开, `*`代表通配符, 加了`^`代表不匹配<br>例如: `*.c, ^*.cpp, config.toml, ^README.md`")
89
- with gr.Row():
90
- txt_pattern = gr.Textbox(show_label=False, placeholder="输入框为空则代表匹配所有文件").style(container=False)
91
- code_plugin_name = "解析任意code项目"
92
- variant = crazy_fns[code_plugin_name]["Color"] if "Color" in crazy_fns[code_plugin_name] else "secondary"
93
- crazy_fns[code_plugin_name]["Button"] = gr.Button(code_plugin_name, variant=variant)
94
- crazy_fns[code_plugin_name]["Button"].style(size="sm")
95
- with gr.Row():
96
- with gr.Accordion("更多函数插件", open=True):
97
- dropdown_fn_list = [k for k in crazy_fns.keys() if not crazy_fns[k].get("AsButton", True)]
98
- dropdown_fn_list.remove(code_plugin_name)
99
- with gr.Column(scale=1):
100
- dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(container=False)
101
- with gr.Column(scale=1):
102
- switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
103
- with gr.Row():
104
- with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up:
105
- file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
106
- with gr.Accordion("展开SysPrompt & 交互界面布局 & Github地址", open=(LAYOUT == "TOP-DOWN")):
107
- system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
108
- top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
109
- temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
110
- checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "底部输入区"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区")
111
- gr.Markdown(description)
112
- with gr.Accordion("备选输入区", open=True, visible=False) as area_input_secondary:
113
- with gr.Row():
114
- txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False)
115
- with gr.Row():
116
- submitBtn2 = gr.Button("提交", variant="primary")
117
- with gr.Row():
118
- resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
119
- stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
120
- # 功能区显示开关与功能区的互动
121
- def fn_area_visibility(a):
122
- ret = {}
123
- ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
124
- ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
125
- ret.update({area_input_primary: gr.update(visible=("底部输入区" not in a))})
126
- ret.update({area_input_secondary: gr.update(visible=("底部输入区" in a))})
127
- if "底部输入区" in a: ret.update({txt: gr.update(value="")})
128
- return ret
129
- checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2] )
130
- # 整理反复出现的控件句柄组合
131
- input_combo = [cookies, txt, txt2, top_p, temperature, chatbot, history, system_prompt, txt_pattern]
132
- output_combo = [cookies, chatbot, history, status]
133
- predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=input_combo, outputs=output_combo)
134
- # 提交按钮、重置按钮
135
- cancel_handles.append(txt.submit(**predict_args))
136
- cancel_handles.append(txt2.submit(**predict_args))
137
- cancel_handles.append(submitBtn.click(**predict_args))
138
- cancel_handles.append(submitBtn2.click(**predict_args))
139
- resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
140
- resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
141
- # 基础功能区的回调函数注册
142
- for k in functional:
143
- click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  cancel_handles.append(click_handle)
145
- # 文件上传区,接收文件后与chatbot的互动
146
- file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
147
- # 函数插件-固定按钮区
148
- for k in crazy_fns:
149
- if not crazy_fns[k].get("AsButton", True): continue
150
- click_handle = crazy_fns[k]["Button"].click(ArgsGeneralWrapper(crazy_fns[k]["Function"]), [*input_combo, gr.State(PORT)], output_combo)
 
 
 
 
151
  click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
 
 
 
152
  cancel_handles.append(click_handle)
153
- # 函数插件-解析任意code项目
154
- click_handle = crazy_fns[code_plugin_name]["Button"].click(ArgsGeneralWrapper(crazy_fns[code_plugin_name]["Function"]), [*input_combo, gr.State(PORT)], output_combo)
155
- click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
156
- cancel_handles.append(click_handle)
157
- # 函数插件-下拉菜单与随变按钮的互动
158
- def on_dropdown_changed(k):
159
- variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
160
- return {switchy_bt: gr.update(value=k, variant=variant)}
161
- dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt] )
162
- # 随变按钮的回调函数注册
163
- def route(k, *args, **kwargs):
164
- if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
165
- yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
166
- click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo)
167
- click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
168
- # def expand_file_area(file_upload, area_file_up):
169
- # if len(file_upload)>0: return {area_file_up: gr.update(open=True)}
170
- # click_handle.then(expand_file_area, [file_upload, area_file_up], [area_file_up])
171
- cancel_handles.append(click_handle)
172
- # 终止按钮的回调函数注册
173
- stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
174
- stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
175
- # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
176
- def auto_opentab_delay():
177
- import threading, webbrowser, time
178
- print(f"如果浏览器没有自动打开,请复制并转到以下URL:")
179
- print(f"\t(亮色主题): http://localhost:{PORT}")
180
- print(f"\t(暗色主题): http://localhost:{PORT}/?__dark-theme=true")
181
- def open():
182
- time.sleep(2) # 打开浏览器
183
- webbrowser.open_new_tab(f"http://localhost:{PORT}/?__dark-theme=true")
184
- threading.Thread(target=open, name="open-browser", daemon=True).start()
185
- threading.Thread(target=auto_update, name="self-upgrade", daemon=True).start()
186
 
187
- auto_opentab_delay()
188
- demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION)
 
1
  import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
 
 
 
2
 
3
+ def main():
4
+ import gradio as gr
5
+ from request_llm.bridge_all import predict
6
+ from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, DummyWith
7
+ # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
8
+ proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY, AVAIL_LLM_MODELS = \
9
+ get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY', 'AVAIL_LLM_MODELS')
10
 
11
+ # 如果WEB_PORT是-1, 则随机选取WEB端口
12
+ PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
13
+ if not AUTHENTICATION: AUTHENTICATION = None
14
 
15
+ from check_proxy import get_current_version
16
+ initial_prompt = "Serve me as a writing and programming assistant."
17
+ title_html = f"<h1 align=\"center\">ChatGPT 学术优化 {get_current_version()}</h1>"
18
+ description = """代码开源和更新[地址🚀](https://github.com/binary-husky/chatgpt_academic),感谢热情的[开发者们❤️](https://github.com/binary-husky/chatgpt_academic/graphs/contributors)"""
19
 
20
+ # 问询记录, python 版本建议3.9+(越新越好)
21
+ import logging
22
+ os.makedirs("gpt_log", exist_ok=True)
23
+ try:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO, encoding="utf-8")
24
+ except:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO)
25
+ print("所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!")
26
 
27
+ # 一些普通功能模块
28
+ from core_functional import get_core_functions
29
+ functional = get_core_functions()
30
 
31
+ # 高级函数插件
32
+ from crazy_functional import get_crazy_functions
33
+ crazy_fns = get_crazy_functions()
34
 
35
+ # 处理markdown文本格式的转变
36
+ gr.Chatbot.postprocess = format_io
37
 
38
+ # 做一些外观色彩上的调整
39
+ from theme import adjust_theme, advanced_css
40
+ set_theme = adjust_theme()
41
 
42
+ # 代理与自动更新
43
+ from check_proxy import check_proxy, auto_update, warm_up_modules
44
+ proxy_info = check_proxy(proxies)
45
 
46
+ gr_L1 = lambda: gr.Row().style()
47
+ gr_L2 = lambda scale: gr.Column(scale=scale)
48
+ if LAYOUT == "TOP-DOWN":
49
+ gr_L1 = lambda: DummyWith()
50
+ gr_L2 = lambda scale: gr.Row()
51
+ CHATBOT_HEIGHT /= 2
52
 
53
+ cancel_handles = []
54
+ with gr.Blocks(title="ChatGPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
55
+ gr.HTML(title_html)
56
+ cookies = gr.State({'api_key': API_KEY, 'llm_model': LLM_MODEL})
57
+ with gr_L1():
58
+ with gr_L2(scale=2):
59
+ chatbot = gr.Chatbot()
60
+ chatbot.style(height=CHATBOT_HEIGHT)
61
+ history = gr.State([])
62
+ with gr_L2(scale=1):
63
+ with gr.Accordion("输入区", open=True) as area_input_primary:
64
+ with gr.Row():
65
+ txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
66
+ with gr.Row():
67
+ submitBtn = gr.Button("提交", variant="primary")
68
+ with gr.Row():
69
+ resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
70
+ stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
71
+ clearBtn = gr.Button("清除", variant="secondary", visible=False); clearBtn.style(size="sm")
72
+ with gr.Row():
73
+ status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}")
74
+ with gr.Accordion("基础功能区", open=True) as area_basic_fn:
75
+ with gr.Row():
76
+ for k in functional:
77
+ variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
78
+ functional[k]["Button"] = gr.Button(k, variant=variant)
79
+ with gr.Accordion("函数插件区", open=True) as area_crazy_fn:
80
+ with gr.Row():
81
+ gr.Markdown("注意:以下“红颜色”标识的函数插件需从输入区读取路径作为参数.")
82
+ with gr.Row():
83
+ for k in crazy_fns:
84
+ if not crazy_fns[k].get("AsButton", True): continue
85
+ variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
86
+ crazy_fns[k]["Button"] = gr.Button(k, variant=variant)
87
+ crazy_fns[k]["Button"].style(size="sm")
88
+ with gr.Row():
89
+ with gr.Accordion("解析任意code项目", open=True):
90
+ gr.Markdown("输入时用逗号隔开, `*`代表通配符, 加了`^`代表不匹配<br>例如: `*.c, ^*.cpp, config.toml, ^README.md`")
91
+ with gr.Row():
92
+ txt_pattern = gr.Textbox(show_label=False, placeholder="输入框为空则代表匹配所有文件").style(container=False)
93
+ code_plugin_name = "解析任意code项目"
94
+ variant = crazy_fns[code_plugin_name]["Color"] if "Color" in crazy_fns[code_plugin_name] else "secondary"
95
+ crazy_fns[code_plugin_name]["Button"] = gr.Button(code_plugin_name, variant=variant)
96
+ crazy_fns[code_plugin_name]["Button"].style(size="sm")
97
+ with gr.Row():
98
+ with gr.Accordion("更多��数插件", open=True):
99
+ dropdown_fn_list = [k for k in crazy_fns.keys() if not crazy_fns[k].get("AsButton", True)]
100
+ with gr.Column(scale=1):
101
+ dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(container=False)
102
+ with gr.Column(scale=1):
103
+ switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
104
+ with gr.Row():
105
+ with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up:
106
+ file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
107
+ with gr.Accordion("更换模型 & SysPrompt & 交互界面布局", open=(LAYOUT == "TOP-DOWN")):
108
+ system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
109
+ top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
110
+ temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
111
+ max_length_sl = gr.Slider(minimum=256, maximum=4096, value=512, step=1, interactive=True, label="Local LLM MaxLength",)
112
+ checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "底部输入区", "输入清除键"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区")
113
+ md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False)
114
+
115
+ gr.Markdown(description)
116
+ with gr.Accordion("备选输入区", open=True, visible=False) as area_input_secondary:
117
+ with gr.Row():
118
+ txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False)
119
+ with gr.Row():
120
+ submitBtn2 = gr.Button("提交", variant="primary")
121
+ with gr.Row():
122
+ resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn2.style(size="sm")
123
+ stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn2.style(size="sm")
124
+ clearBtn2 = gr.Button("清除", variant="secondary", visible=False); clearBtn.style(size="sm")
125
+ # 功能区显示开关与功能区的互动
126
+ def fn_area_visibility(a):
127
+ ret = {}
128
+ ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
129
+ ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
130
+ ret.update({area_input_primary: gr.update(visible=("底部输入区" not in a))})
131
+ ret.update({area_input_secondary: gr.update(visible=("底部输入区" in a))})
132
+ ret.update({clearBtn: gr.update(visible=("输入清除键" in a))})
133
+ ret.update({clearBtn2: gr.update(visible=("输入清除键" in a))})
134
+ if "底部输入区" in a: ret.update({txt: gr.update(value="")})
135
+ return ret
136
+ checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2] )
137
+ # 整理反复出现的控件句柄组合
138
+ input_combo = [cookies, max_length_sl, md_dropdown, txt, txt2, top_p, temperature, chatbot, history, system_prompt, txt_pattern]
139
+ output_combo = [cookies, chatbot, history, status]
140
+ predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=input_combo, outputs=output_combo)
141
+ # 提交按钮、重置按钮
142
+ cancel_handles.append(txt.submit(**predict_args))
143
+ cancel_handles.append(txt2.submit(**predict_args))
144
+ cancel_handles.append(submitBtn.click(**predict_args))
145
+ cancel_handles.append(submitBtn2.click(**predict_args))
146
+ resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
147
+ resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
148
+ clearBtn.click(lambda: ("",""), None, [txt, txt2])
149
+ clearBtn2.click(lambda: ("",""), None, [txt, txt2])
150
+ # 基础功能区的回调函数注册
151
+ for k in functional:
152
+ click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)
153
+ cancel_handles.append(click_handle)
154
+ # 文件上传区,接收文件后与chatbot的互动
155
+ file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes], [chatbot, txt, txt2])
156
+ # 函数插件-固定按钮区
157
+ for k in crazy_fns:
158
+ if not crazy_fns[k].get("AsButton", True): continue
159
+ click_handle = crazy_fns[k]["Button"].click(ArgsGeneralWrapper(crazy_fns[k]["Function"]), [*input_combo, gr.State(PORT)], output_combo)
160
+ click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
161
+ cancel_handles.append(click_handle)
162
+ # 函数插件-解析任意code项目
163
+ click_handle = crazy_fns[code_plugin_name]["Button"].click(ArgsGeneralWrapper(crazy_fns[code_plugin_name]["Function"]), [*input_combo, gr.State(PORT)], output_combo)
164
+ click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
165
  cancel_handles.append(click_handle)
166
+ # 函数插件-下拉菜单与随变按钮的互动
167
+ def on_dropdown_changed(k):
168
+ variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
169
+ return {switchy_bt: gr.update(value=k, variant=variant)}
170
+ dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt] )
171
+ # 随变按钮的回调函数注册
172
+ def route(k, *args, **kwargs):
173
+ if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
174
+ yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
175
+ click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo)
176
  click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
177
+ # def expand_file_area(file_upload, area_file_up):
178
+ # if len(file_upload)>0: return {area_file_up: gr.update(open=True)}
179
+ # click_handle.then(expand_file_area, [file_upload, area_file_up], [area_file_up])
180
  cancel_handles.append(click_handle)
181
+ # 终止按钮的回调函数注册
182
+ stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
183
+ stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
184
+
185
+ # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
186
+ def auto_opentab_delay():
187
+ import threading, webbrowser, time
188
+ print(f"如果浏览器没有自动打开,请复制并转到以下URL:")
189
+ print(f"\t(亮色主题): http://localhost:{PORT}")
190
+ print(f"\t(暗色主题): http://localhost:{PORT}/?__dark-theme=true")
191
+ def open():
192
+ time.sleep(2) # 打开浏览器
193
+ webbrowser.open_new_tab(f"http://localhost:{PORT}/?__dark-theme=true")
194
+ threading.Thread(target=open, name="open-browser", daemon=True).start()
195
+ threading.Thread(target=auto_update, name="self-upgrade", daemon=True).start()
196
+ threading.Thread(target=warm_up_modules, name="warm-up", daemon=True).start()
197
+
198
+ auto_opentab_delay()
199
+ demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
 
201
+ if __name__ == "__main__":
202
+ main()
request_llm/README.md CHANGED
@@ -1,35 +1,53 @@
1
  # 如何使用其他大语言模型(v3.0分支测试中)
2
 
3
- ## 1. 先运行text-generation
 
 
 
 
4
  ``` sh
5
- # 下载模型( text-generation 这么牛的项目,别忘了给人家star )
6
- git clone https://github.com/oobabooga/text-generation-webui.git
 
 
 
 
7
 
8
- # 安装text-generation的额外依赖
9
- pip install accelerate bitsandbytes flexgen gradio llamacpp markdown numpy peft requests rwkv safetensors sentencepiece tqdm datasets git+https://github.com/huggingface/transformers
10
 
11
- # 切换路径
12
- cd text-generation-webui
13
 
14
- # 下载模型
 
 
 
 
 
 
 
 
 
 
15
  python download-model.py facebook/galactica-1.3b
16
  # 其他可选如 facebook/opt-1.3b
 
17
  # facebook/galactica-6.7b
18
  # facebook/galactica-120b
19
  # facebook/pygmalion-1.3b 等
20
  # 详情见 https://github.com/oobabooga/text-generation-webui
21
 
22
- # 启动text-generation,注意把模型的斜杠改成下划线
23
- python server.py --cpu --listen --listen-port 7860 --model facebook_galactica-1.3b
24
  ```
25
 
26
- ## 2. 修改config.py
 
27
  ``` sh
28
- # LLM_MODEL格式较复杂 TGUI:[模型]@[ws地址]:[ws端口] , 端口要和上面给定的端口一致
29
- LLM_MODEL = "TGUI:galactica-1.3b@localhost:7860"
30
  ```
31
 
32
- ## 3. 运行!
33
  ``` sh
34
  cd chatgpt-academic
35
  python main.py
 
1
  # 如何使用其他大语言模型(v3.0分支测试中)
2
 
3
+ ## ChatGLM
4
+
5
+ - 安装依赖 `pip install -r request_llm/requirements_chatglm.txt`
6
+ - 修改配置,在config.py中将LLM_MODEL的值改为"chatglm"
7
+
8
  ``` sh
9
+ LLM_MODEL = "chatglm"
10
+ ```
11
+ - 运行!
12
+ ``` sh
13
+ `python main.py`
14
+ ```
15
 
 
 
16
 
17
+ ---
18
+ ## Text-Generation-UI (TGUI)
19
 
20
+ ### 1. 部署TGUI
21
+ ``` sh
22
+ # 1 下载模型
23
+ git clone https://github.com/oobabooga/text-generation-webui.git
24
+ # 2 这个仓库的最新代码有问题,回滚到几周之前
25
+ git reset --hard fcda3f87767e642d1c0411776e549e1d3894843d
26
+ # 3 切换路径
27
+ cd text-generation-webui
28
+ # 4 安装text-generation的额外依赖
29
+ pip install accelerate bitsandbytes flexgen gradio llamacpp markdown numpy peft requests rwkv safetensors sentencepiece tqdm datasets git+https://github.com/huggingface/transformers
30
+ # 5 下载模型
31
  python download-model.py facebook/galactica-1.3b
32
  # 其他可选如 facebook/opt-1.3b
33
+ # facebook/galactica-1.3b
34
  # facebook/galactica-6.7b
35
  # facebook/galactica-120b
36
  # facebook/pygmalion-1.3b 等
37
  # 详情见 https://github.com/oobabooga/text-generation-webui
38
 
39
+ # 6 启动text-generation
40
+ python server.py --cpu --listen --listen-port 7865 --model facebook_galactica-1.3b
41
  ```
42
 
43
+ ### 2. 修改config.py
44
+
45
  ``` sh
46
+ # LLM_MODEL格式: tgui:[模型]@[ws地址]:[ws端口] , 端口要和上面给定的端口一致
47
+ LLM_MODEL = "tgui:galactica-1.3b@localhost:7860"
48
  ```
49
 
50
+ ### 3. 运行!
51
  ``` sh
52
  cd chatgpt-academic
53
  python main.py
request_llm/bridge_all.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ 该文件中主要包含2个函数
4
+
5
+ 不具备多线程能力的函数:
6
+ 1. predict: 正常对话时使用,具备完备的交互功能,不可多线程
7
+
8
+ 具备多线程调用能力的函数
9
+ 2. predict_no_ui_long_connection:在实验过程中发现调用predict_no_ui处理长文档时,和openai的连接容易断掉,这个函数用stream的方式解决这个问题,同样支持多线程
10
+ """
11
+ import tiktoken
12
+ from functools import wraps, lru_cache
13
+ from concurrent.futures import ThreadPoolExecutor
14
+
15
+ from .bridge_chatgpt import predict_no_ui_long_connection as chatgpt_noui
16
+ from .bridge_chatgpt import predict as chatgpt_ui
17
+
18
+ from .bridge_chatglm import predict_no_ui_long_connection as chatglm_noui
19
+ from .bridge_chatglm import predict as chatglm_ui
20
+
21
+ # from .bridge_tgui import predict_no_ui_long_connection as tgui_noui
22
+ # from .bridge_tgui import predict as tgui_ui
23
+
24
+ colors = ['#FF00FF', '#00FFFF', '#FF0000', '#990099', '#009999', '#990044']
25
+
26
+ class LazyloadTiktoken(object):
27
+ def __init__(self, model):
28
+ self.model = model
29
+
30
+ @staticmethod
31
+ @lru_cache(maxsize=128)
32
+ def get_encoder(model):
33
+ print('正在加载tokenizer,如果是第一次运行,可能需要一点时间下载参数')
34
+ tmp = tiktoken.encoding_for_model(model)
35
+ print('加载tokenizer完毕')
36
+ return tmp
37
+
38
+ def encode(self, *args, **kwargs):
39
+ encoder = self.get_encoder(self.model)
40
+ return encoder.encode(*args, **kwargs)
41
+
42
+ def decode(self, *args, **kwargs):
43
+ encoder = self.get_encoder(self.model)
44
+ return encoder.decode(*args, **kwargs)
45
+
46
+ tokenizer_gpt35 = LazyloadTiktoken("gpt-3.5-turbo")
47
+ tokenizer_gpt4 = LazyloadTiktoken("gpt-4")
48
+ get_token_num_gpt35 = lambda txt: len(tokenizer_gpt35.encode(txt, disallowed_special=()))
49
+ get_token_num_gpt4 = lambda txt: len(tokenizer_gpt4.encode(txt, disallowed_special=()))
50
+
51
+ model_info = {
52
+ # openai
53
+ "gpt-3.5-turbo": {
54
+ "fn_with_ui": chatgpt_ui,
55
+ "fn_without_ui": chatgpt_noui,
56
+ "endpoint": "https://api.openai.com/v1/chat/completions",
57
+ "max_token": 4096,
58
+ "tokenizer": tokenizer_gpt35,
59
+ "token_cnt": get_token_num_gpt35,
60
+ },
61
+
62
+ "gpt-4": {
63
+ "fn_with_ui": chatgpt_ui,
64
+ "fn_without_ui": chatgpt_noui,
65
+ "endpoint": "https://api.openai.com/v1/chat/completions",
66
+ "max_token": 8192,
67
+ "tokenizer": tokenizer_gpt4,
68
+ "token_cnt": get_token_num_gpt4,
69
+ },
70
+
71
+ # api_2d
72
+ "api2d-gpt-3.5-turbo": {
73
+ "fn_with_ui": chatgpt_ui,
74
+ "fn_without_ui": chatgpt_noui,
75
+ "endpoint": "https://openai.api2d.net/v1/chat/completions",
76
+ "max_token": 4096,
77
+ "tokenizer": tokenizer_gpt35,
78
+ "token_cnt": get_token_num_gpt35,
79
+ },
80
+
81
+ "api2d-gpt-4": {
82
+ "fn_with_ui": chatgpt_ui,
83
+ "fn_without_ui": chatgpt_noui,
84
+ "endpoint": "https://openai.api2d.net/v1/chat/completions",
85
+ "max_token": 8192,
86
+ "tokenizer": tokenizer_gpt4,
87
+ "token_cnt": get_token_num_gpt4,
88
+ },
89
+
90
+ # chatglm
91
+ "chatglm": {
92
+ "fn_with_ui": chatglm_ui,
93
+ "fn_without_ui": chatglm_noui,
94
+ "endpoint": None,
95
+ "max_token": 1024,
96
+ "tokenizer": tokenizer_gpt35,
97
+ "token_cnt": get_token_num_gpt35,
98
+ },
99
+
100
+ }
101
+
102
+
103
+ def LLM_CATCH_EXCEPTION(f):
104
+ """
105
+ 装饰器函数,将错误显示出来
106
+ """
107
+ def decorated(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience):
108
+ try:
109
+ return f(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience)
110
+ except Exception as e:
111
+ from toolbox import get_conf
112
+ import traceback
113
+ proxies, = get_conf('proxies')
114
+ tb_str = '\n```\n' + traceback.format_exc() + '\n```\n'
115
+ observe_window[0] = tb_str
116
+ return tb_str
117
+ return decorated
118
+
119
+
120
+ def predict_no_ui_long_connection(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience=False):
121
+ """
122
+ 发送至LLM,等待回复,一次性完成,不显示中间过程。但内部用stream的方法避免中途网线被掐。
123
+ inputs:
124
+ 是本次问询的输入
125
+ sys_prompt:
126
+ 系统静默prompt
127
+ llm_kwargs:
128
+ LLM的内部调优参数
129
+ history:
130
+ 是之前的对话列表
131
+ observe_window = None:
132
+ 用于负责跨越线程传递已经输出的部分,大部分时候仅仅为了fancy的视觉效果,留空即可。observe_window[0]:观测窗。observe_window[1]:看门狗
133
+ """
134
+ import threading, time, copy
135
+
136
+ model = llm_kwargs['llm_model']
137
+ n_model = 1
138
+ if '&' not in model:
139
+ assert not model.startswith("tgui"), "TGUI不支持函数插件的实现"
140
+
141
+ # 如果只询问1个大语言模型:
142
+ method = model_info[model]["fn_without_ui"]
143
+ return method(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience)
144
+ else:
145
+ # 如果同时询问多个大语言模型:
146
+ executor = ThreadPoolExecutor(max_workers=4)
147
+ models = model.split('&')
148
+ n_model = len(models)
149
+
150
+ window_len = len(observe_window)
151
+ assert window_len==3
152
+ window_mutex = [["", time.time(), ""] for _ in range(n_model)] + [True]
153
+
154
+ futures = []
155
+ for i in range(n_model):
156
+ model = models[i]
157
+ method = model_info[model]["fn_without_ui"]
158
+ llm_kwargs_feedin = copy.deepcopy(llm_kwargs)
159
+ llm_kwargs_feedin['llm_model'] = model
160
+ future = executor.submit(LLM_CATCH_EXCEPTION(method), inputs, llm_kwargs_feedin, history, sys_prompt, window_mutex[i], console_slience)
161
+ futures.append(future)
162
+
163
+ def mutex_manager(window_mutex, observe_window):
164
+ while True:
165
+ time.sleep(0.5)
166
+ if not window_mutex[-1]: break
167
+ # 看门狗(watchdog)
168
+ for i in range(n_model):
169
+ window_mutex[i][1] = observe_window[1]
170
+ # 观察窗(window)
171
+ chat_string = []
172
+ for i in range(n_model):
173
+ chat_string.append( f"【{str(models[i])} 说】: <font color=\"{colors[i]}\"> {window_mutex[i][0]} </font>" )
174
+ res = '<br/><br/>\n\n---\n\n'.join(chat_string)
175
+ # # # # # # # # # # #
176
+ observe_window[0] = res
177
+
178
+ t_model = threading.Thread(target=mutex_manager, args=(window_mutex, observe_window), daemon=True)
179
+ t_model.start()
180
+
181
+ return_string_collect = []
182
+ while True:
183
+ worker_done = [h.done() for h in futures]
184
+ if all(worker_done):
185
+ executor.shutdown()
186
+ break
187
+ time.sleep(1)
188
+
189
+ for i, future in enumerate(futures): # wait and get
190
+ return_string_collect.append( f"【{str(models[i])} 说】: <font color=\"{colors[i]}\"> {future.result()} </font>" )
191
+
192
+ window_mutex[-1] = False # stop mutex thread
193
+ res = '<br/>\n\n---\n\n'.join(return_string_collect)
194
+ return res
195
+
196
+
197
+ def predict(inputs, llm_kwargs, *args, **kwargs):
198
+ """
199
+ 发送至LLM,流式获取输出。
200
+ 用于基础的对话功能。
201
+ inputs 是本次问询的输入
202
+ top_p, temperature是LLM的内部调优参数
203
+ history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)
204
+ chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容
205
+ additional_fn代表点击的哪个按钮,按钮见functional.py
206
+ """
207
+
208
+ method = model_info[llm_kwargs['llm_model']]["fn_with_ui"]
209
+ yield from method(inputs, llm_kwargs, *args, **kwargs)
210
+
request_llm/bridge_chatglm.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers import AutoModel, AutoTokenizer
3
+ import time
4
+ import importlib
5
+ from toolbox import update_ui, get_conf
6
+ from multiprocessing import Process, Pipe
7
+
8
+ load_message = "ChatGLM尚未加载,加载需要一段时间。注意,取决于`config.py`的配置,ChatGLM消耗大量的内存(CPU)或显存(GPU),也许会导致低配计算机卡死 ……"
9
+
10
+ #################################################################################
11
+ class GetGLMHandle(Process):
12
+ def __init__(self):
13
+ super().__init__(daemon=True)
14
+ self.parent, self.child = Pipe()
15
+ self.chatglm_model = None
16
+ self.chatglm_tokenizer = None
17
+ self.info = ""
18
+ self.success = True
19
+ self.check_dependency()
20
+ self.start()
21
+
22
+ def check_dependency(self):
23
+ try:
24
+ import sentencepiece
25
+ self.info = "依赖检测通过"
26
+ self.success = True
27
+ except:
28
+ self.info = "缺少ChatGLM的依赖,如果要使用ChatGLM,除了基础的pip依赖以外,您还需要运行`pip install -r request_llm/requirements_chatglm.txt`安装ChatGLM的依赖。"
29
+ self.success = False
30
+
31
+ def ready(self):
32
+ return self.chatglm_model is not None
33
+
34
+ def run(self):
35
+ # 第一次运行,加载参数
36
+ retry = 0
37
+ while True:
38
+ try:
39
+ if self.chatglm_model is None:
40
+ self.chatglm_tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
41
+ device, = get_conf('LOCAL_MODEL_DEVICE')
42
+ if device=='cpu':
43
+ self.chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float()
44
+ else:
45
+ self.chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
46
+ self.chatglm_model = self.chatglm_model.eval()
47
+ break
48
+ else:
49
+ break
50
+ except:
51
+ retry += 1
52
+ if retry > 3:
53
+ self.child.send('[Local Message] Call ChatGLM fail 不能正常加载ChatGLM的参数。')
54
+ raise RuntimeError("不能正常加载ChatGLM的参数!")
55
+
56
+ # 进入任务等待状态
57
+ while True:
58
+ kwargs = self.child.recv()
59
+ try:
60
+ for response, history in self.chatglm_model.stream_chat(self.chatglm_tokenizer, **kwargs):
61
+ self.child.send(response)
62
+ except:
63
+ self.child.send('[Local Message] Call ChatGLM fail.')
64
+ self.child.send('[Finish]')
65
+
66
+ def stream_chat(self, **kwargs):
67
+ self.parent.send(kwargs)
68
+ while True:
69
+ res = self.parent.recv()
70
+ if res != '[Finish]':
71
+ yield res
72
+ else:
73
+ break
74
+ return
75
+
76
+ global glm_handle
77
+ glm_handle = None
78
+ #################################################################################
79
+ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
80
+ """
81
+ 多线程方法
82
+ 函数的说明请见 request_llm/bridge_all.py
83
+ """
84
+ global glm_handle
85
+ if glm_handle is None:
86
+ glm_handle = GetGLMHandle()
87
+ observe_window[0] = load_message + "\n\n" + glm_handle.info
88
+ if not glm_handle.success:
89
+ error = glm_handle.info
90
+ glm_handle = None
91
+ raise RuntimeError(error)
92
+
93
+ # chatglm 没有 sys_prompt 接口,因此把prompt加入 history
94
+ history_feedin = []
95
+ for i in range(len(history)//2):
96
+ history_feedin.append(["What can I do?", sys_prompt] )
97
+ history_feedin.append([history[2*i], history[2*i+1]] )
98
+
99
+ watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可
100
+ response = ""
101
+ for response in glm_handle.stream_chat(query=inputs, history=history_feedin, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']):
102
+ observe_window[0] = response
103
+ if len(observe_window) >= 2:
104
+ if (time.time()-observe_window[1]) > watch_dog_patience:
105
+ raise RuntimeError("程序终止。")
106
+ return response
107
+
108
+
109
+
110
+ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
111
+ """
112
+ 单线程方法
113
+ 函数的说明请见 request_llm/bridge_all.py
114
+ """
115
+ chatbot.append((inputs, ""))
116
+
117
+ global glm_handle
118
+ if glm_handle is None:
119
+ glm_handle = GetGLMHandle()
120
+ chatbot[-1] = (inputs, load_message + "\n\n" + glm_handle.info)
121
+ yield from update_ui(chatbot=chatbot, history=[])
122
+ if not glm_handle.success:
123
+ glm_handle = None
124
+ return
125
+
126
+ if additional_fn is not None:
127
+ import core_functional
128
+ importlib.reload(core_functional) # 热更新prompt
129
+ core_functional = core_functional.get_core_functions()
130
+ if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话)
131
+ inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
132
+
133
+ history_feedin = []
134
+ for i in range(len(history)//2):
135
+ history_feedin.append(["What can I do?", system_prompt] )
136
+ history_feedin.append([history[2*i], history[2*i+1]] )
137
+
138
+ for response in glm_handle.stream_chat(query=inputs, history=history_feedin, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']):
139
+ chatbot[-1] = (inputs, response)
140
+ yield from update_ui(chatbot=chatbot, history=history)
request_llm/bridge_chatgpt.py CHANGED
@@ -21,9 +21,9 @@ import importlib
21
 
22
  # config_private.py放自己的秘密如API和代理网址
23
  # 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件
24
- from toolbox import get_conf, update_ui
25
- proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL = \
26
- get_conf('proxies', 'API_URL', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY', 'LLM_MODEL')
27
 
28
  timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \
29
  '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。'
@@ -42,17 +42,17 @@ def get_full_error(chunk, stream_response):
42
 
43
  def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
44
  """
45
- 发送至chatGPT,等待回复,一次性完成,不显示中间过程。但内部用stream的方法避免中途网线被掐。
46
- inputs:
47
- 是本次问询的输入
48
- sys_prompt:
49
- 系统静默prompt
50
- llm_kwargs:
51
- chatGPT的内部调优参数
52
- history:
53
- 是之前的对话列表
54
- observe_window = None:
55
- 用于负责跨越线程传递已经输出的部分,大部分时候仅仅为了fancy的视觉效果,留空即可。observe_window[0]:观测窗。observe_window[1]:看门狗
56
  """
57
  watch_dog_patience = 5 # 看门狗的耐心, 设置5秒即可
58
  headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt=sys_prompt, stream=True)
@@ -60,7 +60,9 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
60
  while True:
61
  try:
62
  # make a POST request to the API endpoint, stream=False
63
- response = requests.post(API_URL, headers=headers, proxies=proxies,
 
 
64
  json=payload, stream=True, timeout=TIMEOUT_SECONDS); break
65
  except requests.exceptions.ReadTimeout as e:
66
  retry += 1
@@ -83,6 +85,7 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
83
  raise ConnectionAbortedError("OpenAI拒绝了请求:" + error_msg)
84
  else:
85
  raise RuntimeError("OpenAI拒绝了请求:" + error_msg)
 
86
  json_data = json.loads(chunk.lstrip('data:'))['choices'][0]
87
  delta = json_data["delta"]
88
  if len(delta) == 0: break
@@ -105,22 +108,22 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
105
 
106
  def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
107
  """
108
- 发送至chatGPT,流式获取输出。
109
- 用于基础的对话功能。
110
- inputs 是本次问询的输入
111
- top_p, temperature是chatGPT的内部调优参数
112
- history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)
113
- chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容
114
- additional_fn代表点击的哪个按钮,按钮见functional.py
115
  """
116
- if inputs.startswith('sk-') and len(inputs) == 51:
117
  chatbot._cookies['api_key'] = inputs
118
  chatbot.append(("输入已识别为openai的api_key", "api_key已导入"))
119
  yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面
120
  return
121
- elif len(chatbot._cookies['api_key']) != 51:
122
  chatbot.append((inputs, "缺少api_key。\n\n1. 临时解决方案:直接在输入区键入api_key,然后回车提交。\n\n2. 长效解决方案:在config.py中配置。"))
123
- yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面
124
  return
125
 
126
  if additional_fn is not None:
@@ -130,20 +133,27 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
130
  if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话)
131
  inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
132
 
133
- if stream:
134
- raw_input = inputs
135
- logging.info(f'[raw_input] {raw_input}')
136
- chatbot.append((inputs, ""))
137
- yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面
138
 
139
- headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt, stream)
 
 
 
 
 
 
140
  history.append(inputs); history.append(" ")
141
 
142
  retry = 0
143
  while True:
144
  try:
145
  # make a POST request to the API endpoint, stream=True
146
- response = requests.post(API_URL, headers=headers, proxies=proxies,
 
 
147
  json=payload, stream=True, timeout=TIMEOUT_SECONDS);break
148
  except:
149
  retry += 1
@@ -160,21 +170,23 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
160
  while True:
161
  chunk = next(stream_response)
162
  # print(chunk.decode()[6:])
163
- if is_head_of_the_stream:
164
  # 数据流的第一帧不携带content
165
  is_head_of_the_stream = False; continue
166
 
167
  if chunk:
168
  try:
169
- if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
 
 
170
  # 判定为数据流的结束,gpt_replying_buffer也写完了
171
  logging.info(f'[response] {gpt_replying_buffer}')
172
  break
173
  # 处理数据流的主体
174
- chunkjson = json.loads(chunk.decode()[6:])
175
  status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}"
176
  # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出
177
- gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]
178
  history[-1] = gpt_replying_buffer
179
  chatbot[-1] = (history[-2], history[-1])
180
  yield from update_ui(chatbot=chatbot, history=history, msg=status_text) # 刷新界面
@@ -183,31 +195,38 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
183
  traceback.print_exc()
184
  yield from update_ui(chatbot=chatbot, history=history, msg="Json解析不合常规") # 刷新界面
185
  chunk = get_full_error(chunk, stream_response)
186
- error_msg = chunk.decode()
 
187
  if "reduce the length" in error_msg:
188
  chatbot[-1] = (chatbot[-1][0], "[Local Message] Reduce the length. 本次输入过长,或历史数据过长. 历史缓存数据现已释放,您可���请再次尝试.")
189
  history = [] # 清除历史
 
 
190
  elif "Incorrect API key" in error_msg:
191
  chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key. OpenAI以提供了不正确的API_KEY为由,拒绝服务.")
192
  elif "exceeded your current quota" in error_msg:
193
  chatbot[-1] = (chatbot[-1][0], "[Local Message] You exceeded your current quota. OpenAI以账户额度不足为由,拒绝服务.")
 
 
194
  else:
195
  from toolbox import regular_txt_to_markdown
196
  tb_str = '```\n' + traceback.format_exc() + '```'
197
- chatbot[-1] = (chatbot[-1][0], f"[Local Message] 异常 \n\n{tb_str} \n\n{regular_txt_to_markdown(chunk.decode()[4:])}")
198
  yield from update_ui(chatbot=chatbot, history=history, msg="Json异常" + error_msg) # 刷新界面
199
  return
200
 
201
  def generate_payload(inputs, llm_kwargs, history, system_prompt, stream):
202
  """
203
- 整合所有信息,选择LLM模型,生成http请求,为发送请求做准备
204
  """
205
- if len(llm_kwargs['api_key']) != 51:
206
  raise AssertionError("你提供了错误的API_KEY。\n\n1. 临时解决方案:直接在输入区键入api_key,然后回车提交。\n\n2. 长效解决方案:在config.py中配置。")
207
 
 
 
208
  headers = {
209
  "Content-Type": "application/json",
210
- "Authorization": f"Bearer {llm_kwargs['api_key']}"
211
  }
212
 
213
  conversation_cnt = len(history) // 2
@@ -235,7 +254,7 @@ def generate_payload(inputs, llm_kwargs, history, system_prompt, stream):
235
  messages.append(what_i_ask_now)
236
 
237
  payload = {
238
- "model": llm_kwargs['llm_model'],
239
  "messages": messages,
240
  "temperature": llm_kwargs['temperature'], # 1.0,
241
  "top_p": llm_kwargs['top_p'], # 1.0,
 
21
 
22
  # config_private.py放自己的秘密如API和代理网址
23
  # 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件
24
+ from toolbox import get_conf, update_ui, is_any_api_key, select_api_key
25
+ proxies, API_KEY, TIMEOUT_SECONDS, MAX_RETRY = \
26
+ get_conf('proxies', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY')
27
 
28
  timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \
29
  '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。'
 
42
 
43
  def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
44
  """
45
+ 发送至chatGPT,等待回复,一次性完成,不显示中间过程。但内部用stream的方法避免中途网线被掐。
46
+ inputs:
47
+ 是本次问询的输入
48
+ sys_prompt:
49
+ 系统静默prompt
50
+ llm_kwargs:
51
+ chatGPT的内部调优参数
52
+ history:
53
+ 是之前的对话列表
54
+ observe_window = None:
55
+ 用于负责跨越线程传递已经输出的部分,大部分时候仅仅为了fancy的视觉效果,留空即可。observe_window[0]:观测窗。observe_window[1]:看门狗
56
  """
57
  watch_dog_patience = 5 # 看门狗的耐心, 设置5秒即可
58
  headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt=sys_prompt, stream=True)
 
60
  while True:
61
  try:
62
  # make a POST request to the API endpoint, stream=False
63
+ from .bridge_all import model_info
64
+ endpoint = model_info[llm_kwargs['llm_model']]['endpoint']
65
+ response = requests.post(endpoint, headers=headers, proxies=proxies,
66
  json=payload, stream=True, timeout=TIMEOUT_SECONDS); break
67
  except requests.exceptions.ReadTimeout as e:
68
  retry += 1
 
85
  raise ConnectionAbortedError("OpenAI拒绝了请求:" + error_msg)
86
  else:
87
  raise RuntimeError("OpenAI拒绝了请求:" + error_msg)
88
+ if ('data: [DONE]' in chunk): break # api2d 正常完成
89
  json_data = json.loads(chunk.lstrip('data:'))['choices'][0]
90
  delta = json_data["delta"]
91
  if len(delta) == 0: break
 
108
 
109
  def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
110
  """
111
+ 发送至chatGPT,流式获取输出。
112
+ 用于基础的对话功能。
113
+ inputs 是本次问询的输入
114
+ top_p, temperature是chatGPT的内部调优参数
115
+ history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)
116
+ chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容
117
+ additional_fn代表点击的哪个按钮,按钮见functional.py
118
  """
119
+ if is_any_api_key(inputs):
120
  chatbot._cookies['api_key'] = inputs
121
  chatbot.append(("输入已识别为openai的api_key", "api_key已导入"))
122
  yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面
123
  return
124
+ elif not is_any_api_key(chatbot._cookies['api_key']):
125
  chatbot.append((inputs, "缺少api_key。\n\n1. 临时解决方案:直接在输入区键入api_key,然后回车提交。\n\n2. 长效解决方案:在config.py中配置。"))
126
+ yield from update_ui(chatbot=chatbot, history=history, msg="缺少api_key") # 刷新界面
127
  return
128
 
129
  if additional_fn is not None:
 
133
  if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话)
134
  inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
135
 
136
+ raw_input = inputs
137
+ logging.info(f'[raw_input] {raw_input}')
138
+ chatbot.append((inputs, ""))
139
+ yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面
 
140
 
141
+ try:
142
+ headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt, stream)
143
+ except RuntimeError as e:
144
+ chatbot[-1] = (inputs, f"您提供的api-key不满足要求,不包含任何可用于{llm_kwargs['llm_model']}的api-key。")
145
+ yield from update_ui(chatbot=chatbot, history=history, msg="api-key不满足要求") # 刷新界面
146
+ return
147
+
148
  history.append(inputs); history.append(" ")
149
 
150
  retry = 0
151
  while True:
152
  try:
153
  # make a POST request to the API endpoint, stream=True
154
+ from .bridge_all import model_info
155
+ endpoint = model_info[llm_kwargs['llm_model']]['endpoint']
156
+ response = requests.post(endpoint, headers=headers, proxies=proxies,
157
  json=payload, stream=True, timeout=TIMEOUT_SECONDS);break
158
  except:
159
  retry += 1
 
170
  while True:
171
  chunk = next(stream_response)
172
  # print(chunk.decode()[6:])
173
+ if is_head_of_the_stream and (r'"object":"error"' not in chunk.decode()):
174
  # 数据流的第一帧不携带content
175
  is_head_of_the_stream = False; continue
176
 
177
  if chunk:
178
  try:
179
+ chunk_decoded = chunk.decode()
180
+ # 前者API2D的
181
+ if ('data: [DONE]' in chunk_decoded) or (len(json.loads(chunk_decoded[6:])['choices'][0]["delta"]) == 0):
182
  # 判定为数据流的结束,gpt_replying_buffer也写完了
183
  logging.info(f'[response] {gpt_replying_buffer}')
184
  break
185
  # 处理数据流的主体
186
+ chunkjson = json.loads(chunk_decoded[6:])
187
  status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}"
188
  # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出
189
+ gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk_decoded[6:])['choices'][0]["delta"]["content"]
190
  history[-1] = gpt_replying_buffer
191
  chatbot[-1] = (history[-2], history[-1])
192
  yield from update_ui(chatbot=chatbot, history=history, msg=status_text) # 刷新界面
 
195
  traceback.print_exc()
196
  yield from update_ui(chatbot=chatbot, history=history, msg="Json解析不合常规") # 刷新界面
197
  chunk = get_full_error(chunk, stream_response)
198
+ chunk_decoded = chunk.decode()
199
+ error_msg = chunk_decoded
200
  if "reduce the length" in error_msg:
201
  chatbot[-1] = (chatbot[-1][0], "[Local Message] Reduce the length. 本次输入过长,或历史数据过长. 历史缓存数据现已释放,您可���请再次尝试.")
202
  history = [] # 清除历史
203
+ elif "does not exist" in error_msg:
204
+ chatbot[-1] = (chatbot[-1][0], f"[Local Message] Model {llm_kwargs['llm_model']} does not exist. 模型不存在,或者您没有获得体验资格.")
205
  elif "Incorrect API key" in error_msg:
206
  chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key. OpenAI以提供了不正确的API_KEY为由,拒绝服务.")
207
  elif "exceeded your current quota" in error_msg:
208
  chatbot[-1] = (chatbot[-1][0], "[Local Message] You exceeded your current quota. OpenAI以账户额度不足为由,拒绝服务.")
209
+ elif "bad forward key" in error_msg:
210
+ chatbot[-1] = (chatbot[-1][0], "[Local Message] Bad forward key. API2D账户额度不足.")
211
  else:
212
  from toolbox import regular_txt_to_markdown
213
  tb_str = '```\n' + traceback.format_exc() + '```'
214
+ chatbot[-1] = (chatbot[-1][0], f"[Local Message] 异常 \n\n{tb_str} \n\n{regular_txt_to_markdown(chunk_decoded[4:])}")
215
  yield from update_ui(chatbot=chatbot, history=history, msg="Json异常" + error_msg) # 刷新界面
216
  return
217
 
218
  def generate_payload(inputs, llm_kwargs, history, system_prompt, stream):
219
  """
220
+ 整合所有信息,选择LLM模型,生成http请求,为发送请求做准备
221
  """
222
+ if not is_any_api_key(llm_kwargs['api_key']):
223
  raise AssertionError("你提供了错误的API_KEY。\n\n1. 临时解决方案:直接在输入区键入api_key,然后回车提交。\n\n2. 长效解决方案:在config.py中配置。")
224
 
225
+ api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model'])
226
+
227
  headers = {
228
  "Content-Type": "application/json",
229
+ "Authorization": f"Bearer {api_key}"
230
  }
231
 
232
  conversation_cnt = len(history) // 2
 
254
  messages.append(what_i_ask_now)
255
 
256
  payload = {
257
+ "model": llm_kwargs['llm_model'].strip('api2d-'),
258
  "messages": messages,
259
  "temperature": llm_kwargs['temperature'], # 1.0,
260
  "top_p": llm_kwargs['top_p'], # 1.0,
request_llm/bridge_tgui.py CHANGED
@@ -13,23 +13,18 @@ import time
13
  import threading
14
  import importlib
15
  from toolbox import get_conf, update_ui
16
- LLM_MODEL, = get_conf('LLM_MODEL')
17
 
18
- # "TGUI:galactica-1.3b@localhost:7860"
19
- model_name, addr_port = LLM_MODEL.split('@')
20
- assert ':' in addr_port, "LLM_MODEL 格式不正确!" + LLM_MODEL
21
- addr, port = addr_port.split(':')
22
 
23
  def random_hash():
24
  letters = string.ascii_lowercase + string.digits
25
  return ''.join(random.choice(letters) for i in range(9))
26
 
27
- async def run(context, max_token=512):
28
  params = {
29
  'max_new_tokens': max_token,
30
  'do_sample': True,
31
- 'temperature': 0.5,
32
- 'top_p': 0.9,
33
  'typical_p': 1,
34
  'repetition_penalty': 1.05,
35
  'encoder_repetition_penalty': 1.0,
@@ -90,7 +85,7 @@ async def run(context, max_token=512):
90
 
91
 
92
 
93
- def predict_tgui(inputs, top_p, temperature, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
94
  """
95
  发送至chatGPT,流式获取输出。
96
  用于基础的对话功能。
@@ -108,18 +103,26 @@ def predict_tgui(inputs, top_p, temperature, chatbot, history=[], system_prompt=
108
  inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
109
 
110
  raw_input = "What I would like to say is the following: " + inputs
111
- logging.info(f'[raw_input] {raw_input}')
112
  history.extend([inputs, ""])
113
  chatbot.append([inputs, ""])
114
  yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面
115
 
116
- prompt = inputs
117
  tgui_say = ""
118
 
 
 
 
 
 
119
  mutable = ["", time.time()]
120
  def run_coorotine(mutable):
121
  async def get_result(mutable):
122
- async for response in run(prompt):
 
 
 
 
123
  print(response[len(mutable[0]):])
124
  mutable[0] = response
125
  if (time.time() - mutable[1]) > 3:
@@ -140,28 +143,29 @@ def predict_tgui(inputs, top_p, temperature, chatbot, history=[], system_prompt=
140
  chatbot[-1] = (history[-2], history[-1])
141
  yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
142
 
143
- logging.info(f'[response] {tgui_say}')
144
 
145
 
146
 
147
- def predict_tgui_no_ui(inputs, top_p, temperature, history=[], sys_prompt=""):
148
  raw_input = "What I would like to say is the following: " + inputs
149
- prompt = inputs
150
  tgui_say = ""
151
- mutable = ["", time.time()]
152
- def run_coorotine(mutable):
153
- async def get_result(mutable):
154
- async for response in run(prompt, max_token=20):
155
- print(response[len(mutable[0]):])
156
- mutable[0] = response
157
- if (time.time() - mutable[1]) > 3:
 
 
 
 
 
 
158
  print('exit when no listener')
159
  break
160
- asyncio.run(get_result(mutable))
161
- thread_listen = threading.Thread(target=run_coorotine, args=(mutable,))
162
  thread_listen.start()
163
- while thread_listen.is_alive():
164
- time.sleep(1)
165
- mutable[1] = time.time()
166
- tgui_say = mutable[0]
167
- return tgui_say
 
13
  import threading
14
  import importlib
15
  from toolbox import get_conf, update_ui
 
16
 
 
 
 
 
17
 
18
  def random_hash():
19
  letters = string.ascii_lowercase + string.digits
20
  return ''.join(random.choice(letters) for i in range(9))
21
 
22
+ async def run(context, max_token, temperature, top_p, addr, port):
23
  params = {
24
  'max_new_tokens': max_token,
25
  'do_sample': True,
26
+ 'temperature': temperature,
27
+ 'top_p': top_p,
28
  'typical_p': 1,
29
  'repetition_penalty': 1.05,
30
  'encoder_repetition_penalty': 1.0,
 
85
 
86
 
87
 
88
+ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
89
  """
90
  发送至chatGPT,流式获取输出。
91
  用于基础的对话功能。
 
103
  inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
104
 
105
  raw_input = "What I would like to say is the following: " + inputs
 
106
  history.extend([inputs, ""])
107
  chatbot.append([inputs, ""])
108
  yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面
109
 
110
+ prompt = raw_input
111
  tgui_say = ""
112
 
113
+ model_name, addr_port = llm_kwargs['llm_model'].split('@')
114
+ assert ':' in addr_port, "LLM_MODEL 格式不正确!" + llm_kwargs['llm_model']
115
+ addr, port = addr_port.split(':')
116
+
117
+
118
  mutable = ["", time.time()]
119
  def run_coorotine(mutable):
120
  async def get_result(mutable):
121
+ # "tgui:galactica-1.3b@localhost:7860"
122
+
123
+ async for response in run(context=prompt, max_token=llm_kwargs['max_length'],
124
+ temperature=llm_kwargs['temperature'],
125
+ top_p=llm_kwargs['top_p'], addr=addr, port=port):
126
  print(response[len(mutable[0]):])
127
  mutable[0] = response
128
  if (time.time() - mutable[1]) > 3:
 
143
  chatbot[-1] = (history[-2], history[-1])
144
  yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
145
 
 
146
 
147
 
148
 
149
+ def predict_no_ui_long_connection(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience=False):
150
  raw_input = "What I would like to say is the following: " + inputs
151
+ prompt = raw_input
152
  tgui_say = ""
153
+ model_name, addr_port = llm_kwargs['llm_model'].split('@')
154
+ assert ':' in addr_port, "LLM_MODEL 格式不正确!" + llm_kwargs['llm_model']
155
+ addr, port = addr_port.split(':')
156
+
157
+
158
+ def run_coorotine(observe_window):
159
+ async def get_result(observe_window):
160
+ async for response in run(context=prompt, max_token=llm_kwargs['max_length'],
161
+ temperature=llm_kwargs['temperature'],
162
+ top_p=llm_kwargs['top_p'], addr=addr, port=port):
163
+ print(response[len(observe_window[0]):])
164
+ observe_window[0] = response
165
+ if (time.time() - observe_window[1]) > 5:
166
  print('exit when no listener')
167
  break
168
+ asyncio.run(get_result(observe_window))
169
+ thread_listen = threading.Thread(target=run_coorotine, args=(observe_window,))
170
  thread_listen.start()
171
+ return observe_window[0]
 
 
 
 
request_llm/requirements_chatglm.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ protobuf
2
+ transformers==4.27.1
3
+ cpm_kernels
4
+ torch>=1.10
5
+ mdtex2html
6
+ sentencepiece
self_analysis.md DELETED
@@ -1,262 +0,0 @@
1
- # chatgpt-academic项目自译解报告
2
- (Author补充:以下分析均由本项目调用ChatGPT一键生成,如果有不准确的地方,全怪GPT😄)
3
-
4
- ## 对程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能(包括'check_proxy.py', 'config.py'等)。
5
-
6
- 整体概括:
7
-
8
- 该程序是一个基于自然语言处理和机器学习的科学论文辅助工具,主要功能包括聊天机器人、批量总结PDF文档、批量翻译PDF文档、生成函数注释、解析项目源代码等。程序基于 Gradio 构建 Web 服务,并集成了代理和自动更新功能,提高了用户的使用体验。
9
-
10
- 文件功能表格:
11
-
12
- | 文件名称 | 功能 |
13
- | ------------------------------------------------------------ | ------------------------------------------------------------ |
14
- | .\check_proxy.py | 检查代理设置功能。 |
15
- | .\config.py | 配置文件,存储程序的基本设置。 |
16
- | .\config_private.py | 存储代理网络地址的文件。 |
17
- | .\core_functional.py | 主要的程序逻辑,包括聊天机器人和文件处理。 |
18
- | .\cradle.py | 程序入口,初始化程序和启动 Web 服务。 |
19
- | .\crazy_functional.py | 辅助程序功能,包括PDF文档处理、代码处理、函数注释生成等。 |
20
- | .\main.py | 包含聊天机器人的具体实现。 |
21
- | .\show_math.py | 处理 LaTeX 公式的函数。 |
22
- | .\theme.py | 存储 Gradio Web 服务的 CSS 样式文件。 |
23
- | .\toolbox.py | 提供了一系列工具函数,包括文件读写、网页抓取、解析函数参数、生成 HTML 等。 |
24
- | ./crazy_functions/crazy_utils.py | 提供各种工具函数,如解析字符串、清洗文本、清理目录结构等。 |
25
- | ./crazy_functions/\_\_init\_\_.py | crazy_functions 模块的入口文件。 |
26
- | ./crazy_functions/下载arxiv论文翻译摘要.py | 对 arxiv.org 上的 PDF 论文进行下载和翻译。 |
27
- | ./crazy_functions/代码重写为全英文_多线程.py | 将代码文件中的中文注释和字符串替换为英文。 |
28
- | ./crazy_functions/总结word文档.py | 读取 Word 文档并生成摘要。 |
29
- | ./crazy_functions/批量总结PDF文档.py | 批量读取 PDF 文件并生成摘要。 |
30
- | ./crazy_functions/批量总结PDF文档pdfminer.py | 使用 pdfminer 库进行 PDF 文件处理。 |
31
- | ./crazy_functions/批量翻译PDF文档_多线程.py | 使用多线程技术批量翻译 PDF 文件。 |
32
- | ./crazy_functions/生成函数注释.py | 给 Python 函数自动生成说明文档。 |
33
- | ./crazy_functions/解析项目源代码.py | 解析项目中的源代码,提取注释和函数名等信息。 |
34
- | ./crazy_functions/读文章写摘要.py | 读取多个文本文件并生成对应的摘要。 |
35
- | ./crazy_functions/高级功能函数模板.py | 使用 GPT 模型进行文本处理。 |
36
-
37
-
38
-
39
- ## [0/22] 程序概述: check_proxy.py
40
-
41
- 该程序的文件名是check_proxy.py,主要有两个函数:check_proxy和auto_update。
42
-
43
- check_proxy函数中会借助requests库向一个IP查询API发送请求,并返回该IP的地理位置信息。同时根据返回的数据来判断代理是否有效。
44
-
45
- auto_update函数主要用于检查程序更新,会从Github获取程序最新的版本信息,如果当前版本和最新版本相差较大,则会提示用户进行更新。该函数中也会依赖requests库进行网络请求。
46
-
47
- 在程序的开头,还添加了一句防止代理网络影响的代码。程序使用了自己编写的toolbox模块中的get_conf函数来获取代理设置。
48
-
49
- ## [1/22] 程序概述: config.py
50
-
51
- 该程序文件是一个Python模块,文件名为config.py。该模块包含了一些变量和配置选项,用���配置一个OpenAI的聊天机器人。具体的配置选项如下:
52
-
53
- - API_KEY: 密钥,用于连接OpenAI的API。需要填写有效的API密钥。
54
- - USE_PROXY: 是否使用代理。如果需要使用代理,需要将其改为True。
55
- - proxies: 代理的协议、地址和端口。
56
- - CHATBOT_HEIGHT: 聊天机器人对话框的高度。
57
- - LAYOUT: 聊天机器人对话框的布局,默认为左右布局。
58
- - TIMEOUT_SECONDS: 发送请求到OpenAI后,等待多久判定为超时。
59
- - WEB_PORT: 网页的端口,-1代表随机端口。
60
- - MAX_RETRY: 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制。
61
- - LLM_MODEL: OpenAI模型选择,目前只对某些用户开放的gpt4。
62
- - API_URL: OpenAI的API地址。
63
- - CONCURRENT_COUNT: 使用的线程数。
64
- - AUTHENTICATION: 用户名和密码,如果需要。
65
-
66
- ## [2/22] 程序概述: config_private.py
67
-
68
- 该程序文件名为config_private.py,包含了API_KEY的设置和代理的配置。使用了一个名为API_KEY的常量来存储私人的API密钥。此外,还有一个名为USE_PROXY的常量来标记是否需要使用代理。如果需要代理,则使用了一个名为proxies的字典来存储代理网络的地址,其中包括协议类型、地址和端口。
69
-
70
- ## [3/22] 程序概述: core_functional.py
71
-
72
- 该程序文件名为`core_functional.py`,主要是定义了一些核心功能函数,包括英语和中文学术润色、查找语法错误、中译英、学术中英互译、英译中、找图片和解释代码等。每个功能都有一个`Prefix`属性和`Suffix`属性,`Prefix`是指在用户输入的任务前面要显示的文本,`Suffix`是指在任务后面要显示的文本。此外,还有一个`Color`属性指示按钮的颜色,以及一个`PreProcess`函数表示对输入进行预处理的函数。
73
-
74
- ## [4/22] 程序概述: cradle.py
75
-
76
- 该程序文件名为cradle.py,主要功能是检测当前版本与远程最新版本是否一致,如果不一致则输出新版本信息并提示更新。其流程大致如下:
77
-
78
- 1. 导入相关模块与自定义工具箱函数get_conf
79
- 2. 读取配置文件中的代理proxies
80
- 3. 使用requests模块请求远程版本信息(url为https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version)并加载为json格式
81
- 4. 获取远程版本号、是否显示新功能信息、新功能内容
82
- 5. 读取本地版本文件version并加载为json格式
83
- 6. 获取当前版本号
84
- 7. 比较当前版本与远程版本,如果远程版本号比当前版本号高0.05以上,则输出新版本信息并提示更新
85
- 8. 如果不需要更新,则直接返回
86
-
87
- ## [5/22] 程序概述: crazy_functional.py
88
-
89
- 该程序文件名为.\crazy_functional.py,主要定义了一个名为get_crazy_functions()的函数,该函数返回一个字典类型的变量function_plugins,其中包含了一些函数插件。
90
-
91
- 一些重要的函数插件包括:
92
-
93
- - 读文章写摘要:可以自动读取Tex格式的论文,并生成其摘要。
94
-
95
- - 批量生成函数注释:可以批量生成Python函数的文档注释。
96
-
97
- - 解析项目源代码:可以解析Python、C++、Golang、Java及React项目的源代码。
98
-
99
- - 批量总结PDF文档:可以对PDF文档进行批量总结,以提取其中的关键信息。
100
-
101
- - 一键下载arxiv论文并翻译摘要:可以自动下载arxiv.org网站上的PDF论文,并翻译生成其摘要。
102
-
103
- - 批量翻译PDF文档(多线程):可以对PDF文档进行批量翻译,并使用多线程方式提高翻译效率。
104
-
105
- ## [6/22] 程序概述: main.py
106
-
107
- 本程序为一个基于 Gradio 和 GPT-3 的交互式聊天机器人,文件名为 main.py。其中主要功能包括:
108
-
109
- 1. 使用 Gradio 建立 Web 界面,实现用户与聊天机器人的交互;
110
- 2. 通过 bridge_chatgpt 模块,利用 GPT-3 模型实现聊天机器人的逻辑;
111
- 3. 提供一些基础功能和高级函数插件,用户可以通过按钮选择使用;
112
- 4. 提供文档格式转变、外观调整以及代理和自动更新等功能。
113
-
114
- 程序的主要流程为:
115
-
116
- 1. 导入所需的库和模块,并通过 get_conf 函数获取配置信息;
117
- 2. 设置 Gradio 界面的各个组件,包括聊天窗口、输入区、功能区、函数插件区等;
118
- 3. 注册各个组件的回调函数,包括用户输入、信号按钮等,实现机器人逻辑的交互;
119
- 4. 通过 Gradio 的 queue 函数和 launch 函数启动 Web 服务,并提供聊天机器人的功能。
120
-
121
- 此外,程序还提供了代理和自动更新功能,可以确保用户的使用体验。
122
-
123
- ## [7/22] 程序概述: show_math.py
124
-
125
- 该程序是一个Python脚本,文件名为show_math.py。它转换Markdown和LaTeX混合语法到带MathML的HTML。程序使用latex2mathml模块来实现从LaTeX到MathML的转换,将符号转换为HTML实体以批量处理。程序利用正则表达式和递归函数的方法处理不同形式的LaTeX语法,支持以下四种情况:$$形式、$形式、\[..]形式和\(...\)形式。如果无法转��某个公式,则在该位置插入一条错误消息。最后,程序输出HTML字符串。
126
-
127
- ## [8/22] 程序概述: theme.py
128
-
129
- 该程序文件为一个Python脚本,其功能是调整Gradio应用的主题和样式,包括字体、颜色、阴影、背景等等。在程序中,使用了Gradio提供的默认颜色主题,并针对不同元素设置了相应的样式属性,以达到美化显示的效果。此外,程序中还包含了一段高级CSS样式代码,针对表格、列表、聊天气泡、行内代码等元素进行了样式设定。
130
-
131
- ## [9/22] 程序概述: toolbox.py
132
-
133
- 此程序文件主要包含了一系列用于聊天机器人开发的实用工具函数和装饰器函数。主要函数包括:
134
-
135
- 1. ArgsGeneralWrapper:一个装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。
136
-
137
- 2. get_reduce_token_percent:一个函数,用于计算自然语言处理时会出现的token溢出比例。
138
-
139
- 3. predict_no_ui_but_counting_down:一个函数,调用聊天接口,并且保留了一定的界面心跳功能,即当对话太长时,会自动采用二分法截断。
140
-
141
- 4. write_results_to_file:一个函数,将对话记录history生成Markdown格式的文本,并写入文件中。
142
-
143
- 5. regular_txt_to_markdown:一个函数,将普通文本转换为Markdown格式的文本。
144
-
145
- 6. CatchException:一个装饰器函数,捕捉函数调度中的异常,并封装到一个生成器中返回,并显示到聊天当中。
146
-
147
- 7. HotReload:一个装饰器函数,实现函数插件的热更新。
148
-
149
- 8. report_execption:一个函数,向chatbot中添加错误信息。
150
-
151
- 9. text_divide_paragraph:一个函数,将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
152
-
153
- 10. markdown_convertion:一个函数,将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。
154
-
155
- 11. close_up_code_segment_during_stream:一个函数,用于在gpt输出代码的中途,即输出了前面的```,但还没输出完后面的```,补上后面的```。
156
-
157
- 12. format_io:一个函数,将输入和输出解析为HTML格式。将输出部分的Markdown和数学公式转换为HTML格式。
158
-
159
- 13. find_free_port:一个函数,返回当前系统中可用的未使用端口。
160
-
161
- 14. extract_archive:一个函数,解压缩文件。
162
-
163
- 15. find_recent_files:一个函数,查找目录下一分钟内创建的文件。
164
-
165
- 16. on_file_uploaded:一个函数,响应用户上传的文件。
166
-
167
- ## [10/22] 程序概述: crazy_functions\crazy_utils.py
168
-
169
- 这是一个名为"crazy_utils.py"的Python程序文件,包含了两个函数:
170
- 1. `breakdown_txt_to_satisfy_token_limit()`:接受文本字符串、计算文本单词数量的函数和单词数量限制作为输入参数,将长文本拆分成合适的长度,以满足单词数量限制。这个函数使用一个递归方法去拆分长文本。
171
- 2. `breakdown_txt_to_satisfy_token_limit_for_pdf()`:类似于`breakdown_txt_to_satisfy_token_limit()`,但是它使用一个不同的递归方法来拆分长文本,以满足PDF文档中的需求。当出现无法继续拆分的情况时,该函数将使用一个中文句号标记插入文本来截断长文本。如果还是无法拆分,则会引发运行时异常。
172
-
173
- ## [11/22] 程序概述: crazy_functions\__init__.py
174
-
175
- 这个程序文件是一个 Python 的包,包名为 "crazy_functions",并且是其中的一个子模块 "__init__.py"。该包中可能包含多个函数或类,用于实现各种疯狂的功能。由于该文件的具体代码没有给出,因此无法进一步确定该包中的功能。通常情况下,一个包应该具有 __init__.py、__main__.py 和其它相关的模块文件,用于实现该包的各种功能。
176
-
177
- ## [12/22] 程序概述: crazy_functions\下载arxiv论文翻译摘要.py
178
-
179
- 这个程序实现的功能是下载arxiv论文并翻译摘要,文件名为`下载arxiv论文翻译摘要.py`。这个程序引入了`requests`、`unicodedata`、`os`、`re`等Python标准库,以及`pdfminer`、`bs4`等第三方库。其中`download_arxiv_`函数主要实现了从arxiv网站下载论文的功能,包括解析链接、获取论文信息、下载论文和生成文件名等,`get_name`函数则是为了从arxiv网站中获取论文信息创建的辅助函数。`下载arxiv论文并翻译摘要`函数则是实现了从下载好的PDF文件中提取摘要,然后使用预先训练的GPT模型翻译为中文的功能。同时,该函数还会将历史记录写入文件中。函数还会通过`CatchException`函数来捕获程序中出现的异常信息。
180
-
181
- ## [13/22] 程序概述: crazy_functions\代码重写为全英文_多线程.py
182
-
183
- 该程序文件为一个Python多线程程序,文件名为"crazy_functions\代码重写为全英文_多线程.py"。该程序使用了多线程技术,将一个大任务拆成多个小任务,同时执行,提高运行效率。
184
-
185
- 程序的主要功能是将Python文件中的中文转换为英文,同时���转换后的代码输出。程序先清空历史记录,然后尝试导入openai和transformers等依赖库。程序接下来会读取当前路径下的.py文件和crazy_functions文件夹中的.py文件,并将其整合成一个文件清单。随后程序会使用GPT2模型进行中英文的翻译,并将结果保存在本地路径下的"gpt_log/generated_english_version"文件夹中。程序最终会生成一个任务执行报告。
186
-
187
- 需要注意的是,该程序依赖于"request_llm"和"toolbox"库以及本地的"crazy_utils"模块。
188
-
189
- ## [14/22] 程序概述: crazy_functions\总结word文档.py
190
-
191
- 该程序文件是一个 Python 脚本文件,文件名为 ./crazy_functions/总结word文档.py。该脚本是一个函数插件,提供了名为“总结word文档”的函数。该函数的主要功能是批量读取给定文件夹下的 Word 文档文件,并使用 GPT 模型生成对每个文件的概述和意见建议。其中涉及到了读取 Word 文档、使用 GPT 模型等操作,依赖于许多第三方库。该文件也提供了导入依赖的方法,使用该脚本需要安装依赖库 python-docx 和 pywin32。函数功能实现的过程中,使用了一些用于调试的变量(如 fast_debug),可在需要时设置为 True。该脚本文件也提供了对程序功能和贡献者的注释。
192
-
193
- ## [15/22] 程序概述: crazy_functions\批量总结PDF文档.py
194
-
195
- 该程序文件名为 `./crazy_functions\批量总结PDF文档.py`,主要实现了批量处理PDF文档的功能。具体实现了以下几个函数:
196
-
197
- 1. `is_paragraph_break(match)`:根据给定的匹配结果判断换行符是否表示段落分隔。
198
- 2. `normalize_text(text)`:通过将文本特殊符号转换为其基本形式来对文本进行归一化处理。
199
- 3. `clean_text(raw_text)`:对从 PDF 提取出的原始文本进行清洗和格式化处理。
200
- 4. `解析PDF(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)`:对给定的PDF文件进行分析并生成相应的概述。
201
- 5. `批量总结PDF文档(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)`:批量处理PDF文件,对其进行摘要生成。
202
-
203
- 其中,主要用到了第三方库`pymupdf`对PDF文件进行处理。程序通过调用`fitz.open`函数打开PDF文件,使用`page.get_text()`方法获取PDF文本内容。然后,使用`clean_text`函数对文本进行清洗和格式化处理,生成最终的摘要。最后,调用`write_results_to_file`函数将历史记录写入文件并输出。
204
-
205
- ## [16/22] 程序概述: crazy_functions\批量总结PDF文档pdfminer.py
206
-
207
- 这个程序文件名是./crazy_functions\批量总结PDF文档pdfminer.py,是一个用于批量读取PDF文件,解析其中的内容,并对其进行概括的程序。程序中引用了pdfminer和beautifulsoup4等Python库,读取PDF文件并将其转化为文本内容,然后利用GPT模型生成摘要语言,最终输出一个中文和英文的摘要。程序还有一些错误处理的代码,会输出错误信息。
208
-
209
- ## [17/22] 程序概述: crazy_functions\批量翻译PDF文档_多线程.py
210
-
211
- 这是一个 Python 程序文件,文件名为 `批量翻译PDF文档_多线程.py`,包含多个函数。主要功能是批量处理 PDF 文档,解析其中的文本,进行清洗和格式化处理,并使用 OpenAI 的 GPT 模型进行翻译。其中使用了多线程技术来提高程序的效率和并行度。
212
-
213
- ## [18/22] 程序概述: crazy_functions\生成函数注释.py
214
-
215
- 该程序文件名为./crazy_functions\生成函数注释.py。该文件包含两个函数,分别为`生成函数注释`和`批量生成函数注释`。
216
-
217
- 函数`生成函数注释`包含参数`file_manifest`、`project_folder`、`top_p`、`temperature`、`chatbot`、`history`和`systemPromptTxt`。其中,`file_manifest`为一个包含待处理文件路径的列表,`project_folder`表示项目文件夹路径,`top_p`和`temperature`是GPT模型参数,`chatbot`为与用户交互的聊天机器人,`history`记录聊天机器人与用户的历史记录,`systemPromptTxt`为聊天机器人发送信息前的提示语。`生成函数注释`通过读取文件内容,并调用GPT模型对文件中的所有函数生成注释,最后使用markdown表格输出结果。函数中还包含一些条件判断和计时器,以及调用其他自定义模块的函数。
218
-
219
- 函数`批量生成函数注释`包含参数`txt`、`top_p`、`temperature`、`chatbot`、`history`、`systemPromptTxt`和`WEB_PORT`。其中,`txt`表示用户输入的项目文件夹路径,其他参数含义与`生成函数注释`中相同。`批量生成函数注释`主要是通过解析项目文件夹,获取所有待处理文件的路径,并调用函数`生成函数注释`对每个文件进行处理,最终生成注释表格输出给用户。
220
-
221
- ## [19/22] 程序概述: crazy_functions\解析项目源代码.py
222
-
223
- 该程序文件包含了多个函数,用于解析不同类型的项目,如Python项目、C项目、Java项目等。其中,最核心的函��是`解析源代码()`,它会对给定的一组文件进行分析,并返回对应的结果。具体流程如下:
224
-
225
- 1. 遍历所有待分析的文件,对每个文件进行如下处理:
226
-
227
- 1.1 从文件中读取代码内容,构造成一个字符串。
228
-
229
- 1.2 构造一条GPT请求,向`predict_no_ui_but_counting_down()`函数发送请求,等待GPT回复。
230
-
231
- 1.3 将GPT回复添加到机器人会话列表中,更新历史记录。
232
-
233
- 1.4 如果不是快速调试模式,则等待2秒钟,继续分析下一个文件。
234
-
235
- 2. 如果所有文件都分析完成,则向机器人会话列表中添加一条新消息,提示用户整个分析过程已经结束。
236
-
237
- 3. 返回机器人会话列表和历史记录。
238
-
239
- 除此之外,该程序文件还定义了若干个函数,用于针对不同类型的项目进行解析。这些函数会按照不同的方式调用`解析源代码()`函数。例如,对于Python项目,只需要分析.py文件;对于C项目,需要同时分析.h和.cpp文件等。每个函数中都会首先根据给定的项目路径读取相应的文件,然后调用`解析源代码()`函数进行分析。
240
-
241
- ## [20/22] 程序概述: crazy_functions\读文章写摘要.py
242
-
243
- 该程序文件为一个名为“读文章写摘要”的Python函数,用于解析项目文件夹中的.tex文件,并使用GPT模型生成文章的中英文摘要。函数使用了request_llm.bridge_chatgpt和toolbox模块中的函数,并包含两个子函数:解析Paper和CatchException。函数参数包括txt,top_p,temperature,chatbot,history,systemPromptTxt和WEB_PORT。执行过程中函数首先清空历史,然后根据项目文件夹中的.tex文件列表,对每个文件调用解析Paper函数生成中文摘要,最后根据所有文件的中文摘要,调用GPT模型生成英文摘要。函数运行过程中会将结果写入文件并返回聊天机器人和历史记录。
244
-
245
- ## [21/22] 程序概述: crazy_functions\高级功能函数模板.py
246
-
247
- 该程序文件为一个高级功能函数模板,文件名为"./crazy_functions\高级功能函数模板.py"。
248
-
249
- 该文件导入了两个模块,分别是"request_llm.bridge_chatgpt"和"toolbox"。其中"request_llm.bridge_chatgpt"模块包含了一个函数"predict_no_ui_long_connection",该函数用于请求GPT模型进行对话生成。"toolbox"模块包含了三个函数,分别是"catchException"、"report_exception"和"write_results_to_file"函数,这三个函数主要用于异常处理和日志记录等。
250
-
251
- 该文件定义了一个名为"高阶功能模板函数"的函数,并通过"decorator"装饰器将该函数装饰为一个异常处理函数,可以处理函数执行过程中出现的错误。该函数的作用是生成历史事件查询的问题,并向用户询问历史中哪些事件发生在指定日期,并索要相关图片。在查询完所有日期后,该函数返回所有历史事件及其相关图片的列表。其中,该函数的输入参数包括:
252
-
253
- 1. txt: 一个字符串,表示当前消息的文本内容。
254
- 2. top_p: 一个浮点数,表示GPT模型生成文本时的"top_p"参数。
255
- 3. temperature: 一个浮点数,表示GPT模型生成文本时的"temperature"参数。
256
- 4. chatbot: 一个列表,表示当前对话的记录列表。
257
- 5. history: 一个列表,表示当前对话的历史记录列表。
258
- 6. systemPromptTxt: 一个字符串,表示当前对话的系统提示信息。
259
- 7. WEB_PORT: 一个整数,表示当前应用程序的WEB端口号。
260
-
261
- 该函数在执行过程中,会先清空历史记录,以免输入溢出。然后,它会循环5次,生成5个历史事件查询的问题,并向用户请求输入相关信息。每次询问不携带之前的询问历史。在生成每个问题时,该函数会向"chatbot"列表中添加一条消息记录,并设置该记录的初始状态为"[Local Message] waiting gpt response."。然后,该函数会调用"predict_no_ui_long_connection"函数向GPT模型请求生成一段文本,并将生成的文本作为回答。如果请求过程中出现异常,该函数会忽略异常。最后,该函数将问题和回答添加到"chatbot"列表和"history"列表中,并将"chatbot"和"history"列表作为函数的返回值返回。
262
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
toolbox.py CHANGED
@@ -1,13 +1,10 @@
1
  import markdown
2
- import mdtex2html
3
- import threading
4
  import importlib
5
  import traceback
6
  import inspect
7
  import re
8
  from latex2mathml.converter import convert as tex2mathml
9
  from functools import wraps, lru_cache
10
-
11
  ############################### 插件输入输出接驳区 #######################################
12
  class ChatBotWithCookies(list):
13
  def __init__(self, cookie):
@@ -25,9 +22,9 @@ class ChatBotWithCookies(list):
25
 
26
  def ArgsGeneralWrapper(f):
27
  """
28
- 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。
29
  """
30
- def decorated(cookies, txt, txt2, top_p, temperature, chatbot, history, system_prompt, txt_pattern, *args):
31
  txt_passon = txt
32
  if txt == "" and txt2 != "": txt_passon = txt2
33
  # 引入一个有cookie的chatbot
@@ -37,8 +34,9 @@ def ArgsGeneralWrapper(f):
37
  })
38
  llm_kwargs = {
39
  'api_key': cookies['api_key'],
40
- 'llm_model': cookies['llm_model'],
41
  'top_p':top_p,
 
42
  'temperature':temperature,
43
  }
44
  # plugin_kwargs = {
@@ -56,8 +54,47 @@ def update_ui(chatbot, history, msg='正常', **kwargs): # 刷新界面
56
  """
57
  assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时,可用clear将其清空,然后用for+append循环重新赋值。"
58
  yield chatbot.get_cookies(), chatbot, history, msg
59
- ############################### ################## #######################################
60
- ##########################################################################################
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  def get_reduce_token_percent(text):
63
  """
@@ -76,71 +113,11 @@ def get_reduce_token_percent(text):
76
  except:
77
  return 0.5, '不详'
78
 
79
- def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, llm_kwargs, history=[], sys_prompt='', long_connection=True):
80
- """
81
- * 此函数未来将被弃用(替代函数 request_gpt_model_in_new_thread_with_ui_alive 文件 chatgpt_academic/crazy_functions/crazy_utils)
82
-
83
- 调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断
84
- i_say: 当前输入
85
- i_say_show_user: 显示到对话界面上的当前输入,例如,输入整个文件时,你绝对不想把文件的内容都糊到对话界面上
86
- chatbot: 对话界面句柄
87
- top_p, temperature: gpt参数
88
- history: gpt参数 对话历史
89
- sys_prompt: gpt参数 sys_prompt
90
- long_connection: 是否采用更稳定的连接方式(推荐)(已弃用)
91
- """
92
- import time
93
- from request_llm.bridge_chatgpt import predict_no_ui_long_connection
94
- from toolbox import get_conf
95
- TIMEOUT_SECONDS, MAX_RETRY = get_conf('TIMEOUT_SECONDS', 'MAX_RETRY')
96
- # 多线程的时候,需要一个mutable结构在不同线程之间传递信息
97
- # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息
98
- mutable = [None, '']
99
- # multi-threading worker
100
-
101
- def mt(i_say, history):
102
- while True:
103
- try:
104
- mutable[0] = predict_no_ui_long_connection(
105
- inputs=i_say, llm_kwargs=llm_kwargs, history=history, sys_prompt=sys_prompt)
106
-
107
- except ConnectionAbortedError as token_exceeded_error:
108
- # 尝试计算比例,尽可能多地保留文本
109
- p_ratio, n_exceed = get_reduce_token_percent(
110
- str(token_exceeded_error))
111
- if len(history) > 0:
112
- history = [his[int(len(his) * p_ratio):]
113
- for his in history if his is not None]
114
- else:
115
- i_say = i_say[: int(len(i_say) * p_ratio)]
116
- mutable[1] = f'警告,文本过长将进行截断,Token溢出数:{n_exceed},截断比例:{(1-p_ratio):.0%}。'
117
- except TimeoutError as e:
118
- mutable[0] = '[Local Message] 请求超时。'
119
- raise TimeoutError
120
- except Exception as e:
121
- mutable[0] = f'[Local Message] 异常:{str(e)}.'
122
- raise RuntimeError(f'[Local Message] 异常:{str(e)}.')
123
- # 创建新线程发出http请求
124
- thread_name = threading.Thread(target=mt, args=(i_say, history))
125
- thread_name.start()
126
- # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成
127
- cnt = 0
128
- while thread_name.is_alive():
129
- cnt += 1
130
- chatbot[-1] = (i_say_show_user,
131
- f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt % 4)))
132
- yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
133
- time.sleep(1)
134
- # 把gpt的输出从mutable中取出来
135
- gpt_say = mutable[0]
136
- if gpt_say == '[Local Message] Failed with timeout.':
137
- raise TimeoutError
138
- return gpt_say
139
 
140
 
141
  def write_results_to_file(history, file_name=None):
142
  """
143
- 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。
144
  """
145
  import os
146
  import time
@@ -168,7 +145,7 @@ def write_results_to_file(history, file_name=None):
168
 
169
  def regular_txt_to_markdown(text):
170
  """
171
- 将普通文本转换为Markdown格式的文本。
172
  """
173
  text = text.replace('\n', '\n\n')
174
  text = text.replace('\n\n\n', '\n\n')
@@ -176,48 +153,11 @@ def regular_txt_to_markdown(text):
176
  return text
177
 
178
 
179
- def CatchException(f):
180
- """
181
- 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。
182
- """
183
- @wraps(f)
184
- def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
185
- try:
186
- yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)
187
- except Exception as e:
188
- from check_proxy import check_proxy
189
- from toolbox import get_conf
190
- proxies, = get_conf('proxies')
191
- tb_str = '```\n' + traceback.format_exc() + '```'
192
- if chatbot is None or len(chatbot) == 0:
193
- chatbot = [["插件调度异常", "异常原因"]]
194
- chatbot[-1] = (chatbot[-1][0],
195
- f"[Local Message] 实验性函数调用出错: \n\n{tb_str} \n\n当前代理可用性: \n\n{check_proxy(proxies)}")
196
- yield from update_ui(chatbot=chatbot, history=history, msg=f'异常 {e}') # 刷新界面
197
- return decorated
198
-
199
-
200
- def HotReload(f):
201
- """
202
- HotReload的装饰器函数,用于实现Python函数插件的热更新。
203
- 函数热更新是指在不停止程序运行的情况下,更新函数代码,从而达到实时更新功能。
204
- 在装饰器内部,使用wraps(f)来保留函数的元信息,并定义了一个名为decorated的内部函数。
205
- 内部函数通过使用importlib模块的reload函数和inspect模块的getmodule函数来重新加载并获取函数模块,
206
- 然后通过getattr函数获取函数名,并在新模块中重新加载函数。
207
- 最后,使用yield from语句返回重新加载过的函数,并在被装饰的函数上执行。
208
- 最终,装饰器函数返回内部函数。这个内部函数可以将函数的原始定义更新为最新��本,并执行函数的新版本。
209
- """
210
- @wraps(f)
211
- def decorated(*args, **kwargs):
212
- fn_name = f.__name__
213
- f_hot_reload = getattr(importlib.reload(inspect.getmodule(f)), fn_name)
214
- yield from f_hot_reload(*args, **kwargs)
215
- return decorated
216
 
217
 
218
  def report_execption(chatbot, history, a, b):
219
  """
220
- 向chatbot中添加错误信息
221
  """
222
  chatbot.append((a, b))
223
  history.append(a)
@@ -226,7 +166,7 @@ def report_execption(chatbot, history, a, b):
226
 
227
  def text_divide_paragraph(text):
228
  """
229
- 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
230
  """
231
  if '```' in text:
232
  # careful input
@@ -242,7 +182,7 @@ def text_divide_paragraph(text):
242
 
243
  def markdown_convertion(txt):
244
  """
245
- 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。
246
  """
247
  pre = '<div class="markdown-body">'
248
  suf = '</div>'
@@ -334,7 +274,7 @@ def close_up_code_segment_during_stream(gpt_reply):
334
 
335
  def format_io(self, y):
336
  """
337
- 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。
338
  """
339
  if y is None or y == []:
340
  return []
@@ -350,7 +290,7 @@ def format_io(self, y):
350
 
351
  def find_free_port():
352
  """
353
- 返回当前系统中可用的未使用端口。
354
  """
355
  import socket
356
  from contextlib import closing
@@ -429,7 +369,7 @@ def find_recent_files(directory):
429
  return recent_files
430
 
431
 
432
- def on_file_uploaded(files, chatbot, txt):
433
  if len(files) == 0:
434
  return chatbot, txt
435
  import shutil
@@ -451,13 +391,18 @@ def on_file_uploaded(files, chatbot, txt):
451
  dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')
452
  moved_files = [fp for fp in glob.glob(
453
  'private_upload/**/*', recursive=True)]
454
- txt = f'private_upload/{time_tag}'
 
 
 
 
 
455
  moved_files_str = '\t\n\n'.join(moved_files)
456
  chatbot.append(['我上传了文件,请查收',
457
  f'[Local Message] 收到以下文件: \n\n{moved_files_str}' +
458
  f'\n\n调用路径参数已自动修正到: \n\n{txt}' +
459
  f'\n\n现在您点击任意“红颜色”标识的函数插件时,以上文件将被作为输入参数'+err_msg])
460
- return chatbot, txt
461
 
462
 
463
  def on_report_generated(files, chatbot):
@@ -470,9 +415,43 @@ def on_report_generated(files, chatbot):
470
  return report_files, chatbot
471
 
472
  def is_openai_api_key(key):
473
- # 正确的 API_KEY 是 "sk-" + 48 位大小写字母数字的组合
474
  API_MATCH = re.match(r"sk-[a-zA-Z0-9]{48}$", key)
475
- return API_MATCH
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
 
477
  @lru_cache(maxsize=128)
478
  def read_single_conf_with_lru_cache(arg):
@@ -483,14 +462,13 @@ def read_single_conf_with_lru_cache(arg):
483
  r = getattr(importlib.import_module('config'), arg)
484
  # 在读取API_KEY时,检查一下是不是忘了改config
485
  if arg == 'API_KEY':
486
- if is_openai_api_key(r):
487
  print亮绿(f"[API_KEY] 您的 API_KEY 是: {r[:15]}*** API_KEY 导入成功")
488
  else:
489
- print亮红( "[API_KEY] 正确的 API_KEY 是 'sk-' + '48 位大小写字母数字' 的组合,请在config文件中修改API密��, 添加海外代理之后再运行。" + \
490
- "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)")
491
  if arg == 'proxies':
492
  if r is None:
493
- print亮红('[PROXY] 网络代理状态:未配置。无代理状态下很可能无法访问。建议:检查USE_PROXY选项是否修改。')
494
  else:
495
  print亮绿('[PROXY] 网络代理状态:已配置。配置信息如下:', r)
496
  assert isinstance(r, dict), 'proxies格式错误,请注意proxies选项的格式,不要遗漏括号。'
 
1
  import markdown
 
 
2
  import importlib
3
  import traceback
4
  import inspect
5
  import re
6
  from latex2mathml.converter import convert as tex2mathml
7
  from functools import wraps, lru_cache
 
8
  ############################### 插件输入输出接驳区 #######################################
9
  class ChatBotWithCookies(list):
10
  def __init__(self, cookie):
 
22
 
23
  def ArgsGeneralWrapper(f):
24
  """
25
+ 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。
26
  """
27
+ def decorated(cookies, max_length, llm_model, txt, txt2, top_p, temperature, chatbot, history, system_prompt, txt_pattern, *args):
28
  txt_passon = txt
29
  if txt == "" and txt2 != "": txt_passon = txt2
30
  # 引入一个有cookie的chatbot
 
34
  })
35
  llm_kwargs = {
36
  'api_key': cookies['api_key'],
37
+ 'llm_model': llm_model,
38
  'top_p':top_p,
39
+ 'max_length': max_length,
40
  'temperature':temperature,
41
  }
42
  # plugin_kwargs = {
 
54
  """
55
  assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时,可用clear将其清空,然后用for+append循环重新赋值。"
56
  yield chatbot.get_cookies(), chatbot, history, msg
57
+
58
+ def CatchException(f):
59
+ """
60
+ 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。
61
+ """
62
+ @wraps(f)
63
+ def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
64
+ try:
65
+ yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)
66
+ except Exception as e:
67
+ from check_proxy import check_proxy
68
+ from toolbox import get_conf
69
+ proxies, = get_conf('proxies')
70
+ tb_str = '```\n' + traceback.format_exc() + '```'
71
+ if chatbot is None or len(chatbot) == 0:
72
+ chatbot = [["插件调度异常", "异常原因"]]
73
+ chatbot[-1] = (chatbot[-1][0],
74
+ f"[Local Message] 实验性函数调用出错: \n\n{tb_str} \n\n当前代理可用性: \n\n{check_proxy(proxies)}")
75
+ yield from update_ui(chatbot=chatbot, history=history, msg=f'异常 {e}') # 刷新界面
76
+ return decorated
77
+
78
+
79
+ def HotReload(f):
80
+ """
81
+ HotReload的装饰器函数,用于实现Python函数插件的热更新。
82
+ 函数热更新是指在不停止程序运行的情况下,更新函数代码,从而达到实时更新功能。
83
+ 在装饰器内部,使用wraps(f)来保留函数的元信息,并定义了一个名为decorated的内部函数。
84
+ 内部函数通过使用importlib模块的reload函数和inspect模块的getmodule函数来重新加载并获取函数模块,
85
+ 然后通过getattr函数获取函数名,并在新模块中重新加载函数。
86
+ 最后,使用yield from语句返回重新加载过的函数,并在被装饰的函数上执行。
87
+ 最终,装饰器函数返回内部函数。这个内部函数可以将函数的原始定义更新为最新版本,并执行函数的新版本。
88
+ """
89
+ @wraps(f)
90
+ def decorated(*args, **kwargs):
91
+ fn_name = f.__name__
92
+ f_hot_reload = getattr(importlib.reload(inspect.getmodule(f)), fn_name)
93
+ yield from f_hot_reload(*args, **kwargs)
94
+ return decorated
95
+
96
+
97
+ ####################################### 其他小工具 #####################################
98
 
99
  def get_reduce_token_percent(text):
100
  """
 
113
  except:
114
  return 0.5, '不详'
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
 
118
  def write_results_to_file(history, file_name=None):
119
  """
120
+ 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。
121
  """
122
  import os
123
  import time
 
145
 
146
  def regular_txt_to_markdown(text):
147
  """
148
+ 将普通文本转换为Markdown格式的文本。
149
  """
150
  text = text.replace('\n', '\n\n')
151
  text = text.replace('\n\n\n', '\n\n')
 
153
  return text
154
 
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
 
158
  def report_execption(chatbot, history, a, b):
159
  """
160
+ 向chatbot中添加错误信息
161
  """
162
  chatbot.append((a, b))
163
  history.append(a)
 
166
 
167
  def text_divide_paragraph(text):
168
  """
169
+ 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
170
  """
171
  if '```' in text:
172
  # careful input
 
182
 
183
  def markdown_convertion(txt):
184
  """
185
+ 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。
186
  """
187
  pre = '<div class="markdown-body">'
188
  suf = '</div>'
 
274
 
275
  def format_io(self, y):
276
  """
277
+ 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。
278
  """
279
  if y is None or y == []:
280
  return []
 
290
 
291
  def find_free_port():
292
  """
293
+ 返回当前系统中可用的未使用端口。
294
  """
295
  import socket
296
  from contextlib import closing
 
369
  return recent_files
370
 
371
 
372
+ def on_file_uploaded(files, chatbot, txt, txt2, checkboxes):
373
  if len(files) == 0:
374
  return chatbot, txt
375
  import shutil
 
391
  dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')
392
  moved_files = [fp for fp in glob.glob(
393
  'private_upload/**/*', recursive=True)]
394
+ if "底部输入区" in checkboxes:
395
+ txt = ""
396
+ txt2 = f'private_upload/{time_tag}'
397
+ else:
398
+ txt = f'private_upload/{time_tag}'
399
+ txt2 = ""
400
  moved_files_str = '\t\n\n'.join(moved_files)
401
  chatbot.append(['我上传了文件,请查收',
402
  f'[Local Message] 收到以下文件: \n\n{moved_files_str}' +
403
  f'\n\n调用路径参数已自动修正到: \n\n{txt}' +
404
  f'\n\n现在您点击任意“红颜色”标识的函数插件时,以上文件将被作为输入参数'+err_msg])
405
+ return chatbot, txt, txt2
406
 
407
 
408
  def on_report_generated(files, chatbot):
 
415
  return report_files, chatbot
416
 
417
  def is_openai_api_key(key):
 
418
  API_MATCH = re.match(r"sk-[a-zA-Z0-9]{48}$", key)
419
+ return bool(API_MATCH)
420
+
421
+ def is_api2d_key(key):
422
+ if key.startswith('fk') and len(key) == 41:
423
+ return True
424
+ else:
425
+ return False
426
+
427
+ def is_any_api_key(key):
428
+ if ',' in key:
429
+ keys = key.split(',')
430
+ for k in keys:
431
+ if is_any_api_key(k): return True
432
+ return False
433
+ else:
434
+ return is_openai_api_key(key) or is_api2d_key(key)
435
+
436
+
437
+ def select_api_key(keys, llm_model):
438
+ import random
439
+ avail_key_list = []
440
+ key_list = keys.split(',')
441
+
442
+ if llm_model.startswith('gpt-'):
443
+ for k in key_list:
444
+ if is_openai_api_key(k): avail_key_list.append(k)
445
+
446
+ if llm_model.startswith('api2d-'):
447
+ for k in key_list:
448
+ if is_api2d_key(k): avail_key_list.append(k)
449
+
450
+ if len(avail_key_list) == 0:
451
+ raise RuntimeError(f"您提供的api-key不满足要求,不包含任何可用于{llm_model}的api-key。")
452
+
453
+ api_key = random.choice(avail_key_list) # 随机负载均衡
454
+ return api_key
455
 
456
  @lru_cache(maxsize=128)
457
  def read_single_conf_with_lru_cache(arg):
 
462
  r = getattr(importlib.import_module('config'), arg)
463
  # 在读取API_KEY时,检查一下是不是忘了改config
464
  if arg == 'API_KEY':
465
+ if is_any_api_key(r):
466
  print亮绿(f"[API_KEY] 您的 API_KEY 是: {r[:15]}*** API_KEY 导入成功")
467
  else:
468
+ print亮红( "[API_KEY] 正确的 API_KEY 是'sk'开头的51位密钥(OpenAI),或者 'fk'开头的41位密钥,请在config文件中修改API密钥之后再运行。")
 
469
  if arg == 'proxies':
470
  if r is None:
471
+ print亮红('[PROXY] 网络代理状态:未配置。无代理状态下很可能无法访问OpenAI家族的模型。建议:检查USE_PROXY选项是否修改。')
472
  else:
473
  print亮绿('[PROXY] 网络代理状态:已配置。配置信息如下:', r)
474
  assert isinstance(r, dict), 'proxies格式错误,请注意proxies选项的格式,不要遗漏括号。'
version CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "version": 2.7,
3
  "show_feature": true,
4
- "new_feature": "修复BUG <-> 改善理解pdf(chatpdf)功能 <-> 如果一键更新失败,可前往github手动更新"
5
  }
 
1
  {
2
+ "version": 3.1,
3
  "show_feature": true,
4
+ "new_feature": "添加支持清华ChatGLM和GPT-4 <-> 改进架构,支持与多个LLM模型同时对话 <-> 添加支持API2D(国内,可支持gpt4)<-> 支持多API-KEY负载均衡(并列填写,逗号分割) <-> 添加输入区文本清除按键"
5
  }