Compare commits

..

486 Commits

Author SHA1 Message Date
qingxu fu
1c6c29e6dd 更新注释 2023-04-13 11:18:44 +08:00
qingxu fu
74f26a7d64 改善chatpdf的功能 2023-04-13 11:08:53 +08:00
fuqingxu
1c96ed39c3 启动ChatGPT+ChatGLM 2023-04-12 17:41:33 +08:00
fuqingxu
5b040d552e Merge branch 'master' of https://github.com/binary-husky/chatgpt_academic 2023-04-12 16:57:56 +08:00
fuqingxu
c563ac2274 UTF8 Ignore read file errors 2023-04-12 16:57:01 +08:00
binary-husky
d28af7611a Update README.md 2023-04-12 12:04:57 +08:00
binary-husky
9714d3ea2d Update README.md 2023-04-12 11:21:20 +08:00
binary-husky
65c51eb05b Update README.md 2023-04-12 02:46:04 +08:00
binary-husky
5d98d82526 Update README.md 2023-04-12 02:41:43 +08:00
binary-husky
9215199ae1 Update README.md 2023-04-12 02:27:55 +08:00
binary-husky
7ded328970 Update README.md 2023-04-12 02:27:10 +08:00
binary-husky
057b8cd943 Update README.md 2023-04-12 00:12:42 +08:00
binary-husky
2ab6acc6de Update README.md 2023-04-12 00:08:31 +08:00
Your Name
c917f6e6fe 移除故障代码说明 2023-04-11 21:19:31 +08:00
binary-husky
97d33e9413 默认关闭share
注意,由于国内 Gradio 的网络访问较为缓慢,启用 demo.queue().launch(share=True, inbrowser=True) 时所有网络会经过 Gradio 服务器转发,导致打字机体验大幅下降,现在默认启动方式已经改为 share=False,如有需要公网访问的需求,可以重新修改为 share=True 启动。
2023-04-11 21:13:21 +08:00
binary-husky
76940a3041 Merge pull request #413 from liyishuai/patch-1
Dockerfile: unbuffer stdout
2023-04-11 20:15:10 +08:00
binary-husky
de658b3104 Update README.md 2023-04-11 20:00:33 +08:00
qingxu fu
35a5c97eca Merge branch 'master' of https://github.com/binary-husky/chatgpt_academic into master 2023-04-11 19:59:09 +08:00
qingxu fu
7b44010a71 2.67 修复typo 2023-04-11 19:59:06 +08:00
qingxu fu
e467ab2d3f 2.67 修复typo 2023-04-11 19:58:37 +08:00
binary-husky
4681ba5e3c Update README.md 2023-04-11 19:34:03 +08:00
qingxu fu
7c494be291 Merge branch 'master' of https://github.com/binary-husky/chatgpt_academic into master 2023-04-11 19:32:02 +08:00
qingxu fu
4a96d165ca 修改功能说明 2023-04-11 19:31:57 +08:00
binary-husky
c151adf697 Update README.md 2023-04-11 19:00:20 +08:00
binary-husky
095d32df84 Update README.md 2023-04-11 18:58:16 +08:00
qingxu fu
3084c03e55 UP 2023-04-11 18:50:56 +08:00
qingxu fu
37ffbacd08 修复 2023-04-11 18:49:22 +08:00
qingxu fu
8f8b1e9d10 2.62 BUG 修复 2023-04-11 18:47:51 +08:00
qingxu fu
c84753beb9 renew all 2023-04-11 18:36:38 +08:00
qingxu fu
e356029248 UP 2023-04-11 18:23:59 +08:00
Your Name
db6137dd27 紧急bug修复 2023-04-11 18:16:33 +08:00
Your Name
e9b4e0c75a 紧急BUG修复 2023-04-11 18:15:26 +08:00
Your Name
df246195d3 紧急bug修复 2023-04-11 18:12:31 +08:00
qingxu fu
7395290aaa version 2.6 2023-04-11 17:55:30 +08:00
qingxu fu
87d7e320d3 print change 2023-04-11 17:52:40 +08:00
qingxu fu
8afcc522df Merge branch 'dev_grand' of https://github.com/binary-husky/chatgpt_academic into dev_grand 2023-04-11 17:42:59 +08:00
qingxu fu
38b0ce6805 修正解析源代码bug 2023-04-11 17:42:56 +08:00
qingxu fu
04b280be1b 更正bug 2023-04-11 17:40:50 +08:00
Yishuai Li
fe7b2d763b Dockerfile: two-stage copy 2023-04-11 17:25:30 +08:00
qingxu fu
90dcc8f1f2 界面重构 2023-04-11 15:31:46 +08:00
Yishuai Li
225c731589 Dockerfile: unbuffer stdout 2023-04-11 15:30:40 +08:00
qingxu fu
d9a92c9016 add arxiv dependency 2023-04-11 15:20:04 +08:00
qingxu fu
039405c3bb 修复chatbotwithcookies的对象传递问题 2023-04-11 15:17:00 +08:00
qingxu fu
f0dbf33d06 移除陈旧函数 2023-04-11 14:45:00 +08:00
qingxu fu
53df6d5647 Merge branch 'master' into dev_grand 2023-04-10 12:38:26 +08:00
binary-husky
78f93c6eae Merge pull request #395 from HougeLangley/master
Added python-docx
2023-04-10 10:05:01 +08:00
HougeLangley
bc8cda92ac Added python-docx
解决在使用批量导入 .docx 文件是提示需要 pip install --upgrade python-docx 的问题
2023-04-10 01:06:34 +08:00
binary-husky
caf1cba1a0 Merge pull request #388 from WangRongsheng/master
update en2ch prompt
2023-04-10 00:39:54 +08:00
qingxu fu
8e128300e0 翻译成地道的中文 2023-04-10 00:36:05 +08:00
qingxu fu
7c94300bba Merge branch 'master' of https://github.com/WangRongsheng/chatgpt_academic into WangRongsheng-master 2023-04-10 00:33:16 +08:00
binary-husky
b2b058fc27 Merge pull request #389 from Ljp66/master
Update toolbox.py
2023-04-10 00:31:24 +08:00
qingxu fu
4179495ac4 +Latex全文中英互译插件 2023-04-10 00:29:53 +08:00
qingxu fu
501093c201 强调中文 2023-04-10 00:21:20 +08:00
qingxu fu
931c941450 实验 2023-04-10 00:11:07 +08:00
qingxu fu
9a2a625910 UP 2023-04-10 00:05:46 +08:00
qingxu fu
c11e7f6e92 更新提示 2023-04-10 00:00:03 +08:00
qingxu fu
e56e625fca 自动更新程序+自动pip包安装 2023-04-09 23:56:24 +08:00
qingxu fu
93ebd4be96 修正prompt 2023-04-09 23:32:32 +08:00
qingxu fu
ebf1055ff4 Latex全文润色 2023-04-09 23:28:57 +08:00
qingxu fu
115c035ff8 增加临时输入api-key的功能 2023-04-09 21:23:21 +08:00
qingxu fu
6eb397ead2 UP 2023-04-09 20:50:33 +08:00
qingxu fu
f8bd5fcd27 增扩框架的参数IO 2023-04-09 20:42:23 +08:00
qingxu fu
4641d0551e st 2023-04-09 19:49:42 +08:00
qingxu fu
a9d6c933f4 declare depriction 2023-04-09 19:02:18 +08:00
qingxu fu
587271ec42 提升稳定性 2023-04-09 18:59:43 +08:00
MPU王荣胜
34a678141a Delete core_functional.py 2023-04-09 11:55:27 +08:00
gbwyljp
f9c4fb4b5d Update toolbox.py
remove duplicate "import importlib"
2023-04-09 11:55:00 +08:00
MPU王荣胜
9f505fb4ca update en2ch prompt 2023-04-09 11:45:34 +08:00
MPU王荣胜
40804913ca update en2ch prompt 2023-04-09 11:38:37 +08:00
binary-husky
bb3dd97cfe Update version 2023-04-08 22:51:37 +08:00
qingxu fu
8ddc1adae4 version 2.5 2023-04-08 22:27:02 +08:00
qingxu fu
4e3f759d0c 移动参数位置 2023-04-08 22:16:33 +08:00
qingxu fu
94ff62bdaa 错别字 2023-04-08 22:15:33 +08:00
qingxu fu
2cbb5dbdaa up 2023-04-08 22:14:05 +08:00
Your Name
3b85a29f91 加入自动更新协议 2023-04-08 02:48:35 +08:00
Your Name
166daa1ea7 显示版本 2023-04-08 02:39:54 +08:00
Your Name
5c3ecd7477 自动更新程序 2023-04-08 02:38:02 +08:00
Your Name
d5b03377ff 多种接口 2023-04-08 00:51:58 +08:00
Your Name
7cd11f2bbd 新插件移动到插件菜单中 2023-04-08 00:42:54 +08:00
Your Name
f65cc8deea Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-04-08 00:41:46 +08:00
Your Name
48ee620524 代码高亮开关 2023-04-08 00:41:39 +08:00
binary-husky
8a5be8fb8d Merge pull request #366 from Hanzoe/master
new function: 实现单篇PDF论文翻译理解
2023-04-08 00:41:03 +08:00
binary-husky
f26b8e28e1 Update README.md 2023-04-08 00:32:22 +08:00
Your Name
b005b84ad6 更新requirements.txt实现代码高亮必要 2023-04-08 00:23:26 +08:00
Your Name
1edf7ef80d Fix dockerfile 2023-04-08 00:01:11 +08:00
Your Name
3fed08f65e version 2.45 2023-04-07 23:58:10 +08:00
Your Name
fa8603d745 Merge branch 'master' into dev 2023-04-07 23:55:19 +08:00
Your Name
6b5c2538cf 新增谷歌学术统合小助手 2023-04-07 23:54:24 +08:00
Your Name
7f1c7ebd68 version 2.43 2023-04-07 22:08:05 +08:00
Your Name
ff87aebc29 处理多线程中出现的网络问题 2023-04-07 22:06:08 +08:00
Hanzoe
2c746056ff Update crazy_functional.py 2023-04-07 21:35:36 +08:00
Hanzoe
0e4cac29f8 Add files via upload 2023-04-07 21:34:55 +08:00
Hanzoe
8513d46398 Merge pull request #1 from binary-husky/master
单篇论文翻译理解
2023-04-07 21:34:11 +08:00
Your Name
b2495a6f7e Merge branch 'dev' of github.com:binary-husky/chatgpt_academic into dev 2023-04-07 21:09:43 +08:00
Your Name
5603d33d67 highlight 2023-04-07 21:09:37 +08:00
Your Name
d06d4f3a6f highlight 2023-04-07 21:08:34 +08:00
Your Name
b2adc77a73 Merge branch 'dev' of github.com:binary-husky/chatgpt_academic into dev 2023-04-07 21:00:32 +08:00
Your Name
1f6e2547b2 Merge branch 'master' into dev 2023-04-07 20:59:35 +08:00
qingxu fu
fd0e3fb5c4 代码、公式高亮 2023-04-07 20:30:30 +08:00
qingxu fu
a0b7ae6674 Merge branch 'master' of https://github.com/binary-husky/chatgpt_academic into master 2023-04-07 19:26:20 +08:00
qingxu fu
8ca232cda3 修复小BUG 2023-04-07 19:26:17 +08:00
binary-husky
34e983c7a5 Update README.md 2023-04-07 19:09:18 +08:00
binary-husky
c0d096726c Update README.md 2023-04-07 19:08:41 +08:00
qingxu fu
969e8c1d89 正确显示列表序号 2023-04-07 18:33:46 +08:00
binary-husky
d4e3082db4 Update toolbox.py 2023-04-07 18:27:52 +08:00
binary-husky
777e56882b Update README.md 2023-04-07 18:21:13 +08:00
Your Name
4da7d75ad4 修复公式显示错误 2023-04-07 18:14:27 +08:00
qingxu fu
1538acaa5a fix equation 2023-04-07 17:55:24 +08:00
qingxu fu
b47f69978e 更新requirements.txt 2023-04-07 12:45:47 +08:00
binary-husky
823c136de4 Update README.md 2023-04-06 19:24:37 +08:00
binary-husky
cede926b54 Update README.md 2023-04-06 19:15:58 +08:00
binary-husky
bb036d92c6 Update README.md 2023-04-06 18:55:16 +08:00
binary-husky
7d96a5753c Update README.md 2023-04-06 18:49:49 +08:00
qingxu fu
179d87d3eb 改善提示 2023-04-06 18:45:24 +08:00
Your Name
e42f84a812 替换基础函数 2023-04-06 18:41:04 +08:00
qingxu fu
8c21ada50c 主要代码规整化 2023-04-06 18:29:49 +08:00
qingxu fu
f99a7bb6f6 小问题修复 2023-04-06 18:26:46 +08:00
qingxu fu
1c4cdde478 format file 2023-04-06 18:15:11 +08:00
qingxu fu
7b851ff6b4 修复完成后的文件显示问题 2023-04-06 18:13:16 +08:00
qingxu fu
f1b50dd5f5 fix error 2023-04-06 17:23:26 +08:00
qingxu fu
d936800765 Merge branch 'dev_ui' of https://github.com/binary-husky/chatgpt_academic into dev_ui 2023-04-06 17:19:28 +08:00
qingxu fu
b6e05f93d1 change UI 2023-04-06 17:19:25 +08:00
qingxu fu
2c9bf11464 change UI 2023-04-06 17:18:30 +08:00
qingxu fu
e5d014ea2f change UI 2023-04-06 17:17:31 +08:00
qingxu fu
cd89a4809e 恢复模板函数 2023-04-06 17:15:13 +08:00
qingxu fu
fe8a1ab590 修正打印提示 2023-04-06 16:59:52 +08:00
qingxu fu
f63100939a update self_analysis 2023-04-06 16:33:01 +08:00
qingxu fu
9587808c12 2.4版本 2023-04-06 16:13:56 +08:00
Your Name
527ef979dc End 2023-04-06 03:43:53 +08:00
Your Name
bb0b6a2f34 update 2023-04-06 03:30:02 +08:00
Your Name
19302a33b4 重命名一些函数 2023-04-06 02:02:04 +08:00
Your Name
03cf9fda6c 修改文件命名 2023-04-05 16:19:35 +08:00
qingxu fu
ab35afd399 Merge remote-tracking branch 'origin/master' into dev_ui 2023-04-05 14:35:46 +08:00
binary-husky
53d20b26d9 Update README.md 2023-04-05 14:34:43 +08:00
binary-husky
d5c1c150d2 Update README.md 2023-04-05 14:09:56 +08:00
binary-husky
3eb4bbb123 Update README.md 2023-04-05 14:09:35 +08:00
binary-husky
f4d252ebe2 Update README.md 2023-04-05 14:07:59 +08:00
Your Name
ee7494c0b7 处理没有文件返回的问题 2023-04-05 02:15:47 +08:00
qingxu fu
dcdc8351e7 BUG FIX 2023-04-05 01:58:34 +08:00
qingxu fu
0aeb5b28cd 改进效率 2023-04-05 00:25:53 +08:00
qingxu fu
1dd1720d38 Merge branch 'dev_ui' of https://github.com/binary-husky/chatgpt_academic into dev_ui 2023-04-05 00:15:09 +08:00
qingxu fu
19be0490af BUG FIX 2023-04-05 00:11:12 +08:00
qingxu fu
0c9e18291a BUG FIX 2023-04-05 00:10:06 +08:00
qingxu fu
9f47d0f714 Bug Fix: Hot Reload Wapper For All 2023-04-05 00:09:13 +08:00
qingxu fu
7a254c150f 参数输入bug修复 2023-04-05 00:07:08 +08:00
qingxu fu
3648648b3d 支持更多界面布局的切换 2023-04-04 23:46:47 +08:00
qingxu fu
1da60b7a0c merge 2023-04-04 22:56:06 +08:00
qingxu fu
c40f6f00bb check_new_version 2023-04-04 22:54:08 +08:00
binary-husky
a239abac50 Update version 2023-04-04 22:34:28 +08:00
binary-husky
1042d28e1f Update version 2023-04-04 22:20:39 +08:00
binary-husky
7b75422c26 Update version 2023-04-04 22:20:21 +08:00
binary-husky
99817e9040 Update version 2023-04-04 22:17:47 +08:00
qingxu fu
c9fa26405d 规划版本号 2023-04-04 21:38:20 +08:00
binary-husky
005232afa6 Update issue templates 2023-04-04 17:13:40 +08:00
binary-husky
5b8cc5a899 Update README.md 2023-04-04 15:33:53 +08:00
qingxu fu
a4137e7170 修复代码英文重构Bug 2023-04-04 15:23:42 +08:00
qingxu fu
aaf44750d9 默认暗色护眼主题 2023-04-03 20:56:00 +08:00
binary-husky
bd6eb90449 Merge pull request #290 from LiZheGuang/master
fix: 🐛 修复react解析项目不显示在下拉列表的问题
2023-04-03 17:58:28 +08:00
LiZheGuang
b5a48369a4 fix: 🐛 修复react解析项目不显示在下拉列表的问题 2023-04-03 17:44:09 +08:00
binary-husky
6b5bdbe98a Update issue templates 2023-04-03 17:00:51 +08:00
qingxu fu
69624c66d7 update README 2023-04-03 09:32:01 +08:00
binary-husky
69be335d22 Update README.md 2023-04-03 01:49:40 +08:00
binary-husky
bb1e410cb4 Update README.md 2023-04-03 01:47:49 +08:00
binary-husky
9ccc53fa96 Update README.md 2023-04-03 01:39:17 +08:00
binary-husky
4b83486b3d Update README.md 2023-04-03 01:38:44 +08:00
binary-husky
417c8325de Update README.md 2023-04-03 01:03:00 +08:00
binary-husky
d51ae6abb2 Update README.md 2023-04-03 01:01:57 +08:00
binary-husky
fff7b8ef91 Update README.md 2023-04-02 22:15:12 +08:00
binary-husky
c59eb8ff9e Update README.md 2023-04-02 22:04:33 +08:00
binary-husky
a74f0a9343 Update config.py 2023-04-02 22:02:41 +08:00
binary-husky
f4905a60e2 Update README.md 2023-04-02 21:51:41 +08:00
binary-husky
a562849e4c Update README.md 2023-04-02 21:44:44 +08:00
binary-husky
6105b7f73b Update README.md 2023-04-02 21:41:36 +08:00
binary-husky
3486fb5c10 Update README.md 2023-04-02 21:39:28 +08:00
binary-husky
5f7a1a3da3 Update README.md 2023-04-02 21:33:09 +08:00
binary-husky
8d086ce7c0 Update README.md 2023-04-02 21:31:44 +08:00
binary-husky
b188c4a2b5 Update README.md 2023-04-02 21:28:59 +08:00
binary-husky
10cf456aa8 Update README.md 2023-04-02 21:27:19 +08:00
Your Name
4043db7f33 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-04-02 20:35:16 +08:00
Your Name
9a192fd473 #236 2023-04-02 20:35:09 +08:00
Your Name
9f91fca4d2 remove verbose print 2023-04-02 20:22:11 +08:00
Your Name
160b001bef CHATBOT_HEIGHT - 1 2023-04-02 20:20:37 +08:00
Your Name
1d912bc10d return None instead of [] when no file is concluded 2023-04-02 20:18:58 +08:00
Your Name
51b3f8adca +异常处理 2023-04-02 20:03:25 +08:00
Your Name
16de1812d3 微调theme 2023-04-02 20:02:47 +08:00
binary-husky
641b96548a Update README.md 2023-04-02 16:55:18 +08:00
Your Name
34f4ba211d Merge branch 'CSS' of https://github.com/Keldos-Li/chatgpt_academic (#236) 2023-04-02 16:01:35 +08:00
Your Name
19aba350a3 修改按钮提示 2023-04-02 15:48:54 +08:00
binary-husky
ab57f4bfb0 Merge pull request #253 from RongkangXiong/dev
add crazy_functions 解析一个Java项目
2023-04-02 15:40:03 +08:00
Your Name
b7e0a48cd2 添加Golang、Java等项目的支持 2023-04-02 15:33:09 +08:00
Your Name
58b051ead3 加入 arxiv 小助手插件 2023-04-02 15:19:21 +08:00
RongkangXiong
0c7378e096 add crazy_functions 解析一个Rect项目 2023-04-02 03:07:21 +08:00
RongkangXiong
a52ae14457 add crazy_functions 解析一个Java项目 2023-04-02 02:59:03 +08:00
Your Name
ce3e9b6289 Merge branch 'master' into dev 2023-04-02 01:24:03 +08:00
Your Name
9f07531a16 update 2023-04-02 01:23:15 +08:00
Your Name
2f646b3199 stage llm model interface 2023-04-02 01:18:51 +08:00
Your Name
30b1cbd95c q 2023-04-02 00:51:17 +08:00
Your Name
6c32961211 接入TGUI 2023-04-02 00:40:05 +08:00
Your Name
ba7c7290c1 成功借助tgui调用更多LLM 2023-04-02 00:22:41 +08:00
Your Name
f245f94444 up 2023-04-01 23:46:32 +08:00
Your Name
e86ffad6e7 wait new pr 2023-04-01 21:56:55 +08:00
Your Name
706b2604d8 修改文件名 2023-04-01 21:45:58 +08:00
Keldos
e35f7a7186 fix: 修正CSS中的注释解决列表显示
- 同时使用.markdown-body缩限了css作用域
2023-04-01 20:34:18 +08:00
binary-husky
7c91cfebfa Update README.md 2023-04-01 20:21:31 +08:00
Your Name
9d84ddbc62 advanced theme 2023-04-01 19:48:14 +08:00
Your Name
3d3ffd6de2 新的arxiv论文插件 2023-04-01 19:43:56 +08:00
binary-husky
82038a42da Merge pull request #239 from ylsislove/golang-code-analysis
feat: add function to parse Golang projects
2023-04-01 19:42:06 +08:00
binary-husky
0ce2d423cf Update functional_crazy.py 2023-04-01 19:37:39 +08:00
wangyu
4d6bdca3fc feat: add function to parse Golang projects
This commit adds a new function to parse Golang projects to the collection of crazy functions.
2023-04-01 19:19:36 +08:00
Your Name
c64dbb03fd fix bug 2023-04-01 19:07:58 +08:00
Your Name
8575c82ed7 README 2023-04-01 18:07:26 +08:00
Your Name
bca61754e3 Typo in Prompt 2023-04-01 17:29:30 +08:00
Your Name
f61ea1559c python3.7 compat 2023-04-01 17:11:59 +08:00
Keldos
12c36a68ce feat: 调整表格样式 2023-04-01 16:58:51 +08:00
Keldos
998e127b2f feat: 使用CSS完善表格、列表、代码块、对话气泡显示样式
移植了 川虎ChatGPT 的CSS——但是川虎ChatGPT的CSS也是我写的~
2023-04-01 16:51:38 +08:00
Your Name
c9c9449a59 README up 2023-04-01 16:36:57 +08:00
Your Name
722b538261 update README 2023-04-01 16:35:45 +08:00
Your Name
29fb436e76 Merge branch 'dev' 2023-04-01 16:31:57 +08:00
binary-husky
6789eaee45 Update README.md 2023-04-01 04:25:03 +08:00
binary-husky
937823ec64 Update README.md 2023-04-01 04:19:02 +08:00
Your Name
3c95299f48 交互优化 2023-04-01 04:11:31 +08:00
Your Name
639e24fc82 将css样式移动到theme文件,减少main.py的代码行数 2023-04-01 03:39:43 +08:00
binary-husky
364810983a Merge pull request #209 from jr-shen/dev-1
(1)修改语法检查的prompt,确保输出格式统一。

之前使用时经常发现输出没有把修改的部分加粗,或者在表格中把整段文字输出了,影响阅读。因此在之前的prompt基础上增加了一个example,确保输出格式统一。

(2)表格内增加了边框线,使行/列之间的分隔更清楚。

使用时发现没有边框的表格在里面文字较多时难以区分。因此增加表格内边框线。
2023-04-01 03:37:02 +08:00
Your Name
cb9404c4de 优化Token溢出时的处理 2023-04-01 03:36:05 +08:00
Your Name
17a18e99fa 隐藏、显示功能区 2023-04-01 00:21:27 +08:00
Your Name
30ea77a496 更清朗些的UI 2023-03-31 23:54:25 +08:00
Your Name
01931b0bd2 更清朗的UI 2023-03-31 23:51:17 +08:00
Junru Shen
6a2c7db7c1 add markdown table border line to make text boundary more clear 2023-03-31 23:40:21 +08:00
Junru Shen
9c15c446a6 make grammar correction prompt more clear 2023-03-31 23:38:49 +08:00
Your Name
44ed8a46ad 对word和pdf进行简易的支持 2023-03-31 23:18:45 +08:00
Your Name
41801c017c Merge branch 'master' into dev 2023-03-31 23:08:30 +08:00
Your Name
3e88422ab6 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-31 22:49:45 +08:00
Your Name
7c8b8b95b2 修复bug 2023-03-31 22:49:39 +08:00
Your Name
65b1d78516 优化自译解功能 2023-03-31 22:36:46 +08:00
binary-husky
e815afb792 Update README.md 2023-03-31 21:48:45 +08:00
Your Name
ac681d3201 移动函数到调用模组 2023-03-31 21:46:47 +08:00
binary-husky
ecebdf3ab5 Merge pull request #204 from Eralien/dev-clean_pdf
feat: clean pdf fitz text
2023-03-31 21:42:18 +08:00
binary-husky
8aea6536e0 add contributor 2023-03-31 21:41:17 +08:00
binary-husky
9c90b28bed Merge pull request #147 from JasonGuo1/master
feat(toolbox.py,总结word文档.py): 支持rar格式与7z格式解压;word读取
2023-03-31 21:39:05 +08:00
Your Name
36ef2fa884 JasonGuo1 2023-03-31 21:37:46 +08:00
Your Name
89ca010a11 Merge branch 'master' of https://github.com/JasonGuo1/chatgpt_academic into JasonGuo1-master 2023-03-31 21:31:31 +08:00
Siyuan Feng
60fc2bf4c1 feat: clean pdf fitz text 2023-03-31 21:26:55 +08:00
binary-husky
838c3dc881 Merge pull request #117 from XMB-7/better_prompt
feat: better prompt
2023-03-31 21:19:25 +08:00
Your Name
16c59e1bf6 Merge branch 'better_prompt' of https://github.com/XMB-7/chatgpt_academic into XMB-7-better_prompt 2023-03-31 21:18:28 +08:00
binary-husky
fb889cb4ce Merge pull request #174 from Euclid-Jie/Euclid_Test
feature(read pdf paper then write summary)
2023-03-31 21:06:02 +08:00
Your Name
c91cfc64d9 整合 2023-03-31 21:05:18 +08:00
Your Name
dcab956cff Merge branch 'dev' into Euclid-Jie-Euclid_Test 2023-03-31 21:03:43 +08:00
Your Name
da55ae68f6 pdfminer整合到一个文件中 2023-03-31 21:03:12 +08:00
Your Name
201f53c0f0 Merge branch 'Euclid_Test' of https://github.com/Euclid-Jie/chatgpt_academic into Euclid-Jie-Euclid_Test 2023-03-31 20:26:59 +08:00
Your Name
77a98f03d0 修改文本 2023-03-31 20:12:27 +08:00
Your Name
9ee5545ad5 fix import error 2023-03-31 20:05:31 +08:00
Your Name
d37b0ce447 Merge branch 'dev' of github.com:binary-husky/chatgpt_academic into dev 2023-03-31 20:04:11 +08:00
Your Name
0abb84ae4b config新增说明 2023-03-31 20:02:12 +08:00
binary-husky
e6034b6928 Merge pull request #194 from fulyaec/enhance-chataca
修改AUTHENTICATION的判断,使得AUTHENTICATION为None/[]/""时都可以正确判断
2023-03-31 19:49:40 +08:00
Your Name
ac9e72b9f8 revert toolbox 2023-03-31 19:46:01 +08:00
Your Name
cb1ac5d13d Merge branch 'enhance-chataca' of https://github.com/fulyaec/chatgpt_academic into fulyaec-enhance-chataca 2023-03-31 19:45:23 +08:00
binary-husky
3497addc7b Merge pull request #198 from oneLuckyman/feature-match-API_KEY
一个小改进:更精准的 API_KEY 确认机制
2023-03-31 19:28:21 +08:00
Your Name
f17c580fd9 Merge remote-tracking branch 'origin/hot-reload-test' 2023-03-31 19:21:15 +08:00
Jia Xinglong
808e23c98a 使用 re 模块的 match 函数可以更精准的匹配和确认 API_KEY 是否正确 2023-03-31 17:38:39 +08:00
fulyaec
e3e4fa19a2 refactor and enhance 2023-03-31 16:24:40 +08:00
binary-husky
3cc0635628 Update main.py 2023-03-31 13:33:03 +08:00
binary-husky
7149f9fe90 Update README.md 2023-03-31 13:29:37 +08:00
binary-husky
d2f009ba8d Update README.md 2023-03-31 13:11:10 +08:00
欧玮杰
8f4f13efd5 fix(the ".PDF" file can not be recognized): 2023-03-31 10:26:40 +08:00
欧玮杰
fefe96144f fix(fix "gbk" encode error in 批量总结PDF文档 line14):
由于不可编码字符,导致报错,添加软解码,处理原始文本。
2023-03-31 10:03:10 +08:00
欧玮杰
5521f0e41c feature(read pdf paper then write summary):
add a func called readPdf in toolbox, which can read pdf paper to str. then use bs4.BeautifulSoup to clean content.
2023-03-31 00:54:01 +08:00
binary-husky
2d5d719696 Merge pull request #171 from RoderickChan/add-deploy-instruction
在README中添加远程部署的指导
2023-03-31 00:00:35 +08:00
binary-husky
2b339464ee Update README.md 2023-03-30 23:59:01 +08:00
binary-husky
43ad798c68 Update README.md 2023-03-30 23:34:17 +08:00
RoderickChan
a441c90436 在README中添加远程部署的指导方案 2023-03-30 23:31:44 +08:00
JasonGuo1
5ca623e9c5 feat(总结word文档):增加读取docx、doc格式的功能 2023-03-30 23:23:41 +08:00
binary-husky
c74a8b04b5 添加Wiki链接 2023-03-30 23:09:45 +08:00
JasonGuo1
34c693a571 feat(toolbox):调整了空格的问题 2023-03-30 20:28:15 +08:00
binary-husky
d4cd1877f4 Merge pull request #151 from SadPencil/patch-1
Fix a typo
2023-03-30 19:14:48 +08:00
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
Sad Pencil
70c02a08e9 Fix a typo 2023-03-30 15:55:46 +08:00
JasonGuo1
27f7153f37 feat(toolbox): 支持rar格式与7z格式解压,修改了下注释 2023-03-30 15:48:55 +08:00
JasonGuo1
eb69704c20 feat(toolbox): 支持rar格式与7z格式解压,修改了下注释 2023-03-30 15:48:00 +08:00
JasonGuo1
d616915348 feat(toolbox): 支持rar格式与7z格式解压,修改了下注释 2023-03-30 15:47:18 +08:00
JasonGuo1
5381df8f35 feat(toolbox): 支持rar格式与7z格式解压,修改了下注释 2023-03-30 15:45:58 +08:00
JasonGuo1
a7c857d4d9 feat(支持rar格式与7z格式解压) 2023-03-30 15:24:01 +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
Xiaoming Bai
932c430d5d better prompt 2023-03-30 00:06:02 +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 <qsj287068067@126.com>
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
Your Name
9299c93b17 Merge branch 'test-3-26' 2023-03-26 20:21:39 +08:00
binary-husky
3463a1173a Merge pull request #10 from ifyz/patch-1
Update main.py
2023-03-26 20:21:14 +08:00
Your Name
74eaff4919 fix dockerfile 2023-03-26 20:18:55 +08:00
binary-husky
dd51708309 Update main.py 2023-03-26 20:11:44 +08:00
Your Name
25693c362c UI 2023-03-26 20:10:14 +08:00
Your Name
9eb15f5e68 调整样式 2023-03-26 20:04:59 +08:00
Your Name
7e195244f1 up 2023-03-26 19:32:04 +08:00
Your Name
98d97ebbc8 Merge branch 'ifyz-patch-1' into test-3-26 2023-03-26 19:14:49 +08:00
Your Name
6ab3672cfe Merge branch 'patch-1' of https://github.com/ifyz/chatgpt_academic into ifyz-patch-1 2023-03-26 19:14:27 +08:00
Your Name
6f1ad29e3f add comments 2023-03-26 19:13:58 +08:00
ifyz
61c65d90fe Update main.py
使用全局变量,禁用Gradio 的分析功能。解决国内用户因调用GoogleAnalytics导致的加载缓慢。
使用本地字体,修改Gradio默认从Googleapis调用字体。从而解决用户由于国内网络环境打开首页缓慢的问题。
2023-03-26 17:11:58 +08:00
ifyz
8965706169 Update main.py
使用本地字体,修改Gradio默认从Googleapis调用字体。从而解决用户由于国内网络环境打开首页缓慢的问题。
2023-03-26 15:48:16 +08:00
qingxu fu
a63ae898ce Merge branch 'master' of https://github.com/binary-husky/chatgpt_academic into master 2023-03-24 21:03:33 +08:00
binary-husky
186f10a3e3 Update README.md 2023-03-24 21:03:09 +08:00
binary-husky
67ed394484 Update README.md 2023-03-24 21:02:02 +08:00
qingxu fu
2f4c46b22c trim button text 2023-03-24 20:56:34 +08:00
binary-husky
2f5c977a27 Update predict.py 2023-03-24 19:54:52 +08:00
binary-husky
f801cfbcf6 Update .gitattributes 2023-03-24 19:51:52 +08:00
binary-husky
15693f3f8f Update .gitattributes 2023-03-24 19:50:54 +08:00
binary-husky
8cbac095c1 Create .gitattributes 2023-03-24 19:49:58 +08:00
Your Name
289ace03cf 测试实验性功能 使用说明 2023-03-24 19:47:37 +08:00
Your Name
cefc40aff8 update readme 2023-03-24 19:42:21 +08:00
binary-husky
15dd4b7a80 Update README.md 2023-03-24 19:38:33 +08:00
Your Name
5f8473badb source 2023-03-24 19:37:47 +08:00
Your Name
a8cfe2f113 remote additional file 2023-03-24 19:35:13 +08:00
Your Name
27e056ea35 move images 2023-03-24 19:34:21 +08:00
binary-husky
278f21fde0 Update README.md 2023-03-24 19:20:43 +08:00
Your Name
121f288878 push 2023-03-24 19:10:34 +08:00
binary-husky
5a6b46f0b5 Update README.md 2023-03-24 19:04:55 +08:00
binary-husky
22766d3c12 Update README.md 2023-03-24 19:03:03 +08:00
Your Name
4c72e6cc80 fix count down error 2023-03-24 18:53:43 +08:00
Your Name
38705af90b beta 2023-03-24 18:47:45 +08:00
Your Name
35e15aab8c bug fix 2023-03-24 18:08:48 +08:00
Your Name
1cad53f641 模块化封装 2023-03-24 18:04:59 +08:00
Your Name
818690037a up 2023-03-24 16:34:48 +08:00
Your Name
8053f696d5 用gpt给自己生成注释 2023-03-24 16:25:40 +08:00
Your Name
0b1afab5dd muban 2023-03-24 16:22:26 +08:00
Your Name
aa87d031f5 易读性+ 2023-03-24 16:17:01 +08:00
Your Name
ba2dd3d0ff 批量生成函数注释 2023-03-24 16:14:25 +08:00
Your Name
c19419e1fb 生成文本报告 2023-03-24 15:42:09 +08:00
Your Name
031232c986 better traceback 2023-03-24 15:25:14 +08:00
Your Name
ea4cd5a75a 增加读latex文章的功能,添加测试样例 2023-03-24 14:56:57 +08:00
Your Name
3fb519bf83 Merge remote-tracking branch 'origin/master' into test-3-24 2023-03-24 13:29:37 +08:00
Your Name
1e4bcc0757 设置及时响应 2023-03-24 13:28:12 +08:00
Your Name
44b40ff726 update 2023-03-24 13:12:25 +08:00
binary-husky
791dbf8592 Update functional_crazy.py 2023-03-24 13:11:41 +08:00
binary-husky
82fe0f758d Update functional_crazy.py 2023-03-24 13:06:42 +08:00
binary-husky
8b1def3425 Update functional_crazy.py 2023-03-24 13:06:34 +08:00
binary-husky
8e85e83cec Update functional_crazy.py 2023-03-24 13:02:47 +08:00
qingxu fu
ecdeda8e92 Merge branch 'master' of github.com:binary-husky/chatgpt_academic into master 2023-03-24 11:43:24 +08:00
qingxu fu
831009f027 auto retry 2023-03-24 11:42:39 +08:00
binary-husky
c6da02422b Update README.md 2023-03-24 00:43:33 +08:00
binary-husky
2ad73e9ec3 Update README.md 2023-03-23 22:15:31 +08:00
binary-husky
a0f73a61ea Update predict.py 2023-03-23 22:13:09 +08:00
binary-husky
1b6d611888 Update README.md 2023-03-23 17:03:08 +08:00
Your Name
47d9ea4921 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-23 00:35:01 +08:00
Your Name
b1e33b0f7a 正确地显示requests错误 2023-03-23 00:34:55 +08:00
binary-husky
1e125ca05f Update README.md 2023-03-23 00:20:39 +08:00
binary-husky
16253ed53c Update README.md 2023-03-23 00:15:44 +08:00
binary-husky
8beb75762c Update README.md 2023-03-22 22:52:15 +08:00
Your Name
8da4a0af45 Merge branch 'master' of github.com:binary-husky/chatgpt_academic 2023-03-22 22:42:56 +08:00
Your Name
371bef6e1a bug fix 2023-03-22 22:42:50 +08:00
Your Name
2aaa836d81 程序自解析功能 2023-03-22 22:37:14 +08:00
binary-husky
14d53a288f Update README.md 2023-03-22 22:34:15 +08:00
binary-husky
b1d6e711c0 Update README.md 2023-03-22 20:47:28 +08:00
binary-husky
32b005199d Update README.md 2023-03-22 20:06:09 +08:00
binary-husky
a8886562a1 Update README.md 2023-03-22 20:02:03 +08:00
binary-husky
a60d881268 Update README.md 2023-03-22 19:58:10 +08:00
binary-husky
b9967686a1 私密配置
# config_private.py放自己的秘密如API和代理网址
# 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件
2023-03-22 19:49:45 +08:00
binary-husky
dd3b3524bd 借鉴github.com/GaiZhenbiao/ChuanhuChatGPT项目 2023-03-22 19:47:49 +08:00
binary-husky
a880819ffd from github.com/polarwinkel/mdtex2html 2023-03-22 19:46:08 +08:00
binary-husky
b8d802a922 Update README.md 2023-03-22 19:39:02 +08:00
binary-husky
01aafd4df2 Update README.md 2023-03-22 19:36:39 +08:00
binary-husky
7b3b6f5241 Update README.md 2023-03-22 19:35:34 +08:00
binary-husky
7a50af1897 Update README.md 2023-03-22 19:33:26 +08:00
binary-husky
5dc406c641 修复gradio不吃代理的问题 2023-03-22 19:22:42 +08:00
qingxu fu
3103817990 add private conf 2023-03-22 17:54:15 +08:00
qingxu fu
88aaf310c4 upload 2023-03-22 17:48:25 +08:00
qingxu fu
e8d86a3242 代理位置 2023-03-22 17:45:10 +08:00
qingxu fu
37fd1b1c97 upload 2023-03-22 17:35:23 +08:00
qingxu fu
e3e313beab logging 2023-03-22 17:32:48 +08:00
qingxu fu
380a8a9d4d fix logging encoding 2023-03-22 17:30:30 +08:00
qingxu fu
d00f6bb1a6 add proxy debug funtion 2023-03-22 17:25:37 +08:00
binary-husky
f8a44a82a9 Update README.md 2023-03-22 16:09:37 +08:00
binary-husky
2be45c386d Update predict.py 2023-03-21 21:24:38 +08:00
binary-husky
2b7e8b9278 Update README.md 2023-03-21 17:53:40 +08:00
binary-husky
8590014462 Update README.md 2023-03-21 17:53:04 +08:00
binary-husky
8215caddb2 Update README.md 2023-03-21 15:49:52 +08:00
505030475
93a9d27b1e ok 2023-03-21 13:53:24 +08:00
binary-husky
e128523103 Update README.md 2023-03-21 13:45:08 +08:00
505030475
da0caab4cf add deploy method for windows 2023-03-21 13:35:53 +08:00
binary-husky
6e9813565a Update README.md 2023-03-20 18:56:09 +08:00
binary-husky
01cc409f99 Update README.md 2023-03-20 18:55:06 +08:00
Your Name
3438f8f291 readme 2023-03-20 18:39:48 +08:00
43 changed files with 986 additions and 3136 deletions

