优化导图图片与交互,补充解析升级对比

develop-refact
panyy 2026-10-22 14:48:02 +08:00
parent f445884497
commit 8b501924f7
11 changed files with 445 additions and 48 deletions

View File

@ -0,0 +1,85 @@
{
"baseline": "PyPI mineru==2.7.1 bdist_wheel",
"url": "https://files.pythonhosted.org/packages/36/fd/d94ab07cbcfabae65a306a6d704214ec6024f443d8119e24234f1b3fa3ba/mineru-2.7.1-py3-none-any.whl",
"sha256": "3c144149f2749a79be240833c392216ddd69c1516de162b29dbaddbc0ce38f73",
"upstream_files": 187,
"local_files": 200,
"changes": [
{
"path": "mineru/backend/vlm/utils.py",
"status": "modified"
},
{
"path": "mineru/backend/vlm/vlm_analyze.py",
"status": "modified"
},
{
"path": "mineru/cli/common.py",
"status": "modified"
},
{
"path": "mineru/cli/fast_api.py",
"status": "modified"
},
{
"path": "mineru/cli/gradio_app.py",
"status": "modified"
},
{
"path": "mineru/cli/static/markmap/d3.min.js",
"status": "added"
},
{
"path": "mineru/cli/static/markmap/markmap-lib.js",
"status": "added"
},
{
"path": "mineru/cli/static/markmap/markmap-toolbar.js",
"status": "added"
},
{
"path": "mineru/cli/static/markmap/markmap-view.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/index-B_viQAxH.css",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/index-zcV97yfy.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/markdown-_Dy2zPzC.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/assets/vendor-DSv9k51x.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/index.html",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/d3.min.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/markmap-lib.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/markmap-toolbar.js",
"status": "added"
},
{
"path": "mineru/cli/static/web/markmap/markmap-view.js",
"status": "added"
},
{
"path": "mineru/utils/table_merge.py",
"status": "modified"
}
]
}

View File

@ -0,0 +1,8 @@
{
"baseline": "PyPI mineru==4.0.12 bdist_wheel",
"url": "https://files.pythonhosted.org/packages/3e/ef/cdf3279dc11a02acfeff4733a29762d2c539f9739c31e2ada8ec37705840/mineru-4.0.12-py3-none-any.whl",
"sha256": "a3ff8582a4608eb1f4dde55800ac156d59b01ceabd2ab4002bdf8e86306b1eab",
"upstream_files": 630,
"local_files": 630,
"changes": []
}

View File

