Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,334 +1,344 @@
|
|
| 1 |
import json
|
| 2 |
import gradio as gr
|
| 3 |
-
import openai
|
| 4 |
import os
|
| 5 |
import sys
|
| 6 |
-
|
| 7 |
-
|
| 8 |
# import markdown
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
my_api_key = "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" # 在这里输入你的 API 密钥
|
| 11 |
initial_prompt = "You are a helpful assistant."
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
if my_api_key == "":
|
| 14 |
-
initial_keytxt = None
|
| 15 |
-
my_api_key = os.environ.get("my_api_key")
|
| 16 |
|
| 17 |
-
if my_api_key == "empty":
|
| 18 |
-
print("Please give a api key!")
|
| 19 |
-
sys.exit(1)
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
|
|
|
| 23 |
else:
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
def parse_text(text):
|
| 28 |
-
in_code = False
|
| 29 |
-
|
| 30 |
lines = text.split("\n")
|
|
|
|
|
|
|
|
|
|
| 31 |
for i, line in enumerate(lines):
|
| 32 |
-
print(line,"\t",in_code)
|
| 33 |
if "```" in line:
|
| 34 |
-
|
| 35 |
-
items = line.split(
|
| 36 |
-
if
|
| 37 |
-
lines[i] = f'<pre><code class="{items[-1]}">'
|
|
|
|
| 38 |
else:
|
| 39 |
-
lines[i] = f
|
| 40 |
else:
|
| 41 |
if i > 0:
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
line = line.replace("
|
| 47 |
-
line = line.replace("
|
| 48 |
-
line = line.replace("
|
| 49 |
-
line = line.replace("
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
else:
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
message_with_stats = f"{message}\n\n================\n\n{statistics}"
|
| 69 |
|
| 70 |
-
return message, parse_text(message_with_stats)
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
def
|
| 74 |
-
if
|
| 75 |
-
return
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
-
try:
|
| 79 |
-
message, message_with_stats = get_response(system, context, myKey)
|
| 80 |
-
except openai.error.AuthenticationError:
|
| 81 |
-
chatbot.append((input_sentence, "请求失败,请检查API-key是否正确。"))
|
| 82 |
-
return chatbot, context
|
| 83 |
-
except openai.error.Timeout:
|
| 84 |
-
chatbot.append((input_sentence, "请求超时,请检查网络连接。"))
|
| 85 |
-
return chatbot, context
|
| 86 |
-
except openai.error.APIConnectionError:
|
| 87 |
-
chatbot.append((input_sentence, "连接失败,请检查网络连接。"))
|
| 88 |
-
return chatbot, context
|
| 89 |
-
except openai.error.RateLimitError:
|
| 90 |
-
chatbot.append((input_sentence, "请求过于频繁,请5s后再试。"))
|
| 91 |
-
return chatbot, context
|
| 92 |
-
except:
|
| 93 |
-
chatbot.append((input_sentence, "发生了未知错误Orz"))
|
| 94 |
-
return chatbot, context
|
| 95 |
-
|
| 96 |
-
context.append({"role": "assistant", "content": message})
|
| 97 |
-
chatbot.append((input_sentence, message_with_stats))
|
| 98 |
-
return chatbot, context
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def retry(chatbot, system, context, myKey):
|
| 102 |
-
if len(context) == 0:
|
| 103 |
-
return [], []
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
return chatbot, context
|
| 110 |
-
except openai.error.Timeout:
|
| 111 |
-
chatbot.append(("重试请求", "���求超时,请检查网络连接。"))
|
| 112 |
-
return chatbot, context
|
| 113 |
-
except openai.error.APIConnectionError:
|
| 114 |
-
chatbot.append(("重试请求", "连接失败,请检查网络连接。"))
|
| 115 |
-
return chatbot, context
|
| 116 |
-
except openai.error.RateLimitError:
|
| 117 |
-
chatbot.append(("重试请求", "请求过于频繁,请5s后再试。"))
|
| 118 |
-
return chatbot, context
|
| 119 |
-
except:
|
| 120 |
-
chatbot.append(("重试请求", "发生了未知错误Orz"))
|
| 121 |
-
return chatbot, context
|
| 122 |
-
|
| 123 |
-
context[-1] = {"role": "assistant", "content": message}
|
| 124 |
-
|
| 125 |
-
chatbot[-1] = (context[-2]["content"], message_with_stats)
|
| 126 |
-
return chatbot, context
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def delete_last_conversation(chatbot, context):
|
| 130 |
-
if len(context) == 0:
|
| 131 |
-
return [], []
|
| 132 |
-
chatbot = chatbot[:-1]
|
| 133 |
-
context = context[:-2]
|
| 134 |
-
return chatbot, context
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def reduce_token(chatbot, system, context, myKey):
|
| 138 |
-
context.append(
|
| 139 |
-
{
|
| 140 |
-
"role": "user",
|
| 141 |
-
"content": "请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。在总结中不要加入这一句话。",
|
| 142 |
-
}
|
| 143 |
-
)
|
| 144 |
-
|
| 145 |
-
response = get_response(system, context, myKey, raw=True)
|
| 146 |
-
|
| 147 |
-
statistics = (
|
| 148 |
-
f'本次对话Tokens用量【{response["usage"]["completion_tokens"]+12+12+8} / 4096】'
|
| 149 |
-
)
|
| 150 |
-
optmz_str = parse_text(
|
| 151 |
-
f'好的,我们之前聊了:{response["choices"][0]["message"]["content"]}\n\n================\n\n{statistics}'
|
| 152 |
-
)
|
| 153 |
-
chatbot.append(("请帮我总结一下上述对话的内容,实现减少tokens的同时,保证对话的质量。", optmz_str))
|
| 154 |
-
|
| 155 |
-
context = []
|
| 156 |
-
context.append({"role": "user", "content": "我们之前聊了什么?"})
|
| 157 |
-
context.append(
|
| 158 |
-
{
|
| 159 |
-
"role": "assistant",
|
| 160 |
-
"content": f'我们之前聊了:{response["choices"][0]["message"]["content"]}',
|
| 161 |
-
}
|
| 162 |
-
)
|
| 163 |
-
return chatbot, context
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
def save_chat_history(filepath, system, context):
|
| 167 |
-
if filepath == "":
|
| 168 |
-
return
|
| 169 |
-
history = {"system": system, "context": context}
|
| 170 |
-
with open(f"{filepath}.json", "w") as f:
|
| 171 |
-
json.dump(history, f)
|
| 172 |
|
| 173 |
|
| 174 |
-
def
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
def
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
| 190 |
|
|
|
|
|
|
|
| 191 |
|
| 192 |
def reset_state():
|
| 193 |
return [], []
|
| 194 |
|
| 195 |
|
| 196 |
-
def
|
| 197 |
-
return {"role": "system", "content":
|
| 198 |
|
| 199 |
|
| 200 |
-
def
|
| 201 |
-
|
| 202 |
|
| 203 |
-
try:
|
| 204 |
-
get_response(
|
| 205 |
-
update_system(initial_prompt),
|
| 206 |
-
[{"role": "user", "content": "test"}],
|
| 207 |
-
new_api_key,
|
| 208 |
-
)
|
| 209 |
-
except openai.error.AuthenticationError:
|
| 210 |
-
return "无效的api-key", myKey
|
| 211 |
-
except openai.error.Timeout:
|
| 212 |
-
return "请求超时,请检查网络设置", myKey
|
| 213 |
-
except openai.error.APIConnectionError:
|
| 214 |
-
return "网络错误", myKey
|
| 215 |
-
except:
|
| 216 |
-
return "发生了未知错误Orz", myKey
|
| 217 |
-
|
| 218 |
-
encryption_str = "验证成功,api-key已做遮挡处理:" + new_api_key[:4] + "..." + new_api_key[-4:]
|
| 219 |
-
return encryption_str, new_api_key
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
|
|
|
|
|
|
|
|
|
| 222 |
with gr.Blocks() as demo:
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# The 'color_map' parameter has been deprecated.
|
| 233 |
-
# chatbot = gr.Chatbot().style(color_map=("#1D51EE", "#585A5B"))
|
| 234 |
-
context = gr.State([])
|
| 235 |
-
systemPrompt = gr.State(update_system(initial_prompt))
|
| 236 |
-
myKey = gr.State(my_api_key)
|
| 237 |
topic = gr.State("未命名对话历史记录")
|
| 238 |
|
| 239 |
with gr.Row():
|
| 240 |
with gr.Column(scale=12):
|
| 241 |
txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(
|
| 242 |
-
container=False
|
| 243 |
-
)
|
| 244 |
with gr.Column(min_width=50, scale=1):
|
| 245 |
submitBtn = gr.Button("🚀", variant="primary")
|
| 246 |
with gr.Row():
|
| 247 |
emptyBtn = gr.Button("🧹 新的对话")
|
| 248 |
retryBtn = gr.Button("🔄 重新生成")
|
| 249 |
delLastBtn = gr.Button("🗑️ 删除上条对话")
|
| 250 |
-
reduceTokenBtn = gr.Button("♻️
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
|
|
|
|
|
|
| 265 |
with gr.Column():
|
| 266 |
with gr.Row():
|
| 267 |
with gr.Column(scale=6):
|
| 268 |
saveFileName = gr.Textbox(
|
| 269 |
-
show_label=True,
|
| 270 |
-
placeholder=f"在这里输入保存的文件名...",
|
| 271 |
-
label="保存对话",
|
| 272 |
-
value="对话历史记录",
|
| 273 |
-
).style(container=True)
|
| 274 |
with gr.Column(scale=1):
|
| 275 |
saveBtn = gr.Button("💾 保存对话")
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
)
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
)
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
keyTxt.submit(set_apikey, [keyTxt, myKey], [keyTxt, myKey], show_progress=True)
|
| 317 |
-
uploadBtn.upload(
|
| 318 |
-
load_chat_history,
|
| 319 |
-
uploadBtn,
|
| 320 |
-
[chatbot, systemPrompt, context, systemPromptDisplay],
|
| 321 |
-
show_progress=True,
|
| 322 |
-
)
|
| 323 |
-
saveBtn.click(
|
| 324 |
-
save_chat_history,
|
| 325 |
-
[saveFileName, systemPrompt, context],
|
| 326 |
-
None,
|
| 327 |
-
show_progress=True,
|
| 328 |
-
)
|
| 329 |
-
|
| 330 |
-
|
| 331 |
demo.title = "ChatGPT 🚀"
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import gradio as gr
|
| 3 |
+
# import openai
|
| 4 |
import os
|
| 5 |
import sys
|
| 6 |
+
import traceback
|
| 7 |
+
import requests
|
| 8 |
# import markdown
|
| 9 |
+
import csv
|
| 10 |
+
|
| 11 |
+
my_api_key = "" # 在这里输入你的 API 密钥
|
| 12 |
+
HIDE_MY_KEY = False # 如果你想在UI中隐藏你的 API 密钥,将此值设置为 True
|
| 13 |
|
|
|
|
| 14 |
initial_prompt = "You are a helpful assistant."
|
| 15 |
+
API_URL = "https://api.openai.com/v1/chat/completions"
|
| 16 |
+
HISTORY_DIR = "history"
|
| 17 |
+
TEMPLATES_DIR = "templates"
|
| 18 |
|
|
|
|
|
|
|
|
|
|
| 19 |
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
#if we are running in Docker
|
| 22 |
+
if os.environ.get('dockerrun') == 'yes':
|
| 23 |
+
dockerflag = True
|
| 24 |
else:
|
| 25 |
+
dockerflag = False
|
| 26 |
+
|
| 27 |
+
if dockerflag:
|
| 28 |
+
my_api_key = os.environ.get('my_api_key')
|
| 29 |
+
if my_api_key == "empty":
|
| 30 |
+
print("Please give a api key!")
|
| 31 |
+
sys.exit(1)
|
| 32 |
+
#auth
|
| 33 |
+
username = os.environ.get('USERNAME')
|
| 34 |
+
password = os.environ.get('PASSWORD')
|
| 35 |
+
if isinstance(username, type(None)) or isinstance(password, type(None)):
|
| 36 |
+
authflag = False
|
| 37 |
+
else:
|
| 38 |
+
authflag = True
|
| 39 |
|
| 40 |
|
| 41 |
def parse_text(text):
|
|
|
|
|
|
|
| 42 |
lines = text.split("\n")
|
| 43 |
+
lines = [line for line in lines if line != ""]
|
| 44 |
+
count = 0
|
| 45 |
+
firstline = False
|
| 46 |
for i, line in enumerate(lines):
|
|
|
|
| 47 |
if "```" in line:
|
| 48 |
+
count += 1
|
| 49 |
+
items = line.split('`')
|
| 50 |
+
if count % 2 == 1:
|
| 51 |
+
lines[i] = f'<pre><code class="{items[-1]}" style="display: block; white-space: pre; padding: 0 1em 1em 1em; color: #fff; background: #000;">'
|
| 52 |
+
firstline = True
|
| 53 |
else:
|
| 54 |
+
lines[i] = f'</code></pre>'
|
| 55 |
else:
|
| 56 |
if i > 0:
|
| 57 |
+
if count % 2 == 1:
|
| 58 |
+
line = line.replace("&", "&")
|
| 59 |
+
line = line.replace("\"", "`\"`")
|
| 60 |
+
line = line.replace("\'", "`\'`")
|
| 61 |
+
line = line.replace("<", "<")
|
| 62 |
+
line = line.replace(">", ">")
|
| 63 |
+
line = line.replace(" ", " ")
|
| 64 |
+
line = line.replace("*", "*")
|
| 65 |
+
line = line.replace("_", "_")
|
| 66 |
+
line = line.replace("#", "#")
|
| 67 |
+
line = line.replace("-", "-")
|
| 68 |
+
line = line.replace(".", ".")
|
| 69 |
+
line = line.replace("!", "!")
|
| 70 |
+
line = line.replace("(", "(")
|
| 71 |
+
line = line.replace(")", ")")
|
| 72 |
+
lines[i] = "<br>"+line
|
| 73 |
+
text = "".join(lines)
|
| 74 |
+
return text
|
| 75 |
+
|
| 76 |
+
def predict(inputs, top_p, temperature, openai_api_key, chatbot=[], history=[], system_prompt=initial_prompt, retry=False, summary=False): # repetition_penalty, top_k
|
| 77 |
+
|
| 78 |
+
print(f"chatbot 1: {chatbot}")
|
| 79 |
+
|
| 80 |
+
headers = {
|
| 81 |
+
"Content-Type": "application/json",
|
| 82 |
+
"Authorization": f"Bearer {openai_api_key}"
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
chat_counter = len(history) // 2
|
| 86 |
+
|
| 87 |
+
print(f"chat_counter - {chat_counter}")
|
| 88 |
+
|
| 89 |
+
messages = [compose_system(system_prompt)]
|
| 90 |
+
if chat_counter:
|
| 91 |
+
for data in chatbot:
|
| 92 |
+
temp1 = {}
|
| 93 |
+
temp1["role"] = "user"
|
| 94 |
+
temp1["content"] = data[0]
|
| 95 |
+
temp2 = {}
|
| 96 |
+
temp2["role"] = "assistant"
|
| 97 |
+
temp2["content"] = data[1]
|
| 98 |
+
if temp1["content"] != "":
|
| 99 |
+
messages.append(temp1)
|
| 100 |
+
messages.append(temp2)
|
| 101 |
+
else:
|
| 102 |
+
messages[-1]['content'] = temp2['content']
|
| 103 |
+
if retry and chat_counter:
|
| 104 |
+
messages.pop()
|
| 105 |
+
elif summary:
|
| 106 |
+
messages.append(compose_user(
|
| 107 |
+
"请帮我��结一下上述对话的内容,实现减少字数的同时,保证对话的质量。在总结中不要加入这一句话。"))
|
| 108 |
+
history = ["我们刚刚聊了什么?"]
|
| 109 |
else:
|
| 110 |
+
temp3 = {}
|
| 111 |
+
temp3["role"] = "user"
|
| 112 |
+
temp3["content"] = inputs
|
| 113 |
+
messages.append(temp3)
|
| 114 |
+
chat_counter += 1
|
| 115 |
+
# messages
|
| 116 |
+
payload = {
|
| 117 |
+
"model": "gpt-3.5-turbo",
|
| 118 |
+
"messages": messages, # [{"role": "user", "content": f"{inputs}"}],
|
| 119 |
+
"temperature": temperature, # 1.0,
|
| 120 |
+
"top_p": top_p, # 1.0,
|
| 121 |
+
"n": 1,
|
| 122 |
+
"stream": True,
|
| 123 |
+
"presence_penalty": 0,
|
| 124 |
+
"frequency_penalty": 0,
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
if not summary:
|
| 128 |
+
history.append(inputs)
|
| 129 |
+
print(f"payload is - {payload}")
|
| 130 |
+
# make a POST request to the API endpoint using the requests.post method, passing in stream=True
|
| 131 |
+
response = requests.post(API_URL, headers=headers,
|
| 132 |
+
json=payload, stream=True)
|
| 133 |
+
#response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
| 134 |
+
|
| 135 |
+
token_counter = 0
|
| 136 |
+
partial_words = ""
|
| 137 |
+
|
| 138 |
+
counter = 0
|
| 139 |
+
chatbot.append((history[-1], ""))
|
| 140 |
+
for chunk in response.iter_lines():
|
| 141 |
+
if counter == 0:
|
| 142 |
+
counter += 1
|
| 143 |
+
continue
|
| 144 |
+
counter += 1
|
| 145 |
+
# check whether each line is non-empty
|
| 146 |
+
if chunk:
|
| 147 |
+
# decode each line as response data is in bytes
|
| 148 |
+
try:
|
| 149 |
+
if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
|
| 150 |
+
break
|
| 151 |
+
except Exception as e:
|
| 152 |
+
chatbot.pop()
|
| 153 |
+
chatbot.append((history[-1], f"☹️发生了错误<br>返回值:{response.text}<br>异常:{e}"))
|
| 154 |
+
history.pop()
|
| 155 |
+
yield chatbot, history
|
| 156 |
+
break
|
| 157 |
+
#print(json.loads(chunk.decode()[6:])['choices'][0]["delta"] ["content"])
|
| 158 |
+
partial_words = partial_words + \
|
| 159 |
+
json.loads(chunk.decode()[6:])[
|
| 160 |
+
'choices'][0]["delta"]["content"]
|
| 161 |
+
if token_counter == 0:
|
| 162 |
+
history.append(" " + partial_words)
|
| 163 |
+
else:
|
| 164 |
+
history[-1] = parse_text(partial_words)
|
| 165 |
+
chatbot[-1] = (history[-2], history[-1])
|
| 166 |
+
# chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
|
| 167 |
+
token_counter += 1
|
| 168 |
+
# resembles {chatbot: chat, state: history}
|
| 169 |
+
yield chatbot, history
|
| 170 |
|
|
|
|
| 171 |
|
|
|
|
| 172 |
|
| 173 |
+
def delete_last_conversation(chatbot, history):
|
| 174 |
+
chatbot.pop()
|
| 175 |
+
history.pop()
|
| 176 |
+
history.pop()
|
| 177 |
+
return chatbot, history
|
| 178 |
|
| 179 |
+
def save_chat_history(filename, system, history, chatbot):
|
| 180 |
+
if filename == "":
|
| 181 |
+
return
|
| 182 |
+
if not filename.endswith(".json"):
|
| 183 |
+
filename += ".json"
|
| 184 |
+
os.makedirs(HISTORY_DIR, exist_ok=True)
|
| 185 |
+
json_s = {"system": system, "history": history, "chatbot": chatbot}
|
| 186 |
+
with open(os.path.join(HISTORY_DIR, filename), "w") as f:
|
| 187 |
+
json.dump(json_s, f)
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
+
def load_chat_history(filename):
|
| 191 |
+
with open(os.path.join(HISTORY_DIR, filename), "r") as f:
|
| 192 |
+
json_s = json.load(f)
|
| 193 |
+
return filename, json_s["system"], json_s["history"], json_s["chatbot"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
|
| 196 |
+
def get_file_names(dir, plain=False, filetype=".json"):
|
| 197 |
+
# find all json files in the current directory and return their names
|
| 198 |
+
try:
|
| 199 |
+
files = [f for f in os.listdir(dir) if f.endswith(filetype)]
|
| 200 |
+
except FileNotFoundError:
|
| 201 |
+
files = []
|
| 202 |
+
if plain:
|
| 203 |
+
return files
|
| 204 |
+
else:
|
| 205 |
+
return gr.Dropdown.update(choices=files)
|
| 206 |
|
| 207 |
+
def get_history_names(plain=False):
|
| 208 |
+
return get_file_names(HISTORY_DIR, plain)
|
| 209 |
|
| 210 |
+
def load_template(filename):
|
| 211 |
+
lines = []
|
| 212 |
+
with open(os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8") as csvfile:
|
| 213 |
+
reader = csv.reader(csvfile)
|
| 214 |
+
lines = list(reader)
|
| 215 |
+
lines = lines[1:]
|
| 216 |
+
return {row[0]:row[1] for row in lines}, gr.Dropdown.update(choices=[row[0] for row in lines])
|
| 217 |
|
| 218 |
+
def get_template_names(plain=False):
|
| 219 |
+
return get_file_names(TEMPLATES_DIR, plain, filetype=".csv")
|
| 220 |
|
| 221 |
def reset_state():
|
| 222 |
return [], []
|
| 223 |
|
| 224 |
|
| 225 |
+
def compose_system(system_prompt):
|
| 226 |
+
return {"role": "system", "content": system_prompt}
|
| 227 |
|
| 228 |
|
| 229 |
+
def compose_user(user_input):
|
| 230 |
+
return {"role": "user", "content": user_input}
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
def reset_textbox():
|
| 234 |
+
return gr.update(value='')
|
| 235 |
+
|
| 236 |
+
title = """<h1 align="center">川虎ChatGPT 🚀</h1>"""
|
| 237 |
+
description = """<div align=center>
|
| 238 |
+
|
| 239 |
+
由Bilibili [土川虎虎虎](https://space.bilibili.com/29125536) 开发
|
| 240 |
+
|
| 241 |
+
访问川虎ChatGPT的 [GitHub项���](https://github.com/GaiZhenbiao/ChuanhuChatGPT) 下载最新版脚本
|
| 242 |
|
| 243 |
+
此App使用 `gpt-3.5-turbo` 大语言模型
|
| 244 |
+
</div>
|
| 245 |
+
"""
|
| 246 |
with gr.Blocks() as demo:
|
| 247 |
+
gr.HTML(title)
|
| 248 |
+
gr.HTML('''<center><a href="https://huggingface.co/spaces/JohnSmith9982/ChuanhuChatGPT?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="复制 Space"></a>强烈建议点击上面的按钮复制一份这个Space,在你自己的Space里运行,响应更迅速、也更安全👆</center>''')
|
| 249 |
+
keyTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入你的OpenAI API-key...",
|
| 250 |
+
value=my_api_key, label="API Key", type="password", visible=not HIDE_MY_KEY).style(container=True)
|
| 251 |
+
chatbot = gr.Chatbot() # .style(color_map=("#1D51EE", "#585A5B"))
|
| 252 |
+
history = gr.State([])
|
| 253 |
+
promptTemplates = gr.State({})
|
| 254 |
+
TRUECOMSTANT = gr.State(True)
|
| 255 |
+
FALSECONSTANT = gr.State(False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
topic = gr.State("未命名对话历史记录")
|
| 257 |
|
| 258 |
with gr.Row():
|
| 259 |
with gr.Column(scale=12):
|
| 260 |
txt = gr.Textbox(show_label=False, placeholder="在这里输入").style(
|
| 261 |
+
container=False)
|
|
|
|
| 262 |
with gr.Column(min_width=50, scale=1):
|
| 263 |
submitBtn = gr.Button("🚀", variant="primary")
|
| 264 |
with gr.Row():
|
| 265 |
emptyBtn = gr.Button("🧹 新的对话")
|
| 266 |
retryBtn = gr.Button("🔄 重新生成")
|
| 267 |
delLastBtn = gr.Button("🗑️ 删除上条对话")
|
| 268 |
+
reduceTokenBtn = gr.Button("♻️ 总结对话")
|
| 269 |
+
systemPromptTxt = gr.Textbox(show_label=True, placeholder=f"在这里输入System Prompt...",
|
| 270 |
+
label="System prompt", value=initial_prompt).style(container=True)
|
| 271 |
+
with gr.Accordion(label="加载Prompt模板", open=False):
|
| 272 |
+
with gr.Column():
|
| 273 |
+
with gr.Row():
|
| 274 |
+
with gr.Column(scale=6):
|
| 275 |
+
templateFileSelectDropdown = gr.Dropdown(label="选择Prompt模板集合文件(.csv)", choices=get_template_names(plain=True), multiselect=False)
|
| 276 |
+
with gr.Column(scale=1):
|
| 277 |
+
templateRefreshBtn = gr.Button("🔄 刷新")
|
| 278 |
+
templaeFileReadBtn = gr.Button("📂 读入模板")
|
| 279 |
+
with gr.Row():
|
| 280 |
+
with gr.Column(scale=6):
|
| 281 |
+
templateSelectDropdown = gr.Dropdown(label="从Prompt模板中加载", choices=[], multiselect=False)
|
| 282 |
+
with gr.Column(scale=1):
|
| 283 |
+
templateApplyBtn = gr.Button("⬇️ 应用")
|
| 284 |
+
with gr.Accordion(label="保存/加载对话历史记录(在文本框中输入文件名,点击“保存对话”按钮,历史记录文件会被存储到Python文件旁边)", open=False):
|
| 285 |
with gr.Column():
|
| 286 |
with gr.Row():
|
| 287 |
with gr.Column(scale=6):
|
| 288 |
saveFileName = gr.Textbox(
|
| 289 |
+
show_label=True, placeholder=f"在这里输入保存的文件名...", label="设置保存文件名", value="对话历史记录").style(container=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
with gr.Column(scale=1):
|
| 291 |
saveBtn = gr.Button("💾 保存对话")
|
| 292 |
+
with gr.Row():
|
| 293 |
+
with gr.Column(scale=6):
|
| 294 |
+
historyFileSelectDropdown = gr.Dropdown(label="从列表中加载对话", choices=get_history_names(plain=True), multiselect=False)
|
| 295 |
+
with gr.Column(scale=1):
|
| 296 |
+
historyRefreshBtn = gr.Button("🔄 刷新")
|
| 297 |
+
historyReadBtn = gr.Button("📂 读入对话")
|
| 298 |
+
#inputs, top_p, temperature, top_k, repetition_penalty
|
| 299 |
+
with gr.Accordion("参数", open=False):
|
| 300 |
+
top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.05,
|
| 301 |
+
interactive=True, label="Top-p (nucleus sampling)",)
|
| 302 |
+
temperature = gr.Slider(minimum=-0, maximum=5.0, value=1.0,
|
| 303 |
+
step=0.1, interactive=True, label="Temperature",)
|
| 304 |
+
#top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
|
| 305 |
+
#repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
|
| 306 |
+
gr.Markdown(description)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
txt.submit(predict, [txt, top_p, temperature, keyTxt,
|
| 310 |
+
chatbot, history, systemPromptTxt], [chatbot, history])
|
| 311 |
+
txt.submit(reset_textbox, [], [txt])
|
| 312 |
+
submitBtn.click(predict, [txt, top_p, temperature, keyTxt, chatbot,
|
| 313 |
+
history, systemPromptTxt], [chatbot, history], show_progress=True)
|
| 314 |
+
submitBtn.click(reset_textbox, [], [txt])
|
| 315 |
+
emptyBtn.click(reset_state, outputs=[chatbot, history])
|
| 316 |
+
retryBtn.click(predict, [txt, top_p, temperature, keyTxt, chatbot, history,
|
| 317 |
+
systemPromptTxt, TRUECOMSTANT], [chatbot, history], show_progress=True)
|
| 318 |
+
delLastBtn.click(delete_last_conversation, [chatbot, history], [
|
| 319 |
+
chatbot, history], show_progress=True)
|
| 320 |
+
reduceTokenBtn.click(predict, [txt, top_p, temperature, keyTxt, chatbot, history,
|
| 321 |
+
systemPromptTxt, FALSECONSTANT, TRUECOMSTANT], [chatbot, history], show_progress=True)
|
| 322 |
+
saveBtn.click(save_chat_history, [
|
| 323 |
+
saveFileName, systemPromptTxt, history, chatbot], None, show_progress=True)
|
| 324 |
+
saveBtn.click(get_history_names, None, [historyFileSelectDropdown])
|
| 325 |
+
historyRefreshBtn.click(get_history_names, None, [historyFileSelectDropdown])
|
| 326 |
+
historyReadBtn.click(load_chat_history, [historyFileSelectDropdown], [saveFileName, systemPromptTxt, history, chatbot], show_progress=True)
|
| 327 |
+
templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])
|
| 328 |
+
templaeFileReadBtn.click(load_template, [templateFileSelectDropdown], [promptTemplates, templateSelectDropdown], show_progress=True)
|
| 329 |
+
templateApplyBtn.click(lambda x, y: x[y], [promptTemplates, templateSelectDropdown], [systemPromptTxt], show_progress=True)
|
| 330 |
+
|
| 331 |
+
# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
demo.title = "ChatGPT 🚀"
|
| 333 |
+
|
| 334 |
+
#if running in Docker
|
| 335 |
+
if dockerflag:
|
| 336 |
+
if authflag:
|
| 337 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=(username, password))
|
| 338 |
+
else:
|
| 339 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)
|
| 340 |
+
#if not running in Docker
|
| 341 |
+
else:
|
| 342 |
+
demo.queue().launch(share=False) # 改为 share=True 可以创建公开分享链接
|
| 343 |
+
#demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口
|
| 344 |
+
#demo.queue().launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码
|