JohnSmith9982 commited on
Commit
4e8a8a4
1 Parent(s): 2f876ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -24
app.py CHANGED
@@ -6,18 +6,34 @@ import sys
6
  import traceback
7
  import requests
8
  # import markdown
 
9
 
10
  my_api_key = "" # 在这里输入你的 API 密钥
11
  initial_prompt = "You are a helpful assistant."
12
-
13
  API_URL = "https://api.openai.com/v1/chat/completions"
 
 
 
14
 
15
- if my_api_key == "":
16
- my_api_key = os.environ.get('my_api_key')
17
 
18
- if my_api_key == "empty":
19
- print("Please give a api key!")
20
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
 
23
  def parse_text(text):
@@ -40,7 +56,8 @@ def parse_text(text):
40
  line = line.replace("<", "&lt;")
41
  line = line.replace(">", "&gt;")
42
  line = line.replace(" ", "&nbsp;")
43
- lines[i] = '<br/>'+line
 
44
  return "".join(lines)
45
 
46
  def predict(inputs, top_p, temperature, openai_api_key, chatbot=[], history=[], system_prompt=initial_prompt, retry=False, summary=False): # repetition_penalty, top_k
@@ -70,7 +87,7 @@ def predict(inputs, top_p, temperature, openai_api_key, chatbot=[], history=[],
70
  messages[-1]['content'] = temp2['content']
71
  if retry and chat_counter:
72
  messages.pop()
73
- elif summary and chat_counter:
74
  messages.append(compose_user(
75
  "请帮我总结一下上述对话的内容,实现减少字数的同时,保证对话的质量。在总结中不要加入这一句话。"))
76
  history = ["我们刚刚聊了什么?"]
@@ -146,30 +163,47 @@ def delete_last_conversation(chatbot, history):
146
  history.pop()
147
  return chatbot, history
148
 
149
- def save_chat_history(filepath, system, history, chatbot):
150
- if filepath == "":
151
  return
152
- if not filepath.endswith(".json"):
153
- filepath += ".json"
 
154
  json_s = {"system": system, "history": history, "chatbot": chatbot}
155
- with open(filepath, "w") as f:
156
  json.dump(json_s, f)
157
 
158
 
159
  def load_chat_history(filename):
160
- with open(filename, "r") as f:
161
  json_s = json.load(f)
162
  return filename, json_s["system"], json_s["history"], json_s["chatbot"]
163
 
164
 
165
- def get_history_names(plain=False):
166
  # find all json files in the current directory and return their names
167
- files = [f for f in os.listdir() if f.endswith(".json")]
 
 
 
168
  if plain:
169
  return files
170
  else:
171
  return gr.Dropdown.update(choices=files)
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
  def reset_state():
175
  return [], []
@@ -202,6 +236,7 @@ with gr.Blocks() as demo:
202
  value=my_api_key, label="API Key", type="password").style(container=True)
203
  chatbot = gr.Chatbot() # .style(color_map=("#1D51EE", "#585A5B"))
204
  history = gr.State([])
 
205
  TRUECOMSTANT = gr.State(True)
206
  FALSECONSTANT = gr.State(False)
207
  topic = gr.State("未命名对话历史记录")
@@ -219,6 +254,19 @@ with gr.Blocks() as demo:
219
  reduceTokenBtn = gr.Button("♻️ 总结对话")
220
  systemPromptTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入System Prompt...",
221
  label="System prompt", value=initial_prompt).style(container=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  with gr.Accordion(label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到Python文件旁边)", open=False):
223
  with gr.Column():
224
  with gr.Row():
@@ -229,10 +277,10 @@ with gr.Blocks() as demo:
229
  saveBtn = gr.Button("💾 保存对话")
230
  with gr.Row():
231
  with gr.Column(scale=6):
232
- uploadDropdown = gr.Dropdown(label="从列表中加载对话", choices=get_history_names(plain=True), multiselect=False)
233
  with gr.Column(scale=1):
234
- refreshBtn = gr.Button("🔄 刷新")
235
- uploadBtn = gr.Button("📂 读取对话")
236
  #inputs, top_p, temperature, top_k, repetition_penalty
237
  with gr.Accordion("参数", open=False):
238
  top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.05,
@@ -259,12 +307,25 @@ with gr.Blocks() as demo:
259
  systemPromptTxt, FALSECONSTANT, TRUECOMSTANT], [chatbot, history], show_progress=True)
