Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
1 change: 1 addition & 0 deletions scripts/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
Expand Down
68 changes: 68 additions & 0 deletions src/viewer/selection/dehyphenate-copy.js
Original file line number Diff line number Diff line change
@@ -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 };
}
20 changes: 13 additions & 7 deletions src/viewer/selection/markdown-copy.js
Original file line number Diff line number Diff line change
@@ -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 = {}) {
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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+$/, '');
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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.
Expand Down
64 changes: 64 additions & 0 deletions tests/markdown-copy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
});
4 changes: 2 additions & 2 deletions tests/tagged-paragraph-copy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',()=>{
Expand Down
Loading