gradio_app.py 7.83 KB
Newer Older
1
# -*- coding: utf-8 -*-
陈正乐 committed
2 3 4
import sys

sys.path.append('../')
5
import gradio as gr
6
from langchain_core.prompts import PromptTemplate
7 8

from src.llm.chatglm import ChatGLMSerLLM
9 10
from src.llm.ernie_with_sdk import ChatERNIESerLLM
from qianfan import ChatCompletion
11
import os
陈正乐 committed
12
import asyncio
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
from src.pgdb.chat.c_db import UPostgresDB
from src.pgdb.knowledge.similarity import VectorStore_FAISS
from src.config.consts import (
    CHAT_DB_USER,
    CHAT_DB_HOST,
    CHAT_DB_PORT,
    CHAT_DB_DBNAME,
    CHAT_DB_PASSWORD,
    EMBEEDING_MODEL_PATH,
    FAISS_STORE_PATH,
    INDEX_NAME,
    VEC_DB_HOST,
    VEC_DB_PASSWORD,
    VEC_DB_PORT,
    VEC_DB_USER,
    VEC_DB_DBNAME,
陈正乐 committed
29 30
    SIMILARITY_SHOW_NUMBER,
    GR_PORT,
陈正乐 committed
31 32
    GR_SERVER_NAME,
    ICON_PATH
33 34 35 36 37 38 39 40 41 42 43
)
from src.server.qa import QA

prompt1 = """'''
{context}
'''
请你根据上述已知资料回答下面的问题,问题如下:
{question}"""

PROMPT1 = PromptTemplate(input_variables=["context", "question"], template=prompt1)

陈正乐 committed
44 45

def main():
46 47 48 49 50 51 52 53 54 55
    c_db = UPostgresDB(host=CHAT_DB_HOST, database=CHAT_DB_DBNAME, user=CHAT_DB_USER, password=CHAT_DB_PASSWORD,
                       port=CHAT_DB_PORT, )
    vecstore_faiss = VectorStore_FAISS(
        embedding_model_name=EMBEEDING_MODEL_PATH,
        store_path=FAISS_STORE_PATH,
        index_name=INDEX_NAME,
        info={"port": VEC_DB_PORT, "host": VEC_DB_HOST, "dbname": VEC_DB_DBNAME, "username": VEC_DB_USER,
              "password": VEC_DB_PASSWORD},
        show_number=SIMILARITY_SHOW_NUMBER,
        reset=False)
陈正乐 committed
56 57 58
    base_llm = ChatERNIESerLLM(
        chat_completion=ChatCompletion(ak="pT7sV1smp4AeDl0LjyZuHBV9", sk="b3N0ibo1IKTLZlSs7weZc8jdR0oHjyMu"))
    # base_llm = ChatGLMSerLLM(url='http://192.168.22.106:8088')
59

60
    my_chat = QA(PROMPT1, base_llm, {"temperature": 0.9}, ['context', 'question'], _db=c_db,
陈正乐 committed
61
                 _faiss_db=vecstore_faiss)
62

陈正乐 committed
63 64
    def clear():  # 清空输入框
        return ''
65

陈正乐 committed
66
    def show_history():  # 显示对话历史
67 68
        return my_chat.get_history()

陈正乐 committed
69 70 71 72 73 74
    def stop_btn():
        return gr.Button(interactive=False)

    def restart_btn():
        return gr.Button(interactive=True)

75
    def get_users():
陈正乐 committed
76 77
        o_users = my_chat.get_users()
        users_l = [item[0] for item in o_users]
陈正乐 committed
78 79
        return gr.components.Radio(choices=users_l, label="选择一个用户", value=users_l[0], interactive=True), users_l[
            0]
80

陈正乐 committed
81 82 83
    def create_chat(user_account):
        my_chat.create_chat(user_account)

84 85
    def get_chats(user_account):
        o_chats = my_chat.get_chats(user_account)
陈正乐 committed
86 87
        if len(o_chats) >= 13:
            o_chats = o_chats[:13]
陈正乐 committed
88
        chats_l = [item[0] + ':' + item[1] for item in o_chats]
陈正乐 committed
89 90 91 92 93 94 95
        if my_chat.chat_id:
            result = [item for item in chats_l if item.split(":")[0].strip() == my_chat.chat_id][0]
            return gr.components.Radio(choices=chats_l, label="历史对话", value=result, interactive=True,
                                       show_label=True)
        else:
            return gr.components.Radio(choices=chats_l, label="历史对话", value=chats_l[0], interactive=True,
                                       show_label=True)
96

陈正乐 committed
97 98 99
    def set_info(question):
        my_chat.set_info(question)

100 101 102 103
    def set_chat_id(chat_id_info):
        chat_id = chat_id_info.split(':')[0]
        my_chat.set_chat_id(chat_id)

陈正乐 committed
104 105 106 107 108
    def load():
        l_users, t_user = get_users()
        l_chats = get_chats(t_user)
        return l_users, l_chats