260
  saveBtn.click(save_chat_history, [
261
  saveFileName, systemPromptTxt, history, chatbot], None, show_progress=True)
262
- saveBtn.click(get_history_names, None, [uploadDropdown])
263
- refreshBtn.click(get_history_names, None, [uploadDropdown])
264
- uploadBtn.click(load_chat_history, [uploadDropdown], [saveFileName, systemPromptTxt, history, chatbot], show_progress=True)
 
 
 
265
 
266
  print("川虎的温馨提示:访问 http://localhost:7860 查看界面")
267
  # 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接
268
  demo.title = "川虎ChatGPT 🚀"
269
- demo.queue().launch(server_name = "0.0.0.0", share=False) # 改为 share=True 可以创建公开分享链接
270
- # demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口
 
 
 
 
 
 
 
 
 
 
 
6
  import traceback
7
  import requests
8
  # import markdown
9
+ import csv
10
 
11
  my_api_key = "" # 在这里输入你的 API 密钥
12
  initial_prompt = "You are a helpful assistant."
 
13
  API_URL = "https://api.openai.com/v1/chat/completions"
14
+ HISTORY_DIR = "history"
15
+ TEMPLATES_DIR = "templates"
16
+
17
 
 
 
18
 
19
+ #if we are running in Docker
20
+ if os.environ.get('dockerrun') == 'yes':
21
+ dockerflag = True
22
+ else:
23
+ dockerflag = False
24
+
25
+ if dockerflag:
26
+ my_api_key = os.environ.get('my_api_key')
27
+ if my_api_key == "empty":
28
+ print("Please give a api key!")
29
+ sys.exit(1)
30
+ #auth
31
+ username = os.environ.get('USERNAME')
32
+ password = os.environ.get('PASSWORD')
33
+ if isinstance(username, type(None)) or isinstance(password, type(None)):
34
+ authflag = False
35
+ else:
36
+ authflag = True
37
 
38
 
39
  def parse_text(text):
 
56
  line = line.replace("<", "&lt;")
57
  line = line.replace(">", "&gt;")
58
  line = line.replace(" ", "&nbsp;")
59
+ if not line.startswith("<br/>"):
60
+ lines[i] = '<br/>'+line
61
  return "".join(lines)
62
 
63
  def predict(inputs, top_p, temperature, openai_api_key, chatbot=[], history=[], system_prompt=initial_prompt, retry=False, summary=False): # repetition_penalty, top_k
 
87
  messages[-1]['content'] = temp2['content']
88
  if retry and chat_counter:
89
  messages.pop()
90
+ elif summary:
91
  messages.append(compose_user(
92
  "请帮我总结一下上述对话的内容,实现减少字数的同时,保证对话的质量。在总结中不要加入这一句话。"))
93
  history = ["我们刚刚聊了什么?"]
 
163
  history.pop()
164
  return chatbot, history
165
 
166
+ def save_chat_history(filename, system, history, chatbot):
167
+ if filename == "":
168
  return
169
+ if not filename.endswith(".json"):
170
+ filename += ".json"
171
+ os.makedirs(HISTORY_DIR, exist_ok=True)
172
  json_s = {"system": system, "history": history, "chatbot": chatbot}
173
+ with open(os.path.join(HISTORY_DIR, filename), "w") as f:
174
  json.dump(json_s, f)
175
 
176
 
177
  def load_chat_history(filename):
178
+ with open(os.path.join(HISTORY_DIR, filename), "r") as f:
179
  json_s = json.load(f)
180
  return filename, json_s["system"], json_s["history"], json_s["chatbot"]
181
 
182
 
183
+ def get_file_names(dir, plain=False, filetype=".json"):
184
  # find all json files in the current directory and return their names
185
+ try:
186
+ files = [f for f in os.listdir(dir) if f.endswith(filetype)]
187
+ except FileNotFoundError:
188
+ files = []
189
  if plain:
190
  return files
191
  else:
192
  return gr.Dropdown.update(choices=files)
193
 