View File

@@ -7,17 +7,11 @@ assignees: ''
--- ---
- **(1) Describe the bug 简述** **Describe the bug 简述**
**Screen Shot 截图**
- **(2) Screen Shot 截图** **Terminal Traceback 终端traceback如果有**
- **(3) Terminal Traceback 终端traceback如有**
- **(4) Material to Help Reproduce Bugs 帮助我们复现的测试材料样本(如有)**
Before submitting an issue 提交issue之前 Before submitting an issue 提交issue之前

5
.gitignore vendored
View File

@@ -132,7 +132,6 @@ dmypy.json
.pyre/ .pyre/
.vscode .vscode
.idea
history history
ssr_conf ssr_conf
@@ -142,6 +141,4 @@ private.md
private_upload private_upload
other_llms other_llms
cradle* cradle*
debug* debug*
private*
crazy_functions/test_project/pdf_and_word

View File

@@ -1,6 +1,3 @@
# 此Dockerfile适用于“无本地模型”的环境构建如果需要使用chatglm等本地模型请参考 docs/Dockerfile+ChatGLM
# 如何构建: 先修改 `config.py` 然后 docker build -t gpt-academic .
# 如何运行: docker run --rm -it --net=host gpt-academic
FROM python:3.11 FROM python:3.11
RUN echo '[global]' > /etc/pip.conf && \ RUN echo '[global]' > /etc/pip.conf && \
@@ -14,7 +11,4 @@ RUN pip3 install -r requirements.txt
COPY . . COPY . .
# 可选步骤,用于预热模块
RUN python3 -c 'from check_proxy import warm_up_modules; warm_up_modules()'
CMD ["python3", "-u", "main.py"] CMD ["python3", "-u", "main.py"]

View File

@@ -1,6 +1,6 @@
# How to build | 如何构建: docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM . # How to build | 如何构建: docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
# How to run | 如何运行 (1) 直接运行选择0号GPU: docker run --rm -it --net=host --gpus="0" gpt-academic # How to run | 如何运行 (1) 直接运行: docker run --rm -it --net=host --gpus=all gpt-academic
# How to run | 如何运行 (2) 我想运行之前进容器做一些调整: docker run --rm -it --net=host --gpus="0" gpt-academic bash # How to run | 如何运行 (2) 我想运行之前进容器做一些调整: docker run --rm -it --net=host --gpus=all gpt-academic bash
# 从NVIDIA源从而支持显卡运损检查宿主的nvidia-smi中的cuda版本必须>=11.3 # 从NVIDIA源从而支持显卡运损检查宿主的nvidia-smi中的cuda版本必须>=11.3
FROM nvidia/cuda:11.3.1-runtime-ubuntu20.04 FROM nvidia/cuda:11.3.1-runtime-ubuntu20.04
@@ -24,7 +24,7 @@ RUN curl -sS https://bootstrap.pypa.io/get-pip.py | python3.8
# 下载分支 # 下载分支
WORKDIR /gpt WORKDIR /gpt
RUN $useProxyNetwork git clone https://github.com/binary-husky/chatgpt_academic.git RUN $useProxyNetwork git clone https://github.com/binary-husky/chatgpt_academic.git -b v3.0
WORKDIR /gpt/chatgpt_academic WORKDIR /gpt/chatgpt_academic
RUN $useProxyNetwork python3 -m pip install -r requirements.txt RUN $useProxyNetwork python3 -m pip install -r requirements.txt
RUN $useProxyNetwork python3 -m pip install -r request_llm/requirements_chatglm.txt RUN $useProxyNetwork python3 -m pip install -r request_llm/requirements_chatglm.txt
@@ -36,20 +36,11 @@ from transformers import AutoModel, AutoTokenizer \n\
chatglm_tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) \n\ chatglm_tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) \n\
chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float() ' >> warm_up_chatglm.py chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float() ' >> warm_up_chatglm.py
RUN python3 -u warm_up_chatglm.py RUN python3 -u warm_up_chatglm.py
# 禁用缓存,确保更新代码
ADD "https://www.random.org/cgi-bin/randbyte?nbytes=10&format=h" skipcache
RUN $useProxyNetwork git pull RUN $useProxyNetwork git pull
# 预热Tiktoken模块
RUN python3 -c 'from check_proxy import warm_up_modules; warm_up_modules()'
# 为chatgpt-academic配置代理和API-KEY (非必要 可选步骤) # 为chatgpt-academic配置代理和API-KEY (非必要 可选步骤)
# 可同时填写多个API-KEY支持openai的key和api2d的key共存用英文逗号分割例如API_KEY = "sk-openaikey1,fkxxxx-api2dkey2,........"
# LLM_MODEL 是选择初始的模型
# LOCAL_MODEL_DEVICE 是选择chatglm等本地模型运行的设备可选 cpu 和 cuda
RUN echo ' \n\ RUN echo ' \n\
API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,fkxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \n\ API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \n\
USE_PROXY = True \n\ USE_PROXY = True \n\
LLM_MODEL = "chatglm" \n\ LLM_MODEL = "chatglm" \n\
LOCAL_MODEL_DEVICE = "cuda" \n\ LOCAL_MODEL_DEVICE = "cuda" \n\

238
README.md
View File

