binker commited on
Commit
a5bbef7
·
1 Parent(s): 5918399

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from response_parser import *
2
+ import gradio as gr
3
+
4
+
5
+ def initialization(state_dict: Dict) -> None:
6
+ if not os.path.exists('cache'):
7
+ os.mkdir('cache')
8
+ if state_dict["bot_backend"] is None:
9
+ state_dict["bot_backend"] = BotBackend()
10
+ if 'OPENAI_API_KEY' in os.environ:
11
+ del os.environ['OPENAI_API_KEY']
12
+
13
+
14
+ def get_bot_backend(state_dict: Dict) -> BotBackend:
15
+ return state_dict["bot_backend"]
16
+
17
+
18
+ def switch_to_gpt4(state_dict: Dict, whether_switch: bool) -> None:
19
+ bot_backend = get_bot_backend(state_dict)
20
+ if whether_switch:
21
+ bot_backend.update_gpt_model_choice("GPT-4")
22
+ else:
23
+ bot_backend.update_gpt_model_choice("GPT-3.5")
24
+
25
+
26
+ def add_text(state_dict: Dict, history: List, text: str) -> Tuple[List, Dict]:
27
+ bot_backend = get_bot_backend(state_dict)
28
+ bot_backend.add_text_message(user_text=text)
29
+
30
+ history = history + [(text, None)]
31
+
32
+ return history, gr.update(value="", interactive=False)
33
+
34
+
35
+ def add_file(state_dict: Dict, history: List, file) -> List:
36
+ bot_backend = get_bot_backend(state_dict)
37
+ path = file.name
38
+ filename = os.path.basename(path)
39
+
40
+ bot_msg = [f'📁[{filename}]', None]
41
+ history.append(bot_msg)
42
+
43
+ bot_backend.add_file_message(path=path, bot_msg=bot_msg)
44
+
45
+ return history
46
+
47
+
48
+ def undo_upload_file(state_dict: Dict, history: List) -> Tuple[List, Dict]:
49
+ bot_backend = get_bot_backend(state_dict)
50
+ bot_msg = bot_backend.revoke_file()
51
+
52
+ if bot_msg is None:
53
+ return history, gr.Button.update(interactive=False)
54
+
55
+ else:
56
+ assert history[-1] == bot_msg
57
+ del history[-1]
58
+ if bot_backend.revocable_files:
59
+ return history, gr.Button.update(interactive=True)
60
+ else:
61
+ return history, gr.Button.update(interactive=False)
62
+
63
+
64
+ def refresh_file_display(state_dict: Dict) -> List[str]:
65
+ bot_backend = get_bot_backend(state_dict)
66
+ work_dir = bot_backend.jupyter_work_dir
67
+ filenames = os.listdir(work_dir)
68
+ paths = []
69
+ for filename in filenames:
70
+ paths.append(
71
+ os.path.join(work_dir, filename)
72
+ )
73
+ return paths
74
+
75
+
76
+ def restart_ui(history: List) -> Tuple[List, Dict, Dict, Dict, Dict]:
77
+ history.clear()
78
+ return (
79
+ history,
80
+ gr.Textbox.update(value="", interactive=False),
81
+ gr.Button.update(interactive=False),
82
+ gr.Button.update(interactive=False),
83
+ gr.Button.update(interactive=False)
84
+ )
85
+
86
+
87
+ def restart_bot_backend(state_dict: Dict) -> None:
88
+ bot_backend = get_bot_backend(state_dict)
89
+ bot_backend.restart()
90
+
91
+
92
+ def bot(state_dict: Dict, history: List) -> List:
93
+ bot_backend = get_bot_backend(state_dict)
94
+
95
+ while bot_backend.finish_reason in ('new_input', 'function_call'):
96
+ if history[-1][0] is None:
97
+ history.append(
98
+ [None, ""]
99
+ )
100
+ else:
101
+ history[-1][1] = ""
102
+
103
+ response = chat_completion(bot_backend=bot_backend)
104
+ for chunk in response:
105
+ history, weather_exit = parse_response(
106
+ chunk=chunk,
107
+ history=history,
108
+ bot_backend=bot_backend
109
+ )
110
+ yield history
111
+ if weather_exit:
112
+ exit(-1)
113
+
114
+ yield history
115
+
116
+
117
+ if __name__ == '__main__':
118
+ config = get_config()
119
+ with gr.Blocks(theme=gr.themes.Base()) as block:
120
+ """
121
+ Reference: https://www.gradio.app/guides/creating-a-chatbot-fast
122
+ """
123
+ # UI components
124
+ state = gr.State(value={"bot_backend": None})
125
+ with gr.Tab("Chat"):
126
+ chatbot = gr.Chatbot([], elem_id="chatbot", label="Local Code Interpreter", height=750)
127
+ with gr.Row():
128
+ with gr.Column(scale=0.85):
129
+ text_box = gr.Textbox(
130
+ show_label=False,
131
+ placeholder="Enter text and press enter, or upload a file",
132
+ container=False
133
+ )
134
+ with gr.Column(scale=0.15, min_width=0):
135
+ file_upload_button = gr.UploadButton("📁", file_types=['file'])
136
+ with gr.Row(equal_height=True):
137
+ with gr.Column(scale=0.7):
138
+ check_box = gr.Checkbox(label="Use GPT-4", interactive=config['model']['GPT-4']['available'])
139
+ check_box.change(fn=switch_to_gpt4, inputs=[state, check_box])
140
+ with gr.Column(scale=0.15, min_width=0):
141
+ restart_button = gr.Button(value='🔄 Restart')
142
+ with gr.Column(scale=0.15, min_width=0):
143
+ undo_file_button = gr.Button(value="↩️Undo upload file", interactive=False)
144
+ with gr.Tab("Files"):
145
+ file_output = gr.Files()
146
+
147
+ # Components function binding
148
+ txt_msg = text_box.submit(add_text, [state, chatbot, text_box], [chatbot, text_box], queue=False).then(
149
+ bot, [state, chatbot], chatbot
150
+ )
151
+ txt_msg.then(fn=refresh_file_display, inputs=[state], outputs=[file_output])
152
+ txt_msg.then(lambda: gr.update(interactive=True), None, [text_box], queue=False)
153
+ txt_msg.then(lambda: gr.Button.update(interactive=False), None, [undo_file_button], queue=False)
154
+
155
+ file_msg = file_upload_button.upload(
156
+ add_file, [state, chatbot, file_upload_button], [chatbot], queue=False
157
+ ).then(
158
+ bot, [state, chatbot], chatbot
159
+ )
160
+ file_msg.then(lambda: gr.Button.update(interactive=True), None, [undo_file_button], queue=False)
161
+ file_msg.then(fn=refresh_file_display, inputs=[state], outputs=[file_output])
162
+
163
+ undo_file_button.click(
164
+ fn=undo_upload_file, inputs=[state, chatbot], outputs=[chatbot, undo_file_button]
165
+ ).then(
166
+ fn=refresh_file_display, inputs=[state], outputs=[file_output]
167
+ )
168
+
169
+ restart_button.click(
170
+ fn=restart_ui, inputs=[chatbot],
171
+ outputs=[chatbot, text_box, restart_button, file_upload_button, undo_file_button]
172
+ ).then(
173
+ fn=restart_bot_backend, inputs=[state], queue=False
174
+ ).then(
175
+ fn=refresh_file_display, inputs=[state], outputs=[file_output]
176
+ ).then(
177
+ fn=lambda: (gr.Textbox.update(interactive=True), gr.Button.update(interactive=True),
178
+ gr.Button.update(interactive=True)),
179
+ inputs=None, outputs=[text_box, restart_button, file_upload_button], queue=False
180
+ )
181
+
182
+ block.load(fn=initialization, inputs=[state])
183
+
184
+ block.queue()
185
+ block.launch(inbrowser=True)