194
+ def get_history_names(plain=False):
195
+ return get_file_names(HISTORY_DIR, plain)
196
+
197
+ def load_template(filename):
198
+ lines = []
199
+ with open(os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8") as csvfile:
200
+ reader = csv.reader(csvfile)
201
+ lines = list(reader)
202
+ lines = lines[1:]
203
+ return {row[0]:row[1] for row in lines}, gr.Dropdown.update(choices=[row[0] for row in lines])
204
+
205
+ def get_template_names(plain=False):
206
+ return get_file_names(TEMPLATES_DIR, plain, filetype=".csv")
207
 
208
  def reset_state():
209
  return [], []
 
236
  value=my_api_key, label="API Key", type="password").style(container=True)
237
  chatbot = gr.Chatbot() # .style(color_map=("#1D51EE", "#585A5B"))
238
  history = gr.State([])
239
+ promptTemplates = gr.State({})
240
  TRUECOMSTANT = gr.State(True)
241
  FALSECONSTANT = gr.State(False)
242
  topic = gr.State("未命名对话历史记录")
 
254
  reduceTokenBtn = gr.Button("♻️ 总结对话")
255
  systemPromptTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入System Prompt...",
256
  label="System prompt", value=initial_prompt).style(container=True)
257
+ with gr.Accordion(label="加载Prompt模板", open=False):
258
+ with gr.Column():
259
+ with gr.Row():
260
+ with gr.Column(scale=6):
261
+ templateFileSelectDropdown = gr.Dropdown(label="选择Prompt模板集合文件(.csv)", choices=get_template_names(plain=True), multiselect=False)
262
+ with gr.Column(scale=1):
263
+ templateRefreshBtn = gr.Button("🔄 刷新")
264
+ templaeFileReadBtn = gr.Button("📂 读入模板")
265
+ with gr.Row():
266
+ with gr.Column(scale=6):
267
+ templateSelectDropdown = gr.Dropdown(label="从Prompt模板中加载", choices=[], multiselect=False)
268
+ with gr.Column(scale=1):
269
+ templateApplyBtn = gr.Button("⬇️ 应用")
270
  with gr.Accordion(label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到Python文件旁边)", open=False):
271
  with gr.Column():
272
  with gr.Row():
 
277
  saveBtn = gr.Button("💾 保存对话")
278
  with gr.Row():
279
  with gr.Column(scale=6):
280
+ historyFileSelectDropdown = gr.Dropdown(label="从列表中加载对话", choices=get_history_names(plain=True), multiselect=False)
281
  with gr.Column(scale=1):
282
+ historyRefreshBtn = gr.Button("🔄 刷新")
283
+ historyReadBtn = gr.Button("📂 读入对话")
284
  #inputs, top_p, temperature, top_k, repetition_penalty
285
  with gr.Accordion("参数", open=False):
286
  top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.05,
 
307
  systemPromptTxt, FALSECONSTANT, TRUECOMSTANT], [chatbot, history], show_progress=True)
308
  saveBtn.click(save_chat_history, [
309
  saveFileName, systemPromptTxt, history, chatbot], None, show_progress=True)
310
+ saveBtn.click(get_history_names, None, [historyFileSelectDropdown])
311
+ historyRefreshBtn.click(get_history_names, None, [historyFileSelectDropdown])
312
+ historyReadBtn.click(load_chat_history, [historyFileSelectDropdown], [saveFileName, systemPromptTxt, history, chatbot], show_progress=True)
313
+ templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])
314
+ templaeFileReadBtn.click(load_template, [templateFileSelectDropdown], [promptTemplates, templateSelectDropdown], show_progress=True)
315
+ templateApplyBtn.click(lambda x, y: x[y], [promptTemplates, templateSelectDropdown], [systemPromptTxt], show_progress=True)
316
 
317
  print("川虎的温馨提示:访问 http://localhost:7860 查看界面")
318
  # 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接
319
  demo.title = "川虎ChatGPT 🚀"
320
+
321
+ #if running in Docker
322
+ if dockerflag:
323
+ if authflag:
324
+ demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=(username, password))
325
+ else:
326
+ demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)
327
+ #if not running in Docker
328
+ else:
329
+ demo.queue().launch(server_name = "0.0.0.0", share=False) # 改为 share=True 可以创建公开分享链接
330
+ #demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口
331
+ #demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码