Numberlla commited on
Commit
8adc473
1 Parent(s): 264392f

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +144 -0
main.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
2
+ import gradio as gr
3
+ from predict import predict
4
+ from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf
5
+
6
+ # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到
7
+ proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT = \
8
+ get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT')
9
+
10
+ # 如果WEB_PORT是-1, 则随机选取WEB端口
11
+ PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
12
+ if not AUTHENTICATION: AUTHENTICATION = None
13
+
14
+ initial_prompt = "Serve me as a writing and programming assistant."
15
+ title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
16
+
17
+ # 问询记录, python 版本建议3.9+(越新越好)
18
+ import logging
19
+ os.makedirs("gpt_log", exist_ok=True)
20
+ try:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO, encoding="utf-8")
21
+ except:logging.basicConfig(filename="gpt_log/chat_secrets.log", level=logging.INFO)
22
+ print("所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!")
23
+
24
+ # 一些普通功能模块
25
+ from functional import get_functionals
26
+ functional = get_functionals()
27
+
28
+ # 高级函数插件
29
+ from functional_crazy import get_crazy_functionals
30
+ crazy_fns = get_crazy_functionals()
31
+
32
+ # 处理markdown文本格式的转变
33
+ gr.Chatbot.postprocess = format_io
34
+
35
+ # 做一些外观色彩上的调整
36
+ from theme import adjust_theme, advanced_css
37
+ set_theme = adjust_theme()
38
+
39
+ cancel_handles = []
40
+ with gr.Blocks(theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
41
+ gr.HTML(title_html)
42
+ with gr.Row().style(equal_height=True):
43
+ with gr.Column(scale=2):
44
+ chatbot = gr.Chatbot()
45
+ chatbot.style(height=CHATBOT_HEIGHT)
46
+ history = gr.State([])
47
+ with gr.Column(scale=1):
48
+ with gr.Row():
49
+ txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
50
+ with gr.Row():
51
+ submitBtn = gr.Button("提交", variant="primary")
52
+ with gr.Row():
53
+ resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
54
+ stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
55
+ with gr.Row():
56
+ from check_proxy import check_proxy
57
+ status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {check_proxy(proxies)}")
58
+ with gr.Accordion("基础功能区", open=True) as area_basic_fn:
59
+ with gr.Row():
60
+ for k in functional:
61
+ variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
62
+ functional[k]["Button"] = gr.Button(k, variant=variant)
63
+ with gr.Accordion("函数插件区", open=True) as area_crazy_fn:
64
+ with gr.Row():
65
+ gr.Markdown("注意:以下“红颜色”标识的函数插件需从input区读取路径作为参数.")
66
+ with gr.Row():
67
+ for k in crazy_fns:
68
+ if not crazy_fns[k].get("AsButton", True): continue
69
+ variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
70
+ crazy_fns[k]["Button"] = gr.Button(k, variant=variant)
71
+ with gr.Row():
72
+ with gr.Accordion("更多函数插件", open=True):
73
+ dropdown_fn_list = [k for k in crazy_fns.keys() if not crazy_fns[k].get("AsButton", True)]
74
+ with gr.Column(scale=1):
75
+ dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(container=False)
76
+ with gr.Column(scale=1):
77
+ switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
78
+ with gr.Row():
79
+ with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up:
80
+ file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
81
+ with gr.Accordion("展开SysPrompt & GPT参数 & 交互界面布局", open=False):
82
+ system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
83
+ top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
84
+ temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
85
+ checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区"], value=["基础功能区", "函数���件区"], label="显示/隐藏功能区")
86
+
87
+ # 功能区显示开关与功能区的互动
88
+ def fn_area_visibility(a):
89
+ ret = {}
90
+ ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
91
+ ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
92
+ return ret
93
+ checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn] )
94
+ # 整理反复出现的控件句柄组合
95
+ input_combo = [txt, top_p, temperature, chatbot, history, system_prompt]
96
+ output_combo = [chatbot, history, status]
97
+ predict_args = dict(fn=predict, inputs=input_combo, outputs=output_combo)
98
+ empty_txt_args = dict(fn=lambda: "", inputs=[], outputs=[txt]) # 用于在提交后清空输入栏
99
+ # 提交按钮、重置按钮
100
+ cancel_handles.append(txt.submit(**predict_args)) #; txt.submit(**empty_txt_args) 在提交后清空输入栏
101
+ cancel_handles.append(submitBtn.click(**predict_args)) #; submitBtn.click(**empty_txt_args) 在提交后清空输入栏
102
+ resetBtn.click(lambda: ([], [], "已重置"), None, output_combo)
103
+ # 基础功能区的回调函数注册
104
+ for k in functional:
105
+ click_handle = functional[k]["Button"].click(predict, [*input_combo, gr.State(True), gr.State(k)], output_combo)
106
+ cancel_handles.append(click_handle)
107
+ # 文件上传区,接收文件后与chatbot的互动
108
+ file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])
109
+ # 函数插件-固定按钮区
110
+ for k in crazy_fns:
111
+ if not crazy_fns[k].get("AsButton", True): continue
112
+ click_handle = crazy_fns[k]["Button"].click(crazy_fns[k]["Function"], [*input_combo, gr.State(PORT)], output_combo)
113
+ click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
114
+ cancel_handles.append(click_handle)
115
+ # 函数插件-下拉菜单与随变按钮的互动
116
+ def on_dropdown_changed(k):
117
+ variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
118
+ return {switchy_bt: gr.update(value=k, variant=variant)}
119
+ dropdown.select(on_dropdown_changed, [dropdown], [switchy_bt] )
120
+ # 随变按钮的回调函数注册
121
+ def route(k, *args, **kwargs):
122
+ if k in [r"打开插件列表", r"先从插件列表中选择"]: return
123
+ yield from crazy_fns[k]["Function"](*args, **kwargs)
124
+ click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo)
125
+ click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])
126
+ # def expand_file_area(file_upload, area_file_up):
127
+ # if len(file_upload)>0: return {area_file_up: gr.update(open=True)}
128
+ # click_handle.then(expand_file_area, [file_upload, area_file_up], [area_file_up])
129
+ cancel_handles.append(click_handle)
130
+ # 终止按钮的回调函数注册
131
+ stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
132
+
133
+ # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
134
+ def auto_opentab_delay():
135
+ import threading, webbrowser, time
136
+ print(f"如果浏览器没有自动打开,请复制并转到以下URL: http://localhost:{PORT}")
137
+ def open():
138
+ time.sleep(2)
139
+ webbrowser.open_new_tab(f"http://localhost:{PORT}")
140
+ threading.Thread(target=open, name="open-browser", daemon=True).start()
141
+
142
+ auto_opentab_delay()
143
+ demo.title = "ChatGPT 学术优化"
144
+ demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=True, server_port=PORT, auth=AUTHENTICATION)