From 75ca1efd60abe8adb7def1101940332cc1788e21 Mon Sep 17 00:00:00 2001 From: Jack Yao Date: Thu, 24 Sep 2026 12:34:13 +0800 Subject: [PATCH 1/2] fix: recover PDF extraction results and honest conversion status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PDF.js 提取完成后销毁 loading task,清理失败不再丢弃已提取页面 - Node 环境改用原生文件路径加载 CMap 与标准字体 - 无正文 PDF 返回 PDF_TEXT_UNAVAILABLE/PDF_ENCRYPTED,不再导出占位提示 - 稀疏文本表单标记 sparse-text-pdf,避免误判扫描件重复 OCR - 混合 PDF 仅对无文字页按页 OCR,并按原页号插回正文 - PDF→PDF 复制原字节保留字体/图像/版面(PDF_ORIGINAL_PRESERVED) - 输入/输出 PDF 预览改用本地 PDF.js 逐页渲染,规避 CSP object-src 拦截 - PDF 表格按列坐标定位;DOCX 首行/续行缩进与制表位映射到 PDF 输出 - textFidelity 未实际回读时标为 unverified,未确认页号进入 unresolvedPdfPages Closes #216 --- CHANGELOG.md | 7 + docs/architecture/MULTI_MODEL_ARCHITECTURE.md | 2 +- docs/formats/BASIC_FORMAT_QUALITY.md | 3 +- docs/formats/DOCX_INPUT_MVP.md | 4 +- docs/formats/PDF_TEXT_EXTRACTION_MVP.md | 13 +- public/app.js | 136 ++++++++++++++++-- public/core/document-audit.js | 5 +- public/core/format-registry.js | 76 +++++++++- public/core/ocr/pdf-rasterizer-browser.js | 46 +++--- public/core/ocr/pdf-rasterizer.js | 38 ++--- public/core/ocr/scan-pdf-stage.js | 135 +++++++++++++---- public/core/verification/ocr-readback.js | 31 +++- public/formats/docx.js | 16 ++- public/formats/pdf-output-high-fidelity.js | 25 +++- public/formats/pdf-output.js | 112 ++++++++++++--- public/formats/pdf.js | 129 ++++++++++------- public/index.html | 3 +- public/styles.css | 37 +++++ scripts/browser-smoke-test.js | 4 +- scripts/format-validation-test.js | 4 + scripts/ocr-baseline-test.js | 106 +++++++++++++- scripts/pdf-reader-test.js | 48 ++++++- scripts/release-user-path-e2e-test.js | 12 +- scripts/smoke-test.js | 22 +-- scripts/ui-conversion-e2e-test.js | 65 ++++++++- .../conversions/empty-md-to-json.json | 2 +- 26 files changed, 884 insertions(+), 197 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a38f091..6628d59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ ### 修复 - **Issue #214 跨格式文本与字段偏移**:TXT 保留单换行、缩进和普通下划线字段名;PDF 只在实测坐标支持时补空格,并按重复双栏分离阅读顺序;DOCX 往返保留页面尺寸/页边距、段落对齐/缩进/制表位、表格列宽和 `gridSpan` / `vMerge`。PDF、HTML、DOCX writer 对尚未支持的版面特性发出降级 warning,QualityReport 增加 `layoutFidelity`。新增英文表单布局回归测试。 +- **Issue #216 PDF 提取链可靠性**:PDF.js 提取完成后改为销毁 loading task,清理失败不再丢弃已提取页面;Node 环境改用原生文件路径加载 CMap 与标准字体,修复 `file:` URL 导致提取为空;混合文档保留无文字页页号并发出 `PDF_PAGES_WITHOUT_TEXT`。 +- **Issue #216 空正文不再冒充成功结果**:PDF 经 OCR 仍无可编辑正文时返回 `PDF_TEXT_UNAVAILABLE` / `PDF_ENCRYPTED` 结构化错误,不再把占位提示写入输出正文;工作台对未确认页号显示警告状态而非无条件成功。 +- **Issue #216 扫描件误判与按页 OCR**:稀疏文本英文表单标记为 `sparse-text-pdf`,不再误判为扫描件重复 OCR;扫描 PDF 默认处理全部页面(可用 `options.ocr.maxScanPages` 截断);混合 PDF 仅对无文字页执行 OCR 并按原页号插回正文,OCR 坐标从栅格像素映射回 PDF 点位。 +- **Issue #216 PDF → PDF 保留原件**:同格式转换经模型路由审计后直接复制原 PDF 字节(`PDF_ORIGINAL_PRESERVED`),保留原字体、图像与版面,不新增可检索文字层;修复 PDF.js 转移输入缓冲区导致的原始字节丢失。 +- **Issue #216 PDF 预览链路**:输入与输出 PDF 均改由本地 PDF.js 逐页渲染预览,取代被 Web/Tauri CSP(`object-src 'none'`)拦截的 `` 备用预览;生成文件的 Blob 下载入口独立保留。 +- **Issue #216 版面保真补强**:PDF 表格字段按列坐标定位,不再用空格补齐列;DOCX 首行/续行缩进与制表位(含对齐方式)映射到 PDF 输出;固定布局替代字体按来源文本框宽度缩放;DOCX 单元格保留连续空格、制表符与段落边界。 +- **Issue #216 质量报告诚实性**:未实际运行输出回读时 `textFidelity` 标为 `unverified`,不再由 warning 数量推断高保真;未确认页号进入 `qualityReport.unresolvedPdfPages` 并随输出返回。 ## [2.4.0] - 2026-07-17 diff --git a/docs/architecture/MULTI_MODEL_ARCHITECTURE.md b/docs/architecture/MULTI_MODEL_ARCHITECTURE.md index 391961a..12d734e 100644 --- a/docs/architecture/MULTI_MODEL_ARCHITECTURE.md +++ b/docs/architecture/MULTI_MODEL_ARCHITECTURE.md @@ -253,7 +253,7 @@ S2 已落地为 `public/core/repair-engine.js`、`public/core/repair-actions.js` - `runSsimLayer({ ctx, output })`:资格判断 `ctx.from ∈ {pdf,png}` 且 `ctx.to ∈ {pdf,png}`(当前实际命中 `pdf→pdf` / `png→pdf`);经 `defaultPageImageSource` 取源图 + 输出图像素 → `compareImages` → `qualityReport.ssim = { score, threshold, passed, width, height, pageIndex, sourceFormat, outputFormat }`;低于阈值(默认 0.85)发 info 级 `SSIM_VISUAL_DRIFT`。 - 像素源抽象 `public/core/verification/page-image-source.js`:`defaultPageImageSource`(Node 抛 `VERIFICATION_IMAGE_SOURCE_UNAVAILABLE`;浏览器首次调用 dynamic import `page-image-source-browser.js` 用 vendor pdfjs + canvas `getImageData` 取 RGBA)+ `setPageImageSource` / `resetPageImageSource` 让测试注入 stub。 - `format-registry.js` 抽出 `_runRepairCycle` / `_assembleQuality` 共享,`convert()`(sync)走 `_wrapWithRepairCycle`(rule-diff),`convertAsync()` 走 `_wrapWithRepairCycleAsync`(rule-diff + SSIM)。`options.repair === false` 仍短路整个验证阶段。 -- 注意:Trans2Former 的 `pdf → pdf` 走「reader 抽文本 → writer 重排版」,视觉本就不保真,SSIM 偏低是**诚实信号**,故仅发 info warning,不判失败、不阻塞。本轮渲染 stub-only(Node 无 canvas;真实 PDF/PNG 渲染 fixture + 浏览器端端到端验证留给后续)。 +- 当前 `pdf → pdf` 在完成 reader 与路由审计后复制原 PDF 字节,不重绘页面,也不新增 OCR 可检索文本层;该路径的 SSIM 应反映相同文件的视觉结果。PDF 转其他格式仍按各 reader/writer 的保真范围评估。Node 无 canvas 时视觉回环仍会跳过,不能把跳过视为视觉验证通过。 ### 转换后检验三层 · OCR 回读层(P9-C.3 落地) diff --git a/docs/formats/BASIC_FORMAT_QUALITY.md b/docs/formats/BASIC_FORMAT_QUALITY.md index 78aafa9..739d921 100644 --- a/docs/formats/BASIC_FORMAT_QUALITY.md +++ b/docs/formats/BASIC_FORMAT_QUALITY.md @@ -95,6 +95,7 @@ After: - 连续文本段落进入 `paragraph`。 - 段落内单换行、行首空格和普通下划线字段名保留。 - 质量报告将 `layoutFidelity` 与 `textFidelity`、`structureFidelity` 分开;不承载页面布局的输入标为 `not-applicable`。 +- 未实际运行输出文本回读时,`textFidelity` 为 `unverified`;warning 数量不能单独证明文本保真。 降级说明:TXT 没有字体、分页、坐标等页面布局元数据;连续空行按段落边界规范化。 @@ -121,4 +122,4 @@ After: - P4 生成程序化 PDF 二进制 data URL。 -降级说明:P0 不是程序化 PDF 引擎,不保证复杂分页、字体嵌入和印刷级排版。 +降级说明:P0 不是程序化 PDF 引擎,不保证复杂分页、字体嵌入和印刷级排版;表格字段按列坐标定位,DOCX 段落的首行/续行缩进和左对齐制表位分别映射。固定布局 PDF 的替代字体按来源文本框宽度缩放,但无法恢复原字体字形、逐字间距和图片;仍须用真实文档检查视觉偏移。 diff --git a/docs/formats/DOCX_INPUT_MVP.md b/docs/formats/DOCX_INPUT_MVP.md index 9171f47..c62631b 100644 --- a/docs/formats/DOCX_INPUT_MVP.md +++ b/docs/formats/DOCX_INPUT_MVP.md @@ -9,9 +9,9 @@ DOCX input MVP 的目标是把 Word 文档本地解析为 `DocumentModel`,优 ## 当前支持 - 标题:识别 `w:pStyle` 中的 `Heading1` 到 `Heading6`。 -- 段落:合并 `w:t` 文本。 +- 段落:按 run 顺序保留 `w:t` 文本、连续空格、制表符和换行;`block.text` 与 `inlines` 的纯文本一致。 - 链接:解析 `word/_rels/document.xml.rels` 中的 external hyperlink,并追加到可读文本。 -- 表格:第一行作为 headers,其余行作为 rows;保留 `tblGrid` 列宽、`gridSpan` 跨列和 `vMerge` 纵向合并信息。 +- 表格:第一行作为 headers,其余行作为 rows;保留单元格内的连续空格、制表符及段落分隔,并保留 `tblGrid` 列宽、`gridSpan` 跨列和 `vMerge` 纵向合并信息。 - 段落布局:保留对齐、左右/首行/悬挂缩进、段前段后间距、行距和自定义制表位;文档页面尺寸、方向和页边距供 DOCX writer 回写。 - 图片引用:解析 `a:blip r:embed`,读取 `word/media/*`,进入 `assets` 并生成 asset block。 - 列表:识别 `w:numPr`,映射为 `DocumentModel` list,保留层级 metadata。 diff --git a/docs/formats/PDF_TEXT_EXTRACTION_MVP.md b/docs/formats/PDF_TEXT_EXTRACTION_MVP.md index 34962a6..2c767b1 100644 --- a/docs/formats/PDF_TEXT_EXTRACTION_MVP.md +++ b/docs/formats/PDF_TEXT_EXTRACTION_MVP.md @@ -14,14 +14,23 @@ PDF text extraction MVP 只面向文本型 PDF 的基础文本提取,不承诺 - 上传 PDF 时本地解压常见 `/FlateDecode` 内容流,再抽取其中的 `BT...ET` 文本对象。 - 保留并解析解压后的 ToUnicode CMap,支持常见 CID -> Unicode 映射,用于中文 PDF 的 ` Tj/TJ` 文本恢复。 - PDF.js 失败时才回落到核心轻量解析器;回落解析中的 ToUnicode CMap 必须尽量按当前 `/F... Tf` 字体绑定,多 CMap 无法绑定时不输出猜测文本,避免错误识别污染转换结果。 +- Node 环境使用本地文件路径加载 CMap 与标准字体;PDF.js 提取完成后销毁 loading task,清理失败不丢弃已提取页面。 +- 没有可信正文时,`DocumentModel` 保留空正文与结构化 warning;工作台用 PDF.js 逐页渲染原 PDF,并提供 Blob 下载链接。转换成可编辑输出时若 OCR 后仍无正文,返回 `PDF_TEXT_UNAVAILABLE` 或 `PDF_ENCRYPTED`,不把提示语写入输出。 +- 工作台的 PDF 输出预览也由本地 PDF.js 逐页渲染;生成文件的下载链接独立保留,不依赖浏览器或桌面 WebView 的内嵌 PDF 查看器。 +- `PDF → PDF` 通过模型路由审计后直接复制原 PDF 字节,保留原图像、字体和版面;此路径不执行 OCR,也不添加可检索文字层,结果给出 `PDF_ORIGINAL_PRESERVED` 提示。 +- 自动 OCR 仅在未提取到可信文本时触发;稀疏文本 PDF 标记为 `sparse-text-pdf`,避免把表单字段再次 OCR 后重复或重排。 +- 混合文本页和无文字页时保留全部页号;无文字页写入 `metadata.pdf.pagesWithoutText`,并发出 `PDF_PAGES_WITHOUT_TEXT` warning。异步转换且本地 OCR 可用时只识别无文字页,再按原页号插入正文,避免重复识别已有文本页。 +- 仍未识别到文字的页面进入 `qualityReport.unresolvedPdfPages`;工作台显示具体页号和 warning 内容,并将完成状态标为警告。关闭 Repair 时,核心 API 仍通过输出的 `unresolvedPdfPages` 与 `warnings` 返回同一风险。 +- OCR 坐标在固定布局模型内按来源页尺寸从栅格像素映射回 PDF 点位;重绘型 PDF writer 仍不能恢复原图像和图形,无文字来源页会发出 `PDF_HF_PAGE_VISUALS_UNVERIFIED`。同格式 PDF 路由使用上述原件复制路径。 - 输出 heading + paragraph blocks。 - 按实际水平坐标推断英文片段间的空格;重复双栏页面按左栏后右栏的顺序恢复,避免仅凭字母/数字相邻插入空格。 - 生成 `PDF_TEXT_EXTRACTION_MVP` lossy warning。 ## 当前限制 -- 不处理扫描 PDF。 -- 不处理 OCR。 +- 扫描 PDF 的文字提取依赖独立的本地 OCR 阶段及可用模型;未识别到正文时不得视为转换成功。 +- 无文字页可能本身为空白;若 OCR 不可用、被关闭或识别失败,warning 仍表示该页的可编辑内容未得到确认。同步转换不执行 OCR。 +- 扫描 PDF 默认处理全部页面;只有明确设置 `options.ocr.maxScanPages` 才截断并发出 `OCR_SCAN_PAGES_TRUNCATED`。 - 不还原完整字体、图片、坐标、表格结构和复杂版面;PDF 多栏检测是启发式处理,跨栏标题/特殊阅读顺序仍可能降级。 - 不承诺所有字体子集、自定义 CMap、坐标重排或图形化文字都能恢复为可编辑文本。 - 不调用云端 PDF、OCR 或 AI 服务。 diff --git a/public/app.js b/public/app.js index 28f52f1..dcdfc5a 100644 --- a/public/app.js +++ b/public/app.js @@ -8,6 +8,7 @@ import { renderPreviewHtml, toConversionDocumentModel, toDocumentModel, + createBrowserPdfPageRasterizer, ensurePaddleDefaultModels, rehydrateTesseractAvailability, } from "./browser-transformer.js"; @@ -102,6 +103,7 @@ const verificationOcrReadback = byId("verificationOcrReadback"); const verificationOcrRecognition = byId("verificationOcrRecognition"); const verificationOcrRecognitionRow = byId("verificationOcrRecognitionRow"); const verificationWarnings = byId("verificationWarnings"); +const verificationWarningDetails = byId("verificationWarningDetails"); const securityCenterButton = byId("securityCenterButton"); const workbenchTabs = byId("workbenchTabs"); const workflowSteps = [...document.querySelectorAll("[data-workflow-step]")]; @@ -134,6 +136,9 @@ function greet(name) { let currentFileName = "document.md"; let currentInputContent = sampleMarkdown; let currentOutputBlobUrl = ""; +let currentInputPdfPreviewUrl = ""; +let currentInputPdfRasterizer = null; +let currentOutputPdfRasterizer = null; let currentOutputDownloadBlob = null; let currentOutputFileName = ""; let previewTimer = null; @@ -604,7 +609,7 @@ function describeRuleDiff(ruleDiff, verification) { function describeSsim(ssim, verification) { if (ssim) { const score = typeof ssim.score === "number" ? ssim.score.toFixed(3) : "-"; - return { state: ssim.passed ? "ok" : "drift", text: `score ${score} (阈值 ${ssim.threshold}) · ${ssim.sourceFormat}→${ssim.outputFormat}` }; + return { state: ssim.passed ? "ok" : "drift", text: `第 ${Number(ssim.pageIndex || 0) + 1} 页 · score ${score} (阈值 ${ssim.threshold}) · ${ssim.sourceFormat}→${ssim.outputFormat}` }; } const skip = (verification?.skipped || []).find((entry) => entry.layer === "ssim"); return { state: "skip", text: `跳过:${skip?.reason || "未触发"}` }; @@ -614,7 +619,8 @@ function describeOcrReadback(ocrReadback, verification) { if (ocrReadback) { const f1 = typeof ocrReadback.f1 === "number" ? ocrReadback.f1.toFixed(3) : "-"; const recall = typeof ocrReadback.recall === "number" ? ocrReadback.recall.toFixed(3) : "-"; - return { state: ocrReadback.passed ? "ok" : "drift", text: `f1 ${f1} · recall ${recall} (阈值 ${ocrReadback.threshold}) · ${ocrReadback.engineId}` }; + const pages = ocrReadback.checkedPages ? ` · 已检查 ${ocrReadback.checkedPages}/${ocrReadback.pageCount} 页` : ""; + return { state: ocrReadback.passed ? "ok" : "drift", text: `f1 ${f1} · recall ${recall} (阈值 ${ocrReadback.threshold}) · ${ocrReadback.engineId}${pages}` }; } const skip = (verification?.skipped || []).find((entry) => entry.layer === "ocr-readback"); return { state: "skip", text: `跳过:${skip?.reason || "未触发"}` }; @@ -704,12 +710,27 @@ function renderVerificationReport(quality = currentConversionQuality) { const severityText = Object.keys(severity).length > 0 ? Object.entries(severity).map(([level, count]) => `${level}:${count}`).join(" · ") : "无"; - applyVerificationRow(verificationWarnings, { state: (report.downgradeCount || 0) > 0 ? "drift" : "ok", text: `${report.warningCount || 0} 条(${severityText})` }); + const unresolvedPages = report.unresolvedPdfPages || []; + const unresolvedText = unresolvedPages.length > 0 ? ` · 第 ${unresolvedPages.join("、")} 页文字未确认` : ""; + applyVerificationRow(verificationWarnings, { + state: unresolvedPages.length > 0 || (report.downgradeCount || 0) > 0 ? "drift" : "ok", + text: `${report.warningCount || 0} 条(${severityText})${unresolvedText}`, + }); + if (verificationWarningDetails) { + verificationWarningDetails.replaceChildren(); + const warnings = Array.isArray(quality.warnings) ? quality.warnings : []; + for (const warning of warnings.slice(0, 20)) { + const item = document.createElement("li"); + item.textContent = `[${warning.code || "CONVERSION_NOTICE"}] ${warning.message || ""}`; + verificationWarningDetails.appendChild(item); + } + verificationWarningDetails.hidden = warnings.length === 0; + } const activeLayers = (verification.layers || []).length; if (verificationReportBadge) { verificationReportBadge.textContent = activeLayers > 0 ? `${activeLayers} 层已检验` : "未触发检验层"; - verificationReportBadge.dataset.state = activeLayers > 0 ? "ok" : "skip"; + verificationReportBadge.dataset.state = unresolvedPages.length > 0 ? "warning" : activeLayers > 0 ? "ok" : "skip"; } verificationReportPanel.hidden = false; } @@ -1099,7 +1120,7 @@ function resetGeneratedOutput(metaMessage = "尚未生成") { verificationReportPanel.hidden = true; } textOutputPreview.textContent = ""; - pdfPreview.removeAttribute("src"); + pdfPreview.replaceChildren(); downloadOutputButton.textContent = "下载输出"; if (outputEditor) { outputEditor.value = ""; @@ -1447,12 +1468,92 @@ function renderPreview() { const model = toDocumentModel(content, fromFormatSelect.value, currentFileName); const bodyHtml = renderPreviewHtml(content, fromFormatSelect.value, currentFileName); htmlPreview.innerHTML = bodyHtml; + if (currentInputPdfPreviewUrl) { + URL.revokeObjectURL(currentInputPdfPreviewUrl); + currentInputPdfPreviewUrl = ""; + } + if (currentInputPdfRasterizer) { + void currentInputPdfRasterizer.dispose(); + currentInputPdfRasterizer = null; + } + if (fromFormatSelect.value === "pdf") { + if (model.metadata?.pdf?.textStatus !== "extracted") { + const notice = document.createElement("p"); + notice.textContent = model.metadata?.pdf?.encrypted + ? "此 PDF 已加密,无法提取正文。请先解除密码后重试。" + : "目前未能提取可编辑正文。可在下方查看原 PDF;转换需要可提取文本或可用的 OCR。"; + htmlPreview.prepend(notice); + } + const originalDataUrl = content.match(/^data:application\/pdf;base64,[A-Za-z0-9+/=]+/i)?.[0]; + if (originalDataUrl) { + currentInputPdfPreviewUrl = URL.createObjectURL(new Blob([dataUrlToBytes(originalDataUrl)], { type: "application/pdf" })); + const download = document.createElement("a"); + download.href = currentInputPdfPreviewUrl; + download.download = currentFileName || "original.pdf"; + download.textContent = "下载原 PDF"; + htmlPreview.appendChild(download); + const viewer = document.createElement("div"); + viewer.className = "input-pdf-viewer"; + htmlPreview.appendChild(viewer); + const rasterizer = createBrowserPdfPageRasterizer(); + currentInputPdfRasterizer = rasterizer; + void renderPdfPages(rasterizer, originalDataUrl, viewer, () => currentInputPdfRasterizer === rasterizer, "原 PDF"); + } + } renderMathIn(htmlPreview); renderDocumentModelPanel(model); lastRenderedPayload = payloadKey; setStatus(`浏览器端预览已更新 (${Date.now() - renderStart}ms)`, "success"); } +async function renderPdfPages(rasterizer, content, viewer, isCurrent, labelPrefix) { + const downloadHint = labelPrefix === "原 PDF" ? "上方链接下载原件" : "下载按钮查看 PDF"; + try { + const pageCount = await rasterizer.countPages({ content }); + if (!isCurrent() || !viewer.isConnected) return; + if (!Number.isSafeInteger(pageCount) || pageCount < 1) throw new Error("PDF 页数不可用"); + const controls = document.createElement("div"); + controls.className = "input-pdf-controls"; + const previous = document.createElement("button"); + previous.type = "button"; + previous.textContent = "上一页"; + const next = document.createElement("button"); + next.type = "button"; + next.textContent = "下一页"; + const label = document.createElement("span"); + const image = document.createElement("img"); + image.className = "input-pdf-page"; + image.alt = `${labelPrefix} 页面预览`; + controls.append(previous, label, next); + viewer.append(controls, image); + let pageIndex = 0; + async function showPage(index) { + previous.disabled = true; + next.disabled = true; + try { + const rendered = await rasterizer.rasterize({ content, pageIndex: index, dpi: 96 }); + if (!isCurrent() || !viewer.isConnected) return; + image.src = rendered.dataUrl; + image.alt = `${labelPrefix} 第 ${index + 1} 页`; + label.textContent = `第 ${index + 1} / ${pageCount} 页`; + previous.disabled = index === 0; + next.disabled = index === pageCount - 1; + pageIndex = index; + } catch (error) { + if (isCurrent() && viewer.isConnected) { + viewer.textContent = `${labelPrefix} 页面暂时无法渲染:${error?.message || error}。可使用${downloadHint}。`; + } + } + } + previous.addEventListener("click", () => { void showPage(pageIndex - 1); }); + next.addEventListener("click", () => { void showPage(pageIndex + 1); }); + await showPage(0); + } catch (error) { + if (!isCurrent() || !viewer.isConnected) return; + viewer.textContent = `${labelPrefix} 页面暂时无法渲染:${error?.message || error}。可使用${downloadHint}。`; + } +} + function renderPreviewWhenIdle() { cancelIdleTask(previewIdleHandle); setStatus("预览已排队,浏览器空闲时刷新", "info"); @@ -1478,6 +1579,14 @@ function schedulePreviewUpdate() { } async function handleInputText(rawContent, fileName = currentFileName, { renderInitialPreview = true } = {}) { + if (currentInputPdfPreviewUrl) { + URL.revokeObjectURL(currentInputPdfPreviewUrl); + currentInputPdfPreviewUrl = ""; + } + if (currentInputPdfRasterizer) { + void currentInputPdfRasterizer.dispose(); + currentInputPdfRasterizer = null; + } workspaceRevision += 1; setWorkflowStep("preview"); currentFileName = fileName; @@ -1609,6 +1718,10 @@ function buildWorkerPayload(payload) { function releaseConversionResources() { revokeOutputUrl(); + if (currentOutputPdfRasterizer) { + void currentOutputPdfRasterizer.dispose(); + currentOutputPdfRasterizer = null; + } if (activeConversion?.worker) { activeConversion.worker.terminate(); activeConversion = null; @@ -1739,6 +1852,10 @@ async function transformContent() { } const result = await convertWithWorker({ content, from, to, title, fileName: currentFileName, options }); + const unresolvedPdfPages = result.quality?.qualityReport?.unresolvedPdfPages || result.unresolvedPdfPages || []; + const completionStatus = unresolvedPdfPages.length > 0 + ? `输出已生成,但第 ${unresolvedPdfPages.join("、")} 页的可编辑文字未确认;请核对原 PDF。` + : ""; // 注意:不在主线程重复调用 toConversionDocumentModel,因为 worker/convertAsync // 内部已经完整执行了 prepareConversionModel(包含 read + mappers + audit)。 @@ -1770,7 +1887,10 @@ async function transformContent() { downloadOutputButton.download = currentOutputFileName; downloadOutputButton.textContent = "下载二进制输出"; if (result.format === "pdf") { - pdfPreview.src = outputUrl; + pdfPreview.replaceChildren(); + const rasterizer = createBrowserPdfPageRasterizer(); + currentOutputPdfRasterizer = rasterizer; + void renderPdfPages(rasterizer, result.data, pdfPreview, () => currentOutputPdfRasterizer === rasterizer, "输出 PDF"); updateOutputPreviewVisibility(true); } else { renderBinaryOutputPreview(result); @@ -1781,7 +1901,7 @@ async function transformContent() { setOutputMeta(`二进制输出已生成 · ${result.mime} · ${outputDirectoryLabel}`); updateConversionProgress({ stage: "complete", progress: 1, message: "转换完成" }); updateActiveQueueItem({ status: "done" }); - setStatus("浏览器端本地二进制转换成功", "success"); + setStatus(completionStatus || "浏览器端本地二进制转换成功", completionStatus ? "warning" : "success"); return; } @@ -1796,7 +1916,7 @@ async function transformContent() { setWorkflowStep("output"); updateConversionProgress({ stage: "complete", progress: 1, message: "转换完成" }); updateActiveQueueItem({ status: "done" }); - setStatus("浏览器端转换成功", "success"); + setStatus(completionStatus || "浏览器端转换成功", completionStatus ? "warning" : "success"); } catch (error) { if (error.message === "转换已取消") { updateConversionProgress({ stage: "canceled", progress: 0, message: "转换已取消" }); diff --git a/public/core/document-audit.js b/public/core/document-audit.js index 8922464..8782034 100644 --- a/public/core/document-audit.js +++ b/public/core/document-audit.js @@ -185,9 +185,8 @@ export function ensureDocumentAudit(model, { structureFidelity: warnings.some((warning) => warning.severity === "lossy") ? "medium" : "high", tableFidelity: blocks.some((block) => block.type === "table") ? "tracked" : "not-applicable", assetFidelity: assets.length > 0 ? "tracked" : "not-applicable", - // 修复 issue #122: 添加 textFidelity 字段 - // 基于 warnings 中的文本相关降级判断文本保真度 - textFidelity: warnings.some((w) => w.severity === "lossy" && /text|content|字符|编码/.test(w.message)) ? "medium" : "high", + // Reader/writer warnings are risk indicators, not proof that output text matches input. + textFidelity: "unverified", layoutFidelity: !carriesPageLayout ? "not-applicable" : hasLayoutLoss ? "low" : "medium", warningCount: warnings.length, warningsBySeverity: warningSummary(warnings), diff --git a/public/core/format-registry.js b/public/core/format-registry.js index 41367fc..730832f 100644 --- a/public/core/format-registry.js +++ b/public/core/format-registry.js @@ -1,8 +1,10 @@ import { ConversionError } from "./conversion-error.js"; +import { getPlainText } from "./document-model.js"; import { ensureDocumentAudit } from "./document-audit.js"; import { defaultRepairEngine } from "./repair-engine.js"; import { runVerificationStage, runVerificationStageAsync } from "./verification/verification-stage.js"; import { createWarning, withWarnings } from "./warnings.js"; +import { copyOriginalPdf } from "../formats/pdf.js"; const FORMAT_ALIASES = { markdown: "md", @@ -567,8 +569,15 @@ export class ConverterRegistry { : auditedModel; const baseQualityReport = finalModel.metadata?.qualityReport || {}; + const unresolvedPdfPages = this._unresolvedPdfPages(finalModel, fromFormat, effectiveTo); const qualityReport = { ...baseQualityReport, + unresolvedPdfPages, + textFidelity: verification.ruleDiff + ? (verification.ruleDiff.fidelity === "exact" ? "high" : "medium") + : verification.ocrReadback + ? (verification.ocrReadback.passed ? "medium" : "low") + : "unverified", repairStatus: repairStatusFromDecision(cycle.autoRepair), finalDecision: cycle.autoRepair?.finalDecision || "pending", ruleDiff: verification.ruleDiff, @@ -586,6 +595,7 @@ export class ConverterRegistry { ...cycle.output, quality: { qualityReport, + warnings: finalModel.metadata?.warnings || [], modelReview: finalModel.metadata?.modelReview || null, autoRepair: finalModel.metadata?.autoRepair || null, conversion: finalModel.metadata?.conversion || null, @@ -639,14 +649,57 @@ export class ConverterRegistry { } } + _requirePdfText(model, fromFormat) { + if (fromFormat !== "pdf" || getPlainText(model).trim()) return; + const encrypted = model?.metadata?.pdf?.encrypted === true; + throw new ConversionError( + encrypted + ? "此 PDF 已加密,无法提取正文。请先解除密码后重试。" + : "未能从 PDF 提取可编辑正文。请检查原 PDF 预览,或启用可用的 OCR 后重试。", + { + category: "parse", + code: encrypted ? "PDF_ENCRYPTED" : "PDF_TEXT_UNAVAILABLE", + format: "pdf", + details: { extraction: model?.metadata?.pdf?.extraction || "unknown" }, + }, + ); + } + + _unresolvedPdfPages(model, fromFormat, toFormat) { + if (fromFormat !== "pdf" || toFormat === "pdf") return []; + const recoveredPages = new Set((model?.metadata?.ocr?.lines || []) + .filter((line) => String(line?.text || "").trim()) + .map((line) => line.pageIndex + 1)); + return (model?.metadata?.pdf?.pagesWithoutText || []) + .filter((page) => Number.isSafeInteger(page) && page > 0 && !recoveredPages.has(page)); + } + + _surfacePdfSourceWarnings(model, output, fromFormat) { + if (fromFormat !== "pdf") return output; + const warnings = [...(output.warnings || []), ...(model?.metadata?.warnings || [])]; + const signatures = new Set(); + return { + ...output, + warnings: warnings.filter((warning) => { + const signature = `${warning.code}|${warning.message}`; + if (signatures.has(signature)) return false; + signatures.add(signature); + return true; + }), + unresolvedPdfPages: this._unresolvedPdfPages(model, fromFormat, output.format), + }; + } + convert({ content, from, to, title = "document", fileName = "", options = {} }) { const fromFormat = normalizeFormat(from); const toFormat = normalizeFormat(to); this._checkResourceBudget(content, fromFormat); const model = this.prepareConversionModel({ content, from, to, title, fileName, options }); - const output = this.write({ model, to, title, options }); + const pdfIdentityCopy = fromFormat === "pdf" && toFormat === "pdf"; + if (!pdfIdentityCopy) this._requirePdfText(model, fromFormat); + const output = pdfIdentityCopy ? copyOriginalPdf(content) : this.write({ model, to, title, options }); if (options?.repair === false) { - return output; + return this._surfacePdfSourceWarnings(model, output, fromFormat); } const ctx = this._buildRepairCtx({ content, fromFormat, toFormat, title, fileName, options }); const qualityModel = this._mergeWriterWarnings({ model, output, content, fromFormat, toFormat, fileName, options }); @@ -664,6 +717,17 @@ export class ConverterRegistry { throw new Error("转换已取消"); } + const pdfIdentityCopy = fromFormat === "pdf" && toFormat === "pdf"; + // PDF.js may transfer a Uint8Array's buffer while extracting text. Capture + // same-format output before that operation so the original bytes survive. + const identityOutput = pdfIdentityCopy ? copyOriginalPdf(content) : null; + + if (fromFormat === "pdf") { + const { expandPdfContentForTextExtraction } = await import("../formats/pdf.js"); + content = await expandPdfContentForTextExtraction(content); + if (signal?.aborted) throw new Error("转换已取消"); + } + let model = this.prepareConversionModel({ content, from, to, title, fileName, options }); if (options?.ocr?.enabled !== false && fromFormat === "png") { @@ -675,7 +739,7 @@ export class ConverterRegistry { to: toFormat, signal, }); - } else if (options?.ocr?.enabled !== false && fromFormat === "pdf") { + } else if (options?.ocr?.enabled !== false && fromFormat === "pdf" && toFormat !== "pdf") { if (signal?.aborted) throw new Error("转换已取消"); const { isScannedPdf } = await import("./ocr/pdf-rasterizer.js"); const detection = await isScannedPdf(content, options?.ocr || {}); @@ -688,14 +752,16 @@ export class ConverterRegistry { from: fromFormat, to: toFormat, signal, + pageIndices: detection.pageIndices, }); } } if (signal?.aborted) throw new Error("转换已取消"); - const output = this.write({ model, to, title, options }); + if (!pdfIdentityCopy) this._requirePdfText(model, fromFormat); + const output = identityOutput || this.write({ model, to, title, options }); if (options?.repair === false) { - return output; + return this._surfacePdfSourceWarnings(model, output, fromFormat); } const ctx = this._buildRepairCtx({ content, fromFormat, toFormat, title, fileName, options }); const qualityModel = this._mergeWriterWarnings({ model, output, content, fromFormat, toFormat, fileName, options }); diff --git a/public/core/ocr/pdf-rasterizer-browser.js b/public/core/ocr/pdf-rasterizer-browser.js index 8d682a9..91f17e3 100644 --- a/public/core/ocr/pdf-rasterizer-browser.js +++ b/public/core/ocr/pdf-rasterizer-browser.js @@ -29,7 +29,9 @@ function decodePdfContent(content) { const isBase64 = meta.includes(";base64"); const payload = content.slice(commaIdx + 1); if (isBase64) { - const decoded = globalThis.atob(payload); + // Expanded PDF inputs can carry an extraction payload after the data URL. + const encoded = payload.match(/^[A-Za-z0-9+/=]+/)?.[0] || ""; + const decoded = globalThis.atob(encoded); const bytes = new Uint8Array(decoded.length); for (let i = 0; i < decoded.length; i += 1) bytes[i] = decoded.charCodeAt(i); return bytes; @@ -53,6 +55,9 @@ async function loadPdfJs(vendorUrl = VENDOR_PDFJS) { if (typeof mod?.getDocument !== "function") { throw new Error("vendor pdfjs missing getDocument"); } + if (mod.GlobalWorkerOptions && !mod.GlobalWorkerOptions.workerSrc) { + mod.GlobalWorkerOptions.workerSrc = "/vendor/pdfjs/pdf.worker.min.mjs"; + } return mod; } catch (error) { throw new ConversionError(`PDF.js vendor 加载失败:${error?.message || error}`, { @@ -65,10 +70,18 @@ async function loadPdfJs(vendorUrl = VENDOR_PDFJS) { async function openDocument(pdfjs, content) { const data = decodePdfContent(content); - const loadingTask = pdfjs.getDocument({ data, isEvalSupported: false, disableFontFace: true }); + const loadingTask = pdfjs.getDocument({ + data, + isEvalSupported: false, + disableFontFace: true, + cMapUrl: "/vendor/pdfjs/cmaps/", + cMapPacked: true, + standardFontDataUrl: "/vendor/pdfjs/standard_fonts/", + }); try { - return await loadingTask.promise; + return { document: await loadingTask.promise, loadingTask }; } catch (error) { + try { await loadingTask.destroy(); } catch { /* preserve the parsing error */ } throw new ConversionError(`PDF document 解析失败:${error?.message || error}`, { category: "convert", code: "OCR_RASTERIZER_FAILED", @@ -86,6 +99,7 @@ export function createBrowserPdfPageRasterizer({ vendorUrl = VENDOR_PDFJS } = {} // PDF document 缓存:按 content 的弱标识缓存已打开的 document,避免多页扫描时重复解析 let cachedDocument = null; + let cachedLoadingTask = null; let cachedContentRef = null; async function getCachedDocument(pdfjs, content) { @@ -94,15 +108,16 @@ export function createBrowserPdfPageRasterizer({ vendorUrl = VENDOR_PDFJS } = {} return cachedDocument; } // 清理旧的 document - if (cachedDocument && typeof cachedDocument.destroy === "function") { - try { - cachedDocument.destroy(); - } catch (error) { - // ignore cleanup errors - } + if (cachedLoadingTask) { + try { await cachedLoadingTask.destroy(); } catch { /* ignore cleanup errors */ } } + cachedDocument = null; + cachedLoadingTask = null; + cachedContentRef = null; // 打开新 document 并缓存 - cachedDocument = await openDocument(pdfjs, content); + const opened = await openDocument(pdfjs, content); + cachedDocument = opened.document; + cachedLoadingTask = opened.loadingTask; cachedContentRef = content; return cachedDocument; } @@ -151,15 +166,12 @@ export function createBrowserPdfPageRasterizer({ vendorUrl = VENDOR_PDFJS } = {} // 注意:不在这里 destroy document,让它保持缓存供后续页面使用 }, // 显式清理接口,供外部在完成多页扫描后调用 - dispose() { - if (cachedDocument && typeof cachedDocument.destroy === "function") { - try { - cachedDocument.destroy(); - } catch (error) { - // ignore cleanup errors - } + async dispose() { + if (cachedLoadingTask) { + try { await cachedLoadingTask.destroy(); } catch { /* ignore cleanup errors */ } } cachedDocument = null; + cachedLoadingTask = null; cachedContentRef = null; }, }); diff --git a/public/core/ocr/pdf-rasterizer.js b/public/core/ocr/pdf-rasterizer.js index bb13e47..9650356 100644 --- a/public/core/ocr/pdf-rasterizer.js +++ b/public/core/ocr/pdf-rasterizer.js @@ -1,5 +1,5 @@ import { ConversionError } from "../conversion-error.js"; -import { expandPdfContentForTextExtraction, readPdf } from "../../formats/pdf.js"; +import { expandPdfContentForTextExtraction, hasPdfJsExtractionPayload, readPdf } from "../../formats/pdf.js"; export const OCR_RASTERIZER_UNAVAILABLE = "OCR_RASTERIZER_UNAVAILABLE"; export const OCR_RASTERIZER_FAILED = "OCR_RASTERIZER_FAILED"; @@ -28,24 +28,13 @@ function countModelText(model) { return total; } -const PDFJS_PAYLOAD_MARKER = "% Trans2Former PDFJS_TEXT_START"; - export async function isScannedPdf(content, options = {}) { const threshold = typeof options?.scanPdfThreshold === "number" ? options.scanPdfThreshold : DEFAULT_SCAN_PDF_THRESHOLD; try { const expanded = await expandPdfContentForTextExtraction(content); - const hasPdfJsPayload = typeof expanded === "string" && expanded.includes(PDFJS_PAYLOAD_MARKER); - if (!hasPdfJsPayload) { - return { - scanned: true, - extractedChars: 0, - pageCount: 0, - threshold, - reason: "no-pdfjs-payload", - }; - } + const hasPdfJsPayload = hasPdfJsExtractionPayload(expanded); const model = readPdf({ content: expanded, title: "isScannedPdf-probe", fileName: "" }); // 加密 PDF 不是扫描件:走 OCR 链路只会逐页 open 失败产出误导 warning(issue #104) if (model?.metadata?.pdf?.encrypted) { @@ -60,19 +49,25 @@ export async function isScannedPdf(content, options = {}) { const extractedChars = countModelText(model); // 修复:从 metadata.pdf.pageCount 读取页数(而非不存在的 metadata.pages) const pageCount = model?.metadata?.pdf?.pageCount || 0; + const pageIndices = (model?.metadata?.pdf?.pagesWithoutText || []) + .filter((number) => Number.isSafeInteger(number) && number >= 1 && number <= pageCount) + .map((number) => number - 1); - // 修复:按页归一化阈值,避免多页扫描件因累计水印文字超过固定300阈值而被误判为文本PDF - // 使用每页阈值:如果平均每页提取字符数 < 每页阈值,则判定为扫描件 - const perPageThreshold = threshold; + // Sparse forms can contain only a few genuine text fields. OCR-ing them again + // duplicates and reorders those fields. For mixed PDFs, OCR only textless pages. const avgCharsPerPage = pageCount > 0 ? extractedChars / pageCount : extractedChars; - const isScanned = avgCharsPerPage < perPageThreshold; + const isScanned = extractedChars === 0 || pageIndices.length > 0; return { scanned: isScanned, extractedChars, pageCount, + pageIndices: extractedChars === 0 ? undefined : pageIndices, threshold, - reason: isScanned ? "low-extracted-text" : "text-pdf", + reason: isScanned + ? (extractedChars > 0 ? "mixed-text-and-textless-pages" + : hasPdfJsPayload ? "no-credible-text" : "no-pdfjs-payload") + : avgCharsPerPage < threshold ? "sparse-text-pdf" : "text-pdf", }; } catch (error) { return { @@ -135,6 +130,12 @@ export const defaultPdfPageRasterizer = Object.freeze({ if (browserImpl) return browserImpl.countPages(args); throwUnavailable("countPages"); }, + async dispose() { + if (_injectedRasterizer && typeof _injectedRasterizer.dispose === "function") { + await _injectedRasterizer.dispose(); + } + if (_autoBrowserImpl) await _autoBrowserImpl.dispose(); + }, get DPI_DEFAULT() { return DEFAULT_DPI; }, @@ -152,6 +153,7 @@ export function setPdfPageRasterizer(impl) { } export function resetPdfPageRasterizer() { + if (_autoBrowserImpl) void _autoBrowserImpl.dispose(); _injectedRasterizer = null; _autoBrowserImpl = null; _autoBrowserLoadFailed = false; diff --git a/public/core/ocr/scan-pdf-stage.js b/public/core/ocr/scan-pdf-stage.js index 93f5393..d1a1cea 100644 --- a/public/core/ocr/scan-pdf-stage.js +++ b/public/core/ocr/scan-pdf-stage.js @@ -7,12 +7,11 @@ import { defaultPdfPageRasterizer } from "./pdf-rasterizer.js"; import { mergeOCRResultsToFixedLayout } from "./ocr-to-fixed-layout.js"; import { mapLinesToBlockIds } from "./ocr-structure.js"; import { fixedLayoutToSemantic } from "../models/mappers.js"; -import { getFixedLayoutSummary } from "../models/fixed-layout.js"; +import { createFixedLayoutModel, getFixedLayoutSummary } from "../models/fixed-layout.js"; export const MODEL_VISUAL_FIDELITY_LOST = "MODEL_VISUAL_FIDELITY_LOST"; export const MODEL_TEXT_ORDER_HEURISTIC = "MODEL_TEXT_ORDER_HEURISTIC"; -const DEFAULT_MAX_SCAN_PAGES = 5; const DEFAULT_DPI = 144; const LOW_CONFIDENCE_THRESHOLD = 0.6; @@ -39,6 +38,45 @@ function paragraphsFromPageResult(result) { return paragraphs; } +function mergeOCRPagesWithSourceLayout(sourceLayout, ocrLayout, successfulIndices) { + if (!Array.isArray(sourceLayout?.pages) || sourceLayout.pages.length === 0) return ocrLayout; + const pages = sourceLayout.pages.map((page) => ({ ...page, textRuns: [...(page.textRuns || [])] })); + for (let index = 0; index < successfulIndices.length; index += 1) { + const pageIndex = successfulIndices[index]; + const sourcePage = pages[pageIndex]; + const ocrPage = ocrLayout.pages[index]; + if (!sourcePage || !ocrPage) continue; + const sourceWidth = Number(sourcePage.size?.width); + const sourceHeight = Number(sourcePage.size?.height); + const ocrWidth = Number(ocrPage.size?.width); + const ocrHeight = Number(ocrPage.size?.height); + if (![sourceWidth, sourceHeight, ocrWidth, ocrHeight].every((value) => Number.isFinite(value) && value > 0)) { + continue; + } + const scaleX = sourceWidth / ocrWidth; + const scaleY = sourceHeight / ocrHeight; + const textRuns = ocrPage.textRuns.map((run) => { + if (!run.bbox) return run; + const { x, y, w, h } = run.bbox; + return { + ...run, + bbox: { + x: x * scaleX, + y: sourceHeight - (y + h) * scaleY, + w: w * scaleX, + h: h * scaleY, + }, + fontSize: h * scaleY, + }; + }); + sourcePage.textRuns.push(...textRuns); + } + return createFixedLayoutModel({ + pages, + metadata: { ...(sourceLayout.metadata || {}), ocr: ocrLayout.metadata?.ocr }, + }); +} + export async function runScannedPdfOCRStage(model, ctx = {}) { if (ctx?.options?.ocr?.enabled === false) return model; const registry = ctx.ocrRegistry || defaultOCRRegistry; @@ -57,12 +95,12 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { }; } const rasterizer = ctx.rasterizer || defaultPdfPageRasterizer; - // 钳位到 ≥1 的整数:0/负数/NaN 一律回落默认值,杜绝「maxScanPages=0 静默丢弃全文」 - // 与负页码乱码 warning 两类边界(issue #5 复核发现)。 + // A page limit is an explicit partial-extraction choice. Invalid limits fall + // back to all pages so the default path never silently drops later pages. const rawMaxPages = ctx?.options?.ocr?.maxScanPages; - const maxPages = typeof rawMaxPages === "number" && Number.isFinite(rawMaxPages) && rawMaxPages >= 1 + const configuredMaxPages = typeof rawMaxPages === "number" && Number.isFinite(rawMaxPages) && rawMaxPages >= 1 ? Math.floor(rawMaxPages) - : DEFAULT_MAX_SCAN_PAGES; + : null; const dpi = typeof ctx?.options?.ocr?.dpi === "number" ? ctx.options.ocr.dpi : DEFAULT_DPI; // 用户语言偏好(options.ocr.language)归一化后传引擎;注意下方已有 `let language` // 累积变量(记录引擎返回的语言),此处必须用独立名字避免遮蔽。 @@ -86,17 +124,35 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { ]), }; } - const effectivePages = Math.min(maxPages, Math.max(1, pageCount || 0)); - if (effectivePages === 0) return model; + if (!Number.isSafeInteger(pageCount) || pageCount < 0) { + return { + ...model, + metadata: withWarnings(model.metadata || {}, [createOCREngineFailedWarning({ + engineId: engine.id, + manifestId: engine.manifestId || "", + reason: "rasterizer-invalid-page-count", + cause: String(pageCount), + })]), + }; + } + const maxPages = configuredMaxPages ?? pageCount; + const effectivePages = Math.min(maxPages, pageCount); + const requestedIndices = Array.isArray(ctx.pageIndices) + ? [...new Set(ctx.pageIndices)] + .filter((index) => Number.isSafeInteger(index) && index >= 0 && index < pageCount) + .sort((a, b) => a - b) + : Array.from({ length: pageCount }, (_, index) => index); + const pageIndices = requestedIndices.filter((index) => index < effectivePages); + if (pageIndices.length === 0 && requestedIndices.length === 0) return model; const enhanced = cloneModel(model); - const truncated = typeof pageCount === "number" && pageCount > effectivePages; + const truncated = requestedIndices.length > pageIndices.length; if (truncated) { // 在循环前注入:即使后续每页 OCR 都失败,截断事实也不丢。 enhanced.metadata = withWarnings(enhanced.metadata, [ createOCRScanPagesTruncatedWarning({ totalPages: pageCount, - processedPages: effectivePages, + processedPages: pageIndices.length, maxScanPages: maxPages, engineId: engine.id, }), @@ -105,12 +161,13 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { const lines = []; const aggregateConfidences = []; const pageResults = []; + const successfulIndices = []; let runtimeMsTotal = 0; let language = ""; let modelVersion = ""; try { - for (let pageIndex = 0; pageIndex < effectivePages; pageIndex += 1) { + for (const pageIndex of pageIndices) { // 检查是否已取消 if (ctx?.signal?.aborted) { throw new Error("OCR已取消"); @@ -132,6 +189,7 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { continue; } pageResults.push(pageResult); + successfulIndices.push(pageIndex); runtimeMsTotal += pageResult?.runtimeMs || 0; if (typeof pageResult?.averageConfidence === "number") aggregateConfidences.push(pageResult.averageConfidence); language = language || pageResult?.language || ""; @@ -152,7 +210,7 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { // 清理 rasterizer 缓存的 PDF document if (typeof rasterizer.dispose === "function") { try { - rasterizer.dispose(); + await rasterizer.dispose(); } catch (error) { // ignore cleanup errors } @@ -164,18 +222,41 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { : 0; const fixedLayout = mergeOCRResultsToFixedLayout(pageResults, { language, engine: engine.id, modelVersion }); - enhanced.fixedLayout = fixedLayout; + enhanced.fixedLayout = mergeOCRPagesWithSourceLayout(model.fixedLayout, fixedLayout, successfulIndices); const appendedStart = enhanced.blocks.length; + const ocrBlocks = []; + const ocrBlocksByPage = new Map(); if (pageResults.length > 0) { - const semanticFromLayout = fixedLayoutToSemantic(fixedLayout, { - title: enhanced.title || "scan-ocr", - sourceFormat: enhanced.sourceFormat || "pdf", - }); - enhanced.blocks.push(...(semanticFromLayout.blocks || [])); - // 给追加块预赋稳定 id(绝对索引),供低置信修复按 block.id 命中;document-audit 保留之。 - for (let i = appendedStart; i < enhanced.blocks.length; i += 1) { - if (!enhanced.blocks[i].id) enhanced.blocks[i].id = `ocr-block-${i}`; + for (let index = 0; index < fixedLayout.pages.length; index += 1) { + const semantic = fixedLayoutToSemantic({ pages: [fixedLayout.pages[index]] }, { + title: enhanced.title || "scan-ocr", + sourceFormat: enhanced.sourceFormat || "pdf", + }); + const pageBlocks = semantic.blocks || []; + for (const block of pageBlocks) { + if (!block.id) block.id = `ocr-block-${appendedStart + ocrBlocks.length}`; + ocrBlocks.push(block); + } + ocrBlocksByPage.set(successfulIndices[index], pageBlocks); + } + const pageBlockCounts = model.metadata?.pdf?.pageBlockCounts; + const canInterleave = Array.isArray(pageBlockCounts) + && pageBlockCounts.length === pageCount + && pageBlockCounts.every((count) => Number.isSafeInteger(count) && count >= 0) + && pageBlockCounts.reduce((sum, count) => sum + count, 0) === enhanced.blocks.length; + if (canInterleave) { + const orderedBlocks = []; + let offset = 0; + for (let pageIndex = 0; pageIndex < pageCount; pageIndex += 1) { + const count = pageBlockCounts[pageIndex]; + orderedBlocks.push(...enhanced.blocks.slice(offset, offset + count)); + orderedBlocks.push(...(ocrBlocksByPage.get(pageIndex) || [])); + offset += count; + } + enhanced.blocks = orderedBlocks; + } else { + enhanced.blocks.push(...ocrBlocks); } enhanced.metadata = withWarnings(enhanced.metadata, [ createWarning( @@ -195,16 +276,15 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { // 用文本包含把每行映射到承载它的追加块的 id。不能按 lines 顺序硬配索引: // mergeOCRResultsToFixedLayout 会按阅读顺序(bbox y→x)重排,lines 顺序 ≠ 块顺序。 - const appendedBlocks = enhanced.blocks.slice(appendedStart); - const blockIds = mapLinesToBlockIds(lines, appendedBlocks); + const blockIds = mapLinesToBlockIds(lines, ocrBlocks); lines.forEach((ocrLine, i) => { ocrLine.blockId = blockIds[i] || ""; }); enhanced.metadata.ocr = { language: language || "auto", - pageCount: effectivePages, - // 空 PDF 时 effectivePages 被既有 Math.max(1,…) 钳到 1,取 max 保证 total ≥ processed。 + pageCount: pageIndices.length, totalPageCount: typeof pageCount === "number" ? Math.max(pageCount, effectivePages) : effectivePages, truncated, + pageIndices, lineCount: lines.length, lines, }; @@ -215,9 +295,10 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { tasks: Array.from(new Set([...(enhanced.metadata.modelReview?.tasks || []), "ocr-text-recognition", "scan-pdf-rasterize"])), inferenceMode: "local", ocr: { - pageCount: effectivePages, + pageCount: pageIndices.length, totalPageCount: typeof pageCount === "number" ? Math.max(pageCount, effectivePages) : effectivePages, truncated, + pageIndices, lineCount: lines.length, averageConfidence, runtimeMs: runtimeMsTotal, @@ -225,7 +306,7 @@ export async function runScannedPdfOCRStage(model, ctx = {}) { modelVersion: modelVersion || "", language: language || "auto", fullTextLength: lines.reduce((acc, line) => acc + (line.text?.length || 0), 0), - fixedLayout: getFixedLayoutSummary(fixedLayout), + fixedLayout: getFixedLayoutSummary(enhanced.fixedLayout), }, }; diff --git a/public/core/verification/ocr-readback.js b/public/core/verification/ocr-readback.js index 78f77c9..01e2104 100644 --- a/public/core/verification/ocr-readback.js +++ b/public/core/verification/ocr-readback.js @@ -129,10 +129,24 @@ export async function runOcrReadbackLayer({ : DEFAULT_OCR_READBACK_THRESHOLD; const language = normalizeOCRLanguage(ctx?.options?.ocr?.language); - let recognized; + let recognizedText = ""; + let pageCount = 0; + const confidences = []; try { - const raster = await rasterizer.rasterize({ content: output?.data, pageIndex: 0 }); - recognized = await resolvedEngine.recognize({ image: raster.dataUrl, options: { language } }); + pageCount = await rasterizer.countPages({ content: output?.data }); + const maxPages = Number.isInteger(ctx?.options?.verification?.maxReadbackPages) + ? ctx.options.verification.maxReadbackPages : 20; + if (!Number.isInteger(pageCount) || pageCount < 1) return skip("output-page-count-unavailable"); + if (pageCount > maxPages) return skip(`output-pages-exceed-readback-limit:${pageCount}/${maxPages}`); + const pageTexts = []; + for (let pageIndex = 0; pageIndex < pageCount; pageIndex += 1) { + if (ctx?.options?.signal?.aborted) return skip("cancelled"); + const raster = await rasterizer.rasterize({ content: output?.data, pageIndex }); + const recognized = await resolvedEngine.recognize({ image: raster.dataUrl, options: { language } }); + pageTexts.push(recognizedTextOf(recognized)); + if (typeof recognized?.averageConfidence === "number") confidences.push(recognized.averageConfidence); + } + recognizedText = pageTexts.join("\n"); } catch (error) { const cause = error?.code || error?.message || "unknown"; if (cause === "OCR_RASTERIZER_UNAVAILABLE") { @@ -141,9 +155,12 @@ export async function runOcrReadbackLayer({ return skip(`readback-failed:${cause}`, [ createWarning("info", OCR_READBACK_FAILED, `OCR 回读失败:${cause}.`, { from: ctx?.from, to: ctx?.to, cause }), ]); + } finally { + if (typeof rasterizer.dispose === "function") { + try { await rasterizer.dispose(); } catch { /* preserve readback result */ } + } } - const recognizedText = recognizedTextOf(recognized); const similarity = compareText(originalText, recognizedText); const passed = similarity.f1 >= threshold; const ocrReadback = { @@ -155,8 +172,10 @@ export async function runOcrReadbackLayer({ engineId: resolvedEngine.id, originalLength: similarity.originalLength, recognizedLength: similarity.recognizedLength, - averageConfidence: typeof recognized?.averageConfidence === "number" ? recognized.averageConfidence : null, - pageIndex: 0, + averageConfidence: confidences.length > 0 + ? confidences.reduce((sum, confidence) => sum + confidence, 0) / confidences.length : null, + pageCount, + checkedPages: pageCount, }; const warnings = passed ? [] diff --git a/public/formats/docx.js b/public/formats/docx.js index 7e44e26..57da5b8 100644 --- a/public/formats/docx.js +++ b/public/formats/docx.js @@ -133,8 +133,8 @@ function parseTable(xml) { const columnWidths = [...gridXml.matchAll(/]*\/?\s*>/g)] .map((match) => Number(getAttr(match[0], "w:w"))) .filter((width) => Number.isFinite(width) && width > 0); - // 嵌套表文本经 extractText 平铺进外层单元格;压缩连续换行/空格为单空格防止单元格内 - // 换行破坏 md 表格,但保留 \t(issue #92——表格单元格内含制表符的真实文档存在) + // Keep paragraph boundaries and significant spaces inside cells. Flattening + // adjacent elements without separators joins distinct form fields. const parsedRows = scanBalanced(xml, "w:tr") .map((rowXml) => scanBalanced(rowXml, "w:tc").map((cellXml) => { const gridSpan = cellXml.match(/]*\/?\s*>/)?.[0] || ""; @@ -143,8 +143,11 @@ function parseTable(xml) { const verticalMerge = mergeTag ? (getAttr(mergeTag, "w:val") === "restart" ? "restart" : "continue") : ""; + const paragraphs = scanBalanced(cellXml, "w:p"); return { - text: extractText(cellXml).replace(/[ \n\r]+/g, " ").trim(), + text: paragraphs.length > 0 + ? paragraphs.map((paragraph) => extractText(paragraph)).join("\n") + : extractText(cellXml), columnSpan: Number.isSafeInteger(spanValue) && spanValue > 1 ? spanValue : 1, verticalMerge, }; @@ -352,8 +355,9 @@ function extractRunInlines(xml) { function parseParagraph(xml, relationships, assetStore, zip, warnings, references = {}) { const style = getAttr(xml.match(/]*\/?>/)?.[0] || "", "w:val"); const inlines = extractInlinesFromParagraph(xml, relationships); - // issue #92:preserve tab,只压缩连续换行/空格为单空格 - const text = inlinesToPlainText(inlines).replace(/[ \n\r]+/g, " ").trim(); + // Keep the block text consistent with its inlines. Collapsing spaces here + // makes JSON/XML and fallback writers lose field spacing even when runs survive. + const text = inlinesToPlainText(inlines).replace(/\r\n?/g, "\n"); const imageIds = [...xml.matchAll(/]*r:embed="([^"]+)"/g)].map((match) => match[1]); const paragraphFormat = parseParagraphFormat(xml); const numPr = xml.match(//)?.[0] || ""; @@ -363,7 +367,7 @@ function parseParagraph(xml, relationships, assetStore, zip, warnings, reference } : null; const blocks = []; - if (text) { + if (text.trim()) { if (listMeta) { const list = createList([text], references.orderedNumIds?.has(listMeta.numId), [{ depth: listMeta.depth, diff --git a/public/formats/pdf-output-high-fidelity.js b/public/formats/pdf-output-high-fidelity.js index c5749dc..5c1ef0b 100644 --- a/public/formats/pdf-output-high-fidelity.js +++ b/public/formats/pdf-output-high-fidelity.js @@ -1,12 +1,12 @@ -// 高保真 PDF 输出:直接消费 FixedLayoutModel,保留原始坐标、字体、尺寸。 +// 固定布局 PDF 输出:直接消费 FixedLayoutModel,保留文本起点和可用的宽度信息。 // 与 pdf-output.js 的程序化输出不同,这里不做重新排版,而是按 textRun.bbox 精确 -// 定位每个文本片段,保留原始视觉布局。 +// 定位每个文本片段;字体会替换为 STSong-Light,图像等元素仍可能丢失。 // // 适用场景:PDF → PDF round-trip、OFD → PDF 高保真转换。 // issue #105/#106/#107/#108/#111: 统一 CID 字体、annotations 大小写、降级/字替 warning、rotation。 import { bytesToDataUrl, textToBytes } from "../core/binary-utils.js"; -import { utf16BeHex, pdfUnicodeString, buildCidFontObjects, buildToUnicodeCMap, sanitizeGb1Text } from "./pdf-cid-font.js"; +import { utf16BeHex, pdfUnicodeString, buildCidFontObjects, buildToUnicodeCMap, charWidthFactor, sanitizeGb1Text } from "./pdf-cid-font.js"; import { createWarning } from "../core/warnings.js"; function escapePdfText(value) { @@ -26,7 +26,7 @@ function buildHighFidelityPdfBytes(fixedLayout, title) { // issue #106: 检查未渲染元素 for (const page of pages) { - if (page.images && page.images.length > 0) { + if ((page.images && page.images.length > 0) || (page.assets && page.assets.length > 0)) { warnings.push(createWarning("lossy", "PDF_HF_IMAGES_DROPPED", "High-fidelity PDF output does not embed images; they were omitted.")); break; } @@ -90,8 +90,17 @@ function buildHighFidelityPdfBytes(fixedLayout, title) { const fontSize = run.fontSize || 12; const x = run.bbox.x || 0; const y = run.bbox.y || 0; + // 替换字体的字宽与来源 PDF 不同;按来源 bbox 宽度缩放整段文字, + // 防止相邻英文表单字段在写出时逐段向右漂移。 + const nominalWidth = [...sanitized].reduce((width, char) => + width + fontSize * charWidthFactor(char.codePointAt(0)), 0); + const sourceWidth = Number(run.bbox.w); + const horizontalScale = nominalWidth > 0 && Number.isFinite(sourceWidth) && sourceWidth > 0 + ? Math.max(1, Math.min(1000, sourceWidth / nominalWidth * 100)) + : 100; contentLines.push(`/F1 ${fontSize} Tf`); + contentLines.push(`${horizontalScale.toFixed(3)} Tz`); contentLines.push(`1 0 0 1 ${x.toFixed(2)} ${y.toFixed(2)} Tm`); contentLines.push(`<${utf16BeHex(sanitized)}> Tj`); } @@ -165,6 +174,14 @@ export function writePdfHighFidelity({ model, title = model.title }) { } const { bytes, warnings } = buildHighFidelityPdfBytes(model.fixedLayout, title); + if ((model.metadata?.pdf?.pagesWithoutText || []).length > 0) { + warnings.push(createWarning( + "lossy", + "PDF_HF_PAGE_VISUALS_UNVERIFIED", + "Textless source pages may contain images or graphics that fixed-layout PDF output cannot reproduce; check the original PDF.", + { pages: model.metadata.pdf.pagesWithoutText }, + )); + } return { type: "binary", format: "pdf", diff --git a/public/formats/pdf-output.js b/public/formats/pdf-output.js index 9998441..ab0dd52 100644 --- a/public/formats/pdf-output.js +++ b/public/formats/pdf-output.js @@ -59,12 +59,42 @@ function charAdvance(char, fontSize) { // 把一组 inline segments wrap 成多行,每行仍是 segments 数组并附带宽度。 // segment 形态: { text, style, href? },style: { bold, italic, code, link, strike } -function wrapSegments(segments, fontSize, maxWidth, stats) { +function wrapSegments(segments, fontSize, maxWidth, stats, { + continuationWidth = maxWidth, + firstIndent = 0, + continuationIndent = firstIndent, + tabStops = [], +} = {}) { const lines = []; let currentLine = []; let currentWidth = 0; + const lineLimit = () => lines.length === 0 ? maxWidth : continuationWidth; + const lineIndent = () => lines.length === 0 ? firstIndent : continuationIndent; - function pushSegment(text, style, href) { + function nextTabStop(position) { + const explicit = tabStops.find((stop) => stop.position > position + 0.1); + return explicit ?? { position: (Math.floor(position / 36) + 1) * 36, alignment: "left" }; + } + + function measureFollowingField(segmentIndex, firstChars, startIndex) { + let width = 0; + let beforeDecimal = null; + for (let index = segmentIndex; index < segments.length; index += 1) { + const chars = index === segmentIndex + ? firstChars.slice(startIndex) + : [...sanitizeGb1Text(segments[index].text).text]; + for (const char of chars) { + if (char === "\t" || char === "\n") { + return { width, beforeDecimal: beforeDecimal ?? width }; + } + if ((char === "." || char === ",") && beforeDecimal === null) beforeDecimal = width; + width += charAdvance(char, fontSize); + } + } + return { width, beforeDecimal: beforeDecimal ?? width }; + } + + function pushSegment(text, style, href, segmentIndex) { if (!text) return; // issue #105/#107: 字符降级为 Adobe-GB1 覆盖内字符 const { text: sanitized, dropped } = sanitizeGb1Text(text); @@ -75,7 +105,9 @@ function wrapSegments(segments, fontSize, maxWidth, stats) { } let buffer = ""; let bufferWidth = 0; - for (const char of sanitized) { + const chars = [...sanitized]; + for (let charIndex = 0; charIndex < chars.length; charIndex += 1) { + const char = chars[charIndex]; if (char === "\n") { if (buffer) { currentLine.push({ text: buffer, style, href, width: bufferWidth }); @@ -88,8 +120,36 @@ function wrapSegments(segments, fontSize, maxWidth, stats) { currentWidth = 0; continue; } + if (char === "\t") { + if (buffer) { + currentLine.push({ text: buffer, style, href, width: bufferWidth }); + currentWidth += bufferWidth; + buffer = ""; + bufferWidth = 0; + } + let position = lineIndent() + currentWidth; + let stop = nextTabStop(position); + if (stop.position - lineIndent() > lineLimit() && currentLine.length > 0) { + lines.push(currentLine); + currentLine = []; + currentWidth = 0; + position = lineIndent(); + stop = nextTabStop(position); + } + const field = measureFollowingField(segmentIndex, chars, charIndex + 1); + const alignment = stop.alignment || "left"; + const alignedStart = alignment === "right" ? stop.position - field.width + : alignment === "center" ? stop.position - field.width / 2 + : ["decimal", "num"].includes(alignment) ? stop.position - field.beforeDecimal + : stop.position; + const target = Math.max(position, alignedStart); + const gap = target - position; + currentLine.push({ text: "", width: gap, columnStart: target - lineIndent() }); + currentWidth += gap; + continue; + } const advance = charAdvance(char, fontSize); - if (currentWidth + bufferWidth + advance > maxWidth && (currentLine.length > 0 || buffer.length > 0)) { + if (currentWidth + bufferWidth + advance > lineLimit() && (currentLine.length > 0 || buffer.length > 0)) { if (buffer) { currentLine.push({ text: buffer, style, href, width: bufferWidth }); buffer = ""; @@ -108,8 +168,8 @@ function wrapSegments(segments, fontSize, maxWidth, stats) { } } - for (const segment of segments) { - pushSegment(segment.text, segment.style, segment.href); + for (const [index, segment] of segments.entries()) { + pushSegment(segment.text, segment.style, segment.href, index); } if (currentLine.length > 0) lines.push(currentLine); return lines; @@ -206,9 +266,16 @@ function blockLayout(block) { const indentLeft = Number(format.indentLeft) || 0; const firstLine = Number(format.firstLineIndent) || 0; const hanging = Number(format.hangingIndent) || 0; + const continuationIndent = Math.max(0, layout.indent + indentLeft / 20); return { ...layout, - indent: layout.indent + Math.max(0, indentLeft + firstLine - hanging) / 20, + indent: Math.max(0, continuationIndent + (firstLine - hanging) / 20), + continuationIndent, + rightIndent: Math.max(0, Number(format.indentRight) || 0) / 20, + tabStops: (Array.isArray(format.tabStops) ? format.tabStops : []) + .filter((tab) => Number.isFinite(tab?.position) && tab.position > 0 && tab.alignment !== "clear") + .map((tab) => ({ position: tab.position / 20, alignment: tab.alignment || "left" })) + .sort((a, b) => a.position - b.position), alignment: ["left", "center", "right", "justify"].includes(format.alignment) ? format.alignment : "left", marginTop: Math.max(0, Number(format.spacingBefore) || 0) / 20, marginBottom: Number.isFinite(Number(format.spacingAfter)) ? Math.max(0, Number(format.spacingAfter)) / 20 : layout.marginBottom, @@ -476,7 +543,9 @@ function buildPdfBytes(model, title, paperSize) { // 内部函数使用闭包访问 PAGE_WIDTH, PAGE_HEIGHT, CONTENT_WIDTH function blockToLinesLocal(block, stats) { const layout = blockLayout(block); - const maxWidth = CONTENT_WIDTH - layout.indent; + const continuationIndent = layout.continuationIndent ?? layout.indent; + const rightIndent = layout.rightIndent || 0; + const maxWidth = CONTENT_WIDTH - layout.indent - rightIndent; if (block.type === "code") { const text = String(block.code ?? ""); @@ -541,23 +610,21 @@ function buildPdfBytes(model, title, paperSize) { const cellLines = row.map((cell, cellIndex) => { const spanInfo = cellSpans[rowIndex]?.[cellIndex] || {}; const columnSpan = Number.isSafeInteger(spanInfo.columnSpan) && spanInfo.columnSpan > 0 ? spanInfo.columnSpan : 1; + const columnStart = columnWidths.slice(0, logicalColumn).reduce((sum, width) => sum + width, 0); const cellWidth = columnWidths.slice(logicalColumn, logicalColumn + columnSpan).reduce((sum, width) => sum + width, 0) || CONTENT_WIDTH / cols * columnSpan; logicalColumn += columnSpan; const inlines = getCellInlineTokens(cell); let segments = flattenInlinesToSegments(inlines); if (rowIndex === 0) segments = segments.map((segment) => ({ ...segment, style: { ...segment.style, bold: true } })); - return { lines: wrapSegments(segments, fontSize, Math.max(8, cellWidth - 8), stats), width: cellWidth }; + return { lines: wrapSegments(segments, fontSize, Math.max(8, cellWidth - 8), stats), columnStart }; }); const maxLines = Math.max(...cellLines.map((cell) => cell.lines.length), 1); for (let lineIdx = 0; lineIdx < maxLines; lineIdx += 1) { const mergedSegments = []; - cellLines.forEach((cell, colIdx) => { + cellLines.forEach((cell) => { const lineSegments = cell.lines[lineIdx] || []; - const usedWidth = lineSegments.reduce((sum, seg) => sum + seg.width, 0); - if (lineSegments.length > 0) mergedSegments.push(...lineSegments); - const pad = Math.max(0, cell.width - usedWidth); - if (colIdx < cellLines.length - 1) { - mergedSegments.push({ text: " ".repeat(Math.max(1, Math.floor(pad / (fontSize * 0.5)))), style: {}, href: "", width: pad }); + if (lineSegments.length > 0) { + mergedSegments.push({ ...lineSegments[0], columnStart: cell.columnStart + 4 }, ...lineSegments.slice(1)); } }); lines.push({ @@ -589,10 +656,16 @@ function buildPdfBytes(model, title, paperSize) { if (layout.forceBold) segments = segments.map((seg) => ({ ...seg, style: { ...(seg.style || {}), bold: true } })); if (layout.forceItalic) segments = segments.map((seg) => ({ ...seg, style: { ...(seg.style || {}), italic: true } })); segments = autoLinkifySegments(segments); - const wrapped = wrapSegments(segments, layout.fontSize, maxWidth, stats); + const wrapped = wrapSegments(segments, layout.fontSize, maxWidth, stats, { + continuationWidth: CONTENT_WIDTH - continuationIndent - rightIndent, + firstIndent: layout.indent, + continuationIndent, + tabStops: layout.tabStops, + }); return wrapped.map((lineSegments, idx) => ({ segments: lineSegments, - indent: layout.indent, + indent: idx === 0 ? layout.indent : continuationIndent, + rightIndent, fontSize: layout.fontSize, leading: layout.leading, marginAfter: idx === wrapped.length - 1 ? layout.marginBottom : 0, @@ -624,7 +697,7 @@ function buildPdfBytes(model, title, paperSize) { function renderLineLocal(line) { const ops = []; const annotations = []; - const contentWidth = CONTENT_WIDTH - (line.indent || 0); + const contentWidth = CONTENT_WIDTH - (line.indent || 0) - (line.rightIndent || 0); const lineWidth = line.segments.reduce((sum, seg) => sum + (seg.width != null ? seg.width : String(seg.text || "").length * line.fontSize * 0.5), 0); const alignOffset = line.alignment === "center" ? Math.max(0, (contentWidth - lineWidth) / 2) : line.alignment === "right" ? Math.max(0, contentWidth - lineWidth) @@ -632,6 +705,9 @@ function buildPdfBytes(model, title, paperSize) { let cursorX = marginLeft + (line.indent || 0) + alignOffset; for (const seg of line.segments) { + if (Number.isFinite(seg.columnStart)) { + cursorX = marginLeft + (line.indent || 0) + seg.columnStart; + } if (!seg.text) continue; const segWidth = seg.width != null ? seg.width : seg.text.length * line.fontSize * 0.5; const style = seg.style || {}; diff --git a/public/formats/pdf.js b/public/formats/pdf.js index cac4b8e..27c1fdb 100644 --- a/public/formats/pdf.js +++ b/public/formats/pdf.js @@ -1,15 +1,12 @@ -import { createDocumentModel, createHeading, createList, createParagraph, createRawBlock } from "../core/document-model.js"; +import { createDocumentModel, createHeading, createList, createParagraph } from "../core/document-model.js"; import { createFixedLayoutModel } from "../core/models/fixed-layout.js"; +import { bytesToDataUrl } from "../core/binary-utils.js"; +import { ConversionError } from "../core/conversion-error.js"; import { createWarning, withWarnings } from "../core/warnings.js"; -import { escapeHtml } from "./text-utils.js"; - -const PDF_FALLBACK_TEXT = "这是有效 PDF,但当前核心文本抽取器暂时无法读取其中的正文编码或压缩内容流。下方保留原 PDF 预览;如需转换为可编辑文本,请等待核心 OCR/Layout 增强或导入可复制文本的 PDF。"; -const PDF_ENCRYPTED_TEXT = "此 PDF 受密码保护(已加密),本地解析器无法在不输入密码的情况下提取正文。请先用 PDF 工具解除密码后重新导入;下方保留原 PDF 预览(浏览器查看器可能支持输入密码)。"; const PDFJS_PAYLOAD_START = "% Trans2Former PDFJS_TEXT_START"; const PDFJS_PAYLOAD_END = "% Trans2Former PDFJS_TEXT_END"; const MAX_INFLATED_STREAM_BYTES = 64 * 1024 * 1024; const MAX_INFLATED_TOTAL_BYTES = 128 * 1024 * 1024; -const MAX_EMBEDDED_PDF_BYTES = 4 * 1024 * 1024; function decodePdfString(value) { // PDF 32000-1 §7.3.4.2:单遍解码转义。链式 replace 是错的——\\ 后跟 n 会被 @@ -106,30 +103,6 @@ function coercePdfBytes(content) { return binaryStringToBytes(text); } -function binaryStringToBase64(value) { - const binary = String(value || ""); - if (typeof Buffer !== "undefined") { - return Buffer.from(binary, "latin1").toString("base64"); - } - if (typeof btoa === "function") { - return btoa(binary); - } - return ""; -} - -function toPdfDataUrl(content, source) { - const text = String(content ?? ""); - const dataUrlMatch = text.match(/^(data:application\/pdf;base64,[A-Za-z0-9+/=]+)/); - if (dataUrlMatch) { - return dataUrlMatch[1]; - } - return `data:application/pdf;base64,${binaryStringToBase64(source)}`; -} - -function escapeHtmlAttribute(value) { - return escapeHtml(value); -} - function printableRatio(text) { const value = String(text || ""); if (!value.length) return 0; @@ -407,6 +380,33 @@ function shouldSeparatePdfItems(previous, current) { return false; } +export function hasPdfJsExtractionPayload(content) { + return extractPdfJsPayload(coercePdfText(content))?.engine === "pdfjs"; +} + +export function copyOriginalPdf(content) { + let source = coercePdfText(content); + if (hasPdfJsExtractionPayload(source)) { + const marker = source.lastIndexOf(`\n${PDFJS_PAYLOAD_START}`); + if (marker >= 0) source = source.slice(0, marker); + } + const bytes = binaryStringToBytes(source); + if (bytes.length < 5 || String.fromCharCode(...bytes.subarray(0, 5)) !== "%PDF-") { + throw new ConversionError("输入不是可复制的 PDF 文件。", { + category: "parse", + code: "PDF_INVALID_SOURCE", + format: "pdf", + }); + } + return { + type: "binary", + format: "pdf", + data: bytesToDataUrl(bytes, "application/pdf"), + mime: "application/pdf", + warnings: [createWarning("info", "PDF_ORIGINAL_PRESERVED", "PDF bytes were preserved without rerendering; OCR text was not added as a searchable layer.")], + }; +} + function joinPdfItems(items, separator = " ") { let output = ""; let previous = null; @@ -436,7 +436,7 @@ async function loadPdfJs() { return await import("pdfjs-dist/legacy/build/pdf.mjs"); } -function getPdfJsAssetOptions() { +async function getPdfJsAssetOptions() { if (typeof window !== "undefined") { return { cMapUrl: "/vendor/pdfjs/cmaps/", @@ -444,10 +444,13 @@ function getPdfJsAssetOptions() { standardFontDataUrl: "/vendor/pdfjs/standard_fonts/", }; } + const { fileURLToPath } = await import("node:url"); + // PDF.js checks for a forward slash suffix before passing this native path to fs. + const nodeAssetPath = (relative) => fileURLToPath(new URL(relative, import.meta.url)).replaceAll("\\", "/"); return { - cMapUrl: new URL("../../node_modules/pdfjs-dist/cmaps/", import.meta.url).href, + cMapUrl: nodeAssetPath("../../node_modules/pdfjs-dist/cmaps/"), cMapPacked: true, - standardFontDataUrl: new URL("../../node_modules/pdfjs-dist/standard_fonts/", import.meta.url).href, + standardFontDataUrl: nodeAssetPath("../../node_modules/pdfjs-dist/standard_fonts/"), }; } @@ -462,7 +465,7 @@ async function extractTextWithPdfJs(content) { useSystemFonts: false, useWorkerFetch: false, verbosity: 0, - ...getPdfJsAssetOptions(), + ...await getPdfJsAssetOptions(), }); document = await loadingTask.promise; const pages = []; @@ -514,21 +517,25 @@ async function extractTextWithPdfJs(content) { pages.push({ pageNumber, blocks: pageBlocks, layout: layoutPage }); } else if (fallbackText) { pages.push({ pageNumber, text: fallbackText, layout: layoutPage }); + } else { + // Keep textless pages in the payload. A mixed text/scan PDF must not + // silently lose page numbers before the caller can report OCR gaps. + pages.push({ pageNumber, layout: layoutPage }); } page.cleanup(); } - await document.destroy(); return { pages, encrypted: false }; } catch (error) { if (typeof console !== "undefined" && console.warn) { console.warn("[trans2former] PDF.js extraction failed, falling back to core parser:", error?.message || error); } - if (document) { - try { await document.destroy(); } catch { /* ignore */ } - } // 加密 PDF 在 getDocument 阶段抛 PasswordException——单独标记, // 让上层给出准确文案而非误导的「扫描件/不可读」链路(issue #104)。 return { pages: [], encrypted: error?.name === "PasswordException" }; + } finally { + if (loadingTask) { + try { await loadingTask.destroy(); } catch { /* cleanup must not discard extracted pages */ } + } } } @@ -935,6 +942,7 @@ export function isLikelyEncryptedPdf(source) { } export async function expandPdfContentForTextExtraction(content) { + if (hasPdfJsExtractionPayload(content)) return content; const source = coercePdfText(content); // 字节输入不能走 String(content)——Uint8Array 会变成逗号十进制串,后续解析 // 全部喂垃圾(issue #103);字符串/dataURL 输入保持原值,字节级不变。 @@ -983,10 +991,11 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" // PDF.js + 版面分析路径:page.blocks 已经是结构化的 heading/list/paragraph if (pdfJsPayload && pdfJsPayload.pages?.some((page) => Array.isArray(page.blocks) && page.blocks.length > 0)) { const layoutBlocks = []; + const pageBlockCounts = []; let totalItems = 0; for (const page of pdfJsPayload.pages) { - if (!Array.isArray(page.blocks)) continue; - for (const block of page.blocks) { + const start = layoutBlocks.length; + for (const block of (Array.isArray(page.blocks) ? page.blocks : [])) { if (!block || typeof block !== "object") continue; if (block.type === "heading" && typeof block.text === "string") { const text = block.text.trim(); @@ -1016,13 +1025,30 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" } } } + if (layoutBlocks.length === start && String(page.text || "").trim()) { + layoutBlocks.push(createParagraph(String(page.text).trim())); + totalItems += 1; + } + pageBlockCounts.push(layoutBlocks.length - start); } if (layoutBlocks.length > 0) { + const pagesWithoutText = pdfJsPayload.pages + .filter((page, index) => pageBlockCounts[index] === 0) + .map((page) => page.pageNumber) + .filter((number) => Number.isSafeInteger(number) && number > 0); const warnings = [createWarning( "lossy", "PDF_LAYOUT_HEURISTIC", "PDF text was reconstructed from PDF.js coordinates with heuristic layout analysis (font-size for headings, y-gap for paragraphs, line-prefix for lists). Visual fidelity is not preserved." )]; + if (pagesWithoutText.length > 0) { + warnings.push(createWarning( + "lossy", + "PDF_PAGES_WITHOUT_TEXT", + `PDF pages ${pagesWithoutText.join(", ")} have no extractable text; they may be blank or require OCR.`, + { pages: pagesWithoutText }, + )); + } const model = createDocumentModel({ title, sourceFormat: format, @@ -1030,10 +1056,13 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" metadata: withWarnings({ pdf: { extraction: "pdfjs-layout", + textStatus: "extracted", engine: pdfJsPayload.engine || "pdfjs-layout", blockCount: layoutBlocks.length, textItemCount: totalItems, pageCount: pdfJsPayload.pages.length, + pagesWithoutText, + pageBlockCounts, fileName, }, }, warnings), @@ -1072,14 +1101,6 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" if (strings.length > 0) { blocks.push(createHeading(1, strings[0])); strings.slice(1).forEach((text) => blocks.push(createParagraph(text))); - } else { - blocks.push(createParagraph(encrypted ? PDF_ENCRYPTED_TEXT : PDF_FALLBACK_TEXT)); - const pdfDataUrl = toPdfDataUrl(content, source); - const embeddedBase64 = pdfDataUrl.slice("data:application/pdf;base64,".length); - const approxBytes = Math.floor(embeddedBase64.length * 3 / 4); - if (embeddedBase64.length > 0 && approxBytes <= MAX_EMBEDDED_PDF_BYTES) { - blocks.push(createRawBlock("html", `