@@ -1,10 +1,14 @@
> **Note**
>
> 紧急很抱歉2.60版本的一部分代码重构出错目前2.67及以上版本已经解决,请您及时更新。
>
# <img src="docs/logo.png" width="40" > ChatGPT 学术优化 # ChatGPT 学术优化
**如果喜欢这个项目请给它一个Star如果你发明了更好用的快捷键或函数插件欢迎发issue或者pull requests** **如果喜欢这个项目请给它一个Star如果你发明了更好用的快捷键或函数插件欢迎发issue或者pull requestsdev分支**
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. 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 to `dev` branch.
> **Note** > **Note**
> >
@@ -12,7 +16,9 @@ If you like this project, please give it a Star. If you've come up with more use
> >
> 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)当中。 > 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)当中。
> >
> 3.已支持OpenAI和API2D的api-key共存可在配置文件中填写如`API_KEY="openai-key1,openai-key2,api2d-key3"`。需要临时更换`API_KEY`时,在输入区输入临时的`API_KEY`然后回车键提交后即可生效 > 3.如果您不太习惯部分中文命名的函数、注释或者界面您可以随时点击相关函数插件调用ChatGPT一键生成纯英文的项目源代码
>
<div align="center"> <div align="center">
@@ -23,41 +29,50 @@ If you like this project, please give it a Star. If you've come up with more use
一键代码解释 | 可以正确显示代码、解释代码 一键代码解释 | 可以正确显示代码、解释代码
[自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键 [自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键
[配置代理服务器](https://www.bilibili.com/video/BV1rc411W7Dr) | 支持配置代理服务器 [配置代理服务器](https://www.bilibili.com/video/BV1rc411W7Dr) | 支持配置代理服务器
模块化设计 | 支持自定义高阶的函数插件与[函数插件],插件支持[热更新](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) 模块化设计 | 支持自定义高阶的实验性功能与[函数插件],插件支持[热更新](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)
[自我程序剖析](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)本项目的源代码 [自我程序剖析](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)本项目的源代码
[程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] 一键可以剖析其他Python/C/C++/Java/Lua/...项目树 [程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] 一键可以剖析其他Python/C/C++/Java项目树
读论文 | [函数插件] 一键解读latex论文全文并生成摘要 读论文 | [函数插件] 一键解读latex论文全文并生成摘要
Latex全文翻译、润色 | [函数插件] 一键翻译或润色latex论文 Latex全文翻译、润色 | [函数插件] 一键翻译或润色latex论文
批量注释生成 | [函数插件] 一键批量生成函数注释 批量注释生成 | [函数插件] 一键批量生成函数注释
chat分析报告生成 | [函数插件] 运行后自动生成总结汇报 chat分析报告生成 | [函数插件] 运行后自动生成总结汇报
Markdown中英互译 | [函数插件] 看到上面5种语言的[README](https://github.com/binary-husky/chatgpt_academic/blob/master/docs/README_EN.md)了吗?
[arxiv小助手](https://www.bilibili.com/video/BV1LM4y1279X) | [函数插件] 输入arxiv文章url即可一键翻译摘要+下载PDF [arxiv小助手](https://www.bilibili.com/video/BV1LM4y1279X) | [函数插件] 输入arxiv文章url即可一键翻译摘要+下载PDF
[PDF论文全文翻译功能](https://www.bilibili.com/video/BV1KT411x7Wn) | [函数插件] PDF论文提取题目&摘要+翻译全文(多线程) [PDF论文全文翻译功能](https://www.bilibili.com/video/BV1KT411x7Wn) | [函数插件] PDF论文提取题目&摘要+翻译全文(多线程)
[谷歌学术统合小助手](https://www.bilibili.com/video/BV19L411U7ia) | [函数插件] 给定任意谷歌学术搜索页面URL让gpt帮你选择有趣的文章 [谷歌学术统合小助手](https://www.bilibili.com/video/BV19L411U7ia) (Version>=2.45) | [函数插件] 给定任意谷歌学术搜索页面URL让gpt帮你选择有趣的文章
公式/图片/表格显示 | 可以同时显示公式的tex形式和渲染形式,支持公式、代码高亮 公式显示 | 可以同时显示公式的tex形式和渲染形式
图片显示 | 可以在markdown中显示图片
多线程函数插件支持 | 支持多线调用chatgpt一键处理海量文本或程序 多线程函数插件支持 | 支持多线调用chatgpt一键处理海量文本或程序
支持GPT输出的markdown表格 | 可以输出支持GPT的markdown表格
启动暗色gradio[主题](https://github.com/binary-husky/chatgpt_academic/issues/173) | 在浏览器url后面添加```/?__dark-theme=true```可以切换dark主题 启动暗色gradio[主题](https://github.com/binary-husky/chatgpt_academic/issues/173) | 在浏览器url后面添加```/?__dark-theme=true```可以切换dark主题
[多LLM模型](https://www.bilibili.com/video/BV1wT411p7yf)支持,[API2D](https://api2d.com/)接口支持 | 同时被GPT3.5、GPT4和[清华ChatGLM](https://github.com/THUDM/ChatGLM-6B)伺候的感觉一定会很不错吧?
huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/gpt-academic) | 登陆huggingface后复制[此空间](https://huggingface.co/spaces/qingxu98/gpt-academic) huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/gpt-academic) | 登陆huggingface后复制[此空间](https://huggingface.co/spaces/qingxu98/gpt-academic)
[多LLM模型](https://www.bilibili.com/video/BV1EM411K7VH/)混合支持([v3.0分支](https://github.com/binary-husky/chatgpt_academic/tree/v3.0)测试中) | 同时被ChatGPT和[清华ChatGLM](https://github.com/THUDM/ChatGLM-6B)伺候的感觉一定会很不错吧?
兼容[TGUI](https://github.com/oobabooga/text-generation-webui)接入更多样的语言模型 | 接入opt-1.3b, galactica-1.3b等模型([v3.0分支](https://github.com/binary-husky/chatgpt_academic/tree/v3.0)测试中)
…… | …… …… | ……
</div> </div>
<!-- - 新界面master主分支, 右dev开发前沿 -->
- 新界面(修改`config.py`中的LAYOUT选项即可实现“左右布局”和“上下布局”的切换 - 新界面
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" > <img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
</div> </div>
- 所有按钮都通过读取functional.py动态生成可随意加自定义功能解放粘贴板 - 所有按钮都通过读取functional.py动态生成可随意加自定义功能解放粘贴板
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" > <img src="img/公式.gif" width="700" >
</div> </div>
- 润色/纠错 - 润色/纠错
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" > <img src="img/润色.gif" width="700" >
</div>
- 支持GPT输出的markdown表格
<div align="center">
<img src="img/demo2.jpg" width="500" >
</div> </div>
- 如果输出包含公式会同时以tex形式和渲染形式显示方便复制和阅读 - 如果输出包含公式会同时以tex形式和渲染形式显示方便复制和阅读
@@ -65,162 +80,156 @@ huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/
<img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" > <img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
</div> </div>
- 懒得看项目代码整个工程直接给chatgpt炫嘴里 - 懒得看项目代码整个工程直接给chatgpt炫嘴里
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" > <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
</div> </div>
- 多种大语言模型混合调用(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4 - 多种大语言模型混合调用([v3.0分支](https://github.com/binary-husky/chatgpt_academic/tree/v3.0)测试中
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" > <img src="https://user-images.githubusercontent.com/96192199/231222778-34776885-a7f0-4f2c-b5f4-7cc2ef3ecb58.png" width="700" >
</div> </div>
多种大语言模型混合调用[huggingface测试版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)huggingface版不支持chatglm
--- ## 直接运行 (Windows, Linux or MacOS)
## 安装-方法1直接运行 (Windows, Linux or MacOS) ### 1. 下载项目
1. 下载项目
```sh ```sh
git clone https://github.com/binary-husky/chatgpt_academic.git git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic cd chatgpt_academic
``` ```
2. 配置API_KEY和代理设置 ### 2. 配置API_KEY和代理设置
在`config.py`中,配置 海外Proxy 和 OpenAI API KEY说明如下 在`config.py`中,配置 海外Proxy 和 OpenAI API KEY说明如下
``` ```
1. 如果你在国内需要设置海外代理才能够顺利使用OpenAI API设置方法请仔细阅读config.py1.修改其中的USE_PROXY为True; 2.按照说明修改其中的proxies 1. 如果你在国内,需要设置海外代理才能够顺利使用 OpenAI API设置方法请仔细阅读config.py1.修改其中的USE_PROXY为True; 2.按照说明修改其中的proxies
2. 配置 OpenAI API KEY。支持任意数量的OpenAI的密钥和API2D的密钥共存/负载均衡多个KEY用英文逗号分隔即可例如输入 API_KEY="OpenAI密钥1,API2D密钥2,OpenAI密钥3,OpenAI密钥4" 2. 配置 OpenAI API KEY。你需要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。
3. 与代理网络有关的issue网络超时、代理不起作用汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1 3. 与代理网络有关的issue网络超时、代理不起作用汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1
``` ```
P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控可以让您的隐私信息更加安全。 P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控可以让您的隐私信息更加安全。
3. 安装依赖 ### 3. 安装依赖
```sh ```sh
# (选择I: 如熟悉python)推荐 # (选择)推荐
python -m pip install -r requirements.txt python -m pip install -r requirements.txt
# 备注使用官方pip源或者阿里pip源其他pip源如一些大学的pip有可能出问题临时换源方法python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
# (选择II: 如不熟悉python使用anaconda步骤也是类似的 # (选择二)如果您使用anaconda步骤也是类似的
# II-1conda create -n gptac_venv python=3.11 # 选择二.1conda create -n gptac_venv python=3.11
# II-2conda activate gptac_venv # 选择二.2conda activate gptac_venv
# II-3python -m pip install -r requirements.txt # 选择二.3python -m pip install -r requirements.txt
# 备注使用官方pip源或者阿里pip源其他pip源如一些大学的pip有可能出问题临时换源方法
# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
``` ```
如果需要支持清华ChatGLM后端需要额外安装更多依赖前提条件熟悉python + 电脑配置够强): ### 4. 运行
```sh
python -m pip install -r request_llm/requirements_chatglm.txt
```
4. 运行
```sh ```sh
python main.py python main.py
``` ```
5. 测试函数插件 ### 5. 测试实验性功能
``` ```
- 测试C++项目头文件分析
input区域 输入 `./crazy_functions/test_project/cpp/libJPG` 然后点击 "[实验] 解析整个C++项目input输入项目根路径"
- 测试给Latex项目写摘要
input区域 输入 `./crazy_functions/test_project/latex/attention` 然后点击 "[实验] 读tex论文写摘要input输入项目根路径"
- 测试Python项目分析 - 测试Python项目分析
选择1input区域 输入 `./crazy_functions/test_project/python/dqn` 然后点击 "解析整个Python项目" input区域 输入 `./crazy_functions/test_project/python/dqn` 然后点击 "[实验] 解析整个py项目input输入项目根路径"
选择2展开文件上传区将python文件/包含python文件的压缩包拖拽进去在出现反馈提示后 然后点击 "解析整个Python项目" - 测试自我代码解读
- 测试自我代码解读(本项目自译解) 点击 "[实验] 请解析并解构此项目本身"
点击 "[多线程Demo] 解析此项目本身(源码自译解)" - 测试实验功能模板函数要求gpt回答历史上的今天发生了什么您可以根据此函数为模板实现更复杂的功能
- 测试函数插件模板函数要求gpt回答历史上的今天发生了什么您可以根据此函数为模板实现更复杂的功能 点击 "[实验] 实验功能函数模板"
点击 "[函数插件模板Demo] 历史上的今天"
- 函数插件区下拉菜单中有更多功能可供选择
``` ```
## 安装-方法2使用Docker ## 使用docker (Linux)
1. 仅ChatGPT推荐大多数人选择
``` sh ``` sh
# 下载项目 # 下载项目
git clone https://github.com/binary-husky/chatgpt_academic.git git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic cd chatgpt_academic
# 配置 海外Proxy”, “API_KEY” 以及 “WEB_PORT” (例如50923) 等 # 配置 海外Proxy 和 OpenAI API KEY
用任意文本编辑器编辑 config.py 用任意文本编辑器编辑 config.py
# 安装 # 安装
docker build -t gpt-academic . docker build -t gpt-academic .
#(最后一步-选择1在Linux环境下用`--net=host`更方便快捷 # 运行
docker run --rm -it --net=host gpt-academic docker run --rm -it --net=host gpt-academic
#(最后一步-选择2在macOS/windows环境下只能用-p选项将容器上的端口(例如50923)暴露给主机上的端口
docker run --rm -it -p 50923:50923 gpt-academic # 测试实验性功能
## 测试自我代码解读
点击 "[实验] 请解析并解构此项目本身"
## 测试实验功能模板函数要求gpt回答历史上的今天发生了什么您可以根据此函数为模板实现更复杂的功能
点击 "[实验] 实验功能函数模板"
##请注意在docker中运行时需要额外注意程序的文件访问权限问题
## 测试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输入项目根路径"
``` ```
2. ChatGPT+ChatGLM需要对Docker熟悉 + 读懂Dockerfile + 电脑配置够强) ## 其他部署方式
- 使用WSL2Windows Subsystem for Linux 子系统)
请访问[部署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)
``` sh - nginx远程部署
# 修改Dockerfile 请访问[部署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)
cd docs && nano Dockerfile+ChatGLM
# 构建 Dockerfile+ChatGLM在docs路径下请先cd docs
docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
# 运行 (1) 直接运行:
docker run --rm -it --net=host --gpus=all gpt-academic
# 运行 (2) 我想运行之前进容器做一些调整:
docker run --rm -it --net=host --gpus=all gpt-academic bash
```
## 安装-方法3其他部署方式需要云服务器知识与经验 ## 自定义新的便捷按钮(学术快捷键自定义
打开functional.py添加条目如下然后重启程序即可。如果按钮已经添加成功并可见那么前缀、后缀都支持热修改无需重启程序即可生效。
1. 远程云服务器部署
请访问[部署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)
2. 使用WSL2Windows Subsystem for Linux 子系统)
请访问[部署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)
## 安装-代理配置
1. 常规方法
[配置代理](https://github.com/binary-husky/chatgpt_academic/issues/1)
2. 纯新手教程
[纯新手教程](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)
---
## 自定义新的便捷按钮 / 自定义函数插件
1. 自定义新的便捷按钮(学术快捷键)
任意文本编辑器打开`core_functional.py`,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。)
例如 例如
``` ```
"超级英译中": { "超级英译中": {
# 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等
"Prefix": "请翻译把下面一段内容成中文然后用一个markdown表格逐一解释文中出现的专有名词\n\n", "Prefix": "请翻译把下面一段内容成中文然后用一个markdown表格逐一解释文中出现的专有名词\n\n",
# 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。 # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。
"Suffix": "", "Suffix": "",
}, },
``` ```
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" > <img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
</div> </div>
2. 自定义函数插件
编写强大的函数插件来执行任何你想得到的和想不到的任务。 如果你发明了更好用的学术快捷键欢迎发issue或者pull requests
本项目的插件编写、调试难度很低只要您具备一定的python基础知识就可以仿照我们提供的模板实现自己的插件功能。
详情请参考[函数插件指南](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)。
## 配置代理
### 方法一:常规方法
在```config.py```中修改端口与代理软件对应
--- <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226571294-37a47cd9-4d40-4c16-97a2-d360845406f7.png" width="500" >
<img src="https://user-images.githubusercontent.com/96192199/226838985-e5c95956-69c2-4c23-a4dd-cd7944eeb451.png" width="500" >
</div>
配置完成后,你可以用以下命令测试代理是否工作,如果一切正常,下面的代码将输出你的代理服务器所在地:
```
python check_proxy.py
```
### 方法二:纯新手教程
[纯新手教程](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)
## 部分功能展示 ## 兼容性测试
1. 图片显示: ### 图片显示:
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" > <img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
</div> </div>
2. 本项目的代码自译解(如果一个程序能够读懂并剖析自己):
### 如果一个程序能够读懂并剖析自己:
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" > <img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
@@ -230,7 +239,7 @@ docker run --rm -it --net=host --gpus=all gpt-academic bash
<img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" > <img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
</div> </div>
3. 其他任意Python/Cpp/Java/Go/Rect/...项目剖析: ### 其他任意Python/Cpp项目剖析
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" > <img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
</div> </div>
@@ -239,45 +248,40 @@ docker run --rm -it --net=host --gpus=all gpt-academic bash
<img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" > <img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
</div> </div>
4. Latex论文一键阅读理解与摘要生成 ### Latex论文一键阅读理解与摘要生成
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" > <img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
</div> </div>
5. 自动报告生成 ### 自动报告生成
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" > <img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" > <img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" > <img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
</div> </div>
6. 模块化功能设计 ### 模块化功能设计
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" > <img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" > <img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
</div> </div>
7. 源代码转译英文 ### 源代码转译英文
<div align="center"> <div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" > <img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
</div> </div>
8. 互联网在线信息综合
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/233575247-fb00819e-6d1b-4bb7-bd54-1d7528f03dd9.png" width="800" >
</div>
## Todo 与 版本规划: ## Todo 与 版本规划:
- version 3.2+ (todo): 函数插件支持更多参数接口
- version 3.1: 支持同时问询多个gpt模型支持api2d支持多个apikey负载均衡 - version 3 (Todo):
- version 3.0: 对chatglm和其他小型llm的支持 - - 支持gpt4和其他更多llm
- version 2.6: 重构了插件结构,提高了交互性,加入更多插件 - version 2.4+ (Todo):
- version 2.5: 自更新,解决总结大工程源代码时文本过长、token溢出的问题 - - 总结大工程源代码时文本过长、token溢出的问题
- - 实现项目打包部署
- - 函数插件参数接口优化
- - 自更新
- version 2.4: (1)新增PDF全文翻译功能; (2)新增输入区切换位置的功能; (3)新增垂直布局选项; (4)多线程函数插件优化。 - version 2.4: (1)新增PDF全文翻译功能; (2)新增输入区切换位置的功能; (3)新增垂直布局选项; (4)多线程函数插件优化。
- version 2.3: 增强多线程交互性 - version 2.3: 增强多线程交互性
- version 2.2: 函数插件支持热重载 - version 2.2: 函数插件支持热重载
@@ -285,16 +289,16 @@ docker run --rm -it --net=host --gpus=all gpt-academic bash
- version 2.0: 引入模块化函数插件 - version 2.0: 引入模块化函数插件
- version 1.0: 基础功能 - version 1.0: 基础功能
chatgpt_academic开发者QQ群734063350
## 参考与学习 ## 参考与学习
``` ```
代码中参考了很多其他优秀项目中的设计,主要包括: 代码中参考了很多其他优秀项目中的设计,主要包括:
# 借鉴项目1借鉴了ChuanhuChatGPT中诸多技巧 # 借鉴项目1借鉴了ChuanhuChatGPT中读取OpenAI json的方法、记录历史问询记录的方法以及gradio queue的使用技巧
https://github.com/GaiZhenbiao/ChuanhuChatGPT https://github.com/GaiZhenbiao/ChuanhuChatGPT
# 借鉴项目2清华ChatGLM-6B # 借鉴项目2
https://github.com/THUDM/ChatGLM-6B https://github.com/THUDM/ChatGLM-6B
``` ```

View File

@@ -103,7 +103,7 @@ def auto_update():
import json import json
proxies, = get_conf('proxies') proxies, = get_conf('proxies')
response = requests.get( response = requests.get(
"https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=5) "https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=1)
remote_json_data = json.loads(response.text) remote_json_data = json.loads(response.text)
remote_version = remote_json_data['version'] remote_version = remote_json_data['version']
if remote_json_data["show_feature"]: if remote_json_data["show_feature"]:
@@ -133,13 +133,6 @@ def auto_update():
except: except:
print('自动更新程序:已禁用') print('自动更新程序:已禁用')
def warm_up_modules():
print('正在执行一些模块的预热...')
from request_llm.bridge_all import model_info
enc = model_info["gpt-3.5-turbo"]['tokenizer']
enc.encode("模块预热", disallowed_special=())
enc = model_info["gpt-4"]['tokenizer']
enc.encode("模块预热", disallowed_special=())
if __name__ == '__main__': if __name__ == '__main__':
import os import os

View File

@@ -1,5 +1,5 @@
# [step 1]>> 例如: API_KEY = "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" 此key无效 # [step 1]>> 例如: API_KEY = "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" 此key无效
API_KEY = "sk-此处填API密钥" # 可同时填写多个API-KEY用英文逗号分割例如API_KEY = "sk-openaikey1,sk-openaikey2,fkxxxx-api2dkey1,fkxxxx-api2dkey2" API_KEY = "sk-此处填API密钥"
# [step 2]>> 改为True应用代理如果直接在海外服务器部署此处不修改 # [step 2]>> 改为True应用代理如果直接在海外服务器部署此处不修改
USE_PROXY = False USE_PROXY = False
@@ -19,12 +19,8 @@ if USE_PROXY:
else: else:
proxies = None proxies = None
# [step 3]>> 多线程函数插件中默认允许多少路线程同时访问OpenAI。Free trial users的限制是每分钟3次Pay-as-you-go users的限制是每分钟3500次
# 一言以蔽之免费用户填3OpenAI绑了信用卡的用户可以填 16 或者更高。提高限制请查询https://platform.openai.com/docs/guides/rate-limits/overview
DEFAULT_WORKER_NUM = 3
# [step 3]>> 以下配置可以优化体验,但大部分场合下并不需要修改
# [step 4]>> 以下配置可以优化体验,但大部分场合下并不需要修改
# 对话窗的高度 # 对话窗的高度
CHATBOT_HEIGHT = 1115 CHATBOT_HEIGHT = 1115
@@ -43,20 +39,15 @@ WEB_PORT = -1
# 如果OpenAI不响应网络卡顿、代理失败、KEY失效重试的次数限制 # 如果OpenAI不响应网络卡顿、代理失败、KEY失效重试的次数限制
MAX_RETRY = 2 MAX_RETRY = 2
# OpenAI模型选择是gpt4现在只对申请成功的人开放体验gpt-4可以试试api2d # OpenAI模型选择是gpt4现在只对申请成功的人开放
LLM_MODEL = "gpt-3.5-turbo" # 可选 ↓↓↓ LLM_MODEL = "gpt-3.5-turbo"
AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "api2d-gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "chatglm"]
# 本地LLM模型如ChatGLM的执行方式 CPU/GPU # OpenAI的API_URL
LOCAL_MODEL_DEVICE = "cpu" # 可选 "cuda" API_URL = "https://api.openai.com/v1/chat/completions"
# 设置gradio的并行线程数不需要修改 # 设置并行使用的线程数
CONCURRENT_COUNT = 100 CONCURRENT_COUNT = 100
# 设置用户名和密码(不需要修改)(相关功能不稳定与gradio版本和网络都相关如果本地使用不建议加这个 # 设置用户名和密码相关功能不稳定与gradio版本和网络都相关如果本地使用不建议加这个
# [("username", "password"), ("username2", "password2"), ...] # [("username", "password"), ("username2", "password2"), ...]
AUTHENTICATION = [] AUTHENTICATION = []
# 重新URL重新定向实现更换API_URL的作用常规情况下不要修改
# 格式 {"https://api.openai.com/v1/chat/completions": "重定向的URL"}
API_URL_REDIRECT = {}

View File

@@ -3,6 +3,7 @@ from toolbox import HotReload # HotReload 的意思是热更新,修改函数
def get_crazy_functions(): def get_crazy_functions():
###################### 第一组插件 ########################### ###################### 第一组插件 ###########################
# [第一组插件]: 最早期编写的项目插件和一些demo
from crazy_functions.读文章写摘要 import 读文章写摘要 from crazy_functions.读文章写摘要 import 读文章写摘要
from crazy_functions.生成函数注释 import 批量生成函数注释 from crazy_functions.生成函数注释 import 批量生成函数注释
from crazy_functions.解析项目源代码 import 解析项目本身 from crazy_functions.解析项目源代码 import 解析项目本身
@@ -15,23 +16,15 @@ def get_crazy_functions():
from crazy_functions.高级功能函数模板 import 高阶功能模板函数 from crazy_functions.高级功能函数模板 import 高阶功能模板函数
from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文 from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文
from crazy_functions.Latex全文润色 import Latex英文润色 from crazy_functions.Latex全文润色 import Latex英文润色
from crazy_functions.询问多个大语言模型 import 同时问询
from crazy_functions.解析项目源代码 import 解析一个Lua项目
from crazy_functions.解析项目源代码 import 解析一个CSharp项目
from crazy_functions.总结word文档 import 总结word文档
function_plugins = { function_plugins = {
"解析整个Python项目": { "解析整个Python项目": {
"Color": "stop", # 按钮颜色 "Color": "stop", # 按钮颜色
"Function": HotReload(解析一个Python项目) "Function": HotReload(解析一个Python项目)
}, },
"批量总结Word文档": {
"Color": "stop",
"Function": HotReload(总结word文档)
},
"解析整个C++项目头文件": { "解析整个C++项目头文件": {
"Color": "stop", # 按钮颜色 "Color": "stop", # 按钮颜色
"AsButton": False, # 加入下拉菜单中
"Function": HotReload(解析一个C项目的头文件) "Function": HotReload(解析一个C项目的头文件)
}, },
"解析整个C++项目(.cpp/.hpp/.c/.h": { "解析整个C++项目(.cpp/.hpp/.c/.h": {
@@ -54,16 +47,6 @@ def get_crazy_functions():
"AsButton": False, # 加入下拉菜单中 "AsButton": False, # 加入下拉菜单中
"Function": HotReload(解析一个Rect项目) "Function": HotReload(解析一个Rect项目)
}, },
"解析整个Lua项目": {
"Color": "stop", # 按钮颜色
"AsButton": False, # 加入下拉菜单中
"Function": HotReload(解析一个Lua项目)
},
"解析整个CSharp项目": {
"Color": "stop", # 按钮颜色
"AsButton": False, # 加入下拉菜单中
"Function": HotReload(解析一个CSharp项目)
},
"读Tex论文写摘要": { "读Tex论文写摘要": {
"Color": "stop", # 按钮颜色 "Color": "stop", # 按钮颜色
"Function": HotReload(读文章写摘要) "Function": HotReload(读文章写摘要)
@@ -87,17 +70,16 @@ def get_crazy_functions():
} }
###################### 第二组插件 ########################### ###################### 第二组插件 ###########################
# [第二组插件]: 经过充分测试 # [第二组插件]: 经过充分测试,但功能上距离达到完美状态还差一点点
from crazy_functions.批量总结PDF文档 import 批量总结PDF文档 from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
from crazy_functions.批量总结PDF文档pdfminer import 批量总结PDF文档pdfminer from crazy_functions.批量总结PDF文档pdfminer import 批量总结PDF文档pdfminer
from crazy_functions.总结word文档 import 总结word文档
from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档 from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
from crazy_functions.谷歌检索小助手 import 谷歌检索小助手 from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入 from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入
from crazy_functions.Latex全文润色 import Latex中文润色 from crazy_functions.Latex全文润色 import Latex中文润色
from crazy_functions.Latex全文翻译 import Latex中译英 from crazy_functions.Latex全文翻译 import Latex中译英
from crazy_functions.Latex全文翻译 import Latex英译中 from crazy_functions.Latex全文翻译 import Latex英译中
from crazy_functions.批量Markdown翻译 import Markdown中译英
from crazy_functions.批量Markdown翻译 import Markdown英译中
function_plugins.update({ function_plugins.update({
"批量翻译PDF文档多线程": { "批量翻译PDF文档多线程": {
@@ -105,10 +87,6 @@ def get_crazy_functions():
"AsButton": True, # 加入下拉菜单中 "AsButton": True, # 加入下拉菜单中
"Function": HotReload(批量翻译PDF文档) "Function": HotReload(批量翻译PDF文档)
}, },
"询问多个GPT模型": {
"Color": "stop", # 按钮颜色
"Function": HotReload(同时问询)
},
"[测试功能] 批量总结PDF文档": { "[测试功能] 批量总结PDF文档": {
"Color": "stop", "Color": "stop",
"AsButton": False, # 加入下拉菜单中 "AsButton": False, # 加入下拉菜单中
@@ -125,7 +103,10 @@ def get_crazy_functions():
"AsButton": False, # 加入下拉菜单中 "AsButton": False, # 加入下拉菜单中
"Function": HotReload(谷歌检索小助手) "Function": HotReload(谷歌检索小助手)
}, },
"批量总结Word文档": {
"Color": "stop",
"Function": HotReload(总结word文档)
},
"理解PDF文档内容 模仿ChatPDF": { "理解PDF文档内容 模仿ChatPDF": {
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效 # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
"Color": "stop", "Color": "stop",
@@ -156,40 +137,24 @@ def get_crazy_functions():
"AsButton": False, # 加入下拉菜单中 "AsButton": False, # 加入下拉菜单中
"Function": HotReload(Latex英译中) "Function": HotReload(Latex英译中)
}, },
"[测试功能] 批量Markdown中译英输入路径或上传压缩包": {
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
"Color": "stop",
"AsButton": False, # 加入下拉菜单中
"Function": HotReload(Markdown中译英)
},
"[测试功能] 批量Markdown英译中输入路径或上传压缩包": {
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
"Color": "stop",
"AsButton": False, # 加入下拉菜单中
"Function": HotReload(Markdown英译中)
},
}) })
###################### 第三组插件 ########################### ###################### 第三组插件 ###########################
# [第三组插件]: 尚未充分测试的函数插件,放在这里 # [第三组插件]: 尚未充分测试的函数插件,放在这里
from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要 try:
function_plugins.update({ from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要
"一键下载arxiv论文并翻译摘要先在input输入编号如1812.10695": { function_plugins.update({
"Color": "stop", "一键下载arxiv论文并翻译摘要先在input输入编号如1812.10695": {
"AsButton": False, # 加入下拉菜单中 "Color": "stop",
"Function": HotReload(下载arxiv论文并翻译摘要) "AsButton": False, # 加入下拉菜单中
} "Function": HotReload(下载arxiv论文并翻译摘要)
}) }
})
from crazy_functions.联网的ChatGPT import 连接网络回答问题
function_plugins.update({ except Exception as err:
"连接网络回答问题(先输入问题,再点击按钮,需要访问谷歌)": { print(f'[下载arxiv论文并翻译摘要] 插件导入失败 {str(err)}')
"Color": "stop",
"AsButton": False, # 加入下拉菜单中
"Function": HotReload(连接网络回答问题)
}
})
###################### 第n组插件 ########################### ###################### 第n组插件 ###########################
return function_plugins return function_plugins

View File

@@ -11,9 +11,10 @@ class PaperFileGroup():
self.sp_file_tag = [] self.sp_file_tag = []
# count_token # count_token
from request_llm.bridge_all import model_info import tiktoken
enc = model_info["gpt-3.5-turbo"]['tokenizer'] from toolbox import get_conf
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
def get_token_num(txt): return len(enc.encode(txt))
self.get_token_num = get_token_num self.get_token_num = get_token_num
def run_file_split(self, max_token_limit=1900): def run_file_split(self, max_token_limit=1900):
@@ -91,7 +92,7 @@ def 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, ch
chatbot=chatbot, chatbot=chatbot,
history_array=[[""] for _ in range(n_split)], history_array=[[""] for _ in range(n_split)],
sys_prompt_array=sys_prompt_array, sys_prompt_array=sys_prompt_array,
# max_workers=5, # 并行任务数量限制最多同时执行5个其他的排队等待 max_workers=10, # OpenAI所允许的最大并行过载
scroller_max_len = 80 scroller_max_len = 80
) )

View File

@@ -11,9 +11,10 @@ class PaperFileGroup():
self.sp_file_tag = [] self.sp_file_tag = []
# count_token # count_token
from request_llm.bridge_all import model_info import tiktoken
enc = model_info["gpt-3.5-turbo"]['tokenizer'] from toolbox import get_conf
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
def get_token_num(txt): return len(enc.encode(txt))
self.get_token_num = get_token_num self.get_token_num = get_token_num
def run_file_split(self, max_token_limit=1900): def run_file_split(self, max_token_limit=1900):
@@ -79,7 +80,7 @@ def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, ch
elif language == 'zh->en': elif language == 'zh->en':
inputs_array = [f"Below is a section from a Chinese academic paper, translate it into English, do not modify any latex command such as \section, \cite and equations:" + inputs_array = [f"Below is a section from a Chinese academic paper, translate it into English, do not modify any latex command such as \section, \cite and equations:" +
f"\n\n{frag}" for frag in pfg.sp_file_contents] f"\n\n{frag}" for frag in pfg.sp_file_contents]
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag] inputs_show_user_array = [f"润色 {f}" for f in pfg.sp_file_tag]
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)] sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
@@ -89,7 +90,7 @@ def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, ch
chatbot=chatbot, chatbot=chatbot,
history_array=[[""] for _ in range(n_split)], history_array=[[""] for _ in range(n_split)],
sys_prompt_array=sys_prompt_array, sys_prompt_array=sys_prompt_array,
# max_workers=5, # OpenAI所允许的最大并行过载 max_workers=10, # OpenAI所允许的最大并行过载
scroller_max_len = 80 scroller_max_len = 80
) )

View File

@@ -1,124 +0,0 @@
"""
这是什么?
这个文件用于函数插件的单元测试
运行方法 python crazy_functions/crazy_functions_test.py
"""
def validate_path():
import os, sys
dir_name = os.path.dirname(__file__)
root_dir_assume = os.path.abspath(os.path.dirname(__file__) + '/..')
os.chdir(root_dir_assume)
sys.path.append(root_dir_assume)
validate_path() # validate path so you can run from base directory
from colorful import *
from toolbox import get_conf, ChatBotWithCookies
proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \
get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY')
llm_kwargs = {
'api_key': API_KEY,
'llm_model': LLM_MODEL,
'top_p':1.0,
'max_length': None,
'temperature':1.0,
}
plugin_kwargs = { }
chatbot = ChatBotWithCookies(llm_kwargs)
history = []
system_prompt = "Serve me as a writing and programming assistant."
web_port = 1024
def test_解析一个Python项目():
from crazy_functions.解析项目源代码 import 解析一个Python项目
txt = "crazy_functions/test_project/python/dqn"
for cookies, cb, hist, msg in 解析一个Python项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_解析一个Cpp项目():
from crazy_functions.解析项目源代码 import 解析一个C项目
txt = "crazy_functions/test_project/cpp/cppipc"
for cookies, cb, hist, msg in 解析一个C项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_Latex英文润色():
from crazy_functions.Latex全文润色 import Latex英文润色
txt = "crazy_functions/test_project/latex/attention"
for cookies, cb, hist, msg in Latex英文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_Markdown中译英():
from crazy_functions.批量Markdown翻译 import Markdown中译英
txt = "README.md"
for cookies, cb, hist, msg in Markdown中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_批量翻译PDF文档():
from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
txt = "crazy_functions/test_project/pdf_and_word"
for cookies, cb, hist, msg in 批量翻译PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_谷歌检索小助手():
from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
txt = "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=auto+reinforcement+learning&btnG="
for cookies, cb, hist, msg in 谷歌检索小助手(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_总结word文档():
from crazy_functions.总结word文档 import 总结word文档
txt = "crazy_functions/test_project/pdf_and_word"
for cookies, cb, hist, msg in 总结word文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_下载arxiv论文并翻译摘要():
from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要
txt = "1812.10695"
for cookies, cb, hist, msg in 下载arxiv论文并翻译摘要(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print(cb)
def test_联网回答问题():
from crazy_functions.联网的ChatGPT import 连接网络回答问题
# txt = "“我们称之为高效”是什么梗?"
# >> 从第0份、第1份、第2份搜索结果可以看出“我们称之为高效”是指在游戏社区中用户们用来形容一些游戏策略或行为非常高效且能够带来好的效果的用语。这个用语最初可能是在群星Stellaris这个游戏里面流行起来的后来也传播到了其他游戏中比如巨像Titan等游戏。其中第1份搜索结果中的一篇文章也指出“我们称之为高效”这 一用语来源于群星Stellaris游戏中的一个情节。
# txt = "为什么说枪毙P社玩家没有一个冤枉的"
# >> 它们都是关于一个知乎用户所发的帖子引用了一群游戏玩家对于需要对P社玩家进行枪毙的讨论这个话题的本质是玩家们对于P 社游戏中的政治与历史元素的不同看法,以及其中不少玩家以极端立场宣扬的想法和言论,因此有人就以枪毙这些玩家来回应此类言论。但是这个话题本身并没有实质内容,只是一个玩笑或者恶搞,并不应该被当做真实的态度或者观点,因此这种说法没有实际意义。
# txt = "谁是应急食品?"
# >> '根据以上搜索结果可以得知,应急食品是“原神”游戏中的角色派蒙的外号。'
# txt = "道路千万条,安全第一条。后面两句是?"
# >> '行车不规范,亲人两行泪。'
# txt = "What is in the canister?"
# >> Rainbow Six Siege 游戏中 Smoke 的 Canister 中装有何种物质相关的官方信息。
# txt = "失败的man是什么?"
# >> 根据第1份搜索结果可以得知失败的man是指一位在B站购买了蜘蛛侠COS服后穿上后被网友嘲笑的UP主而“失败的man”是蜘蛛侠英文名“spiderman”的谐音梗并且网友们还 给这位UP主起了“苍蝇侠”的外号。因此失败的man是指这位UP主在穿上蜘蛛侠COS服后被网友嘲笑的情况。
# txt = "老六是什么,起源于哪里?"
# >> 老六是网络流行语最初起源于游戏《CSGO》指游戏中玩家中独来独往、游离于队伍之外的“自由人”或玩得比较菜或者玩得比较阴险的人 ,后来逐渐演变成指玩得比较阴险的玩家。
# txt = "罗小黑战记因为什么经常被吐槽?"
# >> 3. 更新速度。罗小黑战记的更新时间不定,时而快时而慢,给观众留下了等待的时间过长的印象。
# txt = "沙特、伊朗最近的关系如何?"
# >> 最近在中国的斡旋下沙特和伊朗于3月10日达成了恢复两国外交关系的协议这表明两国关系已经重新回到正常化状态。
# txt = "You should have gone for the head. What does that mean?"
# >> The phrase "You should have gone for the head" is a quote from the Marvel movies, Avengers: Infinity War and Avengers: Endgame. It was spoken by the character Thanos in Infinity War and by Thor in Endgame.
txt = "AutoGPT是什么"
# >> AutoGPT是一个基于GPT-4语言模型的开源应用程序。它可以根据用户需求自主执行任务包括事件分析、营销方案撰写、代码编程、数学运算等等并完全不需要用户插手。它可以自己思考给出实现的步骤和实现细节甚至可以自问自答执 行任务。最近它在GitHub上爆火成为了业内最热门的项目之一。
# txt = "钟离带什么圣遗物?"
for cookies, cb, hist, msg in 连接网络回答问题(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
print("当前问答:", cb[-1][-1].replace("\n"," "))
for i, it in enumerate(cb): print亮蓝(it[0]); print亮黄(it[1])
# test_解析一个Python项目()
# test_Latex英文润色()
# test_Markdown中译英()
# test_批量翻译PDF文档()
# test_谷歌检索小助手()
# test_总结word文档()
# test_下载arxiv论文并翻译摘要()
# test_解析一个Cpp项目()
test_联网回答问题()
input("程序完成,回车退出。")
print("退出。")

View File

@@ -1,11 +1,12 @@
import traceback import traceback
from toolbox import update_ui, get_conf from toolbox import update_ui
def input_clipping(inputs, history, max_token_limit): def input_clipping(inputs, history, max_token_limit):
import tiktoken
import numpy as np import numpy as np
from request_llm.bridge_all import model_info from toolbox import get_conf
enc = model_info["gpt-3.5-turbo"]['tokenizer'] enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) def get_token_num(txt): return len(enc.encode(txt))
mode = 'input-and-history' mode = 'input-and-history'
# 当 输入部分的token占比 小于 全文的一半时,只裁剪历史 # 当 输入部分的token占比 小于 全文的一半时,只裁剪历史
@@ -22,7 +23,7 @@ def input_clipping(inputs, history, max_token_limit):
while n_token > max_token_limit: while n_token > max_token_limit:
where = np.argmax(everything_token) where = np.argmax(everything_token)
encoded = enc.encode(everything[where], disallowed_special=()) encoded = enc.encode(everything[where])
clipped_encoded = encoded[:len(encoded)-delta] clipped_encoded = encoded[:len(encoded)-delta]
everything[where] = enc.decode(clipped_encoded)[:-1] # -1 to remove the may-be illegal char everything[where] = enc.decode(clipped_encoded)[:-1] # -1 to remove the may-be illegal char
everything_token[where] = get_token_num(everything[where]) everything_token[where] = get_token_num(everything[where])
@@ -61,19 +62,17 @@ def request_gpt_model_in_new_thread_with_ui_alive(
""" """
import time import time
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from request_llm.bridge_all import predict_no_ui_long_connection from request_llm.bridge_chatgpt import predict_no_ui_long_connection
# 用户反馈 # 用户反馈
chatbot.append([inputs_show_user, ""]) chatbot.append([inputs_show_user, ""])
msg = '正常'
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
executor = ThreadPoolExecutor(max_workers=16) executor = ThreadPoolExecutor(max_workers=16)
mutable = ["", time.time(), ""] mutable = ["", time.time()]
def _req_gpt(inputs, history, sys_prompt): def _req_gpt(inputs, history, sys_prompt):
retry_op = retry_times_at_unknown_error retry_op = retry_times_at_unknown_error
exceeded_cnt = 0 exceeded_cnt = 0
while True: while True:
# watchdog error
if len(mutable) >= 2 and (time.time()-mutable[1]) > 5:
raise RuntimeError("检测到程序终止。")
try: try:
# 【第一种情况】:顺利完成 # 【第一种情况】:顺利完成
result = predict_no_ui_long_connection( result = predict_no_ui_long_connection(
@@ -100,20 +99,16 @@ def request_gpt_model_in_new_thread_with_ui_alive(
except: except:
# 【第三种情况】:其他错误:重试几次 # 【第三种情况】:其他错误:重试几次
tb_str = '```\n' + traceback.format_exc() + '```' tb_str = '```\n' + traceback.format_exc() + '```'
print(tb_str)
mutable[0] += f"[Local Message] 警告,在执行过程中遭遇问题, Traceback\n\n{tb_str}\n\n" mutable[0] += f"[Local Message] 警告,在执行过程中遭遇问题, Traceback\n\n{tb_str}\n\n"
if retry_op > 0: if retry_op > 0:
retry_op -= 1 retry_op -= 1
mutable[0] += f"[Local Message] 重试中,请稍等 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}\n\n" mutable[0] += f"[Local Message] 重试中 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}\n\n"
if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str):
time.sleep(30)
time.sleep(5) time.sleep(5)
continue # 返回重试 continue # 返回重试
else: else:
time.sleep(5) time.sleep(5)
return mutable[0] # 放弃 return mutable[0] # 放弃
# 提交任务
future = executor.submit(_req_gpt, inputs, history, sys_prompt) future = executor.submit(_req_gpt, inputs, history, sys_prompt)
while True: while True:
# yield一次以刷新前端页面 # yield一次以刷新前端页面
@@ -134,7 +129,7 @@ def request_gpt_model_in_new_thread_with_ui_alive(
def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
inputs_array, inputs_show_user_array, llm_kwargs, inputs_array, inputs_show_user_array, llm_kwargs,
chatbot, history_array, sys_prompt_array, chatbot, history_array, sys_prompt_array,
refresh_interval=0.2, max_workers=-1, scroller_max_len=30, refresh_interval=0.2, max_workers=10, scroller_max_len=30,
handle_token_exceed=True, show_user_at_complete=False, handle_token_exceed=True, show_user_at_complete=False,
retry_times_at_unknown_error=2, retry_times_at_unknown_error=2,
): ):
@@ -155,7 +150,7 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
history_array (list): List of chat history (历史对话输入,双层列表,第一层列表是子任务分解,第二层列表是对话历史) history_array (list): List of chat history (历史对话输入,双层列表,第一层列表是子任务分解,第二层列表是对话历史)
sys_prompt_array (list): List of system prompts 系统输入列表用于输入给GPT的前提提示比如你是翻译官怎样怎样 sys_prompt_array (list): List of system prompts 系统输入列表用于输入给GPT的前提提示比如你是翻译官怎样怎样
refresh_interval (float, optional): Refresh interval for UI (default: 0.2) 刷新时间间隔频率建议低于1不可高于3仅仅服务于视觉效果 refresh_interval (float, optional): Refresh interval for UI (default: 0.2) 刷新时间间隔频率建议低于1不可高于3仅仅服务于视觉效果
max_workers (int, optional): Maximum number of threads (default: see config.py) 最大线程数如果子任务非常多需要用此选项防止高频地请求openai导致错误 max_workers (int, optional): Maximum number of threads (default: 10) 最大线程数如果子任务非常多需要用此选项防止高频地请求openai导致错误
scroller_max_len (int, optional): Maximum length for scroller (default: 30)(数据流的显示最后收到的多少个字符,仅仅服务于视觉效果) scroller_max_len (int, optional): Maximum length for scroller (default: 30)(数据流的显示最后收到的多少个字符,仅仅服务于视觉效果)
handle_token_exceed (bool, optional): (是否在输入过长时,自动缩减文本) handle_token_exceed (bool, optional): (是否在输入过长时,自动缩减文本)
handle_token_exceed是否自动处理token溢出的情况如果选择自动处理则会在溢出时暴力截断默认开启 handle_token_exceed是否自动处理token溢出的情况如果选择自动处理则会在溢出时暴力截断默认开启
@@ -167,35 +162,24 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
""" """
import time, random import time, random
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from request_llm.bridge_all import predict_no_ui_long_connection from request_llm.bridge_chatgpt import predict_no_ui_long_connection
assert len(inputs_array) == len(history_array) assert len(inputs_array) == len(history_array)
assert len(inputs_array) == len(sys_prompt_array) assert len(inputs_array) == len(sys_prompt_array)
if max_workers == -1: # 读取配置文件
try: max_workers, = get_conf('DEFAULT_WORKER_NUM')
except: max_workers = 8
if max_workers <= 0 or max_workers >= 20: max_workers = 8
# 屏蔽掉 chatglm的多线程可能会导致严重卡顿
if not (llm_kwargs['llm_model'].startswith('gpt-') or llm_kwargs['llm_model'].startswith('api2d-')):
max_workers = 1
executor = ThreadPoolExecutor(max_workers=max_workers) executor = ThreadPoolExecutor(max_workers=max_workers)
n_frag = len(inputs_array) n_frag = len(inputs_array)
# 用户反馈 # 用户反馈
chatbot.append(["请开始多线程操作。", ""]) chatbot.append(["请开始多线程操作。", ""])
msg = '正常'
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
# 跨线程传递 # 异步原子
mutable = [["", time.time(), "等待中"] for _ in range(n_frag)] mutable = [["", time.time(), "等待中"] for _ in range(n_frag)]
# 子线程任务
def _req_gpt(index, inputs, history, sys_prompt): def _req_gpt(index, inputs, history, sys_prompt):
gpt_say = "" gpt_say = ""
retry_op = retry_times_at_unknown_error retry_op = retry_times_at_unknown_error
exceeded_cnt = 0 exceeded_cnt = 0
mutable[index][2] = "执行中" mutable[index][2] = "执行中"
while True: while True:
# watchdog error
if len(mutable[index]) >= 2 and (time.time()-mutable[index][1]) > 5:
raise RuntimeError("检测到程序终止。")
try: try:
# 【第一种情况】:顺利完成 # 【第一种情况】:顺利完成
# time.sleep(10); raise RuntimeError("测试") # time.sleep(10); raise RuntimeError("测试")
@@ -228,21 +212,13 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
except: except:
# 【第三种情况】:其他错误 # 【第三种情况】:其他错误
tb_str = '```\n' + traceback.format_exc() + '```' tb_str = '```\n' + traceback.format_exc() + '```'
print(tb_str)
gpt_say += f"[Local Message] 警告,线程{index}在执行过程中遭遇问题, Traceback\n\n{tb_str}\n\n" gpt_say += f"[Local Message] 警告,线程{index}在执行过程中遭遇问题, Traceback\n\n{tb_str}\n\n"
if len(mutable[index][0]) > 0: gpt_say += "此线程失败前收到的回答:\n\n" + mutable[index][0] if len(mutable[index][0]) > 0: gpt_say += "此线程失败前收到的回答:\n\n" + mutable[index][0]
if retry_op > 0: if retry_op > 0:
retry_op -= 1 retry_op -= 1
wait = random.randint(5, 20) wait = random.randint(5, 20)
if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str): for i in range(wait):# 也许等待十几秒后,情况会好转
wait = wait * 3 mutable[index][2] = f"等待重试 {wait-i}"; time.sleep(1)
fail_info = "OpenAI绑定信用卡可解除频率限制 "
else:
fail_info = ""
# 也许等待十几秒后,情况会好转
for i in range(wait):
mutable[index][2] = f"{fail_info}等待重试 {wait-i}"; time.sleep(1)
# 开始重试
mutable[index][2] = f"重试中 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}" mutable[index][2] = f"重试中 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}"
continue # 返回重试 continue # 返回重试
else: else:
@@ -265,6 +241,7 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
break break
# 更好的UI视觉效果 # 更好的UI视觉效果
observe_win = [] observe_win = []
# print([mutable[thread_index][2] for thread_index, _ in enumerate(worker_done)])
# 每个线程都要“喂狗”(看门狗) # 每个线程都要“喂狗”(看门狗)
for thread_index, _ in enumerate(worker_done): for thread_index, _ in enumerate(worker_done):
mutable[thread_index][1] = time.time() mutable[thread_index][1] = time.time()
@@ -274,30 +251,49 @@ def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
replace('\n', '').replace('```', '...').replace( replace('\n', '').replace('```', '...').replace(
' ', '.').replace('<br/>', '.....').replace('$', '.')+"`... ]" ' ', '.').replace('<br/>', '.....').replace('$', '.')+"`... ]"
observe_win.append(print_something_really_funny) observe_win.append(print_something_really_funny)
# 在前端打印些好玩的东西
stat_str = ''.join([f'`{mutable[thread_index][2]}`: {obs}\n\n' stat_str = ''.join([f'`{mutable[thread_index][2]}`: {obs}\n\n'
if not done else f'`{mutable[thread_index][2]}`\n\n' if not done else f'`{mutable[thread_index][2]}`\n\n'
for thread_index, done, obs in zip(range(len(worker_done)), worker_done, observe_win)]) for thread_index, done, obs in zip(range(len(worker_done)), worker_done, observe_win)])
# 在前端打印些好玩的东西
chatbot[-1] = [chatbot[-1][0], f'多线程操作已经开始,完成情况: \n\n{stat_str}' + ''.join(['.']*(cnt % 10+1))] chatbot[-1] = [chatbot[-1][0], f'多线程操作已经开始,完成情况: \n\n{stat_str}' + ''.join(['.']*(cnt % 10+1))]
msg = "正常"
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
# 异步任务结束 # 异步任务结束
gpt_response_collection = [] gpt_response_collection = []
for inputs_show_user, f in zip(inputs_show_user_array, futures): for inputs_show_user, f in zip(inputs_show_user_array, futures):
gpt_res = f.result() gpt_res = f.result()
gpt_response_collection.extend([inputs_show_user, gpt_res]) gpt_response_collection.extend([inputs_show_user, gpt_res])
# 是否在结束时,在界面上显示结果
if show_user_at_complete: if show_user_at_complete:
for inputs_show_user, f in zip(inputs_show_user_array, futures): for inputs_show_user, f in zip(inputs_show_user_array, futures):
gpt_res = f.result() gpt_res = f.result()
chatbot.append([inputs_show_user, gpt_res]) chatbot.append([inputs_show_user, gpt_res])
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面 yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
time.sleep(0.3) time.sleep(1)
return gpt_response_collection return gpt_response_collection
def WithRetry(f):
"""
装饰器函数,用于自动重试。
"""
def decorated(retry, res_when_fail, *args, **kwargs):
assert retry >= 0
while True:
try:
res = yield from f(*args, **kwargs)
return res
except:
retry -= 1
if retry<0:
print("达到最大重试次数")
break
else:
print("重试中……")
continue
return res_when_fail
return decorated
def breakdown_txt_to_satisfy_token_limit(txt, get_token_fn, limit): def breakdown_txt_to_satisfy_token_limit(txt, get_token_fn, limit):
def cut(txt_tocut, must_break_at_empty_line): # 递归 def cut(txt_tocut, must_break_at_empty_line): # 递归
if get_token_fn(txt_tocut) <= limit: if get_token_fn(txt_tocut) <= limit:
@@ -316,6 +312,7 @@ def breakdown_txt_to_satisfy_token_limit(txt, get_token_fn, limit):
if get_token_fn(prev) < limit: if get_token_fn(prev) < limit:
break break
if cnt == 0: if cnt == 0:
print('what the fuck ?')
raise RuntimeError("存在一行极长的文本!") raise RuntimeError("存在一行极长的文本!")
# print(len(post)) # print(len(post))
# 列表递归接龙 # 列表递归接龙
@@ -328,18 +325,8 @@ def breakdown_txt_to_satisfy_token_limit(txt, get_token_fn, limit):
return cut(txt, must_break_at_empty_line=False) return cut(txt, must_break_at_empty_line=False)
def force_breakdown(txt, limit, get_token_fn):
"""
当无法用标点、空行分割时,我们用最暴力的方法切割
"""
for i in reversed(range(len(txt))):
if get_token_fn(txt[:i]) < limit:
return txt[:i], txt[i:]
return "Tiktoken未知错误", "Tiktoken未知错误"
def breakdown_txt_to_satisfy_token_limit_for_pdf(txt, get_token_fn, limit): def breakdown_txt_to_satisfy_token_limit_for_pdf(txt, get_token_fn, limit):
# 递归 def cut(txt_tocut, must_break_at_empty_line): # 递归
def cut(txt_tocut, must_break_at_empty_line, break_anyway=False):
if get_token_fn(txt_tocut) <= limit: if get_token_fn(txt_tocut) <= limit:
return [txt_tocut] return [txt_tocut]
else: else:
@@ -351,40 +338,28 @@ def breakdown_txt_to_satisfy_token_limit_for_pdf(txt, get_token_fn, limit):
if must_break_at_empty_line: if must_break_at_empty_line:
if lines[cnt] != "": if lines[cnt] != "":
continue continue
print(cnt)
prev = "\n".join(lines[:cnt]) prev = "\n".join(lines[:cnt])
post = "\n".join(lines[cnt:]) post = "\n".join(lines[cnt:])
if get_token_fn(prev) < limit: if get_token_fn(prev) < limit:
break break
if cnt == 0: if cnt == 0:
if break_anyway: # print('what the fuck ? 存在一行极长的文本!')
prev, post = force_breakdown(txt_tocut, limit, get_token_fn) raise RuntimeError("存在一行极长的文本!")
else:
raise RuntimeError(f"存在一行极长的文本!{txt_tocut}")
# print(len(post)) # print(len(post))
# 列表递归接龙 # 列表递归接龙
result = [prev] result = [prev]
result.extend(cut(post, must_break_at_empty_line, break_anyway=break_anyway)) result.extend(cut(post, must_break_at_empty_line))
return result return result
try: try:
# 第1次尝试将双空行\n\n作为切分点
return cut(txt, must_break_at_empty_line=True) return cut(txt, must_break_at_empty_line=True)
except RuntimeError: except RuntimeError:
try: try:
# 第2次尝试将单空行\n作为切分点
return cut(txt, must_break_at_empty_line=False) return cut(txt, must_break_at_empty_line=False)
except RuntimeError: except RuntimeError:
try: # 这个中文的句号是故意的,作为一个标识而存在
# 第3次尝试将英文句号.)作为切分点 res = cut(txt.replace('.', '\n'), must_break_at_empty_line=False)
res = cut(txt.replace('.', '\n'), must_break_at_empty_line=False) # 这个中文的句号是故意的,作为一个标识而存在 return [r.replace('\n', '.') for r in res]
return [r.replace('\n', '.') for r in res]
except RuntimeError as e:
try:
# 第4次尝试将中文句号作为切分点
res = cut(txt.replace('', '。。\n'), must_break_at_empty_line=False)
return [r.replace('。。\n', '') for r in res]
except RuntimeError as e:
# 第5次尝试没办法了随便切一下敷衍吧
return cut(txt, must_break_at_empty_line=False, break_anyway=True)
@@ -412,15 +387,12 @@ def read_and_clean_pdf_text(fp):
import re import re
import numpy as np import numpy as np
from colorful import print亮黄, print亮绿 from colorful import print亮黄, print亮绿
fc = 0 # Index 0 文本 fc = 0
fs = 1 # Index 1 字体 fs = 1
fb = 2 # Index 2 框框 fb = 2
REMOVE_FOOT_NOTE = True # 是否丢弃掉 不是正文的内容 (比正文字体小,如参考文献、脚注、图注等) REMOVE_FOOT_NOTE = True
REMOVE_FOOT_FFSIZE_PERCENT = 0.95 # 小于正文的判定为不是正文有些文章的正文部分字体大小不是100%统一的,有肉眼不可见的小变化) REMOVE_FOOT_FFSIZE_PERCENT = 0.95
def primary_ffsize(l): def primary_ffsize(l):
"""
提取文本块主字体
"""
fsize_statiscs = {} fsize_statiscs = {}
for wtf in l['spans']: for wtf in l['spans']:
if wtf['size'] not in fsize_statiscs: fsize_statiscs[wtf['size']] = 0 if wtf['size'] not in fsize_statiscs: fsize_statiscs[wtf['size']] = 0
@@ -428,18 +400,14 @@ def read_and_clean_pdf_text(fp):
return max(fsize_statiscs, key=fsize_statiscs.get) return max(fsize_statiscs, key=fsize_statiscs.get)
def ffsize_same(a,b): def ffsize_same(a,b):
"""
提取字体大小是否近似相等
"""
return abs((a-b)/max(a,b)) < 0.02 return abs((a-b)/max(a,b)) < 0.02
# file_content = ""
with fitz.open(fp) as doc: with fitz.open(fp) as doc:
meta_txt = [] meta_txt = []
meta_font = [] meta_font = []
meta_line = [] meta_line = []
meta_span = [] meta_span = []
############################## <第 1 步,搜集初始信息> ##################################
for index, page in enumerate(doc): for index, page in enumerate(doc):
# file_content += page.get_text() # file_content += page.get_text()
text_areas = page.get_text("dict") # 获取页面上的文本信息 text_areas = page.get_text("dict") # 获取页面上的文本信息
@@ -448,7 +416,6 @@ def read_and_clean_pdf_text(fp):
pf = 998 pf = 998
for l in t['lines']: for l in t['lines']:
txt_line = "".join([wtf['text'] for wtf in l['spans']]) txt_line = "".join([wtf['text'] for wtf in l['spans']])
if len(txt_line) == 0: continue
pf = primary_ffsize(l) pf = primary_ffsize(l)
meta_line.append([txt_line, pf, l['bbox'], l]) meta_line.append([txt_line, pf, l['bbox'], l])
for wtf in l['spans']: # for l in t['lines']: for wtf in l['spans']: # for l in t['lines']:
@@ -462,8 +429,7 @@ def read_and_clean_pdf_text(fp):
if index == 0: if index == 0:
page_one_meta = [" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace( page_one_meta = [" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
'- ', '') for t in text_areas['blocks'] if 'lines' in t] '- ', '') for t in text_areas['blocks'] if 'lines' in t]
# 获取正文主字体
############################## <第 2 步,获取正文主字体> ##################################
fsize_statiscs = {} fsize_statiscs = {}
for span in meta_span: for span in meta_span:
if span[1] not in fsize_statiscs: fsize_statiscs[span[1]] = 0 if span[1] not in fsize_statiscs: fsize_statiscs[span[1]] = 0
@@ -472,7 +438,7 @@ def read_and_clean_pdf_text(fp):
if REMOVE_FOOT_NOTE: if REMOVE_FOOT_NOTE:
give_up_fize_threshold = main_fsize * REMOVE_FOOT_FFSIZE_PERCENT give_up_fize_threshold = main_fsize * REMOVE_FOOT_FFSIZE_PERCENT
############################## <第 3 步,切分和重新整合> ################################## # 切分和重新整合
mega_sec = [] mega_sec = []
sec = [] sec = []
for index, line in enumerate(meta_line): for index, line in enumerate(meta_line):
@@ -514,7 +480,6 @@ def read_and_clean_pdf_text(fp):
finals.append(final) finals.append(final)
meta_txt = finals meta_txt = finals
############################## <第 4 步,乱七八糟的后处理> ##################################
def 把字符太少的块清除为回车(meta_txt): def 把字符太少的块清除为回车(meta_txt):
for index, block_txt in enumerate(meta_txt): for index, block_txt in enumerate(meta_txt):
if len(block_txt) < 100: if len(block_txt) < 100:
@@ -558,9 +523,8 @@ def read_and_clean_pdf_text(fp):
# 换行 -> 双换行 # 换行 -> 双换行
meta_txt = meta_txt.replace('\n', '\n\n') meta_txt = meta_txt.replace('\n', '\n\n')
############################## <第 5 步,展示分割效果> ################################## for f in finals:
# for f in finals: print亮黄(f)
# print亮黄(f) print亮绿('***************************')
# print亮绿('***************************')
return meta_txt, page_one_meta return meta_txt, page_one_meta

View File

@@ -1,5 +1,5 @@
import threading import threading
from request_llm.bridge_all import predict_no_ui_long_connection from request_llm.bridge_chatgpt import predict_no_ui_long_connection
from toolbox import update_ui from toolbox import update_ui
from toolbox import CatchException, write_results_to_file, report_execption from toolbox import CatchException, write_results_to_file, report_execption
from .crazy_utils import breakdown_txt_to_satisfy_token_limit from .crazy_utils import breakdown_txt_to_satisfy_token_limit
@@ -59,9 +59,10 @@ def 全项目切换英文(txt, llm_kwargs, plugin_kwargs, chatbot, history, sys_
# 第5步Token限制下的截断与处理 # 第5步Token限制下的截断与处理
MAX_TOKEN = 3000 MAX_TOKEN = 3000
from request_llm.bridge_all import model_info import tiktoken
enc = model_info["gpt-3.5-turbo"]['tokenizer'] from toolbox import get_conf
def get_token_fn(txt): return len(enc.encode(txt, disallowed_special=())) enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
def get_token_fn(txt): return len(enc.encode(txt))
# 第6步任务函数 # 第6步任务函数

View File

@@ -8,6 +8,8 @@ def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot
import time, os import time, os
# pip install python-docx 用于docx格式跨平台 # pip install python-docx 用于docx格式跨平台
# pip install pywin32 用于doc格式仅支持Win平台 # pip install pywin32 用于doc格式仅支持Win平台
print('begin analysis on:', file_manifest)
for index, fp in enumerate(file_manifest): for index, fp in enumerate(file_manifest):
if fp.split(".")[-1] == "docx": if fp.split(".")[-1] == "docx":
from docx import Document from docx import Document
@@ -27,20 +29,18 @@ def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot
word.Quit() word.Quit()
print(file_content) print(file_content)
prefix = "接下来请你逐文件分析下面的论文文件," if index == 0 else ""
# private_upload里面的文件名在解压zip后容易出现乱码rar和7z格式正常故可以只分析文章内容不输入文件名 # private_upload里面的文件名在解压zip后容易出现乱码rar和7z格式正常故可以只分析文章内容不输入文件名
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf i_say = prefix + f'请对下面的文章片段用中英文做概述,文件名是{os.path.relpath(fp, project_folder)},' \
from request_llm.bridge_all import model_info f'文章内容是 ```{file_content}```'
max_token = model_info[llm_kwargs['llm_model']]['max_token'] i_say_show_user = prefix + f'[{index+1}/{len(file_manifest)}] 假设你是论文审稿专家,请对下面的文章片段做概述: {os.path.abspath(fp)}'
TOKEN_LIMIT_PER_FRAGMENT = max_token * 3 // 4 chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf( yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
txt=file_content,
get_token_fn=model_info[llm_kwargs['llm_model']]['token_cnt'], if not fast_debug:
limit=TOKEN_LIMIT_PER_FRAGMENT msg = '正常'
) # ** gpt request **
this_paper_history = []
for i, paper_frag in enumerate(paper_fragments):
i_say = f'请对下面的文章片段用中文做概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{paper_frag}```'
i_say_show_user = f'请对下面的文章片段做概述: {os.path.abspath(fp)}的第{i+1}/{len(paper_fragments)}个片段。'
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive( gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
inputs=i_say, inputs=i_say,
inputs_show_user=i_say_show_user, inputs_show_user=i_say_show_user,
@@ -48,34 +48,46 @@ def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot
chatbot=chatbot, chatbot=chatbot,
history=[], history=[],
sys_prompt="总结文章。" sys_prompt="总结文章。"
) ) # 带超时倒计时
chatbot[-1] = (i_say_show_user, gpt_say) chatbot[-1] = (i_say_show_user, gpt_say)
history.extend([i_say_show_user,gpt_say]) history.append(i_say_show_user)
this_paper_history.extend([i_say_show_user,gpt_say]) history.append(gpt_say)
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
if not fast_debug: time.sleep(2)
# 已经对该文章的所有片段总结完毕,如果文章被切分了, """
if len(paper_fragments) > 1: # 可按需启用
i_say = f"根据以上的对话,总结文章{os.path.abspath(fp)}的主要内容。" i_say = f'根据你上述的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一篇英文的。'
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive( chatbot.append((i_say, "[Local Message] waiting gpt response."))
inputs=i_say, yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
inputs_show_user=i_say,
llm_kwargs=llm_kwargs,
chatbot=chatbot,
history=this_paper_history,
sys_prompt="总结文章。"
)
history.extend([i_say,gpt_say])
this_paper_history.extend([i_say,gpt_say])
i_say = f'我想让你做一个论文写作导师。您的任务是使用人工智能工具(例如自然语言处理)提供有关如何改进其上述文章的反馈。' \
f'您还应该利用您在有效写作技巧方面的修辞知识和经验来建议作者可以更好地以书面形式表达他们的想法和想法的方法。' \
f'根据你之前的分析,提出建议'
chatbot.append((i_say, "[Local Message] waiting gpt response."))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
"""
if not fast_debug:
msg = '正常'
# ** gpt request **
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
inputs=i_say,
inputs_show_user=i_say,
llm_kwargs=llm_kwargs,
chatbot=chatbot,
history=history,
sys_prompt="总结文章。"
) # 带超时倒计时
chatbot[-1] = (i_say, gpt_say)
history.append(i_say)
history.append(gpt_say)
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
res = write_results_to_file(history) res = write_results_to_file(history)
chatbot.append(("完成了吗?", res)) chatbot.append(("完成了吗?", res))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
res = write_results_to_file(history)
chatbot.append(("所有文件都总结完成了吗?", res))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
@CatchException @CatchException
@@ -111,11 +123,11 @@ def 总结word文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_pr
return return
# 搜索需要处理的文件清单 # 搜索需要处理的文件清单
if txt.endswith('.docx') or txt.endswith('.doc'): file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.docx', recursive=True)] + \
file_manifest = [txt] [f for f in glob.glob(f'{project_folder}/**/*.doc', recursive=True)]
else: # [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.docx', recursive=True)] + \ # [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.doc', recursive=True)] # [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
# 如果没找到任何文件 # 如果没找到任何文件
if len(file_manifest) == 0: if len(file_manifest) == 0:

View File

@@ -1,161 +0,0 @@
from toolbox import update_ui
from toolbox import CatchException, report_execption, write_results_to_file
fast_debug = False
class PaperFileGroup():
def __init__(self):
self.file_paths = []
self.file_contents = []
self.sp_file_contents = []
self.sp_file_index = []
self.sp_file_tag = []
# count_token
from request_llm.bridge_all import model_info
enc = model_info["gpt-3.5-turbo"]['tokenizer']
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
self.get_token_num = get_token_num
def run_file_split(self, max_token_limit=1900):
"""
将长文本分离开来
"""
for index, file_content in enumerate(self.file_contents):
if self.get_token_num(file_content) < max_token_limit:
self.sp_file_contents.append(file_content)
self.sp_file_index.append(index)
self.sp_file_tag.append(self.file_paths[index])
else:
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit)
for j, segment in enumerate(segments):
self.sp_file_contents.append(segment)
self.sp_file_index.append(index)
self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.md")
print('Segmentation: done')
def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'):
import time, os, re
from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
# <-------- 读取Markdown文件删除其中的所有注释 ---------->
pfg = PaperFileGroup()
for index, fp in enumerate(file_manifest):
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
file_content = f.read()
# 记录删除注释后的文本
pfg.file_paths.append(fp)
pfg.file_contents.append(file_content)
# <-------- 拆分过长的Markdown文件 ---------->
pfg.run_file_split(max_token_limit=1500)
n_split = len(pfg.sp_file_contents)
# <-------- 多线程润色开始 ---------->
if language == 'en->zh':
inputs_array = ["This is a Markdown file, translate it into Chinese, do not modify any existing Markdown commands:" +
f"\n\n{frag}" for frag in pfg.sp_file_contents]
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
elif language == 'zh->en':
inputs_array = [f"This is a Markdown file, translate it into English, do not modify any existing Markdown commands:" +
f"\n\n{frag}" for frag in pfg.sp_file_contents]
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
inputs_array=inputs_array,
inputs_show_user_array=inputs_show_user_array,
llm_kwargs=llm_kwargs,
chatbot=chatbot,
history_array=[[""] for _ in range(n_split)],
sys_prompt_array=sys_prompt_array,
# max_workers=5, # OpenAI所允许的最大并行过载
scroller_max_len = 80
)
# <-------- 整理结果,退出 ---------->
create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md"
res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name)
history = gpt_response_collection
chatbot.append((f"{fp}完成了吗?", res))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
@CatchException
def Markdown英译中(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
# 基本信息:功能、贡献者
chatbot.append([
"函数插件功能?",
"对整个Markdown项目进行翻译。函数插件贡献者: Binary-Husky"])
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
# 尝试导入依赖,如果缺少依赖,则给出安装建议
try:
import tiktoken
except:
report_execption(chatbot, history,
a=f"解析项目: {txt}",
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
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 from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.md', recursive=True)]
if len(file_manifest) == 0:
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.md文件: {txt}")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en->zh')
@CatchException
def Markdown中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
# 基本信息:功能、贡献者
chatbot.append([
"函数插件功能?",
"对整个Markdown项目进行翻译。函数插件贡献者: Binary-Husky"])
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
# 尝试导入依赖,如果缺少依赖,则给出安装建议
try:
import tiktoken
except:
report_execption(chatbot, history,
a=f"解析项目: {txt}",
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
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 from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
if txt.endswith('.md'):
file_manifest = [txt]
else:
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.md', recursive=True)]
if len(file_manifest) == 0:
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.md文件: {txt}")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh->en')

View File

@@ -13,7 +13,7 @@ def 批量翻译PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, sys_
# 基本信息:功能、贡献者 # 基本信息:功能、贡献者
chatbot.append([ chatbot.append([
"函数插件功能?", "函数插件功能?",
"批量翻译PDF文档。函数插件贡献者: Binary-Husky"]) "批量总结PDF文档。函数插件贡献者: Binary-Husky"])
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
# 尝试导入依赖,如果缺少依赖,则给出安装建议 # 尝试导入依赖,如果缺少依赖,则给出安装建议
@@ -59,7 +59,7 @@ def 批量翻译PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, sys_
def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, sys_prompt): def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, sys_prompt):
import os import os
import tiktoken import tiktoken
TOKEN_LIMIT_PER_FRAGMENT = 1280 TOKEN_LIMIT_PER_FRAGMENT = 1600
generated_conclusion_files = [] generated_conclusion_files = []
for index, fp in enumerate(file_manifest): for index, fp in enumerate(file_manifest):
@@ -68,9 +68,9 @@ def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot,
# 递归地切割PDF文件 # 递归地切割PDF文件
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
from request_llm.bridge_all import model_info from toolbox import get_conf
enc = model_info["gpt-3.5-turbo"]['tokenizer'] enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) def get_token_num(txt): return len(enc.encode(txt))
paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf( paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT) txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
page_one_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf( page_one_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
@@ -91,14 +91,14 @@ def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot,
# 多线,翻译 # 多线,翻译
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
inputs_array=[ inputs_array=[
f"你需要翻译以下内容\n{frag}" for frag in paper_fragments], f"以下是你需要翻译的论文片段\n{frag}" for frag in paper_fragments],
inputs_show_user_array=[f"\n---\n 原文: \n\n {frag.replace('#', '')} \n---\n 翻译:\n " for frag in paper_fragments], inputs_show_user_array=[f"\n---\n 原文: \n\n {frag.replace('#', '')} \n---\n 翻译:\n " for frag in paper_fragments],
llm_kwargs=llm_kwargs, llm_kwargs=llm_kwargs,
chatbot=chatbot, chatbot=chatbot,
history_array=[[paper_meta] for _ in paper_fragments], history_array=[[paper_meta] for _ in paper_fragments],
sys_prompt_array=[ sys_prompt_array=[
"请你作为一个学术翻译,负责把学术论文准确翻译成中文。注意文章中的每一句话都要翻译。" for _ in paper_fragments], "请你作为一个学术翻译,负责把学术论文的片段准确翻译成中文。" for _ in paper_fragments],
# max_workers=5 # OpenAI所允许的最大并行过载 max_workers=16 # OpenAI所允许的最大并行过载
) )
# 整理报告的格式 # 整理报告的格式

View File

@@ -8,18 +8,17 @@ fast_debug = False
def 解析PDF(file_name, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt): def 解析PDF(file_name, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt):
import tiktoken import tiktoken
print('begin analysis on:', file_name) print('begin analysis on:', file_name)
file_content, page_one = read_and_clean_pdf_text(file_name)
############################## <第 0 步切割PDF> ################################## ############################## <第零步从摘要中提取高价值信息放到history中> ##################################
# 递归地切割PDF文件每一块尽量是完整的一个section比如introductionexperiment等必要时再进行切割 # 递归地切割PDF文件每一块尽量是完整的一个section比如introductionexperiment等必要时再进行切割
# 的长度必须小于 2500 个 Token # 的长度必须小于 2500 个 Token
file_content, page_one = read_and_clean_pdf_text(file_name) # 尝试按照章节切割PDF
TOKEN_LIMIT_PER_FRAGMENT = 2500 TOKEN_LIMIT_PER_FRAGMENT = 2500
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
from request_llm.bridge_all import model_info from toolbox import get_conf
enc = model_info["gpt-3.5-turbo"]['tokenizer'] enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=())) def get_token_num(txt): return len(enc.encode(txt))
paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf( paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT) txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
page_one_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf( page_one_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
@@ -27,11 +26,11 @@ def 解析PDF(file_name, llm_kwargs, plugin_kwargs, chatbot, history, system_pro
# 为了更好的效果我们剥离Introduction之后的部分如果有 # 为了更好的效果我们剥离Introduction之后的部分如果有
paper_meta = page_one_fragments[0].split('introduction')[0].split('Introduction')[0].split('INTRODUCTION')[0] paper_meta = page_one_fragments[0].split('introduction')[0].split('Introduction')[0].split('INTRODUCTION')[0]
############################## <第 1 从摘要中提取高价值信息放到history中> ################################## ############################## <第从摘要中提取高价值信息放到history中> ##################################
final_results = [] final_results = []
final_results.append(paper_meta) final_results.append(paper_meta)
############################## <第 2 步,迭代地历遍整个文章,提取精炼信息> ################################## ############################## <第步,迭代地历遍整个文章,提取精炼信息> ##################################
i_say_show_user = f'首先你在英文语境下通读整篇论文。'; gpt_say = "[Local Message] 收到。" # 用户提示 i_say_show_user = f'首先你在英文语境下通读整篇论文。'; gpt_say = "[Local Message] 收到。" # 用户提示
chatbot.append([i_say_show_user, gpt_say]); yield from update_ui(chatbot=chatbot, history=[]) # 更新UI chatbot.append([i_say_show_user, gpt_say]); yield from update_ui(chatbot=chatbot, history=[]) # 更新UI
@@ -52,14 +51,14 @@ def 解析PDF(file_name, llm_kwargs, plugin_kwargs, chatbot, history, system_pro
iteration_results.append(gpt_say) iteration_results.append(gpt_say)
last_iteration_result = gpt_say last_iteration_result = gpt_say
############################## <第 3 整理history> ################################## ############################## <第整理history> ##################################
final_results.extend(iteration_results) final_results.extend(iteration_results)
final_results.append(f'接下来,你是一名专业的学术教授,利用以上信息,使用中文回答我的问题。') final_results.append(f'接下来,你是一名专业的学术教授,利用以上信息,使用中文回答我的问题。')
# 接下来两句话只显示在界面上,不起实际作用 # 接下来两句话只显示在界面上,不起实际作用
i_say_show_user = f'接下来,你是一名专业的学术教授,利用以上信息,使用中文回答我的问题。'; gpt_say = "[Local Message] 收到。" i_say_show_user = f'接下来,你是一名专业的学术教授,利用以上信息,使用中文回答我的问题。'; gpt_say = "[Local Message] 收到。"
chatbot.append([i_say_show_user, gpt_say]) chatbot.append([i_say_show_user, gpt_say])
############################## <第 4 设置一个token上限防止回答时Token溢出> ################################## ############################## <第设置一个token上限防止回答时Token溢出> ##################################
from .crazy_utils import input_clipping from .crazy_utils import input_clipping
_, final_results = input_clipping("", final_results, max_token_limit=3200) _, final_results = input_clipping("", final_results, max_token_limit=3200)
yield from update_ui(chatbot=chatbot, history=final_results) # 注意这里的历史记录被替代了 yield from update_ui(chatbot=chatbot, history=final_results) # 注意这里的历史记录被替代了

View File

@@ -1,102 +0,0 @@
from toolbox import CatchException, update_ui
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive, input_clipping
import requests
from bs4 import BeautifulSoup
from request_llm.bridge_all import model_info
def google(query, proxies):
query = query # 在此处替换您要搜索的关键词
url = f"https://www.google.com/search?q={query}"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'}
response = requests.get(url, headers=headers, proxies=proxies)
soup = BeautifulSoup(response.content, 'html.parser')
results = []
for g in soup.find_all('div', class_='g'):
anchors = g.find_all('a')
if anchors:
link = anchors[0]['href']
if link.startswith('/url?q='):
link = link[7:]
if not link.startswith('http'):
continue
title = g.find('h3').text
item = {'title': title, 'link': link}
results.append(item)
for r in results:
print(r['link'])
return results
def scrape_text(url, proxies) -> str:
"""Scrape text from a webpage
Args:
url (str): The URL to scrape text from
Returns:
str: The scraped text
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36',
'Content-Type': 'text/plain',
}
try:
response = requests.get(url, headers=headers, proxies=proxies, timeout=8)
if response.encoding == "ISO-8859-1": response.encoding = response.apparent_encoding
except:
return "无法连接到该网页"
soup = BeautifulSoup(response.text, "html.parser")
for script in soup(["script", "style"]):
script.extract()
text = soup.get_text()
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = "\n".join(chunk for chunk in chunks if chunk)
return text
@CatchException
def 连接网络回答问题(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
"""
txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径
llm_kwargs gpt模型参数如温度和top_p等一般原样传递下去就行
plugin_kwargs 插件模型的参数,暂时没有用武之地
chatbot 聊天显示框的句柄,用于显示给用户
history 聊天历史,前情提要
system_prompt 给gpt的静默提醒
web_port 当前软件运行的端口号
"""
history = [] # 清空历史,以免输入溢出
chatbot.append((f"请结合互联网信息回答以下问题:{txt}",
"[Local Message] 请注意,您正在调用一个[函数插件]的模板该模板可以实现ChatGPT联网信息综合。该函数面向希望实现更多有趣功能的开发者它可以作为创建新功能函数的模板。您若希望分享新的功能模组请不吝PR"))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间我们先及时地做一次界面更新
# ------------- < 第1步爬取搜索引擎的结果 > -------------
from toolbox import get_conf
proxies, = get_conf('proxies')
urls = google(txt, proxies)
history = []
# ------------- < 第2步依次访问网页 > -------------
max_search_result = 5 # 最多收纳多少个网页的结果
for index, url in enumerate(urls[:max_search_result]):
res = scrape_text(url['link'], proxies)
history.extend([f"{index}份搜索结果:", res])
chatbot.append([f"{index}份搜索结果:", res[:500]+"......"])
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间我们先及时地做一次界面更新
# ------------- < 第3步ChatGPT综合 > -------------
i_say = f"从以上搜索结果中抽取信息,然后回答问题:{txt}"
i_say, history = input_clipping( # 裁剪输入从最长的条目开始裁剪防止爆token
inputs=i_say,
history=history,
max_token_limit=model_info[llm_kwargs['llm_model']]['max_token']*3//4
)
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
inputs=i_say, inputs_show_user=i_say,
llm_kwargs=llm_kwargs, chatbot=chatbot, history=history,
sys_prompt="请从给定的若干条搜索结果中抽取信息,对最相关的两个搜索结果进行总结,然后回答问题。"
)
chatbot[-1] = (i_say, gpt_say)
history.append(i_say);history.append(gpt_say)
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新

View File

@@ -11,11 +11,9 @@ def 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs,
history_array = [] history_array = []
sys_prompt_array = [] sys_prompt_array = []
report_part_1 = [] report_part_1 = []
assert len(file_manifest) <= 512, "源文件太多超过512个, 请缩减输入文件的数量。或者您也可以选择删除此行警告并修改代码拆分file_manifest列表从而实现分批次处理。"
############################## <第一步,逐个文件分析,多线程> ################################## ############################## <第一步,逐个文件分析,多线程> ##################################
for index, fp in enumerate(file_manifest): for index, fp in enumerate(file_manifest):
# 读取文件
with open(fp, 'r', encoding='utf-8', errors='replace') as f: with open(fp, 'r', encoding='utf-8', errors='replace') as f:
file_content = f.read() file_content = f.read()
prefix = "接下来请你逐文件分析下面的工程" if index==0 else "" prefix = "接下来请你逐文件分析下面的工程" if index==0 else ""
@@ -27,7 +25,6 @@ def 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs,
history_array.append([]) history_array.append([])
sys_prompt_array.append("你是一个程序架构分析师,正在分析一个源代码项目。你的回答必须简单明了。") sys_prompt_array.append("你是一个程序架构分析师,正在分析一个源代码项目。你的回答必须简单明了。")
# 文件读取完成对每一个源代码文件生成一个请求线程发送到chatgpt进行分析
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency( gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
inputs_array = inputs_array, inputs_array = inputs_array,
inputs_show_user_array = inputs_show_user_array, inputs_show_user_array = inputs_show_user_array,
@@ -38,13 +35,28 @@ def 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs,
show_user_at_complete = True show_user_at_complete = True
) )
# 全部文件解析完成,结果写入文件,准备对工程源代码进行汇总分析
report_part_1 = copy.deepcopy(gpt_response_collection) report_part_1 = copy.deepcopy(gpt_response_collection)
history_to_return = report_part_1 history_to_return = report_part_1
res = write_results_to_file(report_part_1) res = write_results_to_file(report_part_1)
chatbot.append(("完成?", "逐个文件分析已完成。" + res + "\n\n正在开始汇总。")) chatbot.append(("完成?", "逐个文件分析已完成。" + res + "\n\n正在开始汇总。"))
yield from update_ui(chatbot=chatbot, history=history_to_return) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history_to_return) # 刷新界面
############################## <存储中间数据进行调试> ##################################
# def objdump(obj):
# import pickle
# with open('objdump.tmp', 'wb+') as f:
# pickle.dump(obj, f)
# return
# def objload():
# import pickle, os
# if not os.path.exists('objdump.tmp'):
# return
# with open('objdump.tmp', 'rb') as f:
# return pickle.load(f)
# objdump([report_part_1, gpt_response_collection, history_to_return, file_manifest, project_folder, fp, llm_kwargs, chatbot])
############################## <第二步,综合,单线程,分组+迭代处理> ################################## ############################## <第二步,综合,单线程,分组+迭代处理> ##################################
batchsize = 16 # 10个文件为一组 batchsize = 16 # 10个文件为一组
report_part_2 = [] report_part_2 = []
@@ -213,54 +225,9 @@ def 解析一个Golang项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, s
report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到本地项目或无权访问: {txt}") report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到本地项目或无权访问: {txt}")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return return
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.go', recursive=True)] + \ file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.go', recursive=True)]
[f for f in glob.glob(f'{project_folder}/**/go.mod', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/go.sum', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/go.work', recursive=True)]
if len(file_manifest) == 0: if len(file_manifest) == 0:
report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到任何golang文件: {txt}") report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到任何golang文件: {txt}")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return return
yield from 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt) yield from 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)
@CatchException
def 解析一个Lua项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, 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 from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.lua', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.xml', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.json', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.toml', recursive=True)]
if len(file_manifest) == 0:
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何lua文件: {txt}")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
yield from 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)
@CatchException
def 解析一个CSharp项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, 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 from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.cs', recursive=True)] + \
[f for f in glob.glob(f'{project_folder}/**/*.csproj', recursive=True)]
if len(file_manifest) == 0:
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何CSharp文件: {txt}")
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
return
yield from 解析源代码新(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)

