Keldos commited on
Commit
ef91b66
·
1 Parent(s): 500c18a

dev (refactor): 适配gradio3.41.0的avatar

Browse files
ChuanhuChatbot.py CHANGED
@@ -44,7 +44,7 @@ with gr.Blocks(theme=small_and_beautiful_theme) as demo:
44
  status_display = gr.Markdown(get_geoip(), elem_id="status-display")
45
  with gr.Row(elem_id="float-display"):
46
  user_info = gr.Markdown(value="getting user info...", elem_id="user-info")
47
- config_info = gr.HTML(get_html("config_info.html").format(bot_avatar=config.bot_avatar, user_avatar=config.user_avatar), visible=False, elem_id="config-info")
48
  update_info = gr.HTML(get_html("update.html").format(
49
  current_version=repo_tag_html(),
50
  version_time=version_time(),
@@ -57,7 +57,7 @@ with gr.Blocks(theme=small_and_beautiful_theme) as demo:
57
  with gr.Row(equal_height=True):
58
  with gr.Column(scale=5):
59
  with gr.Row():
60
- chatbot = gr.Chatbot(label="Chuanhu Chat", elem_id="chuanhu-chatbot", latex_delimiters=latex_delimiters_set, height=700)
61
  with gr.Row():
62
  with gr.Column(min_width=225, scale=12):
63
  user_input = gr.Textbox(
 
44
  status_display = gr.Markdown(get_geoip(), elem_id="status-display")
45
  with gr.Row(elem_id="float-display"):
46
  user_info = gr.Markdown(value="getting user info...", elem_id="user-info")
47
+ config_info = gr.HTML(get_html("config_info.html").format(), visible=False, elem_id="config-info")
48
  update_info = gr.HTML(get_html("update.html").format(
49
  current_version=repo_tag_html(),
50
  version_time=version_time(),
 
57
  with gr.Row(equal_height=True):
58
  with gr.Column(scale=5):
59
  with gr.Row():
60
+ chatbot = gr.Chatbot(label="Chuanhu Chat", elem_id="chuanhu-chatbot", latex_delimiters=latex_delimiters_set, height=700, avatar_images=[config.user_avatar, config.bot_avatar])
61
  with gr.Row():
62
  with gr.Column(min_width=225, scale=12):
63
  user_input = gr.Textbox(
modules/config.py CHANGED
@@ -277,4 +277,12 @@ share = config.get("share", False)
277
 
278
  # avatar
279
  bot_avatar = config.get("bot_avatar", "default")
280
- user_avatar = config.get("user_avatar", "default")
 
 
 
 
 
 
 
 
 
277
 
278
  # avatar
279
  bot_avatar = config.get("bot_avatar", "default")
280
+ user_avatar = config.get("user_avatar", "default")
281
+ if bot_avatar == "" or bot_avatar == "none" or bot_avatar is None:
282
+ bot_avatar = None
283
+ elif bot_avatar == "default":
284
+ bot_avatar = "/web_assets/chatbot.png"
285
+ if user_avatar == "" or user_avatar == "none" or user_avatar is None:
286
+ user_avatar = None
287
+ elif user_avatar == "default":
288
+ user_avatar = "NEED TO ADD"
web_assets/html/config_info.html CHANGED
@@ -1,2 +1,2 @@
1
- <div id="config-bot-avatar-url">{bot_avatar}</div>
2
- <div id="config-user-avatar-url">{user_avatar}</div>
 
1
+
2
+ <!-- removed -->
web_assets/javascript/ChuanhuChat.js CHANGED
@@ -27,24 +27,27 @@ var statusDisplay = null;
27
 
28
  var isInIframe = (window.self !== window.top);
29
  var currentTime = new Date().getTime();
30
- var initialized = false;
31
 
32
- // gradio 页面加载好了么??? 我能动你的元素了么??
33
- function gradioLoaded(mutations) {
34
- for (var i = 0; i < mutations.length; i++) {
35
- if (mutations[i].addedNodes.length) {
36
- if (initialized) {
37
- observer.disconnect(); // 停止监听
38
- return;
39
- }
40
- initialize();
 
41
  }
42
  }
 
 
 
 
43
  }
44
 
45
  function initialize() {
46
- var needInit = {gradioContainer, apSwitch, user_input_tb, userInfoDiv, appTitleDiv, chatbot, chatbotIndicator, chatbotWrap, statusDisplay, sliders, updateChuanhuBtn};
47
- initialized = true;
48
 
49
  loginUserForm = gradioApp().querySelector(".gradio-container > .main > .wrap > .panel > .form")
50
  gradioContainer = gradioApp().querySelector(".gradio-container");
@@ -52,7 +55,6 @@ function initialize() {
52
  userInfoDiv = gradioApp().getElementById("user-info");
53
  appTitleDiv = gradioApp().getElementById("app-title");
54
  chatbot = gradioApp().querySelector('#chuanhu-chatbot');
55
- chatbotIndicator = gradioApp().querySelector('#chuanhu-chatbot>div.wrap');
56
  chatbotWrap = gradioApp().querySelector('#chuanhu-chatbot > .wrapper > .wrap');
57
  apSwitch = gradioApp().querySelector('.apSwitch input[type="checkbox"]');
58
  updateToast = gradioApp().querySelector("#toast-update");
@@ -67,31 +69,22 @@ function initialize() {
67
  userLogged = true;
68
  }
69
 
70
- for (let elem in needInit) {
71
- if (needInit[elem] == null) {
72
- initialized = false;
73
- return;
74
- }
75
- }
76
 
77
- if (initialized) {
78
- adjustDarkMode();
79
- selectHistory();
80
- setTimeout(showOrHideUserInfo(), 2000);
81
- setChatbotHeight();
82
- setChatbotScroll();
83
- setSlider();
84
- setAvatar();
85
- if (!historyLoaded) loadHistoryHtml();
86
- if (!usernameGotten) getUserInfo();
87
- chatbotObserver.observe(chatbotIndicator, { attributes: true });
88
 
89
- const lastCheckTime = localStorage.getItem('lastCheckTime') || 0;
90
- const longTimeNoCheck = currentTime - lastCheckTime > 3 * 24 * 60 * 60 * 1000;
91
- if (longTimeNoCheck && !updateInfoGotten && !isLatestVersion || isLatestVersion && !updateInfoGotten) {
92
- updateLatestVersion();
93
- }
94
  }
 
95
  }
96
 
97
  function gradioApp() {
@@ -221,33 +214,9 @@ function setChatbotScroll() {
221
  chatbotWrap.scrollTo(0,scrollHeight)
222
  }
223
 
224
- var botAvatarUrl = "";
225
- var userAvatarUrl = "";
226
- function setAvatar() {
227
- var botAvatar = gradioApp().getElementById("config-bot-avatar-url").innerText;
228
- var userAvatar = gradioApp().getElementById("config-user-avatar-url").innerText;
229
-
230
- if (botAvatar == "none") {
231
- botAvatarUrl = "";
232
- } else if (isImgUrl(botAvatar)) {
233
- botAvatarUrl = botAvatar;
234
- } else {
235
- // botAvatarUrl = "https://github.com/GaiZhenbiao/ChuanhuChatGPT/assets/70903329/aca3a7ec-4f1d-4667-890c-a6f47bf08f63";
236
- botAvatarUrl = "/file=web_assets/chatbot.png"
237
- }
238
-
239
- if (userAvatar == "none") {
240
- userAvatarUrl = "";
241
- } else if (isImgUrl(userAvatar)) {
242
- userAvatarUrl = userAvatar;
243
- } else {
244
- userAvatarUrl = "data:image/svg+xml,%3Csvg width='32px' height='32px' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E%3Cg stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3E%3Crect fill-opacity='0.5' fill='%23bbbbbb' x='0' y='0' width='32' height='32'%3E%3C/rect%3E%3Cg transform='translate(5, 4)' fill='%23999999' fill-opacity='0.8' fill-rule='nonzero'%3E%3Cpath d='M2.29372246,24 L19.7187739,24 C20.4277609,24 20.985212,23.8373915 21.3911272,23.5121746 C21.7970424,23.1869576 22,22.7418004 22,22.1767029 C22,21.3161536 21.7458721,20.4130827 21.2376163,19.4674902 C20.7293605,18.5218977 19.9956681,17.6371184 19.036539,16.8131524 C18.07741,15.9891863 16.9210688,15.3177115 15.5675154,14.798728 C14.2139621,14.2797445 12.6914569,14.0202527 11,14.0202527 C9.30854307,14.0202527 7.78603793,14.2797445 6.43248458,14.798728 C5.07893122,15.3177115 3.92259002,15.9891863 2.96346097,16.8131524 C2.00433193,17.6371184 1.27063951,18.5218977 0.762383704,19.4674902 C0.254127901,20.4130827 0,21.3161536 0,22.1767029 C0,22.7418004 0.202957595,23.1869576 0.608872784,23.5121746 C1.01478797,23.8373915 1.57640453,24 2.29372246,24 Z M11.0124963,11.6521659 C11.9498645,11.6521659 12.8155943,11.3906214 13.6096856,10.8675324 C14.403777,10.3444433 15.042131,9.63605539 15.5247478,8.74236856 C16.0073646,7.84868174 16.248673,6.84722464 16.248673,5.73799727 C16.248673,4.65135034 16.0071492,3.67452644 15.5241015,2.80752559 C15.0410538,1.94052474 14.4024842,1.25585359 13.6083929,0.753512156 C12.8143016,0.251170719 11.9490027,0 11.0124963,0 C10.0759899,0 9.20860836,0.255422879 8.41035158,0.766268638 C7.6120948,1.2771144 6.97352528,1.96622098 6.49464303,2.8335884 C6.01576078,3.70095582 5.77631966,4.67803631 5.77631966,5.76482987 C5.77631966,6.86452653 6.01554533,7.85912886 6.49399667,8.74863683 C6.97244801,9.63814481 7.60871935,10.3444433 8.40281069,10.8675324 C9.19690203,11.3906214 10.0667972,11.6521659 11.0124963,11.6521659 Z'%3E%3C/path%3E%3C/g%3E%3C/g%3E%3C/svg%3E";
245
- }
246
- }
247
-
248
  function clearChatbot() {
249
  clearHistoryHtml();
250
- clearMessageRows();
251
  }
252
 
253
  function chatbotContentChanged(attempt = 1) {
@@ -256,15 +225,14 @@ function chatbotContentChanged(attempt = 1) {
256
  // clearMessageRows();
257
  saveHistoryHtml();
258
  disableSendBtn();
259
- gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.user').forEach((userElement) => {addAvatars(userElement, 'user')});
260
- gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.bot').forEach((botElement) => {addAvatars(botElement, 'bot'); addChuanhuButton(botElement)});
261
  }, i === 0 ? 0 : 500);
262
  }
263
  // 理论上是不需要多次尝试执行的,可惜gradio的bug导致message可能没有渲染完毕,所以尝试500ms后再次执行
264
  }
265
 
266
  var chatbotObserver = new MutationObserver(() => {
267
- clearMessageRows();
268
  chatbotContentChanged(1);
269
  if (chatbotIndicator.classList.contains('hide')) {
270
  chatbotContentChanged(2);
@@ -272,14 +240,21 @@ var chatbotObserver = new MutationObserver(() => {
272
  });
273
 
274
  // 监视页面内部 DOM 变动
275
- var observer = new MutationObserver(function (mutations) {
276
- gradioLoaded(mutations);
 
 
 
 
 
 
 
277
  });
278
 
279
  // 监视页面变化
280
  window.addEventListener("DOMContentLoaded", function () {
281
- const ga = document.getElementsByTagName("gradio-app");
282
- observer.observe(ga[0], { childList: true, subtree: true });
283
  isInIframe = (window.self !== window.top);
284
  historyLoaded = false;
285
  });
 
27
 
28
  var isInIframe = (window.self !== window.top);
29
  var currentTime = new Date().getTime();
 
30
 
31
+
32
+ function addInit() {
33
+ var needInit = {chatbotIndicator};
34
+
35
+ chatbotIndicator = gradioApp().querySelector('#chuanhu-chatbot > div.wrap');
36
+
37
+ for (let elem in needInit) {
38
+ if (needInit[elem] == null) {
39
+ // addInited = false;
40
+ return false;
41
  }
42
  }
43
+
44
+ chatbotObserver.observe(chatbotIndicator, { attributes: true });
45
+
46
+ return true;
47
  }
48
 
49
  function initialize() {
50
+ gradioObserver.observe(gradioApp(), { childList: true, subtree: true });
 
51
 
52
  loginUserForm = gradioApp().querySelector(".gradio-container > .main > .wrap > .panel > .form")
53
  gradioContainer = gradioApp().querySelector(".gradio-container");
 
55
  userInfoDiv = gradioApp().getElementById("user-info");
56
  appTitleDiv = gradioApp().getElementById("app-title");
57
  chatbot = gradioApp().querySelector('#chuanhu-chatbot');
 
58
  chatbotWrap = gradioApp().querySelector('#chuanhu-chatbot > .wrapper > .wrap');
59
  apSwitch = gradioApp().querySelector('.apSwitch input[type="checkbox"]');
60
  updateToast = gradioApp().querySelector("#toast-update");
 
69
  userLogged = true;
70
  }
71
 
72
+ adjustDarkMode();
73
+ selectHistory();
74
+ setTimeout(showOrHideUserInfo(), 2000);
75
+ setChatbotHeight();
76
+ setChatbotScroll();
77
+ setSlider();
78
 
79
+ if (!historyLoaded) loadHistoryHtml();
80
+ if (!usernameGotten) getUserInfo();
 
 
 
 
 
 
 
 
 
81
 
82
+ const lastCheckTime = localStorage.getItem('lastCheckTime') || 0;
83
+ const longTimeNoCheck = currentTime - lastCheckTime > 3 * 24 * 60 * 60 * 1000;
84
+ if (longTimeNoCheck && !updateInfoGotten && !isLatestVersion || isLatestVersion && !updateInfoGotten) {
85
+ updateLatestVersion();
 
86
  }
87
+ return true;
88
  }
89
 
90
  function gradioApp() {
 
214
  chatbotWrap.scrollTo(0,scrollHeight)
215
  }
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  function clearChatbot() {
218
  clearHistoryHtml();
219
+ // clearMessageRows();
220
  }
221
 
222
  function chatbotContentChanged(attempt = 1) {
 
225
  // clearMessageRows();
226
  saveHistoryHtml();
227
  disableSendBtn();
228
+ // gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.user').forEach((userElement) => {addAvatars(userElement, 'user')});
229
+ gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.bot').forEach(addChuanhuButton);
230
  }, i === 0 ? 0 : 500);
231
  }
232
  // 理论上是不需要多次尝试执行的,可惜gradio的bug导致message可能没有渲染完毕,所以尝试500ms后再次执行
233
  }
234
 
235
  var chatbotObserver = new MutationObserver(() => {
 
236
  chatbotContentChanged(1);
237
  if (chatbotIndicator.classList.contains('hide')) {
238
  chatbotContentChanged(2);
 
240
  });
241
 
242
  // 监视页面内部 DOM 变动
243
+ var gradioObserver = new MutationObserver(function (mutations) {
244
+ for (var i = 0; i < mutations.length; i++) {
245
+ if (mutations[i].addedNodes.length) {
246
+ if (addInit()) {
247
+ gradioObserver.disconnect();
248
+ return;
249
+ }
250
+ }
251
+ }
252
  });
253
 
254
  // 监视页面变化
255
  window.addEventListener("DOMContentLoaded", function () {
256
+ // const ga = document.getElementsByTagName("gradio-app");
257
+ gradioApp().addEventListener("render", initialize);
258
  isInIframe = (window.self !== window.top);
259
  historyLoaded = false;
260
  });
web_assets/javascript/avatar.js DELETED
@@ -1,53 +0,0 @@
1
-
2
- function addAvatars(messageElement, role='user'||'bot') {
3
- if(messageElement.innerHTML === '') {
4
- return;
5
- }
6
- if (messageElement.classList.contains('avatar-added') || messageElement.classList.contains('hide')) {
7
- return;
8
- }
9
- if (role === 'bot' && botAvatarUrl === "" || role === 'user' && userAvatarUrl === "") {
10
- messageElement.classList.add('avatar-added');
11
- return;
12
- }
13
-
14
-
15
- const messageRow = document.createElement('div');
16
- messageRow.classList.add('message-row');
17
- messageElement.classList.add('avatar-added');
18
-
19
- if (role === 'bot') {
20
- messageRow.classList.add('bot-message-row');
21
- } else if (role === 'user') {
22
- messageRow.classList.add('user-message-row');
23
- }
24
-
25
- const avatarDiv = document.createElement('div');
26
- avatarDiv.classList.add('chatbot-avatar');
27
- if (role === 'bot') {
28
- avatarDiv.classList.add('bot-avatar');
29
- avatarDiv.innerHTML = `<img src="${botAvatarUrl}" alt="bot-avatar" />`;
30
- } else if (role === 'user') {
31
- avatarDiv.classList.add('user-avatar');
32
- avatarDiv.innerHTML = `<img src="${userAvatarUrl}" alt="user-avatar" />`;
33
- }
34
-
35
- messageElement.parentNode.replaceChild(messageRow, messageElement);
36
-
37
- if (role === 'bot') {
38
- messageRow.appendChild(avatarDiv);
39
- messageRow.appendChild(messageElement);
40
- } else if (role === 'user') {
41
- messageRow.appendChild(messageElement);
42
- messageRow.appendChild(avatarDiv);
43
- }
44
- }
45
-
46
- function clearMessageRows() {
47
- const messageRows = chatbotWrap.querySelectorAll('.message-row');
48
- messageRows.forEach((messageRow) => {
49
- if (messageRow.innerText === '') {
50
- messageRow.parentNode.removeChild(messageRow);
51
- }
52
- });
53
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
web_assets/stylesheet/chatbot.css CHANGED
@@ -84,13 +84,16 @@ hr.append-display {
84
  min-width: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
85
  }
86
  [data-testid = "bot"] {
87
- max-width: calc(85% - 38px);
88
- border-top-left-radius: 0 !important;
89
  }
90
  [data-testid = "user"] {
91
- max-width: calc(85% - 38px);
92
  width: auto !important;
93
- border-top-right-radius: 0 !important;
 
 
 
94
  }
95
 
96
  /* 屏幕宽度大于等于500px的设备 */
@@ -245,7 +248,7 @@ hr.append-display {
245
  } */
246
 
247
 
248
- .message-row {
249
  flex-direction: row;
250
  display: flex;
251
  gap: 8px;
@@ -275,4 +278,4 @@ hr.append-display {
275
  object-fit: cover;
276
  width: 100%;
277
  height: 100%;
278
- }
 
84
  min-width: calc(var(--text-md)*var(--line-md) + 2*var(--spacing-xl));
85
  }
86
  [data-testid = "bot"] {
87
+ max-width: calc(85% - 40px);
88
+ border-bottom-left-radius: 0 !important;
89
  }
90
  [data-testid = "user"] {
91
+ max-width: calc(85% - 40px);
92
  width: auto !important;
93
+ border-bottom-right-radius: 0 !important;
94
+ }
95
+ .message-row.user-row {
96
+ justify-content: flex-end;
97
  }
98
 
99
  /* 屏幕宽度大于等于500px的设备 */
 
248
  } */
249
 
250
 
251
+ /* .message-row {
252
  flex-direction: row;
253
  display: flex;
254
  gap: 8px;
 
278
  object-fit: cover;
279
  width: 100%;
280
  height: 100%;
281
+ } */