Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main'
Browse files Browse the repository at this point in the history
# Conflicts:
#	ChuanhuChatbot.py
  • Loading branch information
zsunreal committed Apr 28, 2023
2 parents 08acfe1 + 6d421b8 commit 8ed5b0d
Show file tree
Hide file tree
Showing 14 changed files with 353 additions and 116 deletions.
27 changes: 9 additions & 18 deletions ChuanhuChatbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def create_new_model():
user_name = gr.State("")
promptTemplates = gr.State(load_template(get_template_names(plain=True)[0], mode=2))
user_question = gr.State("")
assert type(my_api_key)==str
user_api_key = gr.State(my_api_key)
current_model = gr.State(create_new_model)

Expand All @@ -38,15 +39,6 @@ def create_new_model():
with gr.Row(elem_id="float_display"):
user_info = gr.Markdown(value="getting user info...", elem_id="user_info")

# https://github.com/gradio-app/gradio/pull/3296
def create_greeting(request: gr.Request):
if hasattr(request, "username") and request.username: # is not None or is not ""
logging.info(f"Get User Name: {request.username}")
return gr.Markdown.update(value=f"User: {request.username}"), request.username
else:
return gr.Markdown.update(value=f"User: default", visible=False), ""
demo.load(create_greeting, inputs=None, outputs=[user_info, user_name])

with gr.Row().style(equal_height=True):
with gr.Column(scale=5):
with gr.Row():
Expand All @@ -62,7 +54,7 @@ def create_greeting(request: gr.Request):
cancelBtn = gr.Button(value="", variant="secondary", visible=False, elem_id="cancel_btn")
with gr.Row():
emptyBtn = gr.Button(
i18n("🧹 新的对话"),
i18n("🧹 新的对话"), elem_id="empty_btn"
)
retryBtn = gr.Button(i18n("🔄 重新生成"))
delFirstBtn = gr.Button(i18n("🗑️ 删除最旧对话"))
Expand Down Expand Up @@ -152,8 +144,7 @@ def create_greeting(request: gr.Request):
historyFileSelectDropdown = gr.Dropdown(
label=i18n("从列表中加载对话"),
choices=get_history_names(plain=True),
multiselect=False,
value=get_history_names(plain=True)[0],
multiselect=False
)
with gr.Column(scale=1):
historyRefreshBtn = gr.Button(i18n("🔄 刷新"))
Expand Down Expand Up @@ -319,7 +310,7 @@ def create_greeting(request: gr.Request):

load_history_from_file_args = dict(
fn=load_chat_history,
inputs=[current_model, historyFileSelectDropdown, chatbot, user_name],
inputs=[current_model, historyFileSelectDropdown, user_name],
outputs=[saveFileName, systemPromptTxt, chatbot]
)

Expand All @@ -330,7 +321,7 @@ def create_greeting(request: gr.Request):
user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
user_input.submit(**get_usage_args)

submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args, api_name="predict").then(**end_outputing_args)
submitBtn.click(**get_usage_args)

index_files.change(handle_file_upload, [current_model, index_files, chatbot], [index_files, chatbot, status_display])
Expand Down Expand Up @@ -387,12 +378,12 @@ def create_greeting(request: gr.Request):
two_column.change(update_doc_config, [two_column], None)

# LLM Models
keyTxt.change(set_key, [current_model, keyTxt], [user_api_key, status_display]).then(**get_usage_args)
keyTxt.change(set_key, [current_model, keyTxt], [user_api_key, status_display], api_name="set_key").then(**get_usage_args)
keyTxt.submit(**get_usage_args)
single_turn_checkbox.change(set_single_turn, [current_model, single_turn_checkbox], None)
model_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt], [current_model, status_display, lora_select_dropdown], show_progress=True)
model_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt, user_name], [current_model, status_display, lora_select_dropdown], show_progress=True, api_name="get_model")
model_select_dropdown.change(toggle_like_btn_visibility, [model_select_dropdown], [like_dislike_area], show_progress=False)
lora_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt], [current_model, status_display], show_progress=True)
lora_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt, user_name], [current_model, status_display], show_progress=True)

# Template
systemPromptTxt.change(set_system_prompt, [current_model, systemPromptTxt], None)
Expand Down Expand Up @@ -426,7 +417,7 @@ def create_greeting(request: gr.Request):
)
historyRefreshBtn.click(get_history_names, [gr.State(False), user_name], [historyFileSelectDropdown])
historyFileSelectDropdown.change(**load_history_from_file_args)
downloadFile.change(**load_history_from_file_args)
downloadFile.change(upload_chat_history, [current_model, downloadFile, user_name], [saveFileName, systemPromptTxt, chatbot])

# Advanced
max_context_length_slider.change(set_token_upper_limit, [current_model, max_context_length_slider], None)
Expand Down
37 changes: 37 additions & 0 deletions assets/custom.css
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,43 @@ ol:not(.options), ul:not(.options) {
border-radius: 10px !important;
}

