CoolFace
Apppublic

MapleGu/ChuanhuChatGPT

sourceHugging Facegpl-3.0updated 4y agoView on Hugging Face
0likes
ChuanhuChatbot.py160 linesDownload Raw Back to root
1import gradio as gr2# import openai3import os4import sys5import argparse6from utils import *7from presets import *8 9 10my_api_key = ""    # 在这里输入你的 API 密钥11 12#if we are running in Docker13if os.environ.get('dockerrun') == 'yes':14    dockerflag = True15else:16    dockerflag = False17 18authflag = False19 20if dockerflag:21    my_api_key = os.environ.get('my_api_key')22    if my_api_key == "empty":23        print("Please give a api key!")24        sys.exit(1)25    #auth26    username = os.environ.get('USERNAME')27    password = os.environ.get('PASSWORD')28    if not (isinstance(username, type(None)) or isinstance(password, type(None))):29        authflag = True30else:31    if not my_api_key and os.path.exists("api_key.txt") and os.path.getsize("api_key.txt"):32        with open("api_key.txt", "r") as f:33            my_api_key = f.read().strip()34    if os.path.exists("auth.json"):35        with open("auth.json", "r") as f:36            auth = json.load(f)37            username = auth["username"]38            password = auth["password"]39            if username != "" and password != "":40                authflag = True41 42gr.Chatbot.postprocess = postprocess43 44with gr.Blocks(css=customCSS) as demo:45    gr.HTML(title)46    with gr.Row():47        keyTxt = gr.Textbox(show_label=False, placeholder=f"在这里输入你的OpenAI API-key...",48                            value=my_api_key, type="password", visible=not HIDE_MY_KEY).style(container=True)49        use_streaming_checkbox = gr.Checkbox(label="实时传输回答", value=True, visible=enable_streaming_option)50    chatbot = gr.Chatbot()  # .style(color_map=("#1D51EE", "#585A5B"))51    history = gr.State([])52    token_count = gr.State([])53    promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2))54    TRUECOMSTANT = gr.State(True)55    FALSECONSTANT = gr.State(False)56    topic = gr.State("未命名对话历史记录")57 58    with gr.Row():59        with gr.Column(scale=12):60            user_input = gr.Textbox(show_label=False, placeholder="在这里输入").style(61                container=False)62        with gr.Column(min_width=50, scale=1):63            submitBtn = gr.Button("🚀", variant="primary")64    with gr.Row():65        emptyBtn = gr.Button("🧹 新的对话")66        retryBtn = gr.Button("🔄 重新生成")67        delLastBtn = gr.Button("🗑️ 删除最近一条对话")68        reduceTokenBtn = gr.Button("♻️ 总结对话")69    status_display = gr.Markdown("status: ready")70    systemPromptTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入System Prompt...",71                                 label="System prompt", value=initial_prompt).style(container=True)72    with gr.Accordion(label="加载Prompt模板", open=False):73        with gr.Column():74            with gr.Row():75                with gr.Column(scale=6):76                    templateFileSelectDropdown = gr.Dropdown(label="选择Prompt模板集合文件", choices=get_template_names(plain=True), multiselect=False, value=get_template_names(plain=True)[0])77                with gr.Column(scale=1):78                    templateRefreshBtn = gr.Button("🔄 刷新")79                    templaeFileReadBtn = gr.Button("📂 读入模板")80            with gr.Row():81                with gr.Column(scale=6):82                    templateSelectDropdown = gr.Dropdown(label="从Prompt模板中加载", choices=load_template(get_template_names(plain=True)[0], mode=1), multiselect=False, value=load_template(get_template_names(plain=True)[0], mode=1)[0])83                with gr.Column(scale=1):84                    templateApplyBtn = gr.Button("⬇️ 应用")85    with gr.Accordion(label="保存/加载对话历史记录", open=False):86        with gr.Column():87            with gr.Row():88                with gr.Column(scale=6):89                    saveFileName = gr.Textbox(90                        show_label=True, placeholder=f"在这里输入保存的文件名...", label="设置保存文件名", value="对话历史记录").style(container=True)91                with gr.Column(scale=1):92                    saveHistoryBtn = gr.Button("💾 保存对话")93            with gr.Row():94                with gr.Column(scale=6):95                    historyFileSelectDropdown = gr.Dropdown(label="从列表中加载对话", choices=get_history_names(plain=True), multiselect=False, value=get_history_names(plain=True)[0])96                with gr.Column(scale=1):97                    historyRefreshBtn = gr.Button("🔄 刷新")98                    historyReadBtn = gr.Button("📂 读入对话")99    #inputs, top_p, temperature, top_k, repetition_penalty100    with gr.Accordion("参数", open=False):101        top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.05,102                          interactive=True, label="Top-p (nucleus sampling)",)103        temperature = gr.Slider(minimum=-0, maximum=5.0, value=1.0,104                                step=0.1, interactive=True, label="Temperature",)105        #top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)106        #repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )107    gr.Markdown(description)108 109 110    user_input.submit(predict, [keyTxt, systemPromptTxt, history, user_input, chatbot, token_count, top_p, temperature, use_streaming_checkbox], [chatbot, history, status_display, token_count], show_progress=True)111    user_input.submit(reset_textbox, [], [user_input])112 113    submitBtn.click(predict, [keyTxt, systemPromptTxt, history, user_input, chatbot, token_count, top_p, temperature, use_streaming_checkbox], [chatbot, history, status_display, token_count], show_progress=True)114    submitBtn.click(reset_textbox, [], [user_input])115 116    emptyBtn.click(reset_state, outputs=[chatbot, history, token_count, status_display], show_progress=True)117 118    retryBtn.click(retry, [keyTxt, systemPromptTxt, history, chatbot, token_count, top_p, temperature, use_streaming_checkbox], [chatbot, history, status_display, token_count], show_progress=True)119 120    delLastBtn.click(delete_last_conversation, [chatbot, history, token_count, use_streaming_checkbox], [121                     chatbot, history, token_count, status_display], show_progress=True)122 123    reduceTokenBtn.click(reduce_token_size, [keyTxt, systemPromptTxt, history, chatbot, token_count, top_p, temperature, use_streaming_checkbox], [chatbot, history, status_display, token_count], show_progress=True)124 125    saveHistoryBtn.click(save_chat_history, [126                  saveFileName, systemPromptTxt, history, chatbot], None, show_progress=True)127 128    saveHistoryBtn.click(get_history_names, None, [historyFileSelectDropdown])129 130    historyRefreshBtn.click(get_history_names, None, [historyFileSelectDropdown])131 132    historyReadBtn.click(load_chat_history, [historyFileSelectDropdown, systemPromptTxt, history, chatbot],  [saveFileName, systemPromptTxt, history, chatbot], show_progress=True)133 134    templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])135 136    templaeFileReadBtn.click(load_template, [templateFileSelectDropdown],  [promptTemplates, templateSelectDropdown], show_progress=True)137 138    templateApplyBtn.click(get_template_content, [promptTemplates, templateSelectDropdown, systemPromptTxt],  [systemPromptTxt], show_progress=True)139 140print("川虎的温馨提示:访问 http://localhost:7860 查看界面")141# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接142demo.title = "川虎ChatGPT 🚀"143 144if __name__ == "__main__":145    #if running in Docker146    if dockerflag:147        if authflag:148            demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=(username, password))149        else:150            demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)151    #if not running in Docker152    else:153        if authflag:154            demo.queue().launch(share=False, auth=(username, password))155        else:156            demo.queue().launch(share=False) # 改为 share=True 可以创建公开分享链接157        #demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口158        #demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码159        #demo.queue().launch(auth=("在这里填写用户名", "在这里填写密码")) # 适合Nginx反向代理160