View File

@@ -1,30 +0,0 @@
from toolbox import CatchException, update_ui
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
import datetime
@CatchException
def 同时问询(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
"""
txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径
llm_kwargs gpt模型参数如温度和top_p等一般原样传递下去就行
plugin_kwargs 插件模型的参数如温度和top_p等一般原样传递下去就行
chatbot 聊天显示框的句柄,用于显示给用户
history 聊天历史,前情提要
system_prompt 给gpt的静默提醒
web_port 当前软件运行的端口号
"""
history = [] # 清空历史,以免输入溢出
chatbot.append((txt, "正在同时咨询ChatGPT和ChatGLM……"))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间我们先及时地做一次界面更新
# llm_kwargs['llm_model'] = 'chatglm&gpt-3.5-turbo&api2d-gpt-3.5-turbo' # 支持任意数量的llm接口用&符号分隔
llm_kwargs['llm_model'] = 'chatglm&gpt-3.5-turbo' # 支持任意数量的llm接口用&符号分隔
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
inputs=txt, inputs_show_user=txt,
llm_kwargs=llm_kwargs, chatbot=chatbot, history=history,
sys_prompt=system_prompt,
retry_times_at_unknown_error=0
)
history.append(txt)
history.append(gpt_say)
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新

View File

@@ -6,7 +6,7 @@ def 高阶功能模板函数(txt, llm_kwargs, plugin_kwargs, chatbot, history, s
""" """
txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径 txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径
llm_kwargs gpt模型参数如温度和top_p等一般原样传递下去就行 llm_kwargs gpt模型参数如温度和top_p等一般原样传递下去就行
plugin_kwargs 插件模型的参数,暂时没有用武之地 plugin_kwargs 插件模型的参数,如温度和top_p等一般原样传递下去就行
chatbot 聊天显示框的句柄,用于显示给用户 chatbot 聊天显示框的句柄,用于显示给用户
history 聊天历史,前情提要 history 聊天历史,前情提要
system_prompt 给gpt的静默提醒 system_prompt 给gpt的静默提醒
@@ -26,4 +26,4 @@ def 高阶功能模板函数(txt, llm_kwargs, plugin_kwargs, chatbot, history, s
) )
chatbot[-1] = (i_say, gpt_say) chatbot[-1] = (i_say, gpt_say)
history.append(i_say);history.append(gpt_say) history.append(i_say);history.append(gpt_say)
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新

View File