@ -0,0 +1,105 @@
# MinerU 2.7.1 定制盘点与 4.0.12 合并方案
核验日期:2026-10-22。此次完成源码与发布包对比,尚未替换旧内核、安装新依赖或切换运行服务。
## 1. 基线与核验方法
分别下载 PyPI 官方 `mineru==2.7.1`、`mineru==4.0.12` wheel,验证发布元数据中的 SHA-256,再比较包内 `mineru/` 与本地源码目录。忽略 CRLF/LF 差异、`__pycache__` 和 `.pyc`,不安装依赖、不加载模型。
| 项目 | 本地位置 | 发布包比较结果 |
| --- | --- | --- |
| 旧内核 | `markitdown/mineru` | 官方 187 个文件;本地 200 个;6 个 Python 文件修改,13 个静态文件新增,无删除 |
| 新内核 | `ares/third_party/mineru/mineru` | 官方与本地各 630 个文件;全部一致 |
新内核所在独立 Git 仓库 HEAD 为 `b7f3dd0`,标签为 `mineru-4.0.12-released`,工作区干净。发布包比对进一步确认:**ares 这份 4.0.12 的 MinerU 包没有项目定制修改**。Git 仓库为浅克隆,未通过完整上游历史推断来源。
两个发布包的 URL、哈希、文件数及逐文件差异见同目录 `2.7.1-inventory.json` 和 `4.0.12-inventory.json`。该核验范围是 Python 包 `mineru/`;Dockerfile、业务调用和部署脚本另行检查,不能由包一致推导外围项目也无定制。
旧项目 Git 初始化提交 `e5d281a` 已包含部分定制;仅比较初始化提交到 HEAD 会遗漏 `common.py`、`gradio_app.py`、`table_merge.py`。因此本清单以官方发布包为基准。
## 2. 旧版包内定制:逐项迁移结论
| 文件 | 项目差异 | 4.0.12 现状 | 合并位置与处理 |
| --- | --- | --- | --- |
| `mineru/cli/common.py` | 增加 DOC/DOCX;LibreOffice 转 PDF,失败后 DOCX 使用 python-docx + ReportLab 转文本 PDF;增加解析进度回调 | 原生 Office 等格式交由 DocVortex;PDF/图片仍使用 OCR/VLM;文件完成进度已有,但不等于页级进度 | 原生 Office 路径替代转 PDF;进度改为任务内结构化事件,不照搬旧转换实现 |
| `mineru/cli/fast_api.py` | `/api/file_parse`;解析任务进度注册/查询;内存+原子 JSON 文件状态;日志和 tqdm 推断阶段;智能整理异步任务;长文标题分块、局部整理、全局合并;模型参数;OOM 提示、缓存清理;静态工作台挂载 | v1 自带任务、结果、文件、并发和终态清理机制;没有本项目智能整理接口,也没有旧版日志阶段百分比 | 解析生命周期复用 v1;兼容层只翻译协议;智能整理迁到 MaxKB AI Hub;工作台由现有 Vue 页面承接;OOM 分类和阶段事件按新架构接入 |
| `mineru/backend/vlm/utils.py` | `MINERU_GPU_MEMORY_UTILIZATION` 环境变量覆盖默认显存比例,校验 `0 < value < 1` | 新路径 `model/vlm/engine_utils.py` 有默认计算;VLM server 可显式传 `--gpu-memory-utilization`,但未保留该旧环境变量入口 | 保留旧环境变量兼容,转换到实际本地引擎参数;显式参数优先;远程 VLM 的限额在 VLM 服务端配置 |
| `mineru/backend/vlm/vlm_analyze.py` | 按 `AsyncEngineArgs` 签名过滤参数,适应运行时参数差异 | 新路径 `model/vlm/runtime.py`、新的配置/引擎依赖;4.x 未带相同过滤补丁 | 不原样复制“静默丢弃不支持参数”;厂商适配明确白名单、映射或报错,避免显存等关键配置失效 |
| `mineru/cli/gradio_app.py` | Markmap iframe 导图、普通段落提升为子标题、Word 上传和 PDF 预览、内嵌图片、ZIP 输出、页面文案和布局改造 | 新 Gradio 位于 `kit/gradio`,主项目已有 Vue 工作台 | 保留用户可见能力于 Vue,保留现有风格;不把旧 Gradio 整页移进新版内核 |
| `mineru/utils/table_merge.py` | 新增 `(…continued)` 后缀和 caption 内 `(continued)` 匹配;存在续表标识时允许前表最多一条脚注;合并时清掉前表脚注再接后表脚注 | 新架构的通用表格处理主要归 DocVortex,MinerU 另有 LLM 跨页单元格合并;不能把“已有表格合并”当作旧规则完全等价 | 用真实续表样本验证;需要的规则在新后处理扩展点/依赖层迁移;旧版删除脚注的行为需重点核验,不能无条件照搬造成内容丢失 |
新增 13 个静态文件:4 个 `cli/static/markmap` 资源、9 个 `cli/static/web` 页面及依赖资源。它们属于旧界面交付,不是 OCR 算法或天数算子补丁。
旧进度并非完整的引擎真实完成率:包含固定权重日志阶段和文件回调;使用进程全局当前任务 ID、日志 sink 和 stderr 捕获。迁移后要提供任务隔离的阶段事件;只有明确页数/块数时才显示可计算比例,模型加载等阶段显示文字和耗时。
旧长文整理也不宜逐行照搬:它使用估算 token 预算和分块合并,需要补充超长单段切分、超限/截断识别、失败重试及图片引用保留验证。
## 3. 天数适配实际在哪里
旧项目相对官方 2.7.1 **未发现额外修改 OCR/表格/公式模型或新增天数算子源码**。可见的项目适配主要在:
- `docker/china/Dockerfile.corex`、`docker/china/Dockerfile`:采用天数 CoreX 厂商镜像,保留厂商 Torch/vLLM;使用 `--no-deps` 安装及补齐依赖。
- `scripts/build-images.sh`:区分 CoreX/CUDA 构建,默认 CoreX。
- `scripts/start-mindmap.sh`:设置显存比例与 CoreX `PYTHONPATH`。
- `docker/entrypoint.mineru-api.sh`:注入本地 pipeline/VLM 模型路径、公式分隔符和旧 JSON 配置。
- 包内两项 VLM 补丁:显存比例环境变量、AsyncEngineArgs 参数过滤。
这不覆盖厂商基础镜像中未展开的私有补丁、驱动或 wheel 内容,不能凭仓库源码证明这些二进制已兼容新版。
| 项目 | 旧 CoreX 镜像/项目 | 4.0.12 源码要求或现状 |
| --- | --- | --- |
| 基础运行时 | CoreX 4.4.0 / Torch 2.7.1 / vLLM 0.11.2 / Python 3.10 | `torch` extra:Torch >=2.7,<3、Transformers >=5.10.1,<6;`full` extra:Linux vLLM >=0.19.1,<0.29 |
| VLM 工具依赖 | mineru-vl-utils 0.x 范围 | mineru-vl-utils >=2.0.5,<3 |
| 安装 extras | core/pipeline/vlm 等旧分组 | torch/full/all;不能继续照搬 `[core]` |
| 通用文档转换 | 旧 Word 转 PDF | DocVortex >=0.5.16,<1 原生转换 |
| 配置 | 旧 mineru.json、pipeline/vlm 目录 | 新 config.yaml / `MINERU_CONFIG`、`model.base_dir`、`model.small_backend`、`model.vlm`;模型也要单独核对 |
| 天数参数分支 | 依赖厂商运行环境与旧引擎 | 仍有 `MINERU_VLLM_DEVICE=corex` 和编译参数分支;不等于依赖组合/硬件已验证 |
4.0.12 自带 `docs/zh/usage/compatibility.md` 明确:旧 13 类平台适配指南只适用于 MinerU <4,4.0 不自动继承兼容保证。保留的 `docker/china/corex.Dockerfile` 也实际安装 `mineru[core]>=3.4.0,<4`,**不能把它当成 4.0.12 天数镜像**。
另一个版本隐患:旧 CoreX Dockerfile 安装 `mineru[core]>=2.7.4 --no-deps`,随后复制版本号为 2.7.1 的本地源码。镜像内 distribution metadata 与实际 import 的源码可能不同;新构建应固定版本、打印安全的来源清单并校验导入路径,避免混用。
旧启动脚本含删除重建容器、递归 chmod 等步骤,只供审阅,不应用于此次增量发布。旧 entrypoint 每次重写 JSON 配置,也不能直接用于新版配置。
## 4. ares 外围接入:哪些沿用、哪些不迁
`ares/code/backend/services/parser.py` 的 `_parse_pdf_mineru`:
- multipart 同步调用 `/v1/file_parse?tier=basic`,最长等待 1200 秒。
- 读取 `files[].content.markdown`,提取首标题作为文档名。
- 将 Markdown 中 `data:image/...;base64,...` 替换成 `[图片]`。
- PDF 页数达到阈值(默认 8)或文本密度低时才选择 MinerU,失败则继续本地 PDF/OCR 路线。
以上是 ares 的业务集成,不是 4.0.12 内核定制。当前 MaxKB/思维导图已有异步解析资源和图片资产机制,继续使用自己的集成;不复制“图片改占位符”及静默降级策略。
## 5. 统一到 4.0.12 的落点
目标:主维护目录仍在 `markitdown` 和 `maxkb`,`ares` 只提供已核验的源码来源。保留旧版可回退版本;最终活动内核固定为 4.0.12,项目补丁单独登记。
| 层 | 负责的能力 |
| --- | --- |
| MinerU 4.0.12 | 格式识别、原生 Office、PDF/图片 OCR/VLM、渲染输出、模型生命周期 |
| 项目解析扩展 | 结构化阶段进度、必要的续表规则、经过验证的天数引擎/显存配置 |
| 兼容层 | 有实际调用者时保留旧 `/api/file_parse`、任务查询和结果结构;不重新实现一套任务执行器 |
| MaxKB AI Hub | 资源授权、默认服务/流程、智能整理与长文分块、任务和成果、图片资产鉴权及缓存 |
| 思维导图 Vue 工作台 | 直接上传原文件、Markdown/导图预览、折叠状态、图片展示和导出 |
| 部署配置 | 独立虚拟环境或镜像、固定依赖、本地模型挂载、安全增量启动与回退 |
4.0.12 并不是每种格式都走四档模型:Office/HTML/CSV/EPUB/OFD 等为原生 Flash 路径,PDF/图片才是质量分档解析。前端和服务端需按格式路由,不能把 DOCX 原文件上传后仍机械传 PDF 专用页范围或任意档位。
当前两个需要补齐的业务差异:
1. `web_ui/src/composables/useDocumentProcessor.ts` 仍在上传前做 Word→PDF;应改为原文件直传,旧资源仅在明确需要时回退。
2. `maxkb/apps/system_manage/ai_hub_worker.py` 当前智能整理对超过 60000 字符的输入直接拒绝;旧服务的分块整理能力尚未等价迁入。
## 6. 合并与验收顺序
1. 固定官方 4.0.12 来源与依赖清单,保留旧源代码回退点;移入主维护目录时保留官方许可证及声明,不复制 ares 的虚拟环境、业务数据或凭据。
2. 迁移原文件上传及按格式路由;复用 AI Hub 图片资产、任务和结果处理,验证 DOC/DOCX、表格、幻灯片、PDF 和图片。图片型 Office 内容是否 OCR 需按真实文档单独验收。
3. 迁入长文整理,保留标题、图片引用、上下文预算和中间结果;验证超长单段、多块、模型失败和截断。
4. 在 v1 任务中增加结构化阶段/页块进度,贯通 AI Hub 与工作台;验证多任务互不串状态,不用旧日志百分比模拟真实完成率。
5. 按真实样本校验续表的 caption、脚注和跨页单元格;确认 DocVortex 已覆盖的行为后只补缺失规则。
6. 适配 CoreX:优先验证“4.0.12 文档服务 + 独立厂商 VLM 服务”的可行性(协议、模型、OCR 后端均需验证);若选择本地引擎,则先取得兼容的新厂商依赖组合,不在旧镜像中盲目升级。
7. 通过本地检查及隔离接口验证后,按增量发布约定部署;涉及页面同时发布 8080 使用的 `/admin/` 构建产物。检查远端差异和入口,保留旧服务回退,真实验证后再完成默认资源切换。
尚未完成的验证:4.0.12 在目标天数硬件上的模型启动/精度/显存/持续运行;续表规则的新旧等价性;新原生格式在工作台和知识库全链路的验收。本次源码审计不能替代这些运行测试。

