From 3dc0669846c5fb43f26332e24ae8b70bb0a2dec7 Mon Sep 17 00:00:00 2001 From: John Wooten <60260750+JFWooten4@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:44:32 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9E=20Repair=20discretionary=20hyphens?= =?UTF-8?q?=20in=20copied=20PDF=20text?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use a local English lexicon to repair flattened OCR and wrapped word fragments when paragraph reflow is enabled. Preserve recognized compounds, identifiers, URL tokens, and page or paragraph boundaries; cover Markdown and plain clipboard paths with regressions. Include the lexicon license in the extension build. Co-authored-by: ChatGPT 6.2 --- package.json | 1 + scripts/build.mjs | 1 + src/viewer/selection/dehyphenate-copy.js | 68 ++++++++++++++++++++++++ src/viewer/selection/markdown-copy.js | 20 ++++--- tests/markdown-copy.test.mjs | 64 ++++++++++++++++++++++ tests/tagged-paragraph-copy.test.mjs | 4 +- 6 files changed, 149 insertions(+), 9 deletions(-) create mode 100644 src/viewer/selection/dehyphenate-copy.js diff --git a/package.json b/package.json index 65a7522..e28ca21 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "test:recovery": "node --test tests/pdf-tab-recovery.test.mjs" }, "dependencies": { + "an-array-of-english-words": "2.0.0", "pdfjs-dist": "6.3.289", "qr": "0.7.0" }, diff --git a/scripts/build.mjs b/scripts/build.mjs index a00d423..f3aa3a0 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -52,6 +52,7 @@ await Promise.all([ sourcemap: false, }), writeFile(`${outdir}/manifest.json`, `${JSON.stringify(manifest, null, 2)}\n`), + cp("node_modules/an-array-of-english-words/license", `${outdir}/english-word-list-license.txt`), cp("node_modules/pdfjs-dist/build/pdf.worker.min.mjs", `${outdir}/pdf.worker.min.mjs`), cp("node_modules/pdfjs-dist/cmaps", `${outdir}/cmaps`, { recursive: true }), cp("node_modules/pdfjs-dist/standard_fonts", `${outdir}/standard_fonts`, { recursive: true }), diff --git a/src/viewer/selection/dehyphenate-copy.js b/src/viewer/selection/dehyphenate-copy.js new file mode 100644 index 0000000..0467348 --- /dev/null +++ b/src/viewer/selection/dehyphenate-copy.js @@ -0,0 +1,68 @@ +import englishWords from "an-array-of-english-words" with { type: "json" }; + +let dictionary; +// A real compound can also have a closed spelling. Preserve established +// prefix forms and any compound whose two components are both words. +const compoundPrefixes = new Set([ + "anti", "bi", "co", "counter", "de", "ex", "extra", "inter", "intra", + "mid", "multi", "non", "post", "pre", "pro", "re", "semi", "sub", "super", + "trans", "ultra", "un", "vice", +]); + +function isDiscretionary(left, right, hyphen) { + if (hyphen === "\u00ad") return true; + const first = left.toLowerCase(); + const last = right.toLowerCase(); + if (compoundPrefixes.has(first)) return false; + dictionary ??= new Set(englishWords); + return dictionary.has(first + last) && + (!dictionary.has(first) || !dictionary.has(last)); +} + +// Work on complete prose tokens, not URL paths, email addresses, citations, +// identifiers, or multi-hyphen compounds. OCR may already have flattened +// the original line wrap, so require lexical evidence before removing "-". +function repairInline(text) { + return text.replace(/\S+/gu, token => { + const match = token.match(/^([("'“‘\[]*)([A-Za-z]{2,})([-\u00ad])([a-z]{2,})([)"'”’\].,;:!?]*)$/u); + if (!match) return token; + const [, opening, left, hyphen, right, closing] = match; + return isDiscretionary(left, right, hyphen) + ? opening + left + right + closing : token; + }); +} + +export function repairCopiedRuns(runs) { + let changed = false; + const repaired = []; + for (const original of runs) { + const run = { ...original, text: repairInline(original.text || "") }; + if (run.text !== original.text && original.text) changed = true; + const previous = repaired.at(-1); + const sameBlock = previous && run.block != null && run.block === previous.block && + run.role === "P" && previous.role === "P"; + const separateBlock = previous && run.block != null && previous.block != null && + run.block !== previous.block; + if (previous && !run.newPage && !run.newParagraph && !separateBlock && + !previous.footnoteReference && !run.footnoteReference && + (run.wrapBefore || run.newLine)) { + const left = previous.text.match(/(?:^|\s|[("'“‘\[])([A-Za-z]{2,})([-\u00ad])\s*$/u); + const right = run.text.match(/^\s*([a-z]{2,})(?=$|[\s)"'”’\].,;:!?])/u); + if (left && right) { + const removeHyphen = isDiscretionary(left[1], right[1], left[2]); + // If the line geometry or semantic paragraph confirms continuity, + // join even genuine hyphenated compounds, retaining their hyphen. + if (removeHyphen || run.wrapBefore || sameBlock) { + previous.text = previous.text.trimEnd(); + if (removeHyphen) previous.text = previous.text.slice(0, -1); + run.text = run.text.trimStart(); + run.newLine = false; + run.spaceBefore = false; + changed = true; + } + } + } + repaired.push(run); + } + return { runs: repaired, changed }; +} diff --git a/src/viewer/selection/markdown-copy.js b/src/viewer/selection/markdown-copy.js index a3bc442..d6b298c 100644 --- a/src/viewer/selection/markdown-copy.js +++ b/src/viewer/selection/markdown-copy.js @@ -1,3 +1,5 @@ +import { repairCopiedRuns } from "./dehyphenate-copy.js"; + // PDF.js intentionally uses different fonts for selectable text and canvas // rendering. Read the original font metadata, not text-layer computed styles. export function fontTraits(font, textStyle = {}) { @@ -100,9 +102,12 @@ export function markPdfTextStyles(page, textContent, textDivs) { previousText.transform[5] - item.transform[5] > typicalHeight * 0.8 && previousText.transform[5] - item.transform[5] < typicalHeight * 3.5 && item.transform[4] - previousText.transform[4] < typicalHeight * 6 && - !span.dataset.markdownParagraphStart && !/[-\s]$/.test(previousText.str) && - !/^\s/.test(item.str); - if (hasPdfWordGap(textItems[index - 1], item) || wrappedLine) { + !span.dataset.markdownParagraphStart; + if (wrappedLine && /[-\u00ad]\s*$/u.test(previousText.str) && item.str.trim()) { + span.dataset.markdownWrapBefore = 'true'; + } + if (hasPdfWordGap(textItems[index - 1], item) || (wrappedLine && + !/[-\s\u00ad]$/u.test(previousText.str) && !/^\s/.test(item.str))) { span.dataset.markdownSpaceBefore = 'true'; } if (traits.bold) span.dataset.markdownBold = 'true'; @@ -191,7 +196,7 @@ export function markdownFromRuns(runs, { markdown = true, reflow = true } = {}) parts.push(markdown ? formatRun(current) : current.text); current = null; }; - for (const run of runs) { + for (const run of reflow ? repairCopiedRuns(runs).runs : runs) { if (!run.text) continue; if (markdown && run.footnoteReference) { if (current) current.text = current.text.replace(/\s+$/, ''); @@ -321,6 +326,7 @@ export function selectionToMarkdown(root, selection, doc = document, bold: span.dataset.markdownBold === 'true', italic: span.dataset.markdownItalic === 'true', spaceBefore: span.dataset.markdownSpaceBefore === 'true', + wrapBefore: span.dataset.markdownWrapBefore === 'true', page, pageNumber: Number(page.dataset?.page) || null, xRatio: Number(span.dataset.markdownXRatio), @@ -387,9 +393,9 @@ export function selectionToMarkdown(root, selection, doc = document, previous = run; return result; }); - // Without Markdown, only take over copy for semantic paragraphs. Otherwise - // preserve the browser's native plain-text behavior for untagged PDFs. - if (!markdown && !structuredParagraph) return null; + // Without Markdown, take over only for semantic paragraphs or an actual + // hyphenation repair. Otherwise preserve native plain-text copy. + if (!markdown && !structuredParagraph && !(reflow && repairCopiedRuns(runs).changed)) return null; if (!markdown || noteOnlySelection) return markdownFromRuns(runs, { markdown, reflow }); // Use the already-recovered footnote index text. In older OCR PDFs the // printed numeric label may be read as punctuation or omitted altogether. diff --git a/tests/markdown-copy.test.mjs b/tests/markdown-copy.test.mjs index 55a0560..b3e52b7 100644 --- a/tests/markdown-copy.test.mjs +++ b/tests/markdown-copy.test.mjs @@ -347,3 +347,67 @@ test("includes page 14 note 25 when OCR reads its raised marker as 2s", async () const plain = await copyPetitionSelection(14, 9, 10, { textPage, markdown: false }); assert.equal(plain, null); }); + + +test("repairs flattened OCR words without changing compounds, URLs, or citations", () => { + const source = "clearing cor-porations and the following securi-ties depositories; regu-lations, self-regulatory, book-entry, co-operate, re-sign, 17Ad-10, https://example.org/cor-porations"; + const expected = "clearing corporations and the following securities depositories; regulations, self-regulatory, book-entry, co-operate, re-sign, 17Ad-10, https://example.org/cor-porations"; + assert.equal(markdownFromRuns([{ text: source }]), expected); + assert.equal(markdownFromRuns([{ text: source }], { markdown: false }), expected); + assert.equal(markdownFromRuns([{ text: source }], { reflow: false }), source); +}); + +test("rejoins wrapped words and retains genuine compound hyphens", () => { + const runs = [ + { text: "clearing cor-" }, + { text: "porations and securi-", wrapBefore: true }, + { text: "ties in a self-", newLine: true }, + { text: "regulatory system", wrapBefore: true }, + ]; + assert.equal(markdownFromRuns(runs), "clearing corporations and securities in a self-regulatory system"); + assert.equal(markdownFromRuns(runs, { markdown: false }), "clearing corporations and securities in a self-regulatory system"); + assert.equal(markdownFromRuns([{ text: "cor-" }, { text: "porations", newPage: true, newLine: true }]), "cor-\n\nporations"); + assert.equal(markdownFromRuns([{ text: "securi-" }, { text: "ties", newParagraph: true, wrapBefore: true }]), "securi-\n\nties"); + assert.equal(markdownFromRuns([{ text: "cor\u00adporations", italic: true }]), "_corporations_"); + assert.equal(markdownFromRuns([{ text: "cor-", italic: true }, { text: "porations", italic: true, newLine: true }]), "_corporations_"); +}); + +test("marks geometric hyphen wraps only in the same column", () => { + const line = (str, x, y) => ({ str, width: str.length * 5, height: 10, + dir: "ltr", transform: [10, 0, 0, 10, x, y] }); + const items = [line("clearing cor-", 80, 200), line("porations", 80, 188)]; + const spans = items.map(() => ({ dataset: {} })); + markPdfTextStyles({}, { items, styles: {} }, spans); + assert.equal(spans[1].dataset.markdownWrapBefore, "true"); + assert.equal(spans[1].dataset.markdownSpaceBefore, undefined); + const other = items.map(() => ({ dataset: {} })); + markPdfTextStyles({}, { items: [items[0], line("porations", 280, 188)], styles: {} }, other); + assert.equal(other[1].dataset.markdownWrapBefore, undefined); +}); + +test("plain copy of flattened untagged OCR is intercepted only when reflow repairs text", () => { + const page = {}; + const layer = { closest: selector => selector === ".text-layer" ? layer : null }; + const node = { textContent: "clearing cor-porations and securi-ties", parentElement: layer }; + const span = { dataset: { markdownItem: "true" }, closest: () => page }; + const root = { contains: element => element === layer, querySelectorAll: () => [span] }; + const selection = { isCollapsed: false, rangeCount: 1, anchorNode: node, focusNode: node, + getRangeAt: () => ({ intersectsNode: () => true }) }; + const doc = { createTreeWalker: () => ({ nextNode() { + if (this.done) return false; + this.done = true; + this.currentNode = node; + return true; + } }) }; + const oldFilter = globalThis.NodeFilter; + globalThis.NodeFilter = { SHOW_TEXT: 4 }; + try { + assert.equal(selectionToMarkdown(root, selection, doc, { markdown: false }), "clearing corporations and securities"); + assert.equal(selectionToMarkdown(root, selection, doc, { markdown: false, reflow: false }), null); + node.textContent = "a book-entry security"; + assert.equal(selectionToMarkdown(root, selection, doc, { markdown: false }), null); + } finally { + if (oldFilter === undefined) delete globalThis.NodeFilter; + else globalThis.NodeFilter = oldFilter; + } +}); diff --git a/tests/tagged-paragraph-copy.test.mjs b/tests/tagged-paragraph-copy.test.mjs index e1b1c12..f408985 100644 --- a/tests/tagged-paragraph-copy.test.mjs +++ b/tests/tagged-paragraph-copy.test.mjs @@ -41,9 +41,9 @@ test('joins printed lines within tagged paragraphs but separates distinct paragr assert.equal(markdownFromRuns(runs,{reflow:false}),'The opening\nparagraph\nAnother one.'); }); -test('does not join untagged lines or guess at hyphenation',()=>{ +test('preserves ordinary untagged line breaks and ambiguous compound hyphens',()=>{ assert.equal(markdownFromRuns([{text:'first'},{text:'second',newLine:true}]),'first\nsecond'); - assert.equal(markdownFromRuns([{text:'co-',role:'P',block:'1'},{text:'operate',newLine:true,role:'P',block:'1'}]),'co- operate'); + assert.equal(markdownFromRuns([{text:'co-',role:'P',block:'1'},{text:'operate',newLine:true,role:'P',block:'1'}]),'co-operate'); }); test('preserves italic emphasis across soft printed line breaks',()=>{