Files changed (1) hide show
  1. app.py +400 -401
app.py CHANGED
@@ -1,401 +1,400 @@
1
- import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
2
-
3
- help_menu_description = \
4
- """Github源代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic),
5
- 感谢热情的[开发者们❤️](https://github.com/binary-husky/gpt_academic/graphs/contributors).
6
- </br></br>常见问题请查阅[项目Wiki](https://github.com/binary-husky/gpt_academic/wiki),
7
- 如遇到Bug请前往[Bug反馈](https://github.com/binary-husky/gpt_academic/issues).
8
- </br></br>普通对话使用说明: 1. 输入问题; 2. 点击提交
9
- </br></br>基础功能区使用说明: 1. 输入文本; 2. 点击任意基础功能区按钮
10
- </br></br>函数插件区使用说明: 1. 输入路径/问题, 或者上传文件; 2. 点击任意函数插件区按钮
11
- </br></br>虚空终端使用说明: 点击虚空终端, 然后根据提示输入指令, 再次点击虚空终端
12
- </br></br>如何保存对话: 点击保存当前的对话按钮
13
- </br></br>如何语音对话: 请阅读Wiki
14
- </br></br>如何临时更换API_KEY: 在输入区输入临时API_KEY后提交(网页刷新后失效)"""
15
-
16
- def main():
17
- import subprocess, sys
18
- subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://fastly.jsdelivr.net/gh/binary-husky/gradio-fix@gpt-academic/release/gradio-3.32.7-py3-none-any.whl'])
19
- import gradio as gr
20
- if gr.__version__ not in ['3.32.6', '3.32.7']:
21
- raise ModuleNotFoundError("使用项目内置Gradio获取最优体验! 请运行 `pip install -r requirements.txt` 指令安装内置Gradio及其他依赖, 详情信息见requirements.txt.")
22
- from request_llms.bridge_all import predict
23
- from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, load_chat_cookies, DummyWith
24
- # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址
25
- proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')
26
- CHATBOT_HEIGHT, LAYOUT, AVAIL_LLM_MODELS, AUTO_CLEAR_TXT = get_conf('CHATBOT_HEIGHT', 'LAYOUT', 'AVAIL_LLM_MODELS', 'AUTO_CLEAR_TXT')
27
- ENABLE_AUDIO, AUTO_CLEAR_TXT, PATH_LOGGING, AVAIL_THEMES, THEME = get_conf('ENABLE_AUDIO', 'AUTO_CLEAR_TXT', 'PATH_LOGGING', 'AVAIL_THEMES', 'THEME')
28
- DARK_MODE, NUM_CUSTOM_BASIC_BTN, SSL_KEYFILE, SSL_CERTFILE = get_conf('DARK_MODE', 'NUM_CUSTOM_BASIC_BTN', 'SSL_KEYFILE', 'SSL_CERTFILE')
29
- INIT_SYS_PROMPT = get_conf('INIT_SYS_PROMPT')
30
-
31
- # 如果WEB_PORT是-1, 则随机选取WEB端口
32
- PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
33
- from check_proxy import get_current_version
34
- from themes.theme import adjust_theme, advanced_css, theme_declaration
35
- from themes.theme import js_code_for_css_changing, js_code_for_darkmode_init, js_code_for_toggle_darkmode, js_code_for_persistent_cookie_init
36
- from themes.theme import load_dynamic_theme, to_cookie_str, from_cookie_str, init_cookie
37
- title_html = f"<h1 align=\"center\">GPT 学术优化 {get_current_version()}</h1>{theme_declaration}"
38
-
39
- # 问询记录, python 版本建议3.9+(越新越好)
40
- import logging, uuid
41
- os.makedirs(PATH_LOGGING, exist_ok=True)
42
- try:logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, encoding="utf-8", format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
43
- except:logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
44
- # Disable logging output from the 'httpx' logger
45
- logging.getLogger("httpx").setLevel(logging.WARNING)
46
- print(f"所有问询记录将自动保存在本地目录./{PATH_LOGGING}/chat_secrets.log, 请注意自我隐私保护哦!")
47
-
48
- # 一些普通功能模块
49
- from core_functional import get_core_functions
50
- functional = get_core_functions()
51
-
52
- # 高级函数插件
53
- from crazy_functional import get_crazy_functions
54
- DEFAULT_FN_GROUPS = get_conf('DEFAULT_FN_GROUPS')
55
- plugins = get_crazy_functions()
56
- all_plugin_groups = list(set([g for _, plugin in plugins.items() for g in plugin['Group'].split('|')]))
57
- match_group = lambda tags, groups: any([g in groups for g in tags.split('|')])
58
-
59
- # 处理markdown文本格式的转变
60
- gr.Chatbot.postprocess = format_io
61
-
62
- # 做一些外观色彩上的调整
63
- set_theme = adjust_theme()
64
-
65
- # 代理与自动更新
66
- from check_proxy import check_proxy, auto_update, warm_up_modules
67
- proxy_info = check_proxy(proxies)
68
-
69
- gr_L1 = lambda: gr.Row().style()
70
- gr_L2 = lambda scale, elem_id: gr.Column(scale=scale, elem_id=elem_id)
71
- if LAYOUT == "TOP-DOWN":
72
- gr_L1 = lambda: DummyWith()
73
- gr_L2 = lambda scale, elem_id: gr.Row()
74
- CHATBOT_HEIGHT /= 2
75
-
76
- cancel_handles = []
77
- customize_btns = {}
78
- predefined_btns = {}
79
- with gr.Blocks(title="GPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
80
- gr.HTML(title_html)
81
- gr.HTML('''<center><a href="https://huggingface.co/spaces/qingxu98/gpt-academic?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>请您打开此页面后务必点击上方的“复制空间”(Duplicate Space)按钮!<font color="#FF00FF">使用时,先在输入框填入API-KEY然后回车。</font><br/>切忌在“复制空间”(Duplicate Space)之前填入API_KEY或进行提问,否则您的API_KEY将极可能被空间所有者攫取!<br/>支持任意数量的OpenAI的密钥和API2D的密钥共存,例如输入"OpenAI密钥1,API2D密钥2",然后提交,即可同时使用两种模型接口。</center>''')
82
- secret_css, dark_mode, persistent_cookie = gr.Textbox(visible=False), gr.Textbox(DARK_MODE, visible=False), gr.Textbox(visible=False)
83
- cookies = gr.State(load_chat_cookies())
84
- with gr_L1():
85
- with gr_L2(scale=2, elem_id="gpt-chat"):
86
- chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}", elem_id="gpt-chatbot")
87
- if LAYOUT == "TOP-DOWN": chatbot.style(height=CHATBOT_HEIGHT)
88
- history = gr.State([])
89
- with gr_L2(scale=1, elem_id="gpt-panel"):
90
- with gr.Accordion("输入区", open=True, elem_id="input-panel") as area_input_primary:
91
- with gr.Row():
92
- txt = gr.Textbox(show_label=False, lines=2, placeholder="输入问题或API密钥,输入多个密钥时,用英文逗号间隔。支持多个OpenAI密钥共存。").style(container=False)
93
- with gr.Row():
94
- submitBtn = gr.Button("提交", elem_id="elem_submit", variant="primary")
95
- with gr.Row():
96
- resetBtn = gr.Button("重置", elem_id="elem_reset", variant="secondary"); resetBtn.style(size="sm")
97
- stopBtn = gr.Button("停止", elem_id="elem_stop", variant="secondary"); stopBtn.style(size="sm")
98
- clearBtn = gr.Button("清除", elem_id="elem_clear", variant="secondary", visible=False); clearBtn.style(size="sm")
99
- if ENABLE_AUDIO:
100
- with gr.Row():
101
- audio_mic = gr.Audio(source="microphone", type="numpy", elem_id="elem_audio", streaming=True, show_label=False).style(container=False)
102
- with gr.Row():
103
- status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}", elem_id="state-panel")
104
- with gr.Accordion("基础功能区", open=True, elem_id="basic-panel") as area_basic_fn:
105
- with gr.Row():
106
- for k in range(NUM_CUSTOM_BASIC_BTN):
107
- customize_btn = gr.Button("自定义按钮" + str(k+1), visible=False, variant="secondary", info_str=f'基础功能区: 自定义按钮')
108
- customize_btn.style(size="sm")
109
- customize_btns.update({"自定义按钮" + str(k+1): customize_btn})
110
- for k in functional:
111
- if ("Visible" in functional[k]) and (not functional[k]["Visible"]): continue
112
- variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
113
- functional[k]["Button"] = gr.Button(k, variant=variant, info_str=f'基础功能区: {k}')
114
- functional[k]["Button"].style(size="sm")
115
- predefined_btns.update({k: functional[k]["Button"]})
116
- with gr.Accordion("函数插件区", open=True, elem_id="plugin-panel") as area_crazy_fn:
117
- with gr.Row():
118
- gr.Markdown("插件可读取“输入区”文本/路径作为参数(上传文件自动修正路径)")
119
- with gr.Row(elem_id="input-plugin-group"):
120
- plugin_group_sel = gr.Dropdown(choices=all_plugin_groups, label='', show_label=False, value=DEFAULT_FN_GROUPS,
121
- multiselect=True, interactive=True, elem_classes='normal_mut_select').style(container=False)
122
- with gr.Row():
123
- for k, plugin in plugins.items():
124
- if not plugin.get("AsButton", True): continue
125
- visible = True if match_group(plugin['Group'], DEFAULT_FN_GROUPS) else False
126
- variant = plugins[k]["Color"] if "Color" in plugin else "secondary"
127
- info = plugins[k].get("Info", k)
128
- plugin['Button'] = plugins[k]['Button'] = gr.Button(k, variant=variant,
129
- visible=visible, info_str=f'函数插件区: {info}').style(size="sm")
130
- with gr.Row():
131
- with gr.Accordion("更多函数插件", open=True):
132
- dropdown_fn_list = []
133
- for k, plugin in plugins.items():
134
- if not match_group(plugin['Group'], DEFAULT_FN_GROUPS): continue
135
- if not plugin.get("AsButton", True): dropdown_fn_list.append(k) # 排除已经是按钮的插件
136
- elif plugin.get('AdvancedArgs', False): dropdown_fn_list.append(k) # 对于需要高级参数的插件,亦在下拉菜单中显示
137
- with gr.Row():
138
- dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="", show_label=False).style(container=False)
139
- with gr.Row():
140
- plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False,
141
- placeholder="这里是特殊函数插件的高级参数输入区").style(container=False)
142
- with gr.Row():
143
- switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary").style(size="sm")
144
- with gr.Row():
145
- with gr.Accordion("点击展开“文件下载区”。", open=False) as area_file_up:
146
- file_upload = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload")
147
-
148
-
149
- with gr.Floating(init_x="0%", init_y="0%", visible=True, width=None, drag="forbidden", elem_id="tooltip"):
150
- with gr.Row():
151
- with gr.Tab("上传文件", elem_id="interact-panel"):
152
- gr.Markdown("请上传本地文件/压缩包供“函数插件区”功能调用。请注意: 上传文件后会自动把输入区修改为相应路径。")
153
- file_upload_2 = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload_float")
154
-
155
- with gr.Tab("更换模型", elem_id="interact-panel"):
156
- md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False)
157
- top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
158
- temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
159
- max_length_sl = gr.Slider(minimum=256, maximum=1024*32, value=4096, step=128, interactive=True, label="Local LLM MaxLength",)
160
- system_prompt = gr.Textbox(show_label=True, lines=2, placeholder=f"System Prompt", label="System prompt", value=INIT_SYS_PROMPT)
161
-
162
- with gr.Tab("界面外观", elem_id="interact-panel"):
163
- theme_dropdown = gr.Dropdown(AVAIL_THEMES, value=THEME, label="更换UI主题").style(container=False)
164
- checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "浮动输入区", "输入清除键", "插件参数区"],
165
- value=["基础功能区", "函数插件区"], label="显示/隐藏功能区", elem_id='cbs').style(container=False)
166
- checkboxes_2 = gr.CheckboxGroup(["自定义菜单"],
167
- value=[], label="显示/隐藏自定义菜单", elem_id='cbsc').style(container=False)
168
- dark_mode_btn = gr.Button("切换界面明暗 ☀", variant="secondary").style(size="sm")
169
- dark_mode_btn.click(None, None, None, _js=js_code_for_toggle_darkmode)
170
- with gr.Tab("帮助", elem_id="interact-panel"):
171
- gr.Markdown(help_menu_description)
172
-
173
- with gr.Floating(init_x="20%", init_y="50%", visible=False, width="40%", drag="top") as area_input_secondary:
174
- with gr.Accordion("浮动输入区", open=True, elem_id="input-panel2"):
175
- with gr.Row() as row:
176
- row.style(equal_height=True)
177
- with gr.Column(scale=10):
178
- txt2 = gr.Textbox(show_label=False, placeholder="Input question here.",
179
- elem_id='user_input_float', lines=8, label="输入区2").style(container=False)
180
- with gr.Column(scale=1, min_width=40):
181
- submitBtn2 = gr.Button("提交", variant="primary"); submitBtn2.style(size="sm")
182
- resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn2.style(size="sm")
183
- stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn2.style(size="sm")
184
- clearBtn2 = gr.Button("清除", variant="secondary", visible=False); clearBtn2.style(size="sm")
185
-
186
-
187
- with gr.Floating(init_x="20%", init_y="50%", visible=False, width="40%", drag="top") as area_customize:
188
- with gr.Accordion("自定义菜单", open=True, elem_id="edit-panel"):
189
- with gr.Row() as row:
190
- with gr.Column(scale=10):
191
- AVAIL_BTN = [btn for btn in customize_btns.keys()] + [k for k in functional]
192
- basic_btn_dropdown = gr.Dropdown(AVAIL_BTN, value="自定义按钮1", label="选择一个需要自定义基础功能区按钮").style(container=False)
193
- basic_fn_title = gr.Textbox(show_label=False, placeholder="输入新按钮名称", lines=1).style(container=False)
194
- basic_fn_prefix = gr.Textbox(show_label=False, placeholder="输入新提示前缀", lines=4).style(container=False)
195
- basic_fn_suffix = gr.Textbox(show_label=False, placeholder="输入新提示后缀", lines=4).style(container=False)
196
- with gr.Column(scale=1, min_width=70):
197
- basic_fn_confirm = gr.Button("确认并保存", variant="primary"); basic_fn_confirm.style(size="sm")
198
- basic_fn_load = gr.Button("加载已保存", variant="primary"); basic_fn_load.style(size="sm")
199
- def assign_btn(persistent_cookie_, cookies_, basic_btn_dropdown_, basic_fn_title, basic_fn_prefix, basic_fn_suffix):
200
- ret = {}
201
- customize_fn_overwrite_ = cookies_['customize_fn_overwrite']
202
- customize_fn_overwrite_.update({
203
- basic_btn_dropdown_:
204
- {
205
- "Title":basic_fn_title,
206
- "Prefix":basic_fn_prefix,
207
- "Suffix":basic_fn_suffix,
208
- }
209
- }
210
- )
211
- cookies_.update(customize_fn_overwrite_)
212
- if basic_btn_dropdown_ in customize_btns:
213
- ret.update({customize_btns[basic_btn_dropdown_]: gr.update(visible=True, value=basic_fn_title)})
214
- else:
215
- ret.update({predefined_btns[basic_btn_dropdown_]: gr.update(visible=True, value=basic_fn_title)})
216
- ret.update({cookies: cookies_})
217
- try: persistent_cookie_ = from_cookie_str(persistent_cookie_) # persistent cookie to dict
218
- except: persistent_cookie_ = {}
219
- persistent_cookie_["custom_bnt"] = customize_fn_overwrite_ # dict update new value
220
- persistent_cookie_ = to_cookie_str(persistent_cookie_) # persistent cookie to dict
221
- ret.update({persistent_cookie: persistent_cookie_}) # write persistent cookie
222
- return ret
223
-
224
- def reflesh_btn(persistent_cookie_, cookies_):
225
- ret = {}
226
- for k in customize_btns:
227
- ret.update({customize_btns[k]: gr.update(visible=False, value="")})
228
-
229
- try: persistent_cookie_ = from_cookie_str(persistent_cookie_) # persistent cookie to dict
230
- except: return ret
231
-
232
- customize_fn_overwrite_ = persistent_cookie_.get("custom_bnt", {})
233
- cookies_['customize_fn_overwrite'] = customize_fn_overwrite_
234
- ret.update({cookies: cookies_})
235
-
236
- for k,v in persistent_cookie_["custom_bnt"].items():
237
- if v['Title'] == "": continue
238
- if k in customize_btns: ret.update({customize_btns[k]: gr.update(visible=True, value=v['Title'])})
239
- else: ret.update({predefined_btns[k]: gr.update(visible=True, value=v['Title'])})
240
- return ret
241
-
242
- basic_fn_load.click(reflesh_btn, [persistent_cookie, cookies], [cookies, *customize_btns.values(), *predefined_btns.values()])
243
- h = basic_fn_confirm.click(assign_btn, [persistent_cookie, cookies, basic_btn_dropdown, basic_fn_title, basic_fn_prefix, basic_fn_suffix],
244
- [persistent_cookie, cookies, *customize_btns.values(), *predefined_btns.values()])
245
- # save persistent cookie
246
- h.then(None, [persistent_cookie], None, _js="""(persistent_cookie)=>{setCookie("persistent_cookie", persistent_cookie, 5);}""")
247
-
248
- # 功能区显示开关与功能区的互动
249
- def fn_area_visibility(a):
250
- ret = {}
251
- ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
252
- ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
253
- ret.update({area_input_primary: gr.update(visible=("浮动输入区" not in a))})
254
- ret.update({area_input_secondary: gr.update(visible=("浮动输入区" in a))})
255
- ret.update({clearBtn: gr.update(visible=("输入清除键" in a))})
256
- ret.update({clearBtn2: gr.update(visible=("输入清除键" in a))})
257
- ret.update({plugin_advanced_arg: gr.update(visible=("插件参数区" in a))})
258
- if "浮动输入区" in a: ret.update({txt: gr.update(value="")})
259
- return ret
260
- checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2, plugin_advanced_arg] )
261
-
262
- # 功能区显示开关与功能区的互动
263
- def fn_area_visibility_2(a):
264
- ret = {}
265
- ret.update({area_customize: gr.update(visible=("自定义菜单" in a))})
266
- return ret
267
- checkboxes_2.select(fn_area_visibility_2, [checkboxes_2], [area_customize] )
268
-
269
- # 整理反复出现的控件句柄组合
270
- input_combo = [cookies, max_length_sl, md_dropdown, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg]
271
- output_combo = [cookies, chatbot, history, status]
272
- predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True)], outputs=output_combo)
273
- # 提交按钮、重置按钮
274
- cancel_handles.append(txt.submit(**predict_args))
275
- cancel_handles.append(txt2.submit(**predict_args))
276
- cancel_handles.append(submitBtn.click(**predict_args))
277
- cancel_handles.append(submitBtn2.click(**predict_args))
278
- resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
279
- resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
280
- clearBtn.click(lambda: ("",""), None, [txt, txt2])
281
- clearBtn2.click(lambda: ("",""), None, [txt, txt2])
282
- if AUTO_CLEAR_TXT:
283
- submitBtn.click(lambda: ("",""), None, [txt, txt2])
284
- submitBtn2.click(lambda: ("",""), None, [txt, txt2])
285
- txt.submit(lambda: ("",""), None, [txt, txt2])
286
- txt2.submit(lambda: ("",""), None, [txt, txt2])
287
- # 基础功能区的回调函数注册
288
- for k in functional:
289
- if ("Visible" in functional[k]) and (not functional[k]["Visible"]): continue
290
- click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)
291
- cancel_handles.append(click_handle)
292
- for btn in customize_btns.values():
293
- click_handle = btn.click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(btn.value)], outputs=output_combo)
294
- cancel_handles.append(click_handle)
295
- # 文件上传区,接收文件后与chatbot的互动
296
- file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies]).then(None, None, None, _js=r"()=>{toast_push('上传完毕 ...'); cancel_loading_status();}")
297
- file_upload_2.upload(on_file_uploaded, [file_upload_2, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies]).then(None, None, None, _js=r"()=>{toast_push('上传完毕 ...'); cancel_loading_status();}")
298
- # 函数插件-固定按钮区
299
- for k in plugins:
300
- if not plugins[k].get("AsButton", True): continue
301
- click_handle = plugins[k]["Button"].click(ArgsGeneralWrapper(plugins[k]["Function"]), [*input_combo], output_combo)
302
- click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])
303
- cancel_handles.append(click_handle)
304
- # 函数插件-下拉菜单与随变按钮的互动
305
- def on_dropdown_changed(k):
306
- variant = plugins[k]["Color"] if "Color" in plugins[k] else "secondary"
307
- info = plugins[k].get("Info", k)
308
- ret = {switchy_bt: gr.update(value=k, variant=variant, info_str=f'函数插件区: {info}')}
309
- if plugins[k].get("AdvancedArgs", False): # 是否唤起高级插件参数区
310
- ret.update({plugin_advanced_arg: gr.update(visible=True, label=f"插件[{k}]的高级参数说明:" + plugins[k].get("ArgsReminder", [f"没有提供高级参数功能说明"]))})
311
- else:
312
- ret.update({plugin_advanced_arg: gr.update(visible=False, label=f"插件[{k}]不需要高级参数。")})
313
- return ret
314
- dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt, plugin_advanced_arg] )
315
-
316
- def on_md_dropdown_changed(k):
317
- return {chatbot: gr.update(label="当前模型:"+k)}
318
- md_dropdown.select(on_md_dropdown_changed, [md_dropdown], [chatbot] )
319
-
320
- def on_theme_dropdown_changed(theme, secret_css):
321
- adjust_theme, css_part1, _, adjust_dynamic_theme = load_dynamic_theme(theme)
322
- if adjust_dynamic_theme:
323
- css_part2 = adjust_dynamic_theme._get_theme_css()
324
- else:
325
- css_part2 = adjust_theme()._get_theme_css()
326
- return css_part2 + css_part1
327
-
328
- theme_handle = theme_dropdown.select(on_theme_dropdown_changed, [theme_dropdown, secret_css], [secret_css])
329
- theme_handle.then(
330
- None,
331
- [secret_css],
332
- None,
333
- _js=js_code_for_css_changing
334
- )
335
- # 随变按钮的回调函数注册
336
- def route(request: gr.Request, k, *args, **kwargs):
337
- if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
338
- yield from ArgsGeneralWrapper(plugins[k]["Function"])(request, *args, **kwargs)
339
- click_handle = switchy_bt.click(route,[switchy_bt, *input_combo], output_combo)
340
- click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])
341
- cancel_handles.append(click_handle)
342
- # 终止按钮的回调函数注册
343
- stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
344
- stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
345
- plugins_as_btn = {name:plugin for name, plugin in plugins.items() if plugin.get('Button', None)}
346
- def on_group_change(group_list):
347
- btn_list = []
348
- fns_list = []
349
- if not group_list: # 处理特殊情况:没有选择任何插件组
350
- return [*[plugin['Button'].update(visible=False) for _, plugin in plugins_as_btn.items()], gr.Dropdown.update(choices=[])]
351
- for k, plugin in plugins.items():
352
- if plugin.get("AsButton", True):
353
- btn_list.append(plugin['Button'].update(visible=match_group(plugin['Group'], group_list))) # 刷新按钮
354
- if plugin.get('AdvancedArgs', False): dropdown_fn_list.append(k) # 对于需要高级参数的插件,亦在下拉菜单中显示
355
- elif match_group(plugin['Group'], group_list): fns_list.append(k) # 刷新下拉列表
356
- return [*btn_list, gr.Dropdown.update(choices=fns_list)]
357
- plugin_group_sel.select(fn=on_group_change, inputs=[plugin_group_sel], outputs=[*[plugin['Button'] for name, plugin in plugins_as_btn.items()], dropdown])
358
- if ENABLE_AUDIO:
359
- from crazy_functions.live_audio.audio_io import RealtimeAudioDistribution
360
- rad = RealtimeAudioDistribution()
361
- def deal_audio(audio, cookies):
362
- rad.feed(cookies['uuid'].hex, audio)
363
- audio_mic.stream(deal_audio, inputs=[audio_mic, cookies])
364
-
365
-
366
- demo.load(init_cookie, inputs=[cookies, chatbot], outputs=[cookies])
367
- darkmode_js = js_code_for_darkmode_init
368
- demo.load(None, inputs=None, outputs=[persistent_cookie], _js=js_code_for_persistent_cookie_init)
369
- demo.load(None, inputs=[dark_mode], outputs=None, _js=darkmode_js) # 配置暗色主题或亮色主题
370
- demo.load(None, inputs=[gr.Textbox(LAYOUT, visible=False)], outputs=None, _js='(LAYOUT)=>{GptAcademicJavaScriptInit(LAYOUT);}')
371
-
372
- # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
373
- def run_delayed_tasks():
374
- import threading, webbrowser, time
375
- print(f"如果浏览器没有自动打开,请复制并转到以下URL:")
376
- if DARK_MODE: print(f"\t「暗色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
377
- else: print(f"\t「亮色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
378
-
379
- def auto_updates(): time.sleep(0); auto_update()
380
- def open_browser(): time.sleep(2); webbrowser.open_new_tab(f"http://localhost:{PORT}")
381
- def warm_up_mods(): time.sleep(6); warm_up_modules()
382
-
383
- threading.Thread(target=auto_updates, name="self-upgrade", daemon=True).start() # 查看自动更新
384
- threading.Thread(target=open_browser, name="open-browser", daemon=True).start() # 打开浏览器页面
385
- threading.Thread(target=warm_up_mods, name="warm-up", daemon=True).start() # 预热tiktoken模块
386
-
387
- run_delayed_tasks()
388
- demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=False, favicon_path="docs/logo.png", blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile"])
389
-
390
-
391
- # 如果需要在二级路径下运行
392
- # CUSTOM_PATH = get_conf('CUSTOM_PATH')
393
- # if CUSTOM_PATH != "/":
394
- # from toolbox import run_gradio_in_subpath
395
- # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH)
396
- # else:
397
- # demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png",
398
- # blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile",f"{PATH_LOGGING}/admin"])
399
-
400
- if __name__ == "__main__":
401
- main()
 
1
+ import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
2
+
3
+ help_menu_description = \
4
+ """Github源代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic),
5
+ 感谢热情的[开发者们❤️](https://github.com/binary-husky/gpt_academic/graphs/contributors).
6
+ </br></br>常见问题请查阅[项目Wiki](https://github.com/binary-husky/gpt_academic/wiki),
7
+ 如遇到Bug请前往[Bug反馈](https://github.com/binary-husky/gpt_academic/issues).
8
+ </br></br>普通对话使用说明: 1. 输入问题; 2. 点击提交
9
+ </br></br>基础功能区使用说明: 1. 输入文本; 2. 点击任意基础功能区按钮
10
+ </br></br>函数插件区使用说明: 1. 输入路径/问题, 或者上传文件; 2. 点击任意函数插件区按钮
11
+ </br></br>虚空终端使用说明: 点击虚空终端, 然后根据提示输入指令, 再次点击虚空终端
12
+ </br></br>如何保存对话: 点击保存当前的对话按钮
13
+ </br></br>如何语音对话: 请阅读Wiki
14
+ </br></br>如何临时更换API_KEY: 在输入区输入临时API_KEY后提交(网页刷新后失效)"""
15
+
16
+ def main():
17
+ import subprocess, sys
18
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://fastly.jsdelivr.net/gh/binary-husky/gradio-fix@gpt-academic/release/gradio-3.32.7-py3-none-any.whl'])
19
+ import gradio as gr
20
+ if gr.__version__ not in ['3.32.6', '3.32.7']:
21
+ raise ModuleNotFoundError("使用项目内置Gradio获取最优体验! 请运行 `pip install -r requirements.txt` 指令安装内置Gradio及其他依赖, 详情信息见requirements.txt.")
22
+ from request_llms.bridge_all import predict
23
+ from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, load_chat_cookies, DummyWith
24
+ # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址
25
+ proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')
26
+ CHATBOT_HEIGHT, LAYOUT, AVAIL_LLM_MODELS, AUTO_CLEAR_TXT = get_conf('CHATBOT_HEIGHT', 'LAYOUT', 'AVAIL_LLM_MODELS', 'AUTO_CLEAR_TXT')
27
+ ENABLE_AUDIO, AUTO_CLEAR_TXT, PATH_LOGGING, AVAIL_THEMES, THEME = get_conf('ENABLE_AUDIO', 'AUTO_CLEAR_TXT', 'PATH_LOGGING', 'AVAIL_THEMES', 'THEME')
28
+ DARK_MODE, NUM_CUSTOM_BASIC_BTN, SSL_KEYFILE, SSL_CERTFILE = get_conf('DARK_MODE', 'NUM_CUSTOM_BASIC_BTN', 'SSL_KEYFILE', 'SSL_CERTFILE')
29
+ INIT_SYS_PROMPT = get_conf('INIT_SYS_PROMPT')
30
+
31
+ # 如果WEB_PORT是-1, 则随机选取WEB端口
32
+ PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
33
+ from check_proxy import get_current_version
34
+ from themes.theme import adjust_theme, advanced_css, theme_declaration
35
+ from themes.theme import js_code_for_css_changing, js_code_for_darkmode_init, js_code_for_toggle_darkmode, js_code_for_persistent_cookie_init
36
+ from themes.theme import load_dynamic_theme, to_cookie_str, from_cookie_str, init_cookie
37
+ title_html = f"<h1 align=\"center\">桂工'GPT 学术优化 {get_current_version()}</h1>{theme_declaration}"
38
+
39
+ # 问询记录, python 版本建议3.9+(越新越好)
40
+ import logging, uuid
41
+ os.makedirs(PATH_LOGGING, exist_ok=True)
42
+ try:logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, encoding="utf-8", format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
43
+ except:logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
44
+ # Disable logging output from the 'httpx' logger
45
+ logging.getLogger("httpx").setLevel(logging.WARNING)
46
+ print(f"所有问询记录将自动保存在本地目录./{PATH_LOGGING}/chat_secrets.log, 请注意自我隐私保护哦!")
47
+
48
+ # 一些普通功能模块
49
+ from core_functional import get_core_functions
50
+ functional = get_core_functions()
51
+
52
+ # 高级函数插件
53
+ from crazy_functional import get_crazy_functions
54
+ DEFAULT_FN_GROUPS = get_conf('DEFAULT_FN_GROUPS')
55
+ plugins = get_crazy_functions()
56
+ all_plugin_groups = list(set([g for _, plugin in plugins.items() for g in plugin['Group'].split('|')]))
57
+ match_group = lambda tags, groups: any([g in groups for g in tags.split('|')])
58
+
59
+ # 处理markdown文本格式的转变
60
+ gr.Chatbot.postprocess = format_io
61
+
62
+ # 做一些外观色彩上的调整
63
+ set_theme = adjust_theme()
64
+
65
+ # 代理与自动更新
66
+ from check_proxy import check_proxy, auto_update, warm_up_modules
67
+ proxy_info = check_proxy(proxies)
68
+
69
+ gr_L1 = lambda: gr.Row().style()
70
+ gr_L2 = lambda scale, elem_id: gr.Column(scale=scale, elem_id=elem_id)
71
+ if LAYOUT == "TOP-DOWN":
72
+ gr_L1 = lambda: DummyWith()
73
+ gr_L2 = lambda scale, elem_id: gr.Row()
74
+ CHATBOT_HEIGHT /= 2
75
+
76
+ cancel_handles = []
77
+ customize_btns = {}
78
+ predefined_btns = {}
79
+ with gr.Blocks(title="桂工'GPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
80
+ gr.HTML(title_html)
81
+ secret_css, dark_mode, persistent_cookie = gr.Textbox(visible=False), gr.Textbox(DARK_MODE, visible=False), gr.Textbox(visible=False)
82
+ cookies = gr.State(load_chat_cookies())
83
+ with gr_L1():
84
+ with gr_L2(scale=2, elem_id="gpt-chat"):
85
+ chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}", elem_id="gpt-chatbot")
86
+ if LAYOUT == "TOP-DOWN": chatbot.style(height=CHATBOT_HEIGHT)
87
+ history = gr.State([])
88
+ with gr_L2(scale=1, elem_id="gpt-panel"):
89
+ with gr.Accordion("输入区", open=True, elem_id="input-panel") as area_input_primary:
90
+ with gr.Row():
91
+ txt = gr.Textbox(show_label=False, lines=2, placeholder="输入问题或API密钥,输入多个密钥时,用英文逗号间隔。支持多个OpenAI密钥共存。").style(container=False)
92
+ with gr.Row():
93
+ submitBtn = gr.Button("提交", elem_id="elem_submit", variant="primary")
94
+ with gr.Row():
95
+ resetBtn = gr.Button("重置", elem_id="elem_reset", variant="secondary"); resetBtn.style(size="sm")
96
+ stopBtn = gr.Button("停止", elem_id="elem_stop", variant="secondary"); stopBtn.style(size="sm")
97
+ clearBtn = gr.Button("清除", elem_id="elem_clear", variant="secondary", visible=False); clearBtn.style(size="sm")
98
+ if ENABLE_AUDIO:
99
+ with gr.Row():
100
+ audio_mic = gr.Audio(source="microphone", type="numpy", elem_id="elem_audio", streaming=True, show_label=False).style(container=False)
101
+ with gr.Row():
102
+ status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}", elem_id="state-panel")
103
+ with gr.Accordion("基础功能区", open=True, elem_id="basic-panel") as area_basic_fn:
104
+ with gr.Row():
105
+ for k in range(NUM_CUSTOM_BASIC_BTN):
106
+ customize_btn = gr.Button("自定义按钮" + str(k+1), visible=False, variant="secondary", info_str=f'基础功能区: 自定义按钮')
107
+ customize_btn.style(size="sm")
108
+ customize_btns.update({"自定义按钮" + str(k+1): customize_btn})
109
+ for k in functional:
110
+ if ("Visible" in functional[k]) and (not functional[k]["Visible"]): continue
111
+ variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
112
+ functional[k]["Button"] = gr.Button(k, variant=variant, info_str=f'基础功能区: {k}')
113
+ functional[k]["Button"].style(size="sm")
114
+ predefined_btns.update({k: functional[k]["Button"]})
115
+ with gr.Accordion("函数插件区", open=True, elem_id="plugin-panel") as area_crazy_fn:
116
+ with gr.Row():
117
+ gr.Markdown("插件可读取“输入区”文本/路径作为参数(上传文件自动修正路径)")
118
+ with gr.Row(elem_id="input-plugin-group"):
119
+ plugin_group_sel = gr.Dropdown(choices=all_plugin_groups, label='', show_label=False, value=DEFAULT_FN_GROUPS,
120
+ multiselect=True, interactive=True, elem_classes='normal_mut_select').style(container=False)
121
+ with gr.Row():
122
+ for k, plugin in plugins.items():
123
+ if not plugin.get("AsButton", True): continue
124
+ visible = True if match_group(plugin['Group'], DEFAULT_FN_GROUPS) else False
125
+ variant = plugins[k]["Color"] if "Color" in plugin else "secondary"
126
+ info = plugins[k].get("Info", k)
127
+ plugin['Button'] = plugins[k]['Button'] = gr.Button(k, variant=variant,
128
+ visible=visible, info_str=f'函数插件区: {info}').style(size="sm")
129
+ with gr.Row():
130
+ with gr.Accordion("更多函数插件", open=True):
131
+ dropdown_fn_list = []
132
+ for k, plugin in plugins.items():
133
+ if not match_group(plugin['Group'], DEFAULT_FN_GROUPS): continue
134
+ if not plugin.get("AsButton", True): dropdown_fn_list.append(k) # 排除已经是按钮的插件
135
+ elif plugin.get('AdvancedArgs', False): dropdown_fn_list.append(k) # 对于需要高级参数的插件,亦在下拉菜单中显示
136
+ with gr.Row():
137
+ dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="", show_label=False).style(container=False)
138
+ with gr.Row():
139
+ plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False,
140
+ placeholder="这里是特殊函数插件的高级参数输入区").style(container=False)
141
+ with gr.Row():
142
+ switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary").style(size="sm")
143
+ with gr.Row():
144
+ with gr.Accordion("点击展开“文件下载区”。", open=False) as area_file_up:
145
+ file_upload = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload")
146
+
147
+
148
+ with gr.Floating(init_x="0%", init_y="0%", visible=True, width=None, drag="forbidden", elem_id="tooltip"):
149
+ with gr.Row():
150
+ with gr.Tab("上传文件", elem_id="interact-panel"):
151
+ gr.Markdown("请上传本地文件/压缩包供“函数插件区”功能调用。请注意: 上传文件后会自动把输入区修改为相应路径。")
152
+ file_upload_2 = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload_float")
153
+
154
+ with gr.Tab("更换模型", elem_id="interact-panel"):
155
+ md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False)
156
+ top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
157
+ temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
158
+ max_length_sl = gr.Slider(minimum=256, maximum=1024*32, value=4096, step=128, interactive=True, label="Local LLM MaxLength",)
159
+ system_prompt = gr.Textbox(show_label=True, lines=2, placeholder=f"System Prompt", label="System prompt", value=INIT_SYS_PROMPT)
160
+
161
+ with gr.Tab("界面外观", elem_id="interact-panel"):
162
+ theme_dropdown = gr.Dropdown(AVAIL_THEMES, value=THEME, label="更换UI主题").style(container=False)
163
+ checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "浮动输入区", "输入清除键", "插件参数区"],
164
+ value=["基础功能区", "函数插件区"], label="显示/隐藏功能区", elem_id='cbs').style(container=False)
165
+ checkboxes_2 = gr.CheckboxGroup(["自定义菜单"],
166
+ value=[], label="显示/隐藏自定义菜单", elem_id='cbsc').style(container=False)
167
+ dark_mode_btn = gr.Button("切换界面明暗 ☀", variant="secondary").style(size="sm")
168
+ dark_mode_btn.click(None, None, None, _js=js_code_for_toggle_darkmode)
169
+ with gr.Tab("帮助", elem_id="interact-panel"):
170
+ gr.Markdown(help_menu_description)
171
+
172
+ with gr.Floating(init_x="20%", init_y="50%", visible=False, width="40%", drag="top") as area_input_secondary:
173
+ with gr.Accordion("浮动输入区", open=True, elem_id="input-panel2"):
174
+ with gr.Row() as row:
175
+ row.style(equal_height=True)
176
+ with gr.Column(scale=10):
177
+ txt2 = gr.Textbox(show_label=False, placeholder="Input question here.",
178
+ elem_id='user_input_float', lines=8, label="输入区2").style(container=False)
179
+ with gr.Column(scale=1, min_width=40):
180
+ submitBtn2 = gr.Button("提交", variant="primary"); submitBtn2.style(size="sm")
181
+ resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn2.style(size="sm")
182
+ stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn2.style(size="sm")
183
+ clearBtn2 = gr.Button("清除", variant="secondary", visible=False); clearBtn2.style(size="sm")
184
+
185
+
186
+ with gr.Floating(init_x="20%", init_y="50%", visible=False, width="40%", drag="top") as area_customize:
187
+ with gr.Accordion("自定义菜单", open=True, elem_id="edit-panel"):
188
+ with gr.Row() as row:
189
+ with gr.Column(scale=10):
190
+ AVAIL_BTN = [btn for btn in customize_btns.keys()] + [k for k in functional]
191
+ basic_btn_dropdown = gr.Dropdown(AVAIL_BTN, value="自定义按钮1", label="选择一个需要自定义基础功能区按钮").style(container=False)
192
+ basic_fn_title = gr.Textbox(show_label=False, placeholder="输入新按钮名称", lines=1).style(container=False)
193
+ basic_fn_prefix = gr.Textbox(show_label=False, placeholder="输入新提示前缀", lines=4).style(container=False)
194
+ basic_fn_suffix = gr.Textbox(show_label=False, placeholder="输入新提示后缀", lines=4).style(container=False)
195
+ with gr.Column(scale=1, min_width=70):
196
+ basic_fn_confirm = gr.Button("确认并保存", variant="primary"); basic_fn_confirm.style(size="sm")
197
+ basic_fn_load = gr.Button("加载已保存", variant="primary"); basic_fn_load.style(size="sm")
198
+ def assign_btn(persistent_cookie_, cookies_, basic_btn_dropdown_, basic_fn_title, basic_fn_prefix, basic_fn_suffix):
199
+ ret = {}
200
+ customize_fn_overwrite_ = cookies_['customize_fn_overwrite']
201
+ customize_fn_overwrite_.update({
202
+ basic_btn_dropdown_:
203
+ {
204
+ "Title":basic_fn_title,
205
+ "Prefix":basic_fn_prefix,
206
+ "Suffix":basic_fn_suffix,
207
+ }
208
+ }
209
+ )
210
+ cookies_.update(customize_fn_overwrite_)
211
+ if basic_btn_dropdown_ in customize_btns:
212
+ ret.update({customize_btns[basic_btn_dropdown_]: gr.update(visible=True, value=basic_fn_title)})
213
+ else:
214
+ ret.update({predefined_btns[basic_btn_dropdown_]: gr.update(visible=True, value=basic_fn_title)})
215
+ ret.update({cookies: cookies_})
216
+ try: persistent_cookie_ = from_cookie_str(persistent_cookie_) # persistent cookie to dict
217
+ except: persistent_cookie_ = {}
218
+ persistent_cookie_["custom_bnt"] = customize_fn_overwrite_ # dict update new value
219
+ persistent_cookie_ = to_cookie_str(persistent_cookie_) # persistent cookie to dict
220
+ ret.update({persistent_cookie: persistent_cookie_}) # write persistent cookie
221
+ return ret
222
+
223
+ def reflesh_btn(persistent_cookie_, cookies_):
224
+ ret = {}
225
+ for k in customize_btns:
226
+ ret.update({customize_btns[k]: gr.update(visible=False, value="")})
227
+
228
+ try: persistent_cookie_ = from_cookie_str(persistent_cookie_) # persistent cookie to dict
229
+ except: return ret
230
+
231
+ customize_fn_overwrite_ = persistent_cookie_.get("custom_bnt", {})
232
+ cookies_['customize_fn_overwrite'] = customize_fn_overwrite_
233
+ ret.update({cookies: cookies_})
234
+
235
+ for k,v in persistent_cookie_["custom_bnt"].items():
236
+ if v['Title'] == "": continue
237
+ if k in customize_btns: ret.update({customize_btns[k]: gr.update(visible=True, value=v['Title'])})
238
+ else: ret.update({predefined_btns[k]: gr.update(visible=True, value=v['Title'])})
239
+ return ret
240
+
241
+ basic_fn_load.click(reflesh_btn, [persistent_cookie, cookies], [cookies, *customize_btns.values(), *predefined_btns.values()])
242
+ h = basic_fn_confirm.click(assign_btn, [persistent_cookie, cookies, basic_btn_dropdown, basic_fn_title, basic_fn_prefix, basic_fn_suffix],
243
+ [persistent_cookie, cookies, *customize_btns.values(), *predefined_btns.values()])
244
+ # save persistent cookie
245
+ h.then(None, [persistent_cookie], None, _js="""(persistent_cookie)=>{setCookie("persistent_cookie", persistent_cookie, 5);}""")
246
+
247
+ # 功能区显示开关与功能区的互动
248
+ def fn_area_visibility(a):
249
+ ret = {}
250
+ ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
251
+ ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
252
+ ret.update({area_input_primary: gr.update(visible=("浮动输入区" not in a))})
253
+ ret.update({area_input_secondary: gr.update(visible=("浮动输入区" in a))})
254
+ ret.update({clearBtn: gr.update(visible=("输入清除键" in a))})
255
+ ret.update({clearBtn2: gr.update(visible=("输入清除键" in a))})
256
+ ret.update({plugin_advanced_arg: gr.update(visible=("插件参数区" in a))})
257
+ if "浮动输入区" in a: ret.update({txt: gr.update(value="")})
258
+ return ret
259
+ checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2, plugin_advanced_arg] )
260
+
261
+ # 功能区显示开关与功能区的互动
262
+ def fn_area_visibility_2(a):
263
+ ret = {}
264
+ ret.update({area_customize: gr.update(visible=("自定义菜单" in a))})
265
+ return ret
266
+ checkboxes_2.select(fn_area_visibility_2, [checkboxes_2], [area_customize] )
267
+
268
+ # 整理反复出现的控件句柄组合
269
+ input_combo = [cookies, max_length_sl, md_dropdown, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg]
270
+ output_combo = [cookies, chatbot, history, status]
271
+ predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True)], outputs=output_combo)
272
+ # 提交按钮、重置按钮
273
+ cancel_handles.append(txt.submit(**predict_args))
274
+ cancel_handles.append(txt2.submit(**predict_args))
275
+ cancel_handles.append(submitBtn.click(**predict_args))
276
+ cancel_handles.append(submitBtn2.click(**predict_args))
277
+ resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
278
+ resetBtn2.click(lambda: ([], [], "已重置"), None, [chatbot, history, status])
279
+ clearBtn.click(lambda: ("",""), None, [txt, txt2])
280
+ clearBtn2.click(lambda: ("",""), None, [txt, txt2])
281
+ if AUTO_CLEAR_TXT:
282
+ submitBtn.click(lambda: ("",""), None, [txt, txt2])
283
+ submitBtn2.click(lambda: ("",""), None, [txt, txt2])
284
+ txt.submit(lambda: ("",""), None, [txt, txt2])
285
+ txt2.submit(lambda: ("",""), None, [txt, txt2])
286
+ # 基础功能区的回调函数注册
287
+ for k in functional:
288
+ if ("Visible" in functional[k]) and (not functional[k]["Visible"]): continue
289
+ click_handle = functional[k]["Button"].click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(k)], outputs=output_combo)
290
+ cancel_handles.append(click_handle)
291
+ for btn in customize_btns.values():
292
+ click_handle = btn.click(fn=ArgsGeneralWrapper(predict), inputs=[*input_combo, gr.State(True), gr.State(btn.value)], outputs=output_combo)
293
+ cancel_handles.append(click_handle)
294
+ # 文件上传区,接收文件后与chatbot的互动
295
+ file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies]).then(None, None, None, _js=r"()=>{toast_push('上传完毕 ...'); cancel_loading_status();}")
296
+ file_upload_2.upload(on_file_uploaded, [file_upload_2, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies]).then(None, None, None, _js=r"()=>{toast_push('上传完毕 ...'); cancel_loading_status();}")
297
+ # 函数插件-固定按钮区
298
+ for k in plugins:
299
+ if not plugins[k].get("AsButton", True): continue
300
+ click_handle = plugins[k]["Button"].click(ArgsGeneralWrapper(plugins[k]["Function"]), [*input_combo], output_combo)
301
+ click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])
302
+ cancel_handles.append(click_handle)
303
+ # 函数插件-下拉菜单与随变按钮的互动
304
+ def on_dropdown_changed(k):
305
+ variant = plugins[k]["Color"] if "Color" in plugins[k] else "secondary"
306
+ info = plugins[k].get("Info", k)
307
+ ret = {switchy_bt: gr.update(value=k, variant=variant, info_str=f'函数插件区: {info}')}
308
+ if plugins[k].get("AdvancedArgs", False): # 是否唤起高级插件参数区
309
+ ret.update({plugin_advanced_arg: gr.update(visible=True, label=f"插件[{k}]的高级参数说明:" + plugins[k].get("ArgsReminder", [f"没有提供高级参数功能说明"]))})
310
+ else:
311
+ ret.update({plugin_advanced_arg: gr.update(visible=False, label=f"插件[{k}]不需要高级参数。")})
312
+ return ret
313
+ dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt, plugin_advanced_arg] )
314
+
315
+ def on_md_dropdown_changed(k):
316
+ return {chatbot: gr.update(label="当前模型:"+k)}
317
+ md_dropdown.select(on_md_dropdown_changed, [md_dropdown], [chatbot] )
318
+
319
+ def on_theme_dropdown_changed(theme, secret_css):
320
+ adjust_theme, css_part1, _, adjust_dynamic_theme = load_dynamic_theme(theme)
321
+ if adjust_dynamic_theme:
322
+ css_part2 = adjust_dynamic_theme._get_theme_css()
323
+ else:
324
+ css_part2 = adjust_theme()._get_theme_css()
325
+ return css_part2 + css_part1
326
+
327
+ theme_handle = theme_dropdown.select(on_theme_dropdown_changed, [theme_dropdown, secret_css], [secret_css])
328
+ theme_handle.then(
329
+ None,
330
+ [secret_css],
331
+ None,
332
+ _js=js_code_for_css_changing
333
+ )
334
+ # 随变按钮的���调函数注册
335
+ def route(request: gr.Request, k, *args, **kwargs):
336
+ if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
337
+ yield from ArgsGeneralWrapper(plugins[k]["Function"])(request, *args, **kwargs)
338
+ click_handle = switchy_bt.click(route,[switchy_bt, *input_combo], output_combo)
339
+ click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])
340
+ cancel_handles.append(click_handle)
341
+ # 终止按钮的回调函数注册
342
+ stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
343
+ stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
344
+ plugins_as_btn = {name:plugin for name, plugin in plugins.items() if plugin.get('Button', None)}
345
+ def on_group_change(group_list):
346
+ btn_list = []
347
+ fns_list = []
348
+ if not group_list: # 处理特殊情况:没有选择任何插件组
349
+ return [*[plugin['Button'].update(visible=False) for _, plugin in plugins_as_btn.items()], gr.Dropdown.update(choices=[])]
350
+ for k, plugin in plugins.items():
351
+ if plugin.get("AsButton", True):
352
+ btn_list.append(plugin['Button'].update(visible=match_group(plugin['Group'], group_list))) # 刷新按钮
353
+ if plugin.get('AdvancedArgs', False): dropdown_fn_list.append(k) # 对于需要高级参数的插件,亦在下拉菜单中显示
354
+ elif match_group(plugin['Group'], group_list): fns_list.append(k) # 刷新下拉列表
355
+ return [*btn_list, gr.Dropdown.update(choices=fns_list)]
356
+ plugin_group_sel.select(fn=on_group_change, inputs=[plugin_group_sel], outputs=[*[plugin['Button'] for name, plugin in plugins_as_btn.items()], dropdown])
357
+ if ENABLE_AUDIO:
358
+ from crazy_functions.live_audio.audio_io import RealtimeAudioDistribution
359
+ rad = RealtimeAudioDistribution()
360
+ def deal_audio(audio, cookies):
361
+ rad.feed(cookies['uuid'].hex, audio)
362
+ audio_mic.stream(deal_audio, inputs=[audio_mic, cookies])
363
+
364
+
365
+ demo.load(init_cookie, inputs=[cookies, chatbot], outputs=[cookies])
366
+ darkmode_js = js_code_for_darkmode_init
367
+ demo.load(None, inputs=None, outputs=[persistent_cookie], _js=js_code_for_persistent_cookie_init)
368
+ demo.load(None, inputs=[dark_mode], outputs=None, _js=darkmode_js) # 配置暗色主题或亮色主题
369
+ demo.load(None, inputs=[gr.Textbox(LAYOUT, visible=False)], outputs=None, _js='(LAYOUT)=>{GptAcademicJavaScriptInit(LAYOUT);}')
370
+
371
+ # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
372
+ def run_delayed_tasks():
373
+ import threading, webbrowser, time
374
+ print(f"如果浏览器没有自动打开,请复制并转到以下URL:")
375
+ if DARK_MODE: print(f"\t「暗色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
376
+ else: print(f"\t「亮色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
377
+
378
+ def auto_updates(): time.sleep(0); auto_update()
379
+ def open_browser(): time.sleep(2); webbrowser.open_new_tab(f"http://localhost:{PORT}")
380
+ def warm_up_mods(): time.sleep(6); warm_up_modules()
381
+
382
+ threading.Thread(target=auto_updates, name="self-upgrade", daemon=True).start() # 查看自动更新
383
+ threading.Thread(target=open_browser, name="open-browser", daemon=True).start() # 打开浏览器页面
384
+ threading.Thread(target=warm_up_mods, name="warm-up", daemon=True).start() # 预热tiktoken模块
385
+
386
+ run_delayed_tasks()
387
+ demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=False, favicon_path="docs/logo.png", blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile"])
388
+
389
+
390
+ # 如果需要在二级路径下运行
391
+ # CUSTOM_PATH = get_conf('CUSTOM_PATH')
392
+ # if CUSTOM_PATH != "/":
393
+ # from toolbox import run_gradio_in_subpath
394
+ # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH)
395
+ # else:
396
+ # demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png",
397
+ # blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile",f"{PATH_LOGGING}/admin"])
398
+
399
+ if __name__ == "__main__":
400
+ main()