pdf-skryba 0.10.0 → 0.10.2

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/dist/light.js CHANGED
@@ -3,84 +3,103 @@ import { conservationKey as conservationKey4, lostWords, textConservation, wordK
3
3
 
4
4
  // src/pipeline/glued-word-repair.ts
5
5
  import { conservationKey } from "doc-ir";
6
- var UNIT = /[\s\S]/gu;
7
- var unitsOf = (text) => [...text.matchAll(UNIT)].map((m) => ({ text: m[0], key: conservationKey(m[0]), end: m.index + m[0].length }));
8
- var wordsOf = (units) => {
6
+ var CODE_POINT = /[\s\S]/gu;
7
+ var splitCodePoints = (text) => [...text.matchAll(CODE_POINT)].map((match) => ({
8
+ text: match[0],
9
+ key: conservationKey(match[0]),
10
+ end: match.index + match[0].length
11
+ }));
12
+ var splitWords = (codePoints) => {
9
13
  const words = [];
10
14
  let current = [];
11
- const close = () => {
12
- if (conservationKey(current.map((u) => u.text).join("")).length > 0) words.push(current);
15
+ const closeWord = () => {
16
+ if (conservationKey(current.map((codePoint) => codePoint.text).join("")).length > 0) words.push(current);
13
17
  current = [];
14
18
  };
15
- for (const u of units) {
16
- if (/^\s+$/u.test(u.text)) close();
17
- else current.push(u);
19
+ for (const codePoint of codePoints) {
20
+ if (/^\s+$/u.test(codePoint.text)) closeWord();
21
+ else current.push(codePoint);
18
22
  }
19
- close();
23
+ closeWord();
20
24
  return words;
21
25
  };
22
- var edge = (raw, side) => {
23
- const chars = [...raw];
24
- const order = side === "lead" ? chars : [...chars].reverse();
25
- const out = [];
26
- for (const c of order) {
27
- if (conservationKey(c).length > 0) break;
28
- out.push(c);
26
+ var readNonLetterEdge = (word, side) => {
27
+ const characters = [...word];
28
+ const ordered = side === "lead" ? characters : [...characters].reverse();
29
+ const edge = [];
30
+ for (const character of ordered) {
31
+ if (conservationKey(character).length > 0) break;
32
+ edge.push(character);
29
33
  }
30
- return (side === "lead" ? out : [...out].reverse()).join("");
34
+ return (side === "lead" ? edge : [...edge].reverse()).join("");
31
35
  };
32
- var visible = (text) => text.replaceAll("\u200B", "");
33
- var insertionsFor = (blocks, r) => {
34
- const at = r.pageWords[0];
35
- if (r.kind !== "glued" || r.pageWords.length !== 1 || at === void 0 || r.sourceWords.length < 2) return void 0;
36
- const text = blocks[at.block];
37
- const units = text === void 0 ? void 0 : unitsOf(text);
38
- const word = units === void 0 ? void 0 : wordsOf(units)[at.word];
39
- if (word === void 0) return void 0;
40
- const keys = r.sourceWords.map(conservationKey);
41
- const tokenKey = conservationKey(word.map((u2) => u2.text).join(""));
42
- if (word.map((u2) => u2.key).join("") !== tokenKey || keys.join("") !== tokenKey) return void 0;
36
+ var removeZeroWidthSpaces = (text) => text.replaceAll("\u200B", "");
37
+ var findGluedToken = (blocks, respacing) => {
38
+ const pageWord = respacing.pageWords[0];
39
+ if (respacing.kind !== "glued" || respacing.pageWords.length !== 1 || pageWord === void 0 || respacing.sourceWords.length < 2)
40
+ return void 0;
41
+ const text = blocks[pageWord.block];
42
+ if (text === void 0) return void 0;
43
+ return splitWords(splitCodePoints(text))[pageWord.word];
44
+ };
45
+ var countTrailingCodePoints = (between, trail, lead) => {
46
+ if (removeZeroWidthSpaces(between.map((codePoint) => codePoint.text).join("")) !== trail + lead) return void 0;
47
+ let taken = "";
48
+ let takenCount = 0;
49
+ while (taken.length < trail.length && takenCount < between.length) {
50
+ taken += removeZeroWidthSpaces(between[takenCount++].text);
51
+ }
52
+ return taken === trail ? takenCount : void 0;
53
+ };
54
+ var findSpaceInsertions = (blocks, respacing) => {
55
+ const token = findGluedToken(blocks, respacing);
56
+ if (token === void 0) return void 0;
57
+ const sourceKeys = respacing.sourceWords.map(conservationKey);
58
+ const tokenKey = conservationKey(token.map((codePoint) => codePoint.text).join(""));
59
+ if (token.map((codePoint) => codePoint.key).join("") !== tokenKey || sourceKeys.join("") !== tokenKey)
60
+ return void 0;
43
61
  const offsets = [];
44
- let u = 0;
45
- let letters = 0;
46
- for (let i = 0; i < keys.length - 1; i++) {
47
- const boundary = letters + keys[i].length;
48
- while (u < word.length && letters + word[u].key.length <= boundary && letters < boundary)
49
- letters += word[u++].key.length;
50
- if (letters !== boundary) return void 0;
51
- let next = u;
52
- while (next < word.length && word[next].key.length === 0) next++;
53
- const between = word.slice(u, next);
54
- const trail = edge(r.sourceWords[i], "trail");
55
- if (visible(between.map((x) => x.text).join("")) !== trail + edge(r.sourceWords[i + 1], "lead")) return void 0;
56
- let taken = "";
57
- let k = 0;
58
- while (taken.length < trail.length && k < between.length) taken += visible(between[k++].text);
59
- if (taken !== trail) return void 0;
60
- offsets.push(word[u + k - 1].end);
61
- u += k;
62
+ let position = 0;
63
+ let letterCount = 0;
64
+ for (let sourceIndex = 0; sourceIndex < sourceKeys.length - 1; sourceIndex++) {
65
+ const boundary = letterCount + sourceKeys[sourceIndex].length;
66
+ while (position < token.length && letterCount + token[position].key.length <= boundary && letterCount < boundary)
67
+ letterCount += token[position++].key.length;
68
+ if (letterCount !== boundary) return void 0;
69
+ let nextLetter = position;
70
+ while (nextLetter < token.length && token[nextLetter].key.length === 0) nextLetter++;
71
+ const takenCount = countTrailingCodePoints(
72
+ token.slice(position, nextLetter),
73
+ readNonLetterEdge(respacing.sourceWords[sourceIndex], "trail"),
74
+ readNonLetterEdge(respacing.sourceWords[sourceIndex + 1], "lead")
75
+ );
76
+ if (takenCount === void 0) return void 0;
77
+ offsets.push(token[position + takenCount - 1].end);
78
+ position += takenCount;
62
79
  }
63
80
  return offsets;
64
81
  };
65
82
  function gluedWordEdits(page, respacings) {
66
- const glued = respacings.filter((r) => r.kind === "glued");
83
+ const glued = respacings.filter((respacing) => respacing.kind === "glued");
67
84
  if (glued.length === 0) return { edits: [], repaired: 0 };
68
- const taken = /* @__PURE__ */ new Set();
85
+ const takenOffsets = /* @__PURE__ */ new Set();
69
86
  const edits = [];
70
87
  let repaired = 0;
71
- for (const r of glued) {
72
- const block = r.pageWords[0]?.block;
73
- const at = insertionsFor(page.blocks, r);
74
- if (at === void 0 || block === void 0 || at.some((o) => taken.has(`${block}:${o}`))) continue;
75
- for (const atChar of at) {
76
- taken.add(`${block}:${atChar}`);
88
+ for (const respacing of glued) {
89
+ const block = respacing.pageWords[0]?.block;
90
+ const offsets = findSpaceInsertions(page.blocks, respacing);
91
+ if (offsets === void 0 || block === void 0 || offsets.some((offset) => takenOffsets.has(`${block}:${offset}`)))
92
+ continue;
93
+ for (const atChar of offsets) {
94
+ takenOffsets.add(`${block}:${atChar}`);
77
95
  edits.push({ kind: "insert-space", block, atChar });
78
96
  }
79
97
  repaired += 1;
80
98
  }
81
99
  return { edits, repaired };
82
100
  }
83
- var noWorse = (before, after, repaired) => after.lostLetters <= before.lostLetters && (after.decision !== "lost" || before.decision === "lost") && after.decision !== "abstain" && after.gluedWords <= before.gluedWords - repaired && after.unmatchedPageWords <= before.unmatchedPageWords && after.respacings.filter((r) => r.kind === "split").length <= before.respacings.filter((r) => r.kind === "split").length;
101
+ var countSplitWords = (verdict) => verdict.respacings.filter((respacing) => respacing.kind === "split").length;
102
+ var noWorse = (before, after, repaired) => after.lostLetters <= before.lostLetters && (after.decision !== "lost" || before.decision === "lost") && after.decision !== "abstain" && after.gluedWords <= before.gluedWords - repaired && after.unmatchedPageWords <= before.unmatchedPageWords && countSplitWords(after) <= countSplitWords(before);
84
103
 
85
104
  // src/pipeline/cut-paragraph-repair.ts
86
105
  import { collapseBlanks } from "doc-ir/internal";
@@ -101,8 +120,8 @@ function markerOf(text) {
101
120
  [ROMAN, "letter"],
102
121
  [LETTERED, "letter"]
103
122
  ]) {
104
- const m = pattern.exec(text);
105
- if (m !== null) return { kind, length: m[0].length };
123
+ const match = pattern.exec(text);
124
+ if (match !== null) return { kind, length: match[0].length };
106
125
  }
107
126
  return void 0;
108
127
  }
@@ -111,39 +130,52 @@ function markerOf(text) {
111
130
  import {
112
131
  conservationKey as conservationKey2
113
132
  } from "doc-ir";
114
- var WINDOW = 3;
115
- var TERMINAL = /[.:;!?»"…)]$/u;
133
+ var EDGE_WORD_COUNT = 3;
134
+ var SENTENCE_END = /[.:;!?»"…)]$/u;
116
135
  var startsLowercaseWord = (text) => new RegExp("^\\p{Ll}+(?![\\p{L}\\p{N}])", "u").test(text);
117
- var startsOnALoneLetter = (text) => conservationKey2(text.split(/\s+/)[0] ?? "").length <= 1;
118
- var textOfUnit = (page, blocks) => collapseBlanks(blocks.map((b) => page.blocks[b] ?? "").join(" "));
119
- var readInARow = (tail, head) => {
120
- const words = [...tail, ...head];
121
- if (tail.length === 0 || head.length === 0 || words.some((w) => w === null)) return false;
122
- const links = words;
123
- for (let k = 1; k < links.length; k++) if (links[k].index !== links[k - 1].index + 1) return false;
124
- const last = links[tail.length - 1];
125
- const first = links[tail.length];
126
- return Math.abs(last.lastSize - first.firstSize) < 0.01;
136
+ var startsWithSingleLetterToken = (text) => conservationKey2(text.split(/\s+/)[0] ?? "").length <= 1;
137
+ var readUnitText = (page, blocks) => collapseBlanks(blocks.map((blockIndex) => page.blocks[blockIndex] ?? "").join(" "));
138
+ var isSourceWordLink = (link) => link !== null;
139
+ var isReadInARow = (tail, head) => {
140
+ if (tail.length === 0 || head.length === 0) return false;
141
+ const links = [...tail, ...head];
142
+ if (!links.every(isSourceWordLink)) return false;
143
+ for (let index = 1; index < links.length; index++) {
144
+ if (links[index].index !== links[index - 1].index + 1) return false;
145
+ }
146
+ const tailLast = links[tail.length - 1];
147
+ const headFirst = links[tail.length];
148
+ return Math.abs(tailLast.lastSize - headFirst.firstSize) < 0.01;
149
+ };
150
+ var hasContinuationShape = (firstText, secondText) => {
151
+ if (firstText.length === 0 || SENTENCE_END.test(firstText)) return false;
152
+ if (!startsLowercaseWord(secondText)) return false;
153
+ if (markerOf(secondText) !== void 0) return false;
154
+ return !startsWithSingleLetterToken(secondText);
127
155
  };
128
156
  var noWorse2 = (before, after) => after.decision !== "abstain" && (after.decision !== "lost" || before.decision === "lost") && after.lostLetters <= before.lostLetters && after.gluedWords <= before.gluedWords && after.unmatchedPageWords <= before.unmatchedPageWords;
129
157
  function cutParagraphEdits(page, verdict) {
130
158
  const units = page.units;
131
159
  if (units === void 0 || verdict.decision === "abstain") return { edits: [], joined: 0 };
132
- const links = units.map(
133
- (unit) => unit.blocks.flatMap((b) => verdict.sourceOfPageWords[b] ?? [])
160
+ const unitSourceLinks = units.map(
161
+ (unit) => unit.blocks.flatMap((blockIndex) => verdict.sourceOfPageWords[blockIndex] ?? [])
134
162
  );
135
- const cutAfter = (u) => {
136
- const first = units[u];
137
- const second = units[u + 1];
138
- if (!first.joinable || !second.joinable || !first.adjacentToNext) return false;
139
- const ta = textOfUnit(page, first.blocks);
140
- const tb = textOfUnit(page, second.blocks);
141
- if (ta.length === 0 || TERMINAL.test(ta)) return false;
142
- if (!startsLowercaseWord(tb) || markerOf(tb) !== void 0 || startsOnALoneLetter(tb)) return false;
143
- return readInARow(links[u].slice(-WINDOW), links[u + 1].slice(0, WINDOW));
163
+ const isCutAfter = (unitIndex) => {
164
+ const firstUnit = units[unitIndex];
165
+ const secondUnit = units[unitIndex + 1];
166
+ if (!firstUnit.joinable || !secondUnit.joinable || !firstUnit.adjacentToNext) return false;
167
+ const firstText = readUnitText(page, firstUnit.blocks);
168
+ const secondText = readUnitText(page, secondUnit.blocks);
169
+ if (!hasContinuationShape(firstText, secondText)) return false;
170
+ return isReadInARow(
171
+ unitSourceLinks[unitIndex].slice(-EDGE_WORD_COUNT),
172
+ unitSourceLinks[unitIndex + 1].slice(0, EDGE_WORD_COUNT)
173
+ );
144
174
  };
145
175
  const edits = [];
146
- for (let u = units.length - 2; u >= 0; u--) if (cutAfter(u)) edits.push({ kind: "join-units", unit: u });
176
+ for (let unitIndex = units.length - 2; unitIndex >= 0; unitIndex--) {
177
+ if (isCutAfter(unitIndex)) edits.push({ kind: "join-units", unit: unitIndex });
178
+ }
147
179
  return { edits, joined: edits.length };
148
180
  }
149
181
 
@@ -152,47 +184,54 @@ import {
152
184
  conservationKey as conservationKey3,
153
185
  wordKeysOf
154
186
  } from "doc-ir";
187
+ var isAfterInPageOrder = (later, earlier) => later.block > earlier.block || later.block === earlier.block && later.word > earlier.word;
155
188
  function placeLostPassages(page, passages) {
156
189
  const insertions = [];
157
190
  const abstentions = [];
158
191
  if (passages.length === 0) return { insertions, abstentions };
159
192
  const units = page.units;
160
- const words = page.blocks.map((text) => wordKeysOf(text).length);
161
- const lastBlock = words.length - 1;
162
- const unitOf = (block) => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;
163
- const edgeOf = (at, side) => {
164
- const u = unitOf(at.block);
165
- if (u < 0 || units?.[u]?.paragraphOrHeading !== true) return "anchor-in-container";
166
- const neighbourBlock = side === "before" ? at.block + 1 : at.block - 1;
167
- const atEdge = side === "before" ? at.word === (words[at.block] ?? 0) - 1 : at.word === 0;
168
- if (!atEdge || unitOf(neighbourBlock) === u) return "loss-inside-block";
169
- return u;
193
+ const wordCountByBlock = page.blocks.map((text) => wordKeysOf(text).length);
194
+ const lastBlock = wordCountByBlock.length - 1;
195
+ const findUnitOfBlock = (block) => units?.findIndex((unit) => unit.blocks.includes(block)) ?? -1;
196
+ const findAnchorUnit = (anchor, side) => {
197
+ const unitIndex = findUnitOfBlock(anchor.block);
198
+ if (unitIndex < 0 || units?.[unitIndex]?.paragraphOrHeading !== true) return "anchor-in-container";
199
+ const neighbourBlock = side === "before" ? anchor.block + 1 : anchor.block - 1;
200
+ const isAtEdge = side === "before" ? anchor.word === (wordCountByBlock[anchor.block] ?? 0) - 1 : anchor.word === 0;
201
+ if (!isAtEdge || findUnitOfBlock(neighbourBlock) === unitIndex) return "loss-inside-block";
202
+ return unitIndex;
170
203
  };
171
- const place = (passage) => {
204
+ const placePassage = (passage) => {
172
205
  const { before, after } = passage;
173
206
  if (before === "unanchored" || after === "unanchored") return "anchor-unmatched";
174
207
  if (before === "document-edge" && after === "document-edge") return "no-anchor";
175
- if (before !== "document-edge" && after !== "document-edge") {
176
- if (after.block < before.block || after.block === before.block && after.word <= before.word)
177
- return "anchors-out-of-order";
208
+ if (before !== "document-edge" && after !== "document-edge" && !isAfterInPageOrder(after, before))
209
+ return "anchors-out-of-order";
210
+ const unitBefore = before === "document-edge" ? void 0 : findAnchorUnit(before, "before");
211
+ if (typeof unitBefore === "string") return unitBefore;
212
+ const unitAfter = after === "document-edge" ? void 0 : findAnchorUnit(after, "after");
213
+ if (typeof unitAfter === "string") return unitAfter;
214
+ if (unitBefore === void 0) {
215
+ if (unitAfter === void 0 || after === "document-edge" || after.block !== 0) return "no-anchor";
216
+ return unitAfter - 1;
217
+ }
218
+ if (unitAfter === void 0) {
219
+ if (before === "document-edge" || before.block !== lastBlock) return "no-anchor";
220
+ return unitBefore;
178
221
  }
179
- const u1 = before === "document-edge" ? void 0 : edgeOf(before, "before");
180
- if (typeof u1 === "string") return u1;
181
- const u2 = after === "document-edge" ? void 0 : edgeOf(after, "after");
182
- if (typeof u2 === "string") return u2;
183
- if (u1 === void 0) return after !== "document-edge" && after.block === 0 ? u2 - 1 : "no-anchor";
184
- if (u2 === void 0) return before !== "document-edge" && before.block === lastBlock ? u1 : "no-anchor";
185
- return u2 === u1 + 1 && units?.[u1]?.adjacentToNext === true ? u1 : "blocks-not-adjacent";
222
+ if (unitAfter !== unitBefore + 1 || units?.[unitBefore]?.adjacentToNext !== true) return "blocks-not-adjacent";
223
+ return unitBefore;
186
224
  };
187
225
  for (const passage of passages) {
188
- const at = place(passage);
189
- if (typeof at === "string") abstentions.push(at);
190
- else {
191
- insertions.push({
192
- edit: { kind: "insert-unit-after", unit: at, text: passage.sourceWords.join(" ") },
193
- letters: passage.sourceWords.reduce((n, w) => n + conservationKey3(w).length, 0)
194
- });
226
+ const placement = placePassage(passage);
227
+ if (typeof placement === "string") {
228
+ abstentions.push(placement);
229
+ continue;
195
230
  }
231
+ insertions.push({
232
+ edit: { kind: "insert-unit-after", unit: placement, text: passage.sourceWords.join(" ") },
233
+ letters: passage.sourceWords.reduce((letterTotal, word) => letterTotal + conservationKey3(word).length, 0)
234
+ });
196
235
  }
197
236
  return { insertions, abstentions };
198
237
  }