Spaces:
Runtime error
Runtime error
File size: 27,276 Bytes
8918ac7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 |
import gradio as gr
import os
import re
import markdown
from typing import Dict, Any
def create_manual_tab(constant: Dict[str, Any]) -> Dict[str, Any]:
# 添加自定义CSS,增大文本大小并添加左侧导航栏样式
custom_css = """
<style>
/* 增大整体文本大小 */
.manual-content {
font-size: 16px !important;
line-height: 1.6 !important;
}
/* 标题样式 */
.manual-content h1 {
font-size: 28px !important;
margin-top: 30px !important;
margin-bottom: 20px !important;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
.manual-content h2 {
font-size: 24px !important;
margin-top: 25px !important;
margin-bottom: 15px !important;
border-bottom: 1px solid #ddd;
padding-bottom: 8px;
}
.manual-content h3 {
font-size: 20px !important;
margin-top: 20px !important;
margin-bottom: 10px !important;
}
.manual-content h4 {
font-size: 18px !important;
margin-top: 15px !important;
margin-bottom: 10px !important;
}
/* 段落和列表样式 */
.manual-content p, .manual-content li {
font-size: 16px !important;
margin-bottom: 10px !important;
}
/* 嵌套列表样式 */
.manual-content ul, .manual-content ol {
padding-left: 25px !important;
margin-bottom: 15px !important;
list-style-position: outside !important;
}
.manual-content ul ul,
.manual-content ol ol,
.manual-content ul ol,
.manual-content ol ul {
margin-top: 5px !important;
margin-bottom: 5px !important;
padding-left: 25px !important;
}
.manual-content ul {
list-style-type: disc !important;
}
.manual-content ul ul {
list-style-type: circle !important;
}
.manual-content ul ul ul {
list-style-type: square !important;
}
.manual-content ol {
list-style-type: decimal !important;
}
.manual-content ol ol {
list-style-type: lower-alpha !important;
}
.manual-content ol ol ol {
list-style-type: lower-roman !important;
}
/* 确保列表项正确显示 */
.manual-content li {
display: list-item !important;
margin-bottom: 5px !important;
}
.manual-content li p {
margin-bottom: 5px !important;
display: inline-block !important;
}
/* 代码块样式 */
.manual-content pre {
background-color: #f5f5f5 !important;
padding: 15px !important;
border-radius: 5px !important;
overflow-x: auto !important;
margin: 15px 0 !important;
}
.manual-content code {
font-family: 'Courier New', Courier, monospace !important;
font-size: 15px !important;
}
/* 表格样式 */
.manual-content table {
width: 100% !important;
border-collapse: collapse !important;
margin: 20px 0 !important;
}
.manual-content th, .manual-content td {
border: 1px solid #ddd !important;
padding: 12px !important;
text-align: left !important;
}
.manual-content th {
background-color: #f2f2f2 !important;
font-weight: bold !important;
}
/* 左侧导航栏样式 */
.manual-container {
display: flex !important;
width: 100% !important;
position: relative !important;
}
.manual-nav {
width: 250px !important;
padding: 18px !important;
background-color: #f8f9fa !important;
border-right: 1px solid #ddd !important;
border-radius: 5px !important;
box-shadow: 0 2px 5px rgba(0,0,0,0.1) !important;
font-size: 14px !important;
line-height: 1.4 !important;
align-self: flex-start !important;
position: sticky !important;
top: 20px !important;
max-height: 100% !important;
overflow-y: auto !important;
}
.manual-nav ul {
list-style-type: none !important;
padding: 0 !important;
margin: 0 !important;
}
.manual-nav li {
margin-bottom: 5px !important;
}
.manual-nav a {
display: block !important;
padding: 6px 8px !important;
color: #333 !important;
text-decoration: none !important;
border-radius: 4px !important;
line-height: 1.4 !important;
transition: all 0.2s ease !important;
}
.manual-nav a:hover {
background-color: #e9ecef !important;
transform: translateX(2px) !important;
}
.manual-nav .nav-h2 {
padding-left: 15px !important;
font-size: 13px !important;
}
.manual-nav .nav-h3 {
padding-left: 30px !important;
font-size: 12px !important;
}
.manual-content {
flex: 1 !important;
padding: 20px !important;
overflow-y: auto !important;
margin-left: 20px !important;
}
/* 响应式设计 */
@media (max-width: 768px) {
.manual-container {
flex-direction: column !important;
}
.manual-nav {
position: static !important;
width: 100% !important;
height: auto !important;
max-height: 300px !important;
margin-bottom: 20px !important;
}
.manual-content {
margin-left: 0 !important;
width: 100% !important;
}
}
/* 滚动条样式 */
.manual-nav::-webkit-scrollbar {
width: 6px !important;
}
.manual-nav::-webkit-scrollbar-track {
background: #f1f1f1 !important;
border-radius: 10px !important;
}
.manual-nav::-webkit-scrollbar-thumb {
background: #c1c1c1 !important;
border-radius: 10px !important;
}
.manual-nav::-webkit-scrollbar-thumb:hover {
background: #a8a8a8 !important;
}
/* 强化列表样式 */
.manual-content ul li, .manual-content ol li {
margin-bottom: 8px !important;
line-height: 1.5 !important;
}
.manual-content ul li:last-child, .manual-content ol li:last-child {
margin-bottom: 0 !important;
}
.manual-content ul ul, .manual-content ol ol, .manual-content ul ol, .manual-content ol ul {
margin-top: 8px !important;
}
/* 强调列表项内容 */
.manual-content li strong, .manual-content li b {
color: #2c3e50 !important;
}
/* 确保列表项内的代码块正确显示 */
.manual-content li code {
background-color: #f5f5f5 !important;
padding: 2px 4px !important;
border-radius: 3px !important;
font-size: 14px !important;
color: #e83e8c !important;
}
/* 添加到您现有的custom_css字符串中 */
.manual-content img {
max-width: 100% !important;
height: auto !important;
display: block !important;
margin: 20px auto !important;
border-radius: 5px !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important;
}
/* 为图片添加描述样式 */
.manual-content p img + em {
display: block !important;
text-align: center !important;
color: #666 !important;
font-size: 14px !important;
margin-top: 8px !important;
}
/* 图片点击放大效果相关样式 */
.manual-content img:hover {
cursor: pointer !important;
transform: scale(1.01) !important;
transition: transform 0.2s ease !important;
}
</style>
"""
# 添加JavaScript代码,用于处理导航点击
custom_js = """
<script>
document.addEventListener('DOMContentLoaded', function() {
// 为所有导航链接添加点击事件
document.querySelectorAll('.manual-nav a').forEach(function(link) {
link.addEventListener('click', function(e) {
e.preventDefault();
const targetId = this.getAttribute('href').substring(1);
const targetElement = document.getElementById(targetId);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth'
});
}
});
});
// 为所有手册内容中的图片添加点击事件
document.querySelectorAll('.manual-content img').forEach(function(img) {
img.addEventListener('click', function() {
// 创建一个模态框来显示大图
const modal = document.createElement('div');
modal.style.cssText = 'position:fixed; top:0; left:0; width:100%; height:100%; background-color:rgba(0,0,0,0.8); display:flex; justify-content:center; align-items:center; z-index:9999;';
// 创建大图元素
const largeImg = document.createElement('img');
largeImg.src = this.src;
largeImg.style.cssText = 'max-width:90%; max-height:90%; object-fit:contain;';
// 将大图添加到模态框
modal.appendChild(largeImg);
// 点击模态框关闭它
modal.addEventListener('click', function() {
document.body.removeChild(modal);
});
// 将模态框添加到body
document.body.appendChild(modal);
});
});
});
</script>
"""
# 使用Python的markdown库将Markdown转换为HTML
def markdown_to_html(markdown_content, base_path="src/web/manual"):
"""将Markdown内容转换为HTML,并将图片嵌入为base64编码"""
# 处理图片路径,使用base64编码直接嵌入图片
def embed_image(match):
alt_text = match.group(1)
img_path = match.group(2)
# 检查路径是否为外部URL
if img_path.startswith(('http://', 'https://')):
return f'<img src="{img_path}" alt="{alt_text}" />'
# 处理本地图片路径
try:
# 去掉开头的/以获取正确的路径
if img_path.startswith('/'):
img_path = img_path[1:]
# 获取绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(current_dir))
abs_img_path = os.path.join(project_root, img_path)
# 读取图片并转换为base64
import base64
from pathlib import Path
image_path = Path(abs_img_path)
if image_path.exists():
image_type = image_path.suffix.lstrip('.').lower()
if image_type == 'jpg':
image_type = 'jpeg'
with open(image_path, "rb") as img_file:
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
return f'<img src="data:image/{image_type};base64,{encoded_string}" alt="{alt_text}" style="max-width:100%; height:auto;" />'
else:
print(f"图片文件不存在: {abs_img_path}")
return f'<span style="color:red;">[图片不存在: {img_path}]</span>'
except Exception as e:
print(f"处理图片时出错: {e}, 路径: {img_path}")
return f'<span style="color:red;">[图片加载错误: {img_path}]</span>'
# 使用正则表达式处理所有图片标记
pattern = r'!\[(.*?)\]\((.*?)\)'
processed_content = re.sub(pattern, embed_image, markdown_content)
# 使用Python的markdown库进行转换
html = markdown.markdown(
processed_content,
extensions=[
'tables',
'fenced_code',
'codehilite',
'nl2br',
'extra',
'mdx_truly_sane_lists'
],
extension_configs={
'mdx_truly_sane_lists': {
'nested_indent': 2,
'truly_sane': True
}
}
)
return html
# 从Markdown内容生成HTML导航栏和处理内容
def generate_toc_and_content(markdown_content):
"""从Markdown内容生成HTML导航栏和处理内容"""
# 提取所有标题
headers = re.findall(r'^(#{1,3})\s+(.+)$', markdown_content, re.MULTILINE)
if not headers:
return "<div class='manual-nav'><p>目录加载中...</p></div>", markdown_content
toc_html = "<div class='manual-nav'><ul>"
# 为每个标题创建导航项
for i, (level, title) in enumerate(headers):
level_num = len(level)
header_id = f"header-{i}"
# 根据标题级别添加类
css_class = ""
if level_num == 2:
css_class = "nav-h2"
elif level_num == 3:
css_class = "nav-h3"
toc_html += f"<li><a href='#{header_id}' class='{css_class}'>{title}</a></li>"
toc_html += "</ul></div>"
# 为Markdown内容中的标题添加ID
processed_content = markdown_content
for i, (level, title) in enumerate(headers):
header_id = f"header-{i}"
header_pattern = f"{level} {title}"
header_replacement = f"{level} <span id='{header_id}'></span>{title}"
processed_content = processed_content.replace(header_pattern, header_replacement, 1)
# 将处理后的Markdown转换为HTML
html_content = markdown_to_html(processed_content)
return toc_html, html_content
with gr.Tab("Manual"):
# 添加自定义CSS和JavaScript
gr.HTML(custom_css + custom_js)
with gr.Row():
language = gr.Dropdown(choices=['English', 'Chinese'], value='English', label='Language', interactive=True)
with gr.Tab("Training"):
training_content = load_manual_training(language.value)
toc_html, html_content = generate_toc_and_content(training_content)
training_md = gr.HTML(f"""
<div class="manual-container">
{toc_html}
<div class="manual-content">{html_content}</div>
</div>
""")
with gr.Tab("Prediction"):
prediction_content = load_manual_prediction(language.value)
toc_html, html_content = generate_toc_and_content(prediction_content)
prediction_md = gr.HTML(f"""
<div class="manual-container">
{toc_html}
<div class="manual-content">{html_content}</div>
</div>
""")
with gr.Tab("Evaluation"):
evaluation_content = load_manual_evaluation(language.value)
toc_html, html_content = generate_toc_and_content(evaluation_content)
evaluation_md = gr.HTML(f"""
<div class="manual-container">
{toc_html}
<div class="manual-content">{html_content}</div>
</div>
""")
with gr.Tab("Download"):
download_content = load_manual_download(language.value)
toc_html, html_content = generate_toc_and_content(download_content)
download_md = gr.HTML(f"""
<div class="manual-container">
{toc_html}
<div class="manual-content">{html_content}</div>
</div>
""")
with gr.Tab("FAQ"):
faq_content = load_manual_faq(language.value)
toc_html, html_content = generate_toc_and_content(faq_content)
faq_md = gr.HTML(f"""
<div class="manual-container">
{toc_html}
<div class="manual-content">{html_content}</div>
</div>
""")
# 正确绑定语言切换事件
language.change(
fn=update_manual,
inputs=[language],
outputs=[training_md, prediction_md, evaluation_md, download_md, faq_md]
)
return {"training_md": training_md, "prediction_md": prediction_md, "evaluation_md": evaluation_md, "download_md": download_md, "faq_md": faq_md}
def update_manual(language):
"""更新手册内容"""
training_content = load_manual_training(language)
prediction_content = load_manual_prediction(language)
evaluation_content = load_manual_evaluation(language)
download_content = load_manual_download(language)
faq_content = load_manual_faq(language)
# 使用Python的markdown库将Markdown转换为HTML
def markdown_to_html(markdown_content, base_path="src/web/manual"):
"""将Markdown内容转换为HTML,并将图片嵌入为base64编码"""
# 处理图片路径,使用base64编码直接嵌入图片
def embed_image(match):
alt_text = match.group(1)
img_path = match.group(2)
# 检查路径是否为外部URL
if img_path.startswith(('http://', 'https://')):
return f'<img src="{img_path}" alt="{alt_text}" />'
# 处理本地图片路径
try:
# 去掉开头的/以获取正确的路径
if img_path.startswith('/'):
img_path = img_path[1:]
# 获取绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(current_dir))
abs_img_path = os.path.join(project_root, img_path)
# 读取图片并转换为base64
import base64
from pathlib import Path
image_path = Path(abs_img_path)
if image_path.exists():
image_type = image_path.suffix.lstrip('.').lower()
if image_type == 'jpg':
image_type = 'jpeg'
with open(image_path, "rb") as img_file:
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
return f'<img src="data:image/{image_type};base64,{encoded_string}" alt="{alt_text}" style="max-width:100%; height:auto;" />'
else:
print(f"图片文件不存在: {abs_img_path}")
return f'<span style="color:red;">[图片不存在: {img_path}]</span>'
except Exception as e:
print(f"处理图片时出错: {e}, 路径: {img_path}")
return f'<span style="color:red;">[图片加载错误: {img_path}]</span>'
# 使用正则表达式处理所有图片标记
pattern = r'!\[(.*?)\]\((.*?)\)'
processed_content = re.sub(pattern, embed_image, markdown_content)
# 使用Python的markdown库进行转换
html = markdown.markdown(
processed_content,
extensions=[
'tables',
'fenced_code',
'codehilite',
'nl2br',
'extra',
'mdx_truly_sane_lists'
],
extension_configs={
'mdx_truly_sane_lists': {
'nested_indent': 2,
'truly_sane': True
}
}
)
return html
# 为每个内容生成导航栏和HTML内容
def generate_toc_and_content(markdown_content):
"""从Markdown内容生成HTML导航栏和处理内容"""
# 提取所有标题
headers = re.findall(r'^(#{1,3})\s+(.+)$', markdown_content, re.MULTILINE)
if not headers:
return "<div class='manual-nav'><p>目录加载中...</p></div>", markdown_content
toc_html = "<div class='manual-nav'><ul>"
# 为每个标题创建导航项
for i, (level, title) in enumerate(headers):
level_num = len(level)
header_id = f"header-{i}"
# 根据标题级别添加类
css_class = ""
if level_num == 2:
css_class = "nav-h2"
elif level_num == 3:
css_class = "nav-h3"
toc_html += f"<li><a href='#{header_id}' class='{css_class}'>{title}</a></li>"
toc_html += "</ul></div>"
# 为Markdown内容中的标题添加ID
processed_content = markdown_content
for i, (level, title) in enumerate(headers):
header_id = f"header-{i}"
header_pattern = f"{level} {title}"
header_replacement = f"{level} <span id='{header_id}'></span>{title}"
processed_content = processed_content.replace(header_pattern, header_replacement, 1)
# 将处理后的Markdown转换为HTML
html_content = markdown_to_html(processed_content)
return toc_html, html_content
# 生成带导航栏的HTML
training_toc, training_html = generate_toc_and_content(training_content)
prediction_toc, prediction_html = generate_toc_and_content(prediction_content)
evaluation_toc, evaluation_html = generate_toc_and_content(evaluation_content)
download_toc, download_html = generate_toc_and_content(download_content)
faq_toc, faq_html = generate_toc_and_content(faq_content)
training_output = f"""
<div class="manual-container">
{training_toc}
<div class="manual-content">{training_html}</div>
</div>
"""
prediction_output = f"""
<div class="manual-container">
{prediction_toc}
<div class="manual-content">{prediction_html}</div>
</div>
"""
evaluation_output = f"""
<div class="manual-container">
{evaluation_toc}
<div class="manual-content">{evaluation_html}</div>
</div>
"""
download_output = f"""
<div class="manual-container">
{download_toc}
<div class="manual-content">{download_html}</div>
</div>
"""
faq_output = f"""
<div class="manual-container">
{faq_toc}
<div class="manual-content">{faq_html}</div>
</div>
"""
return training_output, prediction_output, evaluation_output, download_output, faq_output
def load_manual_training(language):
if language == 'Chinese':
manual_path = os.path.join("src/web/manual", "TrainingManual_ZH.md")
else:
manual_path = os.path.join("src/web/manual", "TrainingManual_EN.md")
try:
with open(manual_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"# Error loading manual\n\n{str(e)}"
def load_manual_prediction(language):
if language == 'Chinese':
manual_path = os.path.join("src/web/manual", "PredictionManual_ZH.md")
else:
manual_path = os.path.join("src/web/manual", "PredictionManual_EN.md")
try:
with open(manual_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"# Error loading manual\n\n{str(e)}"
def load_manual_evaluation(language):
if language == 'Chinese':
manual_path = os.path.join("src/web/manual", "EvaluationManual_ZH.md")
else:
manual_path = os.path.join("src/web/manual", "EvaluationManual_EN.md")
try:
with open(manual_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"# Error loading manual\n\n{str(e)}"
def load_manual_download(language):
if language == 'Chinese':
manual_path = os.path.join("src/web/manual", "DownloadManual_ZH.md")
else:
manual_path = os.path.join("src/web/manual", "DownloadManual_EN.md")
try:
with open(manual_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"# Error loading manual\n\n{str(e)}"
def load_manual_faq(language):
if language == 'Chinese':
manual_path = os.path.join("src/web/manual", "QAManual_ZH.md")
else:
manual_path = os.path.join("src/web/manual", "QAManual_EN.md")
try:
with open(manual_path, "r", encoding="utf-8") as f:
return f.read()
except Exception as e:
return f"# FAQ\n\n{str(e)}" |