/* history message */
.wrap>.history-message {
padding: 10px !important;
}
.history-message {
/* padding: 0 !important; */
opacity: 80%;
display: flex;
flex-direction: column;
}
.history-message>.history-message {
padding: 0 !important;
}
.history-message>.message-wrap {
padding: 0 !important;
margin-bottom: 16px;
}
.history-message>.message {
margin-bottom: 16px;
}
.wrap>.history-message::after {
content: "";
display: block;
height: 2px;
background-color: var(--body-text-color-subdued);
margin-bottom: 10px;
margin-top: -10px;
clear: both;
}
.wrap>.history-message>:last-child::after {
content: "仅供查看";
display: block;
text-align: center;
color: var(--body-text-color-subdued);
font-size: 0.8em;
}

/* 表格 */
table {
margin: 1em 0;
Expand Down
141 changes: 123 additions & 18 deletions assets/custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,18 @@ var user_input_tb = null;
var userInfoDiv = null;
var appTitleDiv = null;
var chatbot = null;
var chatbotWrap = null;
var apSwitch = null;
var empty_botton = null;
var messageBotDivs = null;
var renderLatex = null;
var loginUserForm = null;
var logginUser = null;

var userLogged = false;
var usernameGotten = false;
var shouldRenderLatex = false;
var historyLoaded = false;

var ga = document.getElementsByTagName("gradio-app");
var targetNode = ga[0];
Expand All @@ -26,13 +34,21 @@ var isInIframe = (window.self !== window.top);
function gradioLoaded(mutations) {
for (var i = 0; i < mutations.length; i++) {
if (mutations[i].addedNodes.length) {
loginUserForm = document.querySelector(".gradio-container > .main > .wrap > .panel > .form")
gradioContainer = document.querySelector(".gradio-container");
user_input_tb = document.getElementById('user_input_tb');
userInfoDiv = document.getElementById("user_info");
appTitleDiv = document.getElementById("app_title");
chatbot = document.querySelector('#chuanhu_chatbot');
chatbotWrap = document.querySelector('#chuanhu_chatbot > .wrap');
apSwitch = document.querySelector('.apSwitch input[type="checkbox"]');
renderLatex = document.querySelector("#render_latex_checkbox > label > input");
empty_botton = document.getElementById("empty_btn")

if (loginUserForm) {
localStorage.setItem("userLogged", true);
userLogged = true;
}

if (gradioContainer && apSwitch) { // gradioCainter 加载出来了没?
adjustDarkMode();
Expand All @@ -41,15 +57,26 @@ function gradioLoaded(mutations) {
selectHistory();
}
if (userInfoDiv && appTitleDiv) { // userInfoDiv 和 appTitleDiv 加载出来了没?
if (!usernameGotten) {
getUserInfo();
}
setTimeout(showOrHideUserInfo(), 2000);
}
if (chatbot) { // chatbot 加载出来了没?
setChatbotHeight();
}
if (chatbotWrap) {
if (!historyLoaded) {
loadHistoryHtml();
}
}
if (renderLatex) { // renderLatex 加载出来了没?
shouldRenderLatex = renderLatex.checked;
updateMathJax();
}
if (empty_botton) {
emptyHistory();
}
}
}
}
Expand Down Expand Up @@ -102,6 +129,34 @@ function selectHistory() {
}
}

var username = null;
function getUserInfo() {
if (usernameGotten) {
return;
}
userLogged = localStorage.getItem('userLogged');
if (userLogged) {
username = userInfoDiv.innerText;
if (username) {
if (username.includes("getting user info…")) {
setTimeout(getUserInfo, 500);
return;
} else if (username === " ") {
localStorage.removeItem("username");
localStorage.removeItem("userLogged")
userLogged = false;
usernameGotten = true;
return;
} else {
username = username.match(/User:\s*(.*)/)[1] || username;
localStorage.setItem("username", username);
usernameGotten = true;
clearHistoryHtml();
}
}
}
}

function toggleUserInfoVisibility(shouldHide) {
if (userInfoDiv) {
if (shouldHide) {
Expand Down Expand Up @@ -273,41 +328,90 @@ let timeoutId;
let isThrottled = false;
// 监听所有元素中message的变化,用来查找需要渲染的mathjax
var mObserver = new MutationObserver(function (mutationsList, observer) {
if (shouldRenderLatex) {
for (var mutation of mutationsList) {
if (mutation.type === 'childList') {
for (var node of mutation.addedNodes) {
if (node.nodeType === 1 && node.classList.contains('message') && node.classList.contains('bot')) {
// console.log("added");
for (var mutation of mutationsList) {
if (mutation.type === 'childList') {
for (var node of mutation.addedNodes) {
if (node.nodeType === 1 && node.classList.contains('message') && node.classList.contains('bot')) {
if (shouldRenderLatex) {
renderMathJax();
mathjaxUpdated = false;
}
saveHistoryHtml();
}
for (var node of mutation.removedNodes) {
if (node.nodeType === 1 && node.classList.contains('message') && node.classList.contains('bot')) {
// console.log("removed");
}
for (var node of mutation.removedNodes) {
if (node.nodeType === 1 && node.classList.contains('message') && node.classList.contains('bot')) {
if (shouldRenderLatex) {
renderMathJax();
mathjaxUpdated = false;
}
saveHistoryHtml();
}
} else if (mutation.type === 'attributes') {
if (mutation.target.nodeType === 1 && mutation.target.classList.contains('message') && mutation.target.classList.contains('bot')) {
if (isThrottled) break; // 为了防止重复不断疯狂渲染,加上等待_(:з」∠)_
isThrottled = true;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
isThrottled = false;
}
} else if (mutation.type === 'attributes') {
if (mutation.target.nodeType === 1 && mutation.target.classList.contains('message') && mutation.target.classList.contains('bot')) {
if (isThrottled) break; // 为了防止重复不断疯狂渲染,加上等待_(:з」∠)_
isThrottled = true;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
isThrottled = false;
if (shouldRenderLatex) {
// console.log("changed");
renderMathJax();
mathjaxUpdated = false;
}, 500);
}
}
saveHistoryHtml();
}, 500);
}
}
}
});
mObserver.observe(targetNode, { attributes: true, childList: true, subtree: true });

var loadhistorytime = 0; // for debugging
function saveHistoryHtml() {
var historyHtml = document.querySelector('#chuanhu_chatbot > .wrap');
localStorage.setItem('chatHistory', historyHtml.innerHTML);
console.log("History Saved")
historyLoaded = false;
}
function loadHistoryHtml() {
var historyHtml = localStorage.getItem('chatHistory');
if (!historyHtml) {
historyLoaded = true;
return; // no history, do nothing
}
userLogged = localStorage.getItem('userLogged');
if (userLogged){
historyLoaded = true;
return; // logged in, do nothing
}
if (!historyLoaded) {
var fakeHistory = document.createElement('div');
fakeHistory.classList.add('history-message');
fakeHistory.innerHTML = historyHtml;
chatbotWrap.insertBefore(fakeHistory, chatbotWrap.firstChild);
historyLoaded = true;
console.log("History Loaded");
loadhistorytime += 1; // for debugging
} else {
historyLoaded = false;
}
}
function clearHistoryHtml() {
localStorage.removeItem("chatHistory");
historyMessages = chatbotWrap.querySelector('.history-message');
if (historyMessages) {
chatbotWrap.removeChild(historyMessages);
console.log("History Cleared");
}
}
function emptyHistory() {
empty_botton.addEventListener("click", function () {
clearHistoryHtml();
});
}

// 监视页面内部 DOM 变动
var observer = new MutationObserver(function (mutations) {
gradioLoaded(mutations);
Expand All @@ -317,6 +421,7 @@ observer.observe(targetNode, { childList: true, subtree: true });
// 监视页面变化
window.addEventListener("DOMContentLoaded", function () {
isInIframe = (window.self !== window.top);
historyLoaded = false;
});
window.addEventListener('resize', setChatbotHeight);
window.addEventListener('scroll', setChatbotHeight);
Expand Down
3 changes: 2 additions & 1 deletion assets/load-mathjax.js → assets/external-scripts.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

// window.MathJax = {
// tex: {
// inlineMath: [['$', '$'], ['\\(', '\\)']]
Expand All @@ -15,6 +16,6 @@

var config = document.createElement("script");
config.type = "text/x-mathjax-config";
config.text = "MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\\\(','\\\\)']],displayMath: [['$$','$$'], ['\\\\[','\\\\]']]}});";
config.text = "MathJax.Hub.Config({skipStartupTypeset: true, tex2jax: {inlineMath: [['$','$'], ['\\\\(','\\\\)']],displayMath: [['$$','$$'], ['\\\\[','\\\\]']]}});";
document.head.appendChild(config);
})();
1 change: 1 addition & 0 deletions config_example.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"render_latex": false,
"users": [], // 用户列表,[[用户名1, 密码1], [用户名2, 密码2], ...]
"local_embedding": false, //是否在本地编制索引
"hide_history_when_not_logged_in": false, //未登录情况下是否不展示对话历史
"default_model": "gpt-3.5-turbo", // 默认模型
"advance_docs": {
"pdf": {
Expand Down
3 changes: 3 additions & 0 deletions modules/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"server_name",
"server_port",
"share",
"hide_history_when_not_logged_in"
]

# 添加一个统一的config文件,避免文件过多造成的疑惑(优先级最低)
Expand All @@ -36,6 +37,8 @@
lang_config = config.get("language", "auto")
language = os.environ.get("LANGUAGE", lang_config)

hide_history_when_not_logged_in = config.get("hide_history_when_not_logged_in", False)

if os.path.exists("api_key.txt"):
logging.info("检测到api_key.txt文件,正在进行迁移...")
with open("api_key.txt", "r") as f:
Expand Down
Loading

0 comments on commit 8ed5b0d

Please sign in to comment.