Keldos commited on
Commit
5f36649
1 Parent(s): 389ae06

feat: add avatars to bot and user messages (#867)

Browse files

* add avatars to bot and user messages
* set default avatar for user and chatbot and fix a bug

ChuanhuChatbot.py CHANGED
@@ -36,12 +36,13 @@ with gr.Blocks(theme=small_and_beautiful_theme) as demo:
36
  current_model = gr.State(create_new_model)
37
 
38
  topic = gr.State(i18n("未命名对话历史记录"))
39
-
40
  with gr.Row():
41
  gr.HTML(CHUANHU_TITLE, elem_id="app-title")
42
  status_display = gr.Markdown(get_geoip(), elem_id="status-display")
43
  with gr.Row(elem_id="float-display"):
44
  user_info = gr.Markdown(value="getting user info...", elem_id="user-info")
 
45
  update_info = gr.HTML(get_html("update.html").format(
46
  current_version=repo_tag_html(),
47
  version_time=version_time(),
@@ -300,6 +301,7 @@ with gr.Blocks(theme=small_and_beautiful_theme) as demo:
300
  # changeAPIURLBtn = gr.Button(i18n("🔄 切换API地址"))
301
  updateChuanhuBtn = gr.Button(visible=False, elem_classes="invisible-btn", elem_id="update-chuanhu-btn")
302
 
 
303
  gr.Markdown(CHUANHU_DESCRIPTION, elem_id="description")
304
  gr.HTML(get_html("footer.html").format(versions=versions_html()), elem_id="footer")
305
 
@@ -381,7 +383,7 @@ with gr.Blocks(theme=small_and_beautiful_theme) as demo:
381
  inputs=[current_model],
382
  outputs=[chatbot, status_display],
383
  show_progress=True,
384
- _js='clearHistoryHtml',
385
  )
386
 
387
  retryBtn.click(**start_outputing_args).then(
 
36
  current_model = gr.State(create_new_model)
37
 
38
  topic = gr.State(i18n("未命名对话历史记录"))
39
+
40
  with gr.Row():
41
  gr.HTML(CHUANHU_TITLE, elem_id="app-title")
42
  status_display = gr.Markdown(get_geoip(), elem_id="status-display")
43
  with gr.Row(elem_id="float-display"):
44
  user_info = gr.Markdown(value="getting user info...", elem_id="user-info")
45
+ 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")
46
  update_info = gr.HTML(get_html("update.html").format(
47
  current_version=repo_tag_html(),
48
  version_time=version_time(),
 
301
  # changeAPIURLBtn = gr.Button(i18n("🔄 切换API地址"))
302
  updateChuanhuBtn = gr.Button(visible=False, elem_classes="invisible-btn", elem_id="update-chuanhu-btn")
303
 
304
+
305
  gr.Markdown(CHUANHU_DESCRIPTION, elem_id="description")
306
  gr.HTML(get_html("footer.html").format(versions=versions_html()), elem_id="footer")
307
 
 
383
  inputs=[current_model],
384
  outputs=[chatbot, status_display],
385
  show_progress=True,
386
+ _js='clearChatbot',
387
  )
388
 
389
  retryBtn.click(**start_outputing_args).then(
config_example.json CHANGED
@@ -24,6 +24,8 @@
24
  "hide_history_when_not_logged_in": false, //未登录情况下是否不展示对话历史
25
  "check_update": true, //是否启用检查更新
26
  "default_model": "gpt-3.5-turbo", // 默认模型
 
 
27
 
28
  //== API 用量 ==
29
  "show_api_billing": false, //是否显示OpenAI API用量(启用需要填写sensitive_id)
 
24
  "hide_history_when_not_logged_in": false, //未登录情况下是否不展示对话历史
25
  "check_update": true, //是否启用检查更新
26
  "default_model": "gpt-3.5-turbo", // 默认模型
27
+ "bot_avatar": "default", // 机器人头像,可填写图片链接、Data URL (base64),或者"none"(不显示头像)
28
+ "user_avatar": "default", // 用户头像,可填写图片链接、Data URL (base64),或者"none"(不显示头像)
29
 
30
  //== API 用量 ==
31
  "show_api_billing": false, //是否显示OpenAI API用量(启用需要填写sensitive_id)
modules/config.py CHANGED
@@ -261,3 +261,7 @@ except ValueError:
261
  pass
262
 
263
  share = config.get("share", False)
 
 
 
 
 
261
  pass
262
 
263
  share = config.get("share", False)
264
+
265
+ # avatar
266
+ bot_avatar = config.get("bot_avatar", "default")
267
+ user_avatar = config.get("user_avatar", "default")
web_assets/chatbot.png ADDED
web_assets/html/config_info.html ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ <div id="config-bot-avatar-url">{bot_avatar}</div>
2
+ <div id="config-user-avatar-url">{user_avatar}</div>
web_assets/javascript/ChuanhuChat.js CHANGED
@@ -25,7 +25,6 @@ var sliders = null;
25
  var updateChuanhuBtn = null;
26
  var statusDisplay = null;
27
 
28
-
29
  var isInIframe = (window.self !== window.top);
30
  var currentTime = new Date().getTime();
31
  var initialized = false;
@@ -82,6 +81,7 @@ function initialize() {
82
  setChatbotHeight();
83
  setChatbotScroll();
84
  setSlider();
 
85
  if (!historyLoaded) loadHistoryHtml();
86
  if (!usernameGotten) getUserInfo();
87
  chatbotObserver.observe(chatbotIndicator, { attributes: true });
@@ -221,19 +221,49 @@ function setChatbotScroll() {
221
  chatbotWrap.scrollTo(0,scrollHeight)
222
  }
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  function chatbotContentChanged(attempt = 1) {
226
  for (var i = 0; i < attempt; i++) {
227
  setTimeout(() => {
228
  saveHistoryHtml();
229
  disableSendBtn();
230
- gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.bot').forEach(addChuanhuButton);
 
231
  }, i === 0 ? 0 : 500);
232
  }
233
  // 理论上是不需要多次尝试执行的,可惜gradio的bug导致message可能没有渲染完毕,所以尝试500ms后再次执行
234
  }
235
 
236
  var chatbotObserver = new MutationObserver(() => {
 
237
  if (chatbotIndicator.classList.contains('hide')) {
238
  chatbotContentChanged(2);
239
  }
 
25
  var updateChuanhuBtn = null;
26
  var statusDisplay = null;
27
 
 
28
  var isInIframe = (window.self !== window.top);
29
  var currentTime = new Date().getTime();
30
  var initialized = false;
 
81
  setChatbotHeight();
82
  setChatbotScroll();
83
  setSlider();
84
+ setAvatar();
85
  if (!historyLoaded) loadHistoryHtml();
86
  if (!usernameGotten) getUserInfo();
87
  chatbotObserver.observe(chatbotIndicator, { attributes: true });
 
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) {
254
  for (var i = 0; i < attempt; i++) {
255
  setTimeout(() => {
256
  saveHistoryHtml();
257
  disableSendBtn();
258
+ gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.user').forEach((userElement) => {addAvatars(userElement, 'user')});
259
+ gradioApp().querySelectorAll('#chuanhu-chatbot .message-wrap .message.bot').forEach((botElement) => {addAvatars(botElement, 'bot'); addChuanhuButton(botElement)});
260
  }, i === 0 ? 0 : 500);
261
  }
262
  // 理论上是不需要多次尝试执行的,可惜gradio的bug导致message可能没有渲染完毕,所以尝试500ms后再次执行
263
  }
264
 
265
  var chatbotObserver = new MutationObserver(() => {
266
+ chatbotContentChanged(1);
267
  if (chatbotIndicator.classList.contains('hide')) {
268
  chatbotContentChanged(2);
269
  }
web_assets/javascript/avatar.js ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ function addAvatars(messageElement, role='user'||'bot') {
3
+ if (messageElement.classList.contains('avatar-added') || messageElement.classList.contains('hide')) {
4
+ return;
5
+ }
6
+ if (role === 'bot' && botAvatarUrl === "" || role === 'user' && userAvatarUrl === "") {
7
+ messageElement.classList.add('avatar-added');
8
+ return;
9
+ }
10
+
11
+
12
+ const messageRow = document.createElement('div');
13
+ messageRow.classList.add('message-row');
14
+ messageElement.classList.add('avatar-added');
15
+
16
+ if (role === 'bot') {
17
+ messageRow.classList.add('bot-message-row');
18
+ } else if (role === 'user') {
19
+ messageRow.classList.add('user-message-row');
20
+ }
21
+
22
+ const avatarDiv = document.createElement('div');
23
+ avatarDiv.classList.add('chatbot-avatar');
24
+ if (role === 'bot') {
25
+ avatarDiv.classList.add('bot-avatar');
26
+ avatarDiv.innerHTML = `<img src="${botAvatarUrl}" alt="bot-avatar" />`;
27
+ } else if (role === 'user') {
28
+ avatarDiv.classList.add('user-avatar');
29
+ avatarDiv.innerHTML = `<img src="${userAvatarUrl}" alt="user-avatar" />`;
30
+ }
31
+
32
+ messageElement.parentNode.replaceChild(messageRow, messageElement);
33
+
34
+ if (role === 'bot') {
35
+ messageRow.appendChild(avatarDiv);
36
+ messageRow.appendChild(messageElement);
37
+ } else if (role === 'user') {
38
+ messageRow.appendChild(messageElement);
39
+ messageRow.appendChild(avatarDiv);
40
+ }
41
+ }
42
+
43
+ function clearMessageRows() {
44
+ const messageRows = chatbotWrap.querySelectorAll('.message-row');
45
+ messageRows.forEach((messageRow) => {
46
+ messageRow.parentNode.removeChild(messageRow);
47
+ });
48
+ }
web_assets/javascript/utils.js CHANGED
@@ -21,6 +21,22 @@ function transEventListeners(target, source, events) {
21
  }
22
 
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  /* NOTE: These reload functions are not used in the current version of the code.
25
  * From stable-diffusion-webui
26
  */
 
21
  }
22
 
23
 
24
+ function isImgUrl(url) {
25
+ const imageExtensions = /\.(jpg|jpeg|png|gif|bmp|webp)$/i;
26
+ if (url.startsWith('data:image/')) {
27
+ return true;
28
+ }
29
+ if (url.match(imageExtensions)) {
30
+ return true;
31
+ }
32
+ if (url.startsWith('http://') || url.startsWith('https://')) {
33
+ return true;
34
+ }
35
+
36
+ return false;
37
+ }
38
+
39
+
40
  /* NOTE: These reload functions are not used in the current version of the code.
41
  * From stable-diffusion-webui
42
  */
web_assets/stylesheet/chatbot.css CHANGED
@@ -84,13 +84,13 @@ 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: 85%;
88
- border-bottom-left-radius: 0 !important;
89
  }
90
  [data-testid = "user"] {
91
- max-width: 85%;
92
  width: auto !important;
93
- border-bottom-right-radius: 0 !important;
94
  }
95
 
96
  /* 屏幕宽度大于等于500px的设备 */
@@ -112,7 +112,10 @@ hr.append-display {
112
  max-height: calc(100vh - 140px - var(--line-sm)*1rem - 2*var(--block-label-margin) );
113
  }
114
  [data-testid = "bot"] {
115
- max-width: 95% !important;
 
 
 
116
  }
117
  #app-title h1{
118
  letter-spacing: -1px; font-size: 22px;
@@ -201,7 +204,7 @@ hr.append-display {
201
 
202
  /* history message */
203
  .wrapper>.wrap>.history-message {
204
- padding: 10px !important;
205
  }
206
  .history-message {
207
  /* padding: 0 !important; */
@@ -239,4 +242,37 @@ hr.append-display {
239
  /* #chuanhu-chatbot {
240
  transition: height 0.3s ease;
241
  note: find it better without transition animation...;
242
- } */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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的设备 */
 
112
  max-height: calc(100vh - 140px - var(--line-sm)*1rem - 2*var(--block-label-margin) );
113
  }
114
  [data-testid = "bot"] {
115
+ max-width: calc(98% - 20px) !important;
116
+ }
117
+ .chatbot-avatar {
118
+ display: none;
119
  }
120
  #app-title h1{
121
  letter-spacing: -1px; font-size: 22px;
 
204
 
205
  /* history message */
206
  .wrapper>.wrap>.history-message {
207
+ padding-bottom: 10px !important;
208
  }
209
  .history-message {
210
  /* padding: 0 !important; */
 
242
  /* #chuanhu-chatbot {
243
  transition: height 0.3s ease;
244
  note: find it better without transition animation...;
245
+ } */
246
+
247
+
248
+ .message-row {
249
+ flex-direction: row;
250
+ display: flex;
251
+ gap: 8px;
252
+ width: 100%;
253
+ }
254
+ .bot-message-row {
255
+ justify-content: flex-start;
256
+ }
257
+ .user-message-row {
258
+ justify-content: flex-end;
259
+ }
260
+ .chatbot-avatar {
261
+ width: 32px;
262
+ height: 32px;
263
+ background-color: transparent;
264
+ background-size: cover;
265
+ border-radius: 5px !important;
266
+ }
267
+ .chatbot-avatar.bot-avatar {
268
+ margin-left: 5px;
269
+ }
270
+ .chatbot-avatar.user-avatar {
271
+ margin-right: 10px;
272
+ }
273
+ .chatbot-avatar img {
274
+ border-radius: 5px !important;
275
+ object-fit: fill;
276
+ max-width: 100%;
277
+ max-height: 100%;
278
+ }
web_assets/stylesheet/markdown.css CHANGED
@@ -1,5 +1,5 @@
1
 
2
- .message-wrap>div img{
3
  border-radius: 10px !important;
4
  }
5
 
 
1
 
2
+ .md-message img{
3
  border-radius: 10px !important;
4
  }
5