fufa/chatgpt
0
1import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染2import gradio as gr3from predict import predict4from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf5 6# 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到7proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = \8 get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')9 10 11# 如果WEB_PORT是-1, 则随机选取WEB端口12PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT13AUTHENTICATION = None if AUTHENTICATION == [] else AUTHENTICATION14 15initial_prompt = "Serve me as a writing and programming assistant."16title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""17 18# 问询记录, python 版本建议3.9+(越新越好)19import logging20os.makedirs('gpt_log', exist_ok=True)21try:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO, encoding='utf-8')22except:logging.basicConfig(filename='gpt_log/chat_secrets.log', level=logging.INFO)23print('所有问询记录将自动保存在本地目录./gpt_log/chat_secrets.log, 请注意自我隐私保护哦!')24 25# 一些普通功能模块26from functional import get_functionals27functional = get_functionals()28 29# 对一些丧心病狂的实验性功能模块进行测试30from functional_crazy import get_crazy_functionals31crazy_functional = get_crazy_functionals()32 33# 处理markdown文本格式的转变34gr.Chatbot.postprocess = format_io35 36# 做一些外观色彩上的调整37from theme import adjust_theme38set_theme = adjust_theme()39 40cancel_handles = []41with gr.Blocks(theme=set_theme, analytics_enabled=False) as demo:42 gr.HTML(title_html)43 with gr.Row():44 with gr.Column(scale=2):45 chatbot = gr.Chatbot()46 chatbot.style(height=1150)47 chatbot.style()48 history = gr.State([])49 with gr.Column(scale=1):50 with gr.Row():51 txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)52 with gr.Row():53 submitBtn = gr.Button("提交", variant="primary")54 with gr.Row():55 resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")56 stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")57 with gr.Row():58 from check_proxy import check_proxy59 statusDisplay = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {check_proxy(proxies)}")60 with gr.Row():61 for k in functional:62 variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"63 functional[k]["Button"] = gr.Button(k, variant=variant)64 with gr.Row():65 gr.Markdown("注意:以下“红颜色”标识的函数插件需从input区读取路径作为参数.")66 with gr.Row():67 for k in crazy_functional:68 variant = crazy_functional[k]["Color"] if "Color" in crazy_functional[k] else "secondary"69 crazy_functional[k]["Button"] = gr.Button(k, variant=variant)70 with gr.Row():71 gr.Markdown("上传本地文件,供上面的函数插件调用.")72 with gr.Row():73 file_upload = gr.Files(label='任何文件, 但推荐上传压缩文件(zip, tar)', file_count="multiple")74 system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt).style(container=True)75 with gr.Accordion("arguments", open=False):76 top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)77 temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)78 79 predict_args = dict(fn=predict, inputs=[txt, top_p, temperature, chatbot, history, system_prompt], outputs=[chatbot, history, statusDisplay], show_progress=True)80 empty_txt_args = dict(fn=lambda: "", inputs=[], outputs=[txt]) # 用于在提交后清空输入栏81 82 cancel_handles.append(txt.submit(**predict_args))83 # txt.submit(**empty_txt_args) 在提交后清空输入栏84 cancel_handles.append(submitBtn.click(**predict_args))85 # submitBtn.click(**empty_txt_args) 在提交后清空输入栏86 resetBtn.click(lambda: ([], [], "已重置"), None, [chatbot, history, statusDisplay])87 for k in functional:88 click_handle = functional[k]["Button"].click(predict,89 [txt, top_p, temperature, chatbot, history, system_prompt, gr.State(True), gr.State(k)], [chatbot, history, statusDisplay], show_progress=True)90 cancel_handles.append(click_handle)91 file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt], [chatbot, txt])92 for k in crazy_functional:93 click_handle = crazy_functional[k]["Button"].click(crazy_functional[k]["Function"],94 [txt, top_p, temperature, chatbot, history, system_prompt, gr.State(PORT)], [chatbot, history, statusDisplay]95 )96 try: click_handle.then(on_report_generated, [file_upload, chatbot], [file_upload, chatbot])97 except: pass98 cancel_handles.append(click_handle)99 stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)100 101# gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数102def auto_opentab_delay():103 import threading, webbrowser, time104 print(f"URL http://localhost:{PORT}")105 def open(): 106 time.sleep(2)107 webbrowser.open_new_tab(f'http://localhost:{PORT}')108 t = threading.Thread(target=open)109 t.daemon = True; t.start()110 111auto_opentab_delay()112demo.title = "ChatGPT 学术优化"113demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=True, server_port=PORT, auth=AUTHENTICATION)114 