@@ -1,291 +0,0 @@
> **Note**
>
> This English README is automatically generated by the markdown translation plugin in this project, and may not be 100% correct.
>
# <img src="logo.png" width="40" > ChatGPT Academic Optimization
**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.**
> **Note**
>
> 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**!
>
> 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.
>
<div align="center">
Function | Description
--- | ---
One-Click Polish | Supports one-click polishing and finding grammar errors in academic papers.
One-Key Translation Between Chinese and English | One-click translation between Chinese and English.
One-Key Code Interpretation | Can correctly display and interpret code.
[Custom Shortcut Keys](https://www.bilibili.com/video/BV14s4y1E7jN) | Supports custom shortcut keys.
[Configure Proxy Server](https://www.bilibili.com/video/BV1rc411W7Dr) | Supports configuring proxy servers.
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).
[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.
[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
Read the Paper | [Function Plugin] One-click interpretation of the full text of latex paper and generation of abstracts
Latex Full Text Translation, Proofreading | [Function Plugin] One-click translation or proofreading of latex papers.
Batch Comment Generation | [Function Plugin] One-click batch generation of function comments
Chat Analysis Report Generation | [Function Plugin] After running, an automatic summary report will be generated
[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
[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)
[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.
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
Multithreaded Function Plugin Support | Supports multi-threaded calling chatgpt, one-click processing of massive text or programs
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
[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)!
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)
... | ...
</div>
- New interface (switch between "left-right layout" and "up-down layout" by modifying the LAYOUT option in config.py)
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
</div>
- All buttons are dynamically generated by reading functional.py and can add custom functionality at will, freeing up clipboard
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
</div>
- Proofreading / correcting
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
</div>
- 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
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
</div>
- Don't want to read the project code? Just take the whole project to chatgpt
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
</div>
- Multiple major language model mixing calls (ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
</div>
Multiple major language model mixing call [huggingface beta version](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta) (the huggingface version does not support chatglm)
---
## Installation-Method 1: Run directly (Windows, Linux or MacOS)
1. Download project
```sh
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
```
2. Configure API_KEY and proxy settings
In `config.py`, configure the overseas Proxy and OpenAI API KEY as follows:
```
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).
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.
3. Issues related to proxy networks (network timeouts, proxy failures) are summarized at https://github.com/binary-husky/chatgpt_academic/issues/1
```
(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.))
3. Install dependencies
```sh
# (Option One) Recommended
python -m pip install -r requirements.txt
# (Option Two) If you use anaconda, the steps are similar:
# (Option Two.1) conda create -n gptac_venv python=3.11
# (Option Two.2) conda activate gptac_venv
# (Option Two.3) python -m pip install -r requirements.txt
# 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:
# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
```
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):
```sh
python -m pip install -r request_llm/requirements_chatglm.txt
```
4. Run
```sh
python main.py
```
5. Test function plugins
```
- Test Python project analysis
In the input area, enter `./crazy_functions/test_project/python/dqn`, and then click "Analyze the entire Python project"
- Test self-code interpretation
Click "[Multithreading Demo] Interpretation of This Project Itself (Source Code Interpretation)"
- 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.
Click "[Function Plugin Template Demo] Today in History"
- There are more functions to choose from in the function plugin area drop-down menu.
```
## Installation-Method 2: Use Docker (Linux)
1. ChatGPT only (recommended for most people)
``` sh
# download project
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
# configure overseas Proxy and OpenAI API KEY
Edit config.py with any text editor
# Install
docker build -t gpt-academic .
# Run
docker run --rm -it --net=host gpt-academic
# Test function plug-in
## 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.
Click "[Function Plugin Template Demo] Today in History"
## Test Abstract Writing for Latex Projects
Enter ./crazy_functions/test_project/latex/attention in the input area, and then click "Read Tex Paper and Write Abstract"
## Test Python Project Analysis
Enter ./crazy_functions/test_project/python/dqn in the input area and click "Analyze the entire Python project."
More functions are available in the function plugin area drop-down menu.
```
2. ChatGPT+ChatGLM (requires strong familiarity with docker + strong computer configuration)
``` sh
# Modify dockerfile
cd docs && nano Dockerfile+ChatGLM
# How to build | 如何构建 Dockerfile+ChatGLM在docs路径下请先cd docs
docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
# How to run | 如何运行 (1) 直接运行:
docker run --rm -it --net=host --gpus=all gpt-academic
# How to run | 如何运行 (2) 我想运行之前进容器做一些调整:
docker run --rm -it --net=host --gpus=all gpt-academic bash
```
## Installation-Method 3: Other Deployment Methods
1. Remote Cloud Server Deployment
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)
2. Use WSL2 (Windows Subsystem for Linux)
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)
## Installation-Proxy Configuration
### Method 1: Conventional method
[Configure Proxy](https://github.com/binary-husky/chatgpt_academic/issues/1)
### Method Two: Step-by-step tutorial for newcomers
[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)
---
## Customizing Convenient Buttons (Customizing Academic Shortcuts)
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:
```
"Super English to Chinese translation": {
# Prefix, which will be added before your input. For example, to describe your requirements, such as translation, code interpretation, polishing, etc.
"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",
# Suffix, which will be added after your input. For example, combined with the prefix, you can put your input content in quotes.
"Suffix": "",
},
```
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
</div>
---
## Some Function Displays
### Image Display:
You are a professional academic paper translator.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
</div>
### If a program can understand and analyze itself:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
</div>
### Analysis of any Python/Cpp project:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
</div>
### One-click reading comprehension and summary generation of Latex papers
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
</div>
### Automatic report generation
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
</div>
### Modular functional design
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
</div>
### Source code translation to English
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
</div>
## Todo and version planning:
- version 3.2+ (todo): Function plugin supports more parameter interfaces
- version 3.1: Support for inquiring multiple GPT models at the same time! Support for api2d, support for multiple apikeys load balancing
- version 3.0: Support for chatglm and other small llms
- version 2.6: Refactored the plugin structure, improved interactivity, added more plugins
- version 2.5: Self-updating, solves the problem of text being too long and token overflowing when summarizing large project source code
- 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.
- version 2.3: Enhanced multi-threaded interactivity
- version 2.2: Function plugin supports hot reloading
- version 2.1: Foldable layout
- version 2.0: Introduction of modular function plugins
- version 1.0: Basic functions
## Reference and learning
```
The code design of this project has referenced many other excellent projects, including:
# Reference project 1: Borrowed many tips from ChuanhuChatGPT
https://github.com/GaiZhenbiao/ChuanhuChatGPT
# Reference project 2: Tsinghua ChatGLM-6B:
https://github.com/THUDM/ChatGLM-6B
```

View File

@@ -1,296 +0,0 @@
> **Note**
>
> 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%.
>
# <img src="logo.png" width="40" > ChatGPT Optimisation Académique
**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.**
> **Note**
>
> 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!
>
> 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).
>
<div align="center">
Fonctionnalité | Description
--- | ---
Polissage en un clic | Prend en charge la correction en un clic et la recherche d'erreurs de syntaxe dans les documents de recherche.
Traduction Chinois-Anglais en un clic | Une touche pour traduire la partie chinoise en anglais ou celle anglaise en chinois.
Explication de code en un clic | Affiche et explique correctement le code.
[Raccourcis clavier personnalisables](https://www.bilibili.com/video/BV14s4y1E7jN) | Prend en charge les raccourcis clavier personnalisables.
[Configuration du serveur proxy](https://www.bilibili.com/video/BV1rc411W7Dr) | Prend en charge la configuration du serveur proxy.
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).
[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.
[Analyse de programme](https://www.bilibili.com/video/BV1cj411A7VW) | [Plugins] En un clic, les projets Python/C/C++/Java/Lua/... peuvent être analysés.
Lire le document de recherche | [Plugins] Lisez le résumé de l'article en latex et générer un résumé.
Traduction et polissage de l'article complet en LaTeX | [Plugins] Une touche pour traduire ou corriger en LaTeX
Génération Commentaire de fonction en vrac | [Plugins] Lisez en un clic les fonctions et générez des commentaires de fonction.
Rapport d'analyse automatique des chats générés | [Plugins] Génère un rapport de synthèse après l'exécution.
[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
[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)
[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
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
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
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
[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?
Expérience en ligne d'huggingface sans science | Après vous être connecté à huggingface, copiez [cet espace](https://huggingface.co/spaces/qingxu98/gpt-academic)
... | ...
</div>
Vous êtes un traducteur professionnel d'articles universitaires en français.
Ceci est un fichier Markdown, veuillez le traduire en français sans modifier les commandes Markdown existantes :
- 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)
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
</div>
- 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.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
</div>
- Correction/amélioration
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
</div>
- 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.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
</div>
- Pas envie de lire le code du projet ? Faites votre propre démo avec ChatGPT.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
</div>
- Utilisation combinée de plusieurs modèles de langage sophistiqués (ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
</div>
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).
---
## Installation - Méthode 1 : Exécution directe (Windows, Linux or MacOS)
1. Téléchargez le projet
```sh
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
```
2. Configuration de l'API_KEY et des paramètres de proxy
Dans `config.py`, configurez les paramètres de proxy et de clé d'API OpenAI, comme indiqué ci-dessous
```
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).
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.
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.
```
(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.)
3. Installation des dépendances
```sh
# (Option 1) Recommandé
python -m pip install -r requirements.txt
# (Option 2) Si vous utilisez anaconda, les étapes sont similaires :
# (Option 2.1) conda create -n gptac_venv python=3.11
# (Option 2.2) conda activate gptac_venv
# (Option 2.3) python -m pip install -r requirements.txt
# 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 :
# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
```
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) :
```sh
python -m pip install -r request_llm/requirements_chatglm.txt
```
4. Exécution
```sh
python main.py
```
5. Tester les plugins de fonctions
```
- Test Python Project Analysis
Dans la zone de saisie, entrez `./crazy_functions/test_project/python/dqn`, puis cliquez sur "Parse Entire Python Project"
- Test d'auto-lecture du code
Cliquez sur "[Démo multi-thread] Parser ce projet lui-même (auto-traduction de la source)"
- 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.
Cliquez sur "[Démo modèle de plugin de fonction] Histoire du Jour"
- Le menu déroulant de la zone de plugin de fonctionnalité contient plus de fonctionnalités à sélectionner.
```
## Installation - Méthode 2 : Utilisation de docker (Linux)
Vous êtes un traducteur professionnel d'articles académiques en français.
1. ChatGPT seul (recommandé pour la plupart des gens)
``` sh
# Télécharger le projet
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
# Configurer le proxy outre-mer et la clé API OpenAI
Modifier le fichier config.py avec n'importe quel éditeur de texte
# Installer
docker build -t gpt-academic .
# Exécuter
docker run --rm -it --net=host gpt-academic
# Tester les modules de fonction
## 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.
Cliquez sur "[Exemple de modèle de module] Histoire d'aujourd'hui"
## Tester le résumé écrit pour le projet LaTeX
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"
## Tester l'analyse du projet Python
Dans la zone de saisie, tapez ./crazy_functions/test_project/python/dqn, puis cliquez sur "Analyser l'ensemble du projet Python"
D'autres fonctions sont disponibles dans la liste déroulante des modules de fonction.
```
2. ChatGPT+ChatGLM (nécessite une grande connaissance de docker et une configuration informatique suffisamment puissante)
``` sh
# Modifier le dockerfile
cd docs && nano Dockerfile+ChatGLM
# Comment construire | 如何构建 Dockerfile+ChatGLM在docs路径下请先cd docs
docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
# Comment exécuter | 如何运行 (1) Directement exécuter :
docker run --rm -it --net=host --gpus=all gpt-academic
# Comment exécuter | 如何运行 (2) Je veux effectuer quelques ajustements dans le conteneur avant de lancer :
docker run --rm -it --net=host --gpus=all gpt-academic bash
```
## Installation - Méthode 3 : Autres méthodes de déploiement
1. Déploiement sur un cloud serveur distant
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)
2. Utilisation de WSL2 (Windows Subsystem for Linux)
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)
## Configuration de la procuration de l'installation
### Méthode 1 : Méthode conventionnelle
[Configuration de la procuration](https://github.com/binary-husky/chatgpt_academic/issues/1)
### Méthode 2 : Tutoriel pour débutant pur
[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)
---
## Personnalisation des nouveaux boutons pratiques (personnalisation des raccourcis académiques)
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.)
Par exemple:
```
"Traduction Français-Chinois": {
# 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.
"Prefix": "Veuillez traduire le contenu ci-dessous en chinois, puis expliquer chaque terme propre mentionné dans un tableau Markdown :\n\n",
# 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.
"Suffix": "",
},
```
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
</div>
---
## Présentation de certaines fonctionnalités
### Affichage des images:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
</div>
### Si un programme peut comprendre et décomposer lui-même :
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
</div>
### Analyse de tout projet Python/Cpp quelconque :
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
</div>
### Lecture et résumé générés automatiquement pour les articles en Latex
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
</div>
### Génération de rapports automatique
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
</div>
### Conception de fonctionnalités modulaires
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
</div>
### Traduction de code source en anglais
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
</div>
## À faire et planification de version :
- version 3.2+ (à faire) : Prise en charge de plus de paramètres d'interface de plugin de fonction
- 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
- version 3.0 : Prise en charge de chatglm et d'autres petits llm
- version 2.6 : Réorganisation de la structure du plugin, amélioration de l'interactivité, ajout de plus de plugins
- 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
- 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.
- version 2.3 : Amélioration de l'interactivité multi-thread
- version 2.2 : Prise en charge du rechargement à chaud du plugin de fonction
- version 2.1 : Mise en page pliable
- version 2.0 : Introduction du plugin de fonction modulaire
- version 1.0 : Fonctionnalité de base
## Références et apprentissage
```
De nombreux designs d'autres projets exceptionnels ont été utilisés pour référence dans le code, notamment :
# Projet 1 : De nombreuses astuces ont été empruntées à ChuanhuChatGPT
https://github.com/GaiZhenbiao/ChuanhuChatGPT
# Projet 2 : ChatGLM-6B de Tsinghua :
https://github.com/THUDM/ChatGLM-6B
```

View File

@@ -1,302 +0,0 @@
> **Note**
>
> このReadmeファイルは、このプロジェクトのmarkdown翻訳プラグインによって自動的に生成されたもので、100%正確ではない可能性があります。
>
# <img src="logo.png" width="40" > ChatGPT 学術最適化
**このプロジェクトが好きだったら、スターをつけてください。もし、より使いやすい学術用のショートカットキーまたはファンクションプラグインを発明した場合は、issueを発行するかpull requestを作成してください。また、このプロジェクト自体によって翻訳されたREADMEは[英語説明書|](docs/README_EN.md)[日本語説明書|](docs/README_JP.md)[ロシア語説明書|](docs/README_RS.md)[フランス語説明書](docs/README_FR.md)もあります。**
> **注意事項**
>
> 1. **赤色**のラベルが付いているファンクションプラグインボタンのみファイルを読み込めます。一部のプラグインはプラグインエリアのドロップダウンメニューにあります。新しいプラグインのPRを歓迎いたします
>
> 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`)
<div align="center">
機能 | 説明
--- | ---
ワンクリック整形 | 論文の文法エラーを一括で正確に修正できます。
ワンクリック日英翻訳 | 日英翻訳には、ワンクリックで対応できます。
ワンクリックコード説明 | コードの正しい表示と説明が可能です。
[カスタムショートカットキー](https://www.bilibili.com/video/BV14s4y1E7jN) | カスタムショートカットキーをサポートします。
[プロキシサーバーの設定](https://www.bilibili.com/video/BV1rc411W7Dr) | プロキシサーバーの設定をサポートします。
モジュラーデザイン | カスタム高階関数プラグインと[関数プラグイン]、プラグイン[ホット更新]のサポートが可能です。詳細は[こちら](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)
[自己プログラム解析](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)このプロジェクトのソースコード
[プログラム解析機能](https://www.bilibili.com/video/BV1cj411A7VW) | [関数プラグイン] ワンクリックで別のPython/C/C++/Java/Lua/...プロジェクトツリーを解析できます。
論文読解 | [関数プラグイン] LaTeX論文の全文をワンクリックで解読し、要約を生成します。
LaTeX全文翻訳、整形 | [関数プラグイン] ワンクリックでLaTeX論文を翻訳または整形できます。
注釈生成 | [関数プラグイン] ワンクリックで関数の注釈を大量に生成できます。
チャット分析レポート生成 | [関数プラグイン] 実行後、まとめレポートを自動生成します。
[arxivヘルパー](https://www.bilibili.com/video/BV1LM4y1279X) | [関数プラグイン] 入力したarxivの記事URLで要約をワンクリック翻訳+PDFダウンロードができます。
[PDF論文全文翻訳機能](https://www.bilibili.com/video/BV1KT411x7Wn) | [関数プラグイン] PDF論文タイトルと要約を抽出し、全文を翻訳しますマルチスレッド
[Google Scholar Integratorヘルパー](https://www.bilibili.com/video/BV19L411U7ia) | [関数プラグイン] 任意のGoogle Scholar検索ページURLを指定すると、gptが興味深い記事を選択します。
数式/画像/テーブル表示 | 数式のTex形式とレンダリング形式を同時に表示できます。数式、コードのハイライトをサポートしています。
マルチスレッド関数プラグインサポート | ChatGPTをマルチスレッドで呼び出すことができ、大量のテキストやプログラムを簡単に処理できます。
ダークグラジオ[テーマ](https://github.com/binary-husky/chatgpt_academic/issues/173)の起動 | 「/?__dark-theme=true」というURLをブラウザに追加することで、ダークテーマに切り替えることができます。
[多数のLLMモデル](https://www.bilibili.com/video/BV1wT411p7yf)をサポート、[API2D](https://api2d.com/)インターフェースをサポート | GPT3.5、GPT4、[清華ChatGLM](https://github.com/THUDM/ChatGLM-6B)による同時サポートは、とても素晴らしいですね!
huggingface免科学上网[オンライン版](https://huggingface.co/spaces/qingxu98/gpt-academic) | huggingfaceにログイン後、[このスペース](https://huggingface.co/spaces/qingxu98/gpt-academic)をコピーしてください。
...... | ......
</div>
- 新しいインターフェースconfig.pyのLAYOUTオプションを変更するだけで、「左右レイアウト」と「上下レイアウト」を切り替えることができます
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
</div>
- すべてのボタンは、functional.pyを読み込んで動的に生成されます。カスタム機能を自由に追加して、クリップボードを解放します
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
</div>
- 色を修正/修正
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
</div>
- 出力に数式が含まれている場合、TeX形式とレンダリング形式の両方が表示され、コピーと読み取りが容易になります
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
</div>
- プロジェクトのコードを見るのが面倒chatgptに整備されたプロジェクトを直接与えましょう
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
</div>
- 多数の大規模言語モデルの混合呼び出し(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
</div>
多数の大規模言語モデルの混合呼び出し[huggingfaceテスト版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)(huggigface版はchatglmをサポートしていません)
---
## インストール-方法1直接運転 (Windows、LinuxまたはMacOS)
1. プロジェクトをダウンロードします。
```sh
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
```
2. API_KEYとプロキシ設定を構成する
`config.py`で、海外のProxyとOpenAI API KEYを構成して説明します。
```
1.あなたが中国にいる場合、OpenAI APIをスムーズに使用するには海外プロキシを設定する必要があります。構成の詳細については、config.py1.その中のUSE_PROXYをTrueに変更し、2.手順に従ってプロキシを変更する)を詳細に読んでください。
2. OpenAI API KEYを構成する。OpenAIのウェブサイトでAPI KEYを取得してください。一旦API KEYを手に入れると、config.pyファイルで設定するだけです。
3.プロキシネットワークに関連する問題(ネットワークタイムアウト、プロキシが動作しないをhttps://github.com/binary-husky/chatgpt_academic/issues/1にまとめました。
```
(P.S. プログラム実行時にconfig.pyの隣にconfig_private.pyという名前のプライバシー設定ファイルを作成し、同じ名前の設定を上書きするconfig_private.pyが存在するかどうかを優先的に確認します。そのため、私たちの構成読み取りロジックを理解できる場合は、config.pyの隣にconfig_private.pyという名前の新しい設定ファイルを作成し、その中のconfig.pyから設定を移動してください。config_private.pyはgitで保守されていないため、プライバシー情報をより安全にすることができます。)
3. 依存関係をインストールします。
```sh
# 選択肢があります。
python -m pip install -r requirements.txt
# (選択肢2) もしAnacondaを使用する場合、手順は同様です
# (選択肢2.1) conda create -n gptac_venv python=3.11
# (選択肢2.2) conda activate gptac_venv
# (選択肢2.3) python -m pip install -r requirements.txt
# 注: 公式のpipソースまたはAlibabaのpipソースを使用してください。 別のpipソース一部の大学のpipは問題が発生する可能性があります。 一時的なソースの切り替え方法:
# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
```
もしあなたが清華ChatGLMをサポートする必要がある場合、さらに多くの依存関係をインストールする必要がありますPythonに慣れない方やコンピューターの設定が十分でない方は、試みないことをお勧めします
```sh
python -m pip install -r request_llm/requirements_chatglm.txt
```
4. 実行
```sh
python main.py
```
5. 関数プラグインのテスト
```
- Pythonプロジェクト分析のテスト
入力欄に `./crazy_functions/test_project/python/dqn` と入力し、「Pythonプロジェクト全体の解析」をクリックします。
- 自己コード解読のテスト
「[マルチスレッドデモ] このプロジェクト自体を解析します(ソースを翻訳して解読します)」をクリックします。
- 実験的な機能テンプレート関数のテストGPTが「今日の歴史」に何が起こったかを回答することが求められます。この関数をテンプレートとして使用して、より複雑な機能を実装できます。
「[関数プラグインテンプレートデモ] 今日の歴史」をクリックします。
- 関数プラグインエリアのドロップダウンメニューには他にも選択肢があります。
```
## インストール方法2Dockerを使用するLinux
1. ChatGPTのみ大多数の人にお勧めです
``` sh
# プロジェクトのダウンロード
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
# 海外プロキシとOpenAI API KEYの設定
config.pyを任意のテキストエディタで編集する
# インストール
docker build -t gpt-academic .
# 実行
docker run --rm -it --net=host gpt-academic
# 関数プラグインのテスト
## 関数プラグインテンプレート関数のテストGPTが「今日の歴史」に何が起こったかを回答することが求められます。この関数をテンプレートとして使用して、より複雑な機能を実装できます。
「[関数プラグインテンプレートデモ] 今日の歴史」をクリックします。
## Latexプロジェクトの要約を書くテスト
入力欄に./crazy_functions/test_project/latex/attentionと入力し、「テックス論文を読んで要約を書く」をクリックします。
## Pythonプロジェクト分析のテスト
入力欄に./crazy_functions/test_project/python/dqnと入力し、[Pythonプロジェクトの全解析]をクリックします。
関数プラグインエリアのドロップダウンメニューには他にも選択肢があります。
```
2. ChatGPT + ChatGLMDockerに非常に詳しい人+十分なコンピューター設定が必要)
```sh
# Dockerfileの編集
cd docs && nano Dockerfile+ChatGLM
# ビルド方法
docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
# 実行方法 (1) 直接実行:
docker run --rm -it --net=host --gpus=all gpt-academic
# 実行方法 (2) コンテナに入って調整する:
docker run --rm -it --net=host --gpus=all gpt-academic bash
```
## インストール方法3その他のデプロイ方法
1. クラウドサーバーデプロイ
[デプロイ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)
2. WSL2を使用 (Windows Subsystem for Linux)
[デプロイ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)
## インストール-プロキシ設定
1. 通常の方法
[プロキシを設定する](https://github.com/binary-husky/chatgpt_academic/issues/1)
2. 初心者向けチュートリアル
[初心者向けチュートリアル](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)
---
## カスタムボタンの追加(学術ショートカットキー)
`core_functional.py`を任意のテキストエディタで開き、以下のエントリーを追加し、プログラムを再起動してください。(ボタンが追加されて表示される場合、前置詞と後置詞はホット編集がサポートされているため、プログラムを再起動せずに即座に有効になります。)
例:
```
"超级英译中": {
# 前置詞 - あなたの要求を説明するために使用されます。翻訳、コードの説明、編集など。
"Prefix": "以下のコンテンツを中国語に翻訳して、マークダウンテーブルを使用して専門用語を説明してください。\n\n",
# 後置詞 - プレフィックスと共に使用すると、入力内容を引用符で囲むことができます。
"Suffix": "",
},
```
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
</div>
---
## いくつかの機能の例
### 画像表示:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
</div>
### プログラムが自己解析できる場合:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
</div>
### 他のPython/Cppプロジェクトの解析
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
</div>
### Latex論文の一括読解と要約生成
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
</div>
### 自動報告生成
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
</div>
### モジュール化された機能デザイン
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
</div>
### ソースコードの英語翻訳
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
</div>
## Todo およびバージョン計画:
- version 3.2+ (todo): 関数プラグインがより多くのパラメーターインターフェースをサポートするようになります。
- version 3.1: 複数のgptモデルを同時にクエリし、api2dをサポートし、複数のapikeyの負荷分散をサポートします。
- version 3.0: chatglmおよび他の小型llmのサポート
- version 2.6: プラグイン構造を再構成し、相互作用性を高め、より多くのプラグインを追加しました。
- version 2.5: 自己更新。総括的な大規模プロジェクトのソースコードをまとめた場合、テキストが長すぎる、トークンがオーバーフローする問題を解決します。
- version 2.4: (1)PDF全文翻訳機能を追加。(2)入力エリアの位置を切り替える機能を追加。(3)垂直レイアウトオプションを追加。(4)マルチスレッド関数プラグインの最適化。
- version 2.3: 多スレッドの相互作用性を向上させました。
- version 2.2: 関数プラグインでホットリロードをサポート
- version 2.1: 折りたたみ式レイアウト
- version 2.0: モジュール化された関数プラグインを導入
- version 1.0: 基本機能
## 参考および学習
以下は中国語のマークダウンファイルです。日本語に翻訳してください。既存のマークダウンコマンドを変更しないでください:
```
多くの優秀なプロジェクトの設計を参考にしています。主なものは以下の通りです:
# 参考プロジェクト1ChuanhuChatGPTから多くのテクニックを借用
https://github.com/GaiZhenbiao/ChuanhuChatGPT
# 参考プロジェクト2清華ChatGLM-6B
https://github.com/THUDM/ChatGLM-6B
```

View File

@@ -1,291 +0,0 @@
> **Note**
>
> Этот файл самовыражения автоматически генерируется модулем перевода markdown в этом проекте и может быть не на 100% правильным.
>
# <img src="logo.png" width="40" > ChatGPT Academic Optimization
**Если вам понравился этот проект, пожалуйста, поставьте ему звезду. Если вы придумали более полезные академические ярлыки или функциональные плагины, не стесняйтесь создавать запросы на изменение или пул-запросы. Мы также имеем [README на английском языке](docs/README_EN.md), переведенный этим же проектом.
> **Примечание**
>
> 1. Пожалуйста, обратите внимание, что только функциonal plugins (buttons) с **красным цветом** могут читать файлы, некоторые из которых находятся в **выпадающем меню** плагинов. Кроме того, мы приветствуем и обрабатываем любые новые плагины с **наивысшим приоритетом**!
>
> 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) .
<div align="center">
Функция | Описание
--- | ---
Редактирование одним кликом | Поддержка редактирования одним кликом, поиск грамматических ошибок в академических статьях
Переключение языков "Английский-Китайский" одним кликом | Одним кликом переключайте языки "Английский-Китайский"
Разъяснение программного кода одним кликом | Вы можете правильно отобразить и объяснить программный код.
[Настраиваемые сочетания клавиш](https://www.bilibili.com/video/BV14s4y1E7jN) | Поддержка настраиваемых сочетаний клавиш
[Настройка сервера-прокси](https://www.bilibili.com/video/BV1rc411W7Dr) | Поддержка настройки сервера-прокси
Модульный дизайн | Поддержка настраиваемых функциональных плагинов высших порядков и функциональных плагинов, поддерживающих [горячее обновление](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)
[Автоанализ программы](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) кода программы проекта
[Анализ программы](https://www.bilibili.com/video/BV1cj411A7VW) | [Функциональный плагин] Один клик для проанализирования дерева других проектов Python/C/C++/Java/Lua/...
Чтение статей| [Функциональный плагин] Одним кликом прочитайте весь латех (LaTex) текст статьи и сгенерируйте краткое описание
Перевод и редактирование всех статей из LaTex | [Функциональный плагин] Перевод или редактирование LaTex-статьи всего одним нажатием кнопки
Генерация комментариев в пакетном режиме | [Функциональный плагин] Одним кликом сгенерируйте комментарии к функциям в пакетном режиме
Генерация отчетов пакета CHAT | [Функциональный плагин] Автоматически создавайте сводные отчеты после выполнения
[Помощник по arxiv](https://www.bilibili.com/video/BV1LM4y1279X) | [Функциональный плагин] Введите URL статьи arxiv, чтобы легко перевести резюме и загрузить PDF-файл
[Перевод полного текста статьи в формате PDF](https://www.bilibili.com/video/BV1KT411x7Wn) | [Функциональный плагин] Извлеките заголовок статьи, резюме и переведите весь текст статьи (многопоточно)
[Помощник интеграции Google Scholar](https://www.bilibili.com/video/BV19L411U7ia) | [Функциональный плагин] Дайте GPT выбрать для вас интересные статьи на любой странице поиска Google Scholar.
Отображение формул/изображений/таблиц | Одновременно отображается tex-форма и рендер-форма формул, поддержка формул, высокоскоростных кодов
Поддержка функциональных плагинов многопоточности | Поддержка многопоточной работы с плагинами, обрабатывайте огромные объемы текста или программы одним кликом
Запуск темной темы gradio[подробнее](https://github.com/binary-husky/chatgpt_academic/issues/173) | Добавьте / ?__dark-theme=true в конец URL браузера, чтобы переключиться на темную тему.
[Поддержка нескольких моделей LLM](https://www.bilibili.com/video/BV1wT411p7yf), поддержка API2D | Находиться между GPT3.5, GPT4 и [清华ChatGLM](https://github.com/THUDM/ChatGLM-6B) должно быть очень приятно, не так ли?
Альтернатива huggingface без использования научной сети [Онлайн-эксперимент](https://huggingface.co/spaces/qingxu98/gpt-academic) | Войдите в систему, скопируйте пространство [этот пространственный URL](https://huggingface.co/spaces/qingxu98/gpt-academic)
…… | ……
</div>
- Новый интерфейс (вы можете изменить настройку LAYOUT в config.py, чтобы переключаться между "горизонтальным расположением" и "вертикальным расположением")
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
</div>
Вы профессиональный переводчик научных статей.
- Все кнопки генерируются динамически путем чтения functional.py и могут быть легко настроены под пользовательские потребности, освобождая буфер обмена.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
</div>
- Редактирование/корректирование
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
</div>
- Если вывод содержит формулы, они отображаются одновременно как в формате tex, так и в рендеринговом формате для удобства копирования и чтения.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
</div>
- Лень смотреть код проекта? Просто покажите chatgpt.
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
</div>
- Несколько моделей больших языковых моделей смешиваются (ChatGLM + OpenAI-GPT3.5 + [API2D] (https://api2d.com/) -GPT4)
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
</div>
Несколько моделей больших языковых моделей смешиваются в [бета-версии huggingface] (https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta) (huggingface-версия не поддерживает chatglm).
---
## Установка - Метод 1: Запуск (Windows, Linux или MacOS)
1. Скачайте проект
```sh
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
```
2. Настройка API_KEY и настройки прокси
В файле `config.py` настройте зарубежный прокси и OpenAI API KEY, пояснения ниже
```
1. Если вы находитесь в Китае, вам нужно настроить зарубежный прокси, чтобы использовать OpenAI API. Пожалуйста, внимательно прочитайте config.py для получения инструкций (1. Измените USE_PROXY на True; 2. Измените прокси в соответствии с инструкциями).
2. Настройка API KEY OpenAI. Вам необходимо зарегистрироваться на сайте OpenAI и получить API KEY. После получения API KEY настройте его в файле config.py.
3. Вопросы, связанные с сетевыми проблемами (тайм-аут сети, прокси не работает), можно найти здесь: https://github.com/binary-husky/chatgpt_academic/issues/1
```
(Примечание: при запуске программы будет проверяться наличие конфиденциального файла конфигурации с именем `config_private.py` и использоваться в нем конфигурация параметров, которая перезаписывает параметры с такими же именами в `config.py`. Поэтому, если вы понимаете логику чтения нашей конфигурации, мы настоятельно рекомендуем вам создать новый файл конфигурации с именем `config_private.py` рядом с `config.py` и переместить (скопировать) настройки из `config.py` в `config_private.py`. `config_private.py` не подвергается контролю git, что делает конфиденциальную информацию более безопасной.)
3. Установить зависимости
```sh
# (Выбор 1) Рекомендуется
python -m pip install -r requirements.txt
# (Выбор 2) Если вы используете anaconda, то шаги будут аналогичны:
# (Шаг 2.1) conda create -n gptac_venv python=3.11
# (Шаг 2.2) conda activate gptac_venv
# (Шаг 2.3) python -m pip install -r requirements.txt
# Примечание: используйте официальный источник pip или источник pip.aliyun.com. Другие источники pip могут вызывать проблемы. временный метод замены источника:
# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
```
Если требуется поддержка TUNA ChatGLM, необходимо установить дополнительные зависимости (если вы неудобны с python, необходимо иметь хорошую конфигурацию компьютера):
```sh
python -m pip install -r request_llm/requirements_chatglm.txt
```
4. Запустите
```sh
python main.py
```
5. Тестовые функции плагина
```
- Тестирвоание анализа проекта Python
В основной области введите `./crazy_functions/test_project/python/dqn` , а затем нажмите "Анализировать весь проект Python"
- Тестирование самостоятельного чтения кода
Щелкните " [Демонстрационный режим многопоточности] Проанализируйте сам проект (расшифровка источника кода)"
- Тестирование функций шаблонного плагина (вы можете использовать эту функцию как шаблон для более сложных функций, требующих ответа от gpt в связи с тем, что произошло сегодня в истории)
Щелкните " [Функции шаблонного плагина] День в истории"
- На нижней панели дополнительные функции для выбора
```
## Установка - Метод 2: Использование docker (Linux)
1. Только ChatGPT (рекомендуется для большинства пользователей):
``` sh
# Скачать проект
git clone https://github.com/binary-husky/chatgpt_academic.git
cd chatgpt_academic
# Настроить прокси за границей и OpenAI API KEY
Отредактируйте файл config.py в любом текстовом редакторе.
# Установка
docker build -t gpt-academic .
# Запустить
docker run --rm -it --net=host gpt-academic
# Проверка функциональности плагина
## Проверка шаблонной функции плагина (требуется, чтобы gpt ответил, что произошло "в истории на этот день"), вы можете использовать эту функцию в качестве шаблона для реализации более сложных функций.
Нажмите "[Шаблонный демонстрационный плагин] История на этот день".
## Тест абстрактного резюме для проекта на Latex
В области ввода введите ./crazy_functions/test_project/latex/attention, а затем нажмите "Чтение реферата о тезисах статьи на LaTeX".
## Тестовый анализ проекта на Python
Введите в область ввода ./crazy_functions/test_project/python/dqn, затем нажмите "Проанализировать весь проект на Python".
Выбирайте больше функциональных плагинов в нижнем выпадающем меню.
```
2. ChatGPT + ChatGLM (требуется глубокое знание Docker и достаточно мощное компьютерное оборудование):
``` sh
# Изменение Dockerfile
cd docs && nano Dockerfile+ChatGLM
# Как построить | Как запустить (Dockerfile+ChatGLM в пути docs, сначала перейдите в папку с помощью cd docs)
docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
# Как запустить | Как запустить (2) я хочу войти в контейнер и сделать какие-то настройки до запуска:
docker run --rm -it --net=host --gpus=all gpt-academic bash
```
## Установка-Метод 3: Другие способы развертывания
1. Развертывание на удаленном облачном сервере
Пожалуйста, посетите [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)
2. Использование WSL2 (Windows Subsystem for Linux)
Пожалуйста, посетите [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)
## Установка-Настройки прокси
### Метод 1: Обычный способ
[Конфигурация прокси] (https://github.com/binary-husky/chatgpt_academic/issues/1)
### Метод 2: Руководство новичка
[Руководство новичка] (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)
---
## Настройка новой удобной кнопки (настройка быстрой клавиши для научной работы)
Откройте `core_functional.py` любым текстовым редактором, добавьте элементы, как показано ниже, затем перезапустите программу. (Если кнопка уже успешно добавлена и видна, то префикс и суффикс поддерживают горячее изменение, чтобы они оказались в действии, не нужно перезапускать программу.)
например
```
"Супер анг-рус": {
# Префикс, будет добавлен перед вашим вводом. Например, используется для описания ваших потребностей, таких как перевод, кодинг, редактирование и т. д.
"Prefix": "Пожалуйста, переведите этот фрагмент на русский язык, а затем создайте пошаговую таблицу в markdown, чтобы объяснить все специализированные термины, которые встречаются в тексте:\n\n",
# Суффикс, будет добавлен после вашего ввода. Например, совместно с префиксом можно обрамить ваш ввод в кавычки.
"Suffix": "",
},
```
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
</div>
---
## Демонстрация некоторых возможностей
### Отображение изображений:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
</div>
### Если программа может понимать и разбирать сама себя:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
</div>
### Анализ других проектов на Python/Cpp:
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
</div>
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
</div>
### Генерация понимания и абстрактов с помощью Латех статей в один клик
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
</div>
### Автоматическое создание отчетов
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
<img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
</div>
### Модульный дизайн функций
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
</div>
### Трансляция исходного кода на английский язык
<div align="center">
<img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
</div>
## Todo и планирование версий:
- version 3.2+ (todo): функция плагины поддерживают более многочисленные интерфейсы параметров
- version 3.1: поддержка одновременного опроса нескольких моделей gpt! Поддержка api2d, поддержка балансировки нагрузки множества apikey.
- version 3.0: поддержка chatglm и других маленьких llm
- version 2.6: реструктурировал структуру плагинов, повысил интерактивность, добавил больше плагинов
- version 2.5: само обновление, решение проблемы слишком длинного текста и переполнения токена при переводе всего проекта исходного кода
- version 2.4: (1) добавлена функция перевода всего PDF-документа; (2) добавлена функция изменения положения входной области; (3) добавлена опция вертикального макета; (4) оптимизация функций многопоточности плагина.
- version 2.3: улучшение многопоточной интерактивности
- version 2.2: функция плагинов поддерживает горячую перезагрузку
- version 2.1: блочная раскладка
- version 2.0: модульный дизайн функций плагина
- version 1.0: основные функции
## Ссылки на изучение и обучение
```
В коде использовано много хороших дизайнерских решений из других отличных проектов, в том числе:
# Project1: использование многих приемов из ChuanhuChatGPT
https://github.com/GaiZhenbiao/ChuanhuChatGPT
# Project2: ChatGLM-6B в Тхуде:
https://github.com/THUDM/ChatGLM-6B
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -1,256 +0,0 @@
# chatgpt-academic项目自译解报告
Author补充以下分析均由本项目调用ChatGPT一键生成如果有不准确的地方全怪GPT😄
## 对程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能。
整体概括:
该程序是一个基于自然语言处理和机器学习的科学论文辅助工具主要功能包括聊天机器人、批量总结PDF文档、批量翻译PDF文档、生成函数注释、解析项目源代码等。程序基于 Gradio 构建 Web 服务,并集成了代理和自动更新功能,提高了用户的使用体验。
文件功能表格:
| 文件名 | 文件功能 |
| --- | --- |
| check_proxy.py | 用于检查代理的正确性和可用性 |
| colorful.py | 包含不同预设置颜色的常量并用于多种UI元素 |
| config.py | 用于全局配置的类 |
| config_private.py | 与config.py文件一起使用的另一个配置文件用于更改私密信息 |
| core_functional.py | 包含一些TextFunctional类和基础功能函数 |
| crazy_functional.py | 包含大量高级功能函数和实验性的功能函数 |
| main.py | 程序的主入口包含GUI主窗口和主要的UI管理功能 |
| theme.py | 包含一些预设置主题的颜色 |
| toolbox.py | 提供了一些有用的工具函数 |
| crazy_functions\crazy_utils.py | 包含一些用于实现高级功能的辅助函数 |
| crazy_functions\Latex全文润色.py | 实现了对LaTeX文件中全文的润色和格式化功能 |
| crazy_functions\Latex全文翻译.py | 实现了对LaTeX文件中的内容进行翻译的功能 |
| crazy_functions\_\_init\_\_.py | 用于导入crazy_functional.py中的功能函数 |
| crazy_functions\下载arxiv论文翻译摘要.py | 从Arxiv上下载论文并提取重要信息 |
| crazy_functions\代码重写为全英文_多线程.py | 针对中文Python文件将其翻译为全英文 |
| crazy_functions\总结word文档.py | 提取Word文件的重要内容来生成摘要 |
| crazy_functions\批量Markdown翻译.py | 批量翻译Markdown文件 |
| crazy_functions\批量总结PDF文档.py | 批量从PDF文件中提取摘要 |
| crazy_functions\批量总结PDF文档pdfminer.py | 批量从PDF文件中提取摘要 |
| crazy_functions\批量翻译PDF文档_多线程.py | 批量翻译PDF文件 |
| crazy_functions\理解PDF文档内容.py | 批量分析PDF文件并提取摘要 |
| crazy_functions\生成函数注释.py | 自动生成Python文件中函数的注释 |
| crazy_functions\解析项目源代码.py | 解析并分析给定项目的源代码 |
| crazy_functions\询问多个大语言模型.py | 向多个大语言模型询问输入文本并进行处理 |
| crazy_functions\读文献写摘要.py | 根据用户输入读取文献内容并生成摘要 |
| crazy_functions\谷歌检索小助手.py | 利用谷歌学术检索用户提供的论文信息并提取相关信息 |
| crazy_functions\高级功能函数模板.py | 实现高级功能的模板函数 |
| request_llm\bridge_all.py | 处理与LLM的交互 |
| request_llm\bridge_chatglm.py | 使用ChatGLM模型进行聊天 |
| request_llm\bridge_chatgpt.py | 实现对话生成的各项功能 |
| request_llm\bridge_tgui.py | 在Websockets中与用户进行交互并生成文本输出 |
## [0/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\check_proxy.py
该文件主要包括四个函数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 两个第三方库。
## [1/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\colorful.py
该程序文件实现了一些打印文本的函数使其具有不同的颜色输出。当系统为Linux时直接跳过否则使用colorama库来实现颜色输出。程序提供了深色和亮色两种颜色输出方式同时也提供了对打印函数的别名。对于不是终端输出的情况对所有的打印函数进行重复定义以便在重定向时能够避免打印错误日志。
## [2/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\config.py
该程序文件是一个配置文件其主要功能是提供使用API密钥等信息以及对程序的体验进行优化例如定义对话框高度、布局等。还包含一些其他的设置例如设置并行使用的线程数、重试次数限制等等。
## [3/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\config_private.py
这是一个名为config_private.py的Python文件它用于配置API_KEY和代理信息。API_KEY是一个私密密钥用于访问某些受保护的API。USE_PROXY变量设置为True以应用代理proxies变量配置了代理网络的地址和协议。在使用该文件时需要填写正确的API_KEY和代理信息。
## [4/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\core_functional.py
该文件是一个Python模块名为"core_functional.py"。模块中定义了一个字典,包含了各种核心功能的配置信息,如英语学术润色、中文学术润色、查找语法错误等。每个功能都包含一些前言和后语,在前言中描述了该功能的任务和要求,在后语中提供一些附加信息。此外,有些功能还定义了一些特定的处理函数和按钮颜色。
## [5/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functional.py
这是一个Python程序文件文件名是crazy_functional.py。它导入了一个名为HotReload的工具箱并定义了一个名为get_crazy_functions()的函数。这个函数包括三个部分的插件组分别是已经编写完成的第一组插件、已经测试但距离完美状态还差一点点的第二组插件和尚未充分测试的第三组插件。每个插件都有一个名称、一个按钮颜色、一个函数和一个是否加入下拉菜单中的标志位。这些插件提供了多种功能包括生成函数注释、解析项目源代码、批量翻译PDF文档、谷歌检索、PDF文档内容理解和Latex文档的全文润色、翻译等功能。其中第三组插件可能还存在一定的bug。
## [6/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\main.py
该Python脚本代码实现了一个用于交互式对话的Chatbot机器人。它使用了Gradio框架来构建一个Web界面并在此基础之上嵌入了一个文本输入框和与Chatbot进行交互的其他控件包括提交、重置、停止和清除按钮、选择框和滑块等。此外它还包括了一些类和函数和一些用于编程分析的工具和方法。整个程序文件的结构清晰注释丰富并提供了很多技术细节使得开发者可以很容易地在其基础上进行二次开发、修改、扩展和集成。
## [7/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\theme.py
该程序文件名为theme.py主要功能为调节Gradio的全局样式。在该文件中调节了Gradio的主题颜色、字体、阴影、边框、渐变等等样式。同时该文件还添加了一些高级CSS样式比如调整表格单元格的背景和边框设定聊天气泡的圆角、最大宽度和阴影等等。如果CODE_HIGHLIGHT为True则还进行了代码高亮显示。
## [8/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\toolbox.py
这是一个名为`toolbox.py`的源代码文件。该文件包含了一系列工具函数和装饰器用于聊天Bot的开发和调试。其中有一些功能包括将输入参数进行重组、捕捉函数中的异常并记录到历史记录中、生成Markdown格式的聊天记录报告等。该文件中还包含了一些与转换Markdown文本相关的函数。
## [9/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\crazy_utils.py
这是一个Python程序文件 `crazy_utils.py`,它包含了两个函数:
- `input_clipping(inputs, history, max_token_limit)`这个函数接收三个参数inputs 是一个字符串history 是一个列表max_token_limit 是一个整数。它使用 `tiktoken``numpy``toolbox` 模块,处理输入文本和历史记录,将其裁剪到指定的最大标记数,避免输入过长导致的性能问题。如果 inputs 长度不超过 max_token_limit 的一半,则只裁剪历史;否则,同时裁剪输入和历史。
- `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 模型并获取结果,如果子任务出错,返回相应的错误信息,否则返回结果。
## [10/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\Latex全文润色.py
这是一个名为"crazy_functions\Latex全文润色.py"的程序文件,其中包含了两个函数"Latex英文润色"和"Latex中文润色",以及其他辅助函数。这些函数能够对 Latex 项目进行润色处理,其中 "多文件润色" 函数是一个主要函数,它调用了其他辅助函数用于读取和处理 Latex 项目中的文件。函数使用了多线程和机器学习模型进行自然语言处理,对文件进行简化和排版来满足学术标准。注释已删除并可以在函数内部查找。
## [11/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\Latex全文翻译.py
这个程序文件包括一个用于对整个Latex项目进行翻译的函数 `Latex英译中` 和一个用于将中文翻译为英文的函数 `Latex中译英`。这两个函数都会尝试导入依赖库 tiktoken 若无法导入则会提示用户安装。`Latex英译中` 函数会对 Latex 项目中的文件进行分离并去除注释,然后运行多线程翻译。`Latex中译英` 也做同样的事情,只不过是将中文翻译为英文。这个程序文件还包括其他一些帮助函数。
## [12/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\__init__.py
这是一个 Python 包,包名为 `crazy_functions`,在 `__init__.py` 文件中定义了一些函数,包含以下函数:
- `crazy_addition(a, b)`:对两个数进行加法运算,并将结果返回。
- `crazy_multiplication(a, b)`:对两个数进行乘法运算,并将结果返回。
- `crazy_subtraction(a, b)`:对两个数进行减法运算,并将结果返回。
- `crazy_division(a, b)`:对两个数进行除法运算,并将结果返回。
- `crazy_factorial(n)`:计算 `n` 的阶乘并返回结果。
这些函数可能会有一些奇怪或者不符合常规的实现方式(由函数名可以看出来),所以这个包的名称为 `crazy_functions`,可能是暗示这些函数会有一些“疯狂”的实现方式。
## [13/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\下载arxiv论文翻译摘要.py
该程序实现了一个名为“下载arxiv论文并翻译摘要”的函数插件作者是“binary-husky”。该函数的功能是在输入一篇arxiv论文的链接后提取摘要、下载PDF文档、翻译摘要为中文并将翻译结果保存到文件中。程序使用了一些Python库如requests、pdfminer和beautifulsoup4等。程序入口是名为“下载arxiv论文并翻译摘要”的函数其中使用了自定义的辅助函数download_arxiv_和get_name。程序中还使用了其他非函数的辅助函数和变量如update_ui、CatchException、report_exception和get_conf等。
## [14/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\代码重写为全英文_多线程.py
该文件是一个多线程Python脚本包含多个函数和利用第三方库进行的API请求。主要功能是将给定文件夹内的Python代码文件中所有中文转化为英文然后输出转化后的英文代码。重要的功能和步骤包括
1. 清空历史,以免输入溢出
2. 尝试导入依赖,如果缺少依赖,则给出安装建议
3. 集合文件
4. 显示随意内容以防卡顿的感觉
5. Token限制下的截断与处理
6. 多线程操作请求转换中文变为英文的代码
7. 所有线程同时开始执行任务函数
8. 循环轮询各个线程是否执行完毕
9. 把结果写入文件
10. 备份一个文件
## [15/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\总结word文档.py
这是一个名为"总结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文档。
## [16/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量Markdown翻译.py
这个程序文件实现了一个批量Markdown翻译功能可以将一个源代码项目中的Markdown文本翻译成指定语言目前支持中<-英和英<-中)。程序主要分为三个函数`PaperFileGroup`类用于处理长文本的拆分`多文件翻译`是主要函数调用了`request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency`函数进行多线程翻译并输出结果`Markdown英译中``Markdown中译外`分别是英译中和中译英的入口函数用于解析项目路径和调用翻译函数程序依赖于tiktoken等库实现
## [17/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量总结PDF文档.py
这是一个名为批量总结PDF文档的Python脚本包含了多个函数其中有一个函数名为clean_text”,可以对PDF提取出的原始文本进行清洗和格式化处理将连字转换为其基本形式并根据heuristic规则判断换行符是否是段落分隔并相应地进行替换另一个函数名为解析PDF”,可以接收一个PDF文件清单并对清单中的每一个PDF进行解析提取出文本并调用clean_text函数进行清洗和格式化处理然后向用户发送一个包含文章简介信息的问题并等待用户回答最后该脚本也包含一个名为批量总结PDF文档的主函数其中调用了解析PDF函数来完成对PDF文件的批量处理
## [18/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量总结PDF文档pdfminer.py
这个文件是一个Python模块文件名为pdfminer.py它定义了一个函数批量总结PDF文档该函数接受一些参数然后尝试导入pdfminer和beautifulsoup4库该函数将读取pdf文件或tex文件中的内容对其进行分析并使用GPT模型进行自然语言摘要文件中还有一个辅助函数readPdf用于读取pdf文件中的内容
## [19/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\批量翻译PDF文档_多线程.py
这是一个Python脚本文件名是crazy_functions\批量翻译PDF文档_多线程.py该脚本提供了一个名为批量翻译PDF文档的函数可以批量翻译PDF文件并生成报告文件该函数使用了多个模块和函数如toolboxcrazy_utilsupdate_ui等使用了Python的异常处理和多线程功能还使用了一些文本处理函数和第三方库如fitz和tiktoken)。在函数执行过程中它会进行一些参数检查读取和清理PDF文本递归地切割PDF文件获取文章meta信息多线程翻译整理报告格式等操作并更新UI界面和生成报告文件
## [20/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\理解PDF文档内容.py
这是一个解析PDF文件内容的Python程序程序文件名为"理解PDF文档内容.py"程序主要由5个步骤组成第0步是切割PDF文件第1步是从摘要中提取高价值信息放到history中第2步是迭代地历遍整个文章提取精炼信息第3步是整理history第4步是设置一个token上限防止回答时Token溢出程序主要用到了Python中的各种模块和函数库toolbox, tiktoken, pymupdf等
## [21/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\生成函数注释.py
这是一个名为"生成函数注释"的函数带有一个装饰器"@CatchException"可以捕获异常该函数接受文件路径参数和聊天机器人等参数用于对多个Python或C++文件进行函数注释使用了"toolbox""crazy_utils"模块中的函数该函数会逐个读取指定文件中的内容并使用聊天机器人进行交互向用户请求注释信息然后将生成的注释与原文件内容一起输出到一个markdown表格中最后该函数返回一个字符串指示任务是否已完成另外还包含一个名为"批量生成函数注释"的函数它与"生成函数注释"函数一起用于批量处理多个文件
## [22/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\解析项目源代码.py
这个程序文件实现了对一个源代码项目进行分析的功能其中函数`解析项目本身``解析一个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`实时更新界面
## [23/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\询问多个大语言模型.py
这是一个Python程序文件名为"crazy_functions\询问多个大语言模型.py"。该程序实现了一个同时向多个大语言模型询问的功能接收用户输入文本以及模型参数向ChatGPT和ChatGLM模型发出请求并将对话记录显示在聊天框中同时刷新界面
## [24/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\读文章写摘要.py
该程序文件是一个Python模块文件名为"读文章写摘要.py"主要包含两个函数"解析Paper""读文章写摘要"。其中"解析Paper"函数接受文件路径参数等参数逐个打印文件内容并使用GPT模型生成对该文件的摘要"读文章写摘要"函数则接受一段文本内容和参数将该文本内容及其所有.tex文件逐个传递给"解析Paper"函数进行处理并使用GPT模型生成文章的中英文摘要文件还导入了一些工具函数如异常处理信息上报和文件写入等
## [25/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\谷歌检索小助手.py
该文件代码包含了一个名为`get_meta_information`的函数和一个名为`谷歌检索小助手`的装饰器函数用于从谷歌学术中抓取文章元信息并从用户提供的搜索页面中分析所有文章的相关信息该文件使用了许多第三方库如requestsarxivBeautifulSoup等其中`get_meta_information`函数中还定义了一个名为`string_similar`的辅助函数用于比较字符串相似度
## [26/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\crazy_functions\高级功能函数模板.py
该程序文件是一个 Python 模块包含一个名为高阶功能模板函数的函数该函数接受多个参数其中包括输入文本GPT 模型参数插件模型参数聊天显示框聊天历史等 该函数的主要功能是根据输入文本使用 GPT 模型生成一些问题并等待用户回答这些问题使用 Markdown 格式然后将用户回答加入到聊天历史中并更新聊天显示框该函数还包含了一些异常处理和多线程的相关操作该程序文件还引用了另一个 Python 模块中的两个函数分别为CatchExceptionupdate_ui”,并且还引用了一个名为request_gpt_model_in_new_thread_with_ui_alive的自定义函数
## [27/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_all.py
这个文件是用来处理与LLM的交互的包含两个函数一个是 predict_no_ui_long_connection 用来处理长文本的输出可以多线程调用另一个是 predict 用来处理基础的对话功能这个文件会导入其他文件中定义的方法进行调用具体调用哪个方法取决于传入的参数函数中还有一些装饰器和管理多线程的逻辑
## [28/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_chatglm.py
这个程序文件实现了一个使用ChatGLM模型进行聊天的功能具体实现过程是首先进行初始化然后使用GetGLMHandle类进行ChatGLM模型的加载和运行predict_no_ui_long_connection函数用于多线程聊天而predict函数用于单线程聊天它们的不同之处在于前者不会更新UI界面后者会这个文件还导入了其他模块和库例如transformerstimeimportlib等并使用了多进程Pipe
## [29/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_chatgpt.py
这个程序文件是用于对话生成的主要包含三个函数predictpredict_no_uipredict_no_ui_long_connection其中predict是用于普通对话的函数具备完备的交互功能但不具备多线程能力predict_no_ui是高级实验性功能模块调用的函数参数简单可以多线程并行方便实现复杂的功能逻辑predict_no_ui_long_connection解决了predict_no_ui在处理长文档时容易断开连接的问题同样支持多线程程序中还包含一些常量和工具函数用于整合信息选择LLM模型生成http请求发送请求接收响应等它需要配置一个config文件包含代理网址API等敏感信息
## [30/31] 请对下面的程序文件做一个概述: H:\chatgpt_academic_resolve\request_llm\bridge_tgui.py
该程序文件实现了一个基于Websockets的文本生成服务和对话功能其中有三个函数`run()``predict()``predict_no_ui_long_connection()``run()`函数用于连接到Websocket服务并生成文本结果`predict()`函数用于将用户输入作为文本生成的输入同时在UI上显示对话历史记录并在不断更新UI的过程中不断更新生成的文本输出`predict_no_ui_long_connection()`函数与`predict()`函数类似但没有UI并在一段时间内返回单个生成的文本整个程序还引入了多个Python模块来完成相关功能例如`asyncio``websockets``json`等等
## 根据以上分析对程序的整体功能和构架重新做出概括。然后用一张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
程序功能概括该程序是一个聊天机器人可以通过 Web 界面与用户进行交互它包含了丰富的功能如文本润色翻译代码重写在线查找等并且支持多线程处理用户可以通过 Gradio 框架提供的 Web 界面进行交互程序还提供了一些调试工具如toolbox 模块方便程序开发和调试
下表概述了每个文件的功能
| 文件名 | 功能 |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| check_proxy.py | 检查代理是否可用 |
| colorful.py | 用于打印文本的字体颜色输出模块 |
| config.py | 用于程序中的各种设置如并行线程数量和重试次数的限制等 |
| config_private.py | 配置API_KEY和代理信息的文件 |
| core_functional.py | 包含具体的文本处理功能的模块 |
| crazy_functional.py | 包括各种插件函数的模块提供了多种文本处理功能 |
| main.py | 包含 Chatbot 机器人主程序的模块 |
| theme.py | 用于调节全局样式的模块 |
| toolbox.py | 包含工具函数和装饰器用于聊天Bot的开发和调试 |
| crazy_functions\crazy_utils.py | 包含一些辅助函数如文本裁剪和消息捕捉等 |
| crazy_functions\Latex全文润色.py | Latex 项目进行润色处理的功能模块 |
| crazy_functions\Latex全文翻译.py | Latex 项目进行翻译的功能模块 |
| crazy_functions\__init__.py | 定义一些奇特的数学函数等 |
| crazy_functions\下载arxiv论文翻译摘要.py | 下载 Arxiv 论文并翻译摘要的功能模块 |
| crazy_functions\代码重写为全英文_多线程.py | 将Python程序中所有中文转化为英文的功能模块 |
| crazy_functions\总结word文档.py | 解析 docx doc 格式的文件生成文章片段的中英文概述的功能模块 |
## 根据以上分析对程序的整体功能和构架重新做出概括。然后用一张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
根据以上分析整个程序是一个集成了多个有用工具和功能的文本处理和生成工具提供了多种在不同场景下使用的功能包括但不限于对话生成文本摘要PDF文件批量处理代码翻译和实用工具等主要的Python模块包括"toolbox.py"、"config.py"、"core_functional.py""crazy_functional.py"并且还使用了许多第三方库和模块实现相关功能以下是每个程序文件的功能
| 文件名 | 文件功能 |
| --- | --- |
| check_proxy.py | 用于检查代理的正确性和可用性 |
| colorful.py | 包含不同预设置颜色的常量并用于多种UI元素 |
| config.py | 用于全局配置的类 |
| config_private.py | 与config.py文件一起使用的另一个配置文件用于更改私密信息 |
| core_functional.py | 包含一些TextFunctional类和基础功能函数 |
| crazy_functional.py | 包含大量高级功能函数和实验性的功能函数 |
| main.py | 程序的主入口包含GUI主窗口和主要的UI管理功能 |
| theme.py | 包含一些预设置主题的颜色 |
| toolbox.py | 提供了一些有用的工具函数 |
| crazy_functions\crazy_utils.py | 包含一些用于实现高级功能的辅助函数 |
| crazy_functions\Latex全文润色.py | 实现了对LaTeX文件中全文的润色和格式化功能 |
| crazy_functions\Latex全文翻译.py | 实现了对LaTeX文件中的内容进行翻译的功能 |
| crazy_functions\_\_init\_\_.py | 用于导入crazy_functional.py中的功能函数 |
| crazy_functions\下载arxiv论文翻译摘要.py | 从Arxiv上下载论文并提取重要信息 |
| crazy_functions\代码重写为全英文_多线程.py | 针对中文Python文件将其翻译为全英文 |
| crazy_functions\总结word文档.py | 提取Word文件的重要内容来生成摘要 |
| crazy_functions\批量Markdown翻译.py | 批量翻译Markdown文件 |
| crazy_functions\批量总结PDF文档.py | 批量从PDF文件中提取摘要 |
| crazy_functions\批量总结PDF文档pdfminer.py | 批量从PDF文件中提取摘要 |
| crazy_functions\批量翻译PDF文档_多线程.py | 批量翻译PDF文件 |
| crazy_functions\理解PDF文档内容.py | 批量分析PDF文件并提取摘要 |
| crazy_functions\生成函数注释.py | 自动生成Python文件中函数的注释 |
| crazy_functions\解析项目源代码.py | 解析并分析给定项目的源代码 |
| crazy_functions\询问多个大语言模型.py | 向多个大语言模型询问输入文本并进行处理 |
| crazy_functions\读文献写摘要.py | 根据用户输入读取文献内容并生成摘要 |
| crazy_functions\谷歌检索小助手.py | 利用谷歌学术检索用户提供的论文信息并提取相关信息 |
| crazy_functions\高级功能函数模板.py | 实现高级功能的模板函数 |
| request_llm\bridge_all.py | 处理与LLM的交互 |
| request_llm\bridge_chatglm.py | 使用ChatGLM模型进行聊天 |
| request_llm\bridge_chatgpt.py | 实现对话生成的各项功能 |
| request_llm\bridge_tgui.py | 在Websockets中与用户进行交互并生成文本输出 |

View File

Before

Width:  |  Height:  |  Size: 262 KiB

After

Width:  |  Height:  |  Size: 262 KiB

View File

Before

Width:  |  Height:  |  Size: 264 KiB

After

Width:  |  Height:  |  Size: 264 KiB

BIN
img/公式.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 MiB

BIN
img/润色.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 MiB

338
main.py
View File

@@ -1,192 +1,174 @@
import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染 import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
import gradio as gr
from request_llm.bridge_chatgpt import predict
from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, DummyWith
def main(): # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
import gradio as gr proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \
from request_llm.bridge_all import predict get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY')
from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, DummyWith
# 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY, AVAIL_LLM_MODELS = \
get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY', 'AVAIL_LLM_MODELS')
# 如果WEB_PORT是-1, 则随机选取WEB端口 # 如果WEB_PORT是-1, 则随机选取WEB端口
PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
if not AUTHENTICATION: AUTHENTICATION = None if not AUTHENTICATION: AUTHENTICATION = None
from check_proxy import get_current_version from check_proxy import get_current_version
initial_prompt = "Serve me as a writing and programming assistant." initial_prompt = "Serve me as a writing and programming assistant."
title_html = f"<h1 align=\"center\">ChatGPT 学术优化 {get_current_version()}</h1>" title_html = f"<h1 align=\"center\">ChatGPT 学术优化 {get_current_version()}</h1>"
description = """代码开源和更新[地址🚀](https://github.com/binary-husky/chatgpt_academic),感谢热情的[开发者们❤️](https://github.com/binary-husky/chatgpt_academic/graphs/contributors)""" description = """代码开源和更新[地址🚀](https://github.com/binary-husky/chatgpt_academic),感谢热情的[开发者们❤️](https://github.com/binary-husky/chatgpt_academic/graphs/contributors)"""
# 问询记录, python 版本建议3.9+(越新越好) # 问询记录, python 版本建议3.9+(越新越好)
import logging import logging
os.makedirs("gpt_log", exist_ok=True) os.makedirs("gpt_log", exist_ok=True)
try:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO, encoding="utf-8") 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) 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 core_functional import get_core_functions from core_functional import get_core_functions
functional = get_core_functions() functional = get_core_functions()
# 高级函数插件 # 高级函数插件
from crazy_functional import get_crazy_functions from crazy_functional import get_crazy_functions
crazy_fns = get_crazy_functions() crazy_fns = get_crazy_functions()
# 处理markdown文本格式的转变 # 处理markdown文本格式的转变
gr.Chatbot.postprocess = format_io gr.Chatbot.postprocess = format_io
# 做一些外观色彩上的调整 # 做一些外观色彩上的调整
from theme import adjust_theme, advanced_css from theme import adjust_theme, advanced_css
set_theme = adjust_theme() set_theme = adjust_theme()
# 代理与自动更新 # 代理与自动更新
from check_proxy import check_proxy, auto_update, warm_up_modules from check_proxy import check_proxy, auto_update
proxy_info = check_proxy(proxies) proxy_info = check_proxy(proxies)
gr_L1 = lambda: gr.Row().style() gr_L1 = lambda: gr.Row().style()
gr_L2 = lambda scale: gr.Column(scale=scale) gr_L2 = lambda scale: gr.Column(scale=scale)
if LAYOUT == "TOP-DOWN": if LAYOUT == "TOP-DOWN":
gr_L1 = lambda: DummyWith() gr_L1 = lambda: DummyWith()
gr_L2 = lambda scale: gr.Row() gr_L2 = lambda scale: gr.Row()
CHATBOT_HEIGHT /= 2 CHATBOT_HEIGHT /= 2
cancel_handles = [] cancel_handles = []
with gr.Blocks(title="ChatGPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo: with gr.Blocks(title="ChatGPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
gr.HTML(title_html) gr.HTML(title_html)
cookies = gr.State({'api_key': API_KEY, 'llm_model': LLM_MODEL}) cookies = gr.State({'api_key': API_KEY, 'llm_model': LLM_MODEL})
with gr_L1(): with gr_L1():
with gr_L2(scale=2): with gr_L2(scale=2):
chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}") chatbot = gr.Chatbot()
chatbot.style(height=CHATBOT_HEIGHT) chatbot.style(height=CHATBOT_HEIGHT)
history = gr.State([]) history = gr.State([])
with gr_L2(scale=1): with gr_L2(scale=1):
with gr.Accordion("输入区", open=True) as area_input_primary: with gr.Accordion("输入区", open=True) as area_input_primary:
with gr.Row(): with gr.Row():
txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False) txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
with gr.Row(): with gr.Row():
submitBtn = gr.Button("提交", variant="primary") submitBtn = gr.Button("提交", variant="primary")
with gr.Row(): with gr.Row():
resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm") resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm") stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
clearBtn = gr.Button("清除", variant="secondary", visible=False); clearBtn.style(size="sm") with gr.Row():
with gr.Row(): status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}")
status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}") with gr.Accordion("基础功能区", open=True) as area_basic_fn:
with gr.Accordion("基础功能区", open=True) as area_basic_fn: with gr.Row():
with gr.Row(): for k in functional:
for k in functional: variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
variant = functional[k]["Color"] if "Color" in functional[k] else "secondary" functional[k]["Button"] = gr.Button(k, variant=variant)
functional[k]["Button"] = gr.Button(k, variant=variant) with gr.Accordion("函数插件区", open=True) as area_crazy_fn:
with gr.Accordion("函数插件区", open=True) as area_crazy_fn: with gr.Row():
with gr.Row(): gr.Markdown("注意:以下“红颜色”标识的函数插件需从输入区读取路径作为参数.")
gr.Markdown("注意:以下“红颜色”标识的函数插件需从输入区读取路径作为参数.") with gr.Row():
with gr.Row(): for k in crazy_fns:
for k in crazy_fns: if not crazy_fns[k].get("AsButton", True): continue
if not crazy_fns[k].get("AsButton", True): continue variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary" crazy_fns[k]["Button"] = gr.Button(k, variant=variant)
crazy_fns[k]["Button"] = gr.Button(k, variant=variant) crazy_fns[k]["Button"].style(size="sm")
crazy_fns[k]["Button"].style(size="sm") with gr.Row():
with gr.Row(): with gr.Accordion("更多函数插件", open=True):
with gr.Accordion("更多函数插件", open=True): dropdown_fn_list = [k for k in crazy_fns.keys() if not crazy_fns[k].get("AsButton", True)]
dropdown_fn_list = [k for k in crazy_fns.keys() if not crazy_fns[k].get("AsButton", True)] with gr.Column(scale=1):
with gr.Column(scale=1): dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(container=False)
dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(container=False) with gr.Column(scale=1):
with gr.Column(scale=1): switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary") with gr.Row():
with gr.Row(): with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up:
with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up: file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple") with gr.Accordion("展开SysPrompt & 交互界面布局 & Github地址", open=(LAYOUT == "TOP-DOWN")):
with gr.Accordion("更换模型 & SysPrompt & 交互界面布局", open=(LAYOUT == "TOP-DOWN")): system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt) top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
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=2.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",) checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "底部输入区"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区")
max_length_sl = gr.Slider(minimum=256, maximum=4096, value=512, step=1, interactive=True, label="Local LLM MaxLength",) gr.Markdown(description)
checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "底部输入区", "输入清除键"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区") with gr.Accordion("备选输入区", open=True, visible=False) as area_input_secondary:
md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False) with gr.Row():
txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False)
gr.Markdown(description) with gr.Row():
with gr.Accordion("备选输入区", open=True, visible=False) as area_input_secondary: submitBtn2 = gr.Button("提交", variant="primary")
with gr.Row(): with gr.Row():
txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False) resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
with gr.Row(): stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
submitBtn2 = gr.Button("提交", variant="primary") # 功能区显示开关与功能区的互动
with gr.Row(): def fn_area_visibility(a):
resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn2.style(size="sm") ret = {}
stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn2.style(size="sm") ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
clearBtn2 = gr.Button("清除", variant="secondary", visible=False); clearBtn2.style(size="sm") ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
# 功能区显示开关与功能区的互动 ret.update({area_input_primary: gr.update(visible=("底部输入区" not in a))})
def fn_area_visibility(a): ret.update({area_input_secondary: gr.update(visible=("底部输入区" in a))})
ret = {} if "底部输入区" in a: ret.update({txt: gr.update(value="")})
ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))}) return ret
ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))}) checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2] )
ret.update({area_input_primary: gr.update(visible=("底部输入区" not in a))}) # 整理反复出现的控件句柄组合
ret.update({area_input_secondary: gr.update(visible=("底部输入区" in a))}) input_combo = [cookies, txt, txt2, top_p, temperature, chatbot, history, system_prompt]
ret.update({clearBtn: gr.update(visible=("输入清除键" in a))}) output_combo = [cookies, chatbot, history, status]
ret.update({clearBtn2: gr.update(visible=("输入清除键" in a))}) predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=input_combo, outputs=output_combo)
if "底部输入区" in a: ret.update({txt: gr.update(value="")}) # 提交按钮、重置按钮
return ret cancel_handles.append(txt.submit(**predict_args))
checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2] ) cancel_handles.append(txt2.submit(**predict_args))
# 整理反复出现的控件句柄组合 cancel_handles.append(submitBtn.click(**predict_args))
input_combo = [cookies, max_length_sl, md_dropdown, txt, txt2, top_p, temperature, chatbot, history, system_prompt] cancel_handles.append(submitBtn2.click(**predict_args))
output_combo = [cookies, chatbot, history, status] resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=input_combo, outputs=output_combo) resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
# 提交按钮、重置按钮 # 基础功能区的回调函数注册
cancel_handles.append(txt.submit(**predict_args)) for k in functional:
cancel_handles.append(txt2.submit(**predict_args)) click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)
cancel_handles.append(submitBtn.click(**predict_args))
cancel_handles.append(submitBtn2.click(**predict_args))
resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
clearBtn.click(lambda: ("",""), None, [txt, txt2])
clearBtn2.click(lambda: ("",""), None, [txt, txt2])
# 基础功能区的回调函数注册
for k in functional:
click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)
cancel_handles.append(click_handle)
# 文件上传区接收文件后与chatbot的互动
file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes], [chatbot, txt, txt2])
# 函数插件-固定按钮区
for k in crazy_fns:
if not crazy_fns[k].get("AsButton", True): continue
click_handle = crazy_fns[k]["Button"].click(ArgsGeneralWrapper(crazy_fns[k]["Function"]), [*input_combo, gr.State(PORT)], output_combo)
click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
cancel_handles.append(click_handle)
# 函数插件-下拉菜单与随变按钮的互动
def on_dropdown_changed(k):
variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
return {switchy_bt: gr.update(value=k, variant=variant)}
dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt] )
def on_md_dropdown_changed(k):
return {chatbot: gr.update(label="当前模型:"+k)}
md_dropdown.select(on_md_dropdown_changed, [md_dropdown], [chatbot] )
# 随变按钮的回调函数注册
def route(k, *args, **kwargs):
if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo)
click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
# def expand_file_area(file_upload, area_file_up):
# if len(file_upload)>0: return {area_file_up: gr.update(open=True)}
# click_handle.then(expand_file_area, [file_upload, area_file_up], [area_file_up])
cancel_handles.append(click_handle) cancel_handles.append(click_handle)
# 终止按钮的回调函数注册 # 文件上传区接收文件后与chatbot的互动
stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles) file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles) # 函数插件-固定按钮区
for k in crazy_fns:
if not crazy_fns[k].get("AsButton", True): continue
click_handle = crazy_fns[k]["Button"].click(ArgsGeneralWrapper(crazy_fns[k]["Function"]), [*input_combo, gr.State(PORT)], output_combo)
click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
cancel_handles.append(click_handle)
# 函数插件-下拉菜单与随变按钮的互动
def on_dropdown_changed(k):
variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
return {switchy_bt: gr.update(value=k, variant=variant)}
dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt] )
# 随变按钮的回调函数注册
def route(k, *args, **kwargs):
if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo)
click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
# def expand_file_area(file_upload, area_file_up):
# if len(file_upload)>0: return {area_file_up: gr.update(open=True)}
# click_handle.then(expand_file_area, [file_upload, area_file_up], [area_file_up])
cancel_handles.append(click_handle)
# 终止按钮的回调函数注册
stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
# gradio的inbrowser触发不太稳定回滚代码到原始的浏览器打开函数
def auto_opentab_delay():
import threading, webbrowser, time
print(f"如果浏览器没有自动打开请复制并转到以下URL")
print(f"\t(亮色主题): http://localhost:{PORT}")
print(f"\t(暗色主题): http://localhost:{PORT}/?__dark-theme=true")
def open():
time.sleep(2) # 打开浏览器
webbrowser.open_new_tab(f"http://localhost:{PORT}/?__dark-theme=true")
threading.Thread(target=open, name="open-browser", daemon=True).start()
threading.Thread(target=auto_update, name="self-upgrade", daemon=True).start()
# gradio的inbrowser触发不太稳定回滚代码到原始的浏览器打开函数 auto_opentab_delay()
def auto_opentab_delay(): demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION)
import threading, webbrowser, time
print(f"如果浏览器没有自动打开请复制并转到以下URL")
print(f"\t(亮色主题): http://localhost:{PORT}")
print(f"\t(暗色主题): http://localhost:{PORT}/?__dark-theme=true")
def open():
time.sleep(2) # 打开浏览器
webbrowser.open_new_tab(f"http://localhost:{PORT}/?__dark-theme=true")
threading.Thread(target=open, name="open-browser", daemon=True).start()
threading.Thread(target=auto_update, name="self-upgrade", daemon=True).start()
threading.Thread(target=warm_up_modules, name="warm-up", daemon=True).start()
auto_opentab_delay()
demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png")
if __name__ == "__main__":
main()

BIN
objdump.tmp Normal file

Binary file not shown.

View File

@@ -1,53 +1,35 @@
# 如何使用其他大语言模型 # 如何使用其他大语言模型dev分支测试中
## ChatGLM
- 安装依赖 `pip install -r request_llm/requirements_chatglm.txt`
- 修改配置在config.py中将LLM_MODEL的值改为"chatglm"
## 1. 先运行text-generation
``` sh ``` sh
LLM_MODEL = "chatglm" # 下载模型( text-generation 这么牛的项目别忘了给人家star
```
- 运行!
``` sh
`python main.py`
```
---
## Text-Generation-UI (TGUI调试中暂不可用)
### 1. 部署TGUI
``` sh
# 1 下载模型
git clone https://github.com/oobabooga/text-generation-webui.git git clone https://github.com/oobabooga/text-generation-webui.git
# 2 这个仓库的最新代码有问题,回滚到几周之前
git reset --hard fcda3f87767e642d1c0411776e549e1d3894843d # 安装text-generation的额外依赖
# 3 切换路径
cd text-generation-webui
# 4 安装text-generation的额外依赖
pip install accelerate bitsandbytes flexgen gradio llamacpp markdown numpy peft requests rwkv safetensors sentencepiece tqdm datasets git+https://github.com/huggingface/transformers pip install accelerate bitsandbytes flexgen gradio llamacpp markdown numpy peft requests rwkv safetensors sentencepiece tqdm datasets git+https://github.com/huggingface/transformers
# 5 下载模型
# 切换路径
cd text-generation-webui
# 下载模型
python download-model.py facebook/galactica-1.3b python download-model.py facebook/galactica-1.3b
# 其他可选如 facebook/opt-1.3b # 其他可选如 facebook/opt-1.3b
# facebook/galactica-1.3b
# facebook/galactica-6.7b # facebook/galactica-6.7b
# facebook/galactica-120b # facebook/galactica-120b
# facebook/pygmalion-1.3b 等 # facebook/pygmalion-1.3b 等
# 详情见 https://github.com/oobabooga/text-generation-webui # 详情见 https://github.com/oobabooga/text-generation-webui
# 6 启动text-generation # 启动text-generation,注意把模型的斜杠改成下划线
python server.py --cpu --listen --listen-port 7865 --model facebook_galactica-1.3b python server.py --cpu --listen --listen-port 7860 --model facebook_galactica-1.3b
``` ```
### 2. 修改config.py ## 2. 修改config.py
``` sh ``` sh
# LLM_MODEL格式: tgui:[模型]@[ws地址]:[ws端口] , 端口要和上面给定的端口一致 # LLM_MODEL格式较复杂 TGUI:[模型]@[ws地址]:[ws端口] , 端口要和上面给定的端口一致
LLM_MODEL = "tgui:galactica-1.3b@localhost:7860" LLM_MODEL = "TGUI:galactica-1.3b@localhost:7860"
``` ```
### 3. 运行! ## 3. 运行!
``` sh ``` sh
cd chatgpt-academic cd chatgpt-academic
python main.py python main.py

View File

@@ -1,230 +0,0 @@
"""
该文件中主要包含2个函数是所有LLM的通用接口它们会继续向下调用更底层的LLM模型处理多模型并行等细节
不具备多线程能力的函数:正常对话时使用,具备完备的交互功能,不可多线程
1. predict(...)
具备多线程调用能力的函数:在函数插件中被调用,灵活而简洁
2. predict_no_ui_long_connection(...)
"""
import tiktoken
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor
from toolbox import get_conf
from .bridge_chatgpt import predict_no_ui_long_connection as chatgpt_noui
from .bridge_chatgpt import predict as chatgpt_ui
from .bridge_chatglm import predict_no_ui_long_connection as chatglm_noui
from .bridge_chatglm import predict as chatglm_ui
# from .bridge_tgui import predict_no_ui_long_connection as tgui_noui
# from .bridge_tgui import predict as tgui_ui
colors = ['#FF00FF', '#00FFFF', '#FF0000', '#990099', '#009999', '#990044']
class LazyloadTiktoken(object):
def __init__(self, model):
self.model = model
@staticmethod
@lru_cache(maxsize=128)
def get_encoder(model):
print('正在加载tokenizer如果是第一次运行可能需要一点时间下载参数')
tmp = tiktoken.encoding_for_model(model)
print('加载tokenizer完毕')
return tmp
def encode(self, *args, **kwargs):
encoder = self.get_encoder(self.model)
return encoder.encode(*args, **kwargs)
def decode(self, *args, **kwargs):
encoder = self.get_encoder(self.model)
return encoder.decode(*args, **kwargs)
# Endpoint 重定向
API_URL_REDIRECT, = get_conf("API_URL_REDIRECT")
openai_endpoint = "https://api.openai.com/v1/chat/completions"
api2d_endpoint = "https://openai.api2d.net/v1/chat/completions"
# 兼容旧版的配置
try:
API_URL, = get_conf("API_URL")
if API_URL != "https://api.openai.com/v1/chat/completions":
openai_endpoint = API_URL
print("警告API_URL配置选项将被弃用请更换为API_URL_REDIRECT配置")
except:
pass
# 新版配置
if openai_endpoint in API_URL_REDIRECT: openai_endpoint = API_URL_REDIRECT[openai_endpoint]
if api2d_endpoint in API_URL_REDIRECT: api2d_endpoint = API_URL_REDIRECT[api2d_endpoint]
# 获取tokenizer
tokenizer_gpt35 = LazyloadTiktoken("gpt-3.5-turbo")
tokenizer_gpt4 = LazyloadTiktoken("gpt-4")
get_token_num_gpt35 = lambda txt: len(tokenizer_gpt35.encode(txt, disallowed_special=()))
get_token_num_gpt4 = lambda txt: len(tokenizer_gpt4.encode(txt, disallowed_special=()))
model_info = {
# openai
"gpt-3.5-turbo": {
"fn_with_ui": chatgpt_ui,
"fn_without_ui": chatgpt_noui,
"endpoint": openai_endpoint,
"max_token": 4096,
"tokenizer": tokenizer_gpt35,
"token_cnt": get_token_num_gpt35,
},
"gpt-4": {
"fn_with_ui": chatgpt_ui,
"fn_without_ui": chatgpt_noui,
"endpoint": openai_endpoint,
"max_token": 8192,
"tokenizer": tokenizer_gpt4,
"token_cnt": get_token_num_gpt4,
},
# api_2d
"api2d-gpt-3.5-turbo": {
"fn_with_ui": chatgpt_ui,
"fn_without_ui": chatgpt_noui,
"endpoint": api2d_endpoint,
"max_token": 4096,
"tokenizer": tokenizer_gpt35,
"token_cnt": get_token_num_gpt35,
},
"api2d-gpt-4": {
"fn_with_ui": chatgpt_ui,
"fn_without_ui": chatgpt_noui,
"endpoint": api2d_endpoint,
"max_token": 8192,
"tokenizer": tokenizer_gpt4,
"token_cnt": get_token_num_gpt4,
},
# chatglm
"chatglm": {
"fn_with_ui": chatglm_ui,
"fn_without_ui": chatglm_noui,
"endpoint": None,
"max_token": 1024,
"tokenizer": tokenizer_gpt35,
"token_cnt": get_token_num_gpt35,
},
}
def LLM_CATCH_EXCEPTION(f):
"""
装饰器函数,将错误显示出来
"""
def decorated(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience):
try:
return f(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience)
except Exception as e:
from toolbox import get_conf
import traceback
proxies, = get_conf('proxies')
tb_str = '\n```\n' + traceback.format_exc() + '\n```\n'
observe_window[0] = tb_str
return tb_str
return decorated
def predict_no_ui_long_connection(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience=False):
"""
发送至LLM等待回复一次性完成不显示中间过程。但内部用stream的方法避免中途网线被掐。
inputs
是本次问询的输入
sys_prompt:
系统静默prompt
llm_kwargs
LLM的内部调优参数
history
是之前的对话列表
observe_window = None
用于负责跨越线程传递已经输出的部分大部分时候仅仅为了fancy的视觉效果留空即可。observe_window[0]观测窗。observe_window[1]:看门狗
"""
import threading, time, copy
model = llm_kwargs['llm_model']
n_model = 1
if '&' not in model:
assert not model.startswith("tgui"), "TGUI不支持函数插件的实现"
# 如果只询问1个大语言模型
method = model_info[model]["fn_without_ui"]
return method(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience)
else:
# 如果同时询问多个大语言模型:
executor = ThreadPoolExecutor(max_workers=4)
models = model.split('&')
n_model = len(models)
window_len = len(observe_window)
assert window_len==3
window_mutex = [["", time.time(), ""] for _ in range(n_model)] + [True]
futures = []
for i in range(n_model):
model = models[i]
method = model_info[model]["fn_without_ui"]
llm_kwargs_feedin = copy.deepcopy(llm_kwargs)
llm_kwargs_feedin['llm_model'] = model
future = executor.submit(LLM_CATCH_EXCEPTION(method), inputs, llm_kwargs_feedin, history, sys_prompt, window_mutex[i], console_slience)
futures.append(future)
def mutex_manager(window_mutex, observe_window):
while True:
time.sleep(0.5)
if not window_mutex[-1]: break
# 看门狗watchdog
for i in range(n_model):
window_mutex[i][1] = observe_window[1]
# 观察窗window
chat_string = []
for i in range(n_model):
chat_string.append( f"{str(models[i])} 说】: <font color=\"{colors[i]}\"> {window_mutex[i][0]} </font>" )
res = '<br/><br/>\n\n---\n\n'.join(chat_string)
# # # # # # # # # # #
observe_window[0] = res
t_model = threading.Thread(target=mutex_manager, args=(window_mutex, observe_window), daemon=True)
t_model.start()
return_string_collect = []
while True:
worker_done = [h.done() for h in futures]
if all(worker_done):
executor.shutdown()
break
time.sleep(1)
for i, future in enumerate(futures): # wait and get
return_string_collect.append( f"{str(models[i])} 说】: <font color=\"{colors[i]}\"> {future.result()} </font>" )
window_mutex[-1] = False # stop mutex thread
res = '<br/><br/>\n\n---\n\n'.join(return_string_collect)
return res
def predict(inputs, llm_kwargs, *args, **kwargs):
"""
发送至LLM流式获取输出。
用于基础的对话功能。
inputs 是本次问询的输入
top_p, temperature是LLM的内部调优参数
history 是之前的对话列表注意无论是inputs还是history内容太长了都会触发token数量溢出的错误
chatbot 为WebUI中显示的对话列表修改它然后yeild出去可以直接修改对话界面内容
additional_fn代表点击的哪个按钮按钮见functional.py
"""
method = model_info[llm_kwargs['llm_model']]["fn_with_ui"]
yield from method(inputs, llm_kwargs, *args, **kwargs)

View File

@@ -1,143 +0,0 @@
from transformers import AutoModel, AutoTokenizer
import time
import importlib
from toolbox import update_ui, get_conf
from multiprocessing import Process, Pipe
load_message = "ChatGLM尚未加载加载需要一段时间。注意取决于`config.py`的配置ChatGLM消耗大量的内存CPU或显存GPU也许会导致低配计算机卡死 ……"
#################################################################################
class GetGLMHandle(Process):
def __init__(self):
super().__init__(daemon=True)
self.parent, self.child = Pipe()
self.chatglm_model = None
self.chatglm_tokenizer = None
self.info = ""
self.success = True
self.check_dependency()
self.start()
def check_dependency(self):
try:
import sentencepiece
self.info = "依赖检测通过"
self.success = True
except:
self.info = "缺少ChatGLM的依赖如果要使用ChatGLM除了基础的pip依赖以外您还需要运行`pip install -r request_llm/requirements_chatglm.txt`安装ChatGLM的依赖。"
self.success = False
def ready(self):
return self.chatglm_model is not None
def run(self):
# 第一次运行,加载参数
retry = 0
while True:
try:
if self.chatglm_model is None:
self.chatglm_tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
device, = get_conf('LOCAL_MODEL_DEVICE')
if device=='cpu':
self.chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float()
else:
self.chatglm_model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()
self.chatglm_model = self.chatglm_model.eval()
break
else:
break
except:
retry += 1
if retry > 3:
self.child.send('[Local Message] Call ChatGLM fail 不能正常加载ChatGLM的参数。')
raise RuntimeError("不能正常加载ChatGLM的参数")
# 进入任务等待状态
while True:
kwargs = self.child.recv()
try:
for response, history in self.chatglm_model.stream_chat(self.chatglm_tokenizer, **kwargs):
self.child.send(response)
except:
self.child.send('[Local Message] Call ChatGLM fail.')
self.child.send('[Finish]')
def stream_chat(self, **kwargs):
self.parent.send(kwargs)
while True:
res = self.parent.recv()
if res != '[Finish]':
yield res
else:
break
return
global glm_handle
glm_handle = None
#################################################################################
def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
"""
多线程方法
函数的说明请见 request_llm/bridge_all.py
"""
global glm_handle
if glm_handle is None:
glm_handle = GetGLMHandle()
observe_window[0] = load_message + "\n\n" + glm_handle.info
if not glm_handle.success:
error = glm_handle.info
glm_handle = None
raise RuntimeError(error)
# chatglm 没有 sys_prompt 接口因此把prompt加入 history
history_feedin = []
history_feedin.append(["What can I do?", sys_prompt])
for i in range(len(history)//2):
history_feedin.append([history[2*i], history[2*i+1]] )
watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可
response = ""
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']):
observe_window[0] = response
if len(observe_window) >= 2:
if (time.time()-observe_window[1]) > watch_dog_patience:
raise RuntimeError("程序终止。")
return response
def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
"""
单线程方法
函数的说明请见 request_llm/bridge_all.py
"""
chatbot.append((inputs, ""))
global glm_handle
if glm_handle is None:
glm_handle = GetGLMHandle()
chatbot[-1] = (inputs, load_message + "\n\n" + glm_handle.info)
yield from update_ui(chatbot=chatbot, history=[])
if not glm_handle.success:
glm_handle = None
return
if additional_fn is not None:
import core_functional
importlib.reload(core_functional) # 热更新prompt
core_functional = core_functional.get_core_functions()
if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话)
inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
history_feedin = []
history_feedin.append(["What can I do?", system_prompt] )
for i in range(len(history)//2):
history_feedin.append([history[2*i], history[2*i+1]] )
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']):
chatbot[-1] = (inputs, response)
yield from update_ui(chatbot=chatbot, history=history)
history.extend([inputs, response])
yield from update_ui(chatbot=chatbot, history=history)

View File

@@ -21,9 +21,9 @@ import importlib
# config_private.py放自己的秘密如API和代理网址 # config_private.py放自己的秘密如API和代理网址
# 读取时首先看是否存在私密的config_private配置文件不受git管控如果有则覆盖原config文件 # 读取时首先看是否存在私密的config_private配置文件不受git管控如果有则覆盖原config文件
from toolbox import get_conf, update_ui, is_any_api_key, select_api_key, what_keys from toolbox import get_conf, update_ui
proxies, API_KEY, TIMEOUT_SECONDS, MAX_RETRY = \ proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL = \
get_conf('proxies', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY') get_conf('proxies', 'API_URL', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY', 'LLM_MODEL')
timeout_bot_msg = '[Local Message] 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.' + \
'网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。' '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。'
@@ -42,17 +42,17 @@ def get_full_error(chunk, stream_response):
def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False): def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
""" """
发送至chatGPT等待回复一次性完成不显示中间过程。但内部用stream的方法避免中途网线被掐。 发送至chatGPT等待回复一次性完成不显示中间过程。但内部用stream的方法避免中途网线被掐。
inputs inputs
是本次问询的输入 是本次问询的输入
sys_prompt: sys_prompt:
系统静默prompt 系统静默prompt
llm_kwargs llm_kwargs
chatGPT的内部调优参数 chatGPT的内部调优参数
history history
是之前的对话列表 是之前的对话列表
observe_window = None observe_window = None
用于负责跨越线程传递已经输出的部分大部分时候仅仅为了fancy的视觉效果留空即可。observe_window[0]观测窗。observe_window[1]:看门狗 用于负责跨越线程传递已经输出的部分大部分时候仅仅为了fancy的视觉效果留空即可。observe_window[0]观测窗。observe_window[1]:看门狗
""" """
watch_dog_patience = 5 # 看门狗的耐心, 设置5秒即可 watch_dog_patience = 5 # 看门狗的耐心, 设置5秒即可
headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt=sys_prompt, stream=True) headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt=sys_prompt, stream=True)
@@ -60,9 +60,7 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
while True: while True:
try: try:
# make a POST request to the API endpoint, stream=False # make a POST request to the API endpoint, stream=False
from .bridge_all import model_info response = requests.post(API_URL, headers=headers, proxies=proxies,
endpoint = model_info[llm_kwargs['llm_model']]['endpoint']
response = requests.post(endpoint, headers=headers, proxies=proxies,
json=payload, stream=True, timeout=TIMEOUT_SECONDS); break json=payload, stream=True, timeout=TIMEOUT_SECONDS); break
except requests.exceptions.ReadTimeout as e: except requests.exceptions.ReadTimeout as e:
retry += 1 retry += 1
@@ -85,7 +83,6 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
raise ConnectionAbortedError("OpenAI拒绝了请求:" + error_msg) raise ConnectionAbortedError("OpenAI拒绝了请求:" + error_msg)
else: else:
raise RuntimeError("OpenAI拒绝了请求" + error_msg) raise RuntimeError("OpenAI拒绝了请求" + error_msg)
if ('data: [DONE]' in chunk): break # api2d 正常完成
json_data = json.loads(chunk.lstrip('data:'))['choices'][0] json_data = json.loads(chunk.lstrip('data:'))['choices'][0]
delta = json_data["delta"] delta = json_data["delta"]
if len(delta) == 0: break if len(delta) == 0: break
@@ -99,7 +96,7 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
# 看门狗,如果超过期限没有喂狗,则终止 # 看门狗,如果超过期限没有喂狗,则终止
if len(observe_window) >= 2: if len(observe_window) >= 2:
if (time.time()-observe_window[1]) > watch_dog_patience: if (time.time()-observe_window[1]) > watch_dog_patience:
raise RuntimeError("用户取消了程序。") raise RuntimeError("程序终止")
else: raise RuntimeError("意外Json结构"+delta) else: raise RuntimeError("意外Json结构"+delta)
if json_data['finish_reason'] == 'length': if json_data['finish_reason'] == 'length':
raise ConnectionAbortedError("正常结束但显示Token不足导致输出不完整请削减单次输入的文本量。") raise ConnectionAbortedError("正常结束但显示Token不足导致输出不完整请削减单次输入的文本量。")
@@ -108,22 +105,22 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="",
def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None): def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
""" """
发送至chatGPT流式获取输出。 发送至chatGPT流式获取输出。
用于基础的对话功能。 用于基础的对话功能。
inputs 是本次问询的输入 inputs 是本次问询的输入
top_p, temperature是chatGPT的内部调优参数 top_p, temperature是chatGPT的内部调优参数
history 是之前的对话列表注意无论是inputs还是history内容太长了都会触发token数量溢出的错误 history 是之前的对话列表注意无论是inputs还是history内容太长了都会触发token数量溢出的错误
chatbot 为WebUI中显示的对话列表修改它然后yeild出去可以直接修改对话界面内容 chatbot 为WebUI中显示的对话列表修改它然后yeild出去可以直接修改对话界面内容
additional_fn代表点击的哪个按钮按钮见functional.py additional_fn代表点击的哪个按钮按钮见functional.py
""" """
if is_any_api_key(inputs): if inputs.startswith('sk-') and len(inputs) == 51:
chatbot._cookies['api_key'] = inputs chatbot._cookies['api_key'] = inputs
chatbot.append(("输入已识别为openai的api_key", what_keys(inputs))) chatbot.append(("输入已识别为openai的api_key", "api_key已导入"))
yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面
return return
elif not is_any_api_key(chatbot._cookies['api_key']): elif len(chatbot._cookies['api_key']) != 51:
chatbot.append((inputs, "缺少api_key。\n\n1. 临时解决方案直接在输入区键入api_key然后回车提交。\n\n2. 长效解决方案在config.py中配置。")) chatbot.append((inputs, "缺少api_key。\n\n1. 临时解决方案直接在输入区键入api_key然后回车提交。\n\n2. 长效解决方案在config.py中配置。"))
yield from update_ui(chatbot=chatbot, history=history, msg="缺少api_key") # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面
return return
if additional_fn is not None: if additional_fn is not None:
@@ -133,27 +130,20 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话) if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话)
inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"] inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
raw_input = inputs if stream:
logging.info(f'[raw_input] {raw_input}') raw_input = inputs
chatbot.append((inputs, "")) logging.info(f'[raw_input] {raw_input}')
yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面 chatbot.append((inputs, ""))
yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面
try: headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt, stream)
headers, payload = generate_payload(inputs, llm_kwargs, history, system_prompt, stream)
except RuntimeError as e:
chatbot[-1] = (inputs, f"您提供的api-key不满足要求不包含任何可用于{llm_kwargs['llm_model']}的api-key。您可能选择了错误的模型或请求源。")
yield from update_ui(chatbot=chatbot, history=history, msg="api-key不满足要求") # 刷新界面
return
history.append(inputs); history.append(" ") history.append(inputs); history.append(" ")
retry = 0 retry = 0
while True: while True:
try: try:
# make a POST request to the API endpoint, stream=True # make a POST request to the API endpoint, stream=True
from .bridge_all import model_info response = requests.post(API_URL, headers=headers, proxies=proxies,
endpoint = model_info[llm_kwargs['llm_model']]['endpoint']
response = requests.post(endpoint, headers=headers, proxies=proxies,
json=payload, stream=True, timeout=TIMEOUT_SECONDS);break json=payload, stream=True, timeout=TIMEOUT_SECONDS);break
except: except:
retry += 1 retry += 1
@@ -170,23 +160,21 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
while True: while True:
chunk = next(stream_response) chunk = next(stream_response)
# print(chunk.decode()[6:]) # print(chunk.decode()[6:])
if is_head_of_the_stream and (r'"object":"error"' not in chunk.decode()): if is_head_of_the_stream:
# 数据流的第一帧不携带content # 数据流的第一帧不携带content
is_head_of_the_stream = False; continue is_head_of_the_stream = False; continue
if chunk: if chunk:
try: try:
chunk_decoded = chunk.decode() if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
# 前者API2D的
if ('data: [DONE]' in chunk_decoded) or (len(json.loads(chunk_decoded[6:])['choices'][0]["delta"]) == 0):
# 判定为数据流的结束gpt_replying_buffer也写完了 # 判定为数据流的结束gpt_replying_buffer也写完了
logging.info(f'[response] {gpt_replying_buffer}') logging.info(f'[response] {gpt_replying_buffer}')
break break
# 处理数据流的主体 # 处理数据流的主体
chunkjson = json.loads(chunk_decoded[6:]) chunkjson = json.loads(chunk.decode()[6:])
status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}" status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}"
# 如果这里抛出异常一般是文本过长详情见get_full_error的输出 # 如果这里抛出异常一般是文本过长详情见get_full_error的输出
gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk_decoded[6:])['choices'][0]["delta"]["content"] gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]
history[-1] = gpt_replying_buffer history[-1] = gpt_replying_buffer
chatbot[-1] = (history[-2], history[-1]) chatbot[-1] = (history[-2], history[-1])
yield from update_ui(chatbot=chatbot, history=history, msg=status_text) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg=status_text) # 刷新界面
@@ -195,40 +183,31 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
traceback.print_exc() traceback.print_exc()
yield from update_ui(chatbot=chatbot, history=history, msg="Json解析不合常规") # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg="Json解析不合常规") # 刷新界面
chunk = get_full_error(chunk, stream_response) chunk = get_full_error(chunk, stream_response)
chunk_decoded = chunk.decode() error_msg = chunk.decode()
error_msg = chunk_decoded
if "reduce the length" in error_msg: if "reduce the length" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Reduce the length. 本次输入过长,或历史数据过长. 历史缓存数据现已释放,您可以请再次尝试.") chatbot[-1] = (chatbot[-1][0], "[Local Message] Reduce the length. 本次输入过长,或历史数据过长. 历史缓存数据现已释放,您可以请再次尝试.")
history = [] # 清除历史 history = [] # 清除历史
elif "does not exist" in error_msg:
chatbot[-1] = (chatbot[-1][0], f"[Local Message] Model {llm_kwargs['llm_model']} does not exist. 模型不存在,或者您没有获得体验资格.")
elif "Incorrect API key" in error_msg: elif "Incorrect API key" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key. OpenAI以提供了不正确的API_KEY为由拒绝服务.") chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key. OpenAI以提供了不正确的API_KEY为由拒绝服务.")
elif "exceeded your current quota" in error_msg: elif "exceeded your current quota" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] You exceeded your current quota. OpenAI以账户额度不足为由拒绝服务.") chatbot[-1] = (chatbot[-1][0], "[Local Message] You exceeded your current quota. OpenAI以账户额度不足为由拒绝服务.")
elif "bad forward key" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Bad forward key. API2D账户额度不足.")
elif "Not enough point" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Not enough point. API2D账户点数不足.")
else: else:
from toolbox import regular_txt_to_markdown from toolbox import regular_txt_to_markdown
tb_str = '```\n' + traceback.format_exc() + '```' tb_str = '```\n' + traceback.format_exc() + '```'
chatbot[-1] = (chatbot[-1][0], f"[Local Message] 异常 \n\n{tb_str} \n\n{regular_txt_to_markdown(chunk_decoded[4:])}") chatbot[-1] = (chatbot[-1][0], f"[Local Message] 异常 \n\n{tb_str} \n\n{regular_txt_to_markdown(chunk.decode()[4:])}")
yield from update_ui(chatbot=chatbot, history=history, msg="Json异常" + error_msg) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg="Json异常" + error_msg) # 刷新界面
return return
def generate_payload(inputs, llm_kwargs, history, system_prompt, stream): def generate_payload(inputs, llm_kwargs, history, system_prompt, stream):
""" """
整合所有信息选择LLM模型生成http请求为发送请求做准备 整合所有信息选择LLM模型生成http请求为发送请求做准备
""" """
if not is_any_api_key(llm_kwargs['api_key']): if len(llm_kwargs['api_key']) != 51:
raise AssertionError("你提供了错误的API_KEY。\n\n1. 临时解决方案直接在输入区键入api_key然后回车提交。\n\n2. 长效解决方案在config.py中配置。") raise AssertionError("你提供了错误的API_KEY。\n\n1. 临时解决方案直接在输入区键入api_key然后回车提交。\n\n2. 长效解决方案在config.py中配置。")
api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model'])
headers = { headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
"Authorization": f"Bearer {api_key}" "Authorization": f"Bearer {llm_kwargs['api_key']}"
} }
conversation_cnt = len(history) // 2 conversation_cnt = len(history) // 2
@@ -256,7 +235,7 @@ def generate_payload(inputs, llm_kwargs, history, system_prompt, stream):
messages.append(what_i_ask_now) messages.append(what_i_ask_now)
payload = { payload = {
"model": llm_kwargs['llm_model'].strip('api2d-'), "model": llm_kwargs['llm_model'],
"messages": messages, "messages": messages,
"temperature": llm_kwargs['temperature'], # 1.0, "temperature": llm_kwargs['temperature'], # 1.0,
"top_p": llm_kwargs['top_p'], # 1.0, "top_p": llm_kwargs['top_p'], # 1.0,

View File

@@ -13,18 +13,23 @@ import time
import threading import threading
import importlib import importlib
from toolbox import get_conf, update_ui from toolbox import get_conf, update_ui
LLM_MODEL, = get_conf('LLM_MODEL')
# "TGUI:galactica-1.3b@localhost:7860"
model_name, addr_port = LLM_MODEL.split('@')
assert ':' in addr_port, "LLM_MODEL 格式不正确!" + LLM_MODEL
addr, port = addr_port.split(':')
def random_hash(): def random_hash():
letters = string.ascii_lowercase + string.digits letters = string.ascii_lowercase + string.digits
return ''.join(random.choice(letters) for i in range(9)) return ''.join(random.choice(letters) for i in range(9))
async def run(context, max_token, temperature, top_p, addr, port): async def run(context, max_token=512):
params = { params = {
'max_new_tokens': max_token, 'max_new_tokens': max_token,
'do_sample': True, 'do_sample': True,
'temperature': temperature, 'temperature': 0.5,
'top_p': top_p, 'top_p': 0.9,
'typical_p': 1, 'typical_p': 1,
'repetition_penalty': 1.05, 'repetition_penalty': 1.05,
'encoder_repetition_penalty': 1.0, 'encoder_repetition_penalty': 1.0,
@@ -85,7 +90,7 @@ async def run(context, max_token, temperature, top_p, addr, port):
def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None): def predict_tgui(inputs, top_p, temperature, chatbot, history=[], system_prompt='', stream = True, additional_fn=None):
""" """
发送至chatGPT流式获取输出。 发送至chatGPT流式获取输出。
用于基础的对话功能。 用于基础的对话功能。
@@ -103,26 +108,18 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"] inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"]
raw_input = "What I would like to say is the following: " + inputs raw_input = "What I would like to say is the following: " + inputs
logging.info(f'[raw_input] {raw_input}')
history.extend([inputs, ""]) history.extend([inputs, ""])
chatbot.append([inputs, ""]) chatbot.append([inputs, ""])
yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面 yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面
prompt = raw_input prompt = inputs
tgui_say = "" tgui_say = ""
model_name, addr_port = llm_kwargs['llm_model'].split('@')
assert ':' in addr_port, "LLM_MODEL 格式不正确!" + llm_kwargs['llm_model']
addr, port = addr_port.split(':')
mutable = ["", time.time()] mutable = ["", time.time()]
def run_coorotine(mutable): def run_coorotine(mutable):
async def get_result(mutable): async def get_result(mutable):
# "tgui:galactica-1.3b@localhost:7860" async for response in run(prompt):
async for response in run(context=prompt, max_token=llm_kwargs['max_length'],
temperature=llm_kwargs['temperature'],
top_p=llm_kwargs['top_p'], addr=addr, port=port):
print(response[len(mutable[0]):]) print(response[len(mutable[0]):])
mutable[0] = response mutable[0] = response
if (time.time() - mutable[1]) > 3: if (time.time() - mutable[1]) > 3:
@@ -143,29 +140,28 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp
chatbot[-1] = (history[-2], history[-1]) chatbot[-1] = (history[-2], history[-1])
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
logging.info(f'[response] {tgui_say}')
def predict_no_ui_long_connection(inputs, llm_kwargs, history, sys_prompt, observe_window, console_slience=False): def predict_tgui_no_ui(inputs, top_p, temperature, history=[], sys_prompt=""):
raw_input = "What I would like to say is the following: " + inputs raw_input = "What I would like to say is the following: " + inputs
prompt = raw_input prompt = inputs
tgui_say = "" tgui_say = ""
model_name, addr_port = llm_kwargs['llm_model'].split('@') mutable = ["", time.time()]
assert ':' in addr_port, "LLM_MODEL 格式不正确!" + llm_kwargs['llm_model'] def run_coorotine(mutable):
addr, port = addr_port.split(':') async def get_result(mutable):
async for response in run(prompt, max_token=20):
print(response[len(mutable[0]):])
def run_coorotine(observe_window): mutable[0] = response
async def get_result(observe_window): if (time.time() - mutable[1]) > 3:
async for response in run(context=prompt, max_token=llm_kwargs['max_length'],
temperature=llm_kwargs['temperature'],
top_p=llm_kwargs['top_p'], addr=addr, port=port):
print(response[len(observe_window[0]):])
observe_window[0] = response
if (time.time() - observe_window[1]) > 5:
print('exit when no listener') print('exit when no listener')
break break
asyncio.run(get_result(observe_window)) asyncio.run(get_result(mutable))
thread_listen = threading.Thread(target=run_coorotine, args=(observe_window,)) thread_listen = threading.Thread(target=run_coorotine, args=(mutable,))
thread_listen.start() thread_listen.start()
return observe_window[0] while thread_listen.is_alive():
time.sleep(1)
mutable[1] = time.time()
tgui_say = mutable[0]
return tgui_say

View File

@@ -1,6 +0,0 @@
protobuf
transformers==4.27.1
cpm_kernels
torch>=1.10
mdtex2html
sentencepiece

View File

@@ -1,5 +1,4 @@
gradio==3.25.0 gradio>=3.23
tiktoken>=0.3.3
requests[socks] requests[socks]
transformers transformers
python-markdown-math python-markdown-math
@@ -8,9 +7,10 @@ latex2mathml
python-docx python-docx
mdtex2html mdtex2html
colorama colorama
tiktoken
Markdown Markdown
pygments pygments
pymupdf pymupdf
openai openai
numpy numpy
arxiv arxiv

262
self_analysis.md Normal file
View File

@@ -0,0 +1,262 @@
# chatgpt-academic项目自译解报告
Author补充以下分析均由本项目调用ChatGPT一键生成如果有不准确的地方全怪GPT😄
## 对程序的整体功能和构架做出概括。然后用一张markdown表格整理每个文件的功能包括'check_proxy.py', 'config.py'等)。
整体概括:
该程序是一个基于自然语言处理和机器学习的科学论文辅助工具主要功能包括聊天机器人、批量总结PDF文档、批量翻译PDF文档、生成函数注释、解析项目源代码等。程序基于 Gradio 构建 Web 服务,并集成了代理和自动更新功能,提高了用户的使用体验。
文件功能表格:
| 文件名称 | 功能 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| .\check_proxy.py | 检查代理设置功能。 |
| .\config.py | 配置文件,存储程序的基本设置。 |
| .\config_private.py | 存储代理网络地址的文件。 |
| .\core_functional.py | 主要的程序逻辑,包括聊天机器人和文件处理。 |
| .\cradle.py | 程序入口,初始化程序和启动 Web 服务。 |
| .\crazy_functional.py | 辅助程序功能包括PDF文档处理、代码处理、函数注释生成等。 |
| .\main.py | 包含聊天机器人的具体实现。 |
| .\show_math.py | 处理 LaTeX 公式的函数。 |
| .\theme.py | 存储 Gradio Web 服务的 CSS 样式文件。 |
| .\toolbox.py | 提供了一系列工具函数,包括文件读写、网页抓取、解析函数参数、生成 HTML 等。 |
| ./crazy_functions/crazy_utils.py | 提供各种工具函数,如解析字符串、清洗文本、清理目录结构等。 |
| ./crazy_functions/\_\_init\_\_.py | crazy_functions 模块的入口文件。 |
| ./crazy_functions/下载arxiv论文翻译摘要.py | 对 arxiv.org 上的 PDF 论文进行下载和翻译。 |
| ./crazy_functions/代码重写为全英文_多线程.py | 将代码文件中的中文注释和字符串替换为英文。 |
| ./crazy_functions/总结word文档.py | 读取 Word 文档并生成摘要。 |
| ./crazy_functions/批量总结PDF文档.py | 批量读取 PDF 文件并生成摘要。 |
| ./crazy_functions/批量总结PDF文档pdfminer.py | 使用 pdfminer 库进行 PDF 文件处理。 |
| ./crazy_functions/批量翻译PDF文档_多线程.py | 使用多线程技术批量翻译 PDF 文件。 |
| ./crazy_functions/生成函数注释.py | 给 Python 函数自动生成说明文档。 |
| ./crazy_functions/解析项目源代码.py | 解析项目中的源代码,提取注释和函数名等信息。 |
| ./crazy_functions/读文章写摘要.py | 读取多个文本文件并生成对应的摘要。 |
| ./crazy_functions/高级功能函数模板.py | 使用 GPT 模型进行文本处理。 |
## [0/22] 程序概述: check_proxy.py
该程序的文件名是check_proxy.py主要有两个函数check_proxy和auto_update。
check_proxy函数中会借助requests库向一个IP查询API发送请求并返回该IP的地理位置信息。同时根据返回的数据来判断代理是否有效。
auto_update函数主要用于检查程序更新会从Github获取程序最新的版本信息如果当前版本和最新版本相差较大则会提示用户进行更新。该函数中也会依赖requests库进行网络请求。
在程序的开头还添加了一句防止代理网络影响的代码。程序使用了自己编写的toolbox模块中的get_conf函数来获取代理设置。
## [1/22] 程序概述: config.py
该程序文件是一个Python模块文件名为config.py。该模块包含了一些变量和配置选项用于配置一个OpenAI的聊天机器人。具体的配置选项如下
- API_KEY: 密钥用于连接OpenAI的API。需要填写有效的API密钥。
- USE_PROXY: 是否使用代理。如果需要使用代理需要将其改为True。
- proxies: 代理的协议、地址和端口。
- CHATBOT_HEIGHT: 聊天机器人对话框的高度。
- LAYOUT: 聊天机器人对话框的布局,默认为左右布局。
- TIMEOUT_SECONDS: 发送请求到OpenAI后等待多久判定为超时。
- WEB_PORT: 网页的端口,-1代表随机端口。
- MAX_RETRY: 如果OpenAI不响应网络卡顿、代理失败、KEY失效重试的次数限制。
- LLM_MODEL: OpenAI模型选择目前只对某些用户开放的gpt4。
- API_URL: OpenAI的API地址。
- CONCURRENT_COUNT: 使用的线程数。
- AUTHENTICATION: 用户名和密码,如果需要。
## [2/22] 程序概述: config_private.py
该程序文件名为config_private.py包含了API_KEY的设置和代理的配置。使用了一个名为API_KEY的常量来存储私人的API密钥。此外还有一个名为USE_PROXY的常量来标记是否需要使用代理。如果需要代理则使用了一个名为proxies的字典来存储代理网络的地址其中包括协议类型、地址和端口。
## [3/22] 程序概述: core_functional.py
该程序文件名为`core_functional.py`,主要是定义了一些核心功能函数,包括英语和中文学术润色、查找语法错误、中译英、学术中英互译、英译中、找图片和解释代码等。每个功能都有一个`Prefix`属性和`Suffix`属性,`Prefix`是指在用户输入的任务前面要显示的文本,`Suffix`是指在任务后面要显示的文本。此外,还有一个`Color`属性指示按钮的颜色,以及一个`PreProcess`函数表示对输入进行预处理的函数。
## [4/22] 程序概述: cradle.py
该程序文件名为cradle.py主要功能是检测当前版本与远程最新版本是否一致如果不一致则输出新版本信息并提示更新。其流程大致如下
1. 导入相关模块与自定义工具箱函数get_conf
2. 读取配置文件中的代理proxies
3. 使用requests模块请求远程版本信息url为https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version并加载为json格式
4. 获取远程版本号、是否显示新功能信息、新功能内容
5. 读取本地版本文件version并加载为json格式
6. 获取当前版本号
7. 比较当前版本与远程版本如果远程版本号比当前版本号高0.05以上,则输出新版本信息并提示更新
8. 如果不需要更新,则直接返回
## [5/22] 程序概述: crazy_functional.py
该程序文件名为.\crazy_functional.py主要定义了一个名为get_crazy_functions()的函数该函数返回一个字典类型的变量function_plugins其中包含了一些函数插件。
一些重要的函数插件包括:
- 读文章写摘要可以自动读取Tex格式的论文并生成其摘要。
- 批量生成函数注释可以批量生成Python函数的文档注释。
- 解析项目源代码可以解析Python、C++、Golang、Java及React项目的源代码。
- 批量总结PDF文档可以对PDF文档进行批量总结以提取其中的关键信息。
- 一键下载arxiv论文并翻译摘要可以自动下载arxiv.org网站上的PDF论文并翻译生成其摘要。
- 批量翻译PDF文档多线程可以对PDF文档进行批量翻译并使用多线程方式提高翻译效率。
## [6/22] 程序概述: main.py
本程序为一个基于 Gradio 和 GPT-3 的交互式聊天机器人,文件名为 main.py。其中主要功能包括
1. 使用 Gradio 建立 Web 界面,实现用户与聊天机器人的交互;
2. 通过 bridge_chatgpt 模块,利用 GPT-3 模型实现聊天机器人的逻辑;
3. 提供一些基础功能和高级函数插件,用户可以通过按钮选择使用;
4. 提供文档格式转变、外观调整以及代理和自动更新等功能。
程序的主要流程为:
1. 导入所需的库和模块,并通过 get_conf 函数获取配置信息;
2. 设置 Gradio 界面的各个组件,包括聊天窗口、输入区、功能区、函数插件区等;
3. 注册各个组件的回调函数,包括用户输入、信号按钮等,实现机器人逻辑的交互;
4. 通过 Gradio 的 queue 函数和 launch 函数启动 Web 服务,并提供聊天机器人的功能。
此外,程序还提供了代理和自动更新功能,可以确保用户的使用体验。
## [7/22] 程序概述: show_math.py
该程序是一个Python脚本文件名为show_math.py。它转换Markdown和LaTeX混合语法到带MathML的HTML。程序使用latex2mathml模块来实现从LaTeX到MathML的转换将符号转换为HTML实体以批量处理。程序利用正则表达式和递归函数的方法处理不同形式的LaTeX语法支持以下四种情况$$形式、$形式、\[..]形式和\(...\)形式。如果无法转换某个公式则在该位置插入一条错误消息。最后程序输出HTML字符串。
## [8/22] 程序概述: theme.py
该程序文件为一个Python脚本其功能是调整Gradio应用的主题和样式包括字体、颜色、阴影、背景等等。在程序中使用了Gradio提供的默认颜色主题并针对不同元素设置了相应的样式属性以达到美化显示的效果。此外程序中还包含了一段高级CSS样式代码针对表格、列表、聊天气泡、行内代码等元素进行了样式设定。
## [9/22] 程序概述: toolbox.py
此程序文件主要包含了一系列用于聊天机器人开发的实用工具函数和装饰器函数。主要函数包括:
1. ArgsGeneralWrapper一个装饰器函数用于重组输入参数改变输入参数的顺序与结构。
2. get_reduce_token_percent一个函数用于计算自然语言处理时会出现的token溢出比例。
3. predict_no_ui_but_counting_down一个函数调用聊天接口并且保留了一定的界面心跳功能即当对话太长时会自动采用二分法截断。
4. write_results_to_file一个函数将对话记录history生成Markdown格式的文本并写入文件中。
5. regular_txt_to_markdown一个函数将普通文本转换为Markdown格式的文本。
6. CatchException一个装饰器函数捕捉函数调度中的异常并封装到一个生成器中返回并显示到聊天当中。
7. HotReload一个装饰器函数实现函数插件的热更新。
8. report_execption一个函数向chatbot中添加错误信息。
9. text_divide_paragraph一个函数将文本按照段落分隔符分割开生成带有段落标签的HTML代码。
10. markdown_convertion一个函数将Markdown格式的文本转换为HTML格式。如果包含数学公式则先将公式转换为HTML格式。
11. close_up_code_segment_during_stream一个函数用于在gpt输出代码的中途即输出了前面的```,但还没输出完后面的```,补上后面的```。
12. format_io一个函数将输入和输出解析为HTML格式。将输出部分的Markdown和数学公式转换为HTML格式。
13. find_free_port一个函数返回当前系统中可用的未使用端口。
14. extract_archive一个函数解压缩文件。
15. find_recent_files一个函数查找目录下一分钟内创建的文件。
16. on_file_uploaded一个函数响应用户上传的文件。
## [10/22] 程序概述: crazy_functions\crazy_utils.py
这是一个名为"crazy_utils.py"的Python程序文件包含了两个函数
1. `breakdown_txt_to_satisfy_token_limit()`:接受文本字符串、计算文本单词数量的函数和单词数量限制作为输入参数,将长文本拆分成合适的长度,以满足单词数量限制。这个函数使用一个递归方法去拆分长文本。
2. `breakdown_txt_to_satisfy_token_limit_for_pdf()`:类似于`breakdown_txt_to_satisfy_token_limit()`但是它使用一个不同的递归方法来拆分长文本以满足PDF文档中的需求。当出现无法继续拆分的情况时该函数将使用一个中文句号标记插入文本来截断长文本。如果还是无法拆分则会引发运行时异常。
## [11/22] 程序概述: crazy_functions\__init__.py
这个程序文件是一个 Python 的包,包名为 "crazy_functions",并且是其中的一个子模块 "__init__.py"。该包中可能包含多个函数或类,用于实现各种疯狂的功能。由于该文件的具体代码没有给出,因此无法进一步确定该包中的功能。通常情况下,一个包应该具有 __init__.py、__main__.py 和其它相关的模块文件,用于实现该包的各种功能。
## [12/22] 程序概述: crazy_functions\下载arxiv论文翻译摘要.py
这个程序实现的功能是下载arxiv论文并翻译摘要文件名为`下载arxiv论文翻译摘要.py`。这个程序引入了`requests``unicodedata``os``re`等Python标准库以及`pdfminer``bs4`等第三方库。其中`download_arxiv_`函数主要实现了从arxiv网站下载论文的功能包括解析链接、获取论文信息、下载论文和生成文件名等`get_name`函数则是为了从arxiv网站中获取论文信息创建的辅助函数。`下载arxiv论文并翻译摘要`函数则是实现了从下载好的PDF文件中提取摘要然后使用预先训练的GPT模型翻译为中文的功能。同时该函数还会将历史记录写入文件中。函数还会通过`CatchException`函数来捕获程序中出现的异常信息。
## [13/22] 程序概述: crazy_functions\代码重写为全英文_多线程.py
该程序文件为一个Python多线程程序文件名为"crazy_functions\代码重写为全英文_多线程.py"。该程序使用了多线程技术,将一个大任务拆成多个小任务,同时执行,提高运行效率。
程序的主要功能是将Python文件中的中文转换为英文同时将转换后的代码输出。程序先清空历史记录然后尝试导入openai和transformers等依赖库。程序接下来会读取当前路径下的.py文件和crazy_functions文件夹中的.py文件并将其整合成一个文件清单。随后程序会使用GPT2模型进行中英文的翻译并将结果保存在本地路径下的"gpt_log/generated_english_version"文件夹中。程序最终会生成一个任务执行报告。
需要注意的是,该程序依赖于"request_llm"和"toolbox"库以及本地的"crazy_utils"模块。
## [14/22] 程序概述: crazy_functions\总结word文档.py
该程序文件是一个 Python 脚本文件,文件名为 ./crazy_functions/总结word文档.py。该脚本是一个函数插件提供了名为“总结word文档”的函数。该函数的主要功能是批量读取给定文件夹下的 Word 文档文件,并使用 GPT 模型生成对每个文件的概述和意见建议。其中涉及到了读取 Word 文档、使用 GPT 模型等操作,依赖于许多第三方库。该文件也提供了导入依赖的方法,使用该脚本需要安装依赖库 python-docx 和 pywin32。函数功能实现的过程中使用了一些用于调试的变量如 fast_debug可在需要时设置为 True。该脚本文件也提供了对程序功能和贡献者的注释。
## [15/22] 程序概述: crazy_functions\批量总结PDF文档.py
该程序文件名为 `./crazy_functions\批量总结PDF文档.py`主要实现了批量处理PDF文档的功能。具体实现了以下几个函数
1. `is_paragraph_break(match)`:根据给定的匹配结果判断换行符是否表示段落分隔。
2. `normalize_text(text)`:通过将文本特殊符号转换为其基本形式来对文本进行归一化处理。
3. `clean_text(raw_text)`:对从 PDF 提取出的原始文本进行清洗和格式化处理。
4. `解析PDF(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)`对给定的PDF文件进行分析并生成相应的概述。
5. `批量总结PDF文档(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)`批量处理PDF文件对其进行摘要生成。
其中,主要用到了第三方库`pymupdf`对PDF文件进行处理。程序通过调用`fitz.open`函数打开PDF文件使用`page.get_text()`方法获取PDF文本内容。然后使用`clean_text`函数对文本进行清洗和格式化处理,生成最终的摘要。最后,调用`write_results_to_file`函数将历史记录写入文件并输出。
## [16/22] 程序概述: crazy_functions\批量总结PDF文档pdfminer.py
这个程序文件名是./crazy_functions\批量总结PDF文档pdfminer.py是一个用于批量读取PDF文件解析其中的内容并对其进行概括的程序。程序中引用了pdfminer和beautifulsoup4等Python库读取PDF文件并将其转化为文本内容然后利用GPT模型生成摘要语言最终输出一个中文和英文的摘要。程序还有一些错误处理的代码会输出错误信息。
## [17/22] 程序概述: crazy_functions\批量翻译PDF文档_多线程.py
这是一个 Python 程序文件,文件名为 `批量翻译PDF文档_多线程.py`,包含多个函数。主要功能是批量处理 PDF 文档,解析其中的文本,进行清洗和格式化处理,并使用 OpenAI 的 GPT 模型进行翻译。其中使用了多线程技术来提高程序的效率和并行度。
## [18/22] 程序概述: crazy_functions\生成函数注释.py
该程序文件名为./crazy_functions\生成函数注释.py。该文件包含两个函数分别为`生成函数注释``批量生成函数注释`
函数`生成函数注释`包含参数`file_manifest``project_folder``top_p``temperature``chatbot``history``systemPromptTxt`。其中,`file_manifest`为一个包含待处理文件路径的列表,`project_folder`表示项目文件夹路径,`top_p``temperature`是GPT模型参数`chatbot`为与用户交互的聊天机器人,`history`记录聊天机器人与用户的历史记录,`systemPromptTxt`为聊天机器人发送信息前的提示语。`生成函数注释`通过读取文件内容并调用GPT模型对文件中的所有函数生成注释最后使用markdown表格输出结果。函数中还包含一些条件判断和计时器以及调用其他自定义模块的函数。
函数`批量生成函数注释`包含参数`txt``top_p``temperature``chatbot``history``systemPromptTxt``WEB_PORT`。其中,`txt`表示用户输入的项目文件夹路径,其他参数含义与`生成函数注释`中相同。`批量生成函数注释`主要是通过解析项目文件夹,获取所有待处理文件的路径,并调用函数`生成函数注释`对每个文件进行处理,最终生成注释表格输出给用户。
## [19/22] 程序概述: crazy_functions\解析项目源代码.py
该程序文件包含了多个函数用于解析不同类型的项目如Python项目、C项目、Java项目等。其中最核心的函数是`解析源代码()`,它会对给定的一组文件进行分析,并返回对应的结果。具体流程如下:
1. 遍历所有待分析的文件,对每个文件进行如下处理:
1.1 从文件中读取代码内容,构造成一个字符串。
1.2 构造一条GPT请求`predict_no_ui_but_counting_down()`函数发送请求等待GPT回复。
1.3 将GPT回复添加到机器人会话列表中更新历史记录。
1.4 如果不是快速调试模式则等待2秒钟继续分析下一个文件。
2. 如果所有文件都分析完成,则向机器人会话列表中添加一条新消息,提示用户整个分析过程已经结束。
3. 返回机器人会话列表和历史记录。
除此之外,该程序文件还定义了若干个函数,用于针对不同类型的项目进行解析。这些函数会按照不同的方式调用`解析源代码()`函数。例如对于Python项目只需要分析.py文件对于C项目需要同时分析.h和.cpp文件等。每个函数中都会首先根据给定的项目路径读取相应的文件然后调用`解析源代码()`函数进行分析。
## [20/22] 程序概述: crazy_functions\读文章写摘要.py
该程序文件为一个名为“读文章写摘要”的Python函数用于解析项目文件夹中的.tex文件并使用GPT模型生成文章的中英文摘要。函数使用了request_llm.bridge_chatgpt和toolbox模块中的函数并包含两个子函数解析Paper和CatchException。函数参数包括txttop_ptemperaturechatbothistorysystemPromptTxt和WEB_PORT。执行过程中函数首先清空历史然后根据项目文件夹中的.tex文件列表对每个文件调用解析Paper函数生成中文摘要最后根据所有文件的中文摘要调用GPT模型生成英文摘要。函数运行过程中会将结果写入文件并返回聊天机器人和历史记录。
## [21/22] 程序概述: crazy_functions\高级功能函数模板.py
该程序文件为一个高级功能函数模板,文件名为"./crazy_functions\高级功能函数模板.py"。
该文件导入了两个模块,分别是"request_llm.bridge_chatgpt"和"toolbox"。其中"request_llm.bridge_chatgpt"模块包含了一个函数"predict_no_ui_long_connection"该函数用于请求GPT模型进行对话生成。"toolbox"模块包含了三个函数,分别是"catchException"、"report_exception"和"write_results_to_file"函数,这三个函数主要用于异常处理和日志记录等。
该文件定义了一个名为"高阶功能模板函数"的函数,并通过"decorator"装饰器将该函数装饰为一个异常处理函数,可以处理函数执行过程中出现的错误。该函数的作用是生成历史事件查询的问题,并向用户询问历史中哪些事件发生在指定日期,并索要相关图片。在查询完所有日期后,该函数返回所有历史事件及其相关图片的列表。其中,该函数的输入参数包括:
1. txt: 一个字符串,表示当前消息的文本内容。
2. top_p: 一个浮点数表示GPT模型生成文本时的"top_p"参数。
3. temperature: 一个浮点数表示GPT模型生成文本时的"temperature"参数。
4. chatbot: 一个列表,表示当前对话的记录列表。
5. history: 一个列表,表示当前对话的历史记录列表。
6. systemPromptTxt: 一个字符串,表示当前对话的系统提示信息。
7. WEB_PORT: 一个整数表示当前应用程序的WEB端口号。
该函数在执行过程中会先清空历史记录以免输入溢出。然后它会循环5次生成5个历史事件查询的问题并向用户请求输入相关信息。每次询问不携带之前的询问历史。在生成每个问题时该函数会向"chatbot"列表中添加一条消息记录,并设置该记录的初始状态为"[Local Message] waiting gpt response."。然后,该函数会调用"predict_no_ui_long_connection"函数向GPT模型请求生成一段文本并将生成的文本作为回答。如果请求过程中出现异常该函数会忽略异常。最后该函数将问题和回答添加到"chatbot"列表和"history"列表中,并将"chatbot"和"history"列表作为函数的返回值返回。

View File

@@ -1,10 +1,13 @@
import markdown import markdown
import mdtex2html
import threading
import importlib import importlib
import traceback import traceback
import inspect import inspect
import re import re
from latex2mathml.converter import convert as tex2mathml from latex2mathml.converter import convert as tex2mathml
from functools import wraps, lru_cache from functools import wraps, lru_cache
############################### 插件输入输出接驳区 ####################################### ############################### 插件输入输出接驳区 #######################################
class ChatBotWithCookies(list): class ChatBotWithCookies(list):
def __init__(self, cookie): def __init__(self, cookie):
@@ -22,9 +25,9 @@ class ChatBotWithCookies(list):
def ArgsGeneralWrapper(f): def ArgsGeneralWrapper(f):
""" """
装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。
""" """
def decorated(cookies, max_length, llm_model, txt, txt2, top_p, temperature, chatbot, history, system_prompt, *args): def decorated(cookies, txt, txt2, top_p, temperature, chatbot, history, system_prompt, *args):
txt_passon = txt txt_passon = txt
if txt == "" and txt2 != "": txt_passon = txt2 if txt == "" and txt2 != "": txt_passon = txt2
# 引入一个有cookie的chatbot # 引入一个有cookie的chatbot
@@ -34,9 +37,8 @@ def ArgsGeneralWrapper(f):
}) })
llm_kwargs = { llm_kwargs = {
'api_key': cookies['api_key'], 'api_key': cookies['api_key'],
'llm_model': llm_model, 'llm_model': cookies['llm_model'],
'top_p':top_p, 'top_p':top_p,
'max_length': max_length,
'temperature':temperature, 'temperature':temperature,
} }
plugin_kwargs = { plugin_kwargs = {
@@ -53,10 +55,129 @@ def update_ui(chatbot, history, msg='正常', **kwargs): # 刷新界面
""" """
assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时可用clear将其清空然后用for+append循环重新赋值。" assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时可用clear将其清空然后用for+append循环重新赋值。"
yield chatbot.get_cookies(), chatbot, history, msg yield chatbot.get_cookies(), chatbot, history, msg
############################### ################## #######################################
##########################################################################################
def get_reduce_token_percent(text):
"""
* 此函数未来将被弃用
"""
try:
# text = "maximum context length is 4097 tokens. However, your messages resulted in 4870 tokens"
pattern = r"(\d+)\s+tokens\b"
match = re.findall(pattern, text)
EXCEED_ALLO = 500 # 稍微留一点余地,否则在回复时会因余量太少出问题
max_limit = float(match[0]) - EXCEED_ALLO
current_tokens = float(match[1])
ratio = max_limit/current_tokens
assert ratio > 0 and ratio < 1
return ratio, str(int(current_tokens-max_limit))
except:
return 0.5, '不详'
def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, llm_kwargs, history=[], sys_prompt='', long_connection=True):
"""
* 此函数未来将被弃用(替代函数 request_gpt_model_in_new_thread_with_ui_alive 文件 chatgpt_academic/crazy_functions/crazy_utils
调用简单的predict_no_ui接口但是依然保留了些许界面心跳功能当对话太长时会自动采用二分法截断
i_say: 当前输入
i_say_show_user: 显示到对话界面上的当前输入,例如,输入整个文件时,你绝对不想把文件的内容都糊到对话界面上
chatbot: 对话界面句柄
top_p, temperature: gpt参数
history: gpt参数 对话历史
sys_prompt: gpt参数 sys_prompt
long_connection: 是否采用更稳定的连接方式(推荐)(已弃用)
"""
import time
from request_llm.bridge_chatgpt import predict_no_ui_long_connection
from toolbox import get_conf
TIMEOUT_SECONDS, MAX_RETRY = get_conf('TIMEOUT_SECONDS', 'MAX_RETRY')
# 多线程的时候需要一个mutable结构在不同线程之间传递信息
# list就是最简单的mutable结构我们第一个位置放gpt输出第二个位置传递报错信息
mutable = [None, '']
# multi-threading worker
def mt(i_say, history):
while True:
try:
mutable[0] = predict_no_ui_long_connection(
inputs=i_say, llm_kwargs=llm_kwargs, history=history, sys_prompt=sys_prompt)
except ConnectionAbortedError as token_exceeded_error:
# 尝试计算比例,尽可能多地保留文本
p_ratio, n_exceed = get_reduce_token_percent(
str(token_exceeded_error))
if len(history) > 0:
history = [his[int(len(his) * p_ratio):]
for his in history if his is not None]
else:
i_say = i_say[: int(len(i_say) * p_ratio)]
mutable[1] = f'警告文本过长将进行截断Token溢出数{n_exceed},截断比例:{(1-p_ratio):.0%}'
except TimeoutError as e:
mutable[0] = '[Local Message] 请求超时。'
raise TimeoutError
except Exception as e:
mutable[0] = f'[Local Message] 异常:{str(e)}.'
raise RuntimeError(f'[Local Message] 异常:{str(e)}.')
# 创建新线程发出http请求
thread_name = threading.Thread(target=mt, args=(i_say, history))
thread_name.start()
# 原来的线程则负责持续更新UI实现一个超时倒计时并等待新线程的任务完成
cnt = 0
while thread_name.is_alive():
cnt += 1
chatbot[-1] = (i_say_show_user,
f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt % 4)))
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
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):
"""
将对话记录history以Markdown格式写入文件中。如果没有指定文件名则使用当前时间生成文件名。
"""
import os
import time
if file_name is None:
# 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', encoding='utf8') as f:
f.write('# chatGPT 分析报告\n')
for i, content in enumerate(history):
try: # 这个bug没找到触发条件暂时先这样顶一下
if type(content) != str:
content = str(content)
except:
continue
if i % 2 == 0:
f.write('## ')
f.write(content)
f.write('\n\n')
res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}')
print(res)
return res
def regular_txt_to_markdown(text):
"""
将普通文本转换为Markdown格式的文本。
"""
text = text.replace('\n', '\n\n')
text = text.replace('\n\n\n', '\n\n')
text = text.replace('\n\n\n', '\n\n')
return text
def CatchException(f): def CatchException(f):
""" """
装饰器函数捕捉函数f中的异常并封装到一个生成器中返回并显示到聊天当中。 装饰器函数捕捉函数f中的异常并封装到一个生成器中返回并显示到聊天当中。
""" """
@wraps(f) @wraps(f)
def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT): def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
@@ -93,70 +214,9 @@ def HotReload(f):
return decorated return decorated
####################################### 其他小工具 #####################################
def get_reduce_token_percent(text):
"""
* 此函数未来将被弃用
"""
try:
# text = "maximum context length is 4097 tokens. However, your messages resulted in 4870 tokens"
pattern = r"(\d+)\s+tokens\b"
match = re.findall(pattern, text)
EXCEED_ALLO = 500 # 稍微留一点余地,否则在回复时会因余量太少出问题
max_limit = float(match[0]) - EXCEED_ALLO
current_tokens = float(match[1])
ratio = max_limit/current_tokens
assert ratio > 0 and ratio < 1
return ratio, str(int(current_tokens-max_limit))
except:
return 0.5, '不详'
def write_results_to_file(history, file_name=None):
"""
将对话记录history以Markdown格式写入文件中。如果没有指定文件名则使用当前时间生成文件名。
"""
import os
import time
if file_name is None:
# 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', encoding='utf8') as f:
f.write('# chatGPT 分析报告\n')
for i, content in enumerate(history):
try: # 这个bug没找到触发条件暂时先这样顶一下
if type(content) != str:
content = str(content)
except:
continue
if i % 2 == 0:
f.write('## ')
f.write(content)
f.write('\n\n')
res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}')
print(res)
return res
def regular_txt_to_markdown(text):
"""
将普通文本转换为Markdown格式的文本。
"""
text = text.replace('\n', '\n\n')
text = text.replace('\n\n\n', '\n\n')
text = text.replace('\n\n\n', '\n\n')
return text
def report_execption(chatbot, history, a, b): def report_execption(chatbot, history, a, b):
""" """
向chatbot中添加错误信息 向chatbot中添加错误信息
""" """
chatbot.append((a, b)) chatbot.append((a, b))
history.append(a) history.append(a)
@@ -165,7 +225,7 @@ def report_execption(chatbot, history, a, b):
def text_divide_paragraph(text): def text_divide_paragraph(text):
""" """
将文本按照段落分隔符分割开生成带有段落标签的HTML代码。 将文本按照段落分隔符分割开生成带有段落标签的HTML代码。
""" """
if '```' in text: if '```' in text:
# careful input # careful input
@@ -181,7 +241,7 @@ def text_divide_paragraph(text):
def markdown_convertion(txt): def markdown_convertion(txt):
""" """
将Markdown格式的文本转换为HTML格式。如果包含数学公式则先将公式转换为HTML格式。 将Markdown格式的文本转换为HTML格式。如果包含数学公式则先将公式转换为HTML格式。
""" """
pre = '<div class="markdown-body">' pre = '<div class="markdown-body">'
suf = '</div>' suf = '</div>'
@@ -273,7 +333,7 @@ def close_up_code_segment_during_stream(gpt_reply):
def format_io(self, y): def format_io(self, y):
""" """
将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化并将输出部分的Markdown和数学公式转换为HTML格式。 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化并将输出部分的Markdown和数学公式转换为HTML格式。
""" """
if y is None or y == []: if y is None or y == []:
return [] return []
@@ -289,7 +349,7 @@ def format_io(self, y):
def find_free_port(): def find_free_port():
""" """
返回当前系统中可用的未使用端口。 返回当前系统中可用的未使用端口。
""" """
import socket import socket
from contextlib import closing from contextlib import closing
@@ -368,7 +428,7 @@ def find_recent_files(directory):
return recent_files return recent_files
def on_file_uploaded(files, chatbot, txt, txt2, checkboxes): def on_file_uploaded(files, chatbot, txt):
if len(files) == 0: if len(files) == 0:
return chatbot, txt return chatbot, txt
import shutil import shutil
@@ -390,18 +450,13 @@ def on_file_uploaded(files, chatbot, txt, txt2, checkboxes):
dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract') dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')
moved_files = [fp for fp in glob.glob( moved_files = [fp for fp in glob.glob(
'private_upload/**/*', recursive=True)] 'private_upload/**/*', recursive=True)]
if "底部输入区" in checkboxes: txt = f'private_upload/{time_tag}'
txt = ""
txt2 = f'private_upload/{time_tag}'
else:
txt = f'private_upload/{time_tag}'
txt2 = ""
moved_files_str = '\t\n\n'.join(moved_files) moved_files_str = '\t\n\n'.join(moved_files)
chatbot.append(['我上传了文件,请查收', chatbot.append(['我上传了文件,请查收',
f'[Local Message] 收到以下文件: \n\n{moved_files_str}' + f'[Local Message] 收到以下文件: \n\n{moved_files_str}' +
f'\n\n调用路径参数已自动修正到: \n\n{txt}' + f'\n\n调用路径参数已自动修正到: \n\n{txt}' +
f'\n\n现在您点击任意“红颜色”标识的函数插件时,以上文件将被作为输入参数'+err_msg]) f'\n\n现在您点击任意实验功能时,以上文件将被作为输入参数'+err_msg])
return chatbot, txt, txt2 return chatbot, txt
def on_report_generated(files, chatbot): def on_report_generated(files, chatbot):
@@ -414,75 +469,27 @@ def on_report_generated(files, chatbot):
return report_files, chatbot return report_files, chatbot
def is_openai_api_key(key): def is_openai_api_key(key):
# 正确的 API_KEY 是 "sk-" + 48 位大小写字母数字的组合
API_MATCH = re.match(r"sk-[a-zA-Z0-9]{48}$", key) API_MATCH = re.match(r"sk-[a-zA-Z0-9]{48}$", key)
return bool(API_MATCH) return API_MATCH
def is_api2d_key(key):
if key.startswith('fk') and len(key) == 41:
return True
else:
return False
def is_any_api_key(key):
if ',' in key:
keys = key.split(',')
for k in keys:
if is_any_api_key(k): return True
return False
else:
return is_openai_api_key(key) or is_api2d_key(key)
def what_keys(keys):
avail_key_list = {'OpenAI Key':0, "API2D Key":0}
key_list = keys.split(',')
for k in key_list:
if is_openai_api_key(k):
avail_key_list['OpenAI Key'] += 1
for k in key_list:
if is_api2d_key(k):
avail_key_list['API2D Key'] += 1
return f"检测到: OpenAI Key {avail_key_list['OpenAI Key']}API2D Key {avail_key_list['API2D Key']}"
def select_api_key(keys, llm_model):
import random
avail_key_list = []
key_list = keys.split(',')
if llm_model.startswith('gpt-'):
for k in key_list:
if is_openai_api_key(k): avail_key_list.append(k)
if llm_model.startswith('api2d-'):
for k in key_list:
if is_api2d_key(k): avail_key_list.append(k)
if len(avail_key_list) == 0:
raise RuntimeError(f"您提供的api-key不满足要求不包含任何可用于{llm_model}的api-key。您可能选择了错误的模型或请求源。")
api_key = random.choice(avail_key_list) # 随机负载均衡
return api_key
@lru_cache(maxsize=128) @lru_cache(maxsize=128)
def read_single_conf_with_lru_cache(arg): def read_single_conf_with_lru_cache(arg):
from colorful import print亮红, print亮绿, print亮蓝 from colorful import print亮红, print亮绿
try: try:
r = getattr(importlib.import_module('config_private'), arg) r = getattr(importlib.import_module('config_private'), arg)
except: except:
r = getattr(importlib.import_module('config'), arg) r = getattr(importlib.import_module('config'), arg)
# 在读取API_KEY时检查一下是不是忘了改config # 在读取API_KEY时检查一下是不是忘了改config
if arg == 'API_KEY': if arg == 'API_KEY':
print亮蓝(f"[API_KEY] 本项目现已支持OpenAI和API2D的api-key。也支持同时填写多个api-key如API_KEY=\"openai-key1,openai-key2,api2d-key3\"") if is_openai_api_key(r):
print亮蓝(f"[API_KEY] 您既可以在config.py中修改api-key(s)也可以在问题输入区输入临时的api-key(s),然后回车键提交后即可生效。")
if is_any_api_key(r):
print亮绿(f"[API_KEY] 您的 API_KEY 是: {r[:15]}*** API_KEY 导入成功") print亮绿(f"[API_KEY] 您的 API_KEY 是: {r[:15]}*** API_KEY 导入成功")
else: else:
print亮红( "[API_KEY] 正确的 API_KEY 是'sk'开头的51位密钥OpenAI或者 'fk'开头的41位密钥请在config文件中修改API密钥之后再运行。") print亮红( "[API_KEY] 正确的 API_KEY 是 'sk-' + '48 位大小写字母数字' 的组合请在config文件中修改API密钥, 添加海外代理之后再运行。" + \
"如果您刚更新过代码请确保旧版config_private文件中没有遗留任何新增键值")
if arg == 'proxies': if arg == 'proxies':
if r is None: if r is None:
print亮红('[PROXY] 网络代理状态:未配置。无代理状态下很可能无法访问OpenAI家族的模型。建议检查USE_PROXY选项是否修改。') print亮红('[PROXY] 网络代理状态未配置。无代理状态下很可能无法访问。建议检查USE_PROXY选项是否修改。')
else: else:
print亮绿('[PROXY] 网络代理状态:已配置。配置信息如下:', r) print亮绿('[PROXY] 网络代理状态:已配置。配置信息如下:', r)
assert isinstance(r, dict), 'proxies格式错误请注意proxies选项的格式不要遗漏括号。' assert isinstance(r, dict), 'proxies格式错误请注意proxies选项的格式不要遗漏括号。'

View File

@@ -1,5 +1,5 @@
{ {
"version": 3.15, "version": 2.68,
"show_feature": true, "show_feature": true,
"new_feature": "添加联网Google回答问题插件 <-> 修复ChatGLM上下文BUG <-> 添加支持清华ChatGLM和GPT-4 <-> 改进架构支持与多个LLM模型同时对话 <-> 添加支持API2D国内可支持gpt4" "new_feature": "改善理解pdfchatpdf功能 <-> 如果一键更新失败可前往github手动更新"
} }