Spaces:
Sleeping
Sleeping
Merge branch 'newgradio'
Browse files- ChuanhuChatbot.py +0 -1
- assets/custom.css +49 -90
- assets/custom.js +7 -112
- config_example.json +0 -1
- modules/config.py +0 -7
- modules/overwrites.py +19 -17
- modules/presets.py +2 -0
- modules/utils.py +62 -8
- requirements.txt +2 -3
ChuanhuChatbot.py
CHANGED
@@ -89,7 +89,6 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
|
|
89 |
with gr.Row():
|
90 |
single_turn_checkbox = gr.Checkbox(label=i18n("单轮对话"), value=False)
|
91 |
use_websearch_checkbox = gr.Checkbox(label=i18n("使用在线搜索"), value=False)
|
92 |
-
# render_latex_checkbox = gr.Checkbox(label=i18n("渲染LaTeX公式"), value=render_latex, interactive=True, elem_id="render_latex_checkbox")
|
93 |
language_select_dropdown = gr.Dropdown(
|
94 |
label=i18n("选择回复语言(针对搜索&索引功能)"),
|
95 |
choices=REPLY_LANGUAGES,
|
|
|
89 |
with gr.Row():
|
90 |
single_turn_checkbox = gr.Checkbox(label=i18n("单轮对话"), value=False)
|
91 |
use_websearch_checkbox = gr.Checkbox(label=i18n("使用在线搜索"), value=False)
|
|
|
92 |
language_select_dropdown = gr.Dropdown(
|
93 |
label=i18n("选择回复语言(针对搜索&索引功能)"),
|
94 |
choices=REPLY_LANGUAGES,
|
assets/custom.css
CHANGED
@@ -291,17 +291,28 @@ ol:not(.options), ul:not(.options) {
|
|
291 |
border-bottom-right-radius: 0 !important;
|
292 |
}
|
293 |
|
294 |
-
.message p {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
295 |
margin-top: 0.6em !important;
|
296 |
margin-bottom: 0.6em !important;
|
297 |
}
|
298 |
-
.message p:first-child { margin-top: 0 !important; }
|
299 |
-
.message p:last-of-type { margin-bottom: 0 !important; }
|
300 |
|
301 |
.message .md-message {
|
302 |
display: block;
|
303 |
padding: 0 !important;
|
304 |
}
|
|
|
|
|
|
|
305 |
.message .raw-message {
|
306 |
display: block;
|
307 |
padding: 0 !important;
|
@@ -408,101 +419,49 @@ thead th {
|
|
408 |
.message :not(pre) code {
|
409 |
display: inline;
|
410 |
white-space: break-spaces;
|
|
|
411 |
border-radius: 6px;
|
412 |
margin: 0 2px 0 2px;
|
413 |
padding: .2em .4em .1em .4em;
|
414 |
background-color: rgba(175,184,193,0.2);
|
415 |
}
|
416 |
/* 代码块 */
|
417 |
-
.message pre
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
padding: 1.2em
|
424 |
-
|
425 |
-
|
426 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
427 |
}
|
428 |
-
|
429 |
-
|
|
|
|
|
430 |
}
|
431 |
-
|
432 |
-
background-color:
|
433 |
}
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
}
|
438 |
|
439 |
-
/*
|
440 |
-
.
|
441 |
-
.
|
442 |
-
.
|
443 |
-
.
|
444 |
-
.
|
445 |
-
|
446 |
-
|
447 |
-
.highlight .p { color: #f8f8f2 !important} /* Punctuation */
|
448 |
-
.highlight .ch { color: #75715e !important} /* Comment.Hashbang */
|
449 |
-
.highlight .cm { color: #75715e !important} /* Comment.Multiline */
|
450 |
-
.highlight .cp { color: #75715e !important} /* Comment.Preproc */
|
451 |
-
.highlight .cpf { color: #75715e !important} /* Comment.PreprocFile */
|
452 |
-
.highlight .c1 { color: #75715e !important} /* Comment.Single */
|
453 |
-
.highlight .cs { color: #75715e !important} /* Comment.Special */
|
454 |
-
.highlight .gd { color: #f92672 !important} /* Generic.Deleted */
|
455 |
-
.highlight .ge { font-style: italic !important} /* Generic.Emph */
|
456 |
-
.highlight .gi { color: #a6e22e !important} /* Generic.Inserted */
|
457 |
-
.highlight .gs { font-weight: bold !important} /* Generic.Strong */
|
458 |
-
.highlight .gu { color: #75715e !important} /* Generic.Subheading */
|
459 |
-
.highlight .kc { color: #66d9ef !important} /* Keyword.Constant */
|
460 |
-
.highlight .kd { color: #66d9ef !important} /* Keyword.Declaration */
|
461 |
-
.highlight .kn { color: #f92672 !important} /* Keyword.Namespace */
|
462 |
-
.highlight .kp { color: #66d9ef !important} /* Keyword.Pseudo */
|
463 |
-
.highlight .kr { color: #66d9ef !important} /* Keyword.Reserved */
|
464 |
-
.highlight .kt { color: #66d9ef !important} /* Keyword.Type */
|
465 |
-
.highlight .ld { color: #e6db74 !important} /* Literal.Date */
|
466 |
-
.highlight .m { color: #ae81ff !important} /* Literal.Number */
|
467 |
-
.highlight .s { color: #e6db74 !important} /* Literal.String */
|
468 |
-
.highlight .na { color: #a6e22e !important} /* Name.Attribute */
|
469 |
-
.highlight .nb { color: #f8f8f2 !important} /* Name.Builtin */
|
470 |
-
.highlight .nc { color: #a6e22e !important} /* Name.Class */
|
471 |
-
.highlight .no { color: #66d9ef !important} /* Name.Constant */
|
472 |
-
.highlight .nd { color: #a6e22e !important} /* Name.Decorator */
|
473 |
-
.highlight .ni { color: #f8f8f2 !important} /* Name.Entity */
|
474 |
-
.highlight .ne { color: #a6e22e !important} /* Name.Exception */
|
475 |
-
.highlight .nf { color: #a6e22e !important} /* Name.Function */
|
476 |
-
.highlight .nl { color: #f8f8f2 !important} /* Name.Label */
|
477 |
-
.highlight .nn { color: #f8f8f2 !important} /* Name.Namespace */
|
478 |
-
.highlight .nx { color: #a6e22e !important} /* Name.Other */
|
479 |
-
.highlight .py { color: #f8f8f2 !important} /* Name.Property */
|
480 |
-
.highlight .nt { color: #f92672 !important} /* Name.Tag */
|
481 |
-
.highlight .nv { color: #f8f8f2 !important} /* Name.Variable */
|
482 |
-
.highlight .ow { color: #f92672 !important} /* Operator.Word */
|
483 |
-
.highlight .w { color: #f8f8f2 !important} /* Text.Whitespace */
|
484 |
-
.highlight .mb { color: #ae81ff !important} /* Literal.Number.Bin */
|
485 |
-
.highlight .mf { color: #ae81ff !important} /* Literal.Number.Float */
|
486 |
-
.highlight .mh { color: #ae81ff !important} /* Literal.Number.Hex */
|
487 |
-
.highlight .mi { color: #ae81ff !important} /* Literal.Number.Integer */
|
488 |
-
.highlight .mo { color: #ae81ff !important} /* Literal.Number.Oct */
|
489 |
-
.highlight .sa { color: #e6db74 !important} /* Literal.String.Affix */
|
490 |
-
.highlight .sb { color: #e6db74 !important} /* Literal.String.Backtick */
|
491 |
-
.highlight .sc { color: #e6db74 !important} /* Literal.String.Char */
|
492 |
-
.highlight .dl { color: #e6db74 !important} /* Literal.String.Delimiter */
|
493 |
-
.highlight .sd { color: #e6db74 !important} /* Literal.String.Doc */
|
494 |
-
.highlight .s2 { color: #e6db74 !important} /* Literal.String.Double */
|
495 |
-
.highlight .se { color: #ae81ff !important} /* Literal.String.Escape */
|
496 |
-
.highlight .sh { color: #e6db74 !important} /* Literal.String.Heredoc */
|
497 |
-
.highlight .si { color: #e6db74 !important} /* Literal.String.Interpol */
|
498 |
-
.highlight .sx { color: #e6db74 !important} /* Literal.String.Other */
|
499 |
-
.highlight .sr { color: #e6db74 !important} /* Literal.String.Regex */
|
500 |
-
.highlight .s1 { color: #e6db74 !important} /* Literal.String.Single */
|
501 |
-
.highlight .ss { color: #e6db74 !important} /* Literal.String.Symbol */
|
502 |
-
.highlight .bp { color: #f8f8f2 !important} /* Name.Builtin.Pseudo */
|
503 |
-
.highlight .fm { color: #a6e22e !important} /* Name.Function.Magic */
|
504 |
-
.highlight .vc { color: #f8f8f2 !important} /* Name.Variable.Class */
|
505 |
-
.highlight .vg { color: #f8f8f2 !important} /* Name.Variable.Global */
|
506 |
-
.highlight .vi { color: #f8f8f2 !important} /* Name.Variable.Instance */
|
507 |
-
.highlight .vm { color: #f8f8f2 !important} /* Name.Variable.Magic */
|
508 |
-
.highlight .il { color: #ae81ff !important} /* Literal.Number.Integer.Long */
|
|
|
291 |
border-bottom-right-radius: 0 !important;
|
292 |
}
|
293 |
|
294 |
+
.message.user p {
|
295 |
+
white-space: pre-wrap;
|
296 |
+
}
|
297 |
+
.message .user-message {
|
298 |
+
display: block;
|
299 |
+
padding: 0 !important;
|
300 |
+
}
|
301 |
+
|
302 |
+
.message .md-message p {
|
303 |
margin-top: 0.6em !important;
|
304 |
margin-bottom: 0.6em !important;
|
305 |
}
|
306 |
+
.message .md-message p:first-child { margin-top: 0 !important; }
|
307 |
+
.message .md-message p:last-of-type { margin-bottom: 0 !important; }
|
308 |
|
309 |
.message .md-message {
|
310 |
display: block;
|
311 |
padding: 0 !important;
|
312 |
}
|
313 |
+
.message .raw-message p {
|
314 |
+
margin:0 !important;
|
315 |
+
}
|
316 |
.message .raw-message {
|
317 |
display: block;
|
318 |
padding: 0 !important;
|
|
|
419 |
.message :not(pre) code {
|
420 |
display: inline;
|
421 |
white-space: break-spaces;
|
422 |
+
font-family: var(--font-mono);
|
423 |
border-radius: 6px;
|
424 |
margin: 0 2px 0 2px;
|
425 |
padding: .2em .4em .1em .4em;
|
426 |
background-color: rgba(175,184,193,0.2);
|
427 |
}
|
428 |
/* 代码块 */
|
429 |
+
.message pre,
|
430 |
+
.message pre[class*=language-] {
|
431 |
+
color: #fff;
|
432 |
+
overflow-x: auto;
|
433 |
+
overflow-y: hidden;
|
434 |
+
margin: .8em 1em 1em 0em !important;
|
435 |
+
padding: var(--spacing-xl) 1.2em !important;
|
436 |
+
border-radius: var(--radius-lg) !important;
|
437 |
+
}
|
438 |
+
.message pre code,
|
439 |
+
.message pre code[class*=language-] {
|
440 |
+
color: #fff;
|
441 |
+
padding: 0;
|
442 |
+
margin: 0;
|
443 |
+
background-color: unset;
|
444 |
+
text-shadow: none;
|
445 |
+
font-family: var(--font-mono);
|
446 |
}
|
447 |
+
/* 覆盖 gradio 丑陋的复制按钮样式 */
|
448 |
+
pre button[title="copy"] {
|
449 |
+
border-radius: 5px;
|
450 |
+
transition: background-color .2s ease;
|
451 |
}
|
452 |
+
pre button[title="copy"]:hover {
|
453 |
+
background-color: #333232;
|
454 |
}
|
455 |
+
pre button .check {
|
456 |
+
color: #fff !important;
|
457 |
+
background: var(--neutral-950) !important;
|
458 |
}
|
459 |
|
460 |
+
/* 覆盖prism.css */
|
461 |
+
.language-css .token.string,
|
462 |
+
.style .token.string,
|
463 |
+
.token.entity,
|
464 |
+
.token.operator,
|
465 |
+
.token.url {
|
466 |
+
background: none !important;
|
467 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
assets/custom.js
CHANGED
@@ -17,13 +17,11 @@ var chatbotWrap = null;
|
|
17 |
var apSwitch = null;
|
18 |
var empty_botton = null;
|
19 |
var messageBotDivs = null;
|
20 |
-
// var renderLatex = null;
|
21 |
var loginUserForm = null;
|
22 |
var logginUser = null;
|
23 |
|
24 |
var userLogged = false;
|
25 |
var usernameGotten = false;
|
26 |
-
var shouldRenderLatex = false;
|
27 |
var historyLoaded = false;
|
28 |
|
29 |
var ga = document.getElementsByTagName("gradio-app");
|
@@ -51,7 +49,6 @@ function gradioLoaded(mutations) {
|
|
51 |
chatbot = document.querySelector('#chuanhu_chatbot');
|
52 |
chatbotWrap = document.querySelector('#chuanhu_chatbot > .wrap');
|
53 |
apSwitch = document.querySelector('.apSwitch input[type="checkbox"]');
|
54 |
-
// renderLatex = document.querySelector("#render_latex_checkbox > label > input");
|
55 |
empty_botton = document.getElementById("empty_btn")
|
56 |
|
57 |
if (loginUserForm) {
|
@@ -80,10 +77,6 @@ function gradioLoaded(mutations) {
|
|
80 |
}
|
81 |
setChatbotScroll();
|
82 |
}
|
83 |
-
// if (renderLatex) { // renderLatex 加载出来了没?
|
84 |
-
// shouldRenderLatex = renderLatex.checked;
|
85 |
-
// updateMathJax();
|
86 |
-
// }
|
87 |
if (empty_botton) {
|
88 |
emptyHistory();
|
89 |
}
|
@@ -246,10 +239,10 @@ function showOrHideUserInfo() {
|
|
246 |
function toggleDarkMode(isEnabled) {
|
247 |
if (isEnabled) {
|
248 |
document.body.classList.add("dark");
|
249 |
-
|
250 |
} else {
|
251 |
document.body.classList.remove("dark");
|
252 |
-
|
253 |
}
|
254 |
}
|
255 |
function adjustDarkMode() {
|
@@ -377,41 +370,6 @@ function addChuanhuButton(botElement) {
|
|
377 |
botElement.insertBefore(toggleButton, copyButton);
|
378 |
}
|
379 |
|
380 |
-
function addCopyCodeButton(pre) {
|
381 |
-
var code = null;
|
382 |
-
var firstChild = null;
|
383 |
-
code = pre.querySelector('code');
|
384 |
-
if (!code) return;
|
385 |
-
firstChild = code.querySelector('div');
|
386 |
-
if (!firstChild) return;
|
387 |
-
var oldCopyButton = null;
|
388 |
-
oldCopyButton = code.querySelector('button.copy-code-btn');
|
389 |
-
// if (oldCopyButton) oldCopyButton.remove();
|
390 |
-
if (oldCopyButton) return; // 没太有用,新生成的对话中始终会被pre覆盖,导致按钮消失,这段代码不启用……
|
391 |
-
var codeButton = document.createElement('button');
|
392 |
-
codeButton.classList.add('copy-code-btn');
|
393 |
-
codeButton.textContent = '\uD83D\uDCCE';
|
394 |
-
|
395 |
-
code.insertBefore(codeButton, firstChild);
|
396 |
-
codeButton.addEventListener('click', function () {
|
397 |
-
var range = document.createRange();
|
398 |
-
range.selectNodeContents(code);
|
399 |
-
range.setStartBefore(firstChild);
|
400 |
-
navigator.clipboard
|
401 |
-
.writeText(range.toString())
|
402 |
-
.then(() => {
|
403 |
-
codeButton.textContent = '\u2714';
|
404 |
-
setTimeout(function () {
|
405 |
-
codeButton.textContent = '\uD83D\uDCCE';
|
406 |
-
}, 2000);
|
407 |
-
})
|
408 |
-
.catch(e => {
|
409 |
-
console.error(e);
|
410 |
-
codeButton.textContent = '\u2716';
|
411 |
-
});
|
412 |
-
});
|
413 |
-
}
|
414 |
-
|
415 |
function renderMarkdownText(message) {
|
416 |
var mdDiv = message.querySelector('.md-message');
|
417 |
if (mdDiv) mdDiv.classList.remove('hideM');
|
@@ -425,73 +383,17 @@ function removeMarkdownText(message) {
|
|
425 |
if (mdDiv) mdDiv.classList.add('hideM');
|
426 |
}
|
427 |
|
428 |
-
var rendertime = 0; // for debugging
|
429 |
-
var mathjaxUpdated = false;
|
430 |
-
|
431 |
-
function renderMathJax() {
|
432 |
-
messageBotDivs = document.querySelectorAll('.message.bot .md-message');
|
433 |
-
for (var i = 0; i < messageBotDivs.length; i++) {
|
434 |
-
var mathJaxSpan = messageBotDivs[i].querySelector('.MathJax_Preview');
|
435 |
-
if (!mathJaxSpan && shouldRenderLatex && !mathjaxUpdated) {
|
436 |
-
MathJax.Hub.Queue(["Typeset", MathJax.Hub, messageBotDivs[i]]);
|
437 |
-
rendertime +=1; // for debugging
|
438 |
-
// console.log("renderingMathJax", i)
|
439 |
-
}
|
440 |
-
}
|
441 |
-
mathjaxUpdated = true;
|
442 |
-
// console.log("MathJax Rendered")
|
443 |
-
}
|
444 |
-
|
445 |
-
function removeMathjax() {
|
446 |
-
// var jax = MathJax.Hub.getAllJax();
|
447 |
-
// for (var i = 0; i < jax.length; i++) {
|
448 |
-
// // MathJax.typesetClear(jax[i]);
|
449 |
-
// jax[i].Text(newmath)
|
450 |
-
// jax[i].Reprocess()
|
451 |
-
// }
|
452 |
-
// 我真的不会了啊啊啊,mathjax并没有提供转换为原先文本的办法。
|
453 |
-
mathjaxUpdated = true;
|
454 |
-
// console.log("MathJax removed!");
|
455 |
-
}
|
456 |
-
|
457 |
-
function updateMathJax() {
|
458 |
-
// renderLatex.addEventListener("change", function() {
|
459 |
-
// shouldRenderLatex = renderLatex.checked;
|
460 |
-
// if (!mathjaxUpdated) {
|
461 |
-
// if (shouldRenderLatex) {
|
462 |
-
// renderMathJax();
|
463 |
-
// } else {
|
464 |
-
// console.log("MathJax Disabled")
|
465 |
-
// removeMathjax();
|
466 |
-
// }
|
467 |
-
// } else {
|
468 |
-
// if (!shouldRenderLatex) {
|
469 |
-
// mathjaxUpdated = false; // reset
|
470 |
-
// }
|
471 |
-
// }
|
472 |
-
// });
|
473 |
-
if (shouldRenderLatex && !mathjaxUpdated) {
|
474 |
-
renderMathJax();
|
475 |
-
}
|
476 |
-
mathjaxUpdated = false;
|
477 |
-
}
|
478 |
-
|
479 |
let timeoutId;
|
480 |
let isThrottled = false;
|
481 |
var mmutation
|
482 |
-
// 监听所有元素中 bot message
|
483 |
var mObserver = new MutationObserver(function (mutationsList) {
|
484 |
for (mmutation of mutationsList) {
|
485 |
if (mmutation.type === 'childList') {
|
486 |
for (var node of mmutation.addedNodes) {
|
487 |
if (node.nodeType === 1 && node.classList.contains('message') && node.getAttribute('data-testid') === 'bot') {
|
488 |
-
if (shouldRenderLatex) {
|
489 |
-
renderMathJax();
|
490 |
-
mathjaxUpdated = false;
|
491 |
-
}
|
492 |
saveHistoryHtml();
|
493 |
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot').forEach(addChuanhuButton);
|
494 |
-
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot pre').forEach(addCopyCodeButton);
|
495 |
}
|
496 |
if (node.tagName === 'INPUT' && node.getAttribute('type') === 'range') {
|
497 |
setSlider();
|
@@ -499,27 +401,17 @@ var mObserver = new MutationObserver(function (mutationsList) {
|
|
499 |
}
|
500 |
for (var node of mmutation.removedNodes) {
|
501 |
if (node.nodeType === 1 && node.classList.contains('message') && node.getAttribute('data-testid') === 'bot') {
|
502 |
-
if (shouldRenderLatex) {
|
503 |
-
renderMathJax();
|
504 |
-
mathjaxUpdated = false;
|
505 |
-
}
|
506 |
saveHistoryHtml();
|
507 |
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot').forEach(addChuanhuButton);
|
508 |
-
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot pre').forEach(addCopyCodeButton);
|
509 |
}
|
510 |
}
|
511 |
} else if (mmutation.type === 'attributes') {
|
512 |
if (mmutation.target.nodeType === 1 && mmutation.target.classList.contains('message') && mmutation.target.getAttribute('data-testid') === 'bot') {
|
513 |
-
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot pre').forEach(addCopyCodeButton); // 目前写的是有点问题的,会导致加button次数过多,但是bot对话内容生成时又是不断覆盖pre的……
|
514 |
if (isThrottled) break; // 为了防止重复不断疯狂渲染,加上等待_(:з」∠)_
|
515 |
isThrottled = true;
|
516 |
clearTimeout(timeoutId);
|
517 |
timeoutId = setTimeout(() => {
|
518 |
isThrottled = false;
|
519 |
-
if (shouldRenderLatex) {
|
520 |
-
renderMathJax();
|
521 |
-
mathjaxUpdated = false;
|
522 |
-
}
|
523 |
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot').forEach(addChuanhuButton);
|
524 |
saveHistoryHtml();
|
525 |
}, 500);
|
@@ -551,9 +443,13 @@ function loadHistoryHtml() {
|
|
551 |
var tempDiv = document.createElement('div');
|
552 |
tempDiv.innerHTML = historyHtml;
|
553 |
var buttons = tempDiv.querySelectorAll('button.chuanhu-btn');
|
|
|
554 |
for (var i = 0; i < buttons.length; i++) {
|
555 |
buttons[i].parentNode.removeChild(buttons[i]);
|
556 |
}
|
|
|
|
|
|
|
557 |
var fakeHistory = document.createElement('div');
|
558 |
fakeHistory.classList.add('history-message');
|
559 |
fakeHistory.innerHTML = tempDiv.innerHTML;
|
@@ -594,7 +490,6 @@ observer.observe(targetNode, { childList: true, subtree: true });
|
|
594 |
window.addEventListener("DOMContentLoaded", function () {
|
595 |
isInIframe = (window.self !== window.top);
|
596 |
historyLoaded = false;
|
597 |
-
shouldRenderLatex = !!document.querySelector('script[src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"]');
|
598 |
});
|
599 |
window.addEventListener('resize', setChatbotHeight);
|
600 |
window.addEventListener('scroll', setChatbotHeight);
|
|
|
17 |
var apSwitch = null;
|
18 |
var empty_botton = null;
|
19 |
var messageBotDivs = null;
|
|
|
20 |
var loginUserForm = null;
|
21 |
var logginUser = null;
|
22 |
|
23 |
var userLogged = false;
|
24 |
var usernameGotten = false;
|
|
|
25 |
var historyLoaded = false;
|
26 |
|
27 |
var ga = document.getElementsByTagName("gradio-app");
|
|
|
49 |
chatbot = document.querySelector('#chuanhu_chatbot');
|
50 |
chatbotWrap = document.querySelector('#chuanhu_chatbot > .wrap');
|
51 |
apSwitch = document.querySelector('.apSwitch input[type="checkbox"]');
|
|
|
52 |
empty_botton = document.getElementById("empty_btn")
|
53 |
|
54 |
if (loginUserForm) {
|
|
|
77 |
}
|
78 |
setChatbotScroll();
|
79 |
}
|
|
|
|
|
|
|
|
|
80 |
if (empty_botton) {
|
81 |
emptyHistory();
|
82 |
}
|
|
|
239 |
function toggleDarkMode(isEnabled) {
|
240 |
if (isEnabled) {
|
241 |
document.body.classList.add("dark");
|
242 |
+
document.body.style.setProperty("background-color", "var(--neutral-950)", "important");
|
243 |
} else {
|
244 |
document.body.classList.remove("dark");
|
245 |
+
document.body.style.backgroundColor = "";
|
246 |
}
|
247 |
}
|
248 |
function adjustDarkMode() {
|
|
|
370 |
botElement.insertBefore(toggleButton, copyButton);
|
371 |
}
|
372 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
373 |
function renderMarkdownText(message) {
|
374 |
var mdDiv = message.querySelector('.md-message');
|
375 |
if (mdDiv) mdDiv.classList.remove('hideM');
|
|
|
383 |
if (mdDiv) mdDiv.classList.add('hideM');
|
384 |
}
|
385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
386 |
let timeoutId;
|
387 |
let isThrottled = false;
|
388 |
var mmutation
|
389 |
+
// 监听所有元素中 bot message 的变化,为 bot 消息添加复制按钮。
|
390 |
var mObserver = new MutationObserver(function (mutationsList) {
|
391 |
for (mmutation of mutationsList) {
|
392 |
if (mmutation.type === 'childList') {
|
393 |
for (var node of mmutation.addedNodes) {
|
394 |
if (node.nodeType === 1 && node.classList.contains('message') && node.getAttribute('data-testid') === 'bot') {
|
|
|
|
|
|
|
|
|
395 |
saveHistoryHtml();
|
396 |
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot').forEach(addChuanhuButton);
|
|
|
397 |
}
|
398 |
if (node.tagName === 'INPUT' && node.getAttribute('type') === 'range') {
|
399 |
setSlider();
|
|
|
401 |
}
|
402 |
for (var node of mmutation.removedNodes) {
|
403 |
if (node.nodeType === 1 && node.classList.contains('message') && node.getAttribute('data-testid') === 'bot') {
|
|
|
|
|
|
|
|
|
404 |
saveHistoryHtml();
|
405 |
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot').forEach(addChuanhuButton);
|
|
|
406 |
}
|
407 |
}
|
408 |
} else if (mmutation.type === 'attributes') {
|
409 |
if (mmutation.target.nodeType === 1 && mmutation.target.classList.contains('message') && mmutation.target.getAttribute('data-testid') === 'bot') {
|
|
|
410 |
if (isThrottled) break; // 为了防止重复不断疯狂渲染,加上等待_(:з」∠)_
|
411 |
isThrottled = true;
|
412 |
clearTimeout(timeoutId);
|
413 |
timeoutId = setTimeout(() => {
|
414 |
isThrottled = false;
|
|
|
|
|
|
|
|
|
415 |
document.querySelectorAll('#chuanhu_chatbot>.wrap>.message-wrap .message.bot').forEach(addChuanhuButton);
|
416 |
saveHistoryHtml();
|
417 |
}, 500);
|
|
|
443 |
var tempDiv = document.createElement('div');
|
444 |
tempDiv.innerHTML = historyHtml;
|
445 |
var buttons = tempDiv.querySelectorAll('button.chuanhu-btn');
|
446 |
+
var gradioCopyButtons = tempDiv.querySelectorAll('button.copy_code_button');
|
447 |
for (var i = 0; i < buttons.length; i++) {
|
448 |
buttons[i].parentNode.removeChild(buttons[i]);
|
449 |
}
|
450 |
+
for (var i = 0; i < gradioCopyButtons.length; i++) {
|
451 |
+
gradioCopyButtons[i].parentNode.removeChild(gradioCopyButtons[i]);
|
452 |
+
}
|
453 |
var fakeHistory = document.createElement('div');
|
454 |
fakeHistory.classList.add('history-message');
|
455 |
fakeHistory.innerHTML = tempDiv.innerHTML;
|
|
|
490 |
window.addEventListener("DOMContentLoaded", function () {
|
491 |
isInIframe = (window.self !== window.top);
|
492 |
historyLoaded = false;
|
|
|
493 |
});
|
494 |
window.addEventListener('resize', setChatbotHeight);
|
495 |
window.addEventListener('scroll', setChatbotHeight);
|
config_example.json
CHANGED
@@ -16,7 +16,6 @@
|
|
16 |
// "https_proxy": "http://127.0.0.1:1079",
|
17 |
// "http_proxy": "http://127.0.0.1:1079",
|
18 |
// 是否默认渲染LaTeX
|
19 |
-
"render_latex": true,
|
20 |
"users": [], // 用户列表,[[用户名1, 密码1], [用户名2, 密码2], ...]
|
21 |
"local_embedding": false, //是否在本地编制索引
|
22 |
"hide_history_when_not_logged_in": false, //未登录情况下是否不展示对话历史
|
|
|
16 |
// "https_proxy": "http://127.0.0.1:1079",
|
17 |
// "http_proxy": "http://127.0.0.1:1079",
|
18 |
// 是否默认渲染LaTeX
|
|
|
19 |
"users": [], // 用户列表,[[用户名1, 密码1], [用户名2, 密码2], ...]
|
20 |
"local_embedding": false, //是否在本地编制索引
|
21 |
"hide_history_when_not_logged_in": false, //未登录情况下是否不展示对话历史
|
modules/config.py
CHANGED
@@ -18,7 +18,6 @@ __all__ = [
|
|
18 |
"log_level",
|
19 |
"advance_docs",
|
20 |
"update_doc_config",
|
21 |
-
"render_latex",
|
22 |
"usage_limit",
|
23 |
"multi_api_key",
|
24 |
"server_name",
|
@@ -82,12 +81,6 @@ os.environ["MINIMAX_API_KEY"] = minimax_api_key
|
|
82 |
minimax_group_id = config.get("minimax_group_id", "")
|
83 |
os.environ["MINIMAX_GROUP_ID"] = minimax_group_id
|
84 |
|
85 |
-
render_latex = config.get("render_latex", True)
|
86 |
-
|
87 |
-
if render_latex:
|
88 |
-
os.environ["RENDER_LATEX"] = "yes"
|
89 |
-
else:
|
90 |
-
os.environ["RENDER_LATEX"] = "no"
|
91 |
|
92 |
usage_limit = os.environ.get("USAGE_LIMIT", config.get("usage_limit", 120))
|
93 |
|
|
|
18 |
"log_level",
|
19 |
"advance_docs",
|
20 |
"update_doc_config",
|
|
|
21 |
"usage_limit",
|
22 |
"multi_api_key",
|
23 |
"server_name",
|
|
|
81 |
minimax_group_id = config.get("minimax_group_id", "")
|
82 |
os.environ["MINIMAX_GROUP_ID"] = minimax_group_id
|
83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
usage_limit = os.environ.get("USAGE_LIMIT", config.get("usage_limit", 120))
|
86 |
|
modules/overwrites.py
CHANGED
@@ -2,12 +2,12 @@ from __future__ import annotations
|
|
2 |
import logging
|
3 |
|
4 |
from typing import List, Tuple
|
5 |
-
import mdtex2html
|
6 |
from gradio_client import utils as client_utils
|
|
|
|
|
7 |
|
8 |
from modules.presets import *
|
9 |
from modules.index_func import *
|
10 |
-
from modules.config import render_latex
|
11 |
|
12 |
|
13 |
def postprocess(
|
@@ -40,14 +40,18 @@ def postprocess(
|
|
40 |
return processed_messages
|
41 |
|
42 |
def postprocess_chat_messages(
|
43 |
-
self, chat_message: str |
|
44 |
-
) -> str |
|
45 |
if chat_message is None:
|
46 |
return None
|
47 |
elif isinstance(chat_message, (tuple, list)):
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
49 |
mime_type = client_utils.get_mimetype(filepath)
|
50 |
-
filepath = self.make_temp_copy_if_needed(filepath)
|
51 |
return {
|
52 |
"name": filepath,
|
53 |
"mime_type": mime_type,
|
@@ -56,12 +60,13 @@ def postprocess_chat_messages(
|
|
56 |
"is_file": True,
|
57 |
}
|
58 |
elif isinstance(chat_message, str):
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
|
|
65 |
return chat_message
|
66 |
else:
|
67 |
raise ValueError(f"Invalid message for Chatbot component: {chat_message}")
|
@@ -75,11 +80,8 @@ with open("./assets/custom.js", "r", encoding="utf-8") as f, \
|
|
75 |
def reload_javascript():
|
76 |
print("Reloading javascript...")
|
77 |
js = f'<script>{customJS}</script><script async>{externalScripts}</script>'
|
78 |
-
if render_latex:
|
79 |
-
|
80 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML"></script>
|
81 |
-
<script type="text/x-mathjax-config">MathJax.Hub.Config({skipStartupTypeset: false, tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']],displayMath: [['$$','$$'], ['\\[','\\]']]}});</script>
|
82 |
-
"""
|
83 |
def template_response(*args, **kwargs):
|
84 |
res = GradioTemplateResponseOriginal(*args, **kwargs)
|
85 |
res.body = res.body.replace(b'</html>', f'{js}</html>'.encode("utf8"))
|
|
|
2 |
import logging
|
3 |
|
4 |
from typing import List, Tuple
|
|
|
5 |
from gradio_client import utils as client_utils
|
6 |
+
from gradio import utils
|
7 |
+
import inspect
|
8 |
|
9 |
from modules.presets import *
|
10 |
from modules.index_func import *
|
|
|
11 |
|
12 |
|
13 |
def postprocess(
|
|
|
40 |
return processed_messages
|
41 |
|
42 |
def postprocess_chat_messages(
|
43 |
+
self, chat_message: str | tuple | list | None, role: str
|
44 |
+
) -> str | dict | None:
|
45 |
if chat_message is None:
|
46 |
return None
|
47 |
elif isinstance(chat_message, (tuple, list)):
|
48 |
+
file_uri = chat_message[0]
|
49 |
+
if utils.validate_url(file_uri):
|
50 |
+
filepath = file_uri
|
51 |
+
else:
|
52 |
+
filepath = self.make_temp_copy_if_needed(file_uri)
|
53 |
+
|
54 |
mime_type = client_utils.get_mimetype(filepath)
|
|
|
55 |
return {
|
56 |
"name": filepath,
|
57 |
"mime_type": mime_type,
|
|
|
60 |
"is_file": True,
|
61 |
}
|
62 |
elif isinstance(chat_message, str):
|
63 |
+
# chat_message = inspect.cleandoc(chat_message)
|
64 |
+
# escape html spaces
|
65 |
+
# chat_message = chat_message.replace(" ", " ")
|
66 |
+
if role == "bot":
|
67 |
+
chat_message = convert_bot_before_marked(chat_message)
|
68 |
+
elif role == "user":
|
69 |
+
chat_message = convert_user_before_marked(chat_message)
|
70 |
return chat_message
|
71 |
else:
|
72 |
raise ValueError(f"Invalid message for Chatbot component: {chat_message}")
|
|
|
80 |
def reload_javascript():
|
81 |
print("Reloading javascript...")
|
82 |
js = f'<script>{customJS}</script><script async>{externalScripts}</script>'
|
83 |
+
# if render_latex:
|
84 |
+
# js += """\"""
|
|
|
|
|
|
|
85 |
def template_response(*args, **kwargs):
|
86 |
res = GradioTemplateResponseOriginal(*args, **kwargs)
|
87 |
res.body = res.body.replace(b'</html>', f'{js}</html>'.encode("utf8"))
|
modules/presets.py
CHANGED
@@ -238,4 +238,6 @@ small_and_beautiful_theme = gr.themes.Soft(
|
|
238 |
block_title_background_fill_dark="*primary_900",
|
239 |
block_label_background_fill_dark="*primary_900",
|
240 |
input_background_fill="#F6F6F6",
|
|
|
|
|
241 |
)
|
|
|
238 |
block_title_background_fill_dark="*primary_900",
|
239 |
block_label_background_fill_dark="*primary_900",
|
240 |
input_background_fill="#F6F6F6",
|
241 |
+
chatbot_code_background_color="*neutral_950",
|
242 |
+
chatbot_code_background_color_dark="*neutral_950",
|
243 |
)
|
modules/utils.py
CHANGED
@@ -16,7 +16,6 @@ import subprocess
|
|
16 |
import gradio as gr
|
17 |
from pypinyin import lazy_pinyin
|
18 |
import tiktoken
|
19 |
-
import mdtex2html
|
20 |
from markdown import markdown
|
21 |
from pygments import highlight
|
22 |
from pygments.lexers import get_lexer_by_name
|
@@ -133,7 +132,7 @@ def count_token(message):
|
|
133 |
return length
|
134 |
|
135 |
|
136 |
-
def markdown_to_html_with_syntax_highlight(md_str):
|
137 |
def replacer(match):
|
138 |
lang = match.group(1) or "text"
|
139 |
code = match.group(2)
|
@@ -155,7 +154,7 @@ def markdown_to_html_with_syntax_highlight(md_str):
|
|
155 |
return html_str
|
156 |
|
157 |
|
158 |
-
def normalize_markdown(md_text: str) -> str:
|
159 |
lines = md_text.split("\n")
|
160 |
normalized_lines = []
|
161 |
inside_list = False
|
@@ -179,7 +178,7 @@ def normalize_markdown(md_text: str) -> str:
|
|
179 |
return "\n".join(normalized_lines)
|
180 |
|
181 |
|
182 |
-
def convert_mdtext(md_text):
|
183 |
code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
|
184 |
inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
|
185 |
code_blocks = code_block_pattern.findall(md_text)
|
@@ -203,15 +202,70 @@ def convert_mdtext(md_text):
|
|
203 |
output += ALREADY_CONVERTED_MARK
|
204 |
return output
|
205 |
|
206 |
-
|
207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
return (
|
209 |
f'<p style="white-space:pre-wrap;">{html.escape(userinput)}</p>'
|
210 |
+ ALREADY_CONVERTED_MARK
|
211 |
)
|
212 |
|
213 |
|
214 |
-
def detect_converted_mark(userinput):
|
215 |
try:
|
216 |
if userinput.endswith(ALREADY_CONVERTED_MARK):
|
217 |
return True
|
@@ -221,7 +275,7 @@ def detect_converted_mark(userinput):
|
|
221 |
return True
|
222 |
|
223 |
|
224 |
-
def detect_language(code):
|
225 |
if code.startswith("\n"):
|
226 |
first_line = ""
|
227 |
else:
|
|
|
16 |
import gradio as gr
|
17 |
from pypinyin import lazy_pinyin
|
18 |
import tiktoken
|
|
|
19 |
from markdown import markdown
|
20 |
from pygments import highlight
|
21 |
from pygments.lexers import get_lexer_by_name
|
|
|
132 |
return length
|
133 |
|
134 |
|
135 |
+
def markdown_to_html_with_syntax_highlight(md_str): # deprecated
|
136 |
def replacer(match):
|
137 |
lang = match.group(1) or "text"
|
138 |
code = match.group(2)
|
|
|
154 |
return html_str
|
155 |
|
156 |
|
157 |
+
def normalize_markdown(md_text: str) -> str: # deprecated
|
158 |
lines = md_text.split("\n")
|
159 |
normalized_lines = []
|
160 |
inside_list = False
|
|
|
178 |
return "\n".join(normalized_lines)
|
179 |
|
180 |
|
181 |
+
def convert_mdtext(md_text): # deprecated
|
182 |
code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
|
183 |
inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
|
184 |
code_blocks = code_block_pattern.findall(md_text)
|
|
|
202 |
output += ALREADY_CONVERTED_MARK
|
203 |
return output
|
204 |
|
205 |
+
def convert_bot_before_marked(chat_message):
|
206 |
+
"""
|
207 |
+
注意不能给输出加缩进, 否则会被marked解析成代码块
|
208 |
+
"""
|
209 |
+
if '<div class="md-message">' in chat_message:
|
210 |
+
return chat_message
|
211 |
+
else:
|
212 |
+
code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
|
213 |
+
code_blocks = code_block_pattern.findall(chat_message)
|
214 |
+
non_code_parts = code_block_pattern.split(chat_message)[::2]
|
215 |
+
result = []
|
216 |
+
|
217 |
+
raw = f'<div class="raw-message hideM">{escape_markdown(chat_message)}</div>'
|
218 |
+
for non_code, code in zip(non_code_parts, code_blocks + [""]):
|
219 |
+
if non_code.strip():
|
220 |
+
result.append(non_code)
|
221 |
+
if code.strip():
|
222 |
+
code = f"\n```{code}\n```"
|
223 |
+
result.append(code)
|
224 |
+
result = "".join(result)
|
225 |
+
md = f'<div class="md-message">{result}\n</div>'
|
226 |
+
return raw + md
|
227 |
+
|
228 |
+
def convert_user_before_marked(chat_message):
|
229 |
+
if '<div class="user-message">' in chat_message:
|
230 |
+
return chat_message
|
231 |
+
else:
|
232 |
+
return f'<div class="user-message">{escape_markdown(chat_message)}</div>'
|
233 |
+
|
234 |
+
def escape_markdown(text):
|
235 |
+
"""
|
236 |
+
Escape Markdown special characters to HTML-safe equivalents.
|
237 |
+
"""
|
238 |
+
escape_chars = {
|
239 |
+
' ': ' ',
|
240 |
+
'_': '_',
|
241 |
+
'*': '*',
|
242 |
+
'[': '[',
|
243 |
+
']': ']',
|
244 |
+
'(': '(',
|
245 |
+
')': ')',
|
246 |
+
'{': '{',
|
247 |
+
'}': '}',
|
248 |
+
'#': '#',
|
249 |
+
'+': '+',
|
250 |
+
'-': '-',
|
251 |
+
'.': '.',
|
252 |
+
'!': '!',
|
253 |
+
'`': '`',
|
254 |
+
'>': '>',
|
255 |
+
'<': '<',
|
256 |
+
'|': '|'
|
257 |
+
}
|
258 |
+
return ''.join(escape_chars.get(c, c) for c in text)
|
259 |
+
|
260 |
+
|
261 |
+
def convert_asis(userinput): # deprecated
|
262 |
return (
|
263 |
f'<p style="white-space:pre-wrap;">{html.escape(userinput)}</p>'
|
264 |
+ ALREADY_CONVERTED_MARK
|
265 |
)
|
266 |
|
267 |
|
268 |
+
def detect_converted_mark(userinput): # deprecated
|
269 |
try:
|
270 |
if userinput.endswith(ALREADY_CONVERTED_MARK):
|
271 |
return True
|
|
|
275 |
return True
|
276 |
|
277 |
|
278 |
+
def detect_language(code): # deprecated
|
279 |
if code.startswith("\n"):
|
280 |
first_line = ""
|
281 |
else:
|
requirements.txt
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
-
gradio==3.
|
2 |
-
gradio_client==0.2.
|
3 |
-
mdtex2html
|
4 |
pypinyin
|
5 |
tiktoken
|
6 |
socksio
|
|
|
1 |
+
gradio==3.33.1
|
2 |
+
gradio_client==0.2.5
|
|
|
3 |
pypinyin
|
4 |
tiktoken
|
5 |
socksio
|