当前浏览器未能内嵌显示 PDF。请使用下载输出查看原 PDF。

`)); - } } const warnings = [createWarning( "lossy", @@ -1104,7 +1125,7 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" } } - return createDocumentModel({ + const model = createDocumentModel({ title, sourceFormat: format, blocks, @@ -1115,10 +1136,11 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" : strings.length > 0 ? "literal-text-operators" : encrypted - ? "embedded-original-pdf-encrypted" + ? "no-text-encrypted" : fontGlyphIdNoise - ? "embedded-original-pdf-glyph-noise" - : "embedded-original-pdf", + ? "no-text-glyph-noise" + : "no-text", + textStatus: strings.length > 0 ? "extracted" : encrypted ? "encrypted" : "unavailable", engine: pdfJsPayload?.engine || "core-mvp", textItemCount: strings.length, pageCount: pdfJsPayload?.pages?.length || undefined, @@ -1127,4 +1149,7 @@ export function readPdf({ content, title = "pdf", fileName = "", format = "pdf" }, }, warnings), }); + const layoutPages = pdfJsPayload?.pages?.filter((page) => page?.layout).map((page) => page.layout) || []; + if (layoutPages.length > 0) model.fixedLayout = createFixedLayoutModel({ pages: layoutPages }); + return model; } diff --git a/public/index.html b/public/index.html index ab5a5a0..fe1daf7 100644 --- a/public/index.html +++ b/public/index.html @@ -232,7 +232,7 @@

Trans2Former


                 
               
-              
+              
diff --git a/public/styles.css b/public/styles.css index 9364e9f..cad8076 100644 --- a/public/styles.css +++ b/public/styles.css @@ -698,6 +698,10 @@ button:disabled { color: var(--accent-strong); } +.status-chip[data-type="warning"] { + color: var(--color-warning); +} + .status-chip[data-type="info"] { color: var(--muted-strong); } @@ -1419,6 +1423,24 @@ button:disabled { background: #f8fafc; } +.input-pdf-viewer { + margin-top: 12px; +} + +.input-pdf-controls { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 10px; +} + +.input-pdf-page { + display: block; + width: 100%; + height: auto; + background: #f8fafc; +} + .text-output-preview { display: block; margin: 0; @@ -1640,6 +1662,21 @@ button:disabled { color: #586172; } +.verification-badge[data-state="warning"] { + background: var(--color-warning-soft); + color: var(--color-warning-strong); +} + +.verification-warning-details { + margin: 8px 0 0; + padding-left: 20px; + color: var(--color-warning-strong); +} + +.verification-warning-details[hidden] { + display: none; +} + .verification-note { margin: 8px 0 6px; color: var(--muted, #6b7280); diff --git a/scripts/browser-smoke-test.js b/scripts/browser-smoke-test.js index 1c74153..640d11f 100644 --- a/scripts/browser-smoke-test.js +++ b/scripts/browser-smoke-test.js @@ -202,7 +202,9 @@ try { assert.equal(stylesCss.includes("align-items: stretch;"), true, "workspace grid should stretch the source and result panes to fill the available height"); assert.equal(stylesCss.includes("min-height: 620px;"), false, "result pane should not reserve a large empty preview area on short documents"); assert.equal(stylesCss.includes(".source-pane {\n align-self: stretch;"), true, "source pane should stretch to fill the workspace row after removing the bottom drawer"); - assert.equal(stylesCss.includes(".pdf-frame {\n display: none;\n width: 100%;\n height: 100%;"), true, "PDF result preview should fill the result panel instead of using the iframe default size"); + assert.equal(stylesCss.includes(".pdf-frame {\n display: none;\n width: 100%;\n height: 100%;"), true, "PDF result preview should fill the result panel"); + assert.equal(indexHtml.includes('
w.code === OCR_SCAN_PAGES_TRUNCATED); - assert.ok(clampWarning, `maxScanPages=${bogus}: truncation past the clamped default must still warn`); - assert.equal(clampWarning.details.processedPages, 5); + assert.equal(clampWarning, undefined, `maxScanPages=${bogus}: no pages should be truncated`); } } finally { defaultOCRRegistry.unregister(stubEngine.id); @@ -978,6 +978,102 @@ function makeStubEngine(overrides = {}) { } } +// 29c. Mixed PDF OCR handles only textless pages and retains page order. +{ + const pdf = writePdfHighFidelity({ + model: { + title: "mixed-text-scan", + fixedLayout: { + pages: [ + { size: { width: 612, height: 792 }, textRuns: [ + { text: "FIRST", bbox: { x: 100, y: 700, w: 100, h: 12 }, fontSize: 12 }, + ] }, + { size: { width: 612, height: 792 }, textRuns: [] }, + { size: { width: 612, height: 792 }, textRuns: [ + { text: "LAST", bbox: { x: 100, y: 700, w: 100, h: 12 }, fontSize: 12 }, + ] }, + ], + }, + }, + }); + const detection = await isScannedPdf(pdf.data); + assert.equal(detection.reason, "mixed-text-and-textless-pages"); + assert.deepEqual(detection.pageIndices, [1]); + const rasterizedPages = []; + setPdfPageRasterizer({ + async countPages() { return 3; }, + async rasterize({ pageIndex }) { + rasterizedPages.push(pageIndex); + return { dataUrl: "data:image/png;base64,YQ==", width: 100, height: 100 }; + }, + }); + const engine = { + id: "mixed-page-engine", + taskCapabilities: ["ocr-text"], + isAvailable: () => true, + recognize: async () => createOCRResult({ + pages: [{ pageIndex: 0, width: 100, height: 100, lines: [ + { text: "OCR MIDDLE", confidence: 0.9, bbox: { x: 10, y: 20, w: 40, h: 10 } }, + ] }], + fullText: "OCR MIDDLE", + averageConfidence: 0.9, + }), + }; + defaultOCRRegistry.register(engine); + try { + const output = await convertContentAsync({ + content: pdf.data, + from: "pdf", + to: "txt", + title: "mixed-text-scan", + options: { repair: false }, + }); + assert.deepEqual(rasterizedPages, [1], "existing text pages must not be OCR'ed again"); + assert.deepEqual(output.data.trim().split(/\n\s*\n/), ["FIRST", "OCR MIDDLE", "LAST"]); + const pdfOutput = await convertContentAsync({ + content: pdf.data, + from: "pdf", + to: "pdf", + title: "mixed-text-scan", + options: { repair: false }, + }); + assert.deepEqual(rasterizedPages, [1], "PDF identity copy must not run OCR or redraw pages"); + assert.equal(pdfOutput.data, pdf.data, "PDF to PDF should preserve the source bytes"); + assert.ok((pdfOutput.warnings || []).some((warning) => warning.code === "PDF_ORIGINAL_PRESERVED")); + const readBack = readPdf({ content: await expandPdfContentForTextExtraction(pdfOutput.data) }); + assert.equal(readBack.metadata.pdf.pageCount, 3); + assert.equal(readBack.blocks.some((block) => String(block.text || "").includes("OCR MIDDLE")), false); + const verifiedOutput = await convertContentAsync({ + content: pdf.data, + from: "pdf", + to: "txt", + title: "mixed-text-scan", + }); + assert.deepEqual(verifiedOutput.quality.qualityReport.unresolvedPdfPages, []); + const incompleteOutput = await convertContentAsync({ + content: pdf.data, + from: "pdf", + to: "txt", + title: "mixed-text-scan", + options: { ocr: { enabled: false } }, + }); + assert.deepEqual(incompleteOutput.quality.qualityReport.unresolvedPdfPages, [2]); + assert.ok(incompleteOutput.quality.warnings.some((warning) => warning.code === "PDF_PAGES_WITHOUT_TEXT")); + const bareOutput = await convertContentAsync({ + content: pdf.data, + from: "pdf", + to: "txt", + title: "mixed-text-scan", + options: { repair: false, ocr: { enabled: false } }, + }); + assert.deepEqual(bareOutput.unresolvedPdfPages, [2]); + assert.ok(bareOutput.warnings.some((warning) => warning.code === "PDF_PAGES_WITHOUT_TEXT")); + } finally { + defaultOCRRegistry.unregister(engine.id); + resetPdfPageRasterizer(); + } +} + // 30. convertContentAsync routes scanned PDF through OCR stage when stubs registered { const stubRasterizer = { diff --git a/scripts/pdf-reader-test.js b/scripts/pdf-reader-test.js index 298f955..f21a7ed 100644 --- a/scripts/pdf-reader-test.js +++ b/scripts/pdf-reader-test.js @@ -1,5 +1,7 @@ import assert from "node:assert/strict"; import { readPdf, expandPdfContentForTextExtraction } from "../public/formats/pdf.js"; +import { writePdfHighFidelity } from "../public/formats/pdf-output-high-fidelity.js"; +import { convertContent, convertContentAsync } from "../public/browser-transformer.js"; // 测试 PDF reader 的边界条件、错误处理和关键路径 // 覆盖审核报告 #168 指出的未覆盖场景 @@ -228,5 +230,49 @@ try { console.log(` ⚠️ 结构验证: ${err.message}`); } +// 测试 11: 混合文本页与无文字页时,保留页数并明确提示 OCR 缺口。 +console.log("\nTest 11: Mixed text and textless PDF pages"); +const mixedPdf = writePdfHighFidelity({ + model: { + title: "mixed-pages", + fixedLayout: { + pages: [ + { + size: { width: 612, height: 792 }, + textRuns: [{ text: "FIELD", bbox: { x: 100, y: 700, w: 120, h: 12 }, fontSize: 12 }], + }, + { size: { width: 612, height: 792 }, textRuns: [] }, + ], + }, + }, +}); +const mixedExpanded = await expandPdfContentForTextExtraction(mixedPdf.data); +const mixedModel = readPdf({ content: mixedExpanded, title: "mixed-pages" }); +assert.equal(mixedModel.metadata.pdf.pageCount, 2); +assert.deepEqual(mixedModel.metadata.pdf.pagesWithoutText, [2]); +assert.equal(mixedModel.fixedLayout.pages.length, 2); +assert.ok(mixedModel.metadata.warnings.some((warning) => warning.code === "PDF_PAGES_WITHOUT_TEXT")); +console.log(" ✅ 无文字页保留在布局中,并产生可见 warning"); + +// 测试 12: 同格式 PDF 不重新绘制,原字节在同步、异步及预提取入口一致。 +console.log("\nTest 12: PDF identity copy"); +const originalData = mixedPdf.data; +const expectedBytes = Buffer.from(originalData.split(",")[1], "base64"); +for (const output of [ + convertContent({ content: originalData, from: "pdf", to: "pdf", options: { repair: false } }), + convertContent({ content: mixedExpanded, from: "pdf", to: "pdf", options: { repair: false } }), + await convertContentAsync({ content: new Uint8Array(expectedBytes), from: "pdf", to: "pdf", options: { repair: false } }), +]) { + assert.deepEqual(Buffer.from(output.data.split(",")[1], "base64"), expectedBytes); + assert.ok(output.warnings.some((warning) => warning.code === "PDF_ORIGINAL_PRESERVED")); +} +const blankPdf = writePdfHighFidelity({ + model: { title: "blank", fixedLayout: { pages: [{ size: { width: 612, height: 792 }, textRuns: [] }] } }, +}); +const blankCopy = await convertContentAsync({ content: blankPdf.data, from: "pdf", to: "pdf" }); +assert.equal(blankCopy.data, blankPdf.data, "a textless PDF must still be copyable without rerendering"); +assert.deepEqual(blankCopy.quality.qualityReport.unresolvedPdfPages, []); +console.log(" ✅ PDF 同格式转换保留原始字节"); + console.log("\n✅ PDF reader test passed: critical paths and edge cases verified."); -console.log("✅ Covers: empty PDF, corrupted streams, multi-page, metadata, large streams, byte input, boundaries, error handling."); +console.log("✅ Covers: empty PDF, corrupted streams, multi-page, metadata, large streams, byte input, boundaries, error handling, textless pages, identity copy."); diff --git a/scripts/release-user-path-e2e-test.js b/scripts/release-user-path-e2e-test.js index 09da491..b8a127c 100644 --- a/scripts/release-user-path-e2e-test.js +++ b/scripts/release-user-path-e2e-test.js @@ -111,9 +111,7 @@ const markdown = `# Release Matrix\n\n${marker}\n\n| Name | Score |\n| --- | --- const csv = `Name,Score\n${marker},10\n`; const browser = await puppeteer.launch({ headless: "new", - ...(process.env.CI && process.platform === "linux" - ? { args: ["--no-sandbox", "--disable-setuid-sandbox"] } - : {}), + args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"], }); const { server, port } = await startWebServer(await findPort()); @@ -179,5 +177,11 @@ try { } finally { await browser.close(); await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); - await rm(tempDirectory, { recursive: true, force: true }); + const resolvedTemp = path.resolve(os.tmpdir()); + const resolvedFixture = path.resolve(tempDirectory); + if (!resolvedFixture.startsWith(`${resolvedTemp}${path.sep}`) + || !path.basename(resolvedFixture).startsWith("trans2former-release-e2e-")) { + throw new Error("Refusing to remove a fixture outside the dedicated temporary directory."); + } + await rm(resolvedFixture, { recursive: true, force: true }); } diff --git a/scripts/smoke-test.js b/scripts/smoke-test.js index 4beaa87..a1aba74 100644 --- a/scripts/smoke-test.js +++ b/scripts/smoke-test.js @@ -531,14 +531,14 @@ endobj const model = toDocumentModel(noisyPdf, "pdf", "binary-noise.pdf"); assert.equal(validateDocumentModel(model).ok, true); assert.equal(model.blocks.some((block) => String(block.text || "").includes("Ó3□FC")), false); - assert.equal(model.blocks[0].type, "paragraph"); - assert.match(model.blocks[0].text, /这是有效 PDF/); - assert.equal(model.blocks.some((block) => block.type === "raw" && block.format === "html" && block.content.includes("application/pdf")), true); + assert.equal(model.blocks.length, 0, "missing PDF text must not become a placeholder paragraph"); + assert.equal(model.metadata.pdf.textStatus, "unavailable"); assert.equal(model.metadata.warnings.some((warning) => warning.code === "PDF_NO_CREDIBLE_TEXT"), true); - const html = convertContent({ content: noisyPdf, from: "pdf", to: "html", title: "binary-noise.pdf" }); - assert.equal(html.data.includes('type="application/pdf"'), true); - assert.equal(html.data.includes("Ó3□FC"), false); + assert.throws( + () => convertContent({ content: noisyPdf, from: "pdf", to: "html", title: "binary-noise.pdf" }), + (error) => error.code === "PDF_TEXT_UNAVAILABLE", + ); }); test("PDF reader rejects font Glyph ID noise as text", () => { @@ -565,7 +565,7 @@ endobj ); } assert.equal(model.metadata.warnings.some((warning) => warning.code === "PDF_FONT_GLYPH_ID_NOISE"), true); - assert.equal(model.metadata.pdf.extraction, "embedded-original-pdf-glyph-noise"); + assert.equal(model.metadata.pdf.extraction, "no-text-glyph-noise"); }); test("PDF reader consumes pdfjs-layout payload with structured blocks", () => { @@ -784,7 +784,9 @@ test("issue #106 high-fidelity PDF reports omitted images, signatures, and subst assert.equal(warningCodes.has("PDF_HF_IMAGES_DROPPED"), true); assert.equal(warningCodes.has("PDF_HF_SIGNATURES_DROPPED"), true); assert.equal(warningCodes.has("PDF_HF_FONT_SUBSTITUTED"), true); - assert.match(new TextDecoder().decode(dataUrlToBytes(output.data)), /\/URI \(https:\/\/example\.com\)/); + const pdfText = new TextDecoder().decode(dataUrlToBytes(output.data)); + assert.match(pdfText, /\/URI \(https:\/\/example\.com\)/); + assert.match(pdfText, /125\.000 Tz/, "substituted font must use the source text-run width"); }); test("P8-M4 high-fidelity PDF output preserves FixedLayoutModel coordinates", () => { @@ -826,8 +828,8 @@ test("P8-M4 high-fidelity PDF output preserves FixedLayoutModel coordinates", () assert.equal(model.fixedLayout.pages[0].annotations.length, 1); assert.equal(model.fixedLayout.pages[0].rotation, 90); - // 转换为 PDF,应该使用高保真路径 - const output = convertContent({ content: fakePdfWithLayout, from: "pdf", to: "pdf", title: "high-fidelity.pdf" }); + // Writer 单独消费 FixedLayoutModel;完整的 PDF→PDF 路由会直接复制原文件。 + const output = writePdfBinary({ model, title: "high-fidelity.pdf" }); assertValidOutput(output, "pdf", "pdf high-fidelity round-trip"); const bytes = dataUrlToBytes(output.data); assert.equal(new TextDecoder().decode(bytes.slice(0, 5)), "%PDF-"); diff --git a/scripts/ui-conversion-e2e-test.js b/scripts/ui-conversion-e2e-test.js index 8e486ac..9ba8635 100644 --- a/scripts/ui-conversion-e2e-test.js +++ b/scripts/ui-conversion-e2e-test.js @@ -5,6 +5,7 @@ import path from "node:path"; import puppeteer from "puppeteer"; import { startWebServer } from "../src/web-server.js"; +import { writePdfHighFidelity } from "../public/formats/pdf-output-high-fidelity.js"; const PORT_START = 49233; const PORT_END = 49313; @@ -32,9 +33,7 @@ const { server, port } = await startWebServer(await findPort()); const baseUrl = `http://127.0.0.1:${port}`; const browser = await puppeteer.launch({ headless: "new", - ...(process.env.CI && process.platform === "linux" - ? { args: ["--no-sandbox", "--disable-setuid-sandbox"] } - : {}), + args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"], }); try { @@ -128,6 +127,64 @@ try { assert.equal(uploadResult.downloadHref.startsWith("blob:"), true, "uploaded-file download link should point to a Blob URL"); assert.equal(uploadResult.downloadName, "chinese.html", "uploaded-file download filename should use the source base name and target extension"); assert.equal(uploadResult.errorPanelHidden, true, "UI error panel should remain hidden after uploaded-file conversion"); + + const mixedPdf = writePdfHighFidelity({ + model: { + title: "mixed-ui", + fixedLayout: { pages: [ + { size: { width: 612, height: 792 }, textRuns: [ + { text: "FIRST", bbox: { x: 100, y: 700, w: 100, h: 12 }, fontSize: 12 }, + ] }, + { size: { width: 612, height: 792 }, textRuns: [] }, + ] }, + }, + }); + await page.evaluate((base64) => { + const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)); + const file = new File([bytes], "mixed-ui.pdf", { type: "application/pdf" }); + const transfer = new DataTransfer(); + transfer.items.add(file); + const input = document.getElementById("fileInput"); + input.files = transfer.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + }, mixedPdf.data.split(",")[1]); + await page.waitForFunction(() => document.getElementById("fromFormatSelect")?.value === "pdf", { timeout: 10000 }); + await page.select("#toFormatSelect", "txt"); + await page.click("#transformButton"); + await page.waitForFunction( + () => document.getElementById("downloadOutputButton")?.getAttribute("download") === "mixed-ui.txt", + { timeout: 15000 }, + ); + const pdfResult = await page.evaluate(() => ({ + status: document.getElementById("statusText")?.textContent || "", + statusType: document.getElementById("statusText")?.dataset.type, + warningRow: document.getElementById("verificationWarnings")?.textContent || "", + warningDetails: document.getElementById("verificationWarningDetails")?.textContent || "", + output: document.getElementById("textOutputPreview")?.textContent || "", + })); + assert.equal(pdfResult.statusType, "warning", "unresolved PDF pages must not show an unconditional success state"); + assert.match(pdfResult.status, /第 2 页/); + assert.match(pdfResult.warningRow, /第 2 页文字未确认/); + assert.match(pdfResult.warningDetails, /PDF_PAGES_WITHOUT_TEXT/); + assert.match(pdfResult.output, /FIRST/); + await page.select("#toFormatSelect", "pdf"); + await page.click("#transformButton"); + await page.waitForFunction( + () => document.querySelector("#pdfPreview img.input-pdf-page")?.getAttribute("src")?.startsWith("data:image/png"), + { timeout: 15000 }, + ); + assert.match(await page.$eval("#pdfPreview .input-pdf-controls span", (element) => element.textContent), /第 1 \/ 2 页/); + await page.$eval("#pdfPreview .input-pdf-controls button:nth-of-type(2)", (button) => button.click()); + await page.waitForFunction( + () => document.querySelector("#pdfPreview .input-pdf-controls span")?.textContent.includes("第 2 / 2 页"), + { timeout: 15000 }, + ); + const downloadedPdfBase64 = await page.evaluate(async () => { + const href = document.getElementById("downloadOutputButton").href; + const bytes = new Uint8Array(await (await fetch(href)).arrayBuffer()); + return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join("")); + }); + assert.equal(downloadedPdfBase64, mixedPdf.data.split(",")[1], "PDF to PDF download must preserve the source bytes"); assert.deepEqual(pageErrors, [], `UI should not emit page errors:\n${pageErrors.join("\n")}`); assert.deepEqual( consoleErrors.filter((entry) => !entry.includes("404 (Not Found)")), @@ -135,7 +192,7 @@ try { `UI should not emit console errors/warnings:\n${consoleErrors.join("\n")}`, ); - console.log("UI conversion E2E passed: sample Markdown converts through the real workbench path."); + console.log("UI conversion E2E passed: Markdown conversion, incomplete PDF warning, and paged PDF.js output preview verified."); } finally { await browser.close(); await new Promise((resolve, reject) => { diff --git a/tests/snapshots/conversions/empty-md-to-json.json b/tests/snapshots/conversions/empty-md-to-json.json index 3e9ebd6..1ff03c8 100644 --- a/tests/snapshots/conversions/empty-md-to-json.json +++ b/tests/snapshots/conversions/empty-md-to-json.json @@ -23,7 +23,7 @@ "structureFidelity": "high", "tableFidelity": "not-applicable", "assetFidelity": "not-applicable", - "textFidelity": "high", + "textFidelity": "unverified", "layoutFidelity": "not-applicable", "warningCount": 0, "warningsBySeverity": {}, From 6ead3b4df18b4145be60a3df4a5ad88b677cc5e5 Mon Sep 17 00:00:00 2001 From: Jack Yao Date: Thu, 24 Sep 2026 13:02:40 +0800 Subject: [PATCH 2/2] fix: preserve DOCX multi-section layouts and legacy hMerge spans MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 段落级 sectPr 解析为块级 sectionBreak.pageLayout,多节文档往返保留各节页面几何 - 暂不支持的节属性(分栏/页眉页脚引用等)发出 DOCX_SECTION_PROPS_PARTIAL 降级警告 - 旧式 hMerge restart+continue 折叠映射为 columnSpan,干净映射不再发近似警告 - OCR 读回新增多页门禁:全部页面逐页检验,后续页漏检必失败 - 同步 document-schema 运行时校验与 JSON Schema($defs/pageLayout、$defs/sectionBreak) Refs #216 --- CHANGELOG.md | 1 + docs/development/DEVELOPMENT_TASKS.md | 1 + docs/document-model.schema.json | 39 +++++++++- public/core/document-schema.js | 15 ++++ public/formats/docx-output.js | 38 +++++----- public/formats/docx.js | 92 ++++++++++++++++++++---- scripts/layout-offset-regression-test.js | 85 ++++++++++++++++++++++ scripts/ocr-readback-test.js | 66 ++++++++++++++++- 8 files changed, 303 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6628d59..62c8279 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ - **Issue #216 PDF 预览链路**:输入与输出 PDF 均改由本地 PDF.js 逐页渲染预览,取代被 Web/Tauri CSP(`object-src 'none'`)拦截的 `` 备用预览;生成文件的 Blob 下载入口独立保留。 - **Issue #216 版面保真补强**:PDF 表格字段按列坐标定位,不再用空格补齐列;DOCX 首行/续行缩进与制表位(含对齐方式)映射到 PDF 输出;固定布局替代字体按来源文本框宽度缩放;DOCX 单元格保留连续空格、制表符与段落边界。 - **Issue #216 质量报告诚实性**:未实际运行输出回读时 `textFidelity` 标为 `unverified`,不再由 warning 数量推断高保真;未确认页号进入 `qualityReport.unresolvedPdfPages` 并随输出返回。 +- **Issue #216 DOCX 多节页面设置与旧式横向合并保留**:段落级 `w:sectPr`(节结束标记)解析为 `paragraph` / `heading` 块的 `sectionBreak.pageLayout` 并在写出时还原,body 末尾节仍走 `metadata.ooxml.pageLayout`,多节文档往返后各节页面几何均保留;含分栏、页眉页脚引用、首页不同等暂不支持的节属性时发出 `DOCX_SECTION_PROPS_PARTIAL`。旧式 `w:hMerge`(restart + 连续 continue)映射为 `cellSpans` 的 `columnSpan`,能完整映射时不再发 `DOCX_TABLE_MERGE_APPROXIMATED`;与 `gridSpan` 混用或结构无法干净映射时仍发出该警告。新增多节往返、hMerge 往返与混用冲突回归测试。 ## [2.4.0] - 2026-07-17 diff --git a/docs/development/DEVELOPMENT_TASKS.md b/docs/development/DEVELOPMENT_TASKS.md index 8a3a3b7..a0362b5 100644 --- a/docs/development/DEVELOPMENT_TASKS.md +++ b/docs/development/DEVELOPMENT_TASKS.md @@ -89,6 +89,7 @@ > 仅保留最近 4 周内的记录;更早的归档到 [docs/archive/DEVELOPMENT_HISTORY.md](docs/archive/DEVELOPMENT_HISTORY.md),逐次发布的细节走 [CHANGELOG.md](CHANGELOG.md)。 +- **2026-09-24 (Issue #216 PDF 提取链可靠性、预览与质量诚实性)**:诊断发现 PDF.js 提取成功后被 `document.destroy()` 异常丢弃、Node CMap 传 `file:` URL 提取为空、无正文 PDF 把占位提示导出为正文、备用预览被 CSP `object-src 'none'` 拦截、稀疏英文表单误判为扫描件、质量报告未实测却标高保真。修复:提取后销毁 loading task 且清理失败不丢结果;Node 用原生文件路径加载 CMap/标准字体;无正文返回 `PDF_TEXT_UNAVAILABLE`/`PDF_ENCRYPTED`;`sparse-text-pdf` 标记避免重复 OCR;混合 PDF 仅对无文字页按页 OCR 并按原页号插回(坐标映射回 PDF 点位);PDF→PDF 经路由审计后复制原字节(`PDF_ORIGINAL_PRESERVED`);输入/输出 PDF 预览改本地 PDF.js 逐页渲染;PDF 表格按列坐标定位、DOCX 首行/续行缩进与制表位映射到 PDF;`textFidelity` 未实测标 `unverified`,未确认页号进 `unresolvedPdfPages`,工作台显示警告状态。同日续批:DOCX 多节页面设置经块级 `sectionBreak.pageLayout` 保留(尾部 sectPr 仍走 `metadata.ooxml.pageLayout`,暂不支持的节属性发 `DOCX_SECTION_PROPS_PARTIAL`);旧式 `hMerge` 映射为 `columnSpan`(完整映射不再发 `DOCX_TABLE_MERGE_APPROXIMATED`,混用 gridSpan 等仍警告);OCR 读回补多页门禁(后续页漏检必失败)。仍受限:嵌套表格展平+警告、w:cols 分栏与页眉页脚引用不保留、真实英文文档视觉回归基线待脱敏样例。 - **2026-09-24 (Issue #214 英文文本与表单布局回归)**:TXT 读写保留段内单换行、行首缩进和字段下划线,并将 Markdown 下划线语法识别限制为非单词边界;PDF 仅按真实水平坐标补英文片段空格,检测连续三行以上的双栏内容并按左栏后右栏输出;DOCX 保留页面几何、段落格式/自定义制表位、表格列宽和 `gridSpan` / `vMerge`,DOCX→PDF/HTML 投影保留可表达的页边距、对齐、缩进和列宽;QualityReport 增加 `layoutFidelity`,不可表达的布局发出 lossy warning。增加 `scripts/layout-offset-regression-test.js`,覆盖 TXT、英文 PDF 单栏/双栏、DOCX 表单 DOCX/PDF/HTML 往返。当前无用户脱敏原件,版面回归使用程序生成的合成文档;多节、多栏跨页、旧式 `hMerge`、浮动对象及完整字体主题仍会警告降级。 - **2026-05-30 (OCR 识别质量展示到检验报告 UI + modelReview 保留修复)**:把已计算但一直不可见的 OCR 识别质量呈现给用户。**修复潜伏 bug**:`format-registry.js` `_runRepairCycle` 用 Repair Engine 的 `modelReview`(`engine:"rule-based"`)覆盖了上游 OCR stage 写的 `modelReview`,导致 `ocr`/`ocrQuality` 子对象被丢弃、UI 取不到——改为合并保留 `priorReview.ocr` / `priorReview.ocrQuality`。`public/index.html` 检验报告面板加「OCR 识别质量」行(`#verificationOcrRecognitionRow`,默认 hidden,仅本次跑了 OCR 才显示)。`public/app.js` `renderVerificationReport` 读 `quality.modelReview.ocr` + `.ocrQuality` 渲染:引擎 / 行数 / 置信度 / 质量 grade / 低置信行 / 纠偏角 / 方向校正数 / 已去噪;grade 驱动 ok·skip·drift 配色。`scripts/browser-smoke-test.js` 断言 `#verificationOcrRecognition` 存在。`scripts/ocr-baseline-test.js` 加回归断言(`convertContentAsync` 默认 repair 路径下 `result.quality.modelReview.ocr` 必须存活)。`npm test` 28 个脚本全量通过。 diff --git a/docs/document-model.schema.json b/docs/document-model.schema.json index d47b1d3..dc46252 100644 --- a/docs/document-model.schema.json +++ b/docs/document-model.schema.json @@ -30,7 +30,8 @@ "warnings": { "$ref": "#/$defs/warnings" }, "level": { "type": "integer", "minimum": 1, "maximum": 6 }, "text": { "type": "string" }, - "paragraphFormat": { "$ref": "#/$defs/paragraphFormat" } + "paragraphFormat": { "$ref": "#/$defs/paragraphFormat" }, + "sectionBreak": { "$ref": "#/$defs/sectionBreak" } } }, { @@ -43,7 +44,8 @@ "sourceSpan": { "$ref": "#/$defs/sourceSpan" }, "warnings": { "$ref": "#/$defs/warnings" }, "text": { "type": "string" }, - "paragraphFormat": { "$ref": "#/$defs/paragraphFormat" } + "paragraphFormat": { "$ref": "#/$defs/paragraphFormat" }, + "sectionBreak": { "$ref": "#/$defs/sectionBreak" } } }, { @@ -228,7 +230,14 @@ "properties": { "warnings": { "$ref": "#/$defs/warnings" }, "conversion": { "type": "object" }, - "qualityReport": { "type": "object" } + "qualityReport": { "type": "object" }, + "ooxml": { + "type": "object", + "properties": { + "pageLayout": { "$ref": "#/$defs/pageLayout" } + }, + "additionalProperties": true + } }, "additionalProperties": true } @@ -261,6 +270,30 @@ } } }, + "pageLayout": { + "type": "object", + "additionalProperties": false, + "properties": { + "width": { "type": "integer", "minimum": 1 }, + "height": { "type": "integer", "minimum": 1 }, + "orientation": { "enum": ["portrait", "landscape"] }, + "marginLeft": { "type": "integer", "minimum": 0 }, + "marginRight": { "type": "integer", "minimum": 0 }, + "marginTop": { "type": "integer", "minimum": 0 }, + "marginBottom": { "type": "integer", "minimum": 0 }, + "headerDistance": { "type": "integer", "minimum": 0 }, + "footerDistance": { "type": "integer", "minimum": 0 }, + "gutter": { "type": "integer", "minimum": 0 } + } + }, + "sectionBreak": { + "type": "object", + "additionalProperties": false, + "required": ["pageLayout"], + "properties": { + "pageLayout": { "$ref": "#/$defs/pageLayout" } + } + }, "sourceSpan": { "type": "object", "additionalProperties": false, diff --git a/public/core/document-schema.js b/public/core/document-schema.js index 7fff73f..90428fe 100644 --- a/public/core/document-schema.js +++ b/public/core/document-schema.js @@ -104,6 +104,21 @@ export function validateDocumentModel(model) { }); } } + if (["paragraph", "heading"].includes(block.type) && block.sectionBreak !== undefined) { + const sectionBreak = block.sectionBreak; + if (!isObject(sectionBreak) || !isObject(sectionBreak.pageLayout)) { + errors.push(`blocks[${index}].sectionBreak must be an object with a pageLayout object`); + } else { + const layout = sectionBreak.pageLayout; + for (const key of ["width", "height"]) { + if (layout[key] !== undefined && (!Number.isSafeInteger(layout[key]) || layout[key] <= 0)) errors.push(`blocks[${index}].sectionBreak.pageLayout.${key} must be a positive integer`); + } + for (const key of ["marginLeft", "marginRight", "marginTop", "marginBottom", "headerDistance", "footerDistance", "gutter"]) { + if (layout[key] !== undefined && (!Number.isSafeInteger(layout[key]) || layout[key] < 0)) errors.push(`blocks[${index}].sectionBreak.pageLayout.${key} must be a non-negative integer`); + } + if (layout.orientation !== undefined && !["portrait", "landscape"].includes(layout.orientation)) errors.push(`blocks[${index}].sectionBreak.pageLayout.orientation is invalid`); + } + } if (block.type === "list") { if (typeof block.ordered !== "boolean") errors.push(`blocks[${index}].ordered must be a boolean`); if (!Array.isArray(block.items) || block.items.some((item) => typeof item !== "string")) errors.push(`blocks[${index}].items must be string[]`); diff --git a/public/formats/docx-output.js b/public/formats/docx-output.js index 3eaf9ab..e33c5b9 100644 --- a/public/formats/docx-output.js +++ b/public/formats/docx-output.js @@ -143,17 +143,19 @@ function paragraphFormatProperties(format) { return `${tabProperties}${spacingProperties}${indentProperties}${alignmentProperties}`; } -function mergeParagraphProperties(base, format) { +// ECMA-376 中 sectPr 是 pPr 内靠后的子元素:节页面设置追加在段落属性末尾。 +function mergeParagraphProperties(base, format, sectionLayout) { const extra = paragraphFormatProperties(format); - if (!extra) return base || ""; + const sectionXml = sectionLayout ? sectionPropertiesXml(sectionLayout) : ""; + if (!extra && !sectionXml) return base || ""; const inner = String(base || "").replace(/^\s*]*>/, "").replace(/<\/w:pPr>\s*$/, ""); - return `${inner}${extra}`; + return `${inner}${extra}${sectionXml}`; } function paragraphBlock(block, hyperlinks, opts = {}) { return paragraphFromRuns(runsFromBlock(block, hyperlinks), { ...opts, - pPr: mergeParagraphProperties(opts.pPr, block.paragraphFormat), + pPr: mergeParagraphProperties(opts.pPr, block.paragraphFormat, block.sectionBreak?.pageLayout), }); } @@ -302,17 +304,8 @@ ${allRels} `; } -export function writeDocx({ model, title = model.title }) { - const warnings = []; - if (model.sourceFormat === "pdf") { - warnings.push(createWarning("lossy", "DOCX_PDF_LAYOUT_APPROXIMATED", "PDF coordinates and visual styling were converted to editable DOCX flow; exact page positions, fonts, and pagination are not preserved.")); - } - if (model.sourceFormat === "docx" || model.metadata?.ooxml?.pageLayout) { - warnings.push(createWarning("lossy", "DOCX_LAYOUT_PARTIAL", "Page geometry, paragraph alignment/indent/tabs, and supported table widths/merges are preserved; themes, exact fonts, borders, cell padding, floating objects, and pagination are regenerated or omitted.")); - } - const hyperlinks = createHyperlinkRegistry(); - const bodyXml = model.blocks.map((block) => blockToWordXml(block, hyperlinks)).join("\n"); - const pageLayout = model.metadata?.ooxml?.pageLayout || {}; +// 单个节的 sectPr 构造:body 末尾节与段落级 sectionBreak 共用同一份页面设置序列化。 +function sectionPropertiesXml(pageLayout = {}) { const dimension = (value, fallback) => Number.isSafeInteger(value) && value > 0 ? value : fallback; const margin = (value, fallback) => Number.isSafeInteger(value) && value >= 0 ? value : fallback; const pageWidth = dimension(pageLayout.width, 11906); @@ -326,11 +319,24 @@ export function writeDocx({ model, title = model.title }) { ["header", "headerDistance", 720], ["footer", "footerDistance", 720], ["gutter", "gutter", 0], ].map(([attribute, key, fallback]) => `w:${attribute}="${margin(pageLayout[key], fallback)}"`).join(" "); + return ``; +} + +export function writeDocx({ model, title = model.title }) { + const warnings = []; + if (model.sourceFormat === "pdf") { + warnings.push(createWarning("lossy", "DOCX_PDF_LAYOUT_APPROXIMATED", "PDF coordinates and visual styling were converted to editable DOCX flow; exact page positions, fonts, and pagination are not preserved.")); + } + if (model.sourceFormat === "docx" || model.metadata?.ooxml?.pageLayout) { + warnings.push(createWarning("lossy", "DOCX_LAYOUT_PARTIAL", "Page geometry, paragraph alignment/indent/tabs, and supported table widths/merges are preserved; themes, exact fonts, borders, cell padding, floating objects, and pagination are regenerated or omitted.")); + } + const hyperlinks = createHyperlinkRegistry(); + const bodyXml = model.blocks.map((block) => blockToWordXml(block, hyperlinks)).join("\n"); const documentXml = ` ${bodyXml} - + ${sectionPropertiesXml(model.metadata?.ooxml?.pageLayout || {})} `; const zipBytes = writeStoredZip([ diff --git a/public/formats/docx.js b/public/formats/docx.js index 57da5b8..cbfbdbc 100644 --- a/public/formats/docx.js +++ b/public/formats/docx.js @@ -126,7 +126,8 @@ function scanTopLevelBlocks(body) { } function parseTable(xml) { - // gridSpan / vMerge are represented in the model below; legacy hMerge is still lossy. + // gridSpan / vMerge 与旧式 hMerge(restart + 连续 continue)都映射进模型的 + // columnSpan / verticalMerge;hMerge 与 gridSpan 混用或结构无法干净映射时仍算近似。 const hasMergedCells = / 1; const gridXml = String(xml ?? "").match(/]*>([\s\S]*?)<\/w:tblGrid>/)?.[1] || ""; @@ -137,12 +138,17 @@ function parseTable(xml) { // adjacent elements without separators joins distinct form fields. const parsedRows = scanBalanced(xml, "w:tr") .map((rowXml) => scanBalanced(rowXml, "w:tc").map((cellXml) => { - const gridSpan = cellXml.match(/]*\/?\s*>/)?.[0] || ""; - const spanValue = Number(getAttr(gridSpan, "w:val")); + const gridSpanTag = cellXml.match(/]*\/?\s*>/)?.[0] || ""; + const spanValue = Number(getAttr(gridSpanTag, "w:val")); const mergeTag = cellXml.match(/]*\/?\s*>/)?.[0] || ""; const verticalMerge = mergeTag ? (getAttr(mergeTag, "w:val") === "restart" ? "restart" : "continue") : ""; + // 旧式 hMerge:缺省 w:val 视为 continue(ECMA-376) + const hMergeTag = cellXml.match(/]*\/?\s*>/)?.[0] || ""; + const horizontalMerge = hMergeTag + ? (getAttr(hMergeTag, "w:val") === "restart" ? "restart" : "continue") + : ""; const paragraphs = scanBalanced(cellXml, "w:p"); return { text: paragraphs.length > 0 @@ -150,13 +156,38 @@ function parseTable(xml) { : extractText(cellXml), columnSpan: Number.isSafeInteger(spanValue) && spanValue > 1 ? spanValue : 1, verticalMerge, + horizontalMerge, + hasGridSpan: gridSpanTag !== "", }; })) .filter((row) => row.length > 0); - const rows = parsedRows + // hMerge 折叠:restart 格吸收后续连续 continue 格为 columnSpan,continue 格不占模型列 + // (与 gridSpan 的逻辑列推进一致);continue 无 restart 起始或与 gridSpan 同格混用时不折叠。 + let hasHMergeCells = false; + let hasGridSpanCells = false; + let mergeMapsCleanly = true; + const foldedRows = parsedRows.map((row) => { + const cells = []; + let mergeHead = null; + for (const cell of row) { + hasHMergeCells = hasHMergeCells || cell.horizontalMerge !== ""; + hasGridSpanCells = hasGridSpanCells || cell.hasGridSpan; + if (cell.horizontalMerge === "continue" && mergeHead) { + mergeHead.columnSpan += 1; + continue; + } + // 到达这里的 hMerge 格未被折叠:孤儿 continue,或 restart 与 gridSpan 同格混用 + if (cell.horizontalMerge === "continue") mergeMapsCleanly = false; + if (cell.horizontalMerge === "restart" && cell.hasGridSpan) mergeMapsCleanly = false; + mergeHead = cell.horizontalMerge === "restart" && !cell.hasGridSpan ? cell : null; + cells.push(cell); + } + return cells; + }); + const rows = foldedRows .map((row) => row.map((cell) => cell.text)) .filter((row) => row.length > 0); - const cellSpans = parsedRows.map((row) => row.map(({ columnSpan, verticalMerge }) => ({ + const cellSpans = foldedRows.map((row) => row.map(({ columnSpan, verticalMerge }) => ({ columnSpan, ...(verticalMerge ? { verticalMerge } : {}), }))); @@ -168,7 +199,10 @@ function parseTable(xml) { if (table && cellSpans.some((row) => row.some((cell) => cell.columnSpan > 1 || cell.verticalMerge))) { table.cellSpans = cellSpans; } - return { table, hasMergedCells, hasNestedTable }; + // 能完整映射的 hMerge 不再发近似警告;混用 gridSpan、结构不干净或 hMerge 藏在嵌套表格仍发。 + const mergeApproximated = hasMergedCells + && (!hasHMergeCells || hasGridSpanCells || !mergeMapsCleanly); + return { table, hasNestedTable, mergeApproximated }; } function parseParagraphFormat(xml) { @@ -206,12 +240,20 @@ function parseParagraphFormat(xml) { return Object.keys(format).length > 0 ? format : null; } -function parsePageLayout(xml) { - const sections = [...String(xml ?? "").matchAll(//g)]; - const section = sections.at(-1)?.[0] || ""; - if (!section) return null; - const pageSize = section.match(/]*\/?\s*>/)?.[0] || ""; - const pageMargins = section.match(/]*\/?\s*>/)?.[0] || ""; +// sectPr 中暂不支持的属性(分栏、页眉页脚引用、首页不同、页码格式等); +// w:type 缺省即 nextPage(与 writer 行为一致),仅非默认值算丢失。 +const SECTION_PARTIAL_PROPS = /]*\/?\s*>/)?.[0] || "", "w:val") || "nextPage"; + return sectionType !== "nextPage"; +} + +// 单个 切片 → pageLayout;body 末尾节(parsePageLayout)与段落级节标记共用。 +function parseSectionLayout(section) { + const pageSize = String(section ?? "").match(/]*\/?\s*>/)?.[0] || ""; + const pageMargins = String(section ?? "").match(/]*\/?\s*>/)?.[0] || ""; const layout = {}; for (const [attribute, key] of [["w:w", "width"], ["w:h", "height"]]) { const value = getAttr(pageSize, attribute); @@ -226,6 +268,14 @@ function parsePageLayout(xml) { return Object.keys(layout).length > 0 ? layout : null; } +// 向后兼容:body 级页面设置仍取最后一节(body 末尾 sectPr),与单节行为一致。 +function parsePageLayout(xml) { + const sections = [...String(xml ?? "").matchAll(//g)]; + const section = sections.at(-1)?.[0] || ""; + if (!section) return null; + return parseSectionLayout(section); +} + // 从 styles.xml 解析每个 paragraph style 对应的 heading level(如果有)。 // 兼容 Word 中文模板:styleId 可能是 "1"/"af0"/"a3",w:name 可能是 "heading 1" 或 "标题 1"。 function parseHeadingStyleMap(xml) { @@ -360,6 +410,13 @@ function parseParagraph(xml, relationships, assetStore, zip, warnings, reference const text = inlinesToPlainText(inlines).replace(/\r\n?/g, "\n"); const imageIds = [...xml.matchAll(/]*r:embed="([^"]+)"/g)].map((match) => match[1]); const paragraphFormat = parseParagraphFormat(xml); + // 段落 pPr 内的 sectPr 表示"本节到此结束"(ECMA-376),解析为该块的 sectionBreak; + // body 末尾 sectPr 仍走 metadata.ooxml.pageLayout,两者语义不重叠。 + const sectionPrXml = xml.match(//)?.[0]?.match(//)?.[0] || ""; + const sectionLayout = sectionPrXml ? parseSectionLayout(sectionPrXml) : null; + if (sectionPrXml && hasPartialSectionProps(sectionPrXml)) { + warnings.push(createWarning("lossy", "DOCX_SECTION_PROPS_PARTIAL", "DOCX section properties such as columns, header/footer references, or non-default section types are not preserved; only page geometry is kept.")); + } const numPr = xml.match(//)?.[0] || ""; const listMeta = numPr ? { depth: Number(getAttr(numPr.match(/]*\/?>/)?.[0] || "", "w:val")) || 0, @@ -382,13 +439,20 @@ function parseParagraph(xml, relationships, assetStore, zip, warnings, reference const heading = createHeading(level, text); if (inlines.length > 0) heading.inlines = inlines; if (paragraphFormat) heading.paragraphFormat = paragraphFormat; + if (sectionLayout) heading.sectionBreak = { pageLayout: sectionLayout }; blocks.push(heading); } else { const paragraph = createParagraph(text); if (inlines.length > 0) paragraph.inlines = inlines; if (paragraphFormat) paragraph.paragraphFormat = paragraphFormat; + if (sectionLayout) paragraph.sectionBreak = { pageLayout: sectionLayout }; blocks.push(paragraph); } + } else if (sectionLayout) { + // 空段落仅承担节结束标记(Word 常见写法):保留为空段落载体,节页面设置不再被静默丢弃 + const carrier = createParagraph(""); + carrier.sectionBreak = { pageLayout: sectionLayout }; + blocks.push(carrier); } for (const id of [...xml.matchAll(/]*w:id="([^"]+)"/g)].map((match) => match[1])) { @@ -466,8 +530,8 @@ export function readDocx({ content, title = "document", fileName = "", format = for (const block of scanTopLevelBlocks(body)) { if (block.tag === "tbl") { - const { table, hasMergedCells, hasNestedTable } = parseTable(block.xml); - if (hasMergedCells) { + const { table, mergeApproximated, hasNestedTable } = parseTable(block.xml); + if (mergeApproximated) { warnings.push(createWarning("lossy", "DOCX_TABLE_MERGE_APPROXIMATED", "DOCX merged table cells were flattened into the DocumentModel table shape.")); } if (hasNestedTable) { diff --git a/scripts/layout-offset-regression-test.js b/scripts/layout-offset-regression-test.js index 537811f..ebf414f 100644 --- a/scripts/layout-offset-regression-test.js +++ b/scripts/layout-offset-regression-test.js @@ -8,6 +8,9 @@ import { writePdfBinary } from "../public/formats/pdf-output.js"; import { writeHtml } from "../public/formats/html.js"; import { createDocumentModel } from "../public/core/document-model.js"; import { ensureDocumentAudit } from "../public/core/document-audit.js"; +import { readZipEntries } from "../public/core/zip-container.js"; +import { writeStoredZip } from "../public/core/zip-writer.js"; +import { textToBytes } from "../public/core/binary-utils.js"; // TXT round-trip preserves ordinary underscores, indentation, and single line breaks. const sourceText = " field__id__legacy: A-102\r\nnext line\r\n\r\n second_field: ready\r"; @@ -120,4 +123,86 @@ const reflowedDocxQuality = ensureDocumentAudit({ }, { reader: "docx", writer: "pdf", targetFormat: "pdf" }); assert.equal(reflowedDocxQuality.metadata.qualityReport.layoutFidelity, "low"); +// Multi-section DOCX round-trip: a paragraph-level sectionBreak (portrait A4) and the +// trailing body sectPr (landscape) are both preserved, in document order. +const twoSectionModel = createDocumentModel({ + title: "Two sections", + sourceFormat: "docx", + blocks: [ + { + type: "paragraph", + text: "Portrait section", + sectionBreak: { + pageLayout: { + width: 11906, + height: 16838, + orientation: "portrait", + marginLeft: 1440, + marginRight: 1440, + marginTop: 1440, + marginBottom: 1440, + headerDistance: 720, + footerDistance: 720, + gutter: 0, + }, + }, + }, + { type: "paragraph", text: "Landscape section" }, + ], + metadata: { + ooxml: { + pageLayout: { + width: 16838, + height: 11906, + orientation: "landscape", + marginLeft: 900, + marginRight: 900, + marginTop: 720, + marginBottom: 720, + headerDistance: 720, + footerDistance: 720, + gutter: 0, + }, + }, + }, +}); +const twoSectionDocx = writeDocx({ model: twoSectionModel }); +const twoSectionBytes = new Uint8Array(Buffer.from(twoSectionDocx.data.split(",")[1], "base64")); +const twoSectionXml = readZipEntries(twoSectionBytes).getText("word/document.xml"); +assert.equal((twoSectionXml.match(/ block.sectionBreak); +assert.deepEqual(sectionBreakBlock.sectionBreak, twoSectionModel.blocks[0].sectionBreak); +assert.deepEqual(twoSectionRoundTrip.metadata.ooxml.pageLayout, twoSectionModel.metadata.ooxml.pageLayout); + +// Backward compatibility: a model without sectionBreak still emits exactly one trailing sectPr. +const singleSectionXml = readZipEntries(docxBytes).getText("word/document.xml"); +assert.equal((singleSectionXml.match(/ writeStoredZip([ + { + name: "word/document.xml", + data: textToBytes(` +${bodyXml}`), + }, +]); +const cleanHMerge = readDocx({ + content: docxWithBody(`MergedAB`), + title: "hmerge", +}); +const cleanHMergeTable = cleanHMerge.blocks.find((block) => block.type === "table"); +assert.deepEqual(cleanHMergeTable.headers, ["Merged"]); +assert.deepEqual(cleanHMergeTable.cellSpans, [[{ columnSpan: 2 }], [{ columnSpan: 1 }, { columnSpan: 1 }]]); +assert.equal((cleanHMerge.metadata.warnings || []).some((warning) => warning.code === "DOCX_TABLE_MERGE_APPROXIMATED"), false); + +// Mixing gridSpan and hMerge in one table cannot be mapped cleanly and still warns. +const mixedMerge = readDocx({ + content: docxWithBody(`GridLegacy`), + title: "mixed", +}); +assert.equal(mixedMerge.metadata.warnings.some((warning) => warning.code === "DOCX_TABLE_MERGE_APPROXIMATED"), true); + console.log("Layout offset regressions passed: TXT whitespace, PDF English spacing/columns, and DOCX form geometry."); diff --git a/scripts/ocr-readback-test.js b/scripts/ocr-readback-test.js index aeb0822..f5cb4dd 100644 --- a/scripts/ocr-readback-test.js +++ b/scripts/ocr-readback-test.js @@ -193,4 +193,68 @@ function model(blocks) { assert.equal(result.quality.qualityReport.ruleDiff.identical, true); } -console.log("OCR readback test passed: compareText (identical/subset/CJK/empty), normalizeText, extractModelText, readback layer gating/drift/unavailable/rasterizer-fail, async three-layer merge, end-to-end null-on-text covered."); +// 14. multi-page output: every page is rasterized and read back (no later-page skip) +{ + const rasterizedPages = []; + const pageTexts = ["Alpha page one", "Beta page two", "Gamma page three"]; + let recognizeCall = 0; + const multiPageRasterizer = { + async rasterize({ pageIndex }) { + rasterizedPages.push(pageIndex); + return { dataUrl: "data:image/png;base64,AAAA", width: 16, height: 16 }; + }, + async countPages() { return 3; }, + }; + const pagedEngine = { + id: "stub-ocr-paged", + taskCapabilities: ["ocr-text"], + isAvailable: () => true, + recognize: async () => ({ fullText: pageTexts[recognizeCall++], averageConfidence: 0.9, pages: [] }), + }; + const layer = await runOcrReadbackLayer({ + model: model(pageTexts.map((text) => ({ type: "paragraph", text }))), + output: { data: "" }, + ctx: { from: "md", to: "pdf", options: {} }, + engine: pagedEngine, + rasterizer: multiPageRasterizer, + }); + assert.equal(layer.eligible, true); + assert.deepEqual(rasterizedPages, [0, 1, 2]); + assert.equal(layer.ocrReadback.pageCount, 3); + assert.equal(layer.ocrReadback.checkedPages, 3); + assert.equal(layer.ocrReadback.passed, true); +} + +// 15. later-page miss gate: text absent from later pages must fail the check +{ + const pageTexts = ["Alpha page one", "", ""]; + let recognizeCall = 0; + const missEngine = { + id: "stub-ocr-miss", + taskCapabilities: ["ocr-text"], + isAvailable: () => true, + recognize: async () => ({ fullText: pageTexts[recognizeCall++], averageConfidence: 0.9, pages: [] }), + }; + const threePageRasterizer = { + async rasterize() { return { dataUrl: "data:image/png;base64,AAAA", width: 16, height: 16 }; }, + async countPages() { return 3; }, + }; + const layer = await runOcrReadbackLayer({ + model: model([ + { type: "paragraph", text: "Alpha page one" }, + { type: "paragraph", text: "Beta page two" }, + { type: "paragraph", text: "Gamma page three" }, + ]), + output: { data: "" }, + ctx: { from: "md", to: "pdf", options: {} }, + engine: missEngine, + rasterizer: threePageRasterizer, + }); + assert.equal(layer.eligible, true); + assert.equal(layer.ocrReadback.checkedPages, 3); + assert.ok(layer.ocrReadback.recall < 0.5, `recall ${layer.ocrReadback.recall} must expose missing later pages`); + assert.equal(layer.ocrReadback.passed, false); + assert.equal(layer.warnings[0].code, OCR_READBACK_DRIFT); +} + +console.log("OCR readback test passed: compareText (identical/subset/CJK/empty), normalizeText, extractModelText, readback layer gating/drift/unavailable/rasterizer-fail, multi-page full coverage and later-page miss gate, async three-layer merge, end-to-end null-on-text covered.");