File size: 4,644 Bytes
f807e7d
 
 
 
175c5c3
f807e7d
 
 
 
 
 
 
 
 
 
 
 
 
9ef3a1d
f807e7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175c5c3
 
f807e7d
 
 
 
ea129da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import json
import time
import random

import gradio as gr
import pandas as pd

from utils.gpt_processor import QuestionAnswerer

qa_processor = QuestionAnswerer()
current_file = None
context = None

with open("final_result.json", 'r', encoding='UTF-8') as fp:
    db = json.load(fp)

def read_examples():
    df = pd.read_csv(r'examples.csv')
    return [f"{keyword}" for keyword in df['word'].tolist()]

def user(message, history):
    #return gr.update(value="", interactive=False), history + [[message, None]]
    return "", history + [[message, None]]

def bot(history):
    user_message = history[-1][0]
    global current_file
    global context
    #check if user input has "我想了解"
    if "我想了解" in user_message:
        # get keyword from "「」"
        keyword = user_message.split("「")[1].split("」")[0]
        # check if keyword is in db
        file_list = []
        for key in db.keys():
            if keyword in db[key]['keywords']:
                file_list.append(key)
        if len(file_list) == 0:
            response = [
                [user_message, "Sorry, I can't find any documents about this topic. Please try again."],
            ]
        else:
            bot_message = "以下是我所找到的文件:"
            for file in file_list:
                bot_message += "\n" + file
            bot_message += "\n\n" + "請複製貼上想要了解的文件,我會給你該文件的摘要"
            response = [
                [user_message, bot_message],
            ]
        history = response
        # history[-1][1] = ""
        # for character in bot_message:
        #     history[-1][1] += character
        #     time.sleep(random.uniform(0.01, 0.05))
        #     yield history
        return history
    
    # check if user input has a pdf file name
    if ".pdf" in user_message or ".docx" in user_message:
        current_file = user_message
        context = db[current_file]['file_full_content']
        # check if file name is in db
        if user_message in db.keys():
            bot_message = f"文件 {user_message} 的摘要如下:"
            bot_message += "\n\n" + db[user_message]['summarized_content']
            bot_message += "\n\n" + "可以透過詢問來了解更多這個文件的內容"
            response = [
                [user_message, bot_message],
            ]
        else:
            response = [
                [user_message, "Sorry, I can't find this file. Please try again."],
            ]
        history[-1] = response[0]
        # history[-1][1] = ""
        # for character in bot_message:
        #     history[-1][1] += character
        #     time.sleep(random.uniform(0.01, 0.05))
        #     yield history
        return history
    if context is None:
        response = [
            [user_message, "請輸入一個文件名稱或是點選下方的範例"],
        ]
        history[-1] = response[0]
        return history
    
    if context is not None:
        bot_message = qa_processor.answer_question(context, user_message)
        response = [
            [user_message, bot_message],
        ]
        history[-1] = response[0]
        return history

with gr.Blocks() as demo:
    history = gr.State([])
    user_question = gr.State("")
    with gr.Row():
        gr.HTML('Junyi Academy Chatbot')
        #status_display = gr.Markdown("Success", elem_id="status_display")
    with gr.Row(equal_height=True):
        with gr.Column(scale=5):
            with gr.Row():
                chatbot = gr.Chatbot()

            with gr.Row():
                with gr.Column(scale=12):
                    user_input = gr.Textbox(
                        show_label=False,
                        placeholder="Enter text",
                        container=False,
                    )
                # with gr.Column(min_width=70, scale=1):
                #     submit_btn = gr.Button("Send")
                with gr.Column(min_width=70, scale=1):
                    clear_btn = gr.Button("Clear")

                response = user_input.submit(user, 
                                  [user_input, chatbot], 
                                  [user_input, chatbot], 
                                  queue=False,
                                  ).then(bot, chatbot, chatbot)
                response.then(lambda: gr.update(interactive=True), None, [user_input], queue=False)
                clear_btn.click(lambda: None, None, chatbot, queue=False)


    examples = gr.Examples(examples=read_examples(),
                           inputs=[user_input])
    
if __name__ == "__main__":
    demo.launch()