Author SHA1 Message Date
qingxu fu 57a668bf30 自译解报告 2023-03-30 18:21:17 +08:00
qingxu fu 700d14be10 Merge branch 'hot-reload-test' of https://github.com/binary-husky/chatgpt_academic into hot-reload-test 2023-03-30 18:05:03 +08:00
qingxu fu 3fe96956ce 新增热更新功能 2023-03-30 18:04:20 +08:00
qingxu fu c358c95630 新增热更新功能 2023-03-30 18:01:06 +08:00
binary-husky 1c3ce18eff Update README.md 2023-03-30 14:48:46 +08:00
binary-husky a689960e31 Update README.md 2023-03-30 14:48:20 +08:00
binary-husky 07eca9fe55 Update README.md 2023-03-30 14:47:19 +08:00
binary-husky 00f29f2120 Update README.md 2023-03-30 14:08:24 +08:00
binary-husky 10ea3daaa5 Update README.md 2023-03-30 13:24:30 +08:00
binary-husky eb95eec122 Merge pull request #124 from Freddd13/master
feat: 添加wsl2使用windows proxy的方法
2023-03-30 12:56:13 +08:00
qingxu fu e03634f9e2 查找语法错误之前先清除换行符 2023-03-30 12:52:28 +08:00
qingxu fu 77d4628877 语法错误查找prompt更新 2023-03-30 12:16:18 +08:00
qingxu fu 8c3d37bbce up 2023-03-30 11:51:55 +08:00
qingxu fu 28f6801870 标准化代码格式 2023-03-30 11:50:11 +08:00
qingxu fu 6d7fb20b5a 修改配置的读取方式 2023-03-30 11:05:38 +08:00
Freddd13 9dc0d3273b update: 修改readme 2023-03-30 02:00:15 +08:00
Freddd13 13e976774f Merge remote-tracking branch 'upstream/master' 2023-03-30 01:58:39 +08:00
Freddd13 35d3346a1c feat: 支持wsl2使用windows proxy 2023-03-30 01:47:39 +08:00
Your Name eaec1c3728 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-30 00:15:37 +08:00
Your Name 0140b0cda8 change UI layout 2023-03-30 00:15:31 +08:00
binary-husky f98fe5b9ab Update README.md 2023-03-30 00:09:58 +08:00
binary-husky 0063f8dd82 Update README.md 2023-03-29 23:53:33 +08:00
binary-husky 23b8c47c54 Update README.md 2023-03-29 23:50:20 +08:00
binary-husky 5353a32345 Update README.md 2023-03-29 23:48:58 +08:00
binary-husky d569d2f9c1 Update README.md 2023-03-29 23:44:37 +08:00
binary-husky 67e6070d80 Update README.md 2023-03-29 23:44:01 +08:00
binary-husky 01873f7811 Merge pull request #108 from sjiang95/condainstall
readme: update
2023-03-29 23:22:44 +08:00
Your Name c2318bc197 Merge branch 'dev' 2023-03-29 23:15:29 +08:00
binary-husky 86dc4ca3af Merge pull request #102 from ValeriaWong/master
feat(读文章写摘要):支持pdf文件批量阅读及总结 #101
2023-03-29 23:14:12 +08:00
Your Name 4a2f73d007 change UI layout 2023-03-29 23:04:37 +08:00
Your Name 9c643e6d8c change ui layout 2023-03-29 23:00:16 +08:00
Your Name 34323c9d36 Merge https://github.com/ValeriaWong/chatgpt_academic into ValeriaWong-master 2023-03-29 21:49:56 +08:00
Your Name 48cc2349e3 add pip package check 2023-03-29 21:47:56 +08:00
Your Name 7d57967519 Merge branch 'master' of https://github.com/ValeriaWong/chatgpt_academic 2023-03-29 21:44:59 +08:00
Shengjiang Quan 68ffa54c84 readme: update
Re-format a part of the markdown content
and add conda instruction for installation.