陈正乐 committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    def clear_text(t):
        if t == "请输入您的问题":
            return ""
        else:
            return t

    def reset_text():
        return ""

    def blur(t):
        if t == "":
            return "请输入您的问题"
        else:
            return t

    def text_his(text, history):
        history = history + [[text, None]]
        return history

    def clear_tip(his):
陈正乐 committed
129
        if not his[0][0] and his[0][1] == "你好,我是新晨科技股份的低空经济人工智能助手小晨,如果您有低空经济相关问题,欢迎随时向我咨询。":
陈正乐 committed
130 131 132 133 134 135
            return his[1:]
        else:
            return his

    with gr.Blocks(css='index.css', title="低空经济知识问答") as demo:
        gr.HTML("""<h1 align="center">低空经济知识问答</h1>""", visible=False)
136
        with gr.Row():
陈正乐 committed
137
            with gr.Column(scale=2, visible=False):
陈正乐 committed
138
                users = gr.components.Radio(choices=[], label="选择一个用户", interactive=True,
陈正乐 committed
139
                                            visible=False, show_label=False)
陈正乐 committed
140 141 142
                chats = gr.components.Radio(choices=[], label="历史对话", interactive=True,
                                            show_label=True, visible=False)
                new_chat_btn = gr.Button("新建对话", visible=False)
143 144
            with gr.Column(scale=8):
                chatbot = gr.Chatbot(bubble_full_width=False,
陈正乐 committed
145
                                     avatar_images=(ICON_PATH + '\\user2.png', ICON_PATH + "\\bot2.png"),
陈正乐 committed
146
                                     value=[[None,
陈正乐 committed
147
                                             "你好,我是新晨科技股份的低空经济人工智能助手小晨,如果您有低空经济相关问题,欢迎随时向我咨询。"]],
陈正乐 committed
148
                                     height=400, show_copy_button=True,
陈正乐 committed
149 150
                                     show_label=False, line_breaks=True)
                with gr.Row():
陈正乐 committed
151 152
                    input_text = gr.Textbox(show_label=False, lines=1, label="文本输入", scale=9, container=False,
                                            placeholder="请输入您的问题", max_lines=1)
陈正乐 committed
153 154
                    sub_btn = gr.Button("提交", scale=1)

陈正乐 committed
155 156 157 158 159 160 161 162 163 164 165 166
        sub_btn.click(
            stop_btn, [], sub_btn
        ).success(
            clear_tip, [chatbot], [chatbot]
        ).success(
            text_his, [input_text, chatbot], [chatbot]
        ).success(
            reset_text, [], input_text
        ).success(
            my_chat.async_chat2, [chatbot], [chatbot]
        ).success(
            restart_btn, [], sub_btn
陈正乐 committed
167
        )
168

陈正乐 committed
169 170 171 172 173 174 175
        # input_text.submit(
        #     stop_btn, [], sub_btn
        # ).then(
        #     my_chat.async_chat2, [input_text, chatbot], [chatbot]
        # ).then(
        #     restart_btn, [], sub_btn
        # )
176

陈正乐 committed
177
        demo.load(load, [], [users, chats])
陈正乐 committed
178

陈正乐 committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        # input_text.submit(my_chat.async_chat, [input_text], [chatbot]
        #               ).then(
        #     stop_btn, None, sub_btn
        # ).then(
        #     set_info, [input_text], []
        # ).then(
        #     get_chats, [users], [chats]
        # ).then(
        #     my_chat.update_history, None, None
        # ).then(
        #     show_history, None, chatbot
        # ).then(
        #     clear, None, [input_text]
        # ).then(
        #     restart_btn, None, sub_btn
        # ).then(
        #     reset_text, [], input_text
        # )

        # new_chat_btn.click(create_chat, [users], []).then(
        #     get_chats, [users], [chats]
        # )

        # users.change(get_chats, [users], [chats]).then(
        #     set_chat_id, [chats], None
        # ).then(
        #     show_history, None, chatbot
        # )

        # chats.change(set_chat_id, [chats], None).then(
        #     show_history, None, chatbot
        # )

        # sub_btn.click(my_chat.async_chat, [input_text], [chatbot]
        #               ).then(
        #     stop_btn, None, sub_btn
        # ).then(
        #     set_info, [input_text], []
        # ).then(
        #     get_chats, [users], [chats]
        # ).then(
        #     my_chat.update_history, None, None
        # ).then(
        #     show_history, None, chatbot
        # ).then(
        #     clear, None, [input_text]
        # ).then(
        #     restart_btn, None, sub_btn
        # ).then(
        #     reset_text, [], input_text
        # )

陈正乐 committed
231
    demo.queue().launch(share=False, inbrowser=True, server_name='0.0.0.0', server_port=GR_PORT)
232 233 234


if __name__ == "__main__":
陈正乐 committed
235
    main()