pdf-skryba 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/first-party/reader.js +177 -58
- package/dist/first-party/reader.js.map +3 -3
- package/dist/first-party.js +1 -0
- package/dist/first-party.js.map +2 -2
- package/dist/index.js +177 -58
- package/dist/index.js.map +3 -3
- package/dist/index.min.js +4 -4
- package/dist/light.js +1 -0
- package/dist/light.js.map +2 -2
- package/dist/light.min.js +1 -1
- package/dist/types/extractor/font-weight.d.ts +1 -6
- package/dist/types/extractor/pdf-bands.d.ts +1 -0
- package/dist/types/extractor/pdf-font-objects.d.ts +2 -3
- package/dist/types/extractor/pdf-glyph-source.d.ts +1 -1
- package/dist/types/extractor/pdf-hidden-text.d.ts +0 -4
- package/dist/types/extractor/pdf-lines.d.ts +2 -0
- package/dist/types/extractor/pdf-objects/refusal.d.ts +1 -1
- package/dist/types/extractor/pdf-ops-ours.d.ts +1 -0
- package/dist/types/extractor/pdf-page-plan.d.ts +4 -0
- package/dist/types/extractor/pdf-reading-order.d.ts +7 -0
- package/dist/types/extractor/pdf-source.d.ts +2 -0
- package/package.json +1 -1
package/dist/first-party.js
CHANGED
|
@@ -62,6 +62,7 @@ var findSpaceInsertions = (blocks, respacing) => {
|
|
|
62
62
|
const token = findGluedToken(blocks, respacing);
|
|
63
63
|
if (token === void 0) return void 0;
|
|
64
64
|
const sourceKeys = respacing.sourceWords.map(conservationKey);
|
|
65
|
+
if (sourceKeys.some((key) => key.length === 0)) return void 0;
|
|
65
66
|
const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(""));
|
|
66
67
|
if (token.map((codePoint) => codePoint.key).join("") !== tokenKey || sourceKeys.join("") !== tokenKey)
|
|
67
68
|
return void 0;
|
package/dist/first-party.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/chunk.ts", "../src/lib/link-schemes.ts", "../src/pipeline/glued-word-repair.ts", "../src/pipeline/lost-text-repair.ts"],
|
|
4
|
-
"sourcesContent": ["/** Splits a list into consecutive groups of at most `size` items, in order. Each caller decides what a group is and\n * how large it may be; this module imports nothing. */\nexport function splitIntoChunks<T>(items: readonly T[], size: number): T[][] {\n const groups: T[][] = [];\n for (let start = 0; start < items.length; start += size) groups.push(items.slice(start, start + size));\n return groups;\n}\n", "/** The URI schemes an external link may keep when it is published: http, https and mailto. A link whose\n * target is not a web page or a mail address is not one a published page vouches for (`javascript:` runs a script,\n * `file:` points at the reader's own disk), so the words of any other scheme stay plain text. */\nexport const PUBLISHED_LINK_SCHEME_PATTERN = /^(?:https?|mailto):/i;\n", "/**\n * Proves where a glued page word should be split again, from the PDF's own reading, and hands the spaces back to the\n * caller as edits. The caller applies them and re-checks the page with `isGluedRepairNoWorse`.\n *\n * THE RULE. A page token is split only when its letters, as the conservation check normalises them, are exactly the\n * concatenation of the two or more consecutive source words the word reading proved. A space goes at each boundary the\n * source gives, and nothing else changes. Anything less certain is left alone and stays counted as glued.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the first of the next, the page may carry\n * non-letters (\u00AB IV.1.1)Vrsta \u00BB). They are split as the source words carry them: the first word's trailing characters,\n * then the next word's leading ones. When the page's characters there are not exactly those, the token is left alone\n * rather than guessed.\n *\n * Offsets are indices in the text the caller published, block by block, so the decision holds for any markup.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One code point of a published block: its text, its letters as the check normalises them, and where it ends in\n * that block's text. */\ninterface CodePoint {\n readonly text: string;\n readonly key: string;\n readonly end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole surrogate pair), so that `end` is a UTF-16 index usable\n * with `slice`. */\nconst CODE_POINT = /[\\s\\S]/gu;\n\nconst splitCodePoints = (text: string): CodePoint[] =>\n [...text.matchAll(CODE_POINT)].map((match) => ({\n text: match[0],\n key: conservationKey(match[0]),\n end: match.index + match[0].length,\n }));\n\n/** The block's words as the check splits them: runs of non-space code points holding at least one letter. The same\n * split as doc-ir's `wordKeysOf`, kept by code point so that offsets can be located. */\nconst splitWords = (codePoints: readonly CodePoint[]): CodePoint[][] => {\n const words: CodePoint[][] = [];\n let current: CodePoint[] = [];\n const closeWord = (): void => {\n if (conservationKey(current.map((codePoint) => codePoint.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const codePoint of codePoints) {\n if (/^\\s+$/u.test(codePoint.text)) closeWord();\n else current.push(codePoint);\n }\n closeWord();\n return words;\n};\n\n/** The leading or trailing characters of a source word that carry no letter. */\nconst readNonLetterEdge = (word: string, side: \"lead\" | \"trail\"): string => {\n const characters = [...word];\n const ordered = side === \"lead\" ? characters : [...characters].reverse();\n const edge: string[] = [];\n for (const character of ordered) {\n if (conservationKey(character).length > 0) break;\n edge.push(character);\n }\n return (side === \"lead\" ? edge : [...edge].reverse()).join(\"\");\n};\n\n/** A renderer may put a zero-width space before a superscript glued to a word. It carries nothing the source says:\n * it is passed over between the words, and the space goes before it. */\nconst removeZeroWidthSpaces = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** The page token a respacing points at, or `undefined` when the respacing is not one glued page word made of two or\n * more source words. */\nconst findGluedToken = (blocks: readonly string[], respacing: Respacing): CodePoint[] | undefined => {\n const pageWord = respacing.pageWords[0];\n if (\n respacing.kind !== \"glued\" ||\n respacing.pageWords.length !== 1 ||\n pageWord === undefined ||\n respacing.sourceWords.length < 2\n )\n return undefined;\n const text = blocks[pageWord.block];\n if (text === undefined) return undefined;\n return splitWords(splitCodePoints(text))[pageWord.word];\n};\n\n/** How many of the non-letter code points between two source words belong to the first word, or `undefined` when they\n * are not exactly the first word's trailing characters followed by the next word's leading ones. */\nconst countTrailingCodePoints = (between: readonly CodePoint[], trail: string, lead: string): number | undefined => {\n if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join(\"\")) !== trail + lead) return undefined;\n let taken = \"\";\n let takenCount = 0;\n while (taken.length < trail.length && takenCount < between.length) {\n taken += removeZeroWidthSpaces(between[takenCount++]!.text);\n }\n return taken === trail ? takenCount : undefined;\n};\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst findSpaceInsertions = (blocks: readonly string[], respacing: Respacing): number[] | undefined => {\n const token = findGluedToken(blocks, respacing);\n if (token === undefined) return undefined;\n const sourceKeys = respacing.sourceWords.map(conservationKey);\n const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(\"\"));\n // Code point by code point, the letters must add up to the token's own (NFKC can join across characters), and the\n // token must be exactly the source words.\n if (token.map((codePoint) => codePoint.key).join(\"\") !== tokenKey || sourceKeys.join(\"\") !== tokenKey)\n return undefined;\n\n const offsets: number[] = [];\n let position = 0;\n let letterCount = 0;\n for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {\n const boundary = letterCount + sourceKeys[sourceIndex]!.length;\n // The code point carrying the first word's last letter must end exactly at the boundary.\n while (position < token.length && letterCount + token[position]!.key.length <= boundary && letterCount < boundary)\n letterCount += token[position++]!.key.length;\n if (letterCount !== boundary) return undefined;\n // The non-letters up to the next word's first letter, split as the source says.\n let nextLetter = position;\n while (nextLetter < token.length && token[nextLetter]!.key.length === 0) nextLetter++;\n const takenCount = countTrailingCodePoints(\n token.slice(position, nextLetter),\n readNonLetterEdge(respacing.sourceWords[sourceIndex]!, \"trail\"),\n readNonLetterEdge(respacing.sourceWords[sourceIndex + 1]!, \"lead\"),\n );\n if (takenCount === undefined) return undefined;\n offsets.push(token[position + takenCount - 1]!.end);\n position += takenCount;\n }\n return offsets;\n};\n\n/** The spaces this check proves, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. It writes nothing: composing a page is the caller's job. */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((respacing) => respacing.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const takenOffsets = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const respacing of glued) {\n const block = respacing.pageWords[0]?.block;\n const offsets = findSpaceInsertions(page.blocks, respacing);\n if (\n offsets === undefined ||\n block === undefined ||\n offsets.some((offset) => takenOffsets.has(`${block}:${offset}`))\n )\n continue;\n for (const atChar of offsets) {\n takenOffsets.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** How many respacings of the verdict are splits: a source word published as several page words. */\nconst countSplitWords = (verdict: ConservationVerdict): number =>\n verdict.respacings.filter((respacing) => respacing.kind === \"split\").length;\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the edits and re-checks,\n * because it writes the page; the rule for keeping or undoing a repair stays here, so that no caller keeps a page\n * that lost a letter. A repair is kept whole or not at all. */\nexport const isGluedRepairNoWorse = (\n before: ConservationVerdict,\n after: ConservationVerdict,\n repaired: number,\n): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n countSplitWords(after) <= countSplitWords(before);\n", "/**\n * Decides where a passage the render lost goes back into the published page, as its own unit between the two adjacent\n * units that hold its source neighbours. It hands the caller the edit and the letters it puts back, or why it\n * abstains; applying the edit, re-checking the page and keeping or undoing the repair are the caller's.\n *\n * THE RULE. A lost passage is a run of consecutive source words neither reading of the conservation check found. Its\n * neighbours are the source words right before and right after it. It goes back only when:\n * - each neighbour is a word the page matched (not an alternate text, a list number or a re-spacing: those have no\n * single place in the page);\n * - the neighbour before is the last word of a paragraph or heading unit, the one after the first word of the next\n * unit, with nothing between the two;\n * - at the start or the end of the document, the one neighbour opens the page's first block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB: a loss inside a paragraph, a table cell or a list, or an\n * image between the two paragraphs. A paragraph cut in the wrong place reads as if nothing were wrong; a \u00AB N characters\n * are not published \u00BB notice does not.\n *\n * THE UNDO IS THE CALLER'S. This module hands back only what the re-check needs: for each passage placed, the edit\n * and the number of letters it puts back (`LostTextInsertion`); for each passage left out, why\n * (`LostTextAbstention`). A caller that wants an exact repair keeps it only when the lost letters drop by exactly the\n * letters handed back and nothing else of the page moves.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are read in content stream order. Measured on\n * 871 paragraphs cut from 45 renders: 426 put back with the page's letters exactly as before, 22 put back elsewhere,\n * where the content stream reads them; some of those read better than the render did, some worse (a second column read\n * line by line). Tried and not kept: also requiring the blocks on each side to follow the source's order. It caught 8\n * of the 22 and cost 17 exact repairs. Text back in the page is what search needs; a paragraph slightly out of place\n * is the lesser defect.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back: a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back, for the caller's accounting. */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Whether `later` sits strictly after `earlier` in the page's reading order (block, then word). */\nconst isAfterInPageOrder = (later: PageWordAt, earlier: PageWordAt): boolean =>\n later.block > earlier.block || (later.block === earlier.block && later.word > earlier.word);\n\n/** Where each lost passage goes, as an edit for the caller to apply, or why it goes nowhere.\n *\n * It reasons on the page's units (`PublishedPage.units`), never on markup. The reason of each abstention travels to the\n * caller, so that a reader of the result knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container`, the same\n * answer as for a page whose anchors sit where a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = wordCountByBlock.length - 1;\n const findUnitOfBlock = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const findAnchorUnit = (anchor: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const unitIndex = findUnitOfBlock(anchor.block);\n if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The loss must sit at the unit's edge: the anchor before is the unit's last word, the anchor after its first.\n const neighbourBlock = side === \"before\" ? anchor.block + 1 : anchor.block - 1;\n const isAtEdge = side === \"before\" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;\n if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return \"loss-inside-block\";\n return unitIndex;\n };\n\n /** The unit the passage goes after (`-1`: before the first unit), or why it goes nowhere. */\n const placePassage = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\" && !isAfterInPageOrder(after, before))\n return \"anchors-out-of-order\";\n const unitBefore = before === \"document-edge\" ? undefined : findAnchorUnit(before, \"before\");\n if (typeof unitBefore === \"string\") return unitBefore;\n const unitAfter = after === \"document-edge\" ? undefined : findAnchorUnit(after, \"after\");\n if (typeof unitAfter === \"string\") return unitAfter;\n // At the start of the document, the passage goes before the unit that opens the page's first block.\n if (unitBefore === undefined) {\n if (unitAfter === undefined || after === \"document-edge\" || after.block !== 0) return \"no-anchor\";\n return unitAfter - 1;\n }\n // At the end of the document, the passage goes after the unit that closes the page's last block.\n if (unitAfter === undefined) {\n if (before === \"document-edge\" || before.block !== lastBlock) return \"no-anchor\";\n return unitBefore;\n }\n if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return \"blocks-not-adjacent\";\n return unitBefore;\n };\n\n for (const passage of passages) {\n const placement = placePassage(passage);\n if (typeof placement === \"string\") {\n abstentions.push(placement);\n continue;\n }\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: placement, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey(word).length, 0),\n });\n }\n return { insertions, abstentions };\n}\n"],
|
|
5
|
-
"mappings": ";AAEO,SAAS,gBAAmB,OAAqB,MAAqB;AAC3E,QAAM,SAAgB,CAAC;AACvB,WAAS,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,KAAM,QAAO,KAAK,MAAM,MAAM,OAAO,QAAQ,IAAI,CAAC;AACrG,SAAO;AACT;;;ACHO,IAAM,gCAAgC;;;ACe7C,SAAS,uBAAoG;AAY7G,IAAM,aAAa;AAEnB,IAAM,kBAAkB,CAAC,SACvB,CAAC,GAAG,KAAK,SAAS,UAAU,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,EAC7C,MAAM,MAAM,CAAC;AAAA,EACb,KAAK,gBAAgB,MAAM,CAAC,CAAC;AAAA,EAC7B,KAAK,MAAM,QAAQ,MAAM,CAAC,EAAE;AAC9B,EAAE;AAIJ,IAAM,aAAa,CAAC,eAAoD;AACtE,QAAM,QAAuB,CAAC;AAC9B,MAAI,UAAuB,CAAC;AAC5B,QAAM,YAAY,MAAY;AAC5B,QAAI,gBAAgB,QAAQ,IAAI,CAAC,cAAc,UAAU,IAAI,EA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AY,EAAG,IAAI;AAAA,EAC5D;AACA,SAAO,UAAU,QAAQ,aAAa;AACxC;AAGA,IAAM,sBAAsB,CAAC,QAA2B,cAA+C;AACrG,QAAM,QAAQ,eAAe,QAAQ,SAAS;AAC9C,MAAI,UAAU,OAAW,QAAO;AAChC,QAAM,aAAa,UAAU,YAAY,IAAI,eAAe;
|
|
4
|
+
"sourcesContent": ["/** Splits a list into consecutive groups of at most `size` items, in order. Each caller decides what a group is and\n * how large it may be; this module imports nothing. */\nexport function splitIntoChunks<T>(items: readonly T[], size: number): T[][] {\n const groups: T[][] = [];\n for (let start = 0; start < items.length; start += size) groups.push(items.slice(start, start + size));\n return groups;\n}\n", "/** The URI schemes an external link may keep when it is published: http, https and mailto. A link whose\n * target is not a web page or a mail address is not one a published page vouches for (`javascript:` runs a script,\n * `file:` points at the reader's own disk), so the words of any other scheme stay plain text. */\nexport const PUBLISHED_LINK_SCHEME_PATTERN = /^(?:https?|mailto):/i;\n", "/**\n * Proves where a glued page word should be split again, from the PDF's own reading, and hands the spaces back to the\n * caller as edits. The caller applies them and re-checks the page with `isGluedRepairNoWorse`.\n *\n * THE RULE. A page token is split only when its letters, as the conservation check normalises them, are exactly the\n * concatenation of the two or more consecutive source words the word reading proved. A space goes at each boundary the\n * source gives, and nothing else changes. Anything less certain is left alone and stays counted as glued.\n *\n * WHERE PUNCTUATION GOES. Between the last letter of one source word and the first of the next, the page may carry\n * non-letters (\u00AB IV.1.1)Vrsta \u00BB). They are split as the source words carry them: the first word's trailing characters,\n * then the next word's leading ones. When the page's characters there are not exactly those, the token is left alone\n * rather than guessed.\n *\n * Offsets are indices in the text the caller published, block by block, so the decision holds for any markup.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport { conservationKey, type ConservationVerdict, type PageEdit, type PublishedPage, type Respacing } from \"doc-ir\";\n\n/** One code point of a published block: its text, its letters as the check normalises them, and where it ends in\n * that block's text. */\ninterface CodePoint {\n readonly text: string;\n readonly key: string;\n readonly end: number;\n}\n\n/** One code point (the `u` flag makes `[\\s\\S]` match a whole surrogate pair), so that `end` is a UTF-16 index usable\n * with `slice`. */\nconst CODE_POINT = /[\\s\\S]/gu;\n\nconst splitCodePoints = (text: string): CodePoint[] =>\n [...text.matchAll(CODE_POINT)].map((match) => ({\n text: match[0],\n key: conservationKey(match[0]),\n end: match.index + match[0].length,\n }));\n\n/** The block's words as the check splits them: runs of non-space code points holding at least one letter. The same\n * split as doc-ir's `wordKeysOf`, kept by code point so that offsets can be located. */\nconst splitWords = (codePoints: readonly CodePoint[]): CodePoint[][] => {\n const words: CodePoint[][] = [];\n let current: CodePoint[] = [];\n const closeWord = (): void => {\n if (conservationKey(current.map((codePoint) => codePoint.text).join(\"\")).length > 0) words.push(current);\n current = [];\n };\n for (const codePoint of codePoints) {\n if (/^\\s+$/u.test(codePoint.text)) closeWord();\n else current.push(codePoint);\n }\n closeWord();\n return words;\n};\n\n/** The leading or trailing characters of a source word that carry no letter. */\nconst readNonLetterEdge = (word: string, side: \"lead\" | \"trail\"): string => {\n const characters = [...word];\n const ordered = side === \"lead\" ? characters : [...characters].reverse();\n const edge: string[] = [];\n for (const character of ordered) {\n if (conservationKey(character).length > 0) break;\n edge.push(character);\n }\n return (side === \"lead\" ? edge : [...edge].reverse()).join(\"\");\n};\n\n/** A renderer may put a zero-width space before a superscript glued to a word. It carries nothing the source says:\n * it is passed over between the words, and the space goes before it. */\nconst removeZeroWidthSpaces = (text: string): string => text.replaceAll(\"\\u200B\", \"\");\n\n/** The page token a respacing points at, or `undefined` when the respacing is not one glued page word made of two or\n * more source words. */\nconst findGluedToken = (blocks: readonly string[], respacing: Respacing): CodePoint[] | undefined => {\n const pageWord = respacing.pageWords[0];\n if (\n respacing.kind !== \"glued\" ||\n respacing.pageWords.length !== 1 ||\n pageWord === undefined ||\n respacing.sourceWords.length < 2\n )\n return undefined;\n const text = blocks[pageWord.block];\n if (text === undefined) return undefined;\n return splitWords(splitCodePoints(text))[pageWord.word];\n};\n\n/** How many of the non-letter code points between two source words belong to the first word, or `undefined` when they\n * are not exactly the first word's trailing characters followed by the next word's leading ones. */\nconst countTrailingCodePoints = (between: readonly CodePoint[], trail: string, lead: string): number | undefined => {\n if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join(\"\")) !== trail + lead) return undefined;\n let taken = \"\";\n let takenCount = 0;\n while (taken.length < trail.length && takenCount < between.length) {\n taken += removeZeroWidthSpaces(between[takenCount++]!.text);\n }\n return taken === trail ? takenCount : undefined;\n};\n\n/** Where in its block one glued token takes its spaces (character indices), or `undefined` to leave it alone. */\nconst findSpaceInsertions = (blocks: readonly string[], respacing: Respacing): number[] | undefined => {\n const token = findGluedToken(blocks, respacing);\n if (token === undefined) return undefined;\n const sourceKeys = respacing.sourceWords.map(conservationKey);\n // A source word with no letter marks no boundary of its own: first, its boundary would fall before the token's first\n // code point (no character to put a space after); between two words, it would double the space of its neighbour's.\n if (sourceKeys.some((key) => key.length === 0)) return undefined;\n const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(\"\"));\n // Code point by code point, the letters must add up to the token's own (NFKC can join across characters), and the\n // token must be exactly the source words.\n if (token.map((codePoint) => codePoint.key).join(\"\") !== tokenKey || sourceKeys.join(\"\") !== tokenKey)\n return undefined;\n\n const offsets: number[] = [];\n let position = 0;\n let letterCount = 0;\n for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {\n const boundary = letterCount + sourceKeys[sourceIndex]!.length;\n // The code point carrying the first word's last letter must end exactly at the boundary.\n while (position < token.length && letterCount + token[position]!.key.length <= boundary && letterCount < boundary)\n letterCount += token[position++]!.key.length;\n if (letterCount !== boundary) return undefined;\n // The non-letters up to the next word's first letter, split as the source says.\n let nextLetter = position;\n while (nextLetter < token.length && token[nextLetter]!.key.length === 0) nextLetter++;\n const takenCount = countTrailingCodePoints(\n token.slice(position, nextLetter),\n readNonLetterEdge(respacing.sourceWords[sourceIndex]!, \"trail\"),\n readNonLetterEdge(respacing.sourceWords[sourceIndex + 1]!, \"lead\"),\n );\n if (takenCount === undefined) return undefined;\n offsets.push(token[position + takenCount - 1]!.end);\n position += takenCount;\n }\n return offsets;\n};\n\n/** The spaces this check proves, as edits for the caller to apply to its own page; `repaired` counts the glued tokens\n * that got all of theirs. It writes nothing: composing a page is the caller's job. */\nexport function gluedWordEdits(\n page: PublishedPage,\n respacings: readonly Respacing[],\n): { edits: PageEdit[]; repaired: number } {\n const glued = respacings.filter((respacing) => respacing.kind === \"glued\");\n if (glued.length === 0) return { edits: [], repaired: 0 };\n const takenOffsets = new Set<string>();\n const edits: PageEdit[] = [];\n let repaired = 0;\n for (const respacing of glued) {\n const block = respacing.pageWords[0]?.block;\n const offsets = findSpaceInsertions(page.blocks, respacing);\n if (\n offsets === undefined ||\n block === undefined ||\n offsets.some((offset) => takenOffsets.has(`${block}:${offset}`))\n )\n continue;\n for (const atChar of offsets) {\n takenOffsets.add(`${block}:${atChar}`);\n edits.push({ kind: \"insert-space\", block, atChar });\n }\n repaired += 1;\n }\n return { edits, repaired };\n}\n\n/** How many respacings of the verdict are splits: a source word published as several page words. */\nconst countSplitWords = (verdict: ConservationVerdict): number =>\n verdict.respacings.filter((respacing) => respacing.kind === \"split\").length;\n\n/** Whether the re-checked page is no worse than the original in any way. The caller applies the edits and re-checks,\n * because it writes the page; the rule for keeping or undoing a repair stays here, so that no caller keeps a page\n * that lost a letter. A repair is kept whole or not at all. */\nexport const isGluedRepairNoWorse = (\n before: ConservationVerdict,\n after: ConservationVerdict,\n repaired: number,\n): boolean =>\n after.lostLetters <= before.lostLetters &&\n (after.decision !== \"lost\" || before.decision === \"lost\") &&\n after.decision !== \"abstain\" &&\n after.gluedWords <= before.gluedWords - repaired &&\n after.unmatchedPageWords <= before.unmatchedPageWords &&\n countSplitWords(after) <= countSplitWords(before);\n", "/**\n * Decides where a passage the render lost goes back into the published page, as its own unit between the two adjacent\n * units that hold its source neighbours. It hands the caller the edit and the letters it puts back, or why it\n * abstains; applying the edit, re-checking the page and keeping or undoing the repair are the caller's.\n *\n * THE RULE. A lost passage is a run of consecutive source words neither reading of the conservation check found. Its\n * neighbours are the source words right before and right after it. It goes back only when:\n * - each neighbour is a word the page matched (not an alternate text, a list number or a re-spacing: those have no\n * single place in the page);\n * - the neighbour before is the last word of a paragraph or heading unit, the one after the first word of the next\n * unit, with nothing between the two;\n * - at the start or the end of the document, the one neighbour opens the page's first block, or closes its last one.\n * Anything else abstains by name and the page stays \u00AB lost \u00BB: a loss inside a paragraph, a table cell or a list, or an\n * image between the two paragraphs. A paragraph cut in the wrong place reads as if nothing were wrong; a \u00AB N characters\n * are not published \u00BB notice does not.\n *\n * THE UNDO IS THE CALLER'S. This module hands back only what the re-check needs: for each passage placed, the edit\n * and the number of letters it puts back (`LostTextInsertion`); for each passage left out, why\n * (`LostTextAbstention`). A caller that wants an exact repair keeps it only when the lost letters drop by exactly the\n * letters handed back and nothing else of the page moves.\n *\n * WHERE IT LANDS IS THE SOURCE'S ORDER, NOT THE RENDER'S. The neighbours are read in content stream order. Measured on\n * 871 paragraphs cut from 45 renders: 426 put back with the page's letters exactly as before, 22 put back elsewhere,\n * where the content stream reads them; some of those read better than the render did, some worse (a second column read\n * line by line). Tried and not kept: also requiring the blocks on each side to follow the source's order. It caught 8\n * of the 22 and cost 17 exact repairs. Text back in the page is what search needs; a paragraph slightly out of place\n * is the lesser defect.\n *\n * The page text is the client's: it stays in memory only, like the verdict it reads.\n */\n\nimport {\n conservationKey,\n wordKeysOf,\n type LostPassage,\n type PageEdit,\n type PageWordAt,\n type PublishedPage,\n} from \"doc-ir\";\n\n/** Why a lost passage was not put back: a closed list. */\nexport type LostTextAbstention =\n | \"no-anchor\"\n | \"anchor-unmatched\"\n | \"anchors-out-of-order\"\n | \"anchor-in-container\"\n | \"loss-inside-block\"\n | \"blocks-not-adjacent\";\n\n/** One passage placed: the edit the caller applies, and the letters it puts back, for the caller's accounting. */\nexport interface LostTextInsertion {\n edit: PageEdit;\n letters: number;\n}\n\n/** Whether `later` sits strictly after `earlier` in the page's reading order (block, then word). */\nconst isAfterInPageOrder = (later: PageWordAt, earlier: PageWordAt): boolean =>\n later.block > earlier.block || (later.block === earlier.block && later.word > earlier.word);\n\n/** Where each lost passage goes, as an edit for the caller to apply, or why it goes nowhere.\n *\n * It reasons on the page's units (`PublishedPage.units`), never on markup. The reason of each abstention travels to the\n * caller, so that a reader of the result knows why nothing was repaired.\n *\n * `units` absent (the caller cannot say what a unit is): every passage abstains with `anchor-in-container`, the same\n * answer as for a page whose anchors sit where a paragraph may not go.\n */\nexport function placeLostPassages(\n page: PublishedPage,\n passages: readonly LostPassage[],\n): { insertions: LostTextInsertion[]; abstentions: LostTextAbstention[] } {\n const insertions: LostTextInsertion[] = [];\n const abstentions: LostTextAbstention[] = [];\n if (passages.length === 0) return { insertions, abstentions };\n const units = page.units;\n const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);\n const lastBlock = wordCountByBlock.length - 1;\n const findUnitOfBlock = (block: number): number => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;\n\n /** The anchor's unit, or why it cannot anchor. */\n const findAnchorUnit = (anchor: PageWordAt, side: \"before\" | \"after\"): number | LostTextAbstention => {\n const unitIndex = findUnitOfBlock(anchor.block);\n if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return \"anchor-in-container\";\n // The loss must sit at the unit's edge: the anchor before is the unit's last word, the anchor after its first.\n const neighbourBlock = side === \"before\" ? anchor.block + 1 : anchor.block - 1;\n const isAtEdge = side === \"before\" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;\n if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return \"loss-inside-block\";\n return unitIndex;\n };\n\n /** The unit the passage goes after (`-1`: before the first unit), or why it goes nowhere. */\n const placePassage = (passage: LostPassage): number | LostTextAbstention => {\n const { before, after } = passage;\n if (before === \"unanchored\" || after === \"unanchored\") return \"anchor-unmatched\";\n if (before === \"document-edge\" && after === \"document-edge\") return \"no-anchor\";\n if (before !== \"document-edge\" && after !== \"document-edge\" && !isAfterInPageOrder(after, before))\n return \"anchors-out-of-order\";\n const unitBefore = before === \"document-edge\" ? undefined : findAnchorUnit(before, \"before\");\n if (typeof unitBefore === \"string\") return unitBefore;\n const unitAfter = after === \"document-edge\" ? undefined : findAnchorUnit(after, \"after\");\n if (typeof unitAfter === \"string\") return unitAfter;\n // At the start of the document, the passage goes before the unit that opens the page's first block.\n if (unitBefore === undefined) {\n if (unitAfter === undefined || after === \"document-edge\" || after.block !== 0) return \"no-anchor\";\n return unitAfter - 1;\n }\n // At the end of the document, the passage goes after the unit that closes the page's last block.\n if (unitAfter === undefined) {\n if (before === \"document-edge\" || before.block !== lastBlock) return \"no-anchor\";\n return unitBefore;\n }\n if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return \"blocks-not-adjacent\";\n return unitBefore;\n };\n\n for (const passage of passages) {\n const placement = placePassage(passage);\n if (typeof placement === \"string\") {\n abstentions.push(placement);\n continue;\n }\n insertions.push({\n edit: { kind: \"insert-unit-after\", unit: placement, text: passage.sourceWords.join(\" \") },\n letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey(word).length, 0),\n });\n }\n return { insertions, abstentions };\n}\n"],
|
|
5
|
+
"mappings": ";AAEO,SAAS,gBAAmB,OAAqB,MAAqB;AAC3E,QAAM,SAAgB,CAAC;AACvB,WAAS,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,KAAM,QAAO,KAAK,MAAM,MAAM,OAAO,QAAQ,IAAI,CAAC;AACrG,SAAO;AACT;;;ACHO,IAAM,gCAAgC;;;ACe7C,SAAS,uBAAoG;AAY7G,IAAM,aAAa;AAEnB,IAAM,kBAAkB,CAAC,SACvB,CAAC,GAAG,KAAK,SAAS,UAAU,CAAC,EAAE,IAAI,CAAC,WAAW;AAAA,EAC7C,MAAM,MAAM,CAAC;AAAA,EACb,KAAK,gBAAgB,MAAM,CA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OAAO,OAAO;AACvF,QAAI,OAAO,cAAc,SAAU,QAAO;AAE1C,QAAI,eAAe,QAAW;AAC5B,UAAI,cAAc,UAAa,UAAU,mBAAmB,MAAM,UAAU,EAAG,QAAO;AACtF,aAAO,YAAY;AAAA,IACrB;AAEA,QAAI,cAAc,QAAW;AAC3B,UAAI,WAAW,mBAAmB,OAAO,UAAU,UAAW,QAAO;AACrE,aAAO;AAAA,IACT;AACA,QAAI,cAAc,aAAa,KAAK,QAAQ,UAAU,GAAG,mBAAmB,KAAM,QAAO;AACzF,WAAO;AAAA,EACT;AAEA,aAAW,WAAW,UAAU;AAC9B,UAAM,YAAY,aAAa,OAAO;AACtC,QAAI,OAAO,cAAc,UAAU;AACjC,kBAAY,KAAK,SAAS;AAC1B;AAAA,IACF;AACA,eAAW,KAAK;AAAA,MACd,MAAM,EAAE,MAAM,qBAAqB,MAAM,WAAW,MAAM,QAAQ,YAAY,KAAK,GAAG,EAAE;AAAA,MACxF,SAAS,QAAQ,YAAY,OAAO,CAAC,aAAa,SAAS,cAAcA,iBAAgB,IAAI,EAAE,QAAQ,CAAC;AAAA,IAC1G,CAAC;AAAA,EACH;AACA,SAAO,EAAE,YAAY,YAAY;AACnC;",
|
|
6
6
|
"names": ["conservationKey"]
|
|
7
7
|
}
|
package/dist/index.js
CHANGED
|
@@ -1443,7 +1443,6 @@ var IS_BOUND_REFUSAL = {
|
|
|
1443
1443
|
"to-unicode": false,
|
|
1444
1444
|
"value-too-large": true,
|
|
1445
1445
|
"document-too-large": true,
|
|
1446
|
-
"glyphs-too-many": true,
|
|
1447
1446
|
"forms-too-many": true,
|
|
1448
1447
|
"font-tables-too-many": true,
|
|
1449
1448
|
"page-missing": false
|
|
@@ -7917,9 +7916,14 @@ function decodePathSubpaths(packed) {
|
|
|
7917
7916
|
return subpaths;
|
|
7918
7917
|
}
|
|
7919
7918
|
|
|
7919
|
+
// src/extractor/pdf-hidden-text.ts
|
|
7920
|
+
var MAX_FILTERED_GLYPHS = 1e5;
|
|
7921
|
+
var shouldDropModeHidden = (glyphs) => glyphs.some(
|
|
7922
|
+
(glyph) => glyph.hiddenReason === void 0 && glyph.isUnpainted === void 0 && !glyph.isSpace && glyph.text.trim() !== ""
|
|
7923
|
+
);
|
|
7924
|
+
|
|
7920
7925
|
// src/extractor/pdf-glyph-source.ts
|
|
7921
7926
|
var MAX_FORM_DEPTH = 8;
|
|
7922
|
-
var MAX_SHOWN_GLYPHS_PER_PAGE = 1e6;
|
|
7923
7927
|
var readName5 = (value) => value?.kind === "name" ? value.value : void 0;
|
|
7924
7928
|
var FALLBACK_FONT = /* @__PURE__ */ new Map([
|
|
7925
7929
|
["BaseFont", { kind: "name", value: "Helvetica" }],
|
|
@@ -7986,10 +7990,15 @@ function chargeFormCall(budget) {
|
|
|
7986
7990
|
var isHighSurrogate = (text) => text?.length === 1 && text.charCodeAt(0) >= 55296 && text.charCodeAt(0) <= 56319;
|
|
7987
7991
|
var isLowSurrogate = (text) => text?.length === 1 && text.charCodeAt(0) >= 56320 && text.charCodeAt(0) <= 57343;
|
|
7988
7992
|
function appendStringGlyphs(bytes, state, into, budget) {
|
|
7989
|
-
const
|
|
7993
|
+
const room = MAX_FILTERED_GLYPHS - budget.painted;
|
|
7994
|
+
const prefixLength = (Math.max(room, 0) + 2) * MAX_CODE_BYTES;
|
|
7995
|
+
const codes = state.codesOf(bytes.length > prefixLength ? bytes.subarray(0, prefixLength) : bytes);
|
|
7990
7996
|
for (const [index, code] of codes.entries()) {
|
|
7997
|
+
if (budget.painted >= MAX_FILTERED_GLYPHS) {
|
|
7998
|
+
budget.cut = true;
|
|
7999
|
+
return;
|
|
8000
|
+
}
|
|
7991
8001
|
budget.painted += 1;
|
|
7992
|
-
if (budget.painted > MAX_SHOWN_GLYPHS_PER_PAGE) throw new PdfObjectsRefusal("glyphs-too-many");
|
|
7993
8002
|
let unicode = state.text(code);
|
|
7994
8003
|
if (unicode === "") {
|
|
7995
8004
|
const ownHalf = state.declared(code);
|
|
@@ -8006,6 +8015,7 @@ function appendStringGlyphs(bytes, state, into, budget) {
|
|
|
8006
8015
|
});
|
|
8007
8016
|
}
|
|
8008
8017
|
}
|
|
8018
|
+
var MAX_CODE_BYTES = 4;
|
|
8009
8019
|
function applyGraphicsStateOperator(op, state, saved) {
|
|
8010
8020
|
if (op === "q") {
|
|
8011
8021
|
if (saved.length < GRAPHICS_STATE_MAX_DEPTH) saved.push(state);
|
|
@@ -8083,7 +8093,7 @@ function openGlyphSource(bytes) {
|
|
|
8083
8093
|
if (page === void 0) throw new PdfObjectsRefusal("page-missing");
|
|
8084
8094
|
const into = [];
|
|
8085
8095
|
walkContentStream(
|
|
8086
|
-
{ doc, into, memo, budget: { painted: 0, forms: 0 } },
|
|
8096
|
+
{ doc, into, memo, budget: { painted: 0, cut: false, forms: 0 } },
|
|
8087
8097
|
readContentOperators(pageContentOf(doc, page)),
|
|
8088
8098
|
page.resources,
|
|
8089
8099
|
0,
|
|
@@ -8290,7 +8300,7 @@ var verticalGlyphs = (glyphs) => glyphs.map((glyph) => ({ ...glyph, vmetric: tru
|
|
|
8290
8300
|
function readPageOperators(doc, page, memo = createGlyphMemo()) {
|
|
8291
8301
|
const out = [];
|
|
8292
8302
|
const bytes = pageContentOf(doc, page);
|
|
8293
|
-
const context = { doc, memo, budget: { painted: 0, forms: 0 } };
|
|
8303
|
+
const context = { doc, memo, budget: { painted: 0, cut: false, forms: 0 } };
|
|
8294
8304
|
emitContentStream(
|
|
8295
8305
|
context,
|
|
8296
8306
|
{
|
|
@@ -8303,8 +8313,10 @@ function readPageOperators(doc, page, memo = createGlyphMemo()) {
|
|
|
8303
8313
|
},
|
|
8304
8314
|
out
|
|
8305
8315
|
);
|
|
8316
|
+
if (context.budget.cut) out.push({ operator: GLYPHS_CUT_OPERATOR, operands: [] });
|
|
8306
8317
|
return out;
|
|
8307
8318
|
}
|
|
8319
|
+
var GLYPHS_CUT_OPERATOR = "glyphsCut";
|
|
8308
8320
|
function emitContentStream(context, frame, out) {
|
|
8309
8321
|
const builder = new PathBuilder();
|
|
8310
8322
|
for (const operator of frame.content instanceof Uint8Array ? readContentOperators(frame.content) : frame.content) {
|
|
@@ -9181,23 +9193,6 @@ function collapseOverpaint(glyphs) {
|
|
|
9181
9193
|
return collapsed;
|
|
9182
9194
|
}
|
|
9183
9195
|
|
|
9184
|
-
// src/extractor/pdf-hidden-text.ts
|
|
9185
|
-
var MAX_FILTERED_GLYPHS = 1e5;
|
|
9186
|
-
function countShownGlyphs(ops) {
|
|
9187
|
-
let glyphCount = 0;
|
|
9188
|
-
for (const { operator, operands } of ops) {
|
|
9189
|
-
if (operator !== "showText" && operator !== "showSpacedText") continue;
|
|
9190
|
-
const items = Array.isArray(operands) ? operands[0] : void 0;
|
|
9191
|
-
if (!Array.isArray(items)) continue;
|
|
9192
|
-
for (const item of items) if (typeof item !== "number") glyphCount += 1;
|
|
9193
|
-
if (glyphCount > MAX_FILTERED_GLYPHS) return glyphCount;
|
|
9194
|
-
}
|
|
9195
|
-
return glyphCount;
|
|
9196
|
-
}
|
|
9197
|
-
var shouldDropModeHidden = (glyphs) => glyphs.some(
|
|
9198
|
-
(glyph) => glyph.hiddenReason === void 0 && glyph.isUnpainted === void 0 && !glyph.isSpace && glyph.text.trim() !== ""
|
|
9199
|
-
);
|
|
9200
|
-
|
|
9201
9196
|
// src/layout/word-gap.ts
|
|
9202
9197
|
var WORD_GAP_EM = 0.1;
|
|
9203
9198
|
|
|
@@ -9466,13 +9461,17 @@ var inkOfLine = (line) => {
|
|
|
9466
9461
|
};
|
|
9467
9462
|
};
|
|
9468
9463
|
var isOverhungBy = (cap, ink) => ink !== void 0 && ink.size * MIN_DROP_CAP_RATIO <= cap.fontSize && ink.y > cap.y && ink.y < cap.y + cap.fontSize && ink.left > cap.x;
|
|
9464
|
+
var MAX_DROP_CAP_CANDIDATES = 1e3;
|
|
9469
9465
|
var liftDropCaps = (lines) => {
|
|
9470
9466
|
const out = lines.map((line) => [...line]);
|
|
9471
9467
|
const inks = out.map(inkOfLine);
|
|
9468
|
+
let candidates = 0;
|
|
9472
9469
|
for (const [lineIndex, line] of out.entries()) {
|
|
9473
9470
|
for (const cap of [...line]) {
|
|
9474
9471
|
if (!isDropCap(cap, out[lineIndex])) continue;
|
|
9475
|
-
|
|
9472
|
+
candidates += 1;
|
|
9473
|
+
if (candidates > MAX_DROP_CAP_CANDIDATES) return lines.map((kept) => [...kept]).filter(isNotEmpty);
|
|
9474
|
+
const target = firstOverhungLine(inks, lineIndex, cap);
|
|
9476
9475
|
if (target < 0) continue;
|
|
9477
9476
|
out[lineIndex] = out[lineIndex].filter((item) => item !== cap);
|
|
9478
9477
|
out[target].unshift(cap);
|
|
@@ -9480,8 +9479,13 @@ var liftDropCaps = (lines) => {
|
|
|
9480
9479
|
inks[target] = inkOfLine(out[target]);
|
|
9481
9480
|
}
|
|
9482
9481
|
}
|
|
9483
|
-
return out.filter(
|
|
9482
|
+
return out.filter(isNotEmpty);
|
|
9483
|
+
};
|
|
9484
|
+
var firstOverhungLine = (inks, end, cap) => {
|
|
9485
|
+
for (let index = 0; index < end; index++) if (isOverhungBy(cap, inks[index])) return index;
|
|
9486
|
+
return -1;
|
|
9484
9487
|
};
|
|
9488
|
+
var isNotEmpty = (line) => line.length > 0;
|
|
9485
9489
|
var trimBlankEnds = (group) => {
|
|
9486
9490
|
const isInk2 = (item) => item.text.trim().length > 0;
|
|
9487
9491
|
const first = group.findIndex(isInk2);
|
|
@@ -9589,6 +9593,16 @@ var linesFromItems = (pageItems, isBold, firstWordWidthAt) => linesFromGroups(gr
|
|
|
9589
9593
|
var READABLE = /[^\s\u0000-\u001F\u007F-\u009F]/;
|
|
9590
9594
|
var hasReadableText = (lines) => lines.some((line) => READABLE.test(line.text));
|
|
9591
9595
|
|
|
9596
|
+
// src/extractor/font-weight.ts
|
|
9597
|
+
function classifyFontWeight(weightValue, name) {
|
|
9598
|
+
if (weightValue !== void 0 && Number.isFinite(weightValue) && weightValue >= 100 && weightValue <= 900) {
|
|
9599
|
+
return weightValue >= 600 ? "bold" : "normal";
|
|
9600
|
+
}
|
|
9601
|
+
if (name === void 0) return "unknown";
|
|
9602
|
+
if (/bold|black|heavy/iu.test(name)) return "bold";
|
|
9603
|
+
return standardFontOf(name) !== void 0 ? "normal" : "unknown";
|
|
9604
|
+
}
|
|
9605
|
+
|
|
9592
9606
|
// src/extractor/pdf-font-objects.ts
|
|
9593
9607
|
var readName8 = (value) => value?.kind === "name" ? value.value : void 0;
|
|
9594
9608
|
var FONT_FILE_KEYS = ["FontFile", "FontFile2", "FontFile3"];
|
|
@@ -9603,14 +9617,6 @@ function readFontMatrix(doc, font) {
|
|
|
9603
9617
|
const numbers = matrix.items.map((item) => doc.resolve(item)).map((item) => item?.kind === "number" ? item.value : Number.NaN);
|
|
9604
9618
|
return numbers.length === 6 && numbers.every((value) => Number.isFinite(value)) ? numbers : void 0;
|
|
9605
9619
|
}
|
|
9606
|
-
function classifyFontWeight(weightValue, name) {
|
|
9607
|
-
if (weightValue !== void 0 && Number.isFinite(weightValue) && weightValue >= 100 && weightValue <= 900) {
|
|
9608
|
-
return weightValue >= 600 ? "bold" : "normal";
|
|
9609
|
-
}
|
|
9610
|
-
if (name === void 0) return "unknown";
|
|
9611
|
-
if (/bold|black|heavy/iu.test(name)) return "bold";
|
|
9612
|
-
return standardFontOf(name) !== void 0 ? "normal" : "unknown";
|
|
9613
|
-
}
|
|
9614
9620
|
function classifyItalic(flags, italicAngle, name) {
|
|
9615
9621
|
if (flags !== void 0 && Number.isFinite(flags) && (flags & 64) !== 0) return true;
|
|
9616
9622
|
if (italicAngle !== void 0 && Number.isFinite(italicAngle) && italicAngle !== 0) return true;
|
|
@@ -10532,6 +10538,7 @@ function readPageText(ctx, pageIndex) {
|
|
|
10532
10538
|
const pageObjectId = pageObjectIdOf(entry);
|
|
10533
10539
|
const [x0 = 0, y0 = 0, x1 = 0, y1 = 0] = entry.visibleBox;
|
|
10534
10540
|
const { glyphs, hide, fontUnread, glyphsUnavailable } = readPageGlyphs(ops, ctx, fontScaleOf, symbolFontOf);
|
|
10541
|
+
const cut = glyphsUnavailable === void 0 && ops.at(-1)?.operator === GLYPHS_CUT_OPERATOR;
|
|
10535
10542
|
const sameFont = createSameFontTest(fonts);
|
|
10536
10543
|
const runs = glyphsUnavailable === void 0 ? groupGlyphsIntoRuns(glyphs, {
|
|
10537
10544
|
pageObjectId,
|
|
@@ -10549,6 +10556,7 @@ function readPageText(ctx, pageIndex) {
|
|
|
10549
10556
|
glyphs: ctx.keepGlyphs ? glyphs : [],
|
|
10550
10557
|
...glyphsUnavailable !== void 0 ? { glyphsUnavailable } : {},
|
|
10551
10558
|
...fontUnread ? { fontUnread: true } : {},
|
|
10559
|
+
...cut ? { textCut: true } : {},
|
|
10552
10560
|
...unreadObjects > 0 ? { unreadObjects } : {},
|
|
10553
10561
|
runs,
|
|
10554
10562
|
reference
|
|
@@ -10558,7 +10566,12 @@ function readPageGlyphs(ops, ctx, fontScaleOf, symbolFontOf) {
|
|
|
10558
10566
|
try {
|
|
10559
10567
|
return { ...buildPageGlyphs(ops, ctx, fontScaleOf, symbolFontOf), glyphsUnavailable: void 0 };
|
|
10560
10568
|
} catch (error) {
|
|
10561
|
-
return {
|
|
10569
|
+
return {
|
|
10570
|
+
glyphs: [],
|
|
10571
|
+
hide: void 0,
|
|
10572
|
+
fontUnread: false,
|
|
10573
|
+
glyphsUnavailable: classifyTextUnreadReason(error)
|
|
10574
|
+
};
|
|
10562
10575
|
}
|
|
10563
10576
|
}
|
|
10564
10577
|
function createSameFontTest(fonts) {
|
|
@@ -10578,8 +10591,6 @@ function classifyTextUnreadReason(error) {
|
|
|
10578
10591
|
return "unexpected";
|
|
10579
10592
|
}
|
|
10580
10593
|
function buildPageGlyphs(ops, ctx, fontScaleOf, symbolFontOf) {
|
|
10581
|
-
if (countShownGlyphs(ops) > MAX_FILTERED_GLYPHS)
|
|
10582
|
-
throw new ReaderError4("FILE_UNSAFE", "the page has too many shown glyphs to be read");
|
|
10583
10594
|
const { candidate, namesLayer } = scanHiddenCandidates(ops);
|
|
10584
10595
|
const isLayerVisible = candidate ? createLayerVisibility(ctx, namesLayer) : void 0;
|
|
10585
10596
|
const all = readGlyphs(ops, isLayerVisible, fontScaleOf, symbolFontOf);
|
|
@@ -10634,6 +10645,7 @@ function readPageSource(text, pageIndex, wants, ctx) {
|
|
|
10634
10645
|
glyphs,
|
|
10635
10646
|
...text.glyphsUnavailable !== void 0 ? { glyphsUnavailableReason: text.glyphsUnavailable } : {},
|
|
10636
10647
|
...text.fontUnread === true ? { hasUnreadFont: true } : {},
|
|
10648
|
+
...text.textCut === true ? { hasCutText: true } : {},
|
|
10637
10649
|
...text.unreadObjects !== void 0 ? { unreadObjects: text.unreadObjects } : {},
|
|
10638
10650
|
...declaredOrder.length > 0 ? { declaredOrder: hoistAgainstTree(declaredOrder, runs) } : {},
|
|
10639
10651
|
...noteIds.size > 0 ? { noteIds } : {},
|
|
@@ -11542,7 +11554,9 @@ var groupNearbyCuts = (cuts) => {
|
|
|
11542
11554
|
};
|
|
11543
11555
|
var pickRepresentative = (group) => group[Math.floor(group.length / 2)];
|
|
11544
11556
|
var findLargestGroup = (groups) => {
|
|
11545
|
-
|
|
11557
|
+
let largest = [];
|
|
11558
|
+
for (const group of groups) if (group.length > largest.length) largest = group;
|
|
11559
|
+
return largest;
|
|
11546
11560
|
};
|
|
11547
11561
|
function findDocumentColumnCut(pages) {
|
|
11548
11562
|
const groups = groupNearbyCuts(pages.map(findColumnCut).filter((x) => x !== void 0));
|
|
@@ -13024,15 +13038,17 @@ function nestedBlockListsOf(block) {
|
|
|
13024
13038
|
return block.cells;
|
|
13025
13039
|
case "list":
|
|
13026
13040
|
return block.items;
|
|
13041
|
+
case "footnote":
|
|
13042
|
+
case "section":
|
|
13043
|
+
return [block.blocks];
|
|
13044
|
+
case "tabs":
|
|
13045
|
+
return block.tabs.map((tab) => tab.blocks);
|
|
13027
13046
|
case "heading":
|
|
13028
13047
|
case "paragraph":
|
|
13029
13048
|
case "image":
|
|
13030
13049
|
case "chart":
|
|
13031
|
-
case "footnote":
|
|
13032
13050
|
case "equation":
|
|
13033
13051
|
case "toc":
|
|
13034
|
-
case "section":
|
|
13035
|
-
case "tabs":
|
|
13036
13052
|
case "diagramText":
|
|
13037
13053
|
return [];
|
|
13038
13054
|
default: {
|
|
@@ -13155,16 +13171,38 @@ var sideWithoutBlankEnds = (group, isOnSide) => {
|
|
|
13155
13171
|
const last = items.length - 1 - [...items].reverse().findIndex(isInked);
|
|
13156
13172
|
return items.slice(first, last + 1);
|
|
13157
13173
|
};
|
|
13158
|
-
var
|
|
13159
|
-
const starts = segments.map((segment) => computeMinimum(segment, (item) => item.x));
|
|
13174
|
+
var mostFrequentStart = (starts) => {
|
|
13160
13175
|
const counts = /* @__PURE__ */ new Map();
|
|
13176
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
13177
|
+
const metAt = /* @__PURE__ */ new Map();
|
|
13178
|
+
const bucketOf = (x) => Math.floor(x / SAME_LINE_PT);
|
|
13179
|
+
const firstKnownNear = (x) => {
|
|
13180
|
+
if (!Number.isFinite(x)) return void 0;
|
|
13181
|
+
let found;
|
|
13182
|
+
const low = bucketOf(x - SAME_LINE_PT) - 1;
|
|
13183
|
+
const high = bucketOf(x + SAME_LINE_PT) + 1;
|
|
13184
|
+
const seen = /* @__PURE__ */ new Set();
|
|
13185
|
+
for (let offset = 0; offset <= 4 && low + offset <= high; offset++) seen.add(low + offset);
|
|
13186
|
+
for (const bucket of seen)
|
|
13187
|
+
for (const known of buckets.get(bucket) ?? [])
|
|
13188
|
+
if (Math.abs(known - x) <= SAME_LINE_PT && (found === void 0 || metAt.get(known) < metAt.get(found)))
|
|
13189
|
+
found = known;
|
|
13190
|
+
return found;
|
|
13191
|
+
};
|
|
13161
13192
|
for (const x of starts) {
|
|
13162
|
-
const key =
|
|
13193
|
+
const key = firstKnownNear(x) ?? x;
|
|
13194
|
+
if (!counts.has(key) && Number.isFinite(key)) {
|
|
13195
|
+
metAt.set(key, metAt.size);
|
|
13196
|
+
const bucket = buckets.get(bucketOf(key));
|
|
13197
|
+
if (bucket === void 0) buckets.set(bucketOf(key), [key]);
|
|
13198
|
+
else bucket.push(key);
|
|
13199
|
+
}
|
|
13163
13200
|
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
13164
13201
|
}
|
|
13165
13202
|
const edge = findMode(counts, "smallest");
|
|
13166
13203
|
return edge !== void 0 && counts.get(edge) >= 2 ? edge : void 0;
|
|
13167
13204
|
};
|
|
13205
|
+
var columnEdge = (segments) => mostFrequentStart(segments.map((segment) => computeMinimum(segment, (item) => item.x)));
|
|
13168
13206
|
var crossesEdge = (group, edge) => edge !== void 0 && inked(group).some((item) => item.x < edge - SAME_LINE_PT && item.x + item.width > edge + SAME_LINE_PT);
|
|
13169
13207
|
var bandedSplit = (pageItems, cut, bound, {
|
|
13170
13208
|
standsAlone = false,
|
|
@@ -13400,24 +13438,87 @@ var tieBlocksOf = (entries) => {
|
|
|
13400
13438
|
}
|
|
13401
13439
|
return blocks;
|
|
13402
13440
|
};
|
|
13403
|
-
var
|
|
13404
|
-
|
|
13405
|
-
const parent =
|
|
13406
|
-
|
|
13407
|
-
|
|
13408
|
-
|
|
13409
|
-
|
|
13410
|
-
|
|
13411
|
-
|
|
13412
|
-
|
|
13441
|
+
var compareNumbers = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
13442
|
+
var tieOverlapComponents = (extents, threshold) => {
|
|
13443
|
+
const parent = extents.map((_, index) => index);
|
|
13444
|
+
const join = (a, b) => {
|
|
13445
|
+
parent[rootOf(parent, b)] = rootOf(parent, a);
|
|
13446
|
+
};
|
|
13447
|
+
const candidates = extents.flatMap((extent, index) => extent.right - extent.left > threshold ? [index] : []);
|
|
13448
|
+
const byLeft = [...candidates].sort((a, b) => compareNumbers(extents[a].left, extents[b].left));
|
|
13449
|
+
const byRight = [...candidates].sort((a, b) => compareNumbers(extents[a].right, extents[b].right));
|
|
13450
|
+
const inserted = new Uint8Array(extents.length);
|
|
13451
|
+
const merged = new Uint8Array(extents.length);
|
|
13452
|
+
const sweeps = /* @__PURE__ */ new Map();
|
|
13453
|
+
const activeSegments = /* @__PURE__ */ new Set();
|
|
13454
|
+
const sweepOf = (segment) => {
|
|
13455
|
+
let sweep = sweeps.get(segment);
|
|
13456
|
+
if (sweep === void 0) {
|
|
13457
|
+
sweep = { active: 0, loose: /* @__PURE__ */ new Set(), mergedActive: 0, mergedRep: -1 };
|
|
13458
|
+
sweeps.set(segment, sweep);
|
|
13459
|
+
}
|
|
13460
|
+
return sweep;
|
|
13461
|
+
};
|
|
13462
|
+
const expire = (gone) => {
|
|
13463
|
+
const sweep = sweepOf(extents[gone].segment);
|
|
13464
|
+
sweep.active--;
|
|
13465
|
+
if (merged[gone] === 1) sweep.mergedActive--;
|
|
13466
|
+
else sweep.loose.delete(gone);
|
|
13467
|
+
if (sweep.active === 0) activeSegments.delete(extents[gone].segment);
|
|
13468
|
+
};
|
|
13469
|
+
const anyActiveOf = (sweep) => {
|
|
13470
|
+
for (const line of sweep.loose) return line;
|
|
13471
|
+
return sweep.mergedRep;
|
|
13472
|
+
};
|
|
13473
|
+
let cursor = 0;
|
|
13474
|
+
for (const line of byLeft) {
|
|
13475
|
+
const { left, segment } = extents[line];
|
|
13476
|
+
while (cursor < byRight.length && !(extents[byRight[cursor]].right - left > threshold)) {
|
|
13477
|
+
const gone = byRight[cursor++];
|
|
13478
|
+
if (inserted[gone] === 1) expire(gone);
|
|
13479
|
+
}
|
|
13480
|
+
if (activeSegments.size >= 2) {
|
|
13481
|
+
for (const other of activeSegments)
|
|
13482
|
+
if (other !== segment) {
|
|
13483
|
+
join(anyActiveOf(sweepOf(other)), line);
|
|
13484
|
+
break;
|
|
13485
|
+
}
|
|
13486
|
+
} else {
|
|
13487
|
+
for (const other of activeSegments) {
|
|
13488
|
+
if (other === segment) continue;
|
|
13489
|
+
const sweep = sweepOf(other);
|
|
13490
|
+
if (sweep.mergedActive > 0) join(sweep.mergedRep, line);
|
|
13491
|
+
for (const looseLine of sweep.loose) {
|
|
13492
|
+
join(looseLine, line);
|
|
13493
|
+
merged[looseLine] = 1;
|
|
13494
|
+
sweep.mergedActive++;
|
|
13495
|
+
sweep.mergedRep = looseLine;
|
|
13496
|
+
}
|
|
13497
|
+
sweep.loose.clear();
|
|
13498
|
+
}
|
|
13413
13499
|
}
|
|
13500
|
+
const own = sweepOf(segment);
|
|
13501
|
+
own.active++;
|
|
13502
|
+
own.loose.add(line);
|
|
13503
|
+
activeSegments.add(segment);
|
|
13504
|
+
inserted[line] = 1;
|
|
13505
|
+
}
|
|
13414
13506
|
const byRoot = /* @__PURE__ */ new Map();
|
|
13415
|
-
|
|
13507
|
+
extents.forEach((_, index) => {
|
|
13416
13508
|
const root = rootOf(parent, index);
|
|
13417
|
-
|
|
13509
|
+
const component = byRoot.get(root);
|
|
13510
|
+
if (component === void 0) byRoot.set(root, [index]);
|
|
13511
|
+
else component.push(index);
|
|
13418
13512
|
});
|
|
13419
13513
|
return [...byRoot.values()];
|
|
13420
13514
|
};
|
|
13515
|
+
var tieComponents = (blocks) => {
|
|
13516
|
+
const members = blocks.flatMap((block, place) => block.ink === void 0 ? [] : [{ block, ink: block.ink, place }]);
|
|
13517
|
+
const extents = members.map((member) => ({ segment: member.block.segment, ...member.ink }));
|
|
13518
|
+
return tieOverlapComponents(extents, TIE_OVERLAP_THRESHOLD_PT).map(
|
|
13519
|
+
(component) => component.map((index) => members[index])
|
|
13520
|
+
);
|
|
13521
|
+
};
|
|
13421
13522
|
var reorderTie = (out, start, end) => {
|
|
13422
13523
|
const blocks = tieBlocksOf(out.slice(start, end));
|
|
13423
13524
|
const ordered = [...blocks];
|
|
@@ -13497,6 +13598,11 @@ var capsOfColumn = (lines, inks) => {
|
|
|
13497
13598
|
return found;
|
|
13498
13599
|
};
|
|
13499
13600
|
var seatDropCaps = (segments, slice) => {
|
|
13601
|
+
if (hasTooManyCandidates(segments))
|
|
13602
|
+
return {
|
|
13603
|
+
segments: segments.map((lines) => lines.filter((line) => line.length > 0).map((line) => [...line])),
|
|
13604
|
+
dropCaps: []
|
|
13605
|
+
};
|
|
13500
13606
|
const dropCaps = [];
|
|
13501
13607
|
const out = [];
|
|
13502
13608
|
segments.forEach((original, segment) => {
|
|
@@ -13523,6 +13629,16 @@ var seatDropCaps = (segments, slice) => {
|
|
|
13523
13629
|
});
|
|
13524
13630
|
return { segments: out, dropCaps };
|
|
13525
13631
|
};
|
|
13632
|
+
var hasTooManyCandidates = (segments) => {
|
|
13633
|
+
let candidates = 0;
|
|
13634
|
+
for (const lines of segments) {
|
|
13635
|
+
const smallestInk = smallestInkOf(lines.map(inkOfLine));
|
|
13636
|
+
for (const line of lines)
|
|
13637
|
+
for (const cap of line)
|
|
13638
|
+
if (isCapOfColumn(cap, line, smallestInk) && ++candidates > MAX_DROP_CAP_CANDIDATES) return true;
|
|
13639
|
+
}
|
|
13640
|
+
return false;
|
|
13641
|
+
};
|
|
13526
13642
|
var extentOf = (items) => items.length === 0 ? { top: void 0, bottom: void 0 } : { top: computeMaximum(items, (run) => run.y + run.height), bottom: computeMinimum(items, (run) => run.y) };
|
|
13527
13643
|
var segmentExtent = (lines) => {
|
|
13528
13644
|
const ink = lines.flat().filter((run) => run.text.trim() !== "");
|
|
@@ -14973,9 +15089,12 @@ function imagesPerCell(images, grid, merge) {
|
|
|
14973
15089
|
0,
|
|
14974
15090
|
Math.min(cols.length - 2, cols.findIndex((_, index) => index > 0 && x <= cols[index]) - 1)
|
|
14975
15091
|
);
|
|
14976
|
-
const
|
|
15092
|
+
const ownerIndex = merge?.ownerAt[row]?.[col];
|
|
15093
|
+
const owner = (ownerIndex === void 0 ? void 0 : merge?.cells[ownerIndex]) ?? { row, col };
|
|
14977
15094
|
const key = `${owner.row},${owner.col}`;
|
|
14978
|
-
|
|
15095
|
+
const cellImages = out.get(key);
|
|
15096
|
+
if (cellImages === void 0) out.set(key, [image]);
|
|
15097
|
+
else cellImages.push(image);
|
|
14979
15098
|
}
|
|
14980
15099
|
return out;
|
|
14981
15100
|
}
|
|
@@ -15610,7 +15729,7 @@ var toTextSourceRun = (run) => ({
|
|
|
15610
15729
|
var textUnreadReasons = (source, ocrLayerPageIndices) => {
|
|
15611
15730
|
const textUnreadByPage = /* @__PURE__ */ new Map();
|
|
15612
15731
|
source.pages.forEach((page, pageIndex) => {
|
|
15613
|
-
const reason = page.glyphsUnavailableReason ?? (page.hasUnreadFont === true && !ocrLayerPageIndices.includes(pageIndex) ? "font" : void 0);
|
|
15732
|
+
const reason = page.glyphsUnavailableReason ?? (page.hasCutText === true ? "limit" : void 0) ?? (page.hasUnreadFont === true && !ocrLayerPageIndices.includes(pageIndex) ? "font" : void 0);
|
|
15614
15733
|
if (reason !== void 0) textUnreadByPage.set(pageIndex, reason);
|
|
15615
15734
|
});
|
|
15616
15735
|
return textUnreadByPage;
|