CoolFace
Apppublic

Intoval/privateChatGPT

sourceHugging Facegpl-3.0updated 3y agoView on Hugging Face
1likes
ChuanhuChatbot.py453 linesDownload Raw Back to root
1# -*- coding:utf-8 -*-2import os3import logging4import sys5 6import gradio as gr7 8from modules import config9from modules.config import *10from modules.utils import *11from modules.presets import *12from modules.overwrites import *13from modules.models import get_model14 15 16gr.Chatbot._postprocess_chat_messages = postprocess_chat_messages17gr.Chatbot.postprocess = postprocess18PromptHelper.compact_text_chunks = compact_text_chunks19 20with open("assets/custom.css", "r", encoding="utf-8") as f:21    customCSS = f.read()22 23def create_new_model():24    return get_model(model_name = MODELS[DEFAULT_MODEL], access_key = my_api_key)[0]25 26with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:27    user_name = gr.State("")28    promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2))29    user_question = gr.State("")30    user_api_key = gr.State(my_api_key)31    current_model = gr.State(create_new_model)32 33    topic = gr.State(i18n("未命名对话历史记录"))34 35    with gr.Row():36        gr.HTML(CHUANHU_TITLE, elem_id="app_title")37        status_display = gr.Markdown(get_geoip(), elem_id="status_display")38    with gr.Row(elem_id="float_display"):39        user_info = gr.Markdown(value="getting user info...", elem_id="user_info")40 41        # https://github.com/gradio-app/gradio/pull/329642        def create_greeting(request: gr.Request):43            if hasattr(request, "username") and request.username: # is not None or is not ""44                logging.info(f"Get User Name: {request.username}")45                return gr.Markdown.update(value=f"User: {request.username}"), request.username46            else:47                return gr.Markdown.update(value=f"User: default", visible=False), ""48        demo.load(create_greeting, inputs=None, outputs=[user_info, user_name])49 50    with gr.Row().style(equal_height=True):51        with gr.Column(scale=5):52            with gr.Row():53                chatbot = gr.Chatbot(elem_id="chuanhu_chatbot").style(height="100%")54            with gr.Row():55                with gr.Column(min_width=225, scale=12):56                    user_input = gr.Textbox(57                        elem_id="user_input_tb",58                        show_label=False, placeholder=i18n("在这里输入")59                    ).style(container=False)60                with gr.Column(min_width=42, scale=1):61                    submitBtn = gr.Button(value="", variant="primary", elem_id="submit_btn")62                    cancelBtn = gr.Button(value="", variant="secondary", visible=False, elem_id="cancel_btn")63            with gr.Row():64                emptyBtn = gr.Button(65                    i18n("🧹 新的对话"),66                )67                retryBtn = gr.Button(i18n("🔄 重新生成"))68                delFirstBtn = gr.Button(i18n("🗑️ 删除最旧对话"))69                delLastBtn = gr.Button(i18n("🗑️ 删除最新对话"))70 71        with gr.Column():72            with gr.Column(min_width=50, scale=1):73                with gr.Tab(label=i18n("模型")):74                    keyTxt = gr.Textbox(75                        show_label=True,76                        placeholder=f"OpenAI API-key...",77                        value=hide_middle_chars(user_api_key.value),78                        type="password",79                        visible=not HIDE_MY_KEY,80                        label="API-Key",81                    )82                    if multi_api_key:83                        usageTxt = gr.Markdown(i18n("多账号模式已开启,无需输入key,可直接开始对话"), elem_id="usage_display", elem_classes="insert_block")84                    else:85                        usageTxt = gr.Markdown(i18n("**发送消息** 或 **提交key** 以显示额度"), elem_id="usage_display", elem_classes="insert_block")86                    model_select_dropdown = gr.Dropdown(87                        label=i18n("选择模型"), choices=MODELS, multiselect=False, value=MODELS[DEFAULT_MODEL], interactive=True88                    )89                    lora_select_dropdown = gr.Dropdown(90                        label=i18n("选择LoRA模型"), choices=[], multiselect=False, interactive=True, visible=False91                    )92                    with gr.Row():93                        use_streaming_checkbox = gr.Checkbox(94                            label=i18n("实时传输回答"), value=True, visible=ENABLE_STREAMING_OPTION95                        )96                        single_turn_checkbox = gr.Checkbox(label=i18n("单轮对话"), value=False)97                        use_websearch_checkbox = gr.Checkbox(label=i18n("使用在线搜索"), value=False)98                    language_select_dropdown = gr.Dropdown(99                        label=i18n("选择回复语言(针对搜索&索引功能)"),100                        choices=REPLY_LANGUAGES,101                        multiselect=False,102                        value=REPLY_LANGUAGES[0],103                    )104                    index_files = gr.Files(label=i18n("上传索引文件"), type="file")105                    two_column = gr.Checkbox(label=i18n("双栏pdf"), value=advance_docs["pdf"].get("two_column", False))106                    # TODO: 公式ocr107                    # formula_ocr = gr.Checkbox(label=i18n("识别公式"), value=advance_docs["pdf"].get("formula_ocr", False))108 109                with gr.Tab(label="Prompt"):110                    systemPromptTxt = gr.Textbox(111                        show_label=True,112                        placeholder=i18n("在这里输入System Prompt..."),113                        label="System prompt",114                        value=INITIAL_SYSTEM_PROMPT,115                        lines=10,116                    ).style(container=False)117                    with gr.Accordion(label=i18n("加载Prompt模板"), open=True):118                        with gr.Column():119                            with gr.Row():120                                with gr.Column(scale=6):121                                    templateFileSelectDropdown = gr.Dropdown(122                                        label=i18n("选择Prompt模板集合文件"),123                                        choices=get_template_names(plain=True),124                                        multiselect=False,125                                        value=get_template_names(plain=True)[0],126                                    ).style(container=False)127                                with gr.Column(scale=1):128                                    templateRefreshBtn = gr.Button(i18n("🔄 刷新"))129                            with gr.Row():130                                with gr.Column():131                                    templateSelectDropdown = gr.Dropdown(132                                        label=i18n("从Prompt模板中加载"),133                                        choices=load_template(134                                            get_template_names(plain=True)[0], mode=1135                                        ),136                                        multiselect=False,137                                    ).style(container=False)138 139                with gr.Tab(label=i18n("保存/加载")):140                    with gr.Accordion(label=i18n("保存/加载对话历史记录"), open=True):141                        with gr.Column():142                            with gr.Row():143                                with gr.Column(scale=6):144                                    historyFileSelectDropdown = gr.Dropdown(145                                        label=i18n("从列表中加载对话"),146                                        choices=get_history_names(plain=True),147                                        multiselect=False,148                                        value=get_history_names(plain=True)[0],149                                    )150                                with gr.Column(scale=1):151                                    historyRefreshBtn = gr.Button(i18n("🔄 刷新"))152                            with gr.Row():153                                with gr.Column(scale=6):154                                    saveFileName = gr.Textbox(155                                        show_label=True,156                                        placeholder=i18n("设置文件名: 默认为.json,可选为.md"),157                                        label=i18n("设置保存文件名"),158                                        value=i18n("对话历史记录"),159                                    ).style(container=True)160                                with gr.Column(scale=1):161                                    saveHistoryBtn = gr.Button(i18n("💾 保存对话"))162                                    exportMarkdownBtn = gr.Button(i18n("📝 导出为Markdown"))163                                    gr.Markdown(i18n("默认保存于history文件夹"))164                            with gr.Row():165                                with gr.Column():166                                    downloadFile = gr.File(interactive=True)167 168                with gr.Tab(label=i18n("高级")):169                    gr.Markdown(i18n("# ⚠️ 务必谨慎更改 ⚠️\n\n如果无法使用请恢复默认设置"))170                    gr.HTML(APPEARANCE_SWITCHER, elem_classes="insert_block")171                    with gr.Accordion(i18n("参数"), open=False):172                        temperature_slider = gr.Slider(173                            minimum=-0,174                            maximum=2.0,175                            value=1.0,176                            step=0.1,177                            interactive=True,178                            label="temperature",179                        )180                        top_p_slider = gr.Slider(181                            minimum=-0,182                            maximum=1.0,183                            value=1.0,184                            step=0.05,185                            interactive=True,186                            label="top-p",187                        )188                        n_choices_slider = gr.Slider(189                            minimum=1,190                            maximum=10,191                            value=1,192                            step=1,193                            interactive=True,194                            label="n choices",195                        )196                        stop_sequence_txt = gr.Textbox(197                            show_label=True,198                            placeholder=i18n("在这里输入停止符,用英文逗号隔开..."),199                            label="stop",200                            value="",201                            lines=1,202                        )203                        max_context_length_slider = gr.Slider(204                            minimum=1,205                            maximum=32768,206                            value=2000,207                            step=1,208                            interactive=True,209                            label="max context",210                        )211                        max_generation_slider = gr.Slider(212                            minimum=1,213                            maximum=32768,214                            value=1000,215                            step=1,216                            interactive=True,217                            label="max generations",218                        )219                        presence_penalty_slider = gr.Slider(220                            minimum=-2.0,221                            maximum=2.0,222                            value=0.0,223                            step=0.01,224                            interactive=True,225                            label="presence penalty",226                        )227                        frequency_penalty_slider = gr.Slider(228                            minimum=-2.0,229                            maximum=2.0,230                            value=0.0,231                            step=0.01,232                            interactive=True,233                            label="frequency penalty",234                        )235                        logit_bias_txt = gr.Textbox(236                            show_label=True,237                            placeholder=f"word:likelihood",238                            label="logit bias",239                            value="",240                            lines=1,241                        )242                        user_identifier_txt = gr.Textbox(243                            show_label=True,244                            placeholder=i18n("用于定位滥用行为"),245                            label=i18n("用户名"),246                            value=user_name.value,247                            lines=1,248                        )249 250                    with gr.Accordion(i18n("网络设置"), open=False):251                        # 优先展示自定义的api_host252                        apihostTxt = gr.Textbox(253                            show_label=True,254                            placeholder=i18n("在这里输入API-Host..."),255                            label="API-Host",256                            value=config.api_host or shared.API_HOST,257                            lines=1,258                        )259                        changeAPIURLBtn = gr.Button(i18n("🔄 切换API地址"))260                        proxyTxt = gr.Textbox(261                            show_label=True,262                            placeholder=i18n("在这里输入代理地址..."),263                            label=i18n("代理地址(示例:http://127.0.0.1:10809)"),264                            value="",265                            lines=2,266                        )267                        changeProxyBtn = gr.Button(i18n("🔄 设置代理地址"))268                        default_btn = gr.Button(i18n("🔙 恢复默认设置"))269 270    gr.Markdown(CHUANHU_DESCRIPTION, elem_id="description")271    gr.HTML(FOOTER.format(versions=versions_html()), elem_id="footer")272    chatgpt_predict_args = dict(273        fn=predict,274        inputs=[275            current_model,276            user_question,277            chatbot,278            use_streaming_checkbox,279            use_websearch_checkbox,280            index_files,281            language_select_dropdown,282        ],283        outputs=[chatbot, status_display],284        show_progress=True,285    )286 287    start_outputing_args = dict(288        fn=start_outputing,289        inputs=[],290        outputs=[submitBtn, cancelBtn],291        show_progress=True,292    )293 294    end_outputing_args = dict(295        fn=end_outputing, inputs=[], outputs=[submitBtn, cancelBtn]296    )297 298    reset_textbox_args = dict(299        fn=reset_textbox, inputs=[], outputs=[user_input]300    )301 302    transfer_input_args = dict(303        fn=transfer_input, inputs=[user_input], outputs=[user_question, user_input, submitBtn, cancelBtn], show_progress=True304    )305 306    get_usage_args = dict(307        fn=billing_info, inputs=[current_model], outputs=[usageTxt], show_progress=False308    )309 310    load_history_from_file_args = dict(311        fn=load_chat_history,312        inputs=[current_model, historyFileSelectDropdown, chatbot, user_name],313        outputs=[saveFileName, systemPromptTxt, chatbot]314    )315 316 317    # Chatbot318    cancelBtn.click(interrupt, [current_model], [])319 320    user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)321    user_input.submit(**get_usage_args)322 323    submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)324    submitBtn.click(**get_usage_args)325 326    index_files.change(handle_file_upload, [current_model, index_files, chatbot], [index_files, chatbot, status_display])327 328    emptyBtn.click(329        reset,330        inputs=[current_model],331        outputs=[chatbot, status_display],332        show_progress=True,333    )334    emptyBtn.click(**reset_textbox_args)335 336    retryBtn.click(**start_outputing_args).then(337        retry,338        [339            current_model,340            chatbot,341            use_streaming_checkbox,342            use_websearch_checkbox,343            index_files,344            language_select_dropdown,345        ],346        [chatbot, status_display],347        show_progress=True,348    ).then(**end_outputing_args)349    retryBtn.click(**get_usage_args)350 351    delFirstBtn.click(352        delete_first_conversation,353        [current_model],354        [status_display],355    )356 357    delLastBtn.click(358        delete_last_conversation,359        [current_model, chatbot],360        [chatbot, status_display],361        show_progress=False362    )363 364    two_column.change(update_doc_config, [two_column], None)365 366    # LLM Models367    keyTxt.change(set_key, [current_model, keyTxt], [user_api_key, status_display]).then(**get_usage_args)368    keyTxt.submit(**get_usage_args)369    single_turn_checkbox.change(set_single_turn, [current_model, single_turn_checkbox], None)370    model_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt], [current_model, status_display, lora_select_dropdown], show_progress=True)371    lora_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt], [current_model, status_display], show_progress=True)372 373    # Template374    systemPromptTxt.change(set_system_prompt, [current_model, systemPromptTxt], None)375    templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])376    templateFileSelectDropdown.change(377        load_template,378        [templateFileSelectDropdown],379        [promptTemplates, templateSelectDropdown],380        show_progress=True,381    )382    templateSelectDropdown.change(383        get_template_content,384        [promptTemplates, templateSelectDropdown, systemPromptTxt],385        [systemPromptTxt],386        show_progress=True,387    )388 389    # S&L390    saveHistoryBtn.click(391        save_chat_history,392        [current_model, saveFileName, chatbot, user_name],393        downloadFile,394        show_progress=True,395    )396    saveHistoryBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown])397    exportMarkdownBtn.click(398        export_markdown,399        [current_model, saveFileName, chatbot, user_name],400        downloadFile,401        show_progress=True,402    )403    historyRefreshBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown])404    historyFileSelectDropdown.change(**load_history_from_file_args)405    downloadFile.change(**load_history_from_file_args)406 407    # Advanced408    max_context_length_slider.change(set_token_upper_limit, [current_model, max_context_length_slider], None)409    temperature_slider.change(set_temperature, [current_model, temperature_slider], None)410    top_p_slider.change(set_top_p, [current_model, top_p_slider], None)411    n_choices_slider.change(set_n_choices, [current_model, n_choices_slider], None)412    stop_sequence_txt.change(set_stop_sequence, [current_model, stop_sequence_txt], None)413    max_generation_slider.change(set_max_tokens, [current_model, max_generation_slider], None)414    presence_penalty_slider.change(set_presence_penalty, [current_model, presence_penalty_slider], None)415    frequency_penalty_slider.change(set_frequency_penalty, [current_model, frequency_penalty_slider], None)416    logit_bias_txt.change(set_logit_bias, [current_model, logit_bias_txt], None)417    user_identifier_txt.change(set_user_identifier, [current_model, user_identifier_txt], None)418 419    default_btn.click(420        reset_default, [], [apihostTxt, proxyTxt, status_display], show_progress=True421    )422    changeAPIURLBtn.click(423        change_api_host,424        [apihostTxt],425        [status_display],426        show_progress=True,427    )428    changeProxyBtn.click(429        change_proxy,430        [proxyTxt],431        [status_display],432        show_progress=True,433    )434 435logging.info(436    colorama.Back.GREEN437    + "\n川虎的温馨提示:访问 http://localhost:7860 查看界面"438    + colorama.Style.RESET_ALL439)440# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接441demo.title = i18n("川虎Chat 🚀")442 443if __name__ == "__main__":444    reload_javascript()445    demo.queue(concurrency_count=CONCURRENT_COUNT).launch(446        auth=auth_list if authflag else None,447        favicon_path="./assets/favicon.ico",448        inbrowser=not dockerflag, # 禁止在docker下开启inbrowser449    )450    # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口451    # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码452    # demo.queue(concurrency_count=CONCURRENT_COUNT).launch(auth=("在这里填写用户名", "在这里填写密码")) # 适合Nginx反向代理453