View File

@ -30,7 +30,7 @@ export interface ParseResult {
}
export interface ParseProgress {
progress: number
progress: number | null
stage: string
status: 'pending' | 'processing' | 'completed' | 'failed'
error: string | null
@ -46,9 +46,9 @@ const ids = new Map<string, string>()
const states: Record<string, ParseProgress['status']> = { PENDING: 'pending', RUNNING: 'processing', SUCCESS: 'completed', FAILED: 'failed' }
async function progress(taskId: string): Promise<MindmapOrganizeProgress> {
const id = ids.get(taskId)
if (!id) return { progress: 0, status: 'pending', stage: '准备中', error: null, file_names: '' }
if (!id) return { progress: null, status: 'pending', stage: '准备中', error: null, file_names: '' }
const task = await hubCall('tasks', 'get', undefined, id)
return { progress: task.status === 'SUCCESS' ? 100 : Math.floor((task.steps || []).filter((s: any) => s.status === 'SUCCESS').length * 100 / Math.max(1, task.snapshot?.nodes?.length || 1)), status: states[task.status], stage: task.status === 'PENDING' ? '等待处理' : task.status === 'RUNNING' ? '处理中' : task.status === 'SUCCESS' ? '完成' : '失败', error: task.error, file_names: task.name, result_md: task.result?.markdown }
return { progress: task.status === 'SUCCESS' ? 100 : task.progress?.percent ?? null, status: states[task.status], stage: task.progress?.stage || (task.status === 'PENDING' ? '等待处理' : task.status === 'RUNNING' ? '处理中' : task.status === 'SUCCESS' ? '完成' : '失败'), error: task.error, file_names: task.name, result_md: task.result?.markdown }
}
export const documentApi = {
async parseDocument(params: ParseParams, taskId: string = uuid()): Promise<ParseResult> {
@ -69,7 +69,7 @@ export const documentApi = {
}
return { backend: 'shared', version: '1', results }
},
async createParseTask(_taskId: string): Promise<ParseProgress> { return { progress: 0, stage: '准备中', status: 'pending', error: null, file_names: '' } },
async createParseTask(_taskId: string): Promise<ParseProgress> { return { progress: null, stage: '准备中', status: 'pending', error: null, file_names: '' } },
getParseProgress: progress,
async createMindmapTask(taskId: string, markdown: string, _mode = 'smart', prompt?: string, config?: { model_id: string; temperature: number }): Promise<MindmapOrganizeProgress> {
if (!config?.model_id) throw new Error('请选择整理模型')

View File

@ -1,5 +1,6 @@
<template>
<div class="markdown-renderer">
<div class="markdown-renderer" @click="openImage">
<el-image-viewer v-if="imageViewer" :url-list="[imageViewer]" @close="imageViewer = ''" />
<template v-if="content">
<div class="content-toolbar render-actions">
<div class="render-actions-left">
@ -26,6 +27,7 @@
</div>
</div>
<div class="render-content">
<el-button v-if="imageError" link type="warning" @click="retryImages">{{ imageError }}</el-button>
<div v-if="mode === 'markdown'" class="render-shell">
<div ref="markdownRef" class="markdown-content rendered-html" v-html="renderedContent"></div>
</div>
@ -72,6 +74,7 @@ import type { PropType } from 'vue'
import { Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { loadHtml2Pdf } from '@/utils/wordToPdf'
import { useImageAssets, hasImageAssets, exportMarkdownBundle, embedImages } from '@/utils/imageAssets'
type RenderMode = 'markdown' | 'html' | 'pdf' | 'richtext'
type FlavorMode = 'commonmark' | 'gfm'
@ -100,6 +103,10 @@ const pdfRef = ref<HTMLElement | null>(null)
const pdfMeasureRef = ref<HTMLElement | null>(null)
const richtextRef = ref<HTMLElement | null>(null)
const pdfPages = ref<string[]>([])
const imageViewer = ref('')
function openImage(event: MouseEvent) {
if (event.target instanceof HTMLImageElement && event.target.src) imageViewer.value = event.target.src
}
watch(
() => props.flavor,
@ -201,11 +208,12 @@ function createMarkdownRenderer(flavor: FlavorMode) {
return md
}
const { content: previewContent, error: imageError, retry: retryImages } = useImageAssets(() => props.content)
const renderedContent = computed(() => {
if (!props.content) return ''
if (!previewContent.value) return ''
const flavor = props.mode === 'markdown' ? activeFlavor.value : 'gfm'
const renderer = createMarkdownRenderer(flavor)
return renderer.render(props.content)
return renderer.render(previewContent.value)
})
async function recalculatePdfPages() {
@ -222,6 +230,8 @@ async function recalculatePdfPages() {
return
}
await Promise.all(Array.from(measureEl.querySelectorAll('img')).map(image => image.decode().catch(() => undefined)))
const children = Array.from(measureEl.children) as HTMLElement[]
if (children.length === 0) {
pdfPages.value = renderedContent.value ? [renderedContent.value] : []
@ -317,11 +327,15 @@ function escapeRtf(text: string) {
}
async function exportHtml(innerHtml: string, fileName: string) {
const html = createFullHtmlDocument(innerHtml, fileName)
const html = createFullHtmlDocument(await embedImages(innerHtml), fileName)
downloadBlob(new Blob([html], { type: 'text/html;charset=utf-8' }), fileName)
}
async function exportMarkdown(markdown: string, fileName: string) {
if (hasImageAssets(markdown)) {
downloadBlob(await exportMarkdownBundle(markdown), fileName.replace(/\.md$/, '.zip'))
return
}
downloadBlob(new Blob([markdown], { type: 'text/markdown;charset=utf-8' }), fileName)
}
@ -349,7 +363,7 @@ async function exportPdf(element: HTMLElement | null, fileName: string) {
}
async function exportDoc(innerHtml: string, fileName: string) {
const docHtml = createFullHtmlDocument(innerHtml, fileName)
const docHtml = createFullHtmlDocument(await embedImages(innerHtml), fileName)
downloadBlob(new Blob(['\ufeff', docHtml], { type: 'application/msword' }), fileName)
}
@ -360,6 +374,7 @@ async function exportRtf(innerHtml: string, fileName: string) {
}
async function handleDownload() {
try {
if (props.mode === 'markdown') {
const suffix = activeFlavor.value === 'commonmark' ? '_commonmark' : '_gfm'
await exportMarkdown(props.content, `${baseFileName.value}${suffix}.md`)
@ -378,6 +393,7 @@ async function handleDownload() {
return
}
await exportRtf(renderedContent.value, `${baseFileName.value}.rtf`)
} catch { ElMessage.error('下载失败,请重试') }
}
</script>

View File

@ -1,5 +1,6 @@
<template>
<div class="mindmap-container">
<el-image-viewer v-if="imageViewer" :url-list="[imageViewer]" @close="imageViewer = ''" />
<div class="content-toolbar mindmap-actions">
<div class="mindmap-actions-left">
<span class="content-toolbar-meta">{{ nodeSummary }}</span>
@ -39,7 +40,8 @@
</el-button>
</div>
</div>
<div class="mindmap-content" @wheel.prevent="handleWheel" @click="handleNodeClick">
<div class="mindmap-content" @click="handleNodeClick">
<el-button v-if="imageError" link type="warning" @click.stop="retryImages">{{ imageError }}</el-button>
<div class="empty-state" v-if="!content">
<el-icon class="empty-icon"><Document /></el-icon>
<p class="empty-text">暂无思维导图内容</p>
@ -63,6 +65,8 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { Transformer } from 'markmap-lib'
import { Markmap, loadCSS, loadJS } from 'markmap-view'
import * as markmapView from 'markmap-view'
import { useImageAssets, embedImages } from '@/utils/imageAssets'
import { captureFolds, restoreFolds, type FoldState } from '@/utils/mindmapState'
const props = defineProps({
content: {
@ -72,6 +76,10 @@ const props = defineProps({
exportResolution: {
type: Number,
default: 0
},
documentKey: {
type: String,
default: 'document'
}
})
@ -82,6 +90,16 @@ const emit = defineEmits<{
const svgRef = ref<SVGElement | null>(null)
let mmInstance: any = null
let renderTimer: number | undefined
let activeDocumentKey = ''
let renderQueue = Promise.resolve()
let needsInitialFit = true
let viewportObserver: ResizeObserver | undefined
const viewStates = new Map<string, { folds: FoldState; camera: any }>()
function rememberView() {
if (!activeDocumentKey || !mmInstance?.state?.data) return
viewStates.set(activeDocumentKey, { folds: captureFolds(mmInstance.state.data), camera: needsInitialFit ? undefined : mmInstance.svg.property('__zoom') })
if (viewStates.size > 10) viewStates.delete(viewStates.keys().next().value!)
}
const transformer = new Transformer()
const scale = ref(1)
const isRendering = ref(false)
@ -145,8 +163,11 @@ const updateNodeStats = () => {
hiddenNodeCount.value = Math.max(0, stats.hidden)
}
const { content: imageContent, error: imageError, retry: retryImages } = useImageAssets(() => props.content)
const imageViewer = ref('')
const initMarkmap = async () => {
if (!svgRef.value) return
if (props.content && !imageContent.value) return
if (!props.content) {
svgRef.value.innerHTML = ''
@ -160,7 +181,11 @@ const initMarkmap = async () => {
isRendering.value = true
try {
const { root, features } = transformer.transform(props.content)
rememberView()
const documentKey = props.documentKey
const saved = viewStates.get(documentKey)
const { root, features } = transformer.transform(imageContent.value)
restoreFolds(root, saved?.folds)
const { styles, scripts } = transformer.getUsedAssets(features)
if (styles) loadCSS(styles)
@ -168,23 +193,21 @@ const initMarkmap = async () => {
await nextTick()
const sourceNodeCount = (props.content.match(/^#{1,6}\s+/gm) || []).length
const initialExpandLevel = sourceNodeCount > 80 ? 2 : -1
const initialExpandLevel = -1
if (mmInstance) {
if (typeof mmInstance.setData === 'function') {
await mmInstance.setData(root, { initialExpandLevel })
mmInstance.fit()
await mmInstance.setData(root, { initialExpandLevel, autoFit: false })
} else {
mmInstance = Markmap.create(svgRef.value, {
autoFit: true,
autoFit: false,
fitRatio: 0.9,
initialExpandLevel
}, root)
}
} else {
mmInstance = Markmap.create(svgRef.value, {
autoFit: true,
autoFit: false,
fitRatio: 0.9,
initialExpandLevel
}, root)
@ -195,6 +218,11 @@ const initMarkmap = async () => {
text.setAttribute('data-editable-node', 'true')
})
updateNodeStats()
await Promise.all(Array.from(svgRef.value?.querySelectorAll('img') || []).map(image => image.decode().catch(() => undefined)))
activeDocumentKey = documentKey
needsInitialFit = !saved?.camera
if (saved?.camera) mmInstance.svg.call(mmInstance.zoom.transform, saved.camera)
else if (svgRef.value.getBoundingClientRect().width > 0) { needsInitialFit = false; await mmInstance.fit() }
} catch (error) {
console.error('Error initializing markmap:', error)
mmInstance = null
@ -204,20 +232,28 @@ const initMarkmap = async () => {
}
// 监听内容变化自动重绘
watch(() => props.content, () => {
watch([imageContent, () => props.documentKey], () => {
window.clearTimeout(renderTimer)
renderTimer = window.setTimeout(() => {
initMarkmap()
renderQueue = renderQueue.catch(() => undefined).then(initMarkmap)
}, 160)
})
onMounted(() => {
initMarkmap()
renderQueue = renderQueue.then(initMarkmap)
viewportObserver = new ResizeObserver(() => {
if (needsInitialFit && mmInstance?.state?.data && svgRef.value && svgRef.value.getBoundingClientRect().width > 0) {
needsInitialFit = false
void mmInstance.fit()
}
})
if (svgRef.value) viewportObserver.observe(svgRef.value)
// 窗口缩放时自动调整导图大小
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
viewportObserver?.disconnect()
window.clearTimeout(renderTimer)
window.removeEventListener('resize', handleResize)
if (mmInstance && typeof mmInstance.destroy === 'function') {
@ -420,6 +456,7 @@ function createVisibleExportSvg() {
const downloadMindMap = async (format: ExportFormat = 'svg') => {
const exportSvg = createVisibleExportSvg()
if (!exportSvg) return
exportSvg.data = await embedImages(exportSvg.data)
const time = new Date().getTime()
if (format === 'svg') {
@ -494,26 +531,16 @@ const zoomOut = () => {
const applyZoom = () => {
if (mmInstance && typeof mmInstance.setScale === 'function') {
mmInstance.setScale(scale.value)
} else if (mmInstance) {
console.error('mmInstance does not have setScale method:', mmInstance)
}
}
// 处理鼠标滚轮缩放
const handleWheel = (event: WheelEvent) => {
event.preventDefault()
const delta = event.deltaY > 0 ? -0.1 : 0.1
if ((scale.value > 0.5 || delta > 0) && (scale.value < 2 || delta < 0)) {
scale.value += delta
applyZoom()
}
}
const handleNodeClick = async (event: MouseEvent) => {
if (event.target instanceof HTMLImageElement && event.target.src) { imageViewer.value = event.target.src; return }
window.setTimeout(updateNodeStats, 0)
const textNode = (event.target as Element | null)?.closest?.('text')
const oldText = textNode?.textContent?.trim()
if (!oldText || !props.content || oldText === '文档思维导图') return
const rootText = (props.content.split('\n')[0] || '').replace(/^#\s+/, '').replace(/\\(.)/g, '$1')
if (!oldText || !props.content || oldText === rootText) return
try {
const { value } = await ElMessageBox.prompt('编辑节点文本', '编辑思维导图节点', {

View File

@ -2,7 +2,7 @@ import { ref, reactive, watch } from 'vue'
import type { Ref } from 'vue'
import { documentApi, type ParseParams } from '@/api/document'
import { convertWordToPdf, isWordFile } from '@/utils/wordToPdf'
import { buildMindmapMarkdown } from '@/utils/mindmapMarkdown'
import { buildMindmapMarkdown, documentTitleFromName } from '@/utils/mindmapMarkdown'
// 根据上一级标题自动补全下一级标题
export function autoPromoteParagraphsToSubheading(text: string): string {
@ -192,7 +192,7 @@ export function useDocumentProcessor() {
results.value = {
markdown,
source: markdown,
mindmap: buildMindmapMarkdown(markdown)
mindmap: buildMindmapMarkdown(markdown, documentTitleFromName(file.name))
}
error.value = null
console.log('Markdown file loaded directly:', fileName, markdown.length)
@ -251,16 +251,22 @@ export function useDocumentProcessor() {
}
// 进度相关
const progressPercent = ref(0)
const progressPercent = ref<number | null>(null)
const progressStage = ref('')
const progressElapsedLabel = ref('')
let progressStartedAt = 0
let progressTimer: ReturnType<typeof setInterval> | null = null
// 启动进度轮询
const startProgressPolling = (taskId: string) => {
stopProgressPolling()
progressPercent.value = 0
progressPercent.value = null
progressStartedAt = Date.now()
progressElapsedLabel.value = '已用时 0 秒'
progressStage.value = '准备中'
progressTimer = setInterval(async () => {
const elapsed = Math.floor((Date.now() - progressStartedAt) / 1000)
progressElapsedLabel.value = elapsed < 60 ? `已用时 ${elapsed} 秒` : `已用时 ${Math.floor(elapsed / 60)} 分 ${elapsed % 60} 秒`
try {
const data = await documentApi.getParseProgress(taskId)
progressPercent.value = data.progress
@ -335,7 +341,7 @@ export function useDocumentProcessor() {
processingStage.value = '生成 Markdown 和思维导图'
const resultData = Object.values(response.results)[0]
const mdContent = resultData.md_content || ''
const mindmapContent = buildMindmapMarkdown(mdContent)
const mindmapContent = buildMindmapMarkdown(mdContent, documentTitleFromName(uploadedDisplayFiles.value[0]?.name || ''))
results.value = {
markdown: mdContent,
source: mdContent,
@ -387,6 +393,7 @@ export function useDocumentProcessor() {
processingStage,
progressPercent,
progressStage,
progressElapsedLabel,
error,
// 选项

View File

@ -0,0 +1,86 @@
import { onBeforeUnmount, ref, watch, type Ref } from 'vue'
import { hubCall } from '@/api/hub'
const pattern = () => /\/admin\/api\/workspace\/[^/\s"<>]+\/ai_hub\/assets\/([a-f0-9-]{36})\/content/g
const cache = new Map<string, Blob>()
const pending = new Map<string, Promise<Blob>>()
let cachedBytes = 0
async function imageBlob(url: string, id: string) {
if (cache.has(url)) return cache.get(url)!
if (pending.has(url)) return pending.get(url)!
const request = hubCall('assets', 'get', undefined, id).then(result => {
if (!(result.content instanceof ArrayBuffer) || !/^image\/(png|jpeg|gif|webp|bmp)$/.test(result.mime)) throw new Error('图片加载失败')
const blob = new Blob([result.content], { type: result.mime })
while (cache.size && cachedBytes + blob.size > 64 * 1024 * 1024) {
const oldest = cache.keys().next().value!
cachedBytes -= cache.get(oldest)!.size
cache.delete(oldest)
}
cache.set(url, blob); cachedBytes += blob.size
return blob
}).finally(() => pending.delete(url))
pending.set(url, request)
return request
}
export function hasImageAssets(content: string) { return pattern().test(content) }
async function replaceAssets(content: string, convert: (blob: Blob) => Promise<string> | string) {
const replacements = new Map<string, string>()
for (const match of content.matchAll(pattern())) {
if (!replacements.has(match[0])) replacements.set(match[0], await convert(await imageBlob(match[0], match[1])))
}
return content.replace(pattern(), url => replacements.get(url)!)
}
export function useImageAssets(source: () => string): { content: Ref<string>; error: Ref<string>; retry: () => void } {
const content = ref(''), error = ref(''), revision = ref(0)
let generation = 0, urls: string[] = []
watch([source, revision], async ([value]) => {
const current = ++generation, nextUrls: string[] = []
error.value = ''
try {
const resolved = await replaceAssets(String(value), blob => {
const url = URL.createObjectURL(blob); nextUrls.push(url); return url
})
if (current === generation) {
const previous = urls; urls = nextUrls; content.value = resolved
// Give both Vue and markmap time to detach the previous DOM.
window.setTimeout(() => previous.forEach(url => URL.revokeObjectURL(url)), 1000)
} else nextUrls.forEach(url => URL.revokeObjectURL(url))
} catch {
nextUrls.forEach(url => URL.revokeObjectURL(url))
if (current === generation) {
content.value = String(value).replace(pattern(), '')
error.value = '图片加载失败,点击重试'
}
}
}, { immediate: true })
onBeforeUnmount(() => { generation++; urls.forEach(url => URL.revokeObjectURL(url)) })
return { content, error, retry: () => revision.value++ }
}
export function blobDataUrl(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result))
reader.onerror = () => reject(new Error('图片读取失败'))
reader.readAsDataURL(blob)
})
}
// Standalone HTML and SVG must not contain browser-session Blob URLs.
export async function embedImages(html: string) {
const document = new DOMParser().parseFromString(html, 'text/html')
for (const image of Array.from(document.querySelectorAll('img'))) {
if (image.src.startsWith('blob:')) image.setAttribute('src', await blobDataUrl(await (await fetch(image.src)).blob()))
}
return document.body.innerHTML
}
export async function exportMarkdownBundle(markdown: string) {
const result = await hubCall('exports', 'post', { markdown })
if (!(result.content instanceof ArrayBuffer) || result.mime !== 'application/zip') throw new Error('导出失败')
return new Blob([result.content], { type: result.mime })
}

View File

@ -74,11 +74,16 @@ function collectTableRows(tokens: Token[], startIndex: number) {
return { rows, endIndex }
}
export function buildMindmapMarkdown(markdown: string) {
export function documentTitleFromName(name: string) {
return name.replace(/\.[^.\\/]+$/, '').trim() || ROOT_TITLE
}
export function buildMindmapMarkdown(markdown: string, title = ROOT_TITLE) {
if (!markdown.trim()) return ''
const tokens = md.parse(markdown, {})
const result: string[] = [`# ${ROOT_TITLE}`]
const rootTitle = normalizeNodeText(title).replace(/([\\`*{}\[\]()#+.!_<>])/g, '\\$1')
const result: string[] = [`# ${rootTitle || ROOT_TITLE}`]
let currentHeadingLevel = 1
let listDepth = 0

View File

@ -0,0 +1,46 @@
export interface MindmapNode {
content?: string
children?: MindmapNode[]
payload?: { fold?: number; [key: string]: unknown }
}
export interface FoldState { paths: Map<string, number>; unique: Map<string, number> }
function identity(node: MindmapNode) {
// Browser Blob URLs change on every preview render; image identity must not.
return (node.content || '').replace(/src="blob:[^"]*"/g, 'src=""').replace(/\s+/g, ' ').trim()
}
function visit(root: MindmapNode, fn: (node: MindmapNode, path: string, text: string) => void) {
const walk = (node: MindmapNode, path: string) => {
fn(node, path, identity(node))
const occurrences = new Map<string, number>()
for (const child of node.children || []) {
const text = identity(child), ordinal = occurrences.get(text) || 0
occurrences.set(text, ordinal + 1)
walk(child, `${path}/${JSON.stringify([text, ordinal])}`)
}
}
walk(root, 'root')
}
export function captureFolds(root: MindmapNode): FoldState {
const paths = new Map<string, number>(), unique = new Map<string, number>(), repeated = new Set<string>()
visit(root, (node, path, text) => {
const fold = node.payload?.fold || 0
paths.set(path, fold)
if (unique.has(text)) repeated.add(text)
else unique.set(text, fold)
})
repeated.forEach(text => unique.delete(text))
return { paths, unique }
}
export function restoreFolds(root: MindmapNode, saved?: FoldState) {
const counts = new Map<string, number>()
visit(root, (_node, _path, text) => counts.set(text, (counts.get(text) || 0) + 1))
visit(root, (node, path, text) => {
const fold = saved?.paths.get(path) ?? (counts.get(text) === 1 ? saved?.unique.get(text) : undefined) ?? 0
node.payload = { ...node.payload, fold: node.children?.length ? fold : 0 }
})
}

View File

@ -113,13 +113,13 @@
<div class="progress-wrapper">
<div class="progress-info">
<span class="progress-stage">{{ progressStage || processingStage || '正在处理文档...' }}</span>
<span class="progress-percent">{{ progressPercent }}%</span>
<span class="progress-percent">{{ progressPercent === null ? progressElapsedLabel : `${progressPercent}%` }}</span>
</div>
<el-progress
:percentage="progressPercent"
:percentage="progressPercent ?? 100"
:stroke-width="10"
:show-text="false"
:indeterminate="progressPercent === 0"
:indeterminate="progressPercent === null"
class="progress-bar"
/>
</div>
@ -152,7 +152,7 @@
:disabled="sourceViewMode === 'ast' || isSmartOrganizing"
/>
<span v-if="isSmartOrganizing" class="smart-organize-status">
{{ smartOrganizeStage || '智能整理中' }} {{ smartOrganizeProgress }}%
{{ smartOrganizeStage || '智能整理中' }} {{ smartOrganizeProgress === null ? '' : `${smartOrganizeProgress}%` }}
</span>
<span v-else-if="smartOrganizeError" class="template-error-inline">
{{ smartOrganizeError }}
@ -191,6 +191,7 @@
<div class="mindmap-box">
<MindMapRenderer
:content="renderedMindmapContent"
:document-key="mindmapDocumentKey"
:export-resolution="config.exportResolution"
@node-edit="handleMindmapNodeEdit"
/>
@ -258,7 +259,7 @@ import { hubCall, onOpenArtifact } from '@/api/hub'
import { documentApi } from '@/api/document'
import { DOCUMENT_CONFIG_STORAGE_KEY, useDocumentProcessor } from '@/composables/useDocumentProcessor'
import { markdownToAstString } from '@/utils/markdownAst'
import { buildMindmapMarkdown, replaceFirstMindmapText } from '@/utils/mindmapMarkdown'
import { buildMindmapMarkdown, documentTitleFromName, replaceFirstMindmapText } from '@/utils/mindmapMarkdown'
import { createEmptyReplacementRule, renderMarkdownTemplate, type ReplacementRule } from '@/utils/markdownTemplate'
const MARKDOWN_RENDER_MODE_KEY = 'mineru.documentProcessor.markdownRenderMode'
@ -301,6 +302,7 @@ const {
processingStage,
progressPercent,
progressStage,
progressElapsedLabel,
error,
backendOptions,
languageOptions,
@ -334,7 +336,7 @@ const draftReplacementRules = ref<ReplacementRule[]>([])
const smartMarkdownContent = ref('')
const smartOrganizeTaskId = ref('')
const isSmartOrganizing = ref(false)
const smartOrganizeProgress = ref(0)
const smartOrganizeProgress = ref<number | null>(null)
const smartOrganizeStage = ref('')
const smartOrganizeError = ref('')
let smartOrganizeTimer: ReturnType<typeof setInterval> | null = null
@ -351,7 +353,10 @@ const activeSourceMarkdownContent = computed(() => {
})
const templateRenderResult = computed(() => renderMarkdownTemplate(activeSourceMarkdownContent.value, replacementRules.value))
const renderedMarkdownContent = computed(() => templateRenderResult.value.markdown)
const renderedMindmapContent = computed(() => buildMindmapMarkdown(renderedMarkdownContent.value))
const openedArtifact = ref<any>(null)
const mindmapDocumentKey = ref(`document-${Date.now()}`)
const documentTitle = computed(() => documentTitleFromName(uploadedDisplayFiles.value[0]?.name || openedArtifact.value?.name || '思维导图'))
const renderedMindmapContent = computed(() => buildMindmapMarkdown(renderedMarkdownContent.value, documentTitle.value))
const templateRenderError = computed(() => templateRenderResult.value.error)
const activeReplacementRuleCount = computed(() => replacementRules.value.filter((rule) => rule.search.trim()).length)
const hasActiveReplacementRules = computed(() => activeReplacementRuleCount.value > 0)
@ -543,6 +548,7 @@ const applyConfig = (nextConfig: typeof config) => {
}
const handleProcessDocument = async () => {
mindmapDocumentKey.value = `parse-${Date.now()}`
openedArtifact.value = null
originalRecognized.value = ''
resetSmartOrganizeState()
@ -623,6 +629,7 @@ const triggerUpload = () => {
const handleFileInputChange = async (event: Event) => {
const input = event.target as HTMLInputElement
if (input.files) {
mindmapDocumentKey.value = `upload-${Date.now()}`
openedArtifact.value = null
originalRecognized.value = ''
await handleFileUpload(input.files)
@ -645,6 +652,7 @@ const handleDrop = async (event: DragEvent) => {
isDragging.value = false
if (event.dataTransfer?.files) {
mindmapDocumentKey.value = `upload-${Date.now()}`
openedArtifact.value = null
originalRecognized.value = ''
await handleFileUpload(event.dataTransfer.files)
@ -675,11 +683,13 @@ const clearAllFiles = () => {
isUploadAreaCollapsed.value = false
}
const openedArtifact = ref<any>(null)
const originalRecognized = ref('')
const stopArtifactListener = onOpenArtifact((artifact) => {
resetSmartOrganizeState()
openedArtifact.value = artifact
mindmapDocumentKey.value = `artifact-${artifact.id}`
uploadedFiles.value = []
uploadedDisplayFiles.value = []
originalRecognized.value = artifact.original || ''
results.value = { markdown: artifact.markdown, source: artifact.markdown, mindmap: buildMindmapMarkdown(artifact.markdown) }
})
@ -696,6 +706,8 @@ async function saveArtifact() {
layout: current?.layout || 'tree'
}, current?.id)
openedArtifact.value = saved
originalRecognized.value = saved.original || ''
results.value = { markdown: saved.markdown, source: saved.markdown, mindmap: buildMindmapMarkdown(saved.markdown) }
ElMessage.success('已保存')
} catch (e: any) { ElMessage.error(e.message || '保存失败') }
}