Signed-off-by: Shengjiang Quan <[email protected]>
2023-03-29 22:36:15 +09:00
ValeriaWong 02ddcdf731 Merge branch 'master' of https://github.com/ValeriaWong/chatgpt_academic 2023-03-29 21:05:25 +08:00
ValeriaWong 14ea206a5a Merge branch 'binary-husky:master' into master 2023-03-29 20:57:07 +08:00
ValeriaWong 814c93bb75 feat(读文章写摘要):支持pdf文件批量阅读及总结 #101 2023-03-29 20:55:13 +08:00
binary-husky fb953148b9 Update main.py 2023-03-29 20:47:34 +08:00
Your Name 2bcd34360a bug quick fix 2023-03-29 20:41:07 +08:00
binary-husky b3211362f9 Merge pull request #82 from Okabe-Rintarou-0/master
支持暂停按钮 #53
2023-03-29 20:38:06 +08:00
Your Name be1bf6cb77 提交后不清空输入栏,添加停止键 2023-03-29 20:36:58 +08:00
Your Name 5f771d8acf Merge branch 'master' of https://github.com/Okabe-Rintarou-0/chatgpt_academic into Okabe-Rintarou-0-master 2023-03-29 20:26:13 +08:00
Your Name 095579c323 Merge branch 'master' of https://github.com/Okabe-Rintarou-0/chatgpt_academic into Okabe-Rintarou-0-master 2023-03-29 20:07:38 +08:00
Your Name f9308300f3 handle ip location lookup error 2023-03-29 19:37:39 +08:00
binary-husky 6ca28fbff2 Merge pull request #87 from Okabe-Rintarou-0/fix-markdown-display
正确显示多行输入的 markdown #84
2023-03-29 19:32:19 +08:00
binary-husky 11f619f76f Merge pull request #96 from eltociear/patch-1
fix typo in predict.py
2023-03-29 18:47:51 +08:00
Your Name 39d0176673 新增代理配置说明 2023-03-29 18:07:33 +08:00
Ikko Eltociear Ashimine 043bd59ffc fix typo in predict.py
refleshing -> refreshing
2023-03-29 18:57:37 +09:00
ValeriaWong 2ac602e0aa feat(读文章写摘要):支持pdf文件批量阅读及总结 2023-03-29 17:57:17 +08:00
Your Name 50ee37f23c error message change 2023-03-29 16:50:37 +08:00
Your Name f0d9098df5 dev 2023-03-29 16:47:15 +08:00
okabe 2401cf2136 fix: markdown display bug #84 2023-03-29 15:29:40 +08:00
okabe dd3c4f988c feat: support stop generate button (#53) 2023-03-29 14:53:53 +08:00
Your Name 22e7dc617b fix directory return bug 2023-03-29 14:28:57 +08:00
Your Name a3c937c202 update comments 2023-03-29 14:16:59 +08:00
505030475 1b01d0fd8a 修复变量名 2023-03-29 13:58:30 +08:00
505030475 0b018bf871 Merge remote-tracking branch 'origin/test-3-29' 2023-03-29 13:44:57 +08:00
505030475 88d41ab4ca config comments 2023-03-29 13:43:07 +08:00
binary-husky 6ebadeb2a6 Update README.md 2023-03-29 13:38:43 +08:00
binary-husky 515045a8d1 Merge pull request #57 from GaiZhenbiao/master
Adding a bunch of nice-to-have features
2023-03-29 13:37:58 +08:00
Your Name 74d5061969 Merge branch 'test-3-29' of github.com:binary-husky/chatgpt_academic into test-3-29 2023-03-29 12:29:52 +08:00
Your Name 0b7c1c50ca 优化Unsplash API的使用 2023-03-29 12:28:45 +08:00
Your Name f45e0d3486 优化Unsplash API的使用 2023-03-29 12:27:47 +08:00
Your Name 881132557e 历史上的今天,带图片 2023-03-29 12:21:47 +08:00
Your Name 6d852d76b0 更新一个更有意思的模板函数 2023-03-29 11:36:55 +08:00
Your Name b588291cdf [实验] 历史上的今天(高级函数demo) 2023-03-29 11:34:03 +08:00
Your Name b4e0fe39ea bug fix 2023-03-29 01:42:11 +08:00
Your Name 7295978c93 change description 2023-03-29 01:39:15 +08:00
Your Name f2359e0442 更好的多线程交互性 2023-03-29 01:32:28 +08:00
Your Name ced6898daa introduce project self-translation 2023-03-29 01:11:53 +08:00
Tuchuanhuhuhu 39ad492a65 增加“重置”按钮,提交之后自动清空输入框 2023-03-28 23:33:19 +08:00
Tuchuanhuhuhu dd8ec0d511 temprature的取值范围为[0, 2] 2023-03-28 23:20:54 +08:00
Tuchuanhuhuhu 43d59d936f 增加并行处理与权限控制 2023-03-28 23:17:12 +08:00
Your Name 4bca8b4f82 simplify codes 2023-03-28 23:09:25 +08:00
Chuan Hu 46eba1f399 Improve the way to open webbrowser 2023-03-28 22:47:30 +08:00
Your Name 5a6877f9fa 界面色彩自定义 2023-03-28 22:35:55 +08:00
Your Name 2c15b51ea4 explain color and theme 2023-03-28 22:31:43 +08:00
Your Name 9666b9b99b Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-28 22:25:27 +08:00
Your Name baf61477d2 remove .vscode from git 2023-03-28 22:24:59 +08:00
Your Name 00e411bd68 update todo 2023-03-28 22:10:22 +08:00
Your Name 37bcdf684d fix unicode bug 2023-03-28 20:31:44 +08:00
binary-husky c80808a0c5 Merge pull request #46 from mambaHu/master
Markdown analysis report garbled issue
2023-03-28 20:04:01 +08:00
luca hu b69313884d improving garbled words issue with utf8 2023-03-28 19:34:18 +08:00
binary-husky 3b6675755e Delete jpeg-compressor.tps 2023-03-28 17:21:14 +08:00
binary-husky 3e2e4937db Delete JpegLibrary.tps 2023-03-28 17:21:06 +08:00
binary-husky e6f7e75e19 Delete UElibJPG.Build.cs 2023-03-28 17:20:54 +08:00
505030475 232d06a1ab theme 2023-03-28 12:59:31 +08:00
505030475 22db1147db o 2023-03-28 12:53:05 +08:00
binary-husky eb77532df5 Update README.md 2023-03-28 01:36:15 +08:00
binary-husky 9ee3d1390d Update README.md 2023-03-28 01:13:55 +08:00
Your Name 141df08332 http post error show 2023-03-27 18:25:07 +08:00
Your Name 248bcb7095 bug fix 2023-03-27 15:16:50 +08:00
Your Name 7c7b1cb030 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-27 15:14:12 +08:00
Your Name 290a33ea74 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-27 15:14:05 +08:00
binary-husky aabe2818e7 Update README.md 2023-03-27 15:09:02 +08:00
binary-husky c3a6a09c4c Update README.md 2023-03-27 15:01:49 +08:00
binary-husky 8c5332748f Update README.md 2023-03-27 15:01:07 +08:00
binary-husky 0b0860defc Update README.md 2023-03-27 14:57:12 +08:00
binary-husky 18894b04f1 Update README.md 2023-03-27 14:56:32 +08:00
binary-husky 8e75ad8134 Update README.md 2023-03-27 14:56:20 +08:00
binary-husky 7c33580bf6 Update README.md 2023-03-27 14:56:03 +08:00
Your Name 223e747d57 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-27 14:53:46 +08:00
Your Name 8c7be26661 up 2023-03-27 14:51:05 +08:00
binary-husky a1fceeae45 Update README.md 2023-03-27 14:47:52 +08:00
binary-husky 4b534400ea Update README.md 2023-03-27 14:45:32 +08:00
binary-husky ac9b590660 Update README.md 2023-03-27 13:47:08 +08:00
binary-husky 695ed5e02d Update README.md 2023-03-27 13:45:08 +08:00
Your Name c063510442 UI change 2023-03-27 13:24:29 +08:00
Your Name bc6d0926b1 file IO 2023-03-27 13:01:22 +08:00
qingxu fu 0f20ffeff4 localFileToRemote 2023-03-27 11:29:11 +08:00
20 changed files with 866 additions and 227 deletions
+4
View File
@@ -131,8 +131,12 @@ dmypy.json
# Pyre type checker
.pyre/
.vscode
history
ssr_conf
config_private.py
gpt_log
private.md
private_upload
other_llms
-16
View File
@@ -1,16 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": false
}
]
}
+100 -34
View File
@@ -1,8 +1,31 @@
# ChatGPT 学术优化
**如果喜欢这个项目,请给它一个Star;如果你发明了更好用的学术快捷键,欢迎发issue或者pull requests**
If you like this project, please give it a Star. If you've come up with more useful academic shortcuts, feel free to open an issue or pull request.
```
代码中参考了很多其他优秀项目中的设计,主要包括:
# 借鉴项目1:借鉴了ChuanhuChatGPT中读取OpenAI json的方法、记录历史问询记录的方法以及gradio queue的使用技巧
https://github.com/GaiZhenbiao/ChuanhuChatGPT
# 借鉴项目2:借鉴了mdtex2html中公式处理的方法
https://github.com/polarwinkel/mdtex2html
项目使用OpenAI的gpt-3.5-turbo模型,期待gpt-4早点放宽门槛😂
```
> **Note**
>
> 1.请注意只有“红颜色”标识的函数插件(按钮)才支持读取文件。目前暂不能完善地支持pdf格式文献的翻译解读,尚不支持word格式文件的读取。
>
> 2.本项目中每个文件的功能都在`project_self_analysis.md`详细说明。随着版本的迭代,您也可以随时自行点击相关函数插件,调用GPT重新生成项目的自译解报告。
>
> 3.如果您不太习惯部分中文命名的函数,您可以随时点击相关函数插件,调用GPT一键生成纯英文的项目源代码。
<div align="center">
功能 | 描述
@@ -21,12 +44,13 @@ chat分析报告生成 | [实验性功能] 运行后自动生成总结汇报
公式显示 | 可以同时显示公式的tex形式和渲染形式
图片显示 | 可以在markdown中显示图片
支持GPT输出的markdown表格 | 可以输出支持GPT的markdown表格
…… | ……
</div>
- 新界面
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227528413-36ab42da-d589-4ef1-ba75-28aa02442d05.png" width="700" >
<img src="https://user-images.githubusercontent.com/96192199/228600410-7d44e34f-63f1-4046-acb8-045cb05da8bb.png" width="700" >
</div>
@@ -36,7 +60,7 @@ chat分析报告生成 | [实验性功能] 运行后自动生成总结汇报
<img src="img/公式.gif" width="700" >
</div>
- 代码的显示自然也不在话下 https://www.bilibili.com/video/BV1F24y147PD/
- 润色/纠错
<div align="center">
<img src="img/润色.gif" width="700" >
</div>
@@ -58,33 +82,61 @@ chat分析报告生成 | [实验性功能] 运行后自动生成总结汇报
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
</div>
## 直接运行 (Windows or Linux or MacOS)
## 直接运行 (Windows, Linux or MacOS)
``` sh
# 下载项目
下载项目
```sh
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
# 在config.py中,配置 海外Proxy 和 OpenAI API KEY
- 1.如果你在国内,需要设置海外代理才能够使用 OpenAI API,你可以通过 config.py 文件来进行设置。
- 2.配置 OpenAI API KEY。你需要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。
# 安装依赖
python -m pip install -r requirements.txt
# 运行
python main.py
# 测试实验性功能
## 测试C++项目头文件分析
input区域 输入 ./crazy_functions/test_project/cpp/libJPG 然后点击 "[实验] 解析整个C++项目(input输入项目根路径)"
## 测试给Latex项目写摘要
input区域 输入 ./crazy_functions/test_project/latex/attention 然后点击 "[实验] 读tex论文写摘要(input输入项目根路径)"
## 测试Python项目分析
input区域 输入 ./crazy_functions/test_project/python/dqn 然后点击 "[实验] 解析整个py项目(input输入项目根路径)"
## 测试自我代码解读
点击 "[实验] 请解析并解构此项目本身"
## 测试实验功能模板函数(要求gpt回答几个数的平方是什么),您可以根据此函数为模板,实现更复杂的功能
点击 "[实验] 实验功能函数模板"
```
我们建议将`config.py`复制为`config_private.py`并将后者用作个性化配置文件以避免`config.py`中的变更影响你的使用或不小心将包含你的OpenAI API KEY的`config.py`提交至本项目。
```sh
cp config.py config_private.py
```
`config_private.py`中,配置 海外Proxy 和 OpenAI API KEY
```
1. 如果你在国内,需要设置海外代理才能够使用 OpenAI API,你可以通过 config.py 文件来进行设置。
2. 配置 OpenAI API KEY。你需要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。
```
安装依赖
```sh
python -m pip install -r requirements.txt
```
或者,如果你希望使用`conda`
```sh
conda create -n gptac 'gradio>=3.23' requests
conda activate gptac
python3 -m pip install mdtex2html
```
运行
```sh
python main.py
```
测试实验性功能
```
- 测试C++项目头文件分析
input区域 输入 `./crazy_functions/test_project/cpp/libJPG` 然后点击 "[实验] 解析整个C++项目(input输入项目根路径)"
- 测试给Latex项目写摘要
input区域 输入 `./crazy_functions/test_project/latex/attention` 然后点击 "[实验] 读tex论文写摘要(input输入项目根路径)"
- 测试Python项目分析
input区域 输入 `./crazy_functions/test_project/python/dqn` 然后点击 "[实验] 解析整个py项目(input输入项目根路径)"
- 测试自我代码解读
点击 "[实验] 请解析并解构此项目本身"
- 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
点击 "[实验] 实验功能函数模板"
```
与代理网络有关的issue(网络超时、代理不起作用)汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1
## 使用docker (Linux)
@@ -102,7 +154,7 @@ docker run --rm -it --net=host gpt-academic
# 测试实验性功能
## 测试自我代码解读
点击 "[实验] 请解析并解构此项目本身"
## 测试实验功能模板函数(要求gpt回答几个数的平方是什么),您可以根据此函数为模板,实现更复杂的功能
## 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
点击 "[实验] 实验功能函数模板"
##(请注意在docker中运行时,需要额外注意程序的文件访问权限问题)
## 测试C++项目头文件分析
@@ -114,6 +166,21 @@ input区域 输入 ./crazy_functions/test_project/python/dqn 然后点击 "[
```
## 使用WSL2Windows Subsystem for Linux 子系统)
选择这种方式默认您已经具备一定基本知识,因此不再赘述多余步骤。如果不是这样,您可以从[这里](https://learn.microsoft.com/zh-cn/windows/wsl/about)或GPT处获取更多关于子系统的信息。
WSL2可以配置使用Windows侧的代理上网,前置步骤可以参考[这里](https://www.cnblogs.com/tuilk/p/16287472.html)
由于Windows相对WSL2的IP会发生变化,我们需要每次启动前先获取这个IP来保证顺利访问,将config.py中设置proxies的部分更改为如下代码:
```python
import subprocess
cmd_get_ip = 'grep -oP "(\d+\.)+(\d+)" /etc/resolv.conf'
ip_proxy = subprocess.run(
cmd_get_ip, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True
).stdout.strip() # 获取windows的IP
proxies = { "http": ip_proxy + ":51837", "https": ip_proxy + ":51837", } # 请自行修改
```
在启动main.py后,可以在windows浏览器中访问服务。至此测试、使用与上面其他方法无异。
## 自定义新的便捷按钮(学术快捷键自定义)
打开functional.py,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。)
@@ -153,11 +220,12 @@ python check_proxy.py
## 兼容性测试
### 图片显示:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226906087-b5f1c127-2060-4db9-af05-487643b21ed9.png" height="200" >
<img src="https://user-images.githubusercontent.com/96192199/226906703-7226495d-6a1f-4a53-9728-ce6778cbdd19.png" height="200" >
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
</div>
### 如果一个程序能够读懂并剖析自己:
<div align="center">
@@ -195,11 +263,9 @@ python check_proxy.py
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
</div>
## Todo:
- (Top Priority) 调用另一个开源项目text-generation-webui的web接口,使用其他llm模型
- 总结大工程源代码时,文本过长、token溢出的问题(目前的方法是直接二分丢弃处理溢出,过于粗暴,有效信息大量丢失)
- UI不够美观
## 参考项目
```
https://github.com/Python-Markdown/markdown
https://github.com/gradio-app/gradio
https://github.com/polarwinkel/mdtex2html
https://github.com/GaiZhenbiao/ChuanhuChatGPT
```
+9 -4
View File
@@ -6,8 +6,11 @@ def check_proxy(proxies):
response = requests.get("https://ipapi.co/json/", proxies=proxies, timeout=4)
data = response.json()
print(f'查询代理的地理位置,返回的结果是{data}')
country = data['country_name']
result = f"代理配置 {proxies_https}, 代理所在地:{country}"
if 'country_name' in data:
country = data['country_name']
result = f"代理配置 {proxies_https}, 代理所在地:{country}"
elif 'error' in data:
result = f"代理配置 {proxies_https}, 代理所在地:未知,IP查询频率受限"
print(result)
return result
except:
@@ -17,6 +20,8 @@ def check_proxy(proxies):
if __name__ == '__main__':
try: from config_private import proxies # 放自己的秘密如API和代理网址 os.path.exists('config_private.py')
except: from config import proxies
import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
from toolbox import get_conf
proxies, = get_conf('proxies')
check_proxy(proxies)
+13 -4
View File
@@ -5,6 +5,13 @@ API_URL = "https://api.openai.com/v1/chat/completions"
# 改为True应用代理
USE_PROXY = False
if USE_PROXY:
# 填写格式是 [协议]:// [地址] :[端口]
# 例如 "socks5h://localhost:11284"
# [协议] 常见协议无非socks5h/http,例如 v2*** 和 s** 的默认本地协议是socks5hcl**h 的默认本地协议是http
# [地址] 懂的都懂,不懂就填localhost或者127.0.0.1肯定错不了(localhost意思是代理软件安装在本机上)
# [端口] 在代理软件的设置里,不同的代理软件界面不一样,但端口号都应该在最显眼的位置上
# 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
proxies = { "http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", }
print('网络代理状态:运行。')
@@ -13,7 +20,7 @@ else:
print('网络代理状态:未配置。无代理状态下很可能无法访问。')
# 发送请求到OpenAI后,等待多久判定为超时
TIMEOUT_SECONDS = 20
TIMEOUT_SECONDS = 25
# 网页的端口, -1代表随机端口
WEB_PORT = -1
@@ -24,6 +31,8 @@ MAX_RETRY = 2
# 选择的OpenAI模型是(gpt4现在只对申请成功的人开放)
LLM_MODEL = "gpt-3.5-turbo"
# 检查一下是不是忘了改config
if API_KEY == "sk-此处填API秘钥":
assert False, "请在config文件中修改API密钥, 添加海外代理之后再运行"
# 设置并行使用的线程数
CONCURRENT_COUNT = 100
# 设置用户名和密码
AUTHENTICATION = [] # [("username", "password"), ("username2", "password2"), ...]
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<TpsData xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>Jpeg Library</Name>
<Location>/Engine/Source/ThirdParty/libJPG/</Location>
<Date>2016-06-10T14:04:17.9005402-04:00</Date>
<Function>We need it because it is a 3rd party lib in GFx</Function>
<Justification />
<Eula> See license in download: http://www.ijg.org/</Eula>
<RedistributeTo>
<EndUserGroup>Licensees</EndUserGroup>
<EndUserGroup>Git</EndUserGroup>
<EndUserGroup>P4</EndUserGroup>
</RedistributeTo>
<LicenseFolder>/Engine/Source/ThirdParty/Licenses/JPEG_License.txt</LicenseFolder>
</TpsData>
@@ -1,17 +0,0 @@
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class UElibJPG : ModuleRules
{
public UElibJPG(ReadOnlyTargetRules Target) : base(Target)
{
Type = ModuleType.External;
string libJPGPath = Target.UEThirdPartySourceDirectory + "libJPG";
PublicIncludePaths.Add(libJPGPath);
ShadowVariableWarningLevel = WarningLevel.Off;
}
}
@@ -1,15 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<TpsData xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>jpeg-compressor</Name>
<Location>/Engine/Source/ThirdParty/libJPG/</Location>
<Date>2016-06-10T14:07:13.8351319-04:00</Date>
<Function>Allows JPEG compression and decompression.</Function>
<Justification>Compressing video frames at runtime for reduced memory usage. Decompression to access the data afterwards.</Justification>
<Eula>https://code.google.com/archive/p/jpeg-compressor/</Eula>
<RedistributeTo>
<EndUserGroup>Licensees</EndUserGroup>
<EndUserGroup>Git</EndUserGroup>
<EndUserGroup>P4</EndUserGroup>
</RedistributeTo>
<LicenseFolder>None</LicenseFolder>
</TpsData>
@@ -0,0 +1,75 @@
import threading
from predict import predict_no_ui_long_connection
from toolbox import CatchException, write_results_to_file
@CatchException
def 全项目切换英文(txt, top_p, temperature, chatbot, history, sys_prompt, WEB_PORT):
history = [] # 清空历史,以免输入溢出
# 集合文件
import time, glob, os
os.makedirs('gpt_log/generated_english_version', exist_ok=True)
os.makedirs('gpt_log/generated_english_version/crazy_functions', exist_ok=True)
file_manifest = [f for f in glob.glob('./*.py') if ('test_project' not in f) and ('gpt_log' not in f)] + \
[f for f in glob.glob('./crazy_functions/*.py') if ('test_project' not in f) and ('gpt_log' not in f)]
i_say_show_user_buffer = []
# 随便显示点什么防止卡顿的感觉
for index, fp in enumerate(file_manifest):
# if 'test_project' in fp: continue
with open(fp, 'r', encoding='utf-8') as f:
file_content = f.read()
i_say_show_user =f'[{index}/{len(file_manifest)}] 接下来请将以下代码中包含的所有中文转化为英文,只输出代码: {os.path.abspath(fp)}'
i_say_show_user_buffer.append(i_say_show_user)
chatbot.append((i_say_show_user, "[Local Message] 等待多线程操作,中间过程不予显示."))
yield chatbot, history, '正常'
# 任务函数
mutable_return = [None for _ in file_manifest]
def thread_worker(fp,index):
with open(fp, 'r', encoding='utf-8') as f:
file_content = f.read()
i_say = f'接下来请将以下代码中包含的所有中文转化为英文,只输出代码,文件名是{fp},文件代码是 ```{file_content}```'
# ** gpt request **
gpt_say = predict_no_ui_long_connection(inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt)
mutable_return[index] = gpt_say
# 所有线程同时开始执行任务函数
handles = [threading.Thread(target=thread_worker, args=(fp,index)) for index, fp in enumerate(file_manifest)]
for h in handles:
h.daemon = True
h.start()
chatbot.append(('开始了吗?', f'多线程操作已经开始'))
yield chatbot, history, '正常'
# 循环轮询各个线程是否执行完毕
cnt = 0
while True:
time.sleep(1)
th_alive = [h.is_alive() for h in handles]
if not any(th_alive): break
stat = ['执行中' if alive else '已完成' for alive in th_alive]
stat_str = '|'.join(stat)
cnt += 1
chatbot[-1] = (chatbot[-1][0], f'多线程操作已经开始,完成情况: {stat_str}' + ''.join(['.']*(cnt%4)))
yield chatbot, history, '正常'
# 把结果写入文件
for index, h in enumerate(handles):
h.join() # 这里其实不需要join了,肯定已经都结束了
fp = file_manifest[index]
gpt_say = mutable_return[index]
i_say_show_user = i_say_show_user_buffer[index]
where_to_relocate = f'gpt_log/generated_english_version/{fp}'
with open(where_to_relocate, 'w+', encoding='utf-8') as f: f.write(gpt_say.lstrip('```').rstrip('```'))
chatbot.append((i_say_show_user, f'[Local Message] 已完成{os.path.abspath(fp)}的转化,\n\n存入{os.path.abspath(where_to_relocate)}'))
history.append(i_say_show_user); history.append(gpt_say)
yield chatbot, history, '正常'
time.sleep(1)
# 备份一个文件
res = write_results_to_file(history)
chatbot.append(("生成一份任务执行报告", res))
yield chatbot, history, '正常'
+99
View File
@@ -0,0 +1,99 @@
from predict import predict_no_ui
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
fast_debug = False
def 解析PDF(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt):
import time, glob, os, fitz
print('begin analysis on:', file_manifest)
for index, fp in enumerate(file_manifest):
with fitz.open(fp) as doc:
file_content = ""
for page in doc:
file_content += page.get_text()
print(file_content)
prefix = "接下来请你逐文件分析下面的论文文件,概括其内容" if index==0 else ""
i_say = prefix + f'请对下面的文章片段用中文做一个概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{file_content}```'
i_say_show_user = prefix + f'[{index}/{len(file_manifest)}] 请对下面的文章片段做一个概述: {os.path.abspath(fp)}'
chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
print('[1] yield chatbot, history')
yield chatbot, history, '正常'
if not fast_debug:
msg = '正常'
# ** gpt request **
gpt_say = yield from predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[]) # 带超时倒计时
print('[2] end gpt req')
chatbot[-1] = (i_say_show_user, gpt_say)
history.append(i_say_show_user); history.append(gpt_say)
print('[3] yield chatbot, history')
yield chatbot, history, msg
print('[4] next')
if not fast_debug: time.sleep(2)
all_file = ', '.join([os.path.relpath(fp, project_folder) for index, fp in enumerate(file_manifest)])
i_say = f'根据以上你自己的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一段英文摘要(包括{all_file})。'
chatbot.append((i_say, "[Local Message] waiting gpt response."))
yield chatbot, history, '正常'
if not fast_debug:
msg = '正常'
# ** gpt request **
gpt_say = yield from predict_no_ui_but_counting_down(i_say, i_say, chatbot, top_p, temperature, history=history) # 带超时倒计时
chatbot[-1] = (i_say, gpt_say)
history.append(i_say); history.append(gpt_say)
yield chatbot, history, msg
res = write_results_to_file(history)
chatbot.append(("完成了吗?", res))
yield chatbot, history, msg
@CatchException
def 批量总结PDF文档(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
import glob, os
# 基本信息:功能、贡献者
chatbot.append([
"函数插件功能?",
"批量总结PDF文档。函数插件贡献者: ValeriaWong"])
yield chatbot, history, '正常'
# 尝试导入依赖,如果缺少依赖,则给出安装建议
try:
import fitz
except:
report_execption(chatbot, history,
a = f"解析项目: {txt}",
b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pymupdf```。")
yield chatbot, history, '正常'
return
# 清空历史,以免输入溢出
history = []
# 检测输入参数,如没有给定输入参数,直接退出
if os.path.exists(txt):
project_folder = txt
else:
if txt == "": txt = '空空如也的输入栏'
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
yield chatbot, history, '正常'
return
# 搜索需要处理的文件清单
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.pdf', recursive=True)] # + \
# [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \
# [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
# [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
# 如果没找到任何文件
if len(file_manifest) == 0:
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex或.pdf文件: {txt}")
yield chatbot, history, '正常'
return
# 开始正式执行任务
yield from 解析PDF(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)
+20
View File
@@ -127,3 +127,23 @@ def 解析一个C项目的头文件(txt, top_p, temperature, chatbot, history, s
return
yield from 解析源代码(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)
@CatchException
def 解析一个C项目(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
history = [] # 清空历史,以免输入溢出
import glob, os
if os.path.exists(txt):
project_folder = txt
else:
if txt == "": txt = '空空如也的输入栏'
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
yield chatbot, history, '正常'
return
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.h', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
if len(file_manifest) == 0:
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.h头文件: {txt}")
yield chatbot, history, '正常'
return
yield from 解析源代码(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)
+13 -5
View File
@@ -1,16 +1,24 @@
from predict import predict_no_ui
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
fast_debug = False
from predict import predict_no_ui_long_connection
from toolbox import CatchException, report_execption, write_results_to_file
import datetime
@CatchException
def 高阶功能模板函数(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
history = [] # 清空历史,以免输入溢出
chatbot.append(("这是什么功能?", "[Local Message] 请注意,您正在调用一个函数模板,该函数面向希望实现更多有趣功能的开发者,它可以作为创建新功能函数的模板。为了做到简单易读,该函数只有25行代码,不会实时反馈文字流或心跳,请耐心等待程序输出完成。另外您若希望分享新的功能模组,请不吝PR!"))
yield chatbot, history, '正常' # 由于请求gpt需要一段时间,我们先及时地做一次状态显示
for i in range(5):
i_say = f'我给出一个数字,你给出该数字的平方。我给出数字:{i}'
currentMonth = (datetime.date.today() + datetime.timedelta(days=i)).month
currentDay = (datetime.date.today() + datetime.timedelta(days=i)).day
i_say = f'历史中哪些事件发生在{currentMonth}{currentDay}日?列举两条并发送相关图片。发送图片时,请使用Markdown,将Unsplash API中的PUT_YOUR_QUERY_HERE替换成描述改事件的三个最重要的单词。'
chatbot.append((i_say, "[Local Message] waiting gpt response."))
yield chatbot, history, '正常' # 由于请求gpt需要一段时间,我们先及时地做一次状态显示
gpt_say = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature) # 请求gpt,需要一段时间
# history = [] 每次询问不携带之前的询问历史
gpt_say = predict_no_ui_long_connection(
inputs=i_say, top_p=top_p, temperature=temperature, history=[],
sys_prompt="当你想发送一张照片时,请使用Markdown, 并且不要有反斜线, 不要用代码块。使用 Unsplash API (https://source.unsplash.com/1280x720/? < PUT_YOUR_QUERY_HERE >)。") # 请求gpt,需要一段时间
chatbot[-1] = (i_say, gpt_say)
history.append(i_say);history.append(gpt_say)
+36 -41
View File
@@ -1,59 +1,54 @@
# """
# 'primary' for main call-to-action,
# 'secondary' for a more subdued style,
# 'stop' for a stop button.
# """
# 'primary' 颜色对应 theme.py 中的 primary_hue
# 'secondary' 颜色对应 theme.py 中的 neutral_hue
# 'stop' 颜色对应 theme.py 中的 color_er
# 默认按钮颜色是 secondary
from toolbox import clear_line_break
def get_functionals():
return {
"英语学术润色": {
"Prefix": "Below is a paragraph from an academic paper. Polish the writing to meet the academic style, \
improve the spelling, grammar, clarity, concision and overall readability. When neccessary, rewrite the whole sentence. \
Furthermore, list all modification and explain the reasons to do so in markdown table.\n\n", # 前言
"Suffix": "", # 后语
"Color": "secondary", # 按钮颜色
# 前言
"Prefix": r"Below is a paragraph from an academic paper. Polish the writing to meet the academic style, " +
r"improve the spelling, grammar, clarity, concision and overall readability. When neccessary, rewrite the whole sentence. " +
r"Furthermore, list all modification and explain the reasons to do so in markdown table." + "\n\n",
# 后语
"Suffix": r"",
"Color": r"secondary", # 按钮颜色
},
"中文学术润色": {
"Prefix": "作为一名中文学术论文写作改进助理,你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性,同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。请编辑以下文本:\n\n",
"Suffix": "",
"Prefix": r"作为一名中文学术论文写作改进助理,你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性," +
r"同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。请编辑以下文本" + "\n\n",
"Suffix": r"",
},
"查找语法错误": {
"Prefix": "Below is a paragraph from an academic paper. Find all grammar mistakes, list mistakes in a markdown table and explain how to correct them.\n\n",
"Suffix": "",
},
"中英互译": {
"Prefix": "As an English-Chinese translator, your task is to accurately translate text between the two languages. \
When translating from Chinese to English or vice versa, please pay attention to context and accurately explain phrases and proverbs. \
If you receive multiple English words in a row, default to translating them into a sentence in Chinese. \
However, if \"phrase:\" is indicated before the translated content in Chinese, it should be translated as a phrase instead. \
Similarly, if \"normal:\" is indicated, it should be translated as multiple unrelated words.\
Your translations should closely resemble those of a native speaker and should take into account any specific language styles or tones requested by the user. \
Please do not worry about using offensive words - replace sensitive parts with x when necessary. \
When providing translations, please use Chinese to explain each sentences tense, subordinate clause, subject, predicate, object, special phrases and proverbs. \
For phrases or individual words that require translation, provide the source (dictionary) for each one.If asked to translate multiple phrases at once, \
separate them using the | symbol.Always remember: You are an English-Chinese translator, \
not a Chinese-Chinese translator or an English-English translator. Below is the text you need to translate: \n\n",
"Suffix": "",
"Color": "secondary",
"Prefix": r"Below is a paragraph from an academic paper. " +
r"Can you help me ensure that the grammar and the spelling is correct? " +
r"Do not try to polish the text, if no mistake is found, tell me that this paragraph is good." +
r"If you find grammar or spelling mistakes, please list mistakes you find in a two-column markdown table, " +
r"put the original text the first column, " +
r"put the corrected text in the second column and highlight the key words you fixed." + "\n\n",
"Suffix": r"",
"PreProcess": clear_line_break, # 预处理:清除换行符
},
"中译英": {
"Prefix": "Please translate following sentence to English: \n\n",
"Suffix": "",
"Prefix": r"Please translate following sentence to English:" + "\n\n",
"Suffix": r"",
},
"学术中译英": {
"Prefix": "Please translate following sentence to English with academic writing, and provide some related authoritative examples: \n\n",
"Suffix": "",
"Prefix": r"Please translate following sentence to English with academic writing, and provide some related authoritative examples:" + "\n\n",
"Suffix": r"",
},
"英译中": {
"Prefix": "请翻译成中文:\n\n",
"Suffix": "",
"Prefix": r"请翻译成中文:" + "\n\n",
"Suffix": r"",
},
"找图片": {
"Prefix": r"我需要你找一张网络图片。使用Unsplash API(https://source.unsplash.com/960x640/?<英语关键词>)获取图片URL" +
r"然后请使用Markdown格式封装,并且不要有反斜线,不要用代码块。现在,请按以下描述给我发送图片:" + "\n\n",
"Suffix": r"",
},
"解释代码": {
"Prefix": "请解释以下代码:\n```\n",
"Suffix": "\n```\n",
"Color": "secondary",
"Prefix": r"请解释以下代码:" + "\n```\n",
"Suffix": "\n```\n",
},
}
+46 -9
View File
@@ -1,3 +1,11 @@
from functools import HotReload # HotReload 的意思是热更新,修改函数插件后,不需要重启程序,代码直接生效
# UserVisibleLevel是过滤器参数。
# 由于UI界面空间有限,所以通过这种方式决定UI界面中显示哪些插件
# 默认函数插件 VisibleLevel 是 0
# 当 UserVisibleLevel >= 函数插件的 VisibleLevel 时,该函数插件才会被显示出来
UserVisibleLevel = 1
def get_crazy_functionals():
from crazy_functions.读文章写摘要 import 读文章写摘要
@@ -5,32 +13,61 @@ def get_crazy_functionals():
from crazy_functions.解析项目源代码 import 解析项目本身
from crazy_functions.解析项目源代码 import 解析一个Python项目
from crazy_functions.解析项目源代码 import 解析一个C项目的头文件
from crazy_functions.解析项目源代码 import 解析一个C项目
from crazy_functions.高级功能函数模板 import 高阶功能模板函数
from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文
return {
"[实验] 请解析并解构此项目本身": {
function_plugins = {
"请解析并解构此项目本身": {
# HotReload 的意思是热更新,修改函数插件后,不需要重启程序,代码直接生效
"Function": 解析项目本身
},
"[实验] 解析整个py项目input输入项目根路径)": {
"解析整个py项目": {
"Color": "stop", # 按钮颜色
"Function": 解析一个Python项目
},
"[实验] 解析整个C++项目input输入项目根路径)": {
"解析整个C++项目头文件": {
"Color": "stop", # 按钮颜色
"Function": 解析一个C项目的头文件
},
"[实验] 读tex论文写摘要(input输入项目根路径)": {
"解析整个C++项目": {
"Color": "stop", # 按钮颜色
"Function": 解析一个C项目
},
"读tex论文写摘要": {
"Color": "stop", # 按钮颜色
"Function": 读文章写摘要
},
"[实验] 批量生成函数注释input输入项目根路径)": {
"批量生成函数注释": {
"Color": "stop", # 按钮颜色
"Function": 批量生成函数注释
},
"[实验] 实验功能函数模板": {
"Color": "stop", # 按钮颜色
"Function": 高阶功能模板函数
"[多线程demo] 把本项目源代码切换成全英文": {
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
"Function": HotReload(全项目切换英文)
},
"[函数插件模板demo] 历史上的今天": {
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
"Function": HotReload(高阶功能模板函数)
},
}
# VisibleLevel=1 经过测试,但功能未达到理想状态
if UserVisibleLevel >= 1:
from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
function_plugins.update({
"[仅供开发调试] 批量总结PDF文档": {
"Color": "stop",
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
"Function": HotReload(批量总结PDF文档)
},
})
# VisibleLevel=2 尚未充分测试的函数插件,放在这里
if UserVisibleLevel >= 2:
function_plugins.update({
})
return function_plugins
+56 -35
View File
@@ -1,24 +1,26 @@
import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
import gradio as gr
from predict import predict
from toolbox import format_io, find_free_port
from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf
# 建议您复制一个config_private.py放自己的秘密如API和代理网址避免不小心传github被别人看到
try: from config_private import proxies, WEB_PORT
except: from config import proxies, WEB_PORT
# 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = \
get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')
# 如果WEB_PORT是-1,则随机选取WEB端口
# 如果WEB_PORT是-1, 则随机选取WEB端口
PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
AUTHENTICATION = None if AUTHENTICATION == [] else AUTHENTICATION
initial_prompt = "Serve me as a writing and programming assistant."
title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
# 问询记录python 版本建议3.9+(越新越好)
# 问询记录, python 版本建议3.9+(越新越好)
import logging
os.makedirs('gpt_log', exist_ok=True)
try:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO, encoding='utf-8')
except:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO)
print('所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log请注意自我隐私保护哦!')
print('所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!')
# 一些普通功能模块
from functional import get_functionals
@@ -31,62 +33,81 @@ crazy_functional = get_crazy_functionals()
# 处理markdown文本格式的转变
gr.Chatbot.postprocess = format_io
# 做一些样式上的调整
try: set_theme = gr.themes.Default( primary_hue=gr.themes.utils.colors.orange,
font=["ui-sans-serif", "system-ui", "sans-serif", gr.themes.utils.fonts.GoogleFont("Source Sans Pro")],
font_mono=["ui-monospace", "Consolas", "monospace", gr.themes.utils.fonts.GoogleFont("IBM Plex Mono")])
except:
set_theme = None; print('gradio版本较旧,不能自定义字体和颜色')
# 做一些外观色彩上的调整
from theme import adjust_theme
set_theme = adjust_theme()
cancel_handles = []
with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:
gr.HTML(title_html)
with gr.Row():
with gr.Column(scale=2):
chatbot = gr.Chatbot()
chatbot.style(height=1000)
chatbot.style(height=1150)
chatbot.style()
history = gr.State([])
TRUE = gr.State(True)
FALSE = gr.State(False)
with gr.Column(scale=1):
with gr.Row():
with gr.Column(scale=12):
txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
with gr.Column(scale=1):
submitBtn = gr.Button("Ask", variant="primary")
txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
with gr.Row():
submitBtn = gr.Button("提交", variant="primary")
with gr.Row():
resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
with gr.Row():
from check_proxy import check_proxy
statusDisplay = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {check_proxy(proxies)}")
with gr.Row():
for k in functional:
variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
functional[k]["Button"] = gr.Button(k, variant=variant)
with gr.Row():
gr.Markdown("注意:以下“红颜色”标识的函数插件需从input区读取路径作为参数.")
with gr.Row():
for k in crazy_functional:
variant = crazy_functional[k]["Color"] if "Color" in crazy_functional[k] else "secondary"
crazy_functional[k]["Button"] = gr.Button(k, variant=variant)
from check_proxy import check_proxy
statusDisplay = gr.Markdown(f"{check_proxy(proxies)}")
systemPromptTxt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt).style(container=True)
#inputs, top_p, temperature, top_k, repetition_penalty
with gr.Row():
gr.Markdown("上传本地文件,供上面的函数插件调用.")
with gr.Row():
file_upload = gr.Files(label='任何文件, 但推荐上传压缩文件(zip, tar)', file_count="multiple")
system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt).style(container=True)
with gr.Accordion("arguments", open=False):
top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
temperature = gr.Slider(minimum=-0, maximum=5.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
txt.submit(predict, [txt, top_p, temperature, chatbot, history, systemPromptTxt], [chatbot, history, statusDisplay])
submitBtn.click(predict, [txt, top_p, temperature, chatbot, history, systemPromptTxt], [chatbot, history, statusDisplay], show_progress=True)
predict_args = dict(fn=predict, inputs=[txt, top_p, temperature, chatbot, history, system_prompt], outputs=[chatbot, history, statusDisplay], show_progress=True)
empty_txt_args = dict(fn=lambda: "", inputs=[], outputs=[txt]) # 用于在提交后清空输入栏
cancel_handles.append(txt.submit(**predict_args))
# txt.submit(**empty_txt_args) 在提交后清空输入栏
cancel_handles.append(submitBtn.click(**predict_args))
# submitBtn.click(**empty_txt_args) 在提交后清空输入栏
resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, statusDisplay])
for k in functional:
functional[k]["Button"].click(predict,
[txt, top_p, temperature, chatbot, history, systemPromptTxt, TRUE, gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)
click_handle = functional[k]["Button"].click(predict,
[txt, top_p, temperature, chatbot, history, system_prompt, gr.State(True), gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)
cancel_handles.append(click_handle)
file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
for k in crazy_functional:
crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],
[txt, top_p, temperature, chatbot, history, systemPromptTxt, gr.State(PORT)], [chatbot, history, statusDisplay])
click_handle = crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],
[txt, top_p, temperature, chatbot, history, system_prompt, gr.State(PORT)], [chatbot, history, statusDisplay]
)
try: click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
except: pass
cancel_handles.append(click_handle)
stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
# 延迟函数,做一些准备工作,最后尝试打开浏览器
# gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
def auto_opentab_delay():
import threading, webbrowser, time
print(f"URL http://localhost:{PORT}")
def open(): time.sleep(2)
webbrowser.open_new_tab(f'http://localhost:{PORT}')
def open():
time.sleep(2)
webbrowser.open_new_tab(f'http://localhost:{PORT}')
t = threading.Thread(target=open)
t.daemon = True; t.start()
auto_opentab_delay()
demo.title = "ChatGPT 学术优化"
demo.queue().launch(server_name="0.0.0.0", share=True, server_port=PORT)
demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=True, server_port=PORT, auth=AUTHENTICATION)
+65 -10
View File
@@ -1,5 +1,16 @@
# 借鉴了 https://github.com/GaiZhenbiao/ChuanhuChatGPT 项目
"""
该文件中主要包含三个函数
不具备多线程能力的函数
1. predict: 正常对话时使用具备完备的交互功能不可多线程
具备多线程调用能力的函数
2. predict_no_ui高级实验性功能模块调用不会实时显示在界面上参数简单可以多线程并行方便实现复杂的功能逻辑
3. predict_no_ui_long_connection在实验过程中发现调用predict_no_ui处理长文档时和openai的连接容易断掉这个函数用stream的方式解决这个问题同样支持多线程
"""
import json
import gradio as gr
import logging
@@ -9,10 +20,12 @@ import importlib
# config_private.py放自己的秘密如API和代理网址
# 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件
try: from config_private import proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL
except: from config import proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL
from toolbox import get_conf
proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL = \
get_conf('proxies', 'API_URL', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY', 'LLM_MODEL')
timeout_bot_msg = '[local] Request timeout, network error. please check proxy settings in config.py.'
timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \
'网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。'
def get_full_error(chunk, stream_response):
"""
@@ -25,7 +38,7 @@ def get_full_error(chunk, stream_response):
break
return chunk
def predict_no_ui(inputs, top_p, temperature, history=[]):
def predict_no_ui(inputs, top_p, temperature, history=[], sys_prompt=""):
"""
发送至chatGPT等待回复一次性完成不显示中间过程
predict函数的简化版
@@ -36,7 +49,7 @@ def predict_no_ui(inputs, top_p, temperature, history=[]):
history 是之前的对话列表
注意无论是inputs还是history内容太长了都会触发token数量溢出的错误然后raise ConnectionAbortedError
"""
headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt="", stream=False)
headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=False)
retry = 0
while True:
@@ -47,8 +60,8 @@ def predict_no_ui(inputs, top_p, temperature, history=[]):
except requests.exceptions.ReadTimeout as e:
retry += 1
traceback.print_exc()
if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
if retry > MAX_RETRY: raise TimeoutError
if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
try:
result = json.loads(response.text)["choices"][0]["message"]["content"]
@@ -58,6 +71,41 @@ def predict_no_ui(inputs, top_p, temperature, history=[]):
raise ConnectionAbortedError("Json解析不合常规,可能是文本过长" + response.text)
def predict_no_ui_long_connection(inputs, top_p, temperature, history=[], sys_prompt=""):
"""
发送至chatGPT等待回复一次性完成不显示中间过程但内部用stream的方法避免有人中途掐网线
"""
headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=True)
retry = 0
while True:
try:
# make a POST request to the API endpoint, stream=False
response = requests.post(API_URL, headers=headers, proxies=proxies,
json=payload, stream=True, timeout=TIMEOUT_SECONDS); break
except requests.exceptions.ReadTimeout as e:
retry += 1
traceback.print_exc()
if retry > MAX_RETRY: raise TimeoutError
if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
stream_response = response.iter_lines()
result = ''
while True:
try: chunk = next(stream_response).decode()
except StopIteration: break
if len(chunk)==0: continue
if not chunk.startswith('data:'):
chunk = get_full_error(chunk.encode('utf8'), stream_response)
raise ConnectionAbortedError("OpenAI拒绝了请求:" + chunk.decode())
delta = json.loads(chunk.lstrip('data:'))['choices'][0]["delta"]
if len(delta) == 0: break
if "role" in delta: continue
if "content" in delta: result += delta["content"]; print(delta["content"], end='')
else: raise RuntimeError("意外Json结构:"+delta)
return result
def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt='',
stream = True, additional_fn=None):
"""
@@ -71,8 +119,9 @@ def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt=''
"""
if additional_fn is not None:
import functional
importlib.reload(functional)
importlib.reload(functional) # 热更新prompt
functional = functional.get_functionals()
if "PreProcess" in functional[additional_fn]: inputs = functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话)
inputs = functional[additional_fn]["Prefix"] + inputs + functional[additional_fn]["Suffix"]
if stream:
@@ -126,13 +175,19 @@ def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt=''
except Exception as e:
traceback.print_exc()
yield chatbot, history, "Json解析不合常规,很可能是文本过长"
yield chatbot, history, "Json解析不合常规"
chunk = get_full_error(chunk, stream_response)
error_msg = chunk.decode()
if "reduce the length" in error_msg:
chatbot[-1] = (history[-1], "[Local Message] Input (or history) is too long, please reduce input or clear history by refleshing this page.")
chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refreshing this page.")
history = []
yield chatbot, history, "Json解析不合常规,很可能是文本过长" + error_msg
elif "Incorrect API key" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")
else:
from toolbox import regular_txt_to_markdown
tb_str = regular_txt_to_markdown(traceback.format_exc())
chatbot[-1] = (chatbot[-1][0], f"[Local Message] Json Error \n\n {tb_str} \n\n {regular_txt_to_markdown(chunk.decode()[4:])}")
yield chatbot, history, "Json解析不合常规" + error_msg
return
def generate_payload(inputs, top_p, temperature, history, system_prompt, stream):
+122
View File
@@ -0,0 +1,122 @@
# chatgpt-academic项目自译解报告
(Author补充:以下分析均由本项目调用ChatGPT一键生成,如果有不准确的地方,全怪GPT😄)
## [0/10] 程序摘要: check_proxy.py
这个程序是一个用来检查代理服务器是否有效的 Python 程序代码。程序文件名为 check_proxy.py。其中定义了一个函数 check_proxy,该函数接收一个代理配置信息 proxies,使用 requests 库向一个代理服务器发送请求,获取该代理的所在地信息并返回。如果请求超时或者异常,该函数将返回一个代理无效的结果。
程序代码分为两个部分,首先是 check_proxy 函数的定义部分,其次是程序文件的入口部分,在该部分代码中,程序从 config_private.py 文件或者 config.py 文件中加载代理配置信息,然后调用 check_proxy 函数来检测代理服务器是否有效。如果配置文件 config_private.py 存在,则会加载其中的代理配置信息,否则会从 config.py 文件中读取。
## [1/10] 程序摘要: config.py
本程序文件名为config.py,主要功能是存储应用所需的常量和配置信息。
其中,包含了应用所需的OpenAI API密钥、API接口地址、网络代理设置、超时设置、网络端口和OpenAI模型选择等信息,在运行应用前需要进行相应的配置。在未配置网络代理时,程序给出了相应的警告提示。
此外,还包含了一个检查函数,用于检查是否忘记修改API密钥。
总之,config.py文件是应用中的一个重要配置文件,用来存储应用所需的常量和配置信息,需要在应用运行前进行相应的配置。
## [2/10] 程序摘要: config_private.py
该文件是一个配置文件,命名为config_private.py。它是一个Python脚本,用于配置OpenAI的API密钥、模型和其它相关设置。该配置文件还可以设置是否使用代理。如果使用代理,需要设置代理协议、地址和端口。在设置代理之后,该文件还包括一些用于测试代理是否正常工作的代码。该文件还包括超时时间、随机端口、重试次数等设置。在文件末尾,还有一个检查代码,如果没有更改API密钥,则抛出异常。
## [3/10] 程序摘要: functional.py
该程序文件名为 functional.py,其中包含一个名为 get_functionals 的函数,该函数返回一个字典,该字典包含了各种翻译、校对等功能的名称、前缀、后缀以及默认按钮颜色等信息。具体功能包括:英语学术润色、中文学术润色、查找语法错误、中英互译、中译英、学术中译英、英译中、解释代码等。该程序的作用为提供各种翻译、校对等功能的模板,以便后续程序可以直接调用。
(Author补充:这个文件汇总了模块化的Prompt调用,如果发现了新的好用Prompt,别藏着哦^_^速速PR
## [4/10] 程序摘要: functional_crazy.py
这个程序文件 functional_crazy.py 导入了一些 python 模块,并提供了一个函数 get_crazy_functionals(),该函数返回不同实验功能的描述和函数。其中,使用的的模块包括:
- crazy_functions.读文章写摘要 中的 读文章写摘要
- crazy_functions.生成函数注释 中的 批量生成函数注释
- crazy_functions.解析项目源代码 中的 解析项目本身、解析一个Python项目、解析一个C项目的头文件、解析一个C项目
- crazy_functions.高级功能函数模板 中的 高阶功能模板函数
返回的实验功能函数包括:
- "[实验] 请解析并解构此项目本身",包含函数:解析项目本身
- "[实验] 解析整个py项目(配合input输入框)",包含函数:解析一个Python项目
- "[实验] 解析整个C++项目头文件(配合input输入框)",包含函数:解析一个C项目的头文件
- "[实验] 解析整个C++项目(配合input输入框)",包含函数:解析一个C项目
- "[实验] 读tex论文写摘要(配合input输入框)",包含函数:读文章写摘要
- "[实验] 批量生成函数注释(配合input输入框)",包含函数:批量生成函数注释
- "[实验] 实验功能函数模板",包含函数:高阶功能模板函数
这些函数用于系统开发和测试,方便开发者进行特定程序语言后台功能开发的测试和实验,增加系统可靠稳定性和用户友好性。
(Author补充:这个文件汇总了模块化的函数,如此设计以方便任何新功能的加入)
## [5/10] 程序摘要: main.py
该程序是一个基于Gradio框架的聊天机器人应用程序。用户可以通过输入问题来获取答案,并与聊天机器人进行对话。该应用程序还集成了一些实验性功能模块,用户可以通过上传本地文件或点击相关按钮来使用这些模块。程序还可以生成对话日志,并且具有一些外观上的调整。在运行时,它会自动打开一个网页并在本地启动服务器。
## [6/10] 程序摘要: predict.py
该程序文件名为predict.py,主要是针对一个基于ChatGPT的聊天机器人进行交互和预测。
第一部分是导入所需的库和配置文件。
第二部分是一个用于获取Openai返回的完整错误信息的函数。
第三部分是用于一次性完成向ChatGPT发送请求和等待回复的函数。
第四部分是用于基础的对话功能的函数,通过stream参数可以选择是否显示中间的过程。
第五部分是用于整合所需信息和选择LLM模型生成的HTTP请求。
Author补充:主要是predict_no_ui和predict两个函数。前者不用stream,方便、高效、易用。后者用stream,展现效果好。)
## [7/10] 程序摘要: show_math.py
这是一个名为show_math.py的Python程序文件,主要用于将Markdown-LaTeX混合文本转换为HTML格式,并包括MathML数学公式。程序使用latex2mathml.converter库将LaTeX公式转换为MathML格式,并使用正则表达式递归地翻译输入的Markdown-LaTeX混合文本。程序包括转换成双美元符号($$)形式、转换成单美元符号($)形式、转换成\[\]形式以及转换成\(\)形式的LaTeX数学公式。如果转换中出现错误,程序将返回相应的错误消息。
## [8/10] 程序摘要: theme.py
这是一个名为theme.py的程序文件,用于设置Gradio界面的颜色和字体主题。该文件中定义了一个名为adjust_theme()的函数,其作用是返回一个Gradio theme对象,设置了Gradio界面的颜色和字体主题。在该函数里面,使用了Graido可用的颜色列表,主要参数包括primary_hue、neutral_hue、font和font_mono等,用于设置Gradio界面的主题色调、字体等。另外,该函数还实现了一些参数的自定义,如input_background_fill_dark、button_transition、button_shadow_hover等,用于设置Gradio界面的渐变、阴影等特效。如果Gradio版本过于陈旧,该函数会抛出异常并返回None。
## [9/10] 程序摘要: toolbox.py
该文件为Python程序文件,文件名为toolbox.py。主要功能包括:
1. 导入markdown、mdtex2html、threading、functools等模块。
2. 定义函数predict_no_ui_but_counting_down,用于生成对话。
3. 定义函数write_results_to_file,用于将对话记录生成Markdown文件。
4. 定义函数regular_txt_to_markdown,将普通文本转换为Markdown格式的文本。
5. 定义装饰器函数CatchException,用于捕获函数执行异常并返回生成器。
6. 定义函数report_execption,用于向chatbot中添加错误信息。
7. 定义函数text_divide_paragraph,用于将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
8. 定义函数markdown_convertion,用于将Markdown格式的文本转换为HTML格式。
9. 定义函数format_io,用于将输入和输出解析为HTML格式。
10. 定义函数find_free_port,用于返回当前系统中可用的未使用端口。
11. 定义函数extract_archive,用于解压归档文件。
12. 定义函数find_recent_files,用于查找最近创建的文件。
13. 定义函数on_file_uploaded,用于处理上传文件的操作。
14. 定义函数on_report_generated,用于处理生成报告文件的操作。
## 程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能。
这是一个基于Gradio框架的聊天机器人应用,支持通过文本聊天来获取答案,并可以使用一系列实验性功能模块,例如生成函数注释、解析项目源代码、读取Latex论文写摘要等。 程序架构分为前端和后端两个部分。前端使用Gradio实现,包括用户输入区域、应答区域、按钮、调用方式等。后端使用Python实现,包括聊天机器人模型、实验性功能模块、模板模块、管理模块、主程序模块等。
每个程序文件的功能如下:
| 文件名 | 功能描述 |
|:----:|:----:|
| check_proxy.py | 检查代理服务器是否有效 |
| config.py | 存储应用所需的常量和配置信息 |
| config_private.py | 存储Openai的API密钥、模型和其他相关设置 |
| functional.py | 提供各种翻译、校对等实用模板 |
| functional_crazy.py | 提供一些实验性质的高级功能 |
| main.py | 基于Gradio框架的聊天机器人应用程序的主程序 |
| predict.py | 用于chatbot预测方案创建,向ChatGPT发送请求和获取回复 |
| show_math.py | 将Markdown-LaTeX混合文本转换为HTML格式,并包括MathML数学公式 |
| theme.py | 设置Gradio界面的颜色和字体主题 |
| toolbox.py | 定义一系列工具函数,用于对输入输出进行格式转换、文件操作、异常捕捉和处理等 |
这些程序文件共同组成了一个聊天机器人应用程序的前端和后端实现,使用户可以方便地进行聊天,并可以使用相应的实验功能模块。
+1 -1
View File
@@ -1,3 +1,3 @@
gradio
gradio>=3.23
requests[socks]
mdtex2html
+82
View File
@@ -0,0 +1,82 @@
import gradio as gr
# gradio可用颜色列表
# gr.themes.utils.colors.slate (石板色)
# gr.themes.utils.colors.gray (灰色)
# gr.themes.utils.colors.zinc (锌色)
# gr.themes.utils.colors.neutral (中性色)
# gr.themes.utils.colors.stone (石头色)
# gr.themes.utils.colors.red (红色)
# gr.themes.utils.colors.orange (橙色)
# gr.themes.utils.colors.amber (琥珀色)
# gr.themes.utils.colors.yellow (黄色)
# gr.themes.utils.colors.lime (酸橙色)
# gr.themes.utils.colors.green (绿色)
# gr.themes.utils.colors.emerald (祖母绿)
# gr.themes.utils.colors.teal (青蓝色)
# gr.themes.utils.colors.cyan (青色)
# gr.themes.utils.colors.sky (天蓝色)
# gr.themes.utils.colors.blue (蓝色)
# gr.themes.utils.colors.indigo (靛蓝色)
# gr.themes.utils.colors.violet (紫罗兰色)
# gr.themes.utils.colors.purple (紫色)
# gr.themes.utils.colors.fuchsia (洋红色)
# gr.themes.utils.colors.pink (粉红色)
# gr.themes.utils.colors.rose (玫瑰色)
def adjust_theme():
try:
color_er = gr.themes.utils.colors.pink
set_theme = gr.themes.Default(
primary_hue=gr.themes.utils.colors.orange,
neutral_hue=gr.themes.utils.colors.gray,
font=["sans-serif", "Microsoft YaHei", "ui-sans-serif", "system-ui", "sans-serif", gr.themes.utils.fonts.GoogleFont("Source Sans Pro")],
font_mono=["ui-monospace", "Consolas", "monospace", gr.themes.utils.fonts.GoogleFont("IBM Plex Mono")])
set_theme.set(
# Colors
input_background_fill_dark="*neutral_800",
# Transition
button_transition="none",
# Shadows
button_shadow="*shadow_drop",
button_shadow_hover="*shadow_drop_lg",
button_shadow_active="*shadow_inset",
input_shadow="0 0 0 *shadow_spread transparent, *shadow_inset",
input_shadow_focus="0 0 0 *shadow_spread *secondary_50, *shadow_inset",
input_shadow_focus_dark="0 0 0 *shadow_spread *neutral_700, *shadow_inset",
checkbox_label_shadow="*shadow_drop",
block_shadow="*shadow_drop",
form_gap_width="1px",
# Button borders
input_border_width="1px",
input_background_fill="white",
# Gradients
stat_background_fill="linear-gradient(to right, *primary_400, *primary_200)",
stat_background_fill_dark="linear-gradient(to right, *primary_400, *primary_600)",
error_background_fill=f"linear-gradient(to right, {color_er.c100}, *background_fill_secondary)",
error_background_fill_dark="*background_fill_primary",
checkbox_label_background_fill="linear-gradient(to top, *neutral_50, white)",
checkbox_label_background_fill_dark="linear-gradient(to top, *neutral_900, *neutral_800)",
checkbox_label_background_fill_hover="linear-gradient(to top, *neutral_100, white)",
checkbox_label_background_fill_hover_dark="linear-gradient(to top, *neutral_900, *neutral_800)",
button_primary_background_fill="linear-gradient(to bottom right, *primary_100, *primary_300)",
button_primary_background_fill_dark="linear-gradient(to bottom right, *primary_500, *primary_600)",
button_primary_background_fill_hover="linear-gradient(to bottom right, *primary_100, *primary_200)",
button_primary_background_fill_hover_dark="linear-gradient(to bottom right, *primary_500, *primary_500)",
button_primary_border_color_dark="*primary_500",
button_secondary_background_fill="linear-gradient(to bottom right, *neutral_100, *neutral_200)",
button_secondary_background_fill_dark="linear-gradient(to bottom right, *neutral_600, *neutral_700)",
button_secondary_background_fill_hover="linear-gradient(to bottom right, *neutral_100, *neutral_100)",
button_secondary_background_fill_hover_dark="linear-gradient(to bottom right, *neutral_600, *neutral_600)",
button_cancel_background_fill=f"linear-gradient(to bottom right, {color_er.c100}, {color_er.c200})",
button_cancel_background_fill_dark=f"linear-gradient(to bottom right, {color_er.c600}, {color_er.c700})",
button_cancel_background_fill_hover=f"linear-gradient(to bottom right, {color_er.c100}, {color_er.c100})",
button_cancel_background_fill_hover_dark=f"linear-gradient(to bottom right, {color_er.c600}, {color_er.c600})",
button_cancel_border_color=color_er.c200,
button_cancel_border_color_dark=color_er.c600,
button_cancel_text_color=color_er.c600,
button_cancel_text_color_dark="white",
)
except:
set_theme = None; print('gradio版本较旧, 不能自定义字体和颜色')
return set_theme
+118 -14
View File
@@ -1,15 +1,15 @@
import markdown, mdtex2html, threading
import markdown, mdtex2html, threading, importlib, traceback, importlib, inspect
from show_math import convert as convert_math
from functools import wraps
def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[]):
def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[], sys_prompt=''):
"""
调用简单的predict_no_ui接口但是依然保留了些许界面心跳功能当对话太长时会自动采用二分法截断
"""
import time
try: from config_private import TIMEOUT_SECONDS, MAX_RETRY
except: from config import TIMEOUT_SECONDS, MAX_RETRY
from predict import predict_no_ui
from toolbox import get_conf
TIMEOUT_SECONDS, MAX_RETRY = get_conf('TIMEOUT_SECONDS', 'MAX_RETRY')
# 多线程的时候,需要一个mutable结构在不同线程之间传递信息
# list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息
mutable = [None, '']
@@ -17,7 +17,7 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
def mt(i_say, history):
while True:
try:
mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history)
mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt)
break
except ConnectionAbortedError as e:
if len(history) > 0:
@@ -27,7 +27,8 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
i_say = i_say[:len(i_say)//2]
mutable[1] = 'Warning! Input file is too long, cut into half. '
except TimeoutError as e:
mutable[0] = '[Local Message] Failed with timeout'
mutable[0] = '[Local Message] Failed with timeout.'
raise TimeoutError
# 创建新线程发出http请求
thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start()
# 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成
@@ -39,6 +40,7 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
time.sleep(1)
# 把gpt的输出从mutable中取出来
gpt_say = mutable[0]
if gpt_say=='[Local Message] Failed with timeout.': raise TimeoutError
return gpt_say
def write_results_to_file(history, file_name=None):
@@ -47,9 +49,10 @@ def write_results_to_file(history, file_name=None):
"""
import os, time
if file_name is None:
file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'
# file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'
file_name = 'chatGPT分析报告' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'
os.makedirs('./gpt_log/', exist_ok=True)
with open(f'./gpt_log/{file_name}', 'w') as f:
with open(f'./gpt_log/{file_name}', 'w', encoding = 'utf8') as f:
f.write('# chatGPT 分析报告\n')
for i, content in enumerate(history):
if i%2==0: f.write('## ')
@@ -77,15 +80,25 @@ def CatchException(f):
try:
yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)
except Exception as e:
import traceback
from check_proxy import check_proxy
try: from config_private import proxies
except: from config import proxies
from toolbox import get_conf
proxies, = get_conf('proxies')
tb_str = regular_txt_to_markdown(traceback.format_exc())
chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}")
yield chatbot, history, f'异常 {e}'
return decorated
def HotReload(f):
"""
装饰器函数实现函数插件热更新
"""
@wraps(f)
def decorated(*args, **kwargs):
fn_name = f.__name__
f_hot_reload = getattr(importlib.reload(inspect.getmodule(f)), fn_name)
yield from f_hot_reload(*args, **kwargs)
return decorated
def report_execption(chatbot, history, a, b):
"""
向chatbot中添加错误信息
@@ -104,8 +117,8 @@ def text_divide_paragraph(text):
# wtf input
lines = text.split("\n")
for i, line in enumerate(lines):
if i!=0: lines[i] = "<p>"+lines[i].replace(" ", "&nbsp;")+"</p>"
text = "".join(lines)
lines[i] = lines[i].replace(" ", "&nbsp;")
text = "</br>".join(lines)
return text
def markdown_convertion(txt):
@@ -123,7 +136,7 @@ def format_io(self, y):
"""
将输入和输出解析为HTML格式将y中最后一项的输入部分段落化并将输出部分的Markdown和数学公式转换为HTML格式
"""
if y is None: return []
if y is None or y == []: return []
i_ask, gpt_reply = y[-1]
i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波
y[-1] = (
@@ -143,3 +156,94 @@ def find_free_port():
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
def extract_archive(file_path, dest_dir):
import zipfile
import tarfile
import os
# Get the file extension of the input file
file_extension = os.path.splitext(file_path)[1]
# Extract the archive based on its extension
if file_extension == '.zip':
with zipfile.ZipFile(file_path, 'r') as zipobj:
zipobj.extractall(path=dest_dir)
print("Successfully extracted zip archive to {}".format(dest_dir))
elif file_extension in ['.tar', '.gz', '.bz2']:
with tarfile.open(file_path, 'r:*') as tarobj:
tarobj.extractall(path=dest_dir)
print("Successfully extracted tar archive to {}".format(dest_dir))
else:
return
def find_recent_files(directory):
"""
me: find files that is created with in one minutes under a directory with python, write a function
gpt: here it is!
"""
import os
import time
current_time = time.time()
one_minute_ago = current_time - 60
recent_files = []
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if file_path.endswith('.log'): continue
created_time = os.path.getctime(file_path)
if created_time >= one_minute_ago:
if os.path.isdir(file_path): continue
recent_files.append(file_path)
return recent_files
def on_file_uploaded(files, chatbot, txt):
if len(files) == 0: return chatbot, txt
import shutil, os, time, glob
from toolbox import extract_archive
try: shutil.rmtree('./private_upload/')
except: pass
time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
os.makedirs(f'private_upload/{time_tag}', exist_ok=True)
for file in files:
file_origin_name = os.path.basename(file.orig_name)
shutil.copy(file.name, f'private_upload/{time_tag}/{file_origin_name}')
extract_archive(f'private_upload/{time_tag}/{file_origin_name}',
dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')
moved_files = [fp for fp in glob.glob('private_upload/**/*', recursive=True)]
txt = f'private_upload/{time_tag}'
moved_files_str = '\t\n\n'.join(moved_files)
chatbot.append(['我上传了文件,请查收',
f'[Local Message] 收到以下文件: \n\n{moved_files_str}\n\n调用路径参数已自动修正到: \n\n{txt}\n\n现在您点击任意实验功能时,以上文件将被作为输入参数'])
return chatbot, txt
def on_report_generated(files, chatbot):
from toolbox import find_recent_files
report_files = find_recent_files('gpt_log')
if len(report_files) == 0: return report_files, chatbot
# files.extend(report_files)
chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。'])
return report_files, chatbot
def get_conf(*args):
# 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
res = []
for arg in args:
try: r = getattr(importlib.import_module('config_private'), arg)
except: r = getattr(importlib.import_module('config'), arg)
res.append(r)
# 在读取API_KEY时,检查一下是不是忘了改config
if arg=='API_KEY' and len(r) != 51:
assert False, "正确的API_KEY密钥是51位,请在config文件中修改API密钥, 添加海外代理之后再运行。" + \
"(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)"
return res
def clear_line_break(txt):
txt = txt.replace('\n', ' ')
txt = txt.replace(' ', ' ')
txt = txt.replace(' ', ' ')
return txt