CoolFace
Apppublic

lifenga/gpt

sourceHugging Facegpl-3.0updated 4y agoView on Hugging Face
0likes
app.py456 linesDownload Raw Back to root
1# -*- coding:utf-8 -*-2import os3import logging4import sys5 6import gradio as gr7 8from utils import *9from presets import *10from overwrites import *11from chat_func import *12 13logging.basicConfig(14    level=logging.DEBUG,15    format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",16)17 18my_api_key = ""  # 在这里输入你的 API 密钥19 20# if we are running in Docker21if os.environ.get("dockerrun") == "yes":22    dockerflag = True23else:24    dockerflag = False25 26authflag = False27 28if dockerflag:29    my_api_key = os.environ.get("my_api_key")30    if my_api_key == "empty":31        logging.error("Please give a api key!")32        sys.exit(1)33    # auth34    username = os.environ.get("USERNAME")35    password = os.environ.get("PASSWORD")36    if not (isinstance(username, type(None)) or isinstance(password, type(None))):37        authflag = True38else:39    if (40        not my_api_key41        and os.path.exists("api_key.txt")42        and os.path.getsize("api_key.txt")43    ):44        with open("api_key.txt", "r") as f:45            my_api_key = f.read().strip()46    if os.path.exists("auth.json"):47        with open("auth.json", "r") as f:48            auth = json.load(f)49            username = auth["username"]50            password = auth["password"]51            if username != "" and password != "":52                authflag = True53 54gr.Chatbot.postprocess = postprocess55PromptHelper.compact_text_chunks = compact_text_chunks56 57with open("custom.css", "r", encoding="utf-8") as f:58    customCSS = f.read()59 60with gr.Blocks(61    css=customCSS,62    theme=gr.themes.Soft(63        primary_hue=gr.themes.Color(64            c50="#02C160",65            c100="rgba(2, 193, 96, 0.2)",66            c200="#02C160",67            c300="rgba(2, 193, 96, 0.32)",68            c400="rgba(2, 193, 96, 0.32)",69            c500="rgba(2, 193, 96, 1.0)",70            c600="rgba(2, 193, 96, 1.0)",71            c700="rgba(2, 193, 96, 0.32)",72            c800="rgba(2, 193, 96, 0.32)",73            c900="#02C160",74            c950="#02C160",75        ),76        secondary_hue=gr.themes.Color(77            c50="#576b95",78            c100="#576b95",79            c200="#576b95",80            c300="#576b95",81            c400="#576b95",82            c500="#576b95",83            c600="#576b95",84            c700="#576b95",85            c800="#576b95",86            c900="#576b95",87            c950="#576b95",88        ),89        neutral_hue=gr.themes.Color(90            name="gray",91            c50="#f9fafb",92            c100="#f3f4f6",93            c200="#e5e7eb",94            c300="#d1d5db",95            c400="#B2B2B2",96            c500="#808080",97            c600="#636363",98            c700="#515151",99            c800="#393939",100            c900="#272727",101            c950="#171717",102        ),103        radius_size=gr.themes.sizes.radius_sm,104    ).set(105        button_primary_background_fill="#06AE56",106        button_primary_background_fill_dark="#06AE56",107        button_primary_background_fill_hover="#07C863",108        button_primary_border_color="#06AE56",109        button_primary_border_color_dark="#06AE56",110        button_primary_text_color="#FFFFFF",111        button_primary_text_color_dark="#FFFFFF",112        button_secondary_background_fill="#F2F2F2",113        button_secondary_background_fill_dark="#2B2B2B",114        button_secondary_text_color="#393939",115        button_secondary_text_color_dark="#FFFFFF",116        # background_fill_primary="#F7F7F7",117        # background_fill_primary_dark="#1F1F1F",118        block_title_text_color="*primary_500",119        block_title_background_fill="*primary_100",120        input_background_fill="#F6F6F6",121    ),122) as demo:123    history = gr.State([])124    token_count = gr.State([])125    promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2))126    user_api_key = gr.State(my_api_key)127    TRUECOMSTANT = gr.State(True)128    FALSECONSTANT = gr.State(False)129    topic = gr.State("未命名对话历史记录")130 131    with gr.Row():132        gr.HTML(title)133        status_display = gr.Markdown(get_geoip(), elem_id="status_display")134 135    with gr.Row(scale=1).style(equal_height=True):136        with gr.Column(scale=5):137            with gr.Row(scale=1):138                chatbot = gr.Chatbot(elem_id="chuanhu_chatbot").style(height="100%")139            with gr.Row(scale=1):140                with gr.Column(scale=12):141                    user_input = gr.Textbox(142                        show_label=False, placeholder="在这里输入"143                    ).style(container=False)144                with gr.Column(min_width=70, scale=1):145                    submitBtn = gr.Button("发送", variant="primary")146            with gr.Row(scale=1):147                emptyBtn = gr.Button(148                    "🧹 新的对话",149                )150                retryBtn = gr.Button("🔄 重新生成")151                delLastBtn = gr.Button("🗑️ 删除一条对话")152                reduceTokenBtn = gr.Button("♻️ 总结对话")153 154        with gr.Column():155            with gr.Column(min_width=50, scale=1):156                with gr.Tab(label="ChatGPT"):157                    keyTxt = gr.Textbox(158                        show_label=True,159                        placeholder=f"OpenAI API-key...",160                        value=hide_middle_chars(my_api_key),161                        type="password",162                        visible=not HIDE_MY_KEY,163                        label="API-Key",164                    )165                    model_select_dropdown = gr.Dropdown(166                        label="选择模型", choices=MODELS, multiselect=False, value=MODELS[0]167                    )168                    use_streaming_checkbox = gr.Checkbox(169                        label="实时传输回答", value=True, visible=enable_streaming_option170                    )171                    use_websearch_checkbox = gr.Checkbox(label="使用在线搜索", value=False)172                    index_files = gr.Files(label="上传索引文件", type="file", multiple=True)173 174                with gr.Tab(label="Prompt"):175                    systemPromptTxt = gr.Textbox(176                        show_label=True,177                        placeholder=f"在这里输入System Prompt...",178                        label="System prompt",179                        value=initial_prompt,180                        lines=10,181                    ).style(container=False)182                    with gr.Accordion(label="加载Prompt模板", open=True):183                        with gr.Column():184                            with gr.Row():185                                with gr.Column(scale=6):186                                    templateFileSelectDropdown = gr.Dropdown(187                                        label="选择Prompt模板集合文件",188                                        choices=get_template_names(plain=True),189                                        multiselect=False,190                                        value=get_template_names(plain=True)[0],191                                    ).style(container=False)192                                with gr.Column(scale=1):193                                    templateRefreshBtn = gr.Button("🔄 刷新")194                            with gr.Row():195                                with gr.Column():196                                    templateSelectDropdown = gr.Dropdown(197                                        label="从Prompt模板中加载",198                                        choices=load_template(199                                            get_template_names(plain=True)[0], mode=1200                                        ),201                                        multiselect=False,202                                        value=load_template(203                                            get_template_names(plain=True)[0], mode=1204                                        )[0],205                                    ).style(container=False)206 207                with gr.Tab(label="保存/加载"):208                    with gr.Accordion(label="保存/加载对话历史记录", open=True):209                        with gr.Column():210                            with gr.Row():211                                with gr.Column(scale=6):212                                    historyFileSelectDropdown = gr.Dropdown(213                                        label="从列表中加载对话",214                                        choices=get_history_names(plain=True),215                                        multiselect=False,216                                        value=get_history_names(plain=True)[0],217                                    )218                                with gr.Column(scale=1):219                                    historyRefreshBtn = gr.Button("🔄 刷新")220                            with gr.Row():221                                with gr.Column(scale=6):222                                    saveFileName = gr.Textbox(223                                        show_label=True,224                                        placeholder=f"设置文件名: 默认为.json,可选为.md",225                                        label="设置保存文件名",226                                        value="对话历史记录",227                                    ).style(container=True)228                                with gr.Column(scale=1):229                                    saveHistoryBtn = gr.Button("💾 保存对话")230                                    exportMarkdownBtn = gr.Button("📝 导出为Markdown")231                                    gr.Markdown("默认保存于history文件夹")232                            with gr.Row():233                                with gr.Column():234                                    downloadFile = gr.File(interactive=True)235 236                with gr.Tab(label="高级"):237                    default_btn = gr.Button("🔙 恢复默认设置")238                    gr.Markdown("# ⚠️ 务必谨慎更改 ⚠️\n\n如果无法使用请恢复默认设置")239 240                    with gr.Accordion("参数", open=False):241                        top_p = gr.Slider(242                            minimum=-0,243                            maximum=1.0,244                            value=1.0,245                            step=0.05,246                            interactive=True,247                            label="Top-p",248                        )249                        temperature = gr.Slider(250                            minimum=-0,251                            maximum=2.0,252                            value=1.0,253                            step=0.1,254                            interactive=True,255                            label="Temperature",256                        )257 258                    apiurlTxt = gr.Textbox(259                        show_label=True,260                        placeholder=f"在这里输入API地址...",261                        label="API地址",262                        value="https://api.openai.com/v1/chat/completions",263                        lines=2,264                    )265                    changeAPIURLBtn = gr.Button("🔄 切换API地址")266                    proxyTxt = gr.Textbox(267                        show_label=True,268                        placeholder=f"在这里输入代理地址...",269                        label="代理地址(示例:http://127.0.0.1:10809)",270                        value="",271                        lines=2,272                    )273                    changeProxyBtn = gr.Button("🔄 设置代理地址")274 275    gr.Markdown(description)276 277    keyTxt.submit(submit_key, keyTxt, [user_api_key, status_display])278    keyTxt.change(submit_key, keyTxt, [user_api_key, status_display])279    # Chatbot280    user_input.submit(281        predict,282        [283            user_api_key,284            systemPromptTxt,285            history,286            user_input,287            chatbot,288            token_count,289            top_p,290            temperature,291            use_streaming_checkbox,292            model_select_dropdown,293            use_websearch_checkbox,294            index_files,295        ],296        [chatbot, history, status_display, token_count],297        show_progress=True,298    )299    user_input.submit(reset_textbox, [], [user_input])300 301    submitBtn.click(302        predict,303        [304            user_api_key,305            systemPromptTxt,306            history,307            user_input,308            chatbot,309            token_count,310            top_p,311            temperature,312            use_streaming_checkbox,313            model_select_dropdown,314            use_websearch_checkbox,315            index_files,316        ],317        [chatbot, history, status_display, token_count],318        show_progress=True,319    )320    submitBtn.click(reset_textbox, [], [user_input])321 322    emptyBtn.click(323        reset_state,324        outputs=[chatbot, history, token_count, status_display],325        show_progress=True,326    )327 328    retryBtn.click(329        retry,330        [331            user_api_key,332            systemPromptTxt,333            history,334            chatbot,335            token_count,336            top_p,337            temperature,338            use_streaming_checkbox,339            model_select_dropdown,340        ],341        [chatbot, history, status_display, token_count],342        show_progress=True,343    )344 345    delLastBtn.click(346        delete_last_conversation,347        [chatbot, history, token_count],348        [chatbot, history, token_count, status_display],349        show_progress=True,350    )351 352    reduceTokenBtn.click(353        reduce_token_size,354        [355            user_api_key,356            systemPromptTxt,357            history,358            chatbot,359            token_count,360            top_p,361            temperature,362            gr.State(0),363            model_select_dropdown,364        ],365        [chatbot, history, status_display, token_count],366        show_progress=True,367    )368 369    # Template370    templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])371    templateFileSelectDropdown.change(372        load_template,373        [templateFileSelectDropdown],374        [promptTemplates, templateSelectDropdown],375        show_progress=True,376    )377    templateSelectDropdown.change(378        get_template_content,379        [promptTemplates, templateSelectDropdown, systemPromptTxt],380        [systemPromptTxt],381        show_progress=True,382    )383 384    # S&L385    saveHistoryBtn.click(386        save_chat_history,387        [saveFileName, systemPromptTxt, history, chatbot],388        downloadFile,389        show_progress=True,390    )391    saveHistoryBtn.click(get_history_names, None, [historyFileSelectDropdown])392    exportMarkdownBtn.click(393        export_markdown,394        [saveFileName, systemPromptTxt, history, chatbot],395        downloadFile,396        show_progress=True,397    )398    historyRefreshBtn.click(get_history_names, None, [historyFileSelectDropdown])399    historyFileSelectDropdown.change(400        load_chat_history,401        [historyFileSelectDropdown, systemPromptTxt, history, chatbot],402        [saveFileName, systemPromptTxt, history, chatbot],403        show_progress=True,404    )405    downloadFile.change(406        load_chat_history,407        [downloadFile, systemPromptTxt, history, chatbot],408        [saveFileName, systemPromptTxt, history, chatbot],409    )410 411    # Advanced412    default_btn.click(413        reset_default, [], [apiurlTxt, proxyTxt, status_display], show_progress=True414    )415    changeAPIURLBtn.click(416        change_api_url,417        [apiurlTxt],418        [status_display],419        show_progress=True,420    )421    changeProxyBtn.click(422        change_proxy,423        [proxyTxt],424        [status_display],425        show_progress=True,426    )427 428logging.info(429    colorama.Back.GREEN430    + "\n川虎的温馨提示:访问 http://localhost:7860 查看界面"431    + colorama.Style.RESET_ALL432)433# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接434demo.title = "阿猿ChatGPT 🚀"435 436if __name__ == "__main__":437    reload_javascript()438    # if running in Docker439    if dockerflag:440        if authflag:441            demo.queue().launch(442                server_name="0.0.0.0", server_port=7860, auth=(username, password),443                favicon_path="./assets/favicon.png"444            )445        else:446            demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False, favicon_path="./assets/favicon.png")447    # if not running in Docker448    else:449        if authflag:450            demo.queue().launch(share=False, auth=(username, password), favicon_path="./assets/favicon.png", inbrowser=True)451        else:452            demo.queue(concurrency_count=1000).launch(share=False,  favicon_path="./assets/favicon.ico", inbrowser=True)  # 改为 share=True 可以创建公开分享链接453        # demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口454        # demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码455        # demo.queue().launch(auth=("在这里填写用户名", "在这里填写密码")) # 适合Nginx反向代理456