hwpx2f 0.0.0-stage → 0.1.0

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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -2
  3. package/THIRD_PARTY_NOTICES.md +75 -0
  4. package/dist/cli.js +76 -0
  5. package/dist/index.d.ts +11 -0
  6. package/dist/index.js +32 -0
  7. package/dist/lib/chunk-36PRCVPO.js +131 -0
  8. package/dist/lib/chunk-45BAITEX.js +9749 -0
  9. package/dist/lib/chunk-4NRZ6MWV.js +133 -0
  10. package/dist/lib/chunk-6CFXTS7A.js +11971 -0
  11. package/dist/lib/chunk-6CPCDYOD.js +104 -0
  12. package/dist/lib/chunk-B6MTS4XP.js +313 -0
  13. package/dist/lib/chunk-BX24E7EG.js +1427 -0
  14. package/dist/lib/chunk-C64I2SU4.js +82 -0
  15. package/dist/lib/chunk-CEKQASS3.js +258 -0
  16. package/dist/lib/chunk-CMWTKXM2.js +204 -0
  17. package/dist/lib/chunk-E6KSYRHG.js +2189 -0
  18. package/dist/lib/chunk-IZDWVMTV.js +28786 -0
  19. package/dist/lib/chunk-JK6YR5NT.js +4276 -0
  20. package/dist/lib/chunk-O6FSHPNE.js +111 -0
  21. package/dist/lib/chunk-OYXOOP2U.js +199 -0
  22. package/dist/lib/chunk-PM4KBWF4.js +49 -0
  23. package/dist/lib/chunk-R5F3GHLO.js +290 -0
  24. package/dist/lib/chunk-R76DWHJR.js +1596 -0
  25. package/dist/lib/chunk-RFS3RTSR.js +6876 -0
  26. package/dist/lib/chunk-RYJRNK5Z.js +47 -0
  27. package/dist/lib/chunk-UOXPGSFH.js +43 -0
  28. package/dist/lib/chunk-UZH4UBMX.js +44 -0
  29. package/dist/lib/chunk-VZTE4GKI.js +52 -0
  30. package/dist/lib/chunk-WEOKEO6L.js +35291 -0
  31. package/dist/lib/detect-4XZNNYZA-O7IPA4XQ.js +32 -0
  32. package/dist/lib/dist-HVSOXNCJ.js +263 -0
  33. package/dist/lib/formula-LC62GV4D-K3VFC5GV.js +1173 -0
  34. package/dist/lib/generator-KYTTL4OS-TRAQ66QE.js +14 -0
  35. package/dist/lib/hancom-EM62ZVDM-WZKVI7XB.js +91 -0
  36. package/dist/lib/image-ocr-ZUZQXLYS-U66LBMRA.js +293 -0
  37. package/dist/lib/page-images-VCIFZAXK-KJLWQDRH.js +95 -0
  38. package/dist/lib/page-range-7R3JU6SQ-MDDQRZVK.js +10 -0
  39. package/dist/lib/parser-JQNH5QMM-HFFI4HYK.js +4310 -0
  40. package/dist/lib/pdf-ocr-C3MBR6J2-J3UGJKWT.js +46 -0
  41. package/dist/lib/to-hwpx-JUT2SOTT-MOPPK6OW.js +17 -0
  42. package/dist/notices/core-util-is/LICENSE +19 -0
  43. package/dist/notices/entities/LICENSE +11 -0
  44. package/dist/notices/immediate/LICENSE.txt +20 -0
  45. package/dist/notices/inherits/LICENSE +16 -0
  46. package/dist/notices/jszip/LICENSE.markdown +651 -0
  47. package/dist/notices/kordoc/LICENSE +21 -0
  48. package/dist/notices/kordoc/NOTICE +376 -0
  49. package/dist/notices/kordoc/THIRD_PARTY/apache-2.0.LICENSE +201 -0
  50. package/dist/notices/kordoc/THIRD_PARTY/claw-hwp.LICENSE +21 -0
  51. package/dist/notices/kordoc/THIRD_PARTY/hayro-pdf.txt +361 -0
  52. package/dist/notices/kordoc/THIRD_PARTY/hml-equation-parser.LICENSE +201 -0
  53. package/dist/notices/kordoc/THIRD_PARTY/hml-equation-parser.txt +35 -0
  54. package/dist/notices/kordoc/THIRD_PARTY/korean-report-hwpx.LICENSE +21 -0
  55. package/dist/notices/kordoc/THIRD_PARTY/memchr.LICENSE +21 -0
  56. package/dist/notices/kordoc/THIRD_PARTY/opendataloader-pdf.txt +32 -0
  57. package/dist/notices/kordoc/THIRD_PARTY/pix2text.txt +17 -0
  58. package/dist/notices/kordoc/THIRD_PARTY/quick-xml.LICENSE +23 -0
  59. package/dist/notices/kordoc/THIRD_PARTY/rhwp-forms.txt +35 -0
  60. package/dist/notices/lie/license.md +7 -0
  61. package/dist/notices/linkify-it/LICENSE +22 -0
  62. package/dist/notices/markdown-it/LICENSE +22 -0
  63. package/dist/notices/mdurl/LICENSE +45 -0
  64. package/dist/notices/pako/LICENSE +21 -0
  65. package/dist/notices/process-nextick-args/license.md +19 -0
  66. package/dist/notices/punycode.js/LICENSE-MIT.txt +20 -0
  67. package/dist/notices/readable-stream/LICENSE +47 -0
  68. package/dist/notices/safe-buffer/LICENSE +21 -0
  69. package/dist/notices/setimmediate/LICENSE.txt +20 -0
  70. package/dist/notices/string_decoder/LICENSE +48 -0
  71. package/dist/notices/uc.micro/LICENSE.txt +20 -0
  72. package/dist/notices/util-deprecate/LICENSE +24 -0
  73. package/package.json +66 -4
@@ -0,0 +1,4276 @@
1
+ import { createRequire as __hwpx2fRequire } from 'node:module'; const require = __hwpx2fRequire(import.meta.url);
2
+ import {
3
+ similarity
4
+ } from "./chunk-C64I2SU4.js";
5
+ import {
6
+ createOrtSession,
7
+ disableOrtTelemetry,
8
+ ortProvidersSetting
9
+ } from "./chunk-UOXPGSFH.js";
10
+ import {
11
+ DEFAULT_OCR_MODELS,
12
+ UNRULED_REGION_TABLES,
13
+ arrowGlyph,
14
+ bracketFeatures,
15
+ bracketShape,
16
+ checkboxFrames,
17
+ circledAt,
18
+ copyOcrTextGaps,
19
+ dashRatio,
20
+ discAt,
21
+ edgeTrim,
22
+ ensureOcrModelsFor,
23
+ extractPageBlocksWithLines,
24
+ findOcrTextGaps,
25
+ gapGlyphs,
26
+ grayCrop,
27
+ handwritingFallbackModels,
28
+ inkBounds,
29
+ inkStats,
30
+ leaderRuns,
31
+ leadingBullet,
32
+ leadingRing,
33
+ leadingTriangle,
34
+ ocrModelsCached,
35
+ ocrSelectionKey,
36
+ ocrSourcePath,
37
+ parseCharacterDict,
38
+ quoteHead,
39
+ rememberOcrTextGaps,
40
+ resolveOcrModels,
41
+ ringBoxes,
42
+ ringBullet,
43
+ romanStems,
44
+ serifOne,
45
+ slantedPair,
46
+ splitRowBands,
47
+ stackedGlyphBands,
48
+ starRun,
49
+ tallInkCount,
50
+ valleyBands
51
+ } from "./chunk-6CFXTS7A.js";
52
+ import {
53
+ validateOcrOptions
54
+ } from "./chunk-PM4KBWF4.js";
55
+ import {
56
+ KordocError,
57
+ OPTIONAL_DEP_INSTALL_HINT
58
+ } from "./chunk-OYXOOP2U.js";
59
+
60
+ // node_modules/kordoc/dist/chunk-XVRM774B.js
61
+ import { createHash } from "crypto";
62
+ import { readFile, stat } from "fs/promises";
63
+ import { basename } from "path";
64
+ var NUMERIC = /^[-+−△▲▽▼]?[\d.,]+[%p원]?$|^[-–—·∼~]원?$|^\([-+−△▲▽▼]?[\d.,]+%?\)$/;
65
+ var blank = () => ({ text: "", colSpan: 1, rowSpan: 1 });
66
+ function rowAnchors(t, r, coveredFromAbove) {
67
+ const out = [];
68
+ const row = t.cells[r] ?? [];
69
+ for (let c = 0; c < row.length; ) {
70
+ if (coveredFromAbove[c]) {
71
+ c++;
72
+ continue;
73
+ }
74
+ const cell = row[c];
75
+ out.push({ c, cell });
76
+ c += Math.max(1, cell.colSpan ?? 1);
77
+ }
78
+ return out;
79
+ }
80
+ function splitTable(t) {
81
+ let changed = false;
82
+ const cover = Array.from({ length: t.rows }, () => Array(t.cols).fill(null));
83
+ for (let r = 0; r < t.rows; r++) for (let c = 0; c < (t.cells[r] ?? []).length; c++) {
84
+ const cell = t.cells[r][c], rs = Math.max(1, cell.rowSpan ?? 1), cs = Math.max(1, cell.colSpan ?? 1);
85
+ if (cover[r][c]) continue;
86
+ for (let i = r + 1; i < Math.min(t.rows, r + rs); i++) for (let j = c; j < Math.min(t.cols, c + cs); j++) cover[i][j] = cell;
87
+ }
88
+ const newRows = [];
89
+ for (let r = 0; r < t.rows; r++) {
90
+ const row = t.cells[r] ?? [];
91
+ const anchors = rowAnchors(t, r, cover[r]);
92
+ const lines = anchors.map((a) => {
93
+ const ls = a.cell.text.split("\n").map((s) => s.trim()).filter(Boolean);
94
+ return (a.cell.rowSpan ?? 1) > 1 && ls.length > 1 && ls.every((l) => !NUMERIC.test(l.replace(/\s+/g, ""))) ? [ls.join("\n")] : ls;
95
+ });
96
+ const counts = /* @__PURE__ */ new Map();
97
+ for (const ls of lines) if (ls.length >= 2) counts.set(ls.length, (counts.get(ls.length) ?? 0) + 1);
98
+ const [k, n] = [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0])[0] ?? [0, 0];
99
+ lines.forEach((ls, i) => {
100
+ if (ls.length > 1 && ls.length < k && ls.every((l) => /^[가-힣A-Za-z]$/.test(l))) lines[i] = [ls.join("")];
101
+ });
102
+ const nonEmpty = lines.filter((ls) => ls.length).length;
103
+ const near = (ls) => ls.length >= 2 && ls.length <= k && ls.length >= Math.ceil(k * 0.8);
104
+ const stacked = lines.filter(near);
105
+ const flat = stacked.flat();
106
+ const numericShare = flat.length ? flat.filter((s) => NUMERIC.test(s.replace(/\s+/g, ""))).length / flat.length : 0;
107
+ const spanOk = anchors.every((a, i) => (a.cell.rowSpan ?? 1) === 1 || lines[i].length <= 1);
108
+ const shares = k === 2 && stacked.length >= 2 && stacked.every((ls) => NUMERIC.test(ls[0].replace(/\s+/g, "")) && /^\(.*\)$/.test(ls[1]));
109
+ const isNum = (s) => NUMERIC.test(s.replace(/\s+/g, ""));
110
+ const kind = (ls) => ls.filter(isNum).length >= ls.length * 0.8 ? "num" : ls.some((l) => /^[○◦]/.test(l)) && ls.every((l) => !isNum(l) && l.replace(/\s+/g, "").length <= 12) ? "label" : "other";
111
+ const kinds = stacked.map(kind);
112
+ const valueRows = numericShare >= 0.6 || kinds.includes("num") && kinds.includes("label") && !kinds.includes("other");
113
+ const breakdown = lines.some((ls) => ls.length >= 2 && !isNum(ls[0]) && ls.slice(1).some((l) => !isNum(l) && /\d\s*원/.test(l))) || lines.some((ls) => ls.some((l) => /^[국도균시군구]\s*[\d,]+$/.test(l)));
114
+ const ok = spanOk && k >= 2 && n >= 2 && (stacked.length * 2 >= nonEmpty || shares) && lines.every((ls) => ls.length <= 1 || near(ls)) && valueRows && !breakdown;
115
+ if (!ok) {
116
+ newRows.push(row);
117
+ continue;
118
+ }
119
+ const sub = Array.from({ length: k }, () => Array.from({ length: row.length }, blank));
120
+ anchors.forEach(({ c, cell }, idx) => {
121
+ const ls = lines[idx], cs = Math.max(1, cell.colSpan ?? 1);
122
+ if (ls.length >= 2) for (let i = 0; i < k; i++) sub[i][c] = { ...cell, text: ls[i] ?? "", colSpan: cs, rowSpan: 1 };
123
+ else {
124
+ cell.rowSpan = (cell.rowSpan ?? 1) + k - 1;
125
+ sub[0][c] = cell;
126
+ }
127
+ });
128
+ for (const owner of new Set(cover[r].filter((x) => !!x))) owner.rowSpan = (owner.rowSpan ?? 1) + k - 1;
129
+ newRows.push(...sub);
130
+ changed = true;
131
+ }
132
+ if (changed) {
133
+ t.cells = newRows;
134
+ t.rows = newRows.length;
135
+ }
136
+ return changed;
137
+ }
138
+ function splitStackedOcrRows(blocks) {
139
+ for (const b of blocks) if (b.type === "table" && b.table) splitTable(b.table);
140
+ return blocks;
141
+ }
142
+ function unframeOcrLayoutTables(blocks, pageHeight) {
143
+ const out = [];
144
+ for (const b of blocks) {
145
+ const t = b.table;
146
+ if (b.type !== "table" || !t || !b.bbox || b.bbox.height < pageHeight * 0.5 || t.cols > 4) {
147
+ out.push(b);
148
+ continue;
149
+ }
150
+ const anchors = [];
151
+ const covered = Array.from({ length: t.rows }, () => /* @__PURE__ */ new Set());
152
+ for (let r = 0; r < t.rows; r++) for (let c = 0; c < (t.cells[r] ?? []).length; c++) {
153
+ if (covered[r].has(c)) continue;
154
+ const cell = t.cells[r][c];
155
+ const rs = Math.max(1, cell.rowSpan ?? 1), cs = Math.max(1, cell.colSpan ?? 1);
156
+ for (let i = r; i < Math.min(t.rows, r + rs); i++) for (let j = c; j < c + cs; j++) if (i !== r || j !== c) covered[i].add(j);
157
+ anchors.push({ r, c, cell });
158
+ }
159
+ const texts = anchors.map((a) => a.cell.text.trim()).filter(Boolean);
160
+ if (!texts.length) {
161
+ out.push(b);
162
+ continue;
163
+ }
164
+ const numeric = texts.filter((s) => NUMERIC.test(s.replace(/\s+/g, ""))).length;
165
+ const avg = texts.reduce((n, s) => n + s.length, 0) / texts.length;
166
+ if (numeric >= texts.length * 0.3 || avg < 15 || texts.filter((s) => /[①-⑤]/.test(s)).length < 2) {
167
+ out.push(b);
168
+ continue;
169
+ }
170
+ anchors.sort((a, b2) => a.c - b2.c || a.r - b2.r);
171
+ for (const { cell } of anchors) {
172
+ if (cell.blocks?.length) {
173
+ out.push(...cell.blocks);
174
+ continue;
175
+ }
176
+ const text = cell.text.trim();
177
+ if (text) out.push({ type: "paragraph", text, pageNumber: b.pageNumber, bbox: b.bbox });
178
+ }
179
+ }
180
+ return out;
181
+ }
182
+ var NAME_VALUE = /^([^\d]*?)\s*(\d[\d,.]*\d|\d)([^\d\n]{0,2})(?:\n([^\d]*))?$/;
183
+ function nameValue(text) {
184
+ const m = NAME_VALUE.exec(text.trim());
185
+ if (!m) return null;
186
+ const name = [m[1], m[4] ?? ""].map((s) => s.replace(/\s+/g, " ").trim()).filter(Boolean).join(" ");
187
+ if ((name.match(/[가-힣A-Za-z]/g) ?? []).length < 2) return null;
188
+ return { name, value: (m[2] + m[3]).trim() };
189
+ }
190
+ function owners(t) {
191
+ const own = Array.from({ length: t.rows }, () => Array(t.cols));
192
+ for (let r = 0; r < t.rows; r++) for (let c = 0; c < t.cols; c++) {
193
+ if (own[r][c]) continue;
194
+ const cell = t.cells[r][c];
195
+ for (let i = r; i < Math.min(t.rows, r + Math.max(1, cell.rowSpan ?? 1)); i++)
196
+ for (let j = c; j < Math.min(t.cols, c + Math.max(1, cell.colSpan ?? 1)); j++) own[i][j] ??= cell;
197
+ }
198
+ return own;
199
+ }
200
+ function headerCuts(text) {
201
+ const out = [];
202
+ for (const m of text.matchAll(/\s+/g)) {
203
+ const l = text.slice(0, m.index).replace(/\s+/g, ""), r = text.slice(m.index + m[0].length).replace(/\s+/g, "");
204
+ if (l.length >= 2 && r.length >= 2) out.push([l, r]);
205
+ }
206
+ return out;
207
+ }
208
+ function cutAt(text, left) {
209
+ let n = 0;
210
+ for (let i = 0; i < text.length; i++) {
211
+ if (!/\s/.test(text[i])) n++;
212
+ if (n === left.length) return [text.slice(0, i + 1).trim(), text.slice(i + 1).trim()];
213
+ }
214
+ return null;
215
+ }
216
+ function splitTable2(t) {
217
+ if (t.cells.length !== t.rows || t.cells.some((row) => row.length !== t.cols)) return false;
218
+ const own = owners(t);
219
+ const anchor = (r, c) => own[r][c] === t.cells[r][c] ? t.cells[r][c] : null;
220
+ const targets = [];
221
+ for (let c = 0; c < t.cols; c++) {
222
+ let filled = 0, hits = 0, grouped = 0, first = -1;
223
+ for (let r = 0; r < t.rows; r++) {
224
+ const cell = anchor(r, c);
225
+ if (!cell || (cell.colSpan ?? 1) !== 1 || cell.blocks?.length || !cell.text.trim()) continue;
226
+ const nv = nameValue(cell.text);
227
+ if (nv) {
228
+ hits++;
229
+ if (first < 0) first = r;
230
+ if (/,\d{2}|\.\d/.test(nv.value)) grouped++;
231
+ }
232
+ if (first >= 0) filled++;
233
+ }
234
+ if (hits >= 5 && hits >= filled * 0.8 && grouped >= 2) targets.push({ c, first });
235
+ }
236
+ if (!targets.length) return false;
237
+ const starts = /* @__PURE__ */ new Map();
238
+ for (const { first } of targets) starts.set(first, (starts.get(first) ?? 0) + 1);
239
+ const start = [...starts].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0][0];
240
+ for (const tg of targets) if (tg.first > start) tg.first = start;
241
+ const heads = targets.map(({ c, first }) => {
242
+ const cell = first > 0 ? anchor(first - 1, c) : null;
243
+ return cell && (cell.colSpan ?? 1) === 1 && (cell.rowSpan ?? 1) === 1 && cell.text.trim() ? cell : null;
244
+ });
245
+ const votes = /* @__PURE__ */ new Map();
246
+ for (const h of heads) if (h) for (const [l, r] of headerCuts(h.text.trim())) votes.set(`${l}\0${r}`, (votes.get(`${l}\0${r}`) ?? 0) + 1);
247
+ const [best, second] = [...votes].sort((a, b) => b[1] - a[1]);
248
+ const cut = best && (!second || best[1] > second[1]) ? best[0].split("\0") : null;
249
+ for (const [k, { c, first }] of [...targets.entries()].reverse()) {
250
+ const grown = /* @__PURE__ */ new Set();
251
+ for (let r = 0; r < t.rows; r++) {
252
+ const cell = anchor(r, c);
253
+ let right = { text: "", colSpan: 1, rowSpan: 1 };
254
+ if (cell && (cell.colSpan ?? 1) === 1 && !cell.blocks?.length) {
255
+ const text = cell.text.trim();
256
+ const nv = r >= first ? nameValue(text) : null;
257
+ const head = r === first - 1 && heads[k] === cell && cut && text.replace(/\s+/g, "") === cut.join("") ? cutAt(text, cut[0]) : null;
258
+ if (nv) {
259
+ cell.text = nv.name;
260
+ right = { ...cell, text: nv.value };
261
+ } else if (head) {
262
+ cell.text = head[0];
263
+ right = { ...cell, text: head[1] };
264
+ } else if (r >= first && text && /^[\d,.\s%()+-]+$/.test(text)) {
265
+ right = { ...cell, text };
266
+ cell.text = "";
267
+ } else cell.colSpan = 2;
268
+ grown.add(cell);
269
+ } else if (!grown.has(own[r][c])) {
270
+ own[r][c].colSpan = Math.max(1, own[r][c].colSpan ?? 1) + 1;
271
+ grown.add(own[r][c]);
272
+ }
273
+ t.cells[r].splice(c + 1, 0, right);
274
+ }
275
+ t.cols++;
276
+ }
277
+ return true;
278
+ }
279
+ function splitOcrNameValueColumns(blocks) {
280
+ for (const b of blocks) if (b.type === "table" && b.table) splitTable2(b.table);
281
+ return blocks;
282
+ }
283
+ var INK_LUMA_MAX = 205;
284
+ var DIM_PAPER_LUMA = 225;
285
+ var INK_BG_DELTA = 35;
286
+ var BG_BLOCK_PT = 12;
287
+ var BG_PERCENTILE = 0.8;
288
+ var LIGHT_INK_MIN = 161;
289
+ var FLAT_RADIUS_PT = 1.1;
290
+ var MIN_LINE_LENGTH_PT = 20;
291
+ var BRIDGE_MIN_LENGTH_PT = 6;
292
+ var ROW_DIVIDER_MIN_PT = 17;
293
+ var ROW_DIVIDER_MARGIN_PT = 0.8;
294
+ var BRIDGE_BOX_MIN_PT = 30;
295
+ var MAX_LINE_WIDTH_PT = 2.5;
296
+ var GAP_TOL_PX = 2;
297
+ var BAND_OVERLAP_RATIO = 0.5;
298
+ var SLOPE_TOL = 0.01;
299
+ var SLOPE_MAX_ROW = 0.8;
300
+ var SURROUND_INK_RATIO = 0.35;
301
+ var DOT_MAX_GAP_PT = 1.3;
302
+ var DOT_MAX_DASH_PT = 4;
303
+ var DOT_MAX_PERIOD_PT = 2.2;
304
+ var DOT_MIN_COUNT = 8;
305
+ var DOT_TOUCH_PT = 1.5;
306
+ var DOT_ONE_SIDE_MIN_PT = 60;
307
+ var FILL_DELTA = 10;
308
+ var FILL_MIN_LENGTH_PT = 10;
309
+ var FILL_MIN_DEPTH_PT = 4;
310
+ var FILL_FLAT_TOL = 12;
311
+ var FILL_FLAT_RATIO = 0.8;
312
+ var FILL_DIV_DELTA = 20;
313
+ var FILL_CHAIN_END_PT = 8;
314
+ var FILL_DIV_SIDE = 2;
315
+ var FILL_GAP_PT = 1.5;
316
+ function dimPaperInkMax(luma, width, height, scale) {
317
+ const hist = new Uint32Array(256);
318
+ for (let p = 0; p < luma.length; p++) hist[luma[p]]++;
319
+ let paper = 255;
320
+ for (let v = 0; v < 256; v++) if (hist[v] > hist[paper]) paper = v;
321
+ if (paper >= DIM_PAPER_LUMA) return null;
322
+ const block = Math.max(8, Math.round(BG_BLOCK_PT * scale));
323
+ const bw = Math.ceil(width / block), bh = Math.ceil(height / block);
324
+ const bg = new Uint8Array(bw * bh);
325
+ const h = new Uint32Array(256);
326
+ for (let by = 0; by < bh; by++) {
327
+ for (let bx = 0; bx < bw; bx++) {
328
+ h.fill(0);
329
+ const x0 = bx * block, y0 = by * block, x1 = Math.min(width, x0 + block), y1 = Math.min(height, y0 + block);
330
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) h[luma[y * width + x]]++;
331
+ const want = (x1 - x0) * (y1 - y0) * BG_PERCENTILE;
332
+ let acc = 0, v = 0;
333
+ for (; v < 255; v++) {
334
+ acc += h[v];
335
+ if (acc >= want) break;
336
+ }
337
+ bg[by * bw + bx] = v;
338
+ }
339
+ }
340
+ const out = new Uint8Array(width * height);
341
+ for (let y = 0; y < height; y++) {
342
+ const row = (y / block | 0) * bw;
343
+ for (let x = 0; x < width; x++) out[y * width + x] = Math.max(0, bg[row + (x / block | 0)] - INK_BG_DELTA);
344
+ }
345
+ return out;
346
+ }
347
+ var slopeTol = 0;
348
+ function detectRulingLines(rgba, width, height, scale, opts = {}) {
349
+ const prev = slopeTol;
350
+ slopeTol = opts.slopeTolerant ? SLOPE_TOL : 0;
351
+ try {
352
+ return detectRulingLinesAt(rgba, width, height, scale);
353
+ } finally {
354
+ slopeTol = prev;
355
+ }
356
+ }
357
+ function detectRulingLinesAt(rgba, width, height, scale) {
358
+ const minLenPx = Math.round(MIN_LINE_LENGTH_PT * scale);
359
+ const maxThickPx = Math.max(1, Math.floor(MAX_LINE_WIDTH_PT * scale));
360
+ const ink = new Uint8Array(width * height);
361
+ const luma = new Uint8Array(width * height);
362
+ for (let p = 0, i = 0; p < ink.length; p++, i += 4) {
363
+ const l = rgba[i] * 77 + rgba[i + 1] * 150 + rgba[i + 2] * 29 >> 8;
364
+ luma[p] = l;
365
+ if (l <= INK_LUMA_MAX && rgba[i + 3] >= 128) ink[p] = 1;
366
+ }
367
+ const inkMax = dimPaperInkMax(luma, width, height, scale);
368
+ if (inkMax) {
369
+ for (let p = 0; p < ink.length; p++) if (ink[p] && luma[p] > inkMax[p]) ink[p] = 0;
370
+ }
371
+ const r = Math.max(2, Math.round(FLAT_RADIUS_PT * scale));
372
+ const sum = new Int32Array((width + 1) * (height + 1));
373
+ for (let y = 0; y < height; y++) {
374
+ let row = 0;
375
+ for (let x = 0; x < width; x++) {
376
+ const p = y * width + x;
377
+ if (ink[p] && luma[p] >= LIGHT_INK_MIN) row++;
378
+ sum[(y + 1) * (width + 1) + x + 1] = sum[y * (width + 1) + x + 1] + row;
379
+ }
380
+ }
381
+ const flat = [];
382
+ for (let y = 0; y < height; y++) {
383
+ const y0 = Math.max(0, y - r), y1 = Math.min(height, y + r + 1);
384
+ for (let x = 0; x < width; x++) {
385
+ const p = y * width + x;
386
+ if (!ink[p] || luma[p] < LIGHT_INK_MIN) continue;
387
+ const x0 = Math.max(0, x - r), x1 = Math.min(width, x + r + 1);
388
+ const n = sum[y1 * (width + 1) + x1] - sum[y0 * (width + 1) + x1] - sum[y1 * (width + 1) + x0] + sum[y0 * (width + 1) + x0];
389
+ if (n * 2 > (y1 - y0) * (x1 - x0)) flat.push(p);
390
+ }
391
+ }
392
+ const label = new Int32Array(width * height);
393
+ for (const p of flat) label[p] = -1;
394
+ const stack = [];
395
+ let id = 0;
396
+ const cells = [];
397
+ for (const seed of flat) {
398
+ if (label[seed] !== -1) continue;
399
+ id++;
400
+ const pix = [];
401
+ let y0 = height, y1 = 0;
402
+ label[seed] = id;
403
+ stack.push(seed);
404
+ while (stack.length) {
405
+ const p = stack.pop();
406
+ pix.push(p);
407
+ const y = p / width | 0, x = p - y * width;
408
+ if (y < y0) y0 = y;
409
+ if (y > y1) y1 = y;
410
+ if (x > 0 && label[p - 1] === -1) {
411
+ label[p - 1] = id;
412
+ stack.push(p - 1);
413
+ }
414
+ if (x < width - 1 && label[p + 1] === -1) {
415
+ label[p + 1] = id;
416
+ stack.push(p + 1);
417
+ }
418
+ if (y > 0 && label[p - width] === -1) {
419
+ label[p - width] = id;
420
+ stack.push(p - width);
421
+ }
422
+ if (y < height - 1 && label[p + width] === -1) {
423
+ label[p + width] = id;
424
+ stack.push(p + width);
425
+ }
426
+ }
427
+ const rows2 = y1 - y0 + 1;
428
+ const lo = new Int32Array(rows2).fill(width), hi = new Int32Array(rows2).fill(-1);
429
+ let x0 = width, x1 = 0;
430
+ for (const p of pix) {
431
+ const y = p / width | 0, x = p - y * width;
432
+ if (x < lo[y - y0]) lo[y - y0] = x;
433
+ if (x > hi[y - y0]) hi[y - y0] = x;
434
+ if (x < x0) x0 = x;
435
+ if (x > x1) x1 = x;
436
+ }
437
+ const dark = (q) => ink[q] !== 0 && luma[q] < LIGHT_INK_MIN;
438
+ let walled = 0;
439
+ for (let i = 0; i < rows2; i++) {
440
+ const base2 = (y0 + i) * width;
441
+ let l = false, rr = false;
442
+ for (let d = 1; d <= r && lo[i] - d >= 0 && !l; d++) l = dark(base2 + lo[i] - d);
443
+ for (let d = 1; d <= r && hi[i] + d < width && !rr; d++) rr = dark(base2 + hi[i] + d);
444
+ if (l && rr) walled++;
445
+ }
446
+ if (walled < rows2 * 0.8 || pix.length < rows2 * (x1 - x0 + 1) * 0.7) continue;
447
+ const mid = rows2 >> 1, base = (y0 + mid) * width;
448
+ let runs = false;
449
+ for (const dir of [-1, 1]) {
450
+ let x = dir < 0 ? lo[mid] : hi[mid];
451
+ let d = 1;
452
+ while (d <= r && x + dir * d >= 0 && x + dir * d < width && !dark(base + x + dir * d)) d++;
453
+ if (d > r || x + dir * d < 0 || x + dir * d >= width) continue;
454
+ x += dir * d;
455
+ for (const [from, step] of [[y0 - 1, -1], [y1 + 1, 1]]) {
456
+ let n = 0;
457
+ for (let y = from; y >= 0 && y < height && n <= 4 * r; y += step) {
458
+ const q = y * width + x;
459
+ if (!(dark(q) || x > 0 && dark(q - 1) || x < width - 1 && dark(q + 1))) break;
460
+ n++;
461
+ }
462
+ if (n > 4 * r) runs = true;
463
+ }
464
+ }
465
+ cells.push({ pix, x0, x1, y0, y1, runs });
466
+ }
467
+ const gap = 3 * r;
468
+ const touch = (a, b) => {
469
+ const ov = (p0, p1, q0, q1) => Math.min(p1, q1) - Math.max(p0, q0);
470
+ const side = (p0, p1, q0, q1) => q0 > p1 ? q0 - p1 : p0 - q1;
471
+ const yo = ov(a.y0, a.y1, b.y0, b.y1), xo = ov(a.x0, a.x1, b.x0, b.x1);
472
+ const hg = side(a.x0, a.x1, b.x0, b.x1), vg = side(a.y0, a.y1, b.y0, b.y1);
473
+ return hg > 0 && hg <= gap && yo >= Math.min(a.y1 - a.y0, b.y1 - b.y0) * 0.5 || vg > 0 && vg <= gap && xo >= Math.min(a.x1 - a.x0, b.x1 - b.x0) * 0.5;
474
+ };
475
+ for (const c of cells) {
476
+ if (c.runs || cells.some((o) => o !== c && touch(c, o))) for (const p of c.pix) ink[p] = 0;
477
+ }
478
+ const gapTol = Math.max(1, Math.round(GAP_TOL_PX * scale / 3));
479
+ const solid = (m, base, step, span) => solidRuns(m, base, step, span, minLenPx, gapTol);
480
+ const dot = {
481
+ maxGap: Math.max(2, Math.round(DOT_MAX_GAP_PT * scale)),
482
+ maxDash: Math.max(2, Math.round(DOT_MAX_DASH_PT * scale)),
483
+ maxPeriod: DOT_MAX_PERIOD_PT * scale
484
+ };
485
+ const dotted = (m, base, step, span) => dottedRuns(m, base, step, span, minLenPx, dot.maxGap, dot.maxDash, dot.maxPeriod);
486
+ const horizontals = detectBands(ink, width, height, maxThickPx, false, solid);
487
+ const filledAt = (x, h) => {
488
+ const yt = Math.round(h.y1 - h.thicknessPx / 2) - 2, yb = Math.round(h.y1 + h.thicknessPx / 2) + 2;
489
+ return yt >= 0 && yb < height && ink[yt * width + x] === 1 && ink[yb * width + x] === 1;
490
+ };
491
+ const trimFilled = (h) => {
492
+ let x1 = Math.round(h.x1), x2 = Math.round(h.x2);
493
+ while (x1 < x2 && filledAt(x1, h)) x1++;
494
+ while (x2 > x1 && filledAt(x2, h)) x2--;
495
+ return x2 - x1 + 1 >= minLenPx ? { ...h, x1, x2, isolated: true } : null;
496
+ };
497
+ const hAdd = detectBands(ink, width, height, maxThickPx, false, solid, true).map(trimFilled).filter((h) => h !== null).filter((h) => !horizontals.some((p) => Math.abs(p.y1 - h.y1) <= maxThickPx && Math.min(p.x2, h.x2) - Math.max(p.x1, h.x1) > (h.x2 - h.x1) * 0.5));
498
+ const baseH = horizontals.length;
499
+ horizontals.push(...hAdd);
500
+ const verticals = detectBands(ink, width, height, maxThickPx, true, solid);
501
+ const faint = (x, y) => {
502
+ const l = luma[y * width + x];
503
+ return l > INK_LUMA_MAX && l <= 230 && x >= 3 && x + 3 < width && l + 20 <= Math.min(luma[y * width + x - 3], luma[y * width + x + 3]);
504
+ };
505
+ for (const v of verticals) {
506
+ const xs = [Math.round(v.x1) - 1, Math.round(v.x1), Math.round(v.x1) + 1];
507
+ const cross = (y) => xs.some((x) => x >= 3 && x + 3 < width && luma[y * width + x] <= INK_LUMA_MAX && luma[y * width + x - 3] <= INK_LUMA_MAX && luma[y * width + x + 3] <= INK_LUMA_MAX);
508
+ const at = (y) => xs.some((x) => faint(x, y));
509
+ for (const dir of [1, -1]) {
510
+ let y = dir > 0 ? Math.round(v.y2) + 1 : Math.round(v.y1) - 1, end = y - dir, gap2 = 0;
511
+ while (y >= 0 && y < height && gap2 <= GAP_TOL_PX) {
512
+ if (at(y)) {
513
+ end = y;
514
+ gap2 = 0;
515
+ } else if (!cross(y)) gap2++;
516
+ y += dir;
517
+ }
518
+ if (Math.abs(end - (dir > 0 ? v.y2 : v.y1)) < minLenPx) continue;
519
+ if (!horizontals.some((h) => Math.abs(h.y1 - end) <= maxThickPx * 2 && h.x1 <= v.x1 + maxThickPx && h.x2 >= v.x1 - maxThickPx)) continue;
520
+ if (!verticals.some((o) => o !== v && Math.abs((dir > 0 ? o.y2 : o.y1) - end) <= maxThickPx * 2)) continue;
521
+ if (dir > 0) v.y2 = end;
522
+ else v.y1 = end;
523
+ }
524
+ }
525
+ const meets = (h) => new Set(verticals.filter((v) => v.x1 >= h.x1 - maxThickPx && v.x1 <= h.x2 + maxThickPx && h.y1 >= v.y1 - maxThickPx && h.y1 <= v.y2 + maxThickPx).map((v) => Math.round(v.x1 / 4))).size >= 2;
526
+ horizontals.splice(baseH, hAdd.length, ...hAdd.filter((h) => h.thicknessPx <= 3 && meets(h)));
527
+ const dotH = detectBands(ink, width, height, maxThickPx, false, dotted);
528
+ const dotV = detectBands(ink, width, height, maxThickPx, true, dotted);
529
+ const tol = Math.max(2, Math.round(DOT_TOUCH_PT * scale));
530
+ const bridgeMin = Math.max(2, Math.round(BRIDGE_MIN_LENGTH_PT * scale));
531
+ const endsOn = (x, y) => horizontals.filter((h) => Math.abs(h.y1 - y) <= tol + h.thicknessPx && h.x1 - tol <= x && h.x2 + tol >= x);
532
+ const sides = (x, y1, y2) => verticals.some((p) => Math.abs(p.x1 - x) <= tol && p.y1 <= y1 + tol && p.y2 >= y2 - tol);
533
+ const boxMin = BRIDGE_BOX_MIN_PT * scale;
534
+ const endsAt = (x, y) => verticals.some((p) => Math.abs(p.x1 - x) <= tol && Math.abs(p.y2 - y) <= tol * 2 && p.y1 < y - tol);
535
+ const startsAt = (x, y) => verticals.some((p) => Math.abs(p.x1 - x) <= tol && Math.abs(p.y1 - y) <= tol * 2 && p.y2 > y + tol);
536
+ const sameSpan = (a, b, x) => a.some((p) => b.some((q) => Math.abs(p.x1 - q.x1) <= tol && Math.abs(p.x2 - q.x2) <= tol && p.x2 - p.x1 >= boxMin && Math.abs(x - (p.x1 + p.x2) / 2) <= (p.x2 - p.x1) * 0.25 && !sides(p.x1, p.y1, q.y1) && !sides(p.x2, p.y1, q.y1) && endsAt(p.x1, p.y1) && endsAt(p.x2, p.y1) && startsAt(q.x1, q.y1) && startsAt(q.x2, q.y1)));
537
+ const shortV = detectBands(ink, width, height, maxThickPx, true, (m, base, step, span) => solidRuns(m, base, step, span, bridgeMin)).filter((v) => v.y2 - v.y1 + 1 < minLenPx);
538
+ const long = verticals.filter((p) => p.y2 - p.y1 + 1 >= minLenPx);
539
+ const inside = (x, y) => endsOn(x, y).some((h) => h.x1 < x - 3 * tol && h.x2 > x + 3 * tol);
540
+ for (const v of shortV) {
541
+ const column = inside(v.x1, v.y1) && inside(v.x1, v.y2) && long.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y2 <= v.y1 + tol) && long.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y1 >= v.y2 - tol);
542
+ if (!column && !sameSpan(endsOn(v.x1, v.y1), endsOn(v.x1, v.y2), v.x1)) continue;
543
+ if (!verticals.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y1 <= v.y1 + tol && p.y2 >= v.y2 - tol)) verticals.push(v);
544
+ }
545
+ const allH = [...horizontals, ...dotH], allV = [...verticals, ...dotV];
546
+ const touchesV = (a) => allV.some((p) => p.x1 >= a.x1 - tol && p.x1 <= a.x2 + tol && a.y1 >= p.y1 - tol && a.y1 <= p.y2 + tol);
547
+ const touchesH = (a) => allH.some((p) => p.y1 >= a.y1 - tol && p.y1 <= a.y2 + tol && a.x1 >= p.x1 - tol && a.x1 <= p.x2 + tol);
548
+ const crossesV = (a) => new Set(allV.filter((p) => p.x1 >= a.x1 - tol && p.x1 <= a.x2 + tol && a.y1 >= p.y1 - tol && a.y1 <= p.y2 + tol).map((p) => Math.round(p.x1 / tol))).size >= 2;
549
+ const oneSideMin = DOT_ONE_SIDE_MIN_PT * scale;
550
+ horizontals.push(...dotH.filter((a) => crossesV(a) || a.x2 - a.x1 >= oneSideMin && touchesV(a)));
551
+ verticals.push(...dotV.filter(touchesH));
552
+ const inkV = [...verticals];
553
+ const ruleH = horizontals.filter((p) => inkV.some((v) => v.x1 >= p.x1 - tol && v.x1 <= p.x2 + tol && p.y1 >= v.y1 - tol && p.y1 <= v.y2 + tol));
554
+ const fill = fillEdges(luma, width, height, scale);
555
+ const fillH = fill.horizontals.filter((a) => ruleH.some((p) => Math.abs(p.x1 - a.x1) <= tol && Math.abs(p.x2 - a.x2) <= tol));
556
+ const rows = /* @__PURE__ */ new Map();
557
+ for (const a of fill.horizontals) if (!fillH.includes(a)) (rows.get(Math.round(a.y1)) ?? rows.set(Math.round(a.y1), []).get(Math.round(a.y1))).push(a);
558
+ const chainEnd = Math.round(FILL_CHAIN_END_PT * scale);
559
+ for (const [y, segs] of rows) {
560
+ for (const p of ruleH) {
561
+ const inside2 = segs.filter((a) => a.x1 >= p.x1 - tol && a.x2 <= p.x2 + tol);
562
+ if (inside2.length < 2 || fillH.some((f) => Math.abs(f.y1 - y) <= tol && f.x1 <= p.x1 + tol && f.x2 >= p.x2 - tol)) continue;
563
+ const lo = Math.min(...inside2.map((a) => a.x1)), hi = Math.max(...inside2.map((a) => a.x2));
564
+ const cover = inside2.reduce((n, a) => n + a.x2 - a.x1, 0);
565
+ if (lo - p.x1 <= chainEnd && p.x2 - hi <= chainEnd && cover >= (p.x2 - p.x1) * 0.5) fillH.push({ ...inside2[0], x1: p.x1, x2: p.x2 });
566
+ }
567
+ }
568
+ for (const a of fill.horizontals) {
569
+ if (fillH.some((f) => f === a || Math.abs(f.y1 - a.y1) <= tol && f.x1 <= a.x1 + tol && f.x2 >= a.x2 - tol)) continue;
570
+ const p = ruleH.find((p2) => (Math.abs(p2.x1 - a.x1) <= tol || Math.abs(p2.x2 - a.x2) <= tol) && a.x1 >= p2.x1 - tol && a.x2 <= p2.x2 + tol && a.x2 - a.x1 >= (p2.x2 - p2.x1) * 0.7);
571
+ if (!p || ruleH.some((q) => Math.abs(q.y1 - a.y1) <= tol)) continue;
572
+ const loose = Math.abs(p.x1 - a.x1) <= tol ? a.x2 : a.x1;
573
+ const depthPx = Math.round(FILL_MIN_DEPTH_PT * scale);
574
+ if (fill.verticals.some((v) => Math.abs(v.x1 - loose) <= tol * 2 && Math.abs(v.y1 - a.y1) <= tol * 2 && v.y2 - v.y1 >= depthPx * 4)) fillH.push({ ...a, x1: p.x1, x2: p.x2 });
575
+ }
576
+ const fillGap = Math.max(2, Math.round(FILL_GAP_PT * scale));
577
+ const sideV = [...inkV, ...fill.verticals];
578
+ const onV = (x, y) => sideV.some((v) => Math.abs(v.x1 - x) <= tol * 2 && v.y1 <= y + tol * 2 && v.y2 >= y - tol * 2);
579
+ for (const a of fill.horizontals) {
580
+ const b = fill.horizontals.find((b2) => b2 !== a && b2.y1 > a.y1 && b2.y1 - a.y1 <= fillGap * 2 && Math.abs(b2.x1 - a.x1) <= tol && Math.abs(b2.x2 - a.x2) <= tol);
581
+ if (!b || a.x2 - a.x1 < tol * 4) continue;
582
+ const y = (a.y1 + b.y1) / 2;
583
+ if (!onV(a.x1, y) || !onV(a.x2, y) || horizontals.some((h) => Math.abs(h.y1 - y) <= tol && h.x1 <= a.x1 + tol && h.x2 >= a.x2 - tol)) continue;
584
+ const p = ruleH.find((p2) => Math.abs(p2.y1 - y) <= fillGap && (Math.abs(p2.x1 - a.x2) <= tol * 3 || Math.abs(a.x1 - p2.x2) <= tol * 3));
585
+ horizontals.push(p ? { ...p, x1: Math.min(a.x1, p.x1), x2: Math.max(a.x2, p.x2) } : { x1: a.x1, y1: y, x2: a.x2, y2: y, thicknessPx: 1 });
586
+ }
587
+ for (const p of ruleH) {
588
+ for (const side of [-1, 1]) {
589
+ const end = side < 0 ? p.x1 : p.x2;
590
+ const a = fill.horizontals.find((a2) => Math.abs(a2.y1 - p.y1) <= fillGap && Math.abs((side < 0 ? a2.x2 : a2.x1) - end) <= tol * 3 && a2.x2 - a2.x1 >= tol * 4);
591
+ if (!a) continue;
592
+ const far = side < 0 ? a.x1 : a.x2;
593
+ if (!onV(far, p.y1) || horizontals.some((h) => Math.abs(h.y1 - p.y1) <= tol && h.x1 <= Math.min(far, end) + tol && h.x2 >= Math.max(far, end) - tol)) continue;
594
+ horizontals.push({ ...p, x1: Math.min(far, p.x1), x2: Math.max(far, p.x2) });
595
+ }
596
+ }
597
+ horizontals.push(...fillH);
598
+ const edgeH = [...ruleH, ...fillH];
599
+ const depth = Math.round(FILL_MIN_DEPTH_PT * scale);
600
+ for (const a of fill.verticals) {
601
+ const col = inkV.find((p) => Math.abs(p.x1 - a.x1) <= tol && p.y1 <= a.y2 + tol * 2 && p.y2 >= a.y1 - tol * 2);
602
+ if (col) {
603
+ const top = edgeH.filter((h) => h.x1 <= a.x1 + tol && h.x2 >= a.x1 - tol && h.y1 < a.y1 && h.y1 >= a.y1 - depth);
604
+ verticals.push({ ...a, y1: top.length ? Math.min(...top.map((h) => h.y1)) : a.y1 });
605
+ } else if (edgeH.some((p) => (Math.abs(p.x1 - a.x1) <= tol || Math.abs(p.x2 - a.x1) <= tol) && p.y1 >= a.y1 - tol && p.y1 <= a.y2 + tol)) verticals.push(a);
606
+ else if ([a.y1, a.y2].every((y) => edgeH.some((p) => Math.abs(p.y1 - y) <= tol * 2 && p.x1 < a.x1 - tol && p.x2 > a.x1 + tol)) && ruleH.some((p) => p.y1 > a.y1 + tol * 2 && p.y1 < a.y2 - tol * 2 && p.x1 < a.x1 - tol && p.x2 > a.x1 + tol)) verticals.push(a);
607
+ }
608
+ for (const v of shortV) {
609
+ if (!endsOn(v.x1, v.y1).length || !endsOn(v.x1, v.y2).length) continue;
610
+ if (!verticals.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y1 >= v.y2 - tol && p.y1 <= v.y2 + tol * 3 && p.y2 - p.y1 + 1 >= minLenPx)) continue;
611
+ if (!verticals.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y1 <= v.y1 + tol && p.y2 >= v.y2 - tol)) verticals.push(v);
612
+ }
613
+ const rowMin = Math.round(ROW_DIVIDER_MIN_PT * scale);
614
+ const margin = Math.max(2, Math.round(ROW_DIVIDER_MARGIN_PT * scale));
615
+ const spans = (x, y1, y2) => (p) => p.y1 <= y1 + tol && p.y2 >= y2 - tol && p.x1 !== x;
616
+ const clearSide = (v, dir) => {
617
+ const half = Math.ceil(v.thicknessPx / 2) + 1;
618
+ let inked = 0, total = 0;
619
+ for (let y = v.y1 + tol; y <= v.y2 - tol; y++) for (let d = half; d < half + margin; d++) {
620
+ const x = Math.round(v.x1) + dir * d;
621
+ if (x < 0 || x >= width) continue;
622
+ total++;
623
+ inked += ink[y * width + x];
624
+ }
625
+ return total > 0 && inked <= total * 0.05;
626
+ };
627
+ const inkMin = Math.max(4, Math.round(scale * scale * 2));
628
+ const inkBetween = (x1, x2, y1, y2) => {
629
+ let n = 0;
630
+ for (let y = Math.max(0, y1); y <= Math.min(height - 1, y2); y++) for (let x = Math.max(0, Math.round(x1)); x <= Math.min(width - 1, Math.round(x2)); x++) n += ink[y * width + x];
631
+ return n >= inkMin;
632
+ };
633
+ for (const v of shortV) {
634
+ if (v.y2 - v.y1 + 1 < rowMin || verticals.includes(v)) continue;
635
+ const solidAcross = (h) => !dotH.includes(h) && h.x1 < v.x1 - tol * 2 && h.x2 > v.x1 + tol * 2;
636
+ const top = endsOn(v.x1, v.y1).filter((h) => solidAcross(h) && v.y1 <= h.y1 + 1);
637
+ const bot = endsOn(v.x1, v.y2).filter((h) => solidAcross(h) && v.y2 >= h.y1 - 1);
638
+ if (!top.length || !bot.length || !clearSide(v, -1) || !clearSide(v, 1)) continue;
639
+ const enclose = verticals.filter(spans(v.x1, v.y1, v.y2));
640
+ const left = enclose.filter((p) => p.x1 < v.x1 - tol).reduce((a, p) => !a || p.x1 > a.x1 ? p : a, null);
641
+ const right = enclose.filter((p) => p.x1 > v.x1 + tol).reduce((a, p) => !a || p.x1 < a.x1 ? p : a, null);
642
+ if (!left || !right) continue;
643
+ if (!inkBetween(left.x1 + margin * 2, v.x1 - margin * 2, v.y1 + tol, v.y2 - tol) || !inkBetween(v.x1 + margin * 2, right.x1 - margin * 2, v.y1 + tol, v.y2 - tol)) continue;
644
+ if (!verticals.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y1 <= v.y1 + tol && p.y2 >= v.y2 - tol)) verticals.push(v);
645
+ }
646
+ const cellDividers = [];
647
+ const frames = [];
648
+ for (let i = 0; i < horizontals.length && frames.length < 32; i++) {
649
+ const a = horizontals[i];
650
+ for (let j = i + 1; j < horizontals.length && frames.length < 32; j++) {
651
+ const b = horizontals[j];
652
+ if (Math.abs(a.x1 - b.x1) > tol || Math.abs(a.x2 - b.x2) > tol) continue;
653
+ const y1 = Math.min(a.y1, b.y1), y2 = Math.max(a.y1, b.y1);
654
+ if (a.x2 - a.x1 < minLenPx * 3 || y2 - y1 < minLenPx * 2) continue;
655
+ if (![a.x1, a.x2].every((x) => verticals.some((v) => Math.abs(v.x1 - x) <= tol && v.y1 <= y1 + tol && v.y2 >= y2 - tol))) continue;
656
+ frames.push({ x1: a.x1, x2: a.x2, y1, y2 });
657
+ }
658
+ }
659
+ for (const a of horizontals) {
660
+ if (frames.length >= 32 || a.x2 - a.x1 < minLenPx * 3) continue;
661
+ const same = horizontals.filter((b) => Math.abs(a.x1 - b.x1) <= tol && Math.abs(a.x2 - b.x2) <= tol);
662
+ for (const v of inkV) {
663
+ if (v.x1 <= a.x1 + tol || v.x1 >= a.x2 - tol || Math.abs(v.y1 - a.y1) > tol) continue;
664
+ const b = same.find((h) => Math.abs(h.y1 - v.y2) <= tol);
665
+ if (!b || b.y1 - a.y1 < minLenPx * 2 || same.filter((h) => h.y1 >= a.y1 - tol && h.y1 <= b.y1 + tol).length < 4) continue;
666
+ if (!frames.some((f) => Math.abs(f.y1 - a.y1) <= tol && Math.abs(f.y2 - b.y1) <= tol)) frames.push({ x1: a.x1, x2: a.x2, y1: a.y1, y2: b.y1, open: true });
667
+ break;
668
+ }
669
+ }
670
+ if (frames.length) {
671
+ const faint2 = new Uint8Array(ink.length);
672
+ for (let p = 0; p < faint2.length; p++) if (luma[p] <= 240 && rgba[p * 4 + 3] >= 128) faint2[p] = 1;
673
+ const hs = detectBands(faint2, width, height, maxThickPx, false, solid);
674
+ const vs = detectBands(faint2, width, height, maxThickPx, true, solid);
675
+ const faintCol = new Uint8Array(ink.length);
676
+ for (let p = 0; p < faint2.length; p++) {
677
+ const x = p % width;
678
+ if (faint2[p] && x >= 3 && x + 3 < width && luma[p] + 12 <= Math.min(luma[p - 3], luma[p + 3])) faintCol[p] = 1;
679
+ }
680
+ const vsOpen = frames.some((f) => f.open) ? detectBands(faintCol, width, height, maxThickPx, true, solid) : [];
681
+ for (const f of frames) {
682
+ const colAt = (x) => inkV.some((v) => Math.abs(v.x1 - x) <= tol && v.y1 <= f.y1 + tol && v.y2 >= f.y2 - tol);
683
+ const endsAtEdge = (h) => f.open ? (Math.abs(h.x1 - f.x1) <= tol || colAt(h.x1)) && (Math.abs(h.x2 - f.x2) <= tol || colAt(h.x2)) : Math.abs(h.x1 - f.x1) <= tol && Math.abs(h.x2 - f.x2) <= tol;
684
+ const innerH = hs.filter((h) => h.y1 > f.y1 + tol && h.y1 < f.y2 - tol && endsAtEdge(h));
685
+ const innerV = (f.open ? vsOpen : vs).filter((v) => v.x1 > f.x1 + tol && v.x1 < f.x2 - tol && Math.abs(v.y1 - f.y1) <= tol && Math.abs(v.y2 - f.y2) <= tol);
686
+ const darkV = inkV.some((v) => v.x1 > f.x1 + tol && v.x1 < f.x2 - tol && v.y1 <= f.y1 + tol && v.y2 >= f.y2 - tol);
687
+ if (innerH.length < 3 || innerV.length < 1 && !darkV) continue;
688
+ for (const h of innerH) if (!horizontals.some((p) => Math.abs(p.y1 - h.y1) <= tol && p.x1 <= h.x1 + tol && p.x2 >= h.x2 - tol)) horizontals.push(h);
689
+ for (const v of innerV) if (!verticals.some((p) => Math.abs(p.x1 - v.x1) <= tol && p.y1 <= v.y1 + tol && p.y2 >= v.y2 - tol)) {
690
+ verticals.push(v);
691
+ cellDividers.push(v);
692
+ }
693
+ }
694
+ }
695
+ return { horizontals, verticals, ...cellDividers.length ? { cellDividers } : {} };
696
+ }
697
+ function fillEdges(pageLuma, width, height, scale) {
698
+ const k = Math.max(1, Math.round(scale));
699
+ const w = Math.floor(width / k), h = Math.floor(height / k), n = w * h;
700
+ const luma = new Uint8Array(n);
701
+ const hist = new Uint32Array(256);
702
+ for (let y = 0; y < h; y++) {
703
+ for (let x = 0; x < w; x++) {
704
+ let mx = 0;
705
+ for (let by = 0; by < k; by++) {
706
+ let i = (y * k + by) * width + x * k;
707
+ for (let bx = 0; bx < k; bx++, i++) if (pageLuma[i] > mx) mx = pageLuma[i];
708
+ }
709
+ luma[y * w + x] = mx;
710
+ hist[mx]++;
711
+ }
712
+ }
713
+ let bg = 255;
714
+ for (let v = 0; v < 256; v++) if (hist[v] > hist[bg]) bg = v;
715
+ const tint = new Uint8Array(n);
716
+ for (let p = 0; p < n; p++) if (luma[p] < bg - FILL_DELTA) tint[p] = 1;
717
+ const depth = Math.max(2, Math.round(FILL_MIN_DEPTH_PT * scale / k));
718
+ const minLen = Math.round(FILL_MIN_LENGTH_PT * scale / k);
719
+ const solid = (m, base, step, span) => solidRuns(m, base, step, span, minLen);
720
+ const run = new Uint16Array(n);
721
+ const mask = new Uint8Array(n);
722
+ const out = { horizontals: [], verticals: [] };
723
+ for (const [dx, dy] of [[0, 1], [0, -1], [1, 0], [-1, 0]]) {
724
+ const step = dy * w + dx;
725
+ const ys = dy > 0 ? [h - 1, -1, -1] : [0, h, 1];
726
+ const xs = dx > 0 ? [w - 1, -1, -1] : [0, w, 1];
727
+ for (let y = ys[0]; y !== ys[1]; y += ys[2]) {
728
+ for (let x = xs[0]; x !== xs[1]; x += xs[2]) {
729
+ const p = y * w + x;
730
+ const nx = x + dx, ny = y + dy;
731
+ run[p] = tint[p] ? nx >= 0 && nx < w && ny >= 0 && ny < h ? Math.min(65535, run[p + step] + 1) : 1 : 0;
732
+ }
733
+ }
734
+ mask.fill(0);
735
+ for (let y = 0; y < h; y++) {
736
+ for (let x = 0; x < w; x++) {
737
+ const p = y * w + x;
738
+ if (run[p] < depth) continue;
739
+ const ox = x - dx, oy = y - dy;
740
+ if (ox < 0 || oy < 0 || ox >= w || oy >= h || !tint[p - step]) mask[p] = 1;
741
+ }
742
+ }
743
+ const vertical = dx !== 0;
744
+ const flat = (s) => {
745
+ const d = depth >> 1;
746
+ const vals = [];
747
+ if (vertical) {
748
+ const x = Math.round(s.x1) + dx * d;
749
+ for (let y = Math.round(s.y1); y <= s.y2; y++) if (x >= 0 && x < w) vals.push(luma[y * w + x]);
750
+ } else {
751
+ const y = Math.round(s.y1) + dy * d;
752
+ for (let x = Math.round(s.x1); x <= s.x2; x++) if (y >= 0 && y < h) vals.push(luma[y * w + x]);
753
+ }
754
+ if (!vals.length) return false;
755
+ const med = [...vals].sort((a, b) => a - b)[vals.length >> 1];
756
+ return vals.filter((v) => Math.abs(v - med) <= FILL_FLAT_TOL).length >= vals.length * FILL_FLAT_RATIO;
757
+ };
758
+ for (const s of detectBands(mask, w, h, 1, vertical, solid)) {
759
+ if (!flat(s)) continue;
760
+ const c2 = (v) => v * k + (k - 1) / 2;
761
+ (vertical ? out.verticals : out.horizontals).push({ x1: c2(s.x1), y1: c2(s.y1), x2: c2(s.x2), y2: c2(s.y2), thicknessPx: 1 });
762
+ }
763
+ }
764
+ const div = new Uint8Array(n);
765
+ for (let y = 0; y < h; y++) {
766
+ for (let x = FILL_DIV_SIDE; x < w - FILL_DIV_SIDE; x++) {
767
+ const p = y * w + x, l = p - FILL_DIV_SIDE, r = p + FILL_DIV_SIDE;
768
+ if (tint[l] && tint[r] && luma[p] >= Math.max(luma[l], luma[r]) + FILL_DIV_DELTA) div[p] = 1;
769
+ }
770
+ }
771
+ const c = (v) => v * k + (k - 1) / 2;
772
+ for (const s of detectBands(div, w, h, 1, true, solid)) out.verticals.push({ x1: c(s.x1), y1: c(s.y1), x2: c(s.x2), y2: c(s.y2), thicknessPx: 1 });
773
+ return out;
774
+ }
775
+ function solidRuns(mask, base, step, span, minLenPx, gapTol = GAP_TOL_PX) {
776
+ const runs = [];
777
+ let runStart = -1;
778
+ let gap = 0;
779
+ for (let pos = 0; pos <= span; pos++) {
780
+ const on = pos < span && mask[base + pos * step] === 1;
781
+ if (on) {
782
+ if (runStart < 0) runStart = pos;
783
+ gap = 0;
784
+ } else if (runStart >= 0) {
785
+ if (++gap > gapTol || pos >= span) {
786
+ const hi = pos - gap;
787
+ if (hi - runStart + 1 >= minLenPx) runs.push({ lo: runStart, hi });
788
+ runStart = -1;
789
+ gap = 0;
790
+ }
791
+ }
792
+ }
793
+ return runs;
794
+ }
795
+ function dottedRuns(mask, base, step, span, minLenPx, maxGap, maxDash, maxPeriod) {
796
+ const runs = [];
797
+ const chain = [];
798
+ const median2 = (xs) => xs.sort((a, b) => a - b)[xs.length >> 1];
799
+ const flush = () => {
800
+ const cnt = chain.length >> 1;
801
+ if (cnt >= DOT_MIN_COUNT && chain[chain.length - 1] - chain[0] + 1 >= minLenPx) {
802
+ const periods = [], dashes2 = [], gaps2 = [];
803
+ for (let k = 0; k < cnt; k++) {
804
+ dashes2.push(chain[2 * k + 1] - chain[2 * k] + 1);
805
+ if (k) {
806
+ periods.push(chain[2 * k] - chain[2 * k - 2]);
807
+ gaps2.push(chain[2 * k] - chain[2 * k - 1] - 1);
808
+ }
809
+ }
810
+ if (median2(periods) <= maxPeriod || median2(dashes2) >= 1.5 * median2(gaps2)) runs.push({ lo: chain[0], hi: chain[chain.length - 1] });
811
+ }
812
+ chain.length = 0;
813
+ };
814
+ let s = -1;
815
+ for (let pos = 0; pos <= span; pos++) {
816
+ const on = pos < span && mask[base + pos * step] === 1;
817
+ if (on) {
818
+ if (s < 0) s = pos;
819
+ continue;
820
+ }
821
+ if (s < 0) continue;
822
+ const lo = s, hi = pos - 1;
823
+ s = -1;
824
+ if (hi - lo + 1 > maxDash) {
825
+ flush();
826
+ continue;
827
+ }
828
+ if (chain.length && lo - chain[chain.length - 1] - 1 > maxGap) flush();
829
+ chain.push(lo, hi);
830
+ }
831
+ flush();
832
+ return runs;
833
+ }
834
+ function detectBands(ink, width, height, maxThickPx, transpose, readRuns, prevRun = false) {
835
+ const lines = transpose ? width : height;
836
+ const span = transpose ? height : width;
837
+ const step = transpose ? width : 1;
838
+ const baseOf = (line) => transpose ? line : line * width;
839
+ const out = [];
840
+ let open = [];
841
+ const surroundInkRatio = (b, side) => {
842
+ if (side < 0 || side >= lines) return 0;
843
+ let dark = 0, total = 0;
844
+ const base = baseOf(side);
845
+ for (let pos = b.lo; pos <= b.hi; pos += 3) {
846
+ total++;
847
+ if (ink[base + pos * step] === 1) dark++;
848
+ }
849
+ return total > 0 ? dark / total : 0;
850
+ };
851
+ const emit = (b) => {
852
+ const span2 = b.hi - b.lo + 1;
853
+ const height2 = b.last - b.first + 1;
854
+ const areaThick = Math.ceil(b.area / span2);
855
+ const sloped = slopeTol > 0 && height2 > maxThickPx && height2 <= maxThickPx + span2 * slopeTol && b.maxRun < span2 * SLOPE_MAX_ROW;
856
+ const thick = sloped ? areaThick : height2;
857
+ if (thick > maxThickPx) return;
858
+ if (prevRun && (surroundInkRatio(b, b.first - 2) >= SURROUND_INK_RATIO || surroundInkRatio(b, b.last + 2) >= SURROUND_INK_RATIO)) return;
859
+ if (surroundInkRatio(b, b.first - 2) >= SURROUND_INK_RATIO && surroundInkRatio(b, b.last + 2) >= SURROUND_INK_RATIO) return;
860
+ const center = (b.first + b.last) / 2;
861
+ out.push(
862
+ transpose ? { x1: center, y1: b.lo, x2: center, y2: b.hi, thicknessPx: thick } : { x1: b.lo, y1: center, x2: b.hi, y2: center, thicknessPx: thick }
863
+ );
864
+ };
865
+ for (let line = 0; line < lines; line++) {
866
+ const runs = readRuns(ink, baseOf(line), step, span);
867
+ const next = [];
868
+ const used = /* @__PURE__ */ new Set();
869
+ for (const band of open) {
870
+ if (band.last !== line - 1) {
871
+ emit(band);
872
+ continue;
873
+ }
874
+ let merged = false;
875
+ for (let r = 0; r < runs.length; r++) {
876
+ if (used.has(r)) continue;
877
+ const run = runs[r];
878
+ const lo = prevRun ? band.plo : band.lo, hi = prevRun ? band.phi : band.hi;
879
+ const overlap = Math.min(hi, run.hi) - Math.max(lo, run.lo) + 1;
880
+ const prevLen = hi - lo + 1, runLen = run.hi - run.lo + 1;
881
+ const shorter = Math.min(prevLen, runLen);
882
+ if (overlap >= shorter * BAND_OVERLAP_RATIO && (!prevRun || shorter * 2 >= Math.max(prevLen, runLen))) {
883
+ band.lo = Math.min(band.lo, run.lo);
884
+ band.hi = Math.max(band.hi, run.hi);
885
+ band.plo = run.lo;
886
+ band.phi = run.hi;
887
+ band.area += run.hi - run.lo + 1;
888
+ band.maxRun = Math.max(band.maxRun, run.hi - run.lo + 1);
889
+ band.last = line;
890
+ next.push(band);
891
+ used.add(r);
892
+ merged = true;
893
+ break;
894
+ }
895
+ }
896
+ if (!merged) emit(band);
897
+ }
898
+ for (let r = 0; r < runs.length; r++) {
899
+ if (!used.has(r)) next.push({ lo: runs[r].lo, hi: runs[r].hi, first: line, last: line, plo: runs[r].lo, phi: runs[r].hi, area: runs[r].hi - runs[r].lo + 1, maxRun: runs[r].hi - runs[r].lo + 1 });
900
+ }
901
+ open = next;
902
+ }
903
+ for (const band of open) emit(band);
904
+ return out;
905
+ }
906
+ function rulingToPdfLines(ruling, scale, pdfHeight) {
907
+ const horizontals = ruling.horizontals.map((s) => {
908
+ const y = pdfHeight - (s.y1 + s.y2) / 2 / scale;
909
+ return {
910
+ x1: Math.min(s.x1, s.x2) / scale,
911
+ y1: y,
912
+ x2: Math.max(s.x1, s.x2) / scale,
913
+ y2: y,
914
+ lineWidth: s.thicknessPx / scale
915
+ };
916
+ });
917
+ const verticals = ruling.verticals.map((s) => {
918
+ const x = (s.x1 + s.x2) / 2 / scale;
919
+ const yA = pdfHeight - Math.max(s.y1, s.y2) / scale;
920
+ const yB = pdfHeight - Math.min(s.y1, s.y2) / scale;
921
+ return { x1: x, y1: yA, x2: x, y2: yB, lineWidth: s.thicknessPx / scale };
922
+ });
923
+ return { horizontals, verticals };
924
+ }
925
+ var INKLESS_DELTA = 32;
926
+ function ringAsks(rgba, pageW, box, text, steps, stepPx) {
927
+ const chars = [...text];
928
+ if (chars.length !== steps.length || !/[가-힣]/.test(text)) return [];
929
+ const gray = grayCrop(rgba, pageW, box);
930
+ const rings = ringBoxes(gray, box.w, box.h, inkStats(gray));
931
+ const owner = ringOwners(chars, (i) => (steps[i] + 0.5) * stepPx, rings);
932
+ return rings.flatMap((r, k) => {
933
+ const at = owner.indexOf(k);
934
+ if (at >= 0 && !/^[\u2460-\u2468]$/.test(chars[at])) return [];
935
+ const { inner } = r;
936
+ return [{ x0: r.x0, x1: r.x1, jamo: r.jamo, box: { x: box.x + inner.x0 - 1, y: box.y + inner.y0 - 1, w: inner.x1 - inner.x0 + 2, h: inner.y1 - inner.y0 + 2 } }];
937
+ });
938
+ }
939
+ function ringOwners(chars, cx, rings) {
940
+ return chars.map((c, i) => {
941
+ if (!c.trim()) return -1;
942
+ let best = -1, d = Infinity;
943
+ rings.forEach((r, k) => {
944
+ const e = Math.abs(cx(i) - (r.x0 + r.x1) / 2);
945
+ if (cx(i) >= r.x0 && cx(i) <= r.x1 && e < d) {
946
+ d = e;
947
+ best = k;
948
+ }
949
+ });
950
+ return best;
951
+ });
952
+ }
953
+ var RING_JAMO = "\u3131\u3134\u3137\u3139\u3141\u3142\u3145\u3147\u3148\u314A\u314B\u314C\u314D\u314E";
954
+ var RING_SYLLABLE = "\uAC00\uB098\uB2E4\uB77C\uB9C8\uBC14\uC0AC\uC544\uC790\uCC28\uCE74\uD0C0\uD30C\uD558";
955
+ function ringGlyph(read, jamo = null, confidence = 1) {
956
+ const t = read.trim();
957
+ if (jamo && /^[가-힣□口ㄱ-ㅎ]$/.test(t) && !RING_SYLLABLE.includes(t)) return String.fromCharCode(12896 + RING_JAMO.indexOf(jamo));
958
+ if (confidence < 0.5 || [...t].length !== 1 || /^[oO0ㅇ]$/.test(t)) return null;
959
+ if (/^[1-9]$/.test(t)) return String.fromCharCode(9311 + Number(t));
960
+ if (RING_JAMO.includes(t)) return String.fromCharCode(12896 + RING_JAMO.indexOf(t));
961
+ if (RING_SYLLABLE.includes(t)) return String.fromCharCode(12910 + RING_SYLLABLE.indexOf(t));
962
+ const l = /^[CSUVWXZ]$/.test(t) ? t.toLowerCase() : t;
963
+ if (/^[a-z]$/.test(l)) return String.fromCharCode(9424 + l.charCodeAt(0) - 97);
964
+ if (/^[A-Z]$/.test(l)) return String.fromCharCode(9398 + l.charCodeAt(0) - 65);
965
+ return null;
966
+ }
967
+ function restoreGlyphs(rgba, pageW, box, text, steps, stepPx, note = {}, rings = []) {
968
+ const chars = [...text];
969
+ if (chars.length !== steps.length) return text;
970
+ const gray = grayCrop(rgba, pageW, box);
971
+ const c = { chars, cx: (i) => (steps[i] + 0.5) * stepPx, gray, w: box.w, h: box.h, ink: inkStats(gray) };
972
+ if (/[[\]]/.test(text)) brackets(c);
973
+ if (text.includes("'")) cornerQuotes(c);
974
+ if (/['"]/.test(text)) quotes(c);
975
+ if (/(^|\D)[1-9](\D|$)|[ㄱ-ㅎa-zCSUVWXZ]/.test(text)) circled(c);
976
+ if (text.includes("*")) stars(c);
977
+ if (/[\u00b7\u2022]/.test(text)) discs(c);
978
+ if (/[-\u2013\u2014]/.test(text)) dashes(c);
979
+ gaps(c);
980
+ if (chars.some((t) => t.includes("\u300C")) && chars.includes(",")) cornerCommas(c);
981
+ note.ringLead = ring(c);
982
+ if (/[I|]/.test(text)) parallels(c);
983
+ if (/[I1Ⅰ-Ⅲ|]|^\s*\./.test(text)) roman(c);
984
+ const owner = ringOwners(chars, c.cx, rings);
985
+ rings.forEach((r, k) => {
986
+ const live = chars.map((_, i) => i).filter((i) => chars[i].trim());
987
+ const at = owner.indexOf(k);
988
+ if (at >= 0) {
989
+ chars[at] = r.glyph + [...chars[at]].slice(1).join("");
990
+ return;
991
+ }
992
+ const prev = live.filter((i) => c.cx(i) < r.x0).pop();
993
+ if (prev !== void 0) chars[prev] += r.glyph;
994
+ else if (live.length) chars[live[0]] = r.glyph + chars[live[0]];
995
+ });
996
+ checkboxes(c);
997
+ return chars.join("");
998
+ }
999
+ var BOX_READ = /^[\u25a1\u2610\u2611\u3141\u53e3[\]\u3010\u3011\u3014\u3015()|1VvNMCXx\u3137\u3134\u221a\u2713\u2714~\u2228\u03bd]+$/u;
1000
+ var BOX_LETTER = /[1VvNMCXx]/;
1001
+ var BOX_AMBIGUOUS = /[A-Za-z0-9()[\]\u3010\u3011\u3014\u3015|~]/u;
1002
+ var BOX_KEPT = /^(?:\u25a1|\u3141|\u53e3|\[\]?|\])$/u;
1003
+ function checkboxes({ chars, cx, gray, w, h, ink }) {
1004
+ const live = chars.map((_, i) => i).filter((i) => chars[i].trim());
1005
+ if (!live.length) return;
1006
+ const d = [];
1007
+ for (let k = 0; k + 1 < live.length; k++) d.push(cx(live[k + 1]) - cx(live[k]));
1008
+ const pitch = d.length >= 2 ? d.sort((a, b) => a - b)[d.length >> 1] : h * 0.6;
1009
+ const taken = [];
1010
+ const pending = [];
1011
+ let sure = 0;
1012
+ for (const f of checkboxFrames(gray, w, h, ink)) {
1013
+ if (taken.some((o) => o.x0 <= f.x1 && f.x0 <= o.x1)) continue;
1014
+ const s = f.x1 - f.x0, mid = (f.x0 + f.x1) / 2;
1015
+ const own = live.filter((i) => Math.abs(cx(i) - mid) <= Math.max(pitch * 0.5, s / 2));
1016
+ const at = live.indexOf(own[0]), last = live.indexOf(own[own.length - 1]);
1017
+ const next = own.length ? live[last + 1] : live.find((i) => cx(i) > mid);
1018
+ if (next === void 0 || cx(next) > f.x1 + s * 3 || !/^[가-힣A-Za-z0-9(]/u.test(chars[next])) continue;
1019
+ const before = at > 0 ? live[at - 1] : void 0;
1020
+ const wordHead = before === void 0 || before !== own[0] - 1 || !/[A-Za-z0-9가-힣]$/u.test(chars[before]);
1021
+ const read = own.map((i) => chars[i]).join("");
1022
+ if (own.some((i) => !BOX_READ.test(chars[i]))) continue;
1023
+ if (/^\(?1*\)?$/.test(read) && read && read !== "()") continue;
1024
+ if (/^[[\u3010\u3014]$/u.test(read) && chars.slice(own[0] + 1).some((t) => /[\]\u3011\u3015]/u.test(t))) continue;
1025
+ if (/^[\]\u3011\u3015]$/u.test(read) && chars.slice(0, own[0]).some((t) => /[[\u3010\u3014]/u.test(t))) continue;
1026
+ if (own.some((i) => BOX_LETTER.test(chars[i])) && (!wordHead || next === own[own.length - 1] + 1 && /^[A-Za-z0-9]/.test(chars[next]))) continue;
1027
+ if (BOX_KEPT.test(read)) {
1028
+ taken.push(f);
1029
+ if (!BOX_AMBIGUOUS.test(read)) sure++;
1030
+ continue;
1031
+ }
1032
+ if (/[\u221a\u2713\u2714\u2228\u03bd]/u.test(read) && !f.checked) continue;
1033
+ const glyph = f.kind === "\u25A1" ? f.checked ? "\u2611" : "\u25A1" : f.checked ? "[\u221A]" : "[]";
1034
+ if (own.length) {
1035
+ taken.push(f);
1036
+ const put = () => {
1037
+ chars[own[0]] = glyph;
1038
+ for (const i of own.slice(1)) chars[i] = "";
1039
+ };
1040
+ if (BOX_AMBIGUOUS.test(read)) pending.push(put);
1041
+ else {
1042
+ sure++;
1043
+ put();
1044
+ }
1045
+ continue;
1046
+ }
1047
+ const prev = live[live.indexOf(next) - 1];
1048
+ if (prev !== void 0 && /(?:\u25a1|\[\])$/u.test(chars[prev])) {
1049
+ taken.push(f);
1050
+ sure++;
1051
+ if (f.checked) chars[prev] = chars[prev].replace(/(?:\u25a1|\[\])$/u, glyph);
1052
+ continue;
1053
+ }
1054
+ if (f.checked || f.kind !== "\u25A1") continue;
1055
+ if (cx(next) < f.x1 + pitch * 0.5) continue;
1056
+ if (Math.abs((f.y0 + f.y1) / 2 - h / 2) > h * 0.25) continue;
1057
+ if (prev !== void 0 && /[.\u00b7\u2026]$/u.test(chars[prev])) continue;
1058
+ const head = prev === void 0 ? leadingBullet(gray, w, h, ink, cx(next))?.mark : void 0;
1059
+ if (head && head !== "\u25A1") continue;
1060
+ if (prev === next - 1 && /[가-힣\u3131-\u318eA-Za-z0-9]$/u.test(chars[prev]) && /^[가-힣A-Za-z0-9]/u.test(chars[next])) continue;
1061
+ const m = Math.max(2, Math.round(s * 0.35)), dirty = (xa, xb) => {
1062
+ let k = 0, n = 0;
1063
+ for (let y = f.y0; y <= f.y1; y++) for (let x = Math.max(0, xa); x <= Math.min(w - 1, xb); x++) {
1064
+ n++;
1065
+ if (gray[y * w + x] <= ink.threshold) k++;
1066
+ }
1067
+ return !n || k / n > 0.05;
1068
+ };
1069
+ if (dirty(f.x0 - m, f.x0 - 1) || dirty(f.x1 + 1, f.x1 + m)) continue;
1070
+ taken.push(f);
1071
+ sure++;
1072
+ chars[next] = glyph + " " + chars[next];
1073
+ }
1074
+ if (sure) for (const put of pending) put();
1075
+ }
1076
+ function trimInklessEnds(rgba, pageW, box, text, steps, stepPx) {
1077
+ const chars = [...text], { w, h } = box;
1078
+ if (chars.length !== steps.length || steps.some((s) => (s + 0.5) * stepPx > w + stepPx)) return { text, steps };
1079
+ const gray = grayCrop(rgba, pageW, box);
1080
+ const hist = new Uint32Array(256);
1081
+ for (const v of gray) hist[v]++;
1082
+ let bg = 0;
1083
+ for (let n = 0; bg < 255 && (n += hist[bg]) < gray.length / 2; ) bg++;
1084
+ const cols = new Uint32Array(w);
1085
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (Math.abs(gray[y * w + x] - bg) > INKLESS_DELTA) cols[x]++;
1086
+ const half = Math.max(stepPx, h * 0.25);
1087
+ const inkless = (i) => {
1088
+ const cx = (steps[i] + 0.5) * stepPx;
1089
+ for (let x = Math.max(0, Math.floor(cx - half)); x <= Math.min(w - 1, Math.ceil(cx + half)); x++) if (cols[x] && cols[x] < h * 0.9) return false;
1090
+ return true;
1091
+ };
1092
+ const blank2 = (i) => !chars[i].trim();
1093
+ const mark = (i) => new RegExp("\\p{P}", "u").test(chars[i]);
1094
+ let a = 0, b = chars.length;
1095
+ while (a < b && (blank2(a) || !mark(a) && inkless(a))) a++;
1096
+ while (b > a && (blank2(b - 1) || !mark(b - 1) && inkless(b - 1))) b--;
1097
+ const cut = (from, to) => chars.slice(from, to).some((c) => c.trim());
1098
+ if (a === b || !cut(0, a) && !cut(b, chars.length)) return { text, steps };
1099
+ return { text: chars.slice(a, b).join(""), steps: steps.slice(a, b) };
1100
+ }
1101
+ function cornerCommas({ chars, cx, gray, w, h, ink }) {
1102
+ const count = (t, ch) => t.split(ch).length - 1;
1103
+ let open = 0;
1104
+ for (let i = 0; i < chars.length; i++) {
1105
+ if (chars[i] !== ",") {
1106
+ open = Math.max(0, open + count(chars[i], "\u300C") - count(chars[i], "\u300D"));
1107
+ continue;
1108
+ }
1109
+ if (open > 0) {
1110
+ const f = bracketFeatures(gray, w, h, ink, cx(i));
1111
+ if (f && bracketShape(f, true) === "\u300D") {
1112
+ chars[i] = "\u300D";
1113
+ open--;
1114
+ }
1115
+ }
1116
+ }
1117
+ }
1118
+ function cornerQuotes({ chars, cx, gray, w, h, ink }) {
1119
+ for (let i = 0; i < chars.length; i++) {
1120
+ if (chars[i] !== "'" || !/^[가-힣]/.test(chars[i + 1] ?? "")) continue;
1121
+ const f = bracketFeatures(gray, w, h, ink, cx(i));
1122
+ if (!f || f.ch < f.charH * 0.45 || bracketShape(f, false) !== "\u300C") continue;
1123
+ const rest = chars.slice(i + 1), end = rest.findIndex((c) => c === "'" || c === "\u300D" || c === ",");
1124
+ const pair = end >= 0 && rest[end] !== "'" && (rest[end] === "\u300D" || (() => {
1125
+ const g = bracketFeatures(gray, w, h, ink, cx(i + 1 + end));
1126
+ return !!g && bracketShape(g, true) === "\u300D";
1127
+ })());
1128
+ if (pair) chars[i] = "\u300C";
1129
+ }
1130
+ }
1131
+ function brackets({ chars, cx, gray, w, h, ink }) {
1132
+ const shape = chars.map((c, i) => {
1133
+ if (c !== "[" && c !== "]") return null;
1134
+ const f = bracketFeatures(gray, w, h, ink, cx(i));
1135
+ return f && bracketShape(f, c === "]");
1136
+ });
1137
+ for (let i = 0; i < chars.length; i++) {
1138
+ if (chars[i] !== "[") continue;
1139
+ const j = chars.findIndex((c, k) => k > i && (c === "[" || c === "]"));
1140
+ if (j < 0 || chars[j] !== "]") continue;
1141
+ const a = shape[i], b = shape[j];
1142
+ const opens = a === "\u3010" || a === "(" || a === "\u3014", closes = b === "\u3011" || b === ")" || b === "\u3015";
1143
+ if ((opens || closes) && (!a || !b)) {
1144
+ if (opens) shape[i] = null;
1145
+ if (closes) shape[j] = null;
1146
+ }
1147
+ }
1148
+ for (let i = 0; i < chars.length; i++) if (shape[i]) chars[i] = shape[i];
1149
+ }
1150
+ function quotes({ chars, cx, gray, w, h, ink }) {
1151
+ const year = (i) => chars[i] === "'" && !/[\p{L}\p{N}]/u.test(chars[i - 1] ?? "") && /^\d{2}(?!\d)/.test(chars.slice(i + 1, i + 4).join(""));
1152
+ const single = { "'": chars.filter((c, i) => c === "'" && !year(i)).length === 1, '"': chars.filter((c) => c === '"').length === 1 };
1153
+ const open = { "'": false, '"': false };
1154
+ for (let i = 0; i < chars.length; i++) {
1155
+ const c = chars[i];
1156
+ const kind = c === "'" || c === "\u2018" || c === "\u2019" ? "'" : c === '"' || c === "\u201C" || c === "\u201D" ? '"' : null;
1157
+ if (!kind) continue;
1158
+ if (c !== kind) {
1159
+ open[kind] = c === "\u2018" || c === "\u201C";
1160
+ continue;
1161
+ }
1162
+ if (open[kind]) {
1163
+ open[kind] = false;
1164
+ continue;
1165
+ }
1166
+ if (!year(i) && !single[kind]) continue;
1167
+ const r = quoteHead(gray, w, h, ink, cx(i));
1168
+ if (r !== null && r >= 0.47) {
1169
+ chars[i] = kind === "'" ? "\u2018" : "\u201C";
1170
+ open[kind] = true;
1171
+ }
1172
+ }
1173
+ }
1174
+ function dashes({ chars, cx, gray, w, h, ink }) {
1175
+ const head = chars.findIndex((c) => c.trim()), letters = chars.some((c) => /[가-힣A-Za-z]/.test(c));
1176
+ for (let i = 0; i < chars.length; i++) {
1177
+ if (!/^[-\u2013\u2014]$/.test(chars[i])) continue;
1178
+ const r = dashRatio(gray, w, h, ink, cx(i));
1179
+ if (r === null) continue;
1180
+ if (r < 0.65) chars[i] = "-";
1181
+ else if (r > 0.75 && i === head && letters) chars[i] = "\u2014";
1182
+ }
1183
+ }
1184
+ function circled({ chars, cx, gray, w, h, ink }) {
1185
+ const alone = (re, i) => re.test(chars[i]) && !re.test(chars[i - 1] ?? "") && !re.test(chars[i + 1] ?? "");
1186
+ const at = chars.flatMap((_, i) => alone(/^\d$/, i) && chars[i] !== "0" || alone(/^[ㄱ-ㅎ]$/, i) || alone(/^[A-Za-z]$/, i) && /[a-zCSUVWXZ]/.test(chars[i]) ? [i] : []);
1187
+ if (!at.length) return;
1188
+ const hit = circledAt(gray, w, h, ink, at.map(cx));
1189
+ const JAMO = "\u3131\u3134\u3137\u3139\u3141\u3142\u3145\u3147\u3148\u314A\u314B\u314C\u314D\u314E";
1190
+ at.forEach((i, k) => {
1191
+ if (!hit[k]) return;
1192
+ const ch = chars[i];
1193
+ chars[i] = /\d/.test(ch) ? String.fromCharCode(9311 + Number(ch)) : /[a-zA-Z]/.test(ch) ? String.fromCharCode(9424 + ch.toLowerCase().charCodeAt(0) - 97) : JAMO.includes(ch) ? String.fromCharCode(12896 + JAMO.indexOf(ch)) : ch;
1194
+ });
1195
+ }
1196
+ function stars({ chars, cx, gray, w, h, ink }) {
1197
+ for (let i = 0; i < chars.length; i++) {
1198
+ if (chars[i] !== "*" || chars[i - 1] === "*") continue;
1199
+ let e = i;
1200
+ while (chars[e + 1] === "*") e++;
1201
+ const n = starRun(gray, w, h, ink, cx(i));
1202
+ if (n > e - i + 1 && n <= 4) chars[e] += "*".repeat(n - (e - i + 1));
1203
+ i = e;
1204
+ }
1205
+ }
1206
+ function discs({ chars, cx, gray, w, h, ink }) {
1207
+ for (let i = 0; i < chars.length; i++) if (/^[\u00b7\u2022]$/.test(chars[i]) && discAt(gray, w, h, ink, cx(i))) chars[i] = "\u25CF";
1208
+ }
1209
+ function gaps({ chars, cx, gray, w, h, ink }) {
1210
+ const { glyphs, bandH } = gapGlyphs(gray, w, h, ink);
1211
+ if (!glyphs.length) return;
1212
+ const live = chars.map((c, i) => i).filter((i) => chars[i].trim());
1213
+ if (!live.length) return;
1214
+ const d = [];
1215
+ for (let k = 0; k + 1 < live.length; k++) if (/[가-힣]$/.test(chars[live[k]]) && /^[가-힣]/.test(chars[live[k + 1]])) d.push(cx(live[k + 1]) - cx(live[k]));
1216
+ const pitch = d.length >= 2 ? d.sort((a, b) => a - b)[d.length >> 1] : bandH;
1217
+ const nearTo = (g) => (i) => Math.abs(cx(i) - (g.x0 + g.x1) / 2) <= Math.max(pitch * 0.45, (g.x1 - g.x0) / 2 + 1);
1218
+ const loose = glyphs.filter((g) => /^[\u00b7.]/.test(g.mark) && !live.some(nearTo(g)));
1219
+ const tail = [...live].reverse().findIndex((i) => !/^\d$/.test(chars[i]));
1220
+ if (tail >= 1 && tail <= 3 && tail < live.length) {
1221
+ const prev = live[live.length - 1 - tail], num = live[live.length - tail];
1222
+ const run = loose.filter((g) => (g.x0 + g.x1) / 2 > cx(prev) && (g.x0 + g.x1) / 2 < cx(num));
1223
+ const mark = run[0]?.mark[0];
1224
+ if (run.length >= 2 && run.length <= 3 && run.every((g) => g.mark[0] === mark) && /^[가-힣?)]$/.test(chars[prev]) && !glyphs.some((g) => !run.includes(g) && (g.x0 + g.x1) / 2 > cx(prev) && (g.x0 + g.x1) / 2 < cx(num)))
1225
+ chars[prev] += " " + mark.repeat(run.length) + " ";
1226
+ }
1227
+ for (const g of glyphs.sort((a, b) => a.x0 - b.x0)) {
1228
+ const mid = (g.x0 + g.x1) / 2;
1229
+ const near = nearTo(g);
1230
+ const cover = live.filter(near);
1231
+ if (g.mark === "\xB7") {
1232
+ const sp = chars.findIndex((c, i) => c === " " && near(i));
1233
+ const p = sp >= 0 ? chars.slice(0, sp).reverse().find((c) => c.trim()) : void 0, q = sp >= 0 ? chars.slice(sp + 1).find((c) => c.trim()) : void 0;
1234
+ if (p && q && /[가-힣]$/.test(p) && /^[가-힣]/.test(q) && !loose.some((o) => o !== g && Math.abs((o.x0 + o.x1) / 2 - mid) <= pitch * 1.5)) chars[sp] = "\xB7";
1235
+ continue;
1236
+ }
1237
+ if (cover.length) {
1238
+ if (g.mark.startsWith("\u25A1") && cover.length === 1 && /^[0Oo\u25cb]$/.test(chars[cover[0]])) chars[cover[0]] = "\u25A1";
1239
+ if (g.mark === "\u3002" && cover.length === 1 && /^[\u00b7\u2022\u318d]$/.test(chars[cover[0]])) chars[cover[0]] = "\u3002";
1240
+ continue;
1241
+ }
1242
+ if (g.mark === "\u25A1\0") continue;
1243
+ const before = live.filter((i) => cx(i) < mid), after = live.filter((i) => cx(i) > mid);
1244
+ if (!before.length) {
1245
+ if (after.length && /^[\u3002\u00b7\u300c\u25b2]$/.test(g.mark) && /^[가-힣]/.test(chars[after[0]])) chars[after[0]] = g.mark + chars[after[0]];
1246
+ else if (g.mark === "-" && /^[\dⅰ-ⅹivx]+\s*-$/.test(chars.join("").trim())) chars[after[0]] = "-" + chars[after[0]];
1247
+ continue;
1248
+ }
1249
+ if (!after.length && g.mark !== ".") continue;
1250
+ if (g.mark === "/" && !(/\d$/.test(chars[before[before.length - 1]]) && /^\d/.test(chars[after[0]]))) continue;
1251
+ const prev = chars[before[before.length - 1]], next = after.length ? chars[after[0]] : "";
1252
+ if (g.mark === "\xB7" || g.mark === ".") {
1253
+ if (loose.some((o) => o !== g && Math.abs((o.x0 + o.x1) / 2 - mid) <= pitch * 1.5)) continue;
1254
+ if (/[\u2026.\u00b7]$/.test(prev) || /^[\u2026.\u00b7]/.test(next)) continue;
1255
+ }
1256
+ if (g.mark === "\u300C") {
1257
+ let sp = chars.findIndex((c, i) => c === " " && near(i));
1258
+ if (sp >= 0) while (chars[sp + 1] === " ") sp++;
1259
+ if (sp >= 0) {
1260
+ chars[sp] = g.mark;
1261
+ continue;
1262
+ }
1263
+ }
1264
+ if (g.mark === "\xB7") {
1265
+ if (/^\d/.test(next)) continue;
1266
+ const sp = chars.findIndex((c, i) => c === " " && near(i));
1267
+ if (sp >= 0) {
1268
+ chars[sp] = g.mark;
1269
+ continue;
1270
+ }
1271
+ }
1272
+ chars[before[before.length - 1]] += g.mark;
1273
+ }
1274
+ }
1275
+ function ring({ chars, cx, gray, w, h, ink }) {
1276
+ const k = chars.findIndex((c) => c.trim());
1277
+ if (k < 0 || !/^[\u3147Oo0\u25cbCc]$/.test(chars[k])) return false;
1278
+ const rest = chars.slice(k + 1).join("").trimStart();
1279
+ const live = chars.map((c, i) => i).filter((i) => chars[i].trim());
1280
+ if (live.length <= 3 && live.every((i) => /^[Oo]$/.test(chars[i]))) {
1281
+ if (leadingBullet(gray, w, h, ink, cx(live[0]))?.mark === "\u25CE") return false;
1282
+ if (!live.every((i) => ringBullet(gray, w, h, ink, cx(i)) === "\u25CB")) return false;
1283
+ for (const i of live) chars[i] = "\u25CB";
1284
+ return true;
1285
+ }
1286
+ if (/^[A-Z]{2,}/.test(rest) && /^[Oo0]$/.test(chars[k])) {
1287
+ if (ringBullet(gray, w, h, ink, cx(k)) !== "\u25CB") return false;
1288
+ chars[k] = chars[k + 1] === " " ? "\u25CB" : "\u25CB ";
1289
+ return true;
1290
+ }
1291
+ if (!/^[(\[「【<]?\d*[가-힣]/.test(rest)) return false;
1292
+ const r = ringBullet(gray, w, h, ink, cx(k));
1293
+ if (/^[Cc]$/.test(chars[k]) && r !== "\u25CB") return false;
1294
+ if (r) chars[k] = r;
1295
+ return r !== null;
1296
+ }
1297
+ function parallels({ chars, cx, gray, w, h, ink }) {
1298
+ for (let s = 0; s < chars.length; ) {
1299
+ if (!/^[I|]$/.test(chars[s])) {
1300
+ s++;
1301
+ continue;
1302
+ }
1303
+ let e = s;
1304
+ while (e + 1 < chars.length && /^[I|]$/.test(chars[e + 1])) e++;
1305
+ if (e - s <= 1 && !/[A-Za-z]/.test((chars[s - 1] ?? "") + (chars[e + 1] ?? ""))) {
1306
+ let p = s - 1, q = e + 1;
1307
+ while (p >= 0 && !chars[p].trim()) p--;
1308
+ while (q < chars.length && !chars[q].trim()) q++;
1309
+ if (slantedPair(gray, w, h, ink, p >= 0 ? cx(p) : -Infinity, q < chars.length ? cx(q) : Infinity)) {
1310
+ chars[s] = "\u2225";
1311
+ for (let k = s + 1; k <= e; k++) chars[k] = "";
1312
+ }
1313
+ }
1314
+ s = e + 1;
1315
+ }
1316
+ }
1317
+ function roman({ chars, cx, gray, w, h, ink }) {
1318
+ const ROMAN = /^[IⅠ-Ⅲ]$/, LATIN = /[A-Za-z]$/;
1319
+ for (let i = 0; i < chars.length; i++) {
1320
+ if (chars[i] !== "1" || /[\dA-Za-z]$/.test(chars[i - 1] ?? "") || /^[\dA-Za-z,]/.test(chars[i + 1] ?? "")) continue;
1321
+ if (serifOne(gray, w, h, ink, cx(i))) chars[i] = "\u2160";
1322
+ }
1323
+ for (let i = 0; i < chars.length; i++) {
1324
+ const hangul = /^[파피]$/.test(chars[i]);
1325
+ if (chars[i] !== "|" && !hangul || chars[i - 1] === "|" || chars[i + 1] === "|") continue;
1326
+ let p = i - 1, q = i + 1;
1327
+ while (p >= 0 && !chars[p].trim()) p--;
1328
+ while (q < chars.length && !chars[q].trim()) q++;
1329
+ const glued = hangul ? chars[p] === "(" && chars[q] === "-" : /[가-힣]$/.test(chars[i - 1] ?? "") || (chars[i + 1] ?? "") === "." || chars[p] === "-" && chars[q] === "-";
1330
+ if (!glued) continue;
1331
+ const n = romanStems(gray, w, h, ink, p >= 0 ? cx(p) : -Infinity, q < chars.length ? cx(q) : Infinity, /[가-힣]$/.test(chars[p] ?? ""));
1332
+ if (n) chars[i] = String.fromCharCode(8543 + n);
1333
+ }
1334
+ const inRoman = (i) => ROMAN.test(chars[i]) || chars[i] === "1" && (ROMAN.test(chars[i - 1] ?? "") || ROMAN.test(chars[i + 1] ?? ""));
1335
+ const k = chars.findIndex((c) => c.trim());
1336
+ if (chars[k] === "." && chars.slice(k + 1).some((c) => /[가-힣A-Za-z0-9]/.test(c))) {
1337
+ const n = romanStems(gray, w, h, ink, -Infinity, cx(k));
1338
+ if (n) chars[k] = String.fromCharCode(8543 + n) + chars[k];
1339
+ }
1340
+ for (let s = 0; s < chars.length; ) {
1341
+ if (!inRoman(s) || s > 0 && LATIN.test(chars[s - 1])) {
1342
+ s++;
1343
+ continue;
1344
+ }
1345
+ let e = s;
1346
+ while (e < chars.length && (inRoman(e) || e > s && chars[e] === "|" && chars[e + 1] !== "|")) e++;
1347
+ const tok = chars.slice(s, e).join("");
1348
+ if (e < chars.length && /^[A-Za-z]/.test(chars[e])) {
1349
+ s = e;
1350
+ continue;
1351
+ }
1352
+ let p = s - 1, q = e;
1353
+ while (p >= 0 && !chars[p].trim()) p--;
1354
+ while (q < chars.length && !chars[q].trim()) q++;
1355
+ const n = romanStems(gray, w, h, ink, p >= 0 ? cx(p) : -Infinity, q < chars.length ? cx(q) : Infinity, /[가-힣]$/.test(chars[p] ?? ""));
1356
+ const canon = n ? [["\u2160", "I"], ["\u2161", "II"], ["\u2162", "III"]][n - 1] : null;
1357
+ if (canon && !canon.includes(tok)) {
1358
+ chars[s] = canon[0];
1359
+ for (let i = s + 1; i < e; i++) chars[i] = "";
1360
+ }
1361
+ s = e;
1362
+ }
1363
+ }
1364
+ var HANGUL_START = /^[\uac00-\ud7a3]/;
1365
+ function restoreSymbols(text, ringDecided = false) {
1366
+ let s = text;
1367
+ if (!ringDecided) s = s.replace(/^([Oo])(\s?)(?=[\uac00-\ud7a3])/, "\u25CB$2");
1368
+ s = s.replace(/(?<![A-Za-z])O{2,}(?![A-Za-z])/g, (m, i) => /[\uac00-\ud7a3]$/.test(s.slice(Math.max(0, i - 2), i).trimEnd()) || /^\s?[\uac00-\ud7a3]/.test(s.slice(i + m.length)) ? "\u25CB".repeat(m.length) : m);
1369
+ s = s.replace(/[\u2206\u0394]/g, "\u25B3");
1370
+ s = s.replace(/\(cid:\d*\)/g, "");
1371
+ s = s.replace(/(^|[^\uac00-\ud7a3])(전|현)\(\s?\)(?=\S)/g, (_, a, b) => `${a}${b}(${b === "\uC804" ? "\u524D" : "\u73FE"})`);
1372
+ if (/[가-힣]/.test(s)) s = s.replace(/(\d)l(?![A-Za-z])/g, "$1\u2113");
1373
+ s = s.replace(/([((])\s?[A-Za-z@&]\s?(?=(?:0\d{1,2}-)?\d{3,4}-\d{4}\b)/g, "$1\u260E");
1374
+ if (!s.includes("]")) s = s.replace(/^\[(?=[\u2460-\u2473])/, "");
1375
+ s = s.replace(/%\u3002/g, "\u2030");
1376
+ if (/[\uac00-\ud7a3]/.test(s)) s = s.replace(/(?<=[\uac00-\ud7a3\d)])\u3002/g, ".");
1377
+ return smartQuotes(dateDots(dateCommas(joinDigitGroups(s))));
1378
+ }
1379
+ function dateCommas(s) {
1380
+ return s.replace(/(?<![\d,.])((?:19|20)\d{2})(\s?)[,.](\s?)(1[0-2]|0?[1-9])(\s?),(\s?)(3[01]|[12]\d|0?[1-9])(?![\d,])/g, "$1.$2$3$4.$5$6$7").replace(/(?<![\d,.])((?:19|20)\d{2})(\s?),(\s?)(1[0-2]|0?[1-9])(\s?)\.(\s?)(3[01]|[12]\d|0?[1-9])(?![\d,])/g, "$1.$2$3$4.$5$6$7");
1381
+ }
1382
+ function dateDots(s) {
1383
+ const D = String.raw`(?:[’‘']\d{2}|(?:19|20)\d{2})\. ?(?:1[0-2]|0?[1-9])(?:\. ?(?:3[01]|[12]\d|0?[1-9]))?`;
1384
+ s = s.replace(new RegExp(String.raw`(?<![\d.])(${D})(?= ?[~∼~] ?${D}\.(?! ?\d))`, "g"), "$1.");
1385
+ return s.replace(
1386
+ /(?<![\d,.])((?:19|20)\d{2})( ?\. ?| )(1[0-2]|0?[1-9])( ?\. ?)(3[01]|[12]\d|0?[1-9])(\.?)( ?)(?=\([월화수목금토일]\))/g,
1387
+ (_, y, a, m, b, d, _dot, sp) => `${y}${a === " " ? ". " : a}${m}${b}${d}.${sp}`
1388
+ );
1389
+ }
1390
+ function joinDigitGroups(s) {
1391
+ return s.replace(/(?<![\d,])\d{1,3}(?:, ?\d{3})+(?![\d])/g, (m) => m.replace(/, /g, ","));
1392
+ }
1393
+ function smartQuotes(s) {
1394
+ if (!/['"]/.test(s)) return s;
1395
+ const chars = [...s];
1396
+ for (const q of ["'", '"']) {
1397
+ const [open, close] = q === "'" ? ["\u2018", "\u2019"] : ["\u201C", "\u201D"];
1398
+ const pos = [];
1399
+ for (let i = 0; i < chars.length; i++) {
1400
+ if (chars[i] !== q) continue;
1401
+ const prev2 = i > 0 ? chars[i - 1] : "";
1402
+ if (q === "'" && !/[\p{L}\p{N}]/u.test(prev2) && /^\d{2}(?!\d)/.test(chars.slice(i + 1, i + 4).join(""))) {
1403
+ chars[i] = close;
1404
+ continue;
1405
+ }
1406
+ pos.push(i);
1407
+ }
1408
+ if (pos.length === 0) continue;
1409
+ const first = pos[0];
1410
+ const prev = first > 0 ? chars[first - 1] : "";
1411
+ const atOpen = prev === "" || /[\s(\[{<\u300c\u300e\u3010\u3008\u300a\u2018\u201c·,:]/.test(prev);
1412
+ let isOpen = pos.length % 2 === 0 || atOpen;
1413
+ for (const i of pos) {
1414
+ chars[i] = isOpen ? open : close;
1415
+ isOpen = !isOpen;
1416
+ }
1417
+ }
1418
+ return chars.join("");
1419
+ }
1420
+ function isDotFragment(text) {
1421
+ return /^[\s.\u00b7\u2024\u2025\u2026\u2027\u2219\u22c5\u318d]+$/.test(text);
1422
+ }
1423
+ function joinLeaderItems(items, ends) {
1424
+ const gone = /* @__PURE__ */ new Set();
1425
+ const sameLine = (a, b) => Math.abs(a.y + a.h / 2 - (b.y + b.h / 2)) <= Math.max(a.h, b.h) / 2;
1426
+ const merge = (left, right) => {
1427
+ const x2 = Math.max(left.x + left.w, right.x + right.w), y2 = Math.max(left.y + left.h, right.y + right.h);
1428
+ left.text = left.text.replace(/[\s.:\u00b7\u2022\u2026]+$/u, "") + " \u2026 " + right.text.replace(/^[\s.:\u00b7\u2022\u2026]+/u, "");
1429
+ left.x = Math.min(left.x, right.x);
1430
+ left.y = Math.min(left.y, right.y);
1431
+ left.w = x2 - left.x;
1432
+ left.h = y2 - left.y;
1433
+ left.confidence = Math.min(left.confidence, right.confidence);
1434
+ gone.add(right);
1435
+ };
1436
+ const junk = (o) => /^[\s.:\u00b7\u2022\u2026]+$/u.test(o.text);
1437
+ const neighbor = (it, toLeft) => {
1438
+ let best = null;
1439
+ for (const o of items) {
1440
+ if (o === it || gone.has(o) || !sameLine(o, it) || junk(o)) continue;
1441
+ const padding = toLeft && ends.get(it)?.lead && /^…\s*\d{1,4}$/.test(it.text) ? Math.max(2, Math.min(o.h, it.h, o.w / 2, it.w / 2) * 0.5) : 2;
1442
+ if (toLeft ? o.x + o.w > it.x + padding : o.x < it.x + it.w - padding) continue;
1443
+ if (!best || (toLeft ? o.x + o.w > best.x + best.w : o.x < best.x)) best = o;
1444
+ }
1445
+ return best;
1446
+ };
1447
+ const dropJunkBetween = (left, right) => {
1448
+ for (const o of items) if (!gone.has(o) && junk(o) && sameLine(o, left) && o.x + o.w / 2 >= left.x + left.w - left.h && o.x + o.w / 2 <= right.x + right.h) gone.add(o);
1449
+ };
1450
+ for (const it of [...items].sort((a, b) => b.x - a.x)) {
1451
+ if (gone.has(it) || !ends.get(it)?.lead) continue;
1452
+ const left = neighbor(it, true);
1453
+ if (left) {
1454
+ dropJunkBetween(left, it);
1455
+ merge(left, it);
1456
+ }
1457
+ }
1458
+ for (const it of [...items].sort((a, b) => a.x - b.x)) {
1459
+ if (gone.has(it) || !ends.get(it)?.trail) continue;
1460
+ const right = neighbor(it, false);
1461
+ if (right) {
1462
+ dropJunkBetween(it, right);
1463
+ merge(it, right);
1464
+ }
1465
+ }
1466
+ const toc = items.filter((it) => !gone.has(it) && /\s\u2026\s\d{1,4}$/.test(it.text));
1467
+ if (toc.length >= 2) {
1468
+ for (const it of items) {
1469
+ if (gone.has(it) || toc.includes(it) || !/^[\s.:\u00b7\u2026]*\d{1,4}$/.test(it.text)) continue;
1470
+ const x2 = it.x + it.w;
1471
+ if (toc.filter((t) => Math.abs(t.x + t.w - x2) <= Math.max(t.h, it.h)).length < 2) continue;
1472
+ const left = neighbor(it, true);
1473
+ if (!left || toc.includes(left)) continue;
1474
+ dropJunkBetween(left, it);
1475
+ merge(left, it);
1476
+ }
1477
+ }
1478
+ return items.filter((it) => !gone.has(it));
1479
+ }
1480
+ function dropNestedFragments(items) {
1481
+ const inside = (a, b) => a.x >= b.x - 2 && a.x + a.w <= b.x + b.w + 2 && a.y >= b.y - 2 && a.y + a.h <= b.y + b.h + 2;
1482
+ return items.filter((a) => !items.some((b) => b !== a && a.h <= b.h * 0.6 && a.confidence < b.confidence && inside(a, b)));
1483
+ }
1484
+ function restoreBulletItems(items) {
1485
+ for (const it of items) {
1486
+ if (it.text !== "O" && it.text !== "o") continue;
1487
+ const cy = it.y + it.h / 2;
1488
+ let next = null;
1489
+ for (const o of items) {
1490
+ if (o === it || o.x < it.x + it.w * 0.5) continue;
1491
+ if (Math.abs(o.y + o.h / 2 - cy) > Math.max(it.h, o.h) / 2) continue;
1492
+ if (o.x - (it.x + it.w) > it.h * 3) continue;
1493
+ if (!next || o.x < next.x) next = o;
1494
+ }
1495
+ if (next && HANGUL_START.test(next.text.trimStart())) it.text = "\u25CB";
1496
+ }
1497
+ }
1498
+ var REC_HEIGHT = 48;
1499
+ var REC_MAX_WIDTH = 3200;
1500
+ var MIN_SIZE = 3;
1501
+ function bandBoxes(b, bands, pageH) {
1502
+ const out = [];
1503
+ for (let i = 0; i < bands.length; i++) {
1504
+ const { y0, y1, x0, x1 } = bands[i];
1505
+ const bh = y1 - y0;
1506
+ const upGap = i > 0 ? (y0 - bands[i - 1].y1) / 2 : y0;
1507
+ const downGap = i < bands.length - 1 ? (bands[i + 1].y0 - y1) / 2 : b.h - y1;
1508
+ const top = Math.max(0, Math.round(b.y + y0 - Math.min(bh * 0.2, upGap)));
1509
+ const bot = Math.min(pageH, Math.round(b.y + y1 + Math.min(bh * 0.2, downGap)));
1510
+ const left = Math.max(b.x, Math.round(b.x + x0 - bh * 0.2));
1511
+ const right = Math.min(b.x + b.w, Math.round(b.x + x1 + bh * 0.2));
1512
+ if (bot - top >= MIN_SIZE && right - left >= MIN_SIZE) out.push({ x: left, y: top, w: right - left, h: bot - top });
1513
+ }
1514
+ return out;
1515
+ }
1516
+ function lineCrop(rgba, pageW, box, rot, keep, stretch = 1) {
1517
+ const srcW = rot === 0 || rot === 180 ? box.w : box.h;
1518
+ const srcH = rot === 0 || rot === 180 ? box.h : box.w;
1519
+ const rw = Math.min(REC_MAX_WIDTH, Math.max(16, Math.round(srcW * REC_HEIGHT * stretch / srcH)));
1520
+ const rgb = new Uint8Array(rw * REC_HEIGHT * 3);
1521
+ const at = (u, v) => {
1522
+ let px, py;
1523
+ if (rot === 0) {
1524
+ px = u;
1525
+ py = v;
1526
+ } else if (rot === 90) {
1527
+ px = box.w - 1 - v;
1528
+ py = u;
1529
+ } else if (rot === 180) {
1530
+ px = box.w - 1 - u;
1531
+ py = box.h - 1 - v;
1532
+ } else {
1533
+ px = v;
1534
+ py = box.h - 1 - u;
1535
+ }
1536
+ return ((box.y + py) * pageW + (box.x + px)) * 4;
1537
+ };
1538
+ const fx = srcW / rw;
1539
+ const fy = srcH / REC_HEIGHT;
1540
+ for (let dy = 0; dy < REC_HEIGHT; dy++) {
1541
+ let sy = (dy + 0.5) * fy - 0.5;
1542
+ if (sy < 0) sy = 0;
1543
+ const y0 = Math.min(srcH - 1, Math.floor(sy));
1544
+ const y1 = Math.min(srcH - 1, y0 + 1);
1545
+ const wy = sy - y0;
1546
+ for (let dx = 0; dx < rw; dx++) {
1547
+ let sx = (dx + 0.5) * fx - 0.5;
1548
+ if (sx < 0) sx = 0;
1549
+ const x0 = Math.min(srcW - 1, Math.floor(sx));
1550
+ const x1 = Math.min(srcW - 1, x0 + 1);
1551
+ const wx = sx - x0;
1552
+ const i00 = at(x0, y0), i01 = at(x1, y0), i10 = at(x0, y1), i11 = at(x1, y1);
1553
+ const o = (dy * rw + dx) * 3;
1554
+ if (keep && rot === 0 && (sx < keep.x0 || sx >= keep.x1 || sy < keep.y0 || sy >= keep.y1)) {
1555
+ rgb[o] = rgb[o + 1] = rgb[o + 2] = keep.bg;
1556
+ continue;
1557
+ }
1558
+ for (let c = 0; c < 3; c++) {
1559
+ const top = rgba[i00 + c] * (1 - wx) + rgba[i01 + c] * wx;
1560
+ const bottom = rgba[i10 + c] * (1 - wx) + rgba[i11 + c] * wx;
1561
+ rgb[o + c] = Math.round(top * (1 - wy) + bottom * wy);
1562
+ }
1563
+ }
1564
+ }
1565
+ return { rgb, w: rw };
1566
+ }
1567
+ var CELL_RULE_MARGIN = 0.7;
1568
+ function splitBoxAtCellRules(b, rules) {
1569
+ const m = b.h * CELL_RULE_MARGIN;
1570
+ const cuts = rules.filter((r) => r.x1 > b.x + m && r.x1 < b.x + b.w - m && r.y1 <= b.y + b.h * 0.25 && r.y2 >= b.y + b.h * 0.75).sort((a, c) => a.x1 - c.x1);
1571
+ if (!cuts.length) return [b];
1572
+ const out = [];
1573
+ let left = b.x;
1574
+ for (const r of cuts) {
1575
+ const edge = Math.floor(r.x1 - r.thicknessPx / 2 - 1);
1576
+ if (edge - left < m) continue;
1577
+ out.push({ ...b, x: left, w: edge - left });
1578
+ left = Math.ceil(r.x1 + r.thicknessPx / 2 + 1);
1579
+ }
1580
+ if (left < b.x + b.w) out.push({ ...b, x: left, w: b.x + b.w - left });
1581
+ return out;
1582
+ }
1583
+ function splitBoxAtRowRules(b, rules) {
1584
+ const min = Math.max(8, b.h * 0.3);
1585
+ const cuts = rules.filter((r) => r.y1 > b.y + min && r.y1 < b.y + b.h - min && r.x1 <= b.x + b.w * 0.25 && r.x2 >= b.x + b.w * 0.75).sort((a, c) => a.y1 - c.y1);
1586
+ if (!cuts.length) return [b];
1587
+ const out = [];
1588
+ let top = b.y;
1589
+ for (const r of cuts) {
1590
+ const edge = Math.floor(r.y1 - r.thicknessPx / 2 - 1);
1591
+ if (edge - top < min) continue;
1592
+ out.push({ ...b, y: top, h: edge - top });
1593
+ top = Math.ceil(r.y1 + r.thicknessPx / 2 + 1);
1594
+ }
1595
+ if (b.y + b.h - top >= min) out.push({ ...b, y: top, h: b.y + b.h - top });
1596
+ return out.length ? out : [b];
1597
+ }
1598
+ var BEAM_WIDTH = 32;
1599
+ var FRAME_TOP_K = 8;
1600
+ var MIN_SYMBOL_PROB = 1e-4;
1601
+ var logAdd = (a, b) => a === -Infinity ? b : b === -Infinity ? a : Math.max(a, b) + Math.log1p(Math.exp(-Math.abs(a - b)));
1602
+ function ctcCandidates(data, T, C, dict, n) {
1603
+ if (n <= 0 || T <= 0) return [];
1604
+ let beams = /* @__PURE__ */ new Map([["", [0, -Infinity]]]);
1605
+ const top = new Int32Array(FRAME_TOP_K);
1606
+ const topP = new Float64Array(FRAME_TOP_K);
1607
+ for (let t = 0; t < T; t++) {
1608
+ const off = t * C;
1609
+ let max = -Infinity, negative = false;
1610
+ for (let c = 0; c < C; c++) {
1611
+ const v = data[off + c];
1612
+ if (v > max) max = v;
1613
+ if (v < 0) negative = true;
1614
+ }
1615
+ const logits = negative || max > 1.0001;
1616
+ let denom = 1;
1617
+ if (logits) {
1618
+ denom = 0;
1619
+ for (let c = 0; c < C; c++) denom += Math.exp(data[off + c] - max);
1620
+ }
1621
+ const prob = (c) => logits ? Math.exp(data[off + c] - max) / denom : data[off + c];
1622
+ let k = 0;
1623
+ for (let c = 1; c < C; c++) {
1624
+ const p = prob(c);
1625
+ if (p < MIN_SYMBOL_PROB || k === FRAME_TOP_K && p <= topP[k - 1]) continue;
1626
+ let i = k < FRAME_TOP_K ? k++ : k - 1;
1627
+ for (; i > 0 && topP[i - 1] < p; i--) {
1628
+ top[i] = top[i - 1];
1629
+ topP[i] = topP[i - 1];
1630
+ }
1631
+ top[i] = c;
1632
+ topP[i] = p;
1633
+ }
1634
+ const blank2 = Math.log(prob(0));
1635
+ const next = /* @__PURE__ */ new Map();
1636
+ const slot = (key) => {
1637
+ let s = next.get(key);
1638
+ if (!s) next.set(key, s = [-Infinity, -Infinity]);
1639
+ return s;
1640
+ };
1641
+ for (const [prefix, [pb, pnb]] of beams) {
1642
+ const total = logAdd(pb, pnb);
1643
+ const last = prefix ? prefix.charCodeAt(prefix.length - 1) : -1;
1644
+ const same = slot(prefix);
1645
+ same[0] = logAdd(same[0], total + blank2);
1646
+ if (last > 0) same[1] = logAdd(same[1], pnb + Math.log(prob(last)));
1647
+ for (let i = 0; i < k; i++) {
1648
+ const s = slot(prefix + String.fromCharCode(top[i]));
1649
+ s[1] = logAdd(s[1], (top[i] === last ? pb : total) + Math.log(topP[i]));
1650
+ }
1651
+ }
1652
+ const ranked = [...next].sort((a, b) => logAdd(b[1][0], b[1][1]) - logAdd(a[1][0], a[1][1]));
1653
+ beams = new Map(ranked.slice(0, BEAM_WIDTH));
1654
+ }
1655
+ const byText = /* @__PURE__ */ new Map();
1656
+ for (const [prefix, [pb, pnb]] of beams) {
1657
+ let text = "";
1658
+ for (let i = 0; i < prefix.length; i++) {
1659
+ const c = prefix.charCodeAt(i);
1660
+ text += c <= dict.length ? dict[c - 1] : c === dict.length + 1 ? " " : "";
1661
+ }
1662
+ text = text.trim();
1663
+ const p = Math.exp(logAdd(pb, pnb));
1664
+ if (text && p > 0) byText.set(text, (byText.get(text) ?? 0) + p);
1665
+ }
1666
+ return [...byText].sort((a, b) => b[1] - a[1]).slice(0, n).map(([text, p]) => ({ text, probability: Math.min(1, p) }));
1667
+ }
1668
+ var DEFAULT_OCR_TUNING = Object.freeze({
1669
+ detLongSide: 960,
1670
+ detThresh: 0.3,
1671
+ detBoxThresh: 0.6,
1672
+ detUnclip: 1.5,
1673
+ textScore: 0.5,
1674
+ recBatch: 1,
1675
+ splitTall: true,
1676
+ trimEdges: true,
1677
+ minInkContrast: 35,
1678
+ postprocess: true,
1679
+ tightBoxes: true,
1680
+ splitLeaders: true,
1681
+ orientPage: true,
1682
+ redetect: true
1683
+ });
1684
+ var DET_MIN_SIZE = 3;
1685
+ var NUMBER_STRETCH = [1.6, 2.2];
1686
+ function badThousands(text) {
1687
+ for (const m of text.matchAll(/(?<![\d.,])\d+(?:,\d*)*,\d+(?![\d,])/g)) {
1688
+ const [head, ...rest] = m[0].split(",");
1689
+ if (head.length > 3 || rest.some((g) => g.length !== 3)) return true;
1690
+ }
1691
+ return false;
1692
+ }
1693
+ function singleNumberText(text) {
1694
+ return /^[-−(△▲]?\d[\d,]*(?:\.\d+)?\)?\s?(?:[가-힣]{1,2}|%)?$/.test(text.trim());
1695
+ }
1696
+ var NUMBER_PAIR = /^[-−]?\d+(?:\.\d+)?\/[-−]?\d+(?:\.\d+)?$/;
1697
+ var DECIMAL_PAIR = /^[-−]?\d+\.\d+\/[-−]?\d+\.\d+$/;
1698
+ function rereadDecimalPair(original, reread) {
1699
+ const r = reread.trim();
1700
+ if (!DECIMAL_PAIR.test(r)) return null;
1701
+ const a = original.replace(/\D/g, ""), b = r.replace(/\D/g, "");
1702
+ let i = 0;
1703
+ for (const ch of b) if (ch === a[i]) i++;
1704
+ return i === a.length && b.length - a.length <= 1 ? r : null;
1705
+ }
1706
+ function rereadNumberText(original, reread) {
1707
+ const skeleton = (t) => t.replace(/[\d,\s]/g, "");
1708
+ if (skeleton(reread) === skeleton(original)) return restoreSymbols(reread.trim());
1709
+ const num = (t) => t.match(/\d[\d,]*\d|\d/g) ?? [];
1710
+ const before = num(original), after = num(reread);
1711
+ if (before.length !== 1 || after.length !== 1) return null;
1712
+ const a = before[0].replace(/,/g, ""), b = after[0].replace(/,/g, "");
1713
+ let i = 0;
1714
+ for (const ch of b) if (ch === a[i]) i++;
1715
+ return b.length > a.length && i === a.length ? original.replace(before[0], after[0]) : null;
1716
+ }
1717
+ var DET_MAX_BOXES = 3e3;
1718
+ var REC_MIN_WIDTH = 320;
1719
+ var REC_BATCH_MAX_PIXELS = 48 * 16e3;
1720
+ var TALL_RATIO = 1.5;
1721
+ var SOLE_BAND_RATIO = 0.7;
1722
+ var ROTATE_RATIO = 3;
1723
+ var ORIENT_MIN_BOXES = 20;
1724
+ var ORIENT_TALL_SHARE = 0.6;
1725
+ var ORIENT_SAMPLE = 12;
1726
+ var ORIENT_MIN_CONF = 0.7;
1727
+ var ORIENT_GAIN = 0.1;
1728
+ var FLIP_MIN_BOXES = 4;
1729
+ var FLIP_WIDE_RATIO = 2;
1730
+ var KEEP_MARGIN = 0.06;
1731
+ var RETRY_SCORE = 0.9;
1732
+ var MULTI_LINE_RATIO = 1.8;
1733
+ var WEAK_LINE_SCORE = 0.75;
1734
+ var TALL_LINE_RATIO = 1.1;
1735
+ var TALL_LINE_SCORE = 0.9;
1736
+ var MARK_GLYPH = /^[\u25cb\u25cf\u25ce\u00d7\u25b3\u25b2\u25a1\u25a0\u25c7\u25c6]$/;
1737
+ var LOW_MARK_SCORE = 0.3;
1738
+ var STACK_WORD_GAP = 0.3;
1739
+ var LEADER_MIN_DOTS = 4;
1740
+ var LEADER_CONTEXT = 0.5;
1741
+ var DET_MIN_SHORT_SIDE = 80;
1742
+ var DET_MAX_LONG_SIDE = 4096;
1743
+ function detInputSize(width, height, longSide) {
1744
+ let ratio = longSide / Math.max(width, height);
1745
+ if (Math.min(width, height) * ratio < DET_MIN_SHORT_SIDE) ratio = Math.min(DET_MIN_SHORT_SIDE / Math.min(width, height), DET_MAX_LONG_SIDE / Math.max(width, height));
1746
+ return { dw: Math.max(32, Math.round(width * ratio / 32) * 32), dh: Math.max(32, Math.round(height * ratio / 32) * 32) };
1747
+ }
1748
+ var MIN_INK_RATIO = 0.01;
1749
+ var MAX_LOCAL_MODEL_BYTES = 1024 * 1024 * 1024;
1750
+ var DET_MEAN = [0.485, 0.456, 0.406];
1751
+ var DET_STD = [0.229, 0.224, 0.225];
1752
+ function rowHeadDashes(rgba, width, items) {
1753
+ const out = [];
1754
+ const dark = (x, y) => {
1755
+ const p = (y * width + x) * 4;
1756
+ return rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8 < 160;
1757
+ };
1758
+ const inBox = (x, y) => items.some((b) => x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h);
1759
+ const done = /* @__PURE__ */ new Set();
1760
+ for (const it of [...items]) {
1761
+ if (done.has(it) || it.h < 12) continue;
1762
+ const row = items.filter((o) => Math.min(o.y + o.h, it.y + it.h) - Math.max(o.y, it.y) >= Math.min(o.h, it.h) * 0.6);
1763
+ for (const o of row) done.add(o);
1764
+ if (row.reduce((k, o) => k + (o.text.match(/[가-힣]/g)?.length ?? 0), 0) < 2) continue;
1765
+ const first = row.reduce((m, o) => o.x < m.x ? o : m);
1766
+ if (!/^[가-힣]/.test(first.text)) continue;
1767
+ if (row.filter((o) => /\d/.test(o.text)).length >= 2) continue;
1768
+ const y0 = Math.min(...row.map((o) => o.y)), y1 = Math.max(...row.map((o) => o.y + o.h)), h = y1 - y0;
1769
+ const x0 = Math.max(0, Math.round(first.x - 2.5 * h)), x1 = first.x - 2;
1770
+ let minX = -1, maxX = -1, minY = Infinity, maxY = -1, groups = 0;
1771
+ for (let x = x0; x < x1; x++) {
1772
+ let on = false;
1773
+ for (let y = y0; y < y1; y++) if (dark(x, y) && !inBox(x, y)) {
1774
+ on = true;
1775
+ if (y < minY) minY = y;
1776
+ if (y > maxY) maxY = y;
1777
+ }
1778
+ if (!on) continue;
1779
+ if (maxX < 0 || x - maxX > 2) {
1780
+ groups++;
1781
+ if (groups === 1) minX = x;
1782
+ }
1783
+ maxX = x;
1784
+ }
1785
+ const bw = maxX - minX + 1, bh = maxY - minY + 1, cy = ((minY + maxY) / 2 - y0) / h;
1786
+ if (groups !== 1 || bh > h * 0.2 || bw < h * 0.3 || bw > h * 1.2 || cy < 0.3 || cy > 0.7) continue;
1787
+ const faint = (x, y) => {
1788
+ const p = (y * width + x) * 4;
1789
+ return rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8 < 230;
1790
+ };
1791
+ let touch = minX <= x0;
1792
+ for (let y = minY; y <= maxY && !touch; y++) for (let d = 2; d <= 4 && !touch; d++) touch = minX - d >= 0 && faint(minX - d, y) || faint(maxX + d, y);
1793
+ if (touch) continue;
1794
+ out.push({ text: "-", x: minX, y: y0, w: bw, h, confidence: first.confidence });
1795
+ }
1796
+ return out;
1797
+ }
1798
+ function rowTailBoxes(rgba, width, items) {
1799
+ const out = [];
1800
+ const dark = (x, y) => {
1801
+ const p = (y * width + x) * 4;
1802
+ return rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8 < 160;
1803
+ };
1804
+ const done = /* @__PURE__ */ new Set();
1805
+ for (const it of items) {
1806
+ if (done.has(it) || it.h < 12) continue;
1807
+ const row = items.filter((o) => Math.min(o.y + o.h, it.y + it.h) - Math.max(o.y, it.y) >= Math.min(o.h, it.h) * 0.6);
1808
+ for (const o of row) done.add(o);
1809
+ if (row.reduce((k, o) => k + (o.text.match(/[가-힣]/g)?.length ?? 0), 0) < 2) continue;
1810
+ const last = row.reduce((m, o) => o.x + o.w > m.x + m.w ? o : m);
1811
+ if (/\d$/.test(last.text.trim())) continue;
1812
+ const y0 = Math.min(...row.map((o) => o.y)), y1 = Math.max(...row.map((o) => o.y + o.h)), h = y1 - y0;
1813
+ const x0 = last.x + last.w + 4, x1 = Math.floor(width * 0.95);
1814
+ if (x1 - x0 < h) continue;
1815
+ const groups = [];
1816
+ for (let x = x0; x < x1; x++) {
1817
+ let top = -1, bot = -1;
1818
+ for (let y = y0; y < y1; y++) if (dark(x, y)) {
1819
+ if (top < 0) top = y;
1820
+ bot = y;
1821
+ }
1822
+ if (top < 0 || bot - top + 1 < h * 0.3) continue;
1823
+ const g = groups[groups.length - 1];
1824
+ if (!g || x - g.maxX > h) groups.push({ minX: x, maxX: x, minY: top, maxY: bot });
1825
+ else {
1826
+ g.maxX = x;
1827
+ g.minY = Math.min(g.minY, top);
1828
+ g.maxY = Math.max(g.maxY, bot);
1829
+ }
1830
+ }
1831
+ const height = Math.floor(rgba.length / 4 / width);
1832
+ const rule = (g) => {
1833
+ for (let x = g.minX; x <= g.maxX; x++) if (g.minY > 1 && dark(x, g.minY - 2) || g.maxY + 2 < height && dark(x, g.maxY + 2)) return true;
1834
+ return false;
1835
+ };
1836
+ const ink = groups.filter((g) => !rule(g));
1837
+ if (ink.length !== 1) continue;
1838
+ const { minX, maxX, minY, maxY } = ink[0];
1839
+ if (maxY - minY + 1 < h * 0.5 || maxX - minX + 1 > h * 4) continue;
1840
+ const pad = 4;
1841
+ out.push({ x: Math.max(0, minX - pad), y: Math.max(0, minY - pad), w: maxX - minX + 1 + 2 * pad, h: maxY - minY + 1 + 2 * pad });
1842
+ }
1843
+ return out;
1844
+ }
1845
+ function joinGapLeaders(rgba, width, items) {
1846
+ const gone = /* @__PURE__ */ new Set();
1847
+ const sameLine = (a, b) => Math.abs(a.y + a.h / 2 - (b.y + b.h / 2)) <= Math.max(a.h, b.h) / 2;
1848
+ const junk = (o) => /^[\s.:\u00b7\u2022\u2026]+$/u.test(o.text);
1849
+ for (const num of [...items].sort((a, b) => a.x - b.x)) {
1850
+ if (gone.has(num) || !/^[\s.:\u00b7\u2026]*\d{1,4}$/u.test(num.text)) continue;
1851
+ let left = null;
1852
+ for (const o of items) if (o !== num && !gone.has(o) && !junk(o) && sameLine(o, num) && o.x + o.w <= num.x + 2 && (!left || o.x + o.w > left.x + left.w)) left = o;
1853
+ if (!left || /\u2026/.test(left.text) || !/[가-힣A-Za-z]/.test(left.text)) continue;
1854
+ const h = Math.max(left.h, num.h), g0 = left.x + left.w, g1 = num.x;
1855
+ if (g1 - g0 < h * 3) continue;
1856
+ const pad = Math.round(h * 0.25), y = Math.max(0, Math.min(left.y, num.y) - pad), x = Math.max(0, Math.round(g0 - h));
1857
+ const box = { x, y, w: Math.min(width, Math.round(g1 + h)) - x, h: Math.min(Math.floor(rgba.length / 4 / width), Math.max(left.y + left.h, num.y + num.h) + pad) - y };
1858
+ const gray = grayCrop(rgba, width, box);
1859
+ const runs = leaderRuns(gray, box.w, box.h, inkStats(gray), LEADER_MIN_DOTS);
1860
+ const cover = runs.reduce((k, [a, b]) => k + Math.max(0, Math.min(b, g1 - box.x) - Math.max(a, g0 - box.x)), 0);
1861
+ if (cover < (g1 - g0) * 0.6) continue;
1862
+ for (const o of items) if (junk(o) && sameLine(o, num) && o.x >= g0 - 2 && o.x + o.w <= g1 + 2) gone.add(o);
1863
+ left.text = left.text.trimEnd() + " " + num.text.replace(/^[\s.:\u00b7\u2026]+/u, "");
1864
+ const x2 = Math.max(left.x + left.w, num.x + num.w), y2 = Math.max(left.y + left.h, num.y + num.h);
1865
+ left.y = Math.min(left.y, num.y);
1866
+ left.w = x2 - left.x;
1867
+ left.h = y2 - left.y;
1868
+ left.confidence = Math.min(left.confidence, num.confidence);
1869
+ gone.add(num);
1870
+ }
1871
+ return items.filter((it) => !gone.has(it));
1872
+ }
1873
+ function rowHeadBoxes(rgba, width, items) {
1874
+ const out = [];
1875
+ const dark = (x, y) => {
1876
+ const p = (y * width + x) * 4;
1877
+ return rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8 < 160;
1878
+ };
1879
+ const inBox = (x, y) => items.some((b) => x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h);
1880
+ const height = Math.floor(rgba.length / 4 / width);
1881
+ const done = /* @__PURE__ */ new Set();
1882
+ for (const it of items) {
1883
+ if (done.has(it) || it.h < 12) continue;
1884
+ const row = items.filter((o) => Math.min(o.y + o.h, it.y + it.h) - Math.max(o.y, it.y) >= Math.min(o.h, it.h) * 0.6);
1885
+ for (const o of row) done.add(o);
1886
+ if (row.reduce((k, o) => k + (o.text.match(/[가-힣]/g)?.length ?? 0), 0) < 2) continue;
1887
+ const first = row.reduce((m, o) => o.x < m.x ? o : m);
1888
+ if (!/^[가-힣\d]/.test(first.text)) continue;
1889
+ const hs = row.map((o) => o.h).sort((a, b) => a - b), h = hs[hs.length >> 1];
1890
+ const y0 = Math.min(...row.map((o) => o.y)), y1 = Math.max(...row.map((o) => o.y + o.h));
1891
+ const x0 = Math.max(0, Math.round(first.x - 4 * h)), x1 = first.x - 2;
1892
+ if (x1 - x0 < h) continue;
1893
+ let groups = 0, minX = -1, maxX = -1, minY = Infinity, maxY = -1;
1894
+ for (let x = x0; x < x1; x++) {
1895
+ let on = false;
1896
+ for (let y = y0; y < y1; y++) if (dark(x, y) && !inBox(x, y)) {
1897
+ on = true;
1898
+ if (y < minY) minY = y;
1899
+ if (y > maxY) maxY = y;
1900
+ }
1901
+ if (!on) continue;
1902
+ if (maxX < 0 || x - maxX > h) {
1903
+ groups++;
1904
+ if (groups === 1) minX = x;
1905
+ }
1906
+ maxX = x;
1907
+ }
1908
+ if (groups !== 1 || minX <= x0 || maxY - minY + 1 < h * 0.5 || maxX - minX + 1 > h * 3) continue;
1909
+ let rule = false;
1910
+ for (let x = minX; x <= maxX && !rule; x++) rule = minY > 1 && dark(x, minY - 2) && !inBox(x, minY - 2) || maxY + 2 < height && dark(x, maxY + 2) && !inBox(x, maxY + 2);
1911
+ if (rule) continue;
1912
+ const pad = Math.max(4, Math.round((maxY - minY + 1) * 0.3));
1913
+ out.push({ x: Math.max(0, minX - pad), y: Math.max(0, minY - pad), w: maxX - minX + 1 + 2 * pad, h: maxY - minY + 1 + 2 * pad });
1914
+ }
1915
+ return out;
1916
+ }
1917
+ function valleyRow(gray, w, h, ink) {
1918
+ if (h < 24) return null;
1919
+ const isInk = (v) => ink.darkInk ? v <= ink.threshold : v > ink.threshold;
1920
+ const rows = [];
1921
+ for (let y = 0; y < h; y++) {
1922
+ let n = 0;
1923
+ for (let x = 0; x < w; x++) if (isInk(gray[y * w + x])) n++;
1924
+ rows.push(n);
1925
+ }
1926
+ const nz = rows.filter((n) => n > 0).sort((p, q) => p - q);
1927
+ if (!nz.length) return null;
1928
+ const med = nz[nz.length >> 1];
1929
+ let best = -1;
1930
+ for (let y = Math.floor(h * 0.3); y < Math.ceil(h * 0.7); y++) if (best < 0 || rows[y] < rows[best]) best = y;
1931
+ return best >= 0 && rows[best] <= med * 0.2 ? [best, best + 1] : null;
1932
+ }
1933
+ function midBlankRow(gray, w, h, ink) {
1934
+ if (h < 24) return null;
1935
+ const isInk = (v) => ink.darkInk ? v <= ink.threshold : v > ink.threshold;
1936
+ const colInk = new Uint32Array(w);
1937
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (isInk(gray[y * w + x])) colInk[x]++;
1938
+ const blank2 = (y) => {
1939
+ let n = 0;
1940
+ for (let x = 0; x < w; x++) if (colInk[x] < h * 0.85 && isInk(gray[y * w + x])) n++;
1941
+ return n <= Math.max(1, w * 0.02);
1942
+ };
1943
+ let best = null;
1944
+ for (let y = Math.floor(h * 0.3); y < Math.ceil(h * 0.7); y++) {
1945
+ if (!blank2(y)) continue;
1946
+ let a = y, b = y + 1;
1947
+ while (a > 0 && blank2(a - 1)) a--;
1948
+ while (b < h && blank2(b)) b++;
1949
+ if (!best || Math.abs((a + b) / 2 - h / 2) < Math.abs((best[0] + best[1]) / 2 - h / 2)) best = [a, b];
1950
+ y = b;
1951
+ }
1952
+ return best;
1953
+ }
1954
+ function placeholderSquares(rgba, width, height, items) {
1955
+ const dark = new Uint8Array(width * height);
1956
+ for (let p = 0, i = 0; p < dark.length; p++, i += 4) dark[p] = rgba[i] * 77 + rgba[i + 1] * 150 + rgba[i + 2] * 29 >> 8 < 128 ? 1 : 0;
1957
+ const covered = (x, y) => items.some((b) => x >= b.x - 2 && x < b.x + b.w + 2 && y >= b.y - 2 && y < b.y + b.h + 2);
1958
+ const seen = new Uint8Array(width * height);
1959
+ const squares = [], bars = [];
1960
+ const stack = [];
1961
+ for (let start = 0; start < dark.length; start++) {
1962
+ if (!dark[start] || seen[start]) continue;
1963
+ const c = { x0: width, y0: height, x1: -1, y1: -1, n: 0, px: [] };
1964
+ stack.push(start);
1965
+ seen[start] = 1;
1966
+ while (stack.length) {
1967
+ const p = stack.pop(), x = p % width, y = (p - x) / width;
1968
+ c.n++;
1969
+ if (c.px.length < 4e3) c.px.push(p);
1970
+ if (x < c.x0) c.x0 = x;
1971
+ if (x > c.x1) c.x1 = x;
1972
+ if (y < c.y0) c.y0 = y;
1973
+ if (y > c.y1) c.y1 = y;
1974
+ for (const q of [p - 1, p + 1, p - width, p + width]) if (q >= 0 && q < dark.length && !seen[q] && dark[q] && Math.abs(q % width - x) <= 1) {
1975
+ seen[q] = 1;
1976
+ stack.push(q);
1977
+ }
1978
+ if (c.n > 4e3) break;
1979
+ }
1980
+ while (stack.length) {
1981
+ const p = stack.pop();
1982
+ seen[p] = 1;
1983
+ }
1984
+ const w = c.x1 - c.x0 + 1, h = c.y1 - c.y0 + 1;
1985
+ if (c.n > 4e3 || covered(c.x0 + c.x1 >> 1, c.y0 + c.y1 >> 1)) continue;
1986
+ if (h >= 2 && h <= 6 && w >= 4 && w <= 30 && c.n >= w * h * 0.7) {
1987
+ bars.push(c);
1988
+ continue;
1989
+ }
1990
+ if (w < 12 || h < 12 || w > 60 || h > 60 || w > h * 1.33 || h > w * 1.33) continue;
1991
+ const at = (x, y) => dark[y * width + x] === 1;
1992
+ const row = (y) => {
1993
+ let k = 0;
1994
+ for (let x = c.x0; x <= c.x1; x++) if (at(x, y)) k++;
1995
+ return k / w;
1996
+ };
1997
+ const col = (x) => {
1998
+ let k = 0;
1999
+ for (let y = c.y0; y <= c.y1; y++) if (at(x, y)) k++;
2000
+ return k / h;
2001
+ };
2002
+ const edge = (vals) => Math.max(...vals) >= 0.8;
2003
+ const top = edge([row(c.y0), row(c.y0 + 1)]), bottom = edge([row(c.y1), row(c.y1 - 1)]), left = edge([col(c.x0), col(c.x0 + 1)]), right = edge([col(c.x1), col(c.x1 - 1)]);
2004
+ let inner = 0;
2005
+ for (let y = c.y0 + Math.ceil(h * 0.25); y <= c.y1 - Math.ceil(h * 0.25); y++) for (let x = c.x0 + Math.ceil(w * 0.25); x <= c.x1 - Math.ceil(w * 0.25); x++) if (at(x, y)) inner++;
2006
+ if (top && bottom && left && right && inner === 0) squares.push(c);
2007
+ }
2008
+ squares.sort((a, b) => a.y0 - b.y0 || a.x0 - b.x0);
2009
+ const out = [];
2010
+ const used = /* @__PURE__ */ new Set();
2011
+ for (const s0 of squares) {
2012
+ if (used.has(s0)) continue;
2013
+ const run = [s0];
2014
+ used.add(s0);
2015
+ const side = s0.y1 - s0.y0 + 1, cy = (s0.y0 + s0.y1) / 2;
2016
+ let text = "\u25A1";
2017
+ for (; ; ) {
2018
+ const last = run[run.length - 1];
2019
+ const next = squares.find((q) => !used.has(q) && Math.abs((q.y0 + q.y1) / 2 - cy) <= side * 0.3 && q.x0 > last.x1 && q.x0 - last.x1 <= side * 2);
2020
+ if (!next) break;
2021
+ const gap = next.x0 - last.x1;
2022
+ const bar = bars.find((b) => b.x0 > last.x1 && b.x1 < next.x0 && Math.abs((b.y0 + b.y1) / 2 - cy) <= side * 0.3);
2023
+ let stroke = 0;
2024
+ if (!bar) for (let y = Math.round(cy - side * 0.15); y <= Math.round(cy + side * 0.15); y++) {
2025
+ let k = 0;
2026
+ for (let x = last.x1 + 1; x < next.x0; x++) {
2027
+ k = dark[y * width + x] ? k + 1 : 0;
2028
+ if (k > stroke) stroke = k;
2029
+ }
2030
+ }
2031
+ if (bar || stroke >= Math.max(4, side * 0.25)) text += "-";
2032
+ else if (gap > side) break;
2033
+ text += "\u25A1";
2034
+ used.add(next);
2035
+ run.push(next);
2036
+ }
2037
+ const x0 = run[0].x0, x1 = run[run.length - 1].x1;
2038
+ out.push({ text, x: x0, y: s0.y0, w: x1 - x0 + 1, h: side, confidence: 0.9 });
2039
+ }
2040
+ return out;
2041
+ }
2042
+ function footerInkBox(rgba, width, height, boxes) {
2043
+ const y0 = Math.floor(height * 0.88), x0 = Math.floor(width * 0.3), x1 = Math.ceil(width * 0.7);
2044
+ let minX = Infinity, maxX = -1, minY = Infinity, maxY = -1;
2045
+ for (let y = y0; y < height; y++) for (let x = x0; x < x1; x++) {
2046
+ const p = (y * width + x) * 4;
2047
+ if (rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8 >= 128) continue;
2048
+ if (boxes.some((b) => x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h)) continue;
2049
+ if (x < minX) minX = x;
2050
+ if (x > maxX) maxX = x;
2051
+ if (y < minY) minY = y;
2052
+ if (y > maxY) maxY = y;
2053
+ }
2054
+ if (maxX < 0) return null;
2055
+ const bh = maxY - minY + 1;
2056
+ if (bh < height * 5e-3 || bh > height * 0.025 || maxX - minX + 1 > width * 0.2) return null;
2057
+ const pad = 4, bx = Math.max(0, minX - pad), by = Math.max(0, minY - pad);
2058
+ return { x: bx, y: by, w: Math.min(width, maxX + pad + 1) - bx, h: Math.min(height, maxY + pad + 1) - by };
2059
+ }
2060
+ function closingParens(rgba, width, items) {
2061
+ const out = [];
2062
+ const dark = (x, y) => {
2063
+ const p = (y * width + x) * 4;
2064
+ return rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 >> 8 < 128;
2065
+ };
2066
+ for (const it of items) {
2067
+ const t = it.text.replace(/\s+$/, "");
2068
+ if ((t.match(/\(/g)?.length ?? 0) <= (t.match(/\)/g)?.length ?? 0) || !/\([^()]*$/.test(t)) continue;
2069
+ const x0 = it.x + it.w + 2;
2070
+ const next = items.filter((o) => o !== it && o.x >= x0 && o.y < it.y + it.h && o.y + o.h > it.y).reduce((m, o) => Math.min(m, o.x), Infinity);
2071
+ let x1 = Math.min(width, next, x0 + it.h * 16);
2072
+ const pageH = Math.floor(rgba.length / 4 / width);
2073
+ const colInk = (x) => {
2074
+ let k = 0;
2075
+ for (let y = it.y; y < it.y + it.h; y++) if (dark(x, y)) k++;
2076
+ return k;
2077
+ };
2078
+ for (let x = x0; x < x1; x++) if (colInk(x) >= it.h * 0.9) {
2079
+ x1 = x;
2080
+ while (x1 > x0 && colInk(x1 - 1) >= it.h * 0.5) x1--;
2081
+ break;
2082
+ }
2083
+ const ruleRow = /* @__PURE__ */ new Set();
2084
+ for (let y = it.y; y < it.y + it.h; y++) {
2085
+ let k = 0;
2086
+ for (let x = x0; x < x1; x++) if (dark(x, y)) k++;
2087
+ if (k > (x1 - x0) * 0.8) for (const d of [-1, 0, 1]) ruleRow.add(y + d);
2088
+ }
2089
+ let minX = Infinity, maxX = -1, minY = Infinity, maxY = -1, cols = 0, prevOn = false, runs = 0;
2090
+ for (let x = x0; x < x1; x++) {
2091
+ let on = false;
2092
+ for (let y = it.y; y < it.y + it.h; y++) if (!ruleRow.has(y) && dark(x, y)) {
2093
+ on = true;
2094
+ if (y < minY) minY = y;
2095
+ if (y > maxY) maxY = y;
2096
+ }
2097
+ if (on) {
2098
+ cols++;
2099
+ if (!prevOn) runs++;
2100
+ if (x < minX) minX = x;
2101
+ maxX = x;
2102
+ }
2103
+ prevOn = on;
2104
+ }
2105
+ if (runs !== 1 || maxX - minX + 1 > it.h * 0.5 || maxY - minY + 1 < it.h * 0.6) continue;
2106
+ const inkRow = (y) => {
2107
+ for (let x = minX; x <= maxX; x++) if (dark(x, y)) return true;
2108
+ return false;
2109
+ };
2110
+ let over = 0;
2111
+ for (let y = minY - 1; y >= 0 && !ruleRow.has(y) && inkRow(y) && over <= it.h; y--) over++;
2112
+ for (let y = maxY + 1; y < pageH && !ruleRow.has(y) && inkRow(y) && over <= it.h; y++) over++;
2113
+ if (over > it.h * 0.6) continue;
2114
+ const meanX = (ya, yb) => {
2115
+ let sx = 0, k = 0;
2116
+ for (let y = ya; y < yb; y++) for (let x = minX; x <= maxX; x++) if (dark(x, y)) {
2117
+ sx += x;
2118
+ k++;
2119
+ }
2120
+ return k ? sx / k : NaN;
2121
+ };
2122
+ const ch = maxY - minY + 1, band = Math.max(1, Math.round(ch * 0.2));
2123
+ const ends = (meanX(minY, minY + band) + meanX(maxY + 1 - band, maxY + 1)) / 2, mid = meanX(minY + Math.floor(ch * 0.4), minY + Math.ceil(ch * 0.6));
2124
+ if (!(mid - ends >= 0.8)) continue;
2125
+ out.push({ text: ")", x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1, confidence: it.confidence });
2126
+ }
2127
+ return out;
2128
+ }
2129
+ var OcrEngine = class _OcrEngine {
2130
+ det;
2131
+ rec;
2132
+ dict;
2133
+ ort;
2134
+ sharp;
2135
+ constructor(parts) {
2136
+ this.det = parts.det;
2137
+ this.rec = parts.rec;
2138
+ this.dict = parts.dict;
2139
+ this.ort = parts.ort;
2140
+ this.sharp = parts.sharp;
2141
+ }
2142
+ static async create(models = DEFAULT_OCR_MODELS) {
2143
+ disableOrtTelemetry();
2144
+ const [ortMod, sharpModRaw] = await Promise.all([
2145
+ tryImport("onnxruntime-node", () => import("onnxruntime-node")),
2146
+ tryImport(
2147
+ "sharp",
2148
+ () => import("sharp")
2149
+ )
2150
+ ]);
2151
+ const sharpAny = sharpModRaw;
2152
+ const sharpMod = typeof sharpAny === "function" ? sharpAny : sharpAny.default ?? sharpAny;
2153
+ const sessionOpts = {
2154
+ graphOptimizationLevel: "all",
2155
+ logSeverityLevel: 3
2156
+ // paddle2onnx 변환 잔여물 W 로그 폭주 억제
2157
+ };
2158
+ const local = (s) => "spec" in s ? Promise.resolve(null) : verifiedBytes(s);
2159
+ const [detBytes, recBytes, dictBytes] = await Promise.all([local(models.det), local(models.rec), local(models.dict)]);
2160
+ const eps = ortProvidersSetting();
2161
+ const session = (s, bytes) => bytes ? createOrtSession((o) => ortMod.InferenceSession.create(bytes, o), sessionOpts).catch((e) => {
2162
+ throw new KordocError(`OCR \uBAA8\uB378\uC744 \uC5F4\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${basename(ocrSourcePath(s))} \u2014 ONNX \uBAA8\uB378\uC774 \uC544\uB2C8\uAC70\uB098 \uC190\uC0C1\uB410\uAC70\uB098 EP(${eps ?? "cpu"})\uB97C \uC4F8 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${e.message}`);
2163
+ }) : createOrtSession((o) => ortMod.InferenceSession.create(ocrSourcePath(s), o), sessionOpts).catch((e) => {
2164
+ if (!eps) throw e;
2165
+ throw new KordocError(`OCR \uC138\uC158\uC744 \uB9CC\uB4E4\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4 \u2014 KORDOC_ORT_PROVIDERS(${eps}) \uB97C \uD655\uC778\uD558\uC138\uC694: ${e.message}`);
2166
+ });
2167
+ const [det, rec, dictYml] = await Promise.all([
2168
+ session(models.det, detBytes),
2169
+ session(models.rec, recBytes),
2170
+ dictBytes ? new TextDecoder().decode(dictBytes) : readFile(ocrSourcePath(models.dict), "utf-8")
2171
+ ]);
2172
+ const dict = parseCharacterDict(dictYml);
2173
+ if (dict.length === 0) {
2174
+ throw "spec" in models.dict ? new Error("OCR \uC0AC\uC804 \uD30C\uC2F1 \uC2E4\uD328 \u2014 \uBAA8\uB378 \uCE90\uC2DC\uB97C \uC0AD\uC81C \uD6C4 \uC7AC\uB2E4\uC6B4\uB85C\uB4DC\uD558\uC138\uC694") : new KordocError(`OCR \uC0AC\uC804 \uD30C\uC2F1 \uC2E4\uD328 \u2014 ${basename(models.dict.file.path)} \uC5D0 PostProcess.character_dict \uBAA9\uB85D\uC774 \uC5C6\uC2B5\uB2C8\uB2E4`);
2175
+ }
2176
+ return new _OcrEngine({ det, rec, dict, ort: ortMod, sharp: sharpMod });
2177
+ }
2178
+ /** onnxruntime-node 1.14+ InferenceSession.release() — 구버전은 무시 */
2179
+ async destroy() {
2180
+ for (const s of [this.det, this.rec]) {
2181
+ const rel = s.release;
2182
+ if (typeof rel === "function") {
2183
+ try {
2184
+ await rel.call(s);
2185
+ } catch {
2186
+ }
2187
+ }
2188
+ }
2189
+ }
2190
+ /**
2191
+ * 페이지 RGBA 픽셀 → 텍스트 라인 인식.
2192
+ * 반환 좌표는 입력 픽셀 기준. 라인은 위→아래, 좌→우 정렬.
2193
+ * @param stats 저신뢰(conf<0.5) 폐기 라인 카운트 출력 — 종전엔 무음 폐기라 관측 불가
2194
+ */
2195
+ /**
2196
+ * 박스 바깥 줄 머리 □ — 가는 테두리 □ 는 검출기가 글줄 박스에 넣지 않아 박스 왼쪽에 따로 남고 통째로 빠진다(장흥 계획 "□ 비전 및 목표",
2197
+ * 함평 "□ 국내외 여건"). 한글 넷 이상 줄의 박스 왼쪽 높이 1.6배 띠에 다른 박스가 없고, 넓힌 crop 의 맨 앞 덩어리가 속 빈 □ 인데
2198
+ * 박스 첫 글자에 걸치지 않으면 붙인다. 이 □ 는 글자 높이만큼 커(1.0배) 박스 안 판정 상한(0.92)을 1.05 로 푼다
2199
+ */
2200
+ outerSquare(rgba, width, it, items) {
2201
+ if (/^[◎●▪□■▣❐❏○ㅇ‣\u2022·]/.test(it.text) || (it.text.match(/[가-힣]/g) ?? []).length < 4) return;
2202
+ const ext = Math.round(it.h * 1.6), x = Math.max(0, it.x - ext);
2203
+ if (it.x - x < it.h * 0.8) return;
2204
+ if (items.some((o) => o !== it && o.x < it.x && o.x + o.w > x && o.y < it.y + it.h && o.y + o.h > it.y)) return;
2205
+ const box = { x, y: it.y, w: it.x + it.w - x, h: it.h };
2206
+ const g = grayCrop(rgba, width, box);
2207
+ const b = leadingBullet(g, box.w, box.h, inkStats(g), it.x - x, 1.05);
2208
+ if (b?.mark !== "\u25A1" || b.covers) return;
2209
+ const ink = inkStats(g), on = (v) => ink.darkInk ? v <= ink.threshold : v > ink.threshold;
2210
+ let left = 0;
2211
+ while (left < it.x - x && !Array.from({ length: box.h }, (_, y) => g[y * box.w + left]).some(on)) left++;
2212
+ it.text = "\u25A1 " + it.text;
2213
+ it.w += it.x - (x + left);
2214
+ it.x = x + left;
2215
+ }
2216
+ async recognizePage(rgba, width, height, stats, tuning = DEFAULT_OCR_TUNING, cellRules = [], rowRules = []) {
2217
+ if (width < DET_MIN_SIZE || height < DET_MIN_SIZE) return [];
2218
+ const detected = await this.detect(rgba, width, height, tuning, stats);
2219
+ if (tuning.orientPage && stats && detected.length >= ORIENT_MIN_BOXES) {
2220
+ const tall = detected.filter((b) => b.h >= b.w * TALL_RATIO);
2221
+ if (tall.length >= detected.length * ORIENT_TALL_SHARE) {
2222
+ const sample = [...tall].sort((a, b) => b.h - a.h).slice(0, ORIENT_SAMPLE);
2223
+ const rots = [0, 90, 270];
2224
+ const probe = await this.recognizeJobs(rgba, width, sample.flatMap((box, group2) => rots.map((rot) => ({ box, rot, group: group2 }))), tuning.recBatch);
2225
+ const mean = (k) => sample.reduce((sum, _, i) => sum + (probe[i * rots.length + k]?.confidence ?? 0), 0) / sample.length;
2226
+ const [m0, m90, m270] = rots.map((_, k) => mean(k));
2227
+ const best2 = Math.max(m90, m270);
2228
+ if (best2 >= ORIENT_MIN_CONF && best2 >= m0 + ORIENT_GAIN) {
2229
+ stats.pageRotation = m90 >= m270 ? 90 : 270;
2230
+ return [];
2231
+ }
2232
+ }
2233
+ }
2234
+ if (tuning.flipProbe && stats && detected.length >= FLIP_MIN_BOXES) {
2235
+ const wide = detected.filter((b) => b.w >= b.h * FLIP_WIDE_RATIO);
2236
+ if (wide.length >= FLIP_MIN_BOXES) {
2237
+ const sample = [...wide].sort((a, b) => b.w - a.w).slice(0, ORIENT_SAMPLE);
2238
+ const probe = await this.recognizeJobs(rgba, width, sample.flatMap((box, group2) => [0, 180].map((rot) => ({ box, rot, group: group2 }))), tuning.recBatch);
2239
+ const mean = (k) => sample.reduce((sum, _, i) => sum + (probe[i * 2 + k]?.confidence ?? 0), 0) / sample.length;
2240
+ if (mean(1) >= ORIENT_MIN_CONF && mean(1) >= mean(0) + ORIENT_GAIN) {
2241
+ stats.pageRotation = 180;
2242
+ return [];
2243
+ }
2244
+ }
2245
+ }
2246
+ const rows = rowRules.length ? detected.flatMap((b) => splitBoxAtRowRules(b, rowRules)) : detected;
2247
+ const boxes = cellRules.length ? rows.flatMap((b) => splitBoxAtCellRules(b, cellRules)) : rows;
2248
+ const footer = tuning.postprocess ? footerInkBox(rgba, width, height, boxes) : null;
2249
+ const jobs = [];
2250
+ const joins = [];
2251
+ let group = 0;
2252
+ for (const b of boxes) {
2253
+ const gray = grayCrop(rgba, width, b);
2254
+ const ink = inkStats(gray);
2255
+ if (tuning.minInkContrast > 0 && ink.contrast < tuning.minInkContrast) continue;
2256
+ if (tuning.minInkContrast > 0 && ink.inkRatio < MIN_INK_RATIO) continue;
2257
+ if (tuning.splitTall && b.h >= b.w * TALL_RATIO) {
2258
+ const bands = splitRowBands(gray, b.w, b.h, ink, 0.45);
2259
+ if (bands.length >= 2) {
2260
+ for (const sub of bandBoxes(b, bands, height)) jobs.push({ box: sub, rot: 0, group: group++ });
2261
+ continue;
2262
+ }
2263
+ const bh = bands.length === 1 ? bands[0].y1 - bands[0].y0 : 0;
2264
+ const outside = (y0, y1) => {
2265
+ const isInk = (v) => ink.darkInk ? v <= ink.threshold : v > ink.threshold;
2266
+ for (let y = 0; y < b.h; y++) if (y < y0 || y >= y1) {
2267
+ for (let x = 0; x < b.w; x++) if (isInk(gray[y * b.w + x])) return true;
2268
+ }
2269
+ return false;
2270
+ };
2271
+ const sole = bh && bh < b.h * SOLE_BAND_RATIO && bh >= Math.max(12, b.h * 0.25) && bands[0].x1 - bands[0].x0 >= bh * 0.5 && ink.inkRatio < 0.35 && outside(bands[0].y0, bands[0].y1) ? bandBoxes(b, bands, height)[0] : void 0;
2272
+ if (sole) {
2273
+ jobs.push({ box: sole, rot: 0, group: group++ });
2274
+ continue;
2275
+ }
2276
+ if (b.h >= b.w * ROTATE_RATIO) {
2277
+ for (const rot of [0, 90, 270]) jobs.push({ box: b, rot, group });
2278
+ group++;
2279
+ continue;
2280
+ }
2281
+ }
2282
+ const trim = tuning.trimEdges ? edgeTrim(gray, b.w, b.h, ink) : null;
2283
+ const keep = trim ? { ...trim, bg: median(gray) } : void 0;
2284
+ const leaders = tuning.splitLeaders ? leaderRuns(gray, b.w, b.h, ink, LEADER_MIN_DOTS) : [];
2285
+ if (leaders.length) {
2286
+ const join = joins.length;
2287
+ joins.push({ box: b, parts: [], trailDots: false });
2288
+ let x0 = 0, dots = false;
2289
+ for (const [a, c] of [...leaders, [b.w, b.w]]) {
2290
+ const bare = { x: b.x + x0, y: b.y, w: a - x0, h: b.h };
2291
+ const end = c > a ? Math.min(c, a + Math.round(b.h * LEADER_CONTEXT)) : a;
2292
+ x0 = c;
2293
+ if (bare.w >= DET_MIN_SIZE && inkStats(grayCrop(rgba, width, bare)).contrast >= Math.max(1, tuning.minInkContrast)) {
2294
+ jobs.push({ box: { ...bare, w: end - (bare.x - b.x) }, rot: 0, group: group++, join, dotsBefore: dots, trimDots: end > a });
2295
+ dots = false;
2296
+ }
2297
+ if (c > a) dots = true;
2298
+ }
2299
+ joins[join].trailDots = dots;
2300
+ continue;
2301
+ }
2302
+ if (keep) jobs.push({ box: b, rot: 0, group, keep });
2303
+ jobs.push({ box: b, rot: 0, group: group++ });
2304
+ }
2305
+ if (footer) jobs.push({ box: footer, rot: 0, group: group++, footer: true });
2306
+ const results = await this.recognizeJobs(rgba, width, jobs, tuning.recBatch, tuning.lineCandidates, tuning.chars);
2307
+ const candidatesOf = tuning.lineCandidates ? /* @__PURE__ */ new Map() : void 0;
2308
+ const charsOf = tuning.chars !== void 0 ? /* @__PURE__ */ new Map() : void 0;
2309
+ const best = /* @__PURE__ */ new Map();
2310
+ const score = (job, confidence) => confidence - (job.keep ? KEEP_MARGIN : 0);
2311
+ jobs.forEach((job, i) => {
2312
+ const r = results[i];
2313
+ if (!r) return;
2314
+ const cur = best.get(job.group);
2315
+ if (!cur || score(job, r.confidence) > score(cur.job, cur.confidence)) best.set(job.group, { job, ...r });
2316
+ });
2317
+ jobs.forEach((job, i) => {
2318
+ const r = results[i], cur = best.get(job.group);
2319
+ if (!job.keep || !r || !cur || cur.job === job) return;
2320
+ const b = cur.text.replace(/\s/g, "");
2321
+ if (r.text.replace(/\s/g, "") === "\xB7" + b && /^[가-힣]/.test(b)) best.set(job.group, { ...cur, text: "\xB7" + cur.text, steps: [r.steps[0], ...cur.steps] });
2322
+ });
2323
+ let items = [];
2324
+ const boxOf = /* @__PURE__ */ new Map();
2325
+ const retry = [];
2326
+ const lowMarks = [];
2327
+ const ringReads = /* @__PURE__ */ new Map();
2328
+ if (tuning.postprocess) {
2329
+ const asks = [...best.values()].flatMap((r) => r.job.rot === 0 ? ringAsks(rgba, width, r.job.box, r.text, r.steps, r.stepPx).map((a) => ({ ...a, job: r.job })) : []);
2330
+ const res = asks.length ? await this.recognizeJobs(rgba, width, asks.map((a, k) => ({ box: a.box, rot: 0, group: k })), tuning.recBatch) : [];
2331
+ asks.forEach((a, k) => {
2332
+ const glyph = res[k] ? ringGlyph(res[k].text, a.jamo, res[k].confidence) : null;
2333
+ if (glyph) ringReads.set(a.job, [...ringReads.get(a.job) ?? [], { x0: a.x0, x1: a.x1, glyph }]);
2334
+ });
2335
+ }
2336
+ for (const r of best.values()) {
2337
+ const { job, confidence, stepPx } = r;
2338
+ const { text: read, steps } = tuning.postprocess && job.rot === 0 ? trimInklessEnds(rgba, width, job.box, r.text, r.steps, stepPx) : r;
2339
+ const note = {};
2340
+ const raw = tuning.postprocess && job.rot === 0 ? restoreGlyphs(rgba, width, job.box, read, steps, stepPx, note, ringReads.get(job)) : read;
2341
+ let text = tuning.postprocess ? restoreSymbols(raw.trim(), note.ringLead) : raw;
2342
+ if (!text.trim()) continue;
2343
+ if (tuning.postprocess && job.rot === 0 && text !== "/" && /^[(:;/)]+$/.test(text) && text.includes("/")) {
2344
+ const g = grayCrop(rgba, width, job.box);
2345
+ if (tallInkCount(g, job.box.w, job.box.h, inkStats(g)) === 1) text = "/";
2346
+ }
2347
+ let ringByShape = false;
2348
+ if (tuning.postprocess && job.rot === 0 && !/^[◎●▪□■▣❐❏○ㅇ◆◇◈]/.test(text)) {
2349
+ const chars = [...read], k = chars.findIndex((c) => c.trim());
2350
+ if (k >= 0 && steps.length === chars.length) {
2351
+ const g = grayCrop(rgba, width, job.box);
2352
+ const b = leadingBullet(g, job.box.w, job.box.h, inkStats(g), (steps[k] + 0.5) * stepPx);
2353
+ const body = (text.match(/[가-힣]/g) ?? []).length >= 4;
2354
+ const miss = /^[Oo0•·ㆍ∙‧○]/.test(text);
2355
+ if (b?.mark === "\u25CE" && b.covers && /^[Oo0○©]/.test(text)) {
2356
+ text = b.mark + " " + text.slice(1).trimStart();
2357
+ ringByShape = true;
2358
+ } else if (b?.mark === "\u25A1" || b?.mark === "\u25A3") {
2359
+ if (!b.covers && body) text = b.mark + " " + text;
2360
+ } else if (b?.mark === "\u25C6" || b?.mark === "\u25C7" || b?.mark === "\u25C8") {
2361
+ if (b.covers ? /^[\p{S}\p{P}]/u.test(text) : body) text = b.covers ? b.mark + " " + text.slice(1).trimStart() : b.mark + " " + text;
2362
+ } else if (b?.mark === "\u2023") {
2363
+ if (b.covers ? text.startsWith("\u2192") : body) text = b.covers ? b.mark + " " + text.slice(1).trimStart() : b.mark + " " + text;
2364
+ } else if (b?.mark === "\u2750" || b?.mark === "\u274F") {
2365
+ if (b.covers ? /^[ㅁ口]/.test(text) : body) text = b.covers ? b.mark + text.slice(1) : b.mark + " " + text;
2366
+ } else if (b && b.mark !== "\u25CE" && body) text = b.covers ? miss ? b.mark + " " + text.slice(1).trimStart() : text : b.mark + " " + text;
2367
+ else if (!b && body && /^[가-힣]/.test(chars[k]) && leadingRing(g, job.box.w, job.box.h, inkStats(g), (steps[k] + 0.5) * stepPx)) text = "\u25CB " + text;
2368
+ }
2369
+ }
2370
+ if (tuning.postprocess && /^\d/.test(text) && job.rot === 0) {
2371
+ const g = grayCrop(rgba, width, job.box);
2372
+ const tri = leadingTriangle(g, job.box.w, job.box.h, inkStats(g));
2373
+ if (tri) text = tri + text;
2374
+ }
2375
+ if (tuning.postprocess && text === "\u2192" && job.rot === 0 && job.join === void 0) {
2376
+ const g = grayCrop(rgba, width, job.box);
2377
+ text = arrowGlyph(g, job.box.w, job.box.h, inkStats(g)) ?? text;
2378
+ }
2379
+ if (job.footer) {
2380
+ if (!/^[-\u2013\u2014]?\s*(?:\d{1,4}|[ivxIVXⅰ-ⅹⅠ-Ⅹ]{1,4})\s*[-\u2013\u2014]?$/.test(text.trim())) continue;
2381
+ text = text.replace(/[\u2013\u2014]/g, "-");
2382
+ }
2383
+ if (tuning.postprocess && isDotFragment(text)) continue;
2384
+ if (confidence < tuning.textScore && !(ringByShape && text.trim() === "\u25CE")) {
2385
+ if (tuning.postprocess && job.rot === 0 && job.join === void 0 && !job.footer) retry.push(job.box);
2386
+ if (tuning.postprocess && job.rot === 0 && job.join === void 0 && !job.footer && MARK_GLYPH.test(text.trim()) && confidence >= LOW_MARK_SCORE) {
2387
+ lowMarks.push({ text: text.trim(), ...this.itemBox(rgba, width, job.box, tuning), confidence });
2388
+ }
2389
+ if (stats) {
2390
+ stats.droppedLowConf++;
2391
+ stats.dropped?.push({ text, ...this.itemBox(rgba, width, job.box, tuning), confidence });
2392
+ if (r.candidates && job.join === void 0 && stats.dropped) stats.dropped[stats.dropped.length - 1].candidates = r.candidates;
2393
+ if (r.charScores && job.rot === 0 && job.join === void 0 && stats.dropped) {
2394
+ const it = stats.dropped[stats.dropped.length - 1], list2 = lineChars(r.text, r.steps, r.charScores, job.box.x, r.stepPx, it);
2395
+ const fit = list2 && joinChars(list2, it.text);
2396
+ if (fit) it.chars = fit;
2397
+ }
2398
+ }
2399
+ continue;
2400
+ }
2401
+ if (job.join !== void 0) {
2402
+ if (job.trimDots) text = text.replace(/[\s.:\u00b7\u2022\u2024\u2025\u2026\u2219\u22c5\u318d]+$/u, "");
2403
+ if (text) joins[job.join].parts.push({ x: job.box.x, text, dotsBefore: job.dotsBefore === true, confidence });
2404
+ continue;
2405
+ }
2406
+ const item = { text, ...this.itemBox(rgba, width, job.box, tuning), confidence };
2407
+ if (r.candidates) candidatesOf?.set(item, { text, list: r.candidates });
2408
+ const list = r.charScores && job.rot === 0 ? lineChars(r.text, r.steps, r.charScores, job.box.x, r.stepPx, item) : void 0;
2409
+ if (list) charsOf?.set(item, list);
2410
+ if (job.rot === 0) rememberOcrTextGaps(item, findOcrTextGaps(rgba, width, job.box, read, text, steps, stepPx));
2411
+ if (job.rot === 0 && job.keep === void 0) boxOf.set(item, job.box);
2412
+ items.push(item);
2413
+ }
2414
+ for (const stretch of tuning.postprocess ? NUMBER_STRETCH : []) {
2415
+ const fix = items.filter((it) => boxOf.has(it) && singleNumberText(it.text) && badThousands(it.text));
2416
+ if (!fix.length) break;
2417
+ const res = await this.recognizeJobs(rgba, width, fix.map((it, k) => ({ box: boxOf.get(it), rot: 0, group: k, stretch })), tuning.recBatch);
2418
+ fix.forEach((it, k) => {
2419
+ const r = res[k];
2420
+ if (!r || /\s/.test(r.text.trim()) || badThousands(r.text) || r.confidence < it.confidence - 0.05) return;
2421
+ const merged = rereadNumberText(it.text, r.text);
2422
+ if (merged === null) return;
2423
+ it.text = merged;
2424
+ rememberOcrTextGaps(it, findOcrTextGaps(rgba, width, boxOf.get(it), r.text, it.text, r.steps, r.stepPx));
2425
+ });
2426
+ }
2427
+ const pairs = tuning.postprocess ? items.filter((it) => boxOf.has(it) && NUMBER_PAIR.test(it.text.trim())) : [];
2428
+ let undotted = pairs.filter((it) => !DECIMAL_PAIR.test(it.text.trim()));
2429
+ if (pairs.length >= 5 && pairs.length - undotted.length >= pairs.length * 0.6) {
2430
+ for (const stretch of NUMBER_STRETCH) {
2431
+ if (!undotted.length) break;
2432
+ const res = await this.recognizeJobs(rgba, width, undotted.map((it, k) => ({ box: boxOf.get(it), rot: 0, group: k, stretch })), tuning.recBatch);
2433
+ undotted = undotted.filter((it, k) => {
2434
+ const r = res[k];
2435
+ const fixed = r && r.confidence >= it.confidence - 0.05 ? rereadDecimalPair(it.text, r.text) : null;
2436
+ if (fixed === null) return true;
2437
+ it.text = fixed;
2438
+ return false;
2439
+ });
2440
+ }
2441
+ }
2442
+ if (tuning.postprocess) {
2443
+ const hs = [...boxOf.values()].map((b) => b.h).sort((x, y) => x - y);
2444
+ const medH = hs.length ? hs[hs.length >> 1] : 0;
2445
+ const tall = items.filter((it) => {
2446
+ const b = boxOf.get(it);
2447
+ return b && medH && b.h >= medH * TALL_LINE_RATIO && it.confidence < TALL_LINE_SCORE && b.w >= b.h * 3 && (it.text.match(/[가-힣]/g) ?? []).length >= 2;
2448
+ });
2449
+ const halves = [];
2450
+ for (const it of tall) {
2451
+ const b = boxOf.get(it);
2452
+ const gray = grayCrop(rgba, width, b);
2453
+ const cut = midBlankRow(gray, b.w, b.h, inkStats(gray)) ?? valleyRow(gray, b.w, b.h, inkStats(gray));
2454
+ if (cut) halves.push({ it, top: { ...b, h: cut[0] }, bottom: { ...b, y: b.y + cut[1], h: b.h - cut[1] } });
2455
+ }
2456
+ const res = halves.length ? await this.recognizeJobs(rgba, width, halves.flatMap((hv, k) => [{ box: hv.top, rot: 0, group: 2 * k }, { box: hv.bottom, rot: 0, group: 2 * k + 1 }]), tuning.recBatch) : [];
2457
+ halves.forEach((hv, k) => {
2458
+ const a = res[2 * k], c = res[2 * k + 1];
2459
+ const need = Math.max(hv.it.confidence + 0.1, 0.85);
2460
+ const covered = (bx) => items.some((o) => o !== hv.it && Math.max(0, Math.min(bx.x + bx.w, o.x + o.w) - Math.max(bx.x, o.x)) * Math.max(0, Math.min(bx.y + bx.h, o.y + o.h) - Math.max(bx.y, o.y)) * 2 > bx.w * bx.h);
2461
+ const parts = [];
2462
+ for (const [r, box] of [[a, hv.top], [c, hv.bottom]]) {
2463
+ if (r && r.confidence >= need && r.text.trim()) parts.push({ text: restoreSymbols(restoreGlyphs(rgba, width, box, r.text, r.steps, r.stepPx).trim()), ...this.itemBox(rgba, width, box, tuning), confidence: r.confidence });
2464
+ else if (!covered(box)) return;
2465
+ }
2466
+ if (parts.length) items.splice(items.indexOf(hv.it), 1, ...parts);
2467
+ });
2468
+ }
2469
+ const blank2 = tuning.postprocess ? jobs.filter((j) => j.rot === 0 && j.join === void 0 && !j.footer && !j.keep && !best.has(j.group)).map((j) => j.box) : [];
2470
+ const sure = [...boxOf.entries()].filter(([it, b]) => it.confidence >= RETRY_SCORE && b.w >= b.h * 1.5).map(([, b]) => b.h).sort((a, b) => a - b);
2471
+ const lineH = sure.length >= 8 ? sure[sure.length >> 1] : 0;
2472
+ const valleySplit = (b) => {
2473
+ if (!lineH || b.h >= b.w * TALL_RATIO || b.h < lineH * MULTI_LINE_RATIO || b.w < lineH * 2) return null;
2474
+ const ruled = (left) => cellRules.filter((r) => left ? r.x1 <= b.x + 2 : r.x1 >= b.x + b.w - 2).reduce((s, r) => s + Math.max(0, Math.min(r.y2, b.y + b.h) - Math.max(r.y1, b.y)), 0) >= b.h * 0.8;
2475
+ if (!ruled(true) || !ruled(false)) return null;
2476
+ const gray = grayCrop(rgba, width, b), ink = inkStats(gray);
2477
+ const n = Math.min(4, Math.round(b.h / lineH));
2478
+ for (const k of [n, n - 1]) {
2479
+ const bands = valleyBands(gray, b.w, b.h, ink, k);
2480
+ if (bands) return bandBoxes(b, bands, height);
2481
+ }
2482
+ return null;
2483
+ };
2484
+ if (tuning.postprocess && lineH) {
2485
+ const weak = items.flatMap((it) => {
2486
+ const b = boxOf.get(it);
2487
+ const parts = b && it.confidence < WEAK_LINE_SCORE ? valleySplit(b) : null;
2488
+ return parts && parts.length >= 2 ? [{ it, parts }] : [];
2489
+ });
2490
+ const flat = weak.flatMap((w) => w.parts);
2491
+ const res = flat.length ? await this.recognizeJobs(rgba, width, flat.map((box, k2) => ({ box, rot: 0, group: k2 })), tuning.recBatch) : [];
2492
+ let k = 0;
2493
+ for (const w of weak) {
2494
+ const rs = res.slice(k, k += w.parts.length);
2495
+ if (rs.some((r) => !r || r.confidence < RETRY_SCORE || !r.text.trim())) continue;
2496
+ if (rs.reduce((s, r) => s + r.confidence, 0) / rs.length < w.it.confidence + 0.15) continue;
2497
+ const parts = w.parts.map((box, i) => ({ text: restoreSymbols(restoreGlyphs(rgba, width, box, rs[i].text, rs[i].steps, rs[i].stepPx).trim()), ...this.itemBox(rgba, width, box, tuning), confidence: rs[i].confidence }));
2498
+ items.splice(items.indexOf(w.it), 1, ...parts);
2499
+ }
2500
+ }
2501
+ if (retry.length || blank2.length) {
2502
+ const subs = [];
2503
+ const valleyed = /* @__PURE__ */ new Set();
2504
+ const stacks = [];
2505
+ for (const b of [...retry, ...blank2]) {
2506
+ const gray = grayCrop(rgba, width, b);
2507
+ const ink = inkStats(gray);
2508
+ const cut = retry.includes(b) ? midBlankRow(gray, b.w, b.h, ink) : null;
2509
+ const inCell = cellRules.some((r) => r.x1 <= b.x + 2 && r.y1 <= b.y && r.y2 >= b.y + b.h) && cellRules.some((r) => r.x1 >= b.x + b.w - 2 && r.y1 <= b.y && r.y2 >= b.y + b.h);
2510
+ if (cut && b.w >= (inCell ? 2 : 3) * Math.max(cut[0], b.h - cut[1])) {
2511
+ subs.push({ ...b, h: cut[0] }, { ...b, y: b.y + cut[1], h: b.h - cut[1] });
2512
+ continue;
2513
+ }
2514
+ const valley = retry.includes(b) ? valleySplit(b) : null;
2515
+ if (valley) {
2516
+ subs.push(...valley);
2517
+ for (const v of valley) valleyed.add(v);
2518
+ continue;
2519
+ }
2520
+ const bands = stackedGlyphBands(gray, b.w, b.h, ink);
2521
+ if (bands) stacks.push({ box: b, parts: bandBoxes(b, bands, height), word: bands.every((x, i) => i === 0 || x.y0 - bands[i - 1].y1 <= STACK_WORD_GAP * Math.max(x.y1 - x.y0, bands[i - 1].y1 - bands[i - 1].y0)) });
2522
+ }
2523
+ const overlap = (a, o) => Math.max(0, Math.min(a.x + a.w, o.x + o.w) - Math.max(a.x, o.x)) * Math.max(0, Math.min(a.y + a.h, o.y + o.h) - Math.max(a.y, o.y));
2524
+ for (let k2 = subs.length - 1; k2 >= 0; k2--) if (subs[k2].h < 8 || items.some((o) => overlap(subs[k2], o) * 2 > subs[k2].w * subs[k2].h)) subs.splice(k2, 1);
2525
+ const res = subs.length ? await this.recognizeJobs(rgba, width, subs.map((box, k2) => ({ box, rot: 0, group: k2 })), tuning.recBatch) : [];
2526
+ subs.forEach((box, k2) => {
2527
+ const r = res[k2];
2528
+ if (!r || r.confidence < RETRY_SCORE) return;
2529
+ let text = restoreSymbols(restoreGlyphs(rgba, width, box, r.text, r.steps, r.stepPx).trim());
2530
+ if (valleyed.has(box) && !/[‘'"“]/u.test(text)) text = text.replace(/(?<=[가-힣])[’”]$/u, "");
2531
+ if ((text.match(/[\p{L}\p{N}]/gu) ?? []).length < 2) return;
2532
+ if (valleyed.has(box) && items.some((o) => overlap(box, o) > 0 && o.text.replace(/\s/g, "").includes(text.replace(/\s/g, "")))) return;
2533
+ items.push({ text, ...this.itemBox(rgba, width, box, tuning), confidence: r.confidence });
2534
+ });
2535
+ const free = stacks.filter((st) => !items.some((o) => overlap(st.box, o) * 2 > st.box.w * st.box.h));
2536
+ const parts = free.flatMap((st) => st.parts);
2537
+ const partRes = parts.length ? await this.recognizeJobs(rgba, width, parts.map((box, k2) => ({ box, rot: 0, group: k2 })), tuning.recBatch) : [];
2538
+ let k = 0;
2539
+ for (const st of free) {
2540
+ const rs = partRes.slice(k, k += st.parts.length);
2541
+ if (rs.length !== st.parts.length || rs.some((r) => !r || r.confidence < RETRY_SCORE || !/^[가-힣]$/.test(r.text.trim()))) continue;
2542
+ if (st.word) items.push({ text: rs.map((r) => r.text.trim()).join(""), ...this.itemBox(rgba, width, st.box, tuning), confidence: Math.min(...rs.map((r) => r.confidence)) });
2543
+ else st.parts.forEach((box, i) => items.push({ text: rs[i].text.trim(), ...this.itemBox(rgba, width, box, tuning), confidence: rs[i].confidence }));
2544
+ }
2545
+ }
2546
+ for (const m of lowMarks) {
2547
+ const aligned = (o) => Math.abs(o.x + o.w / 2 - (m.x + m.w / 2)) <= m.w / 2 || Math.abs(o.y + o.h / 2 - (m.y + m.h / 2)) <= m.h / 2;
2548
+ const peer = items.some((o) => o.text.trim() === m.text && o.confidence >= tuning.textScore && Math.abs(o.w - m.w) <= m.w * 0.2 && Math.abs(o.h - m.h) <= m.h * 0.2 && aligned(o));
2549
+ const taken = items.some((o) => Math.min(m.x + m.w, o.x + o.w) > Math.max(m.x, o.x) && Math.min(m.y + m.h, o.y + o.h) > Math.max(m.y, o.y));
2550
+ if (peer && !taken) items.push(m);
2551
+ }
2552
+ const leaderEnds = /* @__PURE__ */ new Map();
2553
+ for (const j of joins) {
2554
+ if (!j.parts.length) continue;
2555
+ j.parts.sort((a, b) => a.x - b.x);
2556
+ let text = "";
2557
+ const junk = /[\s.:\u00b7\u2022\u2024\u2025\u2026\u2219\u22c5\u318d]+$/u;
2558
+ for (const p of j.parts) {
2559
+ if (p.dotsBefore) text = text.replace(junk, "");
2560
+ const t = p.dotsBefore ? p.text.replace(/^[\s.:\u00b7\u2022\u2024\u2025\u2026\u2219\u22c5\u318d]+/u, "") : p.text;
2561
+ if (t) text += (p.dotsBefore ? text ? " \u2026 " : "\u2026" : text ? " " : "") + t;
2562
+ }
2563
+ if (j.trailDots) text = text.replace(junk, "") + " \u2026";
2564
+ text = text.trim();
2565
+ if (!text) continue;
2566
+ const item = { text, ...this.itemBox(rgba, width, j.box, tuning), confidence: Math.min(...j.parts.map((p) => p.confidence)) };
2567
+ items.push(item);
2568
+ leaderEnds.set(item, { lead: text.startsWith("\u2026"), trail: j.trailDots });
2569
+ }
2570
+ if (leaderEnds.size) items = joinLeaderItems(items, leaderEnds);
2571
+ if (tuning.postprocess) items = dropNestedFragments(items);
2572
+ if (tuning.postprocess) for (const it of items) this.outerSquare(rgba, width, it, items);
2573
+ if (tuning.postprocess) items.push(...closingParens(rgba, width, items));
2574
+ if (tuning.postprocess) items.push(...placeholderSquares(rgba, width, height, items));
2575
+ if (tuning.postprocess) items.push(...rowHeadDashes(rgba, width, items));
2576
+ if (tuning.postprocess) {
2577
+ const tails = rowTailBoxes(rgba, width, items);
2578
+ if (tails.length) {
2579
+ const res = await this.recognizeJobs(rgba, width, tails.map((box, k) => ({ box, rot: 0, group: k })), tuning.recBatch);
2580
+ tails.forEach((box, k) => {
2581
+ const t = res[k]?.text.trim() ?? "";
2582
+ if (/^\d{1,4}$/.test(t) && (res[k]?.confidence ?? 0) >= tuning.textScore) items.push({ text: t, ...this.itemBox(rgba, width, box, tuning), confidence: res[k].confidence });
2583
+ });
2584
+ }
2585
+ const heads = rowHeadBoxes(rgba, width, items);
2586
+ if (heads.length) {
2587
+ const res = await this.recognizeJobs(rgba, width, heads.map((box, k) => ({ box, rot: 0, group: k })), tuning.recBatch);
2588
+ heads.forEach((box, k) => {
2589
+ const t = res[k]?.text.trim() ?? "";
2590
+ if (/^(?:[IVXⅠ-Ⅻ]{1,4}|\d{1,2})\s?\.$/.test(t) && (res[k]?.confidence ?? 0) >= tuning.textScore) items.push({ text: t, ...this.itemBox(rgba, width, box, tuning), confidence: res[k].confidence });
2591
+ });
2592
+ }
2593
+ }
2594
+ if (tuning.postprocess) items = joinGapLeaders(rgba, width, items);
2595
+ if (tuning.postprocess) restoreBulletItems(items);
2596
+ if (candidatesOf) for (const it of items) {
2597
+ const c = candidatesOf.get(it);
2598
+ if (c && c.text === it.text) it.candidates = c.list;
2599
+ }
2600
+ if (charsOf) for (const it of items) {
2601
+ const c = charsOf.get(it);
2602
+ const list = c && joinChars(c, it.text);
2603
+ if (list) it.chars = list;
2604
+ }
2605
+ items.sort((a, b) => a.y - b.y || a.x - b.x);
2606
+ return items;
2607
+ }
2608
+ /** 결과 좌표 — det 박스 그대로 또는 박스 안 잉크 외곽 (tightBoxes) */
2609
+ itemBox(rgba, width, b, tuning) {
2610
+ if (!tuning.tightBoxes) return b;
2611
+ const gray = grayCrop(rgba, width, b);
2612
+ const t = inkBounds(gray, b.w, b.h, inkStats(gray));
2613
+ return { x: b.x + t.x0, y: b.y + t.y0, w: t.x1 - t.x0, h: t.y1 - t.y0 };
2614
+ }
2615
+ // ─── det ─────────────────────────────────────────────
2616
+ async detect(rgba, width, height, tuning, stats) {
2617
+ const { dw, dh } = detInputSize(width, height, tuning.detLongSide);
2618
+ const rgb = await this.sharp(rgba, { raw: { width, height, channels: 4 } }).resize(dw, dh, { fit: "fill" }).removeAlpha().raw().toBuffer();
2619
+ const plane = dw * dh;
2620
+ const input = new Float32Array(3 * plane);
2621
+ for (let i = 0; i < plane; i++) {
2622
+ const r = rgb[i * 3] / 255;
2623
+ const g = rgb[i * 3 + 1] / 255;
2624
+ const b = rgb[i * 3 + 2] / 255;
2625
+ input[i] = (b - DET_MEAN[0]) / DET_STD[0];
2626
+ input[plane + i] = (g - DET_MEAN[1]) / DET_STD[1];
2627
+ input[2 * plane + i] = (r - DET_MEAN[2]) / DET_STD[2];
2628
+ }
2629
+ const tensor = new this.ort.Tensor("float32", input, [1, 3, dh, dw]);
2630
+ const out = await this.det.run({ [this.det.inputNames[0]]: tensor });
2631
+ const probMap = out[this.det.outputNames[0]].data;
2632
+ const rawBoxes = componentBoxes(probMap, dw, dh, tuning.detThresh, tuning.detBoxThresh);
2633
+ if (stats) stats.truncatedBoxes = Math.max(0, rawBoxes.length - DET_MAX_BOXES);
2634
+ const sx = width / dw;
2635
+ const sy = height / dh;
2636
+ const boxes = [];
2637
+ for (const rb of rawBoxes.slice(0, DET_MAX_BOXES)) {
2638
+ const bw = rb.x2 - rb.x1 + 1;
2639
+ const bh = rb.y2 - rb.y1 + 1;
2640
+ const delta = bw * bh * tuning.detUnclip / (2 * (bw + bh));
2641
+ const x1 = Math.max(0, Math.floor((rb.x1 - delta) * sx));
2642
+ const y1 = Math.max(0, Math.floor((rb.y1 - delta) * sy));
2643
+ const x2 = Math.min(width, Math.ceil((rb.x2 + 1 + delta) * sx));
2644
+ const y2 = Math.min(height, Math.ceil((rb.y2 + 1 + delta) * sy));
2645
+ if (x2 - x1 < DET_MIN_SIZE || y2 - y1 < DET_MIN_SIZE) continue;
2646
+ boxes.push({ x: x1, y: y1, w: x2 - x1, h: y2 - y1 });
2647
+ }
2648
+ return boxes;
2649
+ }
2650
+ // ─── rec ─────────────────────────────────────────────
2651
+ /** 라인 작업들을 폭 비율 순으로 배치 인식 — 결과는 jobs 순서 */
2652
+ async recognizeJobs(rgba, pageW, jobs, batchSize, nBest = 0, nAlternatives) {
2653
+ const crops = jobs.map((j) => lineCrop(rgba, pageW, j.box, j.rot, j.keep, j.stretch));
2654
+ const order = crops.map((_, i) => i).sort((a, b) => crops[a].w - crops[b].w);
2655
+ const results = new Array(jobs.length).fill(null);
2656
+ const plane = REC_HEIGHT;
2657
+ for (let s = 0; s < order.length; ) {
2658
+ let e = s + 1;
2659
+ while (e < order.length && e - s < Math.max(1, batchSize) && (e - s + 1) * Math.max(REC_MIN_WIDTH, crops[order[e]].w) * plane <= REC_BATCH_MAX_PIXELS) e++;
2660
+ const idx = order.slice(s, e);
2661
+ const bw = Math.max(REC_MIN_WIDTH, crops[idx[idx.length - 1]].w);
2662
+ const n = idx.length;
2663
+ const chw = 3 * REC_HEIGHT * bw;
2664
+ const input = new Float32Array(n * chw);
2665
+ idx.forEach((ci, k) => {
2666
+ const c = crops[ci];
2667
+ const base = k * chw;
2668
+ const p = REC_HEIGHT * bw;
2669
+ for (let y = 0; y < REC_HEIGHT; y++) {
2670
+ for (let x = 0; x < c.w; x++) {
2671
+ const src = (y * c.w + x) * 3;
2672
+ const dst = base + y * bw + x;
2673
+ input[dst] = c.rgb[src + 2] / 127.5 - 1;
2674
+ input[dst + p] = c.rgb[src + 1] / 127.5 - 1;
2675
+ input[dst + 2 * p] = c.rgb[src] / 127.5 - 1;
2676
+ }
2677
+ }
2678
+ });
2679
+ const tensor = new this.ort.Tensor("float32", input, [n, 3, REC_HEIGHT, bw]);
2680
+ const out = await this.rec.run({ [this.rec.inputNames[0]]: tensor });
2681
+ const logits = out[this.rec.outputNames[0]];
2682
+ const [, T, C] = logits.dims;
2683
+ if (C !== this.dict.length + 2) throw new KordocError(`OCR rec \uCD9C\uB825 \uD074\uB798\uC2A4 ${C}\uAC1C\uAC00 \uC0AC\uC804 ${this.dict.length}\uC790 + 2 \uC640 \uB2E4\uB985\uB2C8\uB2E4 \u2014 \uBAA8\uB378\uC5D0 \uB9DE\uB294 \uC0AC\uC804(ocrRecDict)\uC744 \uC9C0\uC815\uD558\uC138\uC694`);
2684
+ const data = logits.data;
2685
+ idx.forEach((ci, k) => {
2686
+ const r = ctcDecode(data.subarray(k * T * C, (k + 1) * T * C), T, C, this.dict, nAlternatives);
2687
+ const job = jobs[ci], src = job.rot === 0 ? job.box.w : job.box.h;
2688
+ let kept = r;
2689
+ const last = crops[ci].w * T / bw + 1;
2690
+ const chars = r ? [...r.text] : [];
2691
+ if (r && job.rot === 0 && chars.length === r.steps.length && r.steps.some((t) => t > last) && !r.text.includes("(cid:")) {
2692
+ const tallCh = (c) => !/[\s.,:;\u00b7\u2026'"\u2018-\u201d`\-_~]/.test(c);
2693
+ const g = grayCrop(rgba, pageW, job.box);
2694
+ const inside = chars.filter((c, i) => r.steps[i] <= last && tallCh(c)).length;
2695
+ let budget = inside <= 2 ? tallInkCount(g, job.box.w, job.box.h, inkStats(g)) - inside : Infinity;
2696
+ const keep = chars.map((c, i) => r.steps[i] <= last || !tallCh(c) || budget-- > 0);
2697
+ if (!keep.every(Boolean)) kept = { ...r, text: chars.filter((_, i) => keep[i]).join(""), steps: r.steps.filter((_, i) => keep[i]), ...r.charScores && { charScores: r.charScores.filter((_, i) => keep[i]) } };
2698
+ }
2699
+ results[ci] = kept && { ...kept, stepPx: bw / T * (src / crops[ci].w) };
2700
+ const candidates = nBest > 0 && results[ci] ? ctcCandidates(data.subarray(k * T * C, (k + 1) * T * C), T, C, this.dict, nBest) : void 0;
2701
+ if (candidates?.length) results[ci].candidates = candidates;
2702
+ });
2703
+ s = e;
2704
+ }
2705
+ return results;
2706
+ }
2707
+ };
2708
+ function median(gray) {
2709
+ const hist = new Uint32Array(256);
2710
+ for (let i = 0; i < gray.length; i++) hist[gray[i]]++;
2711
+ for (let v = 0, n = 0; v < 256; v++) if ((n += hist[v]) * 2 >= gray.length) return v;
2712
+ return 255;
2713
+ }
2714
+ var MIN_ALTERNATIVE_PROB = 1e-3;
2715
+ function lineChars(text, steps, scores, boxX, stepPx, line) {
2716
+ const chars = [...text];
2717
+ if (chars.length !== steps.length || chars.length !== scores.length) return null;
2718
+ const lo = line.x, hi = line.x + line.w;
2719
+ const at = (i) => boxX + (steps[i] + 0.5) * stepPx;
2720
+ const edge = (i) => i <= 0 ? lo : i >= chars.length ? hi : Math.min(hi, Math.max(lo, (at(i - 1) + at(i)) / 2));
2721
+ return chars.map((ch, i) => {
2722
+ const x = Math.round(edge(i));
2723
+ return { text: ch, box: { x, y: line.y, w: Math.max(0, Math.round(edge(i + 1)) - x), h: line.h }, ...scores[i] };
2724
+ });
2725
+ }
2726
+ function joinChars(list, text) {
2727
+ if (list.map((c) => c.text).join("") === text) return list;
2728
+ let a = 0, b = list.length;
2729
+ while (a < b && !list[a].text.trim()) a++;
2730
+ while (b > a && !list[b - 1].text.trim()) b--;
2731
+ const trimmed = list.slice(a, b);
2732
+ return trimmed.length && trimmed.map((c) => c.text).join("") === text ? trimmed : void 0;
2733
+ }
2734
+ function ctcDecode(data, T, C, dict, alternatives) {
2735
+ let text = "";
2736
+ const scores = alternatives === void 0 ? void 0 : [];
2737
+ let confSum = 0;
2738
+ let confCount = 0;
2739
+ let prev = -1;
2740
+ const runs = [];
2741
+ let open = [];
2742
+ for (let t = 0; t < T; t++) {
2743
+ const off = t * C;
2744
+ let best = 0;
2745
+ let bestV = data[off];
2746
+ for (let c = 1; c < C; c++) {
2747
+ const v = data[off + c];
2748
+ if (v > bestV) {
2749
+ bestV = v;
2750
+ best = c;
2751
+ }
2752
+ }
2753
+ const repeat = best === prev;
2754
+ prev = best;
2755
+ if (repeat && best !== 0) {
2756
+ for (const r of open) r[1] = t;
2757
+ continue;
2758
+ }
2759
+ open = [];
2760
+ if (best === 0) continue;
2761
+ let p = bestV;
2762
+ const logits = p > 1.0001 || p < 0;
2763
+ if (logits) {
2764
+ let denom = 0;
2765
+ for (let c = 0; c < C; c++) denom += Math.exp(data[off + c] - bestV);
2766
+ p = 1 / denom;
2767
+ }
2768
+ confSum += p;
2769
+ confCount++;
2770
+ const tok = best >= 1 && best <= dict.length ? dict[best - 1] : best === dict.length + 1 ? " " : "";
2771
+ text += tok;
2772
+ for (const _ of tok) {
2773
+ const r = [t, t];
2774
+ runs.push(r);
2775
+ open.push(r);
2776
+ }
2777
+ if (scores) {
2778
+ const alts = [];
2779
+ if (alternatives > 0 && [...tok].length === 1) {
2780
+ const prob = (c) => logits ? Math.exp(data[off + c] - bestV) * p : data[off + c];
2781
+ for (let c = 1; c < C; c++) {
2782
+ if (c === best) continue;
2783
+ const q = prob(c), alt = c <= dict.length ? dict[c - 1] : " ";
2784
+ if (q < MIN_ALTERNATIVE_PROB || [...alt].length !== 1 || alts.length === alternatives && q <= alts[alts.length - 1].confidence) continue;
2785
+ if (alts.length === alternatives) alts.pop();
2786
+ let i = alts.length;
2787
+ while (i > 0 && alts[i - 1].confidence < q) i--;
2788
+ alts.splice(i, 0, { text: alt, confidence: q });
2789
+ }
2790
+ }
2791
+ for (const _ of tok) scores.push(alts.length ? { confidence: p, alternatives: alts } : { confidence: p });
2792
+ }
2793
+ }
2794
+ if (!text) return null;
2795
+ return { text, confidence: confCount > 0 ? confSum / confCount : 0, steps: runs.map(([a, b]) => (a + b) / 2), ...scores && { charScores: scores } };
2796
+ }
2797
+ function componentBoxes(prob, w, h, thresh = DEFAULT_OCR_TUNING.detThresh, boxThresh = DEFAULT_OCR_TUNING.detBoxThresh) {
2798
+ const visited = new Uint8Array(w * h);
2799
+ const boxes = [];
2800
+ const stack = [];
2801
+ for (let start = 0; start < w * h; start++) {
2802
+ if (visited[start] || prob[start] <= thresh) continue;
2803
+ let x1 = start % w, x2 = x1, y1 = start / w | 0, y2 = y1;
2804
+ let sum = 0;
2805
+ let count = 0;
2806
+ stack.length = 0;
2807
+ stack.push(start);
2808
+ visited[start] = 1;
2809
+ while (stack.length) {
2810
+ const p = stack.pop();
2811
+ const px = p % w;
2812
+ const py = p / w | 0;
2813
+ sum += prob[p];
2814
+ count++;
2815
+ if (px < x1) x1 = px;
2816
+ if (px > x2) x2 = px;
2817
+ if (py < y1) y1 = py;
2818
+ if (py > y2) y2 = py;
2819
+ if (px > 0 && !visited[p - 1] && prob[p - 1] > thresh) {
2820
+ visited[p - 1] = 1;
2821
+ stack.push(p - 1);
2822
+ }
2823
+ if (px < w - 1 && !visited[p + 1] && prob[p + 1] > thresh) {
2824
+ visited[p + 1] = 1;
2825
+ stack.push(p + 1);
2826
+ }
2827
+ if (py > 0 && !visited[p - w] && prob[p - w] > thresh) {
2828
+ visited[p - w] = 1;
2829
+ stack.push(p - w);
2830
+ }
2831
+ if (py < h - 1 && !visited[p + w] && prob[p + w] > thresh) {
2832
+ visited[p + w] = 1;
2833
+ stack.push(p + w);
2834
+ }
2835
+ }
2836
+ if (x2 - x1 + 1 < DET_MIN_SIZE && y2 - y1 + 1 < DET_MIN_SIZE) continue;
2837
+ boxes.push({ x1, y1, x2, y2, score: sum / count });
2838
+ }
2839
+ return boxes.filter((b) => b.score >= boxThresh).sort((a, b) => a.y1 - b.y1 || a.x1 - b.x1);
2840
+ }
2841
+ async function tryImport(name, loader) {
2842
+ try {
2843
+ return await loader();
2844
+ } catch (e) {
2845
+ throw new Error(
2846
+ `\uB0B4\uC7A5 OCR \uC744 \uC0AC\uC6A9\uD558\uB824\uBA74 optional dependency '${name}' \uC774 \uD544\uC694\uD569\uB2C8\uB2E4. \`npm install ${name}\` \uD6C4 \uB2E4\uC2DC \uC2E4\uD589\uD558\uC138\uC694.${OPTIONAL_DEP_INSTALL_HINT} \uC6D0\uC778: ${e.message}`
2847
+ );
2848
+ }
2849
+ }
2850
+ async function verifiedBytes(s) {
2851
+ const name = basename(s.file.path);
2852
+ const fail = (why2) => new KordocError(`OCR \uBAA8\uB378 \uD30C\uC77C\uC744 \uC77D\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: ${name} (${why2})`);
2853
+ const why = (e) => {
2854
+ const code = e.code;
2855
+ return code === "ENOENT" ? "\uD30C\uC77C\uC774 \uC5C6\uC74C" : code === "EACCES" || code === "EPERM" ? "\uAD8C\uD55C \uC5C6\uC74C" : "\uC77D\uAE30 \uC2E4\uD328";
2856
+ };
2857
+ let st;
2858
+ try {
2859
+ st = await stat(s.file.path);
2860
+ } catch (e) {
2861
+ throw fail(why(e));
2862
+ }
2863
+ if (!st.isFile()) throw fail("\uC77C\uBC18 \uD30C\uC77C\uC774 \uC544\uB2D8");
2864
+ if (st.size > MAX_LOCAL_MODEL_BYTES) throw fail(`${Math.round(st.size / 1048576)}MB \u2014 \uBAA8\uB378 \uD30C\uC77C\uB85C \uBCF4\uAE30\uC5D0 \uB108\uBB34 \uD07D\uB2C8\uB2E4`);
2865
+ let bytes;
2866
+ try {
2867
+ bytes = await readFile(s.file.path);
2868
+ } catch (e) {
2869
+ throw fail(why(e));
2870
+ }
2871
+ const actual = createHash("sha256").update(bytes).digest("hex");
2872
+ if (actual !== s.file.sha256) {
2873
+ throw new KordocError(`OCR \uBAA8\uB378 SHA256 mismatch: ${basename(s.file.path)} \u2014 expected ${s.file.sha256}, got ${actual} (\uB85C\uB4DC \uAC70\uBD80)`);
2874
+ }
2875
+ return bytes;
2876
+ }
2877
+ var engines = /* @__PURE__ */ new Map();
2878
+ function getOcrEngine(models = DEFAULT_OCR_MODELS) {
2879
+ const key = ocrSelectionKey(models);
2880
+ let p = engines.get(key);
2881
+ if (!p) {
2882
+ p = OcrEngine.create(models).catch((err) => {
2883
+ engines.delete(key);
2884
+ throw err;
2885
+ });
2886
+ engines.set(key, p);
2887
+ }
2888
+ return p;
2889
+ }
2890
+ var MAX_SKEW_DEG = 5;
2891
+ var MIN_APPLY_DEG = 0.25;
2892
+ var MIN_GAIN = 1.03;
2893
+ var MIN_LINES = 3;
2894
+ var MIN_GAIN_FEW = 1.05;
2895
+ var LINE_BIN_FRAC = 0.05;
2896
+ var TARGET_LONG = 1e3;
2897
+ var DEWARP_BANDS = 6;
2898
+ var DEWARP_MIN_GAIN = 1.05;
2899
+ var DEWARP_MIN_LINES = 3;
2900
+ var DEWARP_SPREAD_DEG = 0.8;
2901
+ var DEWARP_MONO_TOL_DEG = 0.3;
2902
+ var DEWARP_WIN = 1.02;
2903
+ var DEWARP_LINEAR_TOL_DEG = 0.8;
2904
+ var DEWARP_LINEAR_WIN = 1.12;
2905
+ function fieldAngle(f, y) {
2906
+ const k = f.knots;
2907
+ if (y <= k[0][0]) return k[0][1];
2908
+ for (let i = 1; i < k.length; i++) if (y <= k[i][0]) {
2909
+ const t = (y - k[i - 1][0]) / (k[i][0] - k[i - 1][0]);
2910
+ return k[i - 1][1] * (1 - t) + k[i][1] * t;
2911
+ }
2912
+ return k[k.length - 1][1];
2913
+ }
2914
+ function estimateSkewField(rgba, width, height) {
2915
+ const bh = Math.floor(height / (DEWARP_BANDS / 2 + 0.5));
2916
+ if (bh < 50) return null;
2917
+ const knots = [];
2918
+ const step = pageStep(width, height);
2919
+ for (let k = 0; k < DEWARP_BANDS; k++) {
2920
+ const y0 = Math.floor(k * (height - bh) / (DEWARP_BANDS - 1));
2921
+ const e = estimateSkew(rgba.subarray(y0 * width * 4, (y0 + bh) * width * 4), width, bh, step);
2922
+ if (e.gain >= DEWARP_MIN_GAIN && e.lines >= DEWARP_MIN_LINES) knots.push([y0 + bh / 2, e.angle]);
2923
+ }
2924
+ if (knots.length < 2) return null;
2925
+ const as = knots.map((k) => k[1]);
2926
+ if (Math.max(...as) - Math.min(...as) < DEWARP_SPREAD_DEG) return null;
2927
+ const up = as.some((a, i) => i > 0 && a - as[i - 1] > DEWARP_MONO_TOL_DEG), down = as.some((a, i) => i > 0 && as[i - 1] - a > DEWARP_MONO_TOL_DEG);
2928
+ if (up && down) return null;
2929
+ return { cx: (width - 1) / 2, knots };
2930
+ }
2931
+ function linearSkewField(f, height) {
2932
+ const k = f.knots;
2933
+ if (k.length < 3) return null;
2934
+ const n = k.length, my = k.reduce((s, p) => s + p[0], 0) / n, ma = k.reduce((s, p) => s + p[1], 0) / n;
2935
+ const b = k.reduce((s, p) => s + (p[0] - my) * (p[1] - ma), 0) / k.reduce((s, p) => s + (p[0] - my) ** 2, 0);
2936
+ const at = (y) => ma + b * (y - my);
2937
+ if (k.some((p) => Math.abs(p[1] - at(p[0])) > DEWARP_LINEAR_TOL_DEG)) return null;
2938
+ if (Math.min(...k.map((p) => p[1])) >= 0 || Math.max(...k.map((p) => p[1])) <= 0) return null;
2939
+ return { cx: f.cx, knots: [[0, at(0)], [height - 1, at(height - 1)]] };
2940
+ }
2941
+ function dewarpRows(rgba, width, height, f) {
2942
+ const out = new Uint8Array(rgba.length);
2943
+ for (let y = 0; y < height; y++) {
2944
+ const t = Math.tan(fieldAngle(f, y) * Math.PI / 180);
2945
+ for (let x = 0; x < width; x++) {
2946
+ const sy = y + (x - f.cx) * t, y0 = Math.floor(sy), wy = sy - y0, o = (y * width + x) * 4;
2947
+ if (y0 < 0 || y0 >= height - 1) {
2948
+ out[o] = 255;
2949
+ out[o + 1] = 255;
2950
+ out[o + 2] = 255;
2951
+ out[o + 3] = 255;
2952
+ continue;
2953
+ }
2954
+ const i0 = (y0 * width + x) * 4, i1 = i0 + width * 4;
2955
+ for (let c = 0; c < 4; c++) out[o + c] = Math.round(rgba[i0 + c] * (1 - wy) + rgba[i1 + c] * wy);
2956
+ }
2957
+ }
2958
+ return out;
2959
+ }
2960
+ function inkPoints(rgba, width, height, step) {
2961
+ const sw = Math.floor(width / step), sh = Math.floor(height / step);
2962
+ const xs = [], ys = [];
2963
+ for (let y = 0; y < sh; y++) {
2964
+ for (let x = 0; x < sw; x++) {
2965
+ const i = (y * step * width + x * step) * 4;
2966
+ const l = rgba[i] * 77 + rgba[i + 1] * 150 + rgba[i + 2] * 29 >> 8;
2967
+ if (l < 128) {
2968
+ xs.push(x);
2969
+ ys.push(y);
2970
+ }
2971
+ }
2972
+ }
2973
+ return { xs, ys, sw, sh };
2974
+ }
2975
+ var pageStep = (width, height) => Math.max(1, Math.ceil(Math.max(width, height) / TARGET_LONG));
2976
+ function estimateSkew(rgba, width, height, step = pageStep(width, height)) {
2977
+ const { xs, ys, sw, sh } = inkPoints(rgba, width, height, step);
2978
+ if (xs.length < 200) return { angle: 0, gain: 1, lines: 0, score: 0 };
2979
+ const diag = Math.ceil(Math.hypot(sw, sh));
2980
+ const hist = new Float64Array(2 * diag + 2);
2981
+ const score = (deg) => {
2982
+ const t = deg * Math.PI / 180;
2983
+ const c = Math.cos(t), s = Math.sin(t);
2984
+ hist.fill(0);
2985
+ for (let k = 0; k < xs.length; k++) hist[Math.round(ys[k] * c + xs[k] * s) + diag]++;
2986
+ let sum = 0;
2987
+ for (let i = 0; i < hist.length; i++) sum += hist[i] * hist[i];
2988
+ return sum;
2989
+ };
2990
+ const s0 = score(0);
2991
+ let best = 0, bestS = s0;
2992
+ for (let d = -MAX_SKEW_DEG; d <= MAX_SKEW_DEG + 1e-9; d += 0.2) {
2993
+ const v = score(d);
2994
+ if (v > bestS) {
2995
+ bestS = v;
2996
+ best = d;
2997
+ }
2998
+ }
2999
+ const coarse = best;
3000
+ for (let d = coarse - 0.2; d <= coarse + 0.2 + 1e-9; d += 0.02) {
3001
+ const v = score(d);
3002
+ if (v > bestS) {
3003
+ bestS = v;
3004
+ best = d;
3005
+ }
3006
+ }
3007
+ score(best);
3008
+ let max = 0;
3009
+ for (let i = 0; i < hist.length; i++) if (hist[i] > max) max = hist[i];
3010
+ let lines = 0, on = false;
3011
+ for (let i = 0; i < hist.length; i++) {
3012
+ const ink = hist[i] > max * LINE_BIN_FRAC;
3013
+ if (ink && !on) lines++;
3014
+ on = ink;
3015
+ }
3016
+ return { angle: +(-best).toFixed(2), gain: s0 > 0 ? bestS / s0 : 1, lines, score: bestS };
3017
+ }
3018
+ function dewarpScore(rgba, width, height, f, step) {
3019
+ const { xs, ys, sh } = inkPoints(rgba, width, height, step);
3020
+ const pad = Math.ceil(sh / 2), hist = new Float64Array(sh + 2 * pad + 2);
3021
+ for (let k = 0; k < xs.length; k++) {
3022
+ const x = xs[k] * step, y = ys[k] * step;
3023
+ const r = Math.round((y - (x - f.cx) * Math.tan(fieldAngle(f, y) * Math.PI / 180)) / step) + pad;
3024
+ if (r >= 0 && r < hist.length) hist[r]++;
3025
+ }
3026
+ let sum = 0;
3027
+ for (let i = 0; i < hist.length; i++) sum += hist[i] * hist[i];
3028
+ return sum;
3029
+ }
3030
+ var ROTATE_DEWARP_MIN_DEG = 1.2;
3031
+ var STRAIGHT_MEAN_DEG = 1;
3032
+ function meanFieldAngle(f, height) {
3033
+ let sum = 0, n = 0;
3034
+ for (let y = 0; y < height; y += 8) {
3035
+ sum += fieldAngle(f, y);
3036
+ n++;
3037
+ }
3038
+ return n ? sum / n : 0;
3039
+ }
3040
+ function verticalsStraightened(f, height) {
3041
+ return !!f && Math.abs(meanFieldAngle(f, height)) < STRAIGHT_MEAN_DEG;
3042
+ }
3043
+ function deskewPage(rgba, width, height) {
3044
+ const est = estimateSkew(rgba, width, height);
3045
+ const step = pageStep(width, height);
3046
+ const direct = pickField(rgba, width, height, step);
3047
+ const rotates = Math.abs(est.angle) >= MIN_APPLY_DEG && est.gain >= (est.lines < MIN_LINES ? MIN_GAIN_FEW : MIN_GAIN);
3048
+ const rotated = rotates ? rotateRgba(rgba, width, height, est.angle) : null;
3049
+ const after = rotated && Math.abs(est.angle) >= ROTATE_DEWARP_MIN_DEG ? pickField(rotated, width, height, step) : null;
3050
+ const useDirect = direct && direct.score > est.score * DEWARP_WIN && (!after || direct.score >= after.score);
3051
+ if (useDirect) return { rgba: dewarpRows(rgba, width, height, direct.f), angle: 0, dewarp: direct.f };
3052
+ if (rotated && after && after.score > est.score * DEWARP_WIN) return { rgba: dewarpRows(rotated, width, height, after.f), angle: est.angle, dewarp: after.f };
3053
+ if (!rotated) return { rgba, angle: 0 };
3054
+ return { rgba: rotated, angle: est.angle };
3055
+ }
3056
+ function pickField(rgba, width, height, step) {
3057
+ const piecewise = estimateSkewField(rgba, width, height);
3058
+ if (!piecewise) return null;
3059
+ const linear = linearSkewField(piecewise, height);
3060
+ const pwScore = dewarpScore(rgba, width, height, piecewise, step);
3061
+ const linScore = linear ? dewarpScore(rgba, width, height, linear, step) : 0;
3062
+ return linear && linScore > pwScore * DEWARP_LINEAR_WIN ? { f: linear, score: linScore } : { f: piecewise, score: pwScore };
3063
+ }
3064
+ function rotateQuarter(rgba, width, height, rot) {
3065
+ const out = new Uint8Array(rgba.length);
3066
+ if (rot === 180) {
3067
+ for (let i = 0, j = rgba.length - 4; i < rgba.length; i += 4, j -= 4) {
3068
+ out[i] = rgba[j];
3069
+ out[i + 1] = rgba[j + 1];
3070
+ out[i + 2] = rgba[j + 2];
3071
+ out[i + 3] = rgba[j + 3];
3072
+ }
3073
+ return { rgba: out, width, height };
3074
+ }
3075
+ for (let v = 0; v < width; v++) {
3076
+ for (let u = 0; u < height; u++) {
3077
+ const px = rot === 90 ? width - 1 - v : v, py = rot === 90 ? u : height - 1 - u;
3078
+ const o = (v * height + u) * 4, i = (py * width + px) * 4;
3079
+ out[o] = rgba[i];
3080
+ out[o + 1] = rgba[i + 1];
3081
+ out[o + 2] = rgba[i + 2];
3082
+ out[o + 3] = rgba[i + 3];
3083
+ }
3084
+ }
3085
+ return { rgba: out, width: height, height: width };
3086
+ }
3087
+ function rotateRgba(rgba, width, height, deg) {
3088
+ const out = new Uint8Array(rgba.length);
3089
+ const t = deg * Math.PI / 180;
3090
+ const c = Math.cos(t), s = Math.sin(t);
3091
+ const cx = (width - 1) / 2, cy = (height - 1) / 2;
3092
+ for (let y = 0; y < height; y++) {
3093
+ const dy = y - cy;
3094
+ for (let x = 0; x < width; x++) {
3095
+ const dx = x - cx;
3096
+ const sx = c * dx - s * dy + cx;
3097
+ const sy = s * dx + c * dy + cy;
3098
+ const o = (y * width + x) * 4;
3099
+ const x0 = Math.floor(sx), y0 = Math.floor(sy);
3100
+ if (x0 < 0 || y0 < 0 || x0 >= width - 1 || y0 >= height - 1) {
3101
+ out[o] = 255;
3102
+ out[o + 1] = 255;
3103
+ out[o + 2] = 255;
3104
+ out[o + 3] = 255;
3105
+ continue;
3106
+ }
3107
+ const wx = sx - x0, wy = sy - y0;
3108
+ const i00 = (y0 * width + x0) * 4, i01 = i00 + 4, i10 = i00 + width * 4, i11 = i10 + 4;
3109
+ for (let ch = 0; ch < 4; ch++) {
3110
+ const top = rgba[i00 + ch] * (1 - wx) + rgba[i01 + ch] * wx;
3111
+ const bot = rgba[i10 + ch] * (1 - wx) + rgba[i11 + ch] * wx;
3112
+ out[o + ch] = Math.round(top * (1 - wy) + bot * wy);
3113
+ }
3114
+ }
3115
+ }
3116
+ return out;
3117
+ }
3118
+ var WIDE_LONG = 640;
3119
+ var WIDE_GAIN = 1.05;
3120
+ var WIDE_MIN_GAIN = 1.2;
3121
+ var WIDE_MIN_GAIN_MANY = 1.1;
3122
+ var WIDE_MIN_LINES = 4;
3123
+ var OLD_RANGE = MAX_SKEW_DEG;
3124
+ var QUARTER_TOL = 1.5;
3125
+ function adaptiveInk(rgba, width, height) {
3126
+ const step = Math.max(1, Math.ceil(Math.max(width, height) / WIDE_LONG));
3127
+ const sw = Math.floor(width / step), sh = Math.floor(height / step);
3128
+ const g = new Float32Array(sw * sh);
3129
+ for (let y = 0; y < sh; y++) for (let x = 0; x < sw; x++) {
3130
+ let sum = 0, cnt = 0;
3131
+ for (let dy = 0; dy < step; dy++) for (let dx = 0; dx < step; dx++) {
3132
+ const i = ((y * step + dy) * width + x * step + dx) * 4;
3133
+ sum += rgba[i] * 0.299 + rgba[i + 1] * 0.587 + rgba[i + 2] * 0.114;
3134
+ cnt++;
3135
+ }
3136
+ g[y * sw + x] = sum / cnt;
3137
+ }
3138
+ const W1 = sw + 1, I = new Float64Array(W1 * (sh + 1));
3139
+ for (let y = 0; y < sh; y++) {
3140
+ let row = 0;
3141
+ for (let x = 0; x < sw; x++) {
3142
+ row += g[y * sw + x];
3143
+ I[(y + 1) * W1 + x + 1] = I[y * W1 + x + 1] + row;
3144
+ }
3145
+ }
3146
+ const r = Math.max(3, Math.round(Math.max(sw, sh) / 50));
3147
+ const mask = new Uint8Array(sw * sh);
3148
+ for (let y = 0; y < sh; y++) {
3149
+ const y0 = Math.max(0, y - r), y1 = Math.min(sh, y + r + 1);
3150
+ for (let x = 0; x < sw; x++) {
3151
+ const x0 = Math.max(0, x - r), x1 = Math.min(sw, x + r + 1);
3152
+ const mean = (I[y1 * W1 + x1] - I[y0 * W1 + x1] - I[y1 * W1 + x0] + I[y0 * W1 + x0]) / ((y1 - y0) * (x1 - x0));
3153
+ const v = g[y * sw + x];
3154
+ if (v < mean - 14 && v < mean * 0.8) mask[y * sw + x] = 1;
3155
+ }
3156
+ }
3157
+ const maxDim = Math.max(sw, sh) / 4;
3158
+ const xs = new Int32Array(sw * sh), ys = new Int32Array(sw * sh), stack = new Int32Array(sw * sh), comp = new Int32Array(sw * sh);
3159
+ let n = 0;
3160
+ for (let start = 0; start < mask.length; start++) {
3161
+ if (mask[start] !== 1) continue;
3162
+ let top = 0, len = 0, minX = sw, maxX = 0, minY = sh, maxY = 0;
3163
+ stack[top++] = start;
3164
+ mask[start] = 2;
3165
+ while (top) {
3166
+ const i = stack[--top], x = i % sw, y = (i - x) / sw;
3167
+ comp[len++] = i;
3168
+ if (x < minX) minX = x;
3169
+ if (x > maxX) maxX = x;
3170
+ if (y < minY) minY = y;
3171
+ if (y > maxY) maxY = y;
3172
+ if (x > 0 && mask[i - 1] === 1) {
3173
+ mask[i - 1] = 2;
3174
+ stack[top++] = i - 1;
3175
+ }
3176
+ if (x < sw - 1 && mask[i + 1] === 1) {
3177
+ mask[i + 1] = 2;
3178
+ stack[top++] = i + 1;
3179
+ }
3180
+ if (y > 0 && mask[i - sw] === 1) {
3181
+ mask[i - sw] = 2;
3182
+ stack[top++] = i - sw;
3183
+ }
3184
+ if (y < sh - 1 && mask[i + sw] === 1) {
3185
+ mask[i + sw] = 2;
3186
+ stack[top++] = i + sw;
3187
+ }
3188
+ }
3189
+ if (maxX - minX > maxDim || maxY - minY > maxDim) continue;
3190
+ for (let k = 0; k < len; k++) {
3191
+ const i = comp[k], x = i % sw;
3192
+ xs[n] = x;
3193
+ ys[n] = (i - x) / sw;
3194
+ n++;
3195
+ }
3196
+ }
3197
+ return { xs, ys, n, step };
3198
+ }
3199
+ function estimateWideSkew(rgba, width, height) {
3200
+ const { xs, ys, n } = adaptiveInk(rgba, width, height);
3201
+ if (n < 300) return { angle: 0, gain: 1, gainNear: 1, lines: 0 };
3202
+ let mx = 0, my = 0;
3203
+ for (let k = 0; k < n; k++) {
3204
+ mx = Math.max(mx, xs[k]);
3205
+ my = Math.max(my, ys[k]);
3206
+ }
3207
+ const diag = Math.ceil(Math.hypot(mx, my)) + 1;
3208
+ const hist = new Float64Array(2 * diag + 2);
3209
+ const score = (deg) => {
3210
+ const t = deg * Math.PI / 180, c = Math.cos(t), s = Math.sin(t);
3211
+ hist.fill(0);
3212
+ for (let k = 0; k < n; k++) hist[Math.round(ys[k] * c + xs[k] * s) + diag]++;
3213
+ let sum = 0;
3214
+ for (let i = 0; i < hist.length; i++) sum += hist[i] * hist[i];
3215
+ return sum;
3216
+ };
3217
+ const s0 = score(0);
3218
+ let best = 0, bestS = s0, near = s0;
3219
+ for (let d = -90; d < 90; d += 1) {
3220
+ const v = score(d);
3221
+ if (v > bestS) {
3222
+ bestS = v;
3223
+ best = d;
3224
+ }
3225
+ if (Math.abs(d) <= OLD_RANGE && v > near) near = v;
3226
+ }
3227
+ const refine = (from, fromS) => {
3228
+ let b = from, bs = fromS;
3229
+ for (const [span, inc] of [[1, 0.1], [0.1, 0.02]]) {
3230
+ const c0 = b;
3231
+ for (let d = c0 - span; d <= c0 + span + 1e-9; d += inc) {
3232
+ const v = score(d);
3233
+ if (v > bs) {
3234
+ bs = v;
3235
+ b = d;
3236
+ }
3237
+ }
3238
+ }
3239
+ return [b, bs];
3240
+ };
3241
+ const lineCount = (deg) => {
3242
+ score(deg);
3243
+ let max = 0;
3244
+ for (let i = 0; i < hist.length; i++) if (hist[i] > max) max = hist[i];
3245
+ let cnt = 0, on = false;
3246
+ for (let i = 0; i < hist.length; i++) {
3247
+ const ink = hist[i] > max * LINE_BIN_FRAC;
3248
+ if (ink && !on) cnt++;
3249
+ on = ink;
3250
+ }
3251
+ return cnt;
3252
+ };
3253
+ [best, bestS] = refine(best, bestS);
3254
+ let lines = lineCount(best);
3255
+ let perp = best + 90 > 90 ? best - 90 : best + 90, perpS = 0;
3256
+ for (let d = perp - 10; d <= perp + 10 + 1e-9; d += 1) {
3257
+ const v = score(d);
3258
+ if (v > perpS) {
3259
+ perpS = v;
3260
+ perp = d;
3261
+ }
3262
+ }
3263
+ ;
3264
+ [perp, perpS] = refine(perp, perpS);
3265
+ const perpLines = lineCount(perp);
3266
+ let switched = false;
3267
+ if (perpLines >= Math.max(2 * lines, lines + 5) && perpS >= bestS * 0.4) {
3268
+ best = perp;
3269
+ bestS = perpS;
3270
+ lines = perpLines;
3271
+ switched = true;
3272
+ }
3273
+ let angle = -best;
3274
+ if (angle > 90) angle -= 180;
3275
+ if (angle <= -90) angle += 180;
3276
+ return { angle: +angle.toFixed(2), gain: s0 > 0 ? bestS / s0 : 1, gainNear: switched ? Infinity : near > 0 ? bestS / near : 1, lines };
3277
+ }
3278
+ function rotateRgbaExpand(rgba, width, height, deg) {
3279
+ const t = deg * Math.PI / 180, c = Math.cos(t), s = Math.sin(t);
3280
+ const W2 = Math.ceil(Math.abs(width * c) + Math.abs(height * s)), H2 = Math.ceil(Math.abs(width * s) + Math.abs(height * c));
3281
+ const out = new Uint8Array(W2 * H2 * 4);
3282
+ const cx = (width - 1) / 2, cy = (height - 1) / 2, ox = (W2 - 1) / 2, oy = (H2 - 1) / 2;
3283
+ for (let y = 0; y < H2; y++) {
3284
+ const dy = y - oy;
3285
+ for (let x = 0; x < W2; x++) {
3286
+ const dx = x - ox;
3287
+ const sx = c * dx - s * dy + cx, sy = s * dx + c * dy + cy;
3288
+ const o = (y * W2 + x) * 4;
3289
+ const x0 = Math.floor(sx), y0 = Math.floor(sy);
3290
+ if (x0 < 0 || y0 < 0 || x0 >= width - 1 || y0 >= height - 1) {
3291
+ out[o] = out[o + 1] = out[o + 2] = out[o + 3] = 255;
3292
+ continue;
3293
+ }
3294
+ const wx = sx - x0, wy = sy - y0;
3295
+ const i00 = (y0 * width + x0) * 4, i01 = i00 + 4, i10 = i00 + width * 4, i11 = i10 + 4;
3296
+ for (let ch = 0; ch < 4; ch++) {
3297
+ const top = rgba[i00 + ch] * (1 - wx) + rgba[i01 + ch] * wx;
3298
+ const bot = rgba[i10 + ch] * (1 - wx) + rgba[i11 + ch] * wx;
3299
+ out[o + ch] = Math.round(top * (1 - wy) + bot * wy);
3300
+ }
3301
+ }
3302
+ }
3303
+ return { rgba: out, width: W2, height: H2 };
3304
+ }
3305
+ function borderLuma(rgba, width, height) {
3306
+ const b = Math.max(2, Math.round(Math.max(width, height) * 0.03)), step = Math.max(1, Math.floor(Math.max(width, height) / 400));
3307
+ let sum = 0, cnt = 0;
3308
+ for (let y = 0; y < height; y += step) for (let x = 0; x < width; x += step) {
3309
+ if (x >= b && x < width - b && y >= b && y < height - b) continue;
3310
+ const i = (y * width + x) * 4;
3311
+ sum += rgba[i] * 0.299 + rgba[i + 1] * 0.587 + rgba[i + 2] * 0.114;
3312
+ cnt++;
3313
+ }
3314
+ return cnt ? sum / cnt : 255;
3315
+ }
3316
+ var PHOTO_BORDER_LUMA = 150;
3317
+ var CROP_MAX_AREA = 0.7;
3318
+ function inkCrop(rgba, width, height, deg, outW, outH) {
3319
+ const { xs, ys, n, step } = adaptiveInk(rgba, width, height);
3320
+ if (n < 300) return null;
3321
+ const t = deg * Math.PI / 180, c = Math.cos(t), sn = Math.sin(t);
3322
+ const cx = (width - 1) / 2, cy = (height - 1) / 2, ox = (outW - 1) / 2, oy = (outH - 1) / 2;
3323
+ const px = new Float64Array(n), py = new Float64Array(n);
3324
+ for (let k = 0; k < n; k++) {
3325
+ const sx = (xs[k] + 0.5) * step - cx, sy = (ys[k] + 0.5) * step - cy;
3326
+ px[k] = c * sx + sn * sy + ox;
3327
+ py[k] = -sn * sx + c * sy + oy;
3328
+ }
3329
+ const q = (a) => {
3330
+ const v = Array.from(a).sort((p, r) => p - r);
3331
+ return [v[Math.floor(n * 2e-3)], v[Math.min(n - 1, Math.ceil(n * 0.998))]];
3332
+ };
3333
+ const [x0, x1] = q(px), [y0, y1] = q(py);
3334
+ const mx = Math.max(16, (x1 - x0) * 0.06), my = Math.max(16, (y1 - y0) * 0.04);
3335
+ const X0 = Math.max(0, Math.floor(x0 - mx - step)), Y0 = Math.max(0, Math.floor(y0 - my - step));
3336
+ const X1 = Math.min(outW, Math.ceil(x1 + mx + step)), Y1 = Math.min(outH, Math.ceil(y1 + my + step));
3337
+ if (X1 <= X0 || Y1 <= Y0 || (X1 - X0) * (Y1 - Y0) > outW * outH * CROP_MAX_AREA) return null;
3338
+ return { x: X0, y: Y0, w: X1 - X0, h: Y1 - Y0 };
3339
+ }
3340
+ function cropRgba(rgba, width, c) {
3341
+ const out = new Uint8Array(c.w * c.h * 4);
3342
+ for (let y = 0; y < c.h; y++) out.set(rgba.subarray(((c.y + y) * width + c.x) * 4, ((c.y + y) * width + c.x + c.w) * 4), y * c.w * 4);
3343
+ return out;
3344
+ }
3345
+ function straightenPhoto(rgba, width, height) {
3346
+ const w = estimateWideSkew(rgba, width, height);
3347
+ let turn = w.gain >= (w.lines >= 8 ? WIDE_MIN_GAIN_MANY : WIDE_MIN_GAIN) && w.lines >= WIDE_MIN_LINES && Math.abs(w.angle) >= 1;
3348
+ const a = Math.abs(w.angle);
3349
+ if (turn && Math.abs(a - 90) <= QUARTER_TOL) turn = false;
3350
+ if (turn && a > OLD_RANGE + 1 && w.gainNear < WIDE_GAIN) turn = false;
3351
+ const onDesk = borderLuma(rgba, width, height) < PHOTO_BORDER_LUMA;
3352
+ if (turn && a <= OLD_RANGE && !onDesk) turn = false;
3353
+ if (turn) {
3354
+ const old = estimateSkew(rgba, width, height);
3355
+ const oldSure = old.gain >= (old.lines < MIN_LINES ? MIN_GAIN_FEW : MIN_GAIN) && Math.abs(old.angle) < OLD_RANGE - 0.3;
3356
+ const diff = Math.abs(((w.angle - old.angle) % 180 + 180) % 180);
3357
+ const perpendicular = Math.abs(diff - 90) < 15;
3358
+ if (!onDesk && oldSure && perpendicular) turn = false;
3359
+ if (onDesk && a <= OLD_RANGE && Math.abs(old.angle - w.angle) < 0.5 && oldSure) turn = false;
3360
+ }
3361
+ if (!turn && !onDesk) return null;
3362
+ const cur = turn ? rotateRgbaExpand(rgba, width, height, w.angle) : { rgba, width, height };
3363
+ const c = inkCrop(rgba, width, height, turn ? w.angle : 0, cur.width, cur.height);
3364
+ if (!c) return turn ? { ...cur, angle: w.angle } : null;
3365
+ return { rgba: cropRgba(cur.rgba, cur.width, c), width: c.w, height: c.h, angle: turn ? w.angle : 0 };
3366
+ }
3367
+ var NUMBER = /^-?\d+(?:\.\d+)?%?$/;
3368
+ var CLOCK = /^(\d{1,2}):(\d{2})$/;
3369
+ var value = (t) => {
3370
+ const m = CLOCK.exec(t);
3371
+ return m ? Number(m[1]) * 60 + Number(m[2]) : Number(t.replace(/%$/, ""));
3372
+ };
3373
+ function evenRun(ticks) {
3374
+ let best = [];
3375
+ for (let s = 0; s + 1 < ticks.length; s++) {
3376
+ const step = ticks[s + 1].value - ticks[s].value, gap = ticks[s + 1].pos - ticks[s].pos;
3377
+ if (step === 0 || gap <= 0) continue;
3378
+ let e = s + 1;
3379
+ while (e + 1 < ticks.length) {
3380
+ const d = ticks[e + 1].pos - ticks[e].pos, v = ticks[e + 1].value - ticks[e].value;
3381
+ if (Math.abs(d - gap) > gap * 0.35 || Math.abs(v - step) > Math.abs(step) * 0.25) break;
3382
+ e++;
3383
+ }
3384
+ if (e - s + 1 > best.length) best = ticks.slice(s, e + 1);
3385
+ }
3386
+ return best;
3387
+ }
3388
+ var number = (t) => {
3389
+ const s = t.replace(/-$/, "").trim();
3390
+ return NUMBER.test(s) || CLOCK.test(s) ? value(s) : null;
3391
+ };
3392
+ function valueAxes(items) {
3393
+ const nums = items.filter((it) => number(it.text) !== null);
3394
+ const out = [];
3395
+ const used = /* @__PURE__ */ new Set();
3396
+ for (const seed of nums) {
3397
+ if (used.has(seed)) continue;
3398
+ const col = nums.filter((it) => Math.abs(it.x + it.w - seed.x - seed.w) <= seed.h * 0.8).sort((a, b) => a.y - b.y);
3399
+ const run = evenRun(col.map((it) => ({ pos: it.y + it.h / 2, value: number(it.text), it })));
3400
+ if (run.length < (run[run.length - 1]?.value === 0 ? 3 : 4) || run[1].value > run[0].value) continue;
3401
+ const ticks = run.map((r) => r.it);
3402
+ for (const it of ticks) used.add(it);
3403
+ const h = ticks.reduce((a, it) => a + it.h, 0) / ticks.length;
3404
+ out.push({
3405
+ x1: Math.min(...ticks.map((it) => it.x)),
3406
+ x2: Math.max(...ticks.map((it) => it.x + it.w)),
3407
+ y1: ticks[0].y,
3408
+ y2: ticks[ticks.length - 1].y + ticks[ticks.length - 1].h,
3409
+ h,
3410
+ zero: run[run.length - 1].value === 0,
3411
+ gap: (run[run.length - 1].pos - run[0].pos) / (run.length - 1)
3412
+ });
3413
+ }
3414
+ return out;
3415
+ }
3416
+ function timeAxes(items) {
3417
+ const numeric = items.filter((it) => {
3418
+ const t = it.text.trim().split(/\s+/);
3419
+ return t.length > 0 && t.every((x) => NUMBER.test(x));
3420
+ });
3421
+ const out = [];
3422
+ const used = /* @__PURE__ */ new Set();
3423
+ for (const seed of numeric) {
3424
+ if (used.has(seed)) continue;
3425
+ const row = numeric.filter((it) => Math.abs(it.y + it.h / 2 - seed.y - seed.h / 2) <= Math.min(it.h, seed.h) * 0.6).sort((a, b) => a.x - b.x);
3426
+ const ticks = row.flatMap((it) => {
3427
+ const text = it.text.trim(), per = it.w / Math.max(1, text.length);
3428
+ return [...text.matchAll(/\S+/g)].map((m) => ({ pos: it.x + (m.index + m[0].length / 2) * per, value: value(m[0]), it }));
3429
+ });
3430
+ const run = evenRun(ticks);
3431
+ if (run.length < 4 || run[1].value < run[0].value) continue;
3432
+ const boxes = [...new Set(run.map((r) => r.it))];
3433
+ for (const it of boxes) used.add(it);
3434
+ out.push({ x1: Math.min(...boxes.map((it) => it.x)), x2: Math.max(...boxes.map((it) => it.x + it.w)), y1: Math.min(...boxes.map((it) => it.y)), y2: Math.max(...boxes.map((it) => it.y + it.h)), h: seed.h });
3435
+ }
3436
+ return out;
3437
+ }
3438
+ function categoryRow(items, v) {
3439
+ if (!v.zero) return [];
3440
+ const row = items.filter((it) => {
3441
+ const cy = it.y + it.h / 2, t = it.text.trim();
3442
+ return cy > v.y2 && cy < v.y2 + 3 * v.h && it.x > v.x2 && !/\d/.test(t) && /[가-힣A-Za-z]{2}/.test(t) && t.split(/\s+/).length <= 4;
3443
+ });
3444
+ if (!row.length) return [];
3445
+ const base = row[0].y + row[0].h / 2;
3446
+ const line = row.filter((it) => Math.abs(it.y + it.h / 2 - base) <= v.h * 0.6);
3447
+ const words = line.reduce((n, it) => n + it.text.trim().split(/\s+/).length, 0);
3448
+ return words >= 2 && Math.max(...line.map((it) => it.x + it.w)) > v.x2 + 6 * v.h ? line : [];
3449
+ }
3450
+ function forestPlotItems(items, horizontals, drop) {
3451
+ const cy = (it) => it.y + it.h / 2;
3452
+ for (const hz of [...horizontals, ...linearAxes(items)]) {
3453
+ const h = hz.h;
3454
+ const label = items.some((it) => cy(it) > hz.y1 - 3 * h && cy(it) < hz.y2 + 3 * h && /favou?rs?|better|우세/i.test(it.text));
3455
+ if (!label) continue;
3456
+ const rows = [...new Set(items.map(cy))].sort((a, b) => a - b);
3457
+ const at = rows.findIndex((y) => y >= hz.y1);
3458
+ let top = hz.y1, bottom = hz.y2;
3459
+ for (let i = at - 1; i >= 0 && rows[i + 1] - rows[i] <= 2.5 * h; i--) top = rows[i];
3460
+ const caption = (y) => items.some((it) => Math.abs(cy(it) - y) < h * 0.5 && /^(그림|Figure|Fig\.|표)\s*\d/.test(it.text.trim()));
3461
+ for (let i = at; i + 1 < rows.length && rows[i + 1] - rows[i] <= 2.5 * h && !caption(rows[i + 1]); i++) bottom = rows[i + 1];
3462
+ items.forEach((it, i) => {
3463
+ if (cy(it) >= top - h * 0.5 && cy(it) <= bottom + h * 0.5) drop.add(i);
3464
+ });
3465
+ }
3466
+ }
3467
+ function linearAxes(items) {
3468
+ const nums = items.filter((it) => number(it.text) !== null);
3469
+ const out = [];
3470
+ const used = /* @__PURE__ */ new Set();
3471
+ for (const seed of nums) {
3472
+ if (used.has(seed)) continue;
3473
+ const row = nums.filter((it) => Math.abs(it.y + it.h / 2 - seed.y - seed.h / 2) <= Math.min(it.h, seed.h) * 0.6).sort((a, b) => a.x - b.x);
3474
+ if (row.length < 3) continue;
3475
+ const pts = row.map((it) => ({ pos: it.x + it.w / 2, value: number(it.text) }));
3476
+ const slopes = pts.slice(1).map((p, i) => (p.pos - pts[i].pos) / (p.value - pts[i].value));
3477
+ if (slopes.some((k) => !(k > 0)) || Math.max(...slopes) > Math.min(...slopes) * 1.25) continue;
3478
+ for (const it of row) used.add(it);
3479
+ out.push({ x1: row[0].x, x2: row[row.length - 1].x + row[row.length - 1].w, y1: Math.min(...row.map((it) => it.y)), y2: Math.max(...row.map((it) => it.y + it.h)), h: seed.h });
3480
+ }
3481
+ return out;
3482
+ }
3483
+ function chartPlotItems(items) {
3484
+ const drop = /* @__PURE__ */ new Set();
3485
+ const verticals = valueAxes(items);
3486
+ const horizontals = timeAxes(items);
3487
+ forestPlotItems(items, horizontals, drop);
3488
+ if (!verticals.length) return drop;
3489
+ for (const v of verticals) {
3490
+ const hz = horizontals.find((a) => a.y1 >= v.y2 - v.h && a.y1 <= v.y2 + 5 * v.h && a.x1 >= v.x1 - v.h && a.x1 <= v.x2 + 4 * v.h && a.x2 > v.x2 + 8 * v.h);
3491
+ const cats = hz ? [] : categoryRow(items, v);
3492
+ if (!hz && cats.length === 0) continue;
3493
+ const bottom = hz ? hz.y2 + 2.5 * v.h : Math.max(...cats.map((c) => c.y + c.h)) + 0.5 * v.h;
3494
+ const right = hz ? hz.x2 + 2 * v.h : Math.max(...cats.map((c) => c.x + c.w)) + v.h;
3495
+ const x1 = v.x1 - 5 * v.h, x2 = right, y1 = v.y1 - Math.max(1.5 * v.h, v.gap ?? 0), y2 = bottom;
3496
+ items.forEach((it, i) => {
3497
+ const cx = it.x + it.w / 2, cy = it.y + it.h / 2;
3498
+ if (cx >= x1 && cx <= x2 && cy >= y1 && cy <= y2 && it.x >= x1 - v.h && it.x + it.w <= x2 + v.h) drop.add(i);
3499
+ });
3500
+ const cyOf = (it) => it.y + it.h / 2;
3501
+ const risk = items.find((it) => cyOf(it) > y2 - v.h && cyOf(it) < y2 + 4 * v.h && /at\s*risk|위험\s*(대상|인원)/i.test(it.text));
3502
+ if (risk) {
3503
+ const rows = [...new Set(items.map(cyOf))].sort((a, b) => a - b);
3504
+ let end = cyOf(risk);
3505
+ for (let k = rows.indexOf(end); k + 1 < rows.length && rows[k + 1] - rows[k] <= 2.5 * v.h && !items.some((it) => Math.abs(cyOf(it) - rows[k + 1]) < v.h * 0.5 && /^(그림|Figure|Fig\.|표)\s*\d/.test(it.text.trim())); k++) end = rows[k + 1];
3506
+ items.forEach((it, i) => {
3507
+ if (cyOf(it) >= cyOf(risk) - v.h * 0.5 && cyOf(it) <= end + v.h * 0.5) drop.add(i);
3508
+ });
3509
+ }
3510
+ }
3511
+ return drop;
3512
+ }
3513
+ var CONTACT = /^([가-힣](?:\s*[가-힣]){0,4})\s+([가-힣]{2,4})\s*([^가-힣\s][^가-힣]{5,48})$/;
3514
+ var PHONE = /^\(?0\d{1,3}\)?[-\s]?\d{3,4}-\d{4}\)?$/;
3515
+ var MAIL = /^\(?[\w.+-]+@[\w-]+(?:\.[\w-]+)+\)?$/;
3516
+ function contactParts(text) {
3517
+ const m = CONTACT.exec(text.trim());
3518
+ if (!m) return null;
3519
+ const contact = m[3].includes("@") ? m[3].replace(/\s+/g, "") : m[3].trim();
3520
+ return PHONE.test(contact) || MAIL.test(contact) ? [m[1], m[2], contact] : null;
3521
+ }
3522
+ function owners2(t) {
3523
+ const own = Array.from({ length: t.rows }, () => Array(t.cols));
3524
+ for (let r = 0; r < t.rows; r++) for (let c = 0; c < t.cols; c++) {
3525
+ if (own[r][c]) continue;
3526
+ const cell = t.cells[r][c];
3527
+ for (let i = r; i < Math.min(t.rows, r + Math.max(1, cell.rowSpan ?? 1)); i++)
3528
+ for (let j = c; j < Math.min(t.cols, c + Math.max(1, cell.colSpan ?? 1)); j++) own[i][j] ??= cell;
3529
+ }
3530
+ return own;
3531
+ }
3532
+ function splitTable3(t) {
3533
+ if (t.cells.length !== t.rows || t.cells.some((row) => row.length !== t.cols)) return;
3534
+ const own = owners2(t);
3535
+ const anchor = (r, c) => own[r][c] === t.cells[r][c] ? t.cells[r][c] : null;
3536
+ const targets = [];
3537
+ for (let c = 0; c < t.cols; c++) {
3538
+ let filled = 0, hits = 0;
3539
+ for (let r = 0; r < t.rows; r++) {
3540
+ const cell = anchor(r, c);
3541
+ if (!cell || (cell.colSpan ?? 1) !== 1 || cell.blocks?.length || !cell.text.trim()) continue;
3542
+ if (contactParts(cell.text)) hits++;
3543
+ if (hits) filled++;
3544
+ }
3545
+ if (hits >= 2 && hits >= filled * 0.8) targets.push(c);
3546
+ }
3547
+ for (const c of targets.reverse()) {
3548
+ const grown = /* @__PURE__ */ new Set();
3549
+ for (let r = 0; r < t.rows; r++) {
3550
+ const cell = anchor(r, c);
3551
+ let added = [{ text: "", colSpan: 1, rowSpan: 1 }, { text: "", colSpan: 1, rowSpan: 1 }];
3552
+ if (cell && (cell.colSpan ?? 1) === 1 && !cell.blocks?.length) {
3553
+ const parts = contactParts(cell.text);
3554
+ if (parts) {
3555
+ cell.text = parts[0];
3556
+ added = [{ ...cell, text: parts[1] }, { ...cell, text: parts[2] }];
3557
+ } else cell.colSpan = 3;
3558
+ grown.add(cell);
3559
+ } else if (!grown.has(own[r][c])) {
3560
+ own[r][c].colSpan = Math.max(1, own[r][c].colSpan ?? 1) + 2;
3561
+ grown.add(own[r][c]);
3562
+ }
3563
+ t.cells[r].splice(c + 1, 0, ...added);
3564
+ }
3565
+ t.cols += 2;
3566
+ }
3567
+ }
3568
+ function splitOcrContactColumns(blocks) {
3569
+ for (const b of blocks) if (b.type === "table" && b.table) splitTable3(b.table);
3570
+ return blocks;
3571
+ }
3572
+ var NUMBER2 = /^[-+−△▲▽▼]?[\d.,]+[%p]?$|^[-–—]$|^\([-+−△▲▽▼]?[\d.,]+%?\)$/;
3573
+ function splitTable4(t) {
3574
+ if (t.cells.length !== t.rows || t.cells.some((row) => row.length !== t.cols)) return;
3575
+ const own = Array.from({ length: t.rows }, () => Array(t.cols));
3576
+ for (let r2 = 0; r2 < t.rows; r2++) for (let c = 0; c < t.cols; c++) {
3577
+ if (own[r2][c]) continue;
3578
+ const cell = t.cells[r2][c];
3579
+ for (let i = r2; i < Math.min(t.rows, r2 + Math.max(1, cell.rowSpan ?? 1)); i++)
3580
+ for (let j = c; j < Math.min(t.cols, c + Math.max(1, cell.colSpan ?? 1)); j++) own[i][j] ??= cell;
3581
+ }
3582
+ const numericRow = (r2) => {
3583
+ const texts = [...new Set(own[r2])].map((c) => c.text.trim()).filter(Boolean);
3584
+ return texts.length >= 2 && texts.filter((s) => NUMBER2.test(s.replace(/\s+/g, ""))).length >= texts.length * 0.5;
3585
+ };
3586
+ const first = [...Array(t.rows).keys()].find(numericRow);
3587
+ if (first === void 0 || first < 1) return;
3588
+ const r = first - 1;
3589
+ for (let c = 0; c < t.cols; c++) {
3590
+ const cell = t.cells[r][c], k = cell.colSpan ?? 1;
3591
+ if (own[r][c] !== cell || k < 2 || (cell.rowSpan ?? 1) !== 1 || cell.blocks?.length) continue;
3592
+ const words = cell.text.trim().split(/\s+/);
3593
+ if (words.length !== k || words.some((w) => (w.match(/[가-힣]/g) ?? []).length < 2)) continue;
3594
+ let ok = true;
3595
+ for (let j = c; j < c + k && ok; j++) {
3596
+ const below = [...new Set(own.slice(first).map((row) => row[j]))].map((x) => x.text.trim()).filter(Boolean);
3597
+ ok = below.length >= 2 && below.filter((s) => NUMBER2.test(s.replace(/\s+/g, ""))).length >= below.length * 0.8;
3598
+ }
3599
+ if (!ok) continue;
3600
+ words.forEach((w, i) => {
3601
+ t.cells[r][c + i] = { ...cell, text: w, colSpan: 1 };
3602
+ });
3603
+ c += k - 1;
3604
+ }
3605
+ }
3606
+ function splitOcrJoinedHeaders(blocks) {
3607
+ for (const b of blocks) if (b.type === "table" && b.table) splitTable4(b.table);
3608
+ return blocks;
3609
+ }
3610
+ var isProse = (s) => s.length >= 25 && (s.match(/[가-힣]/g) ?? []).length >= 12 && /\S\s+\S/.test(s);
3611
+ function splitTable5(b) {
3612
+ const t = b.table;
3613
+ if (t.rows < 3 || t.cols < 2 || t.cells.length !== t.rows) return [b];
3614
+ const covered = Array.from({ length: t.rows }, () => /* @__PURE__ */ new Set());
3615
+ const heads = Array.from({ length: t.rows }, () => []);
3616
+ for (let r = 0; r < t.rows; r++) for (let c = 0; c < (t.cells[r] ?? []).length; c++) {
3617
+ if (covered[r].has(c)) continue;
3618
+ const cell = t.cells[r][c];
3619
+ const rs = Math.max(1, cell.rowSpan ?? 1), cs = Math.max(1, cell.colSpan ?? 1);
3620
+ for (let i = r; i < Math.min(t.rows, r + rs); i++) for (let j = c; j < c + cs; j++) if (i !== r || j !== c) covered[i].add(j);
3621
+ heads[r].push({ c, cell });
3622
+ }
3623
+ const fullRow = (r) => {
3624
+ const h = heads[r].filter((x) => x.cell.text.trim() || x.cell.blocks?.length);
3625
+ return h.length === 1 && heads[r].length === 1 && (h[0].cell.colSpan ?? 1) >= t.cols && (h[0].cell.rowSpan ?? 1) === 1 && !h[0].cell.blocks?.length;
3626
+ };
3627
+ const prose = /* @__PURE__ */ new Set();
3628
+ for (let r = 0; r < t.rows; ) {
3629
+ if (!fullRow(r)) {
3630
+ r++;
3631
+ continue;
3632
+ }
3633
+ let e = r;
3634
+ while (e + 1 < t.rows && fullRow(e + 1)) e++;
3635
+ const texts = Array.from({ length: e - r + 1 }, (_, k) => heads[r + k][0].cell.text.trim());
3636
+ const trailingNote = e === t.rows - 1 && texts.every((s) => /^(?:※|\*{1,3}(?!\*))/.test(s));
3637
+ if (!trailingNote && texts.some(isProse)) for (let k = r; k <= e; k++) prose.add(k);
3638
+ r = e + 1;
3639
+ }
3640
+ if (!prose.size) return [b];
3641
+ for (let r = 0; r < t.rows; r++) for (const { cell } of heads[r]) {
3642
+ const end = r + Math.max(1, cell.rowSpan ?? 1) - 1;
3643
+ for (let k = r + 1; k <= end; k++) if (prose.has(k) !== prose.has(r)) return [b];
3644
+ }
3645
+ const out = [];
3646
+ let seg = [];
3647
+ const flush = () => {
3648
+ if (!seg.length) return;
3649
+ const rows = seg.map((r) => t.cells[r]);
3650
+ const sub = { ...t, rows: rows.length, cells: rows };
3651
+ out.push({ ...b, table: sub });
3652
+ seg = [];
3653
+ };
3654
+ for (let r = 0; r < t.rows; r++) {
3655
+ if (!prose.has(r)) {
3656
+ seg.push(r);
3657
+ continue;
3658
+ }
3659
+ flush();
3660
+ out.push({ type: "paragraph", text: heads[r][0].cell.text.trim(), pageNumber: b.pageNumber, ...b.bbox ? { bbox: b.bbox } : {} });
3661
+ }
3662
+ flush();
3663
+ return out;
3664
+ }
3665
+ function splitOcrProseRows(blocks) {
3666
+ return blocks.flatMap((b) => b.type === "table" && b.table ? splitTable5(b) : [b]);
3667
+ }
3668
+ var MAX_CELLS = 60;
3669
+ var TOL = 3;
3670
+ var PAD = 16;
3671
+ async function rescueEmptyCells(engine, tuning, rgba, width, height, ruling, items) {
3672
+ const hs = ruling.horizontals, vs = ruling.verticals;
3673
+ if (hs.length < 2 || vs.length < 2) return [];
3674
+ const uniq = (vals) => {
3675
+ const out2 = [];
3676
+ for (const v of [...vals].sort((a, b) => a - b)) if (!out2.length || v - out2[out2.length - 1] > TOL) out2.push(v);
3677
+ return out2;
3678
+ };
3679
+ const ys = uniq(hs.map((h) => h.y1)), xs = uniq(vs.map((v) => v.x1));
3680
+ const hAt = (y, a, b) => hs.some((h) => Math.abs(h.y1 - y) <= TOL && Math.min(h.x1, h.x2) <= a + TOL && Math.max(h.x1, h.x2) >= b - TOL);
3681
+ const vAt = (x, a, b) => vs.some((v) => Math.abs(v.x1 - x) <= TOL && Math.min(v.y1, v.y2) <= a + TOL && Math.max(v.y1, v.y2) >= b - TOL);
3682
+ const cells = [];
3683
+ for (let j = 0; j + 1 < xs.length && cells.length < MAX_CELLS; j++) {
3684
+ for (let i = 0; i + 1 < ys.length && cells.length < MAX_CELLS; i++) {
3685
+ let k = i + 1;
3686
+ while (k + 1 < ys.length && !hAt(ys[k], xs[j], xs[j + 1])) k++;
3687
+ const [y1, y2, x1, x2] = [ys[i], ys[k], xs[j], xs[j + 1]];
3688
+ i = k - 1;
3689
+ if (y2 - y1 < 15 || x2 - x1 < 20 || (x2 - x1) * (y2 - y1) > width * height * 0.05) continue;
3690
+ if (!hAt(y1, x1, x2) || !hAt(y2, x1, x2) || !vAt(x1, y1, y2) || !vAt(x2, y1, y2)) continue;
3691
+ const bx = Math.ceil(x1 + 4), by = Math.ceil(y1 + 4), box = { x: bx, y: by, w: Math.floor(x2 - 4) - bx, h: Math.floor(y2 - 4) - by };
3692
+ if (box.w < 10 || box.h < 8) continue;
3693
+ if (items.some((it) => Math.min(it.x + it.w, box.x + box.w) > Math.max(it.x, box.x) && Math.min(it.y + it.h, box.y + box.h) > Math.max(it.y, box.y))) continue;
3694
+ let ink = 0;
3695
+ for (let y = box.y; y < box.y + box.h; y++) for (let x = box.x, p = (y * width + x) * 4; x < box.x + box.w; x++, p += 4) {
3696
+ if (rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29 < 128 * 256) ink++;
3697
+ }
3698
+ if (ink >= 40 && ink >= box.w * box.h * 0.01) cells.push(box);
3699
+ }
3700
+ }
3701
+ const out = [];
3702
+ for (const c of cells) {
3703
+ const w = c.w + PAD * 2, h = c.h + PAD * 2;
3704
+ const crop = new Uint8Array(w * h * 4).fill(255);
3705
+ for (let y = 0; y < c.h; y++) crop.set(rgba.subarray(((c.y + y) * width + c.x) * 4, ((c.y + y) * width + c.x + c.w) * 4), ((y + PAD) * w + PAD) * 4);
3706
+ const stats = { droppedLowConf: 0 };
3707
+ const found = await engine.recognizePage(crop, w, h, stats, { ...tuning, orientPage: false });
3708
+ for (const it of found) {
3709
+ out.push({ ...it, x: it.x + c.x - PAD, y: it.y + c.y - PAD, ...it.chars && { chars: it.chars.map((ch) => ({ ...ch, box: { ...ch.box, x: ch.box.x + c.x - PAD, y: ch.box.y + c.y - PAD } })) } });
3710
+ }
3711
+ }
3712
+ return out;
3713
+ }
3714
+ var OCR_RENDER_SCALE = 3;
3715
+ var MAX_OCR_PIXELS = 24e6;
3716
+ var PAGE_TIMEOUT_MS = 12e4;
3717
+ var REDETECT = { minDropped: 15, minShare: 0.15, scale: 5 / 3 };
3718
+ var AUTO_REC = { pageConf: 0.9, gain: 0.06 };
3719
+ var DEFAULT_AUTO_REC = { pageConf: 0.9, gain: 0.08, altConf: 0.95, sureGain: 0.1, minDiff: 0.08, minChars: 80, lazy: true };
3720
+ var DEFAULT_BUILTIN_OCR = Object.freeze({
3721
+ models: DEFAULT_OCR_MODELS,
3722
+ tuning: DEFAULT_OCR_TUNING,
3723
+ handwriting: handwritingFallbackModels(DEFAULT_OCR_MODELS),
3724
+ autoRec: DEFAULT_AUTO_REC
3725
+ });
3726
+ var DEFAULT_BUILTIN_OCR_FETCH = Object.freeze({ ...DEFAULT_BUILTIN_OCR, autoRec: { ...DEFAULT_AUTO_REC, fetch: true } });
3727
+ function builtinOcrConfig(o) {
3728
+ if (!o || o.ocrDet === void 0 && o.ocrDetLongSide === void 0 && o.ocrRec === void 0 && o.ocrRecDict === void 0 && !o.ocrLines) return o?.ocr ? DEFAULT_BUILTIN_OCR_FETCH : DEFAULT_BUILTIN_OCR;
3729
+ const bad = validateOcrOptions(o);
3730
+ if (bad) throw new KordocError(bad);
3731
+ const models = resolveOcrModels(o);
3732
+ return {
3733
+ models,
3734
+ ...o.ocrRec === "auto" ? { handwriting: handwritingFallbackModels(models), autoRec: AUTO_REC } : o.ocrRec === void 0 ? { handwriting: handwritingFallbackModels(models), autoRec: o.ocr ? { ...DEFAULT_AUTO_REC, fetch: true } : DEFAULT_AUTO_REC } : {},
3735
+ tuning: o.ocrDetLongSide === void 0 && !o.ocrLineCandidates && !o.ocrChars ? DEFAULT_OCR_TUNING : {
3736
+ ...DEFAULT_OCR_TUNING,
3737
+ ...o.ocrDetLongSide !== void 0 ? { detLongSide: o.ocrDetLongSide } : {},
3738
+ ...o.ocrLineCandidates ? { lineCandidates: o.ocrLineCandidates } : {},
3739
+ ...o.ocrChars ? { chars: o.ocrChars === true ? 0 : o.ocrChars } : {}
3740
+ },
3741
+ lines: o.ocrLines === "all" ? "all" : o.ocrLines ? "kept" : void 0
3742
+ };
3743
+ }
3744
+ async function recognizeOcrPage(engine, config, tuning, rgba, width, height, stats, cellRules, rowRules) {
3745
+ const read = async (t, st) => {
3746
+ const items2 = await engine.recognizePage(rgba, width, height, st, t, cellRules, rowRules);
3747
+ return st.pageRotation ? items2 : withHandwritingRec(items2, config, t, rgba, width, height, st, cellRules, rowRules);
3748
+ };
3749
+ const items = await read(tuning, stats);
3750
+ if (!tuning.redetect || stats.pageRotation || stats.droppedLowConf < REDETECT.minDropped || stats.droppedLowConf < (items.length + stats.droppedLowConf) * REDETECT.minShare) return items;
3751
+ const bigStats = { droppedLowConf: 0, ...stats.dropped ? { dropped: [] } : {} };
3752
+ const big = await read({ ...tuning, detLongSide: Math.round(tuning.detLongSide * REDETECT.scale) }, bigStats);
3753
+ if (bigStats.pageRotation || bigStats.droppedLowConf >= stats.droppedLowConf || meanConfidence(big) <= meanConfidence(items)) return items;
3754
+ Object.assign(stats, bigStats);
3755
+ return big;
3756
+ }
3757
+ async function withHandwritingRec(items, config, tuning, rgba, width, height, stats, cellRules, rowRules) {
3758
+ if (!config.handwriting) return items;
3759
+ const auto = config.autoRec ?? AUTO_REC;
3760
+ const base = meanConfidence(items);
3761
+ if (base >= auto.pageConf) return items;
3762
+ const altStats = { droppedLowConf: 0, ...stats.dropped ? { dropped: [] } : {} };
3763
+ let alt;
3764
+ try {
3765
+ if (auto.lazy && !auto.fetch && !await ocrModelsCached(config.handwriting)) return items;
3766
+ if (auto.lazy) await ensureOcrModelsFor(config.handwriting, reportModelDownload);
3767
+ alt = await (await getOcrEngine(config.handwriting)).recognizePage(rgba, width, height, altStats, tuning, cellRules, rowRules);
3768
+ } catch (e) {
3769
+ if (!auto.lazy) throw e;
3770
+ return items;
3771
+ }
3772
+ const altMean = meanConfidence(alt);
3773
+ if (altMean - base < auto.gain) return items;
3774
+ if (auto.altConf !== void 0 && altMean - base < (auto.sureGain ?? Infinity)) {
3775
+ if (altMean < auto.altConf) return items;
3776
+ const text = (xs) => xs.map((it) => it.text).join("").replace(/\s/g, "");
3777
+ const a = text(items), b = text(alt);
3778
+ if (a.length < (auto.minChars ?? 0) || 1 - similarity(a, b) < (auto.minDiff ?? 0)) return items;
3779
+ }
3780
+ Object.assign(stats, altStats);
3781
+ return alt;
3782
+ }
3783
+ var announced = /* @__PURE__ */ new Set();
3784
+ function reportModelDownload(p) {
3785
+ if (p.phase !== "download" || announced.has(p.spec.filename)) return;
3786
+ announced.add(p.spec.filename);
3787
+ process.stderr.write(`[kordoc-ocr] ${p.spec.name} \uB2E4\uC6B4\uB85C\uB4DC \uC911 (~${p.spec.sizeMb}MB)...
3788
+ `);
3789
+ }
3790
+ function toOcrLine(it, dropped = false) {
3791
+ return { text: it.text, box: { x: it.x, y: it.y, w: it.w, h: it.h }, confidence: it.confidence, ...dropped ? { dropped: true } : {}, ...it.candidates && { candidates: it.candidates }, ...it.chars && { chars: it.chars } };
3792
+ }
3793
+ function pageLines(pageNumber, width, height, scale, deskewAngle, kept, dropped = [], regionsOnly = false, dewarp) {
3794
+ const lines = [...kept.map((it) => toOcrLine(it)), ...dropped.map((it) => toOcrLine(it, true))].sort((a, b) => a.box.y - b.box.y || a.box.x - b.box.x);
3795
+ return { pageNumber, width, height, scale, deskewAngle, ...dewarp ? { dewarp } : {}, ...regionsOnly ? { regionsOnly: true } : {}, lines };
3796
+ }
3797
+ function cellEdgeVerticals(r) {
3798
+ const touches = (x, y) => r.horizontals.some((h) => Math.abs(h.y1 - y) <= h.thicknessPx + 3 && h.x1 - 3 <= x && h.x2 + 3 >= x);
3799
+ return r.verticals.filter((v) => touches(v.x1, Math.min(v.y1, v.y2)) && touches(v.x1, Math.max(v.y1, v.y2)));
3800
+ }
3801
+ function cellEdgeHorizontals(r) {
3802
+ const touches = (x, y) => r.verticals.some((v) => Math.abs(v.x1 - x) <= v.thicknessPx + 3 && Math.min(v.y1, v.y2) - 3 <= y && Math.max(v.y1, v.y2) + 3 >= y);
3803
+ return r.horizontals.filter((h) => touches(Math.min(h.x1, h.x2), h.y1) && touches(Math.max(h.x1, h.x2), h.y1));
3804
+ }
3805
+ async function runPdfOcr(buffer, targets, mode, warnings, onProgress, detectTables = true, vectorOps, imageRegions, config = DEFAULT_BUILTIN_OCR, linesOut, rastersOut) {
3806
+ const result = /* @__PURE__ */ new Map();
3807
+ if (targets.size === 0) return result;
3808
+ const pdfiumMod = await tryImport2(
3809
+ "@hyzyla/pdfium",
3810
+ () => import("@hyzyla/pdfium")
3811
+ );
3812
+ if (mode === "builtin") await ensureOcrModelsFor(config.models, reportModelDownload);
3813
+ if (mode === "builtin" && config.handwriting && !config.autoRec?.lazy) await ensureOcrModelsFor(config.handwriting, reportModelDownload);
3814
+ const engine = mode === "builtin" ? await getOcrEngine(config.models) : null;
3815
+ const pdfium = await pdfiumMod.PDFiumLibrary.init();
3816
+ const doc = await pdfium.loadDocument(new Uint8Array(buffer));
3817
+ try {
3818
+ let done = 0;
3819
+ const count = doc.getPageCount();
3820
+ for (const pageNo of [...targets].filter((p) => p >= 1 && p <= count).sort((a, b) => a - b)) {
3821
+ const page = doc.getPage(pageNo - 1);
3822
+ onProgress?.(++done, targets.size);
3823
+ try {
3824
+ const { blocks, lines, raster } = await withTimeout(
3825
+ ocrOnePage(page, pageNo, mode, engine, warnings, detectTables, vectorOps?.get(pageNo), imageRegions?.get(pageNo), config, !!rastersOut),
3826
+ PAGE_TIMEOUT_MS,
3827
+ `OCR \uD398\uC774\uC9C0 ${pageNo} \uD0C0\uC784\uC544\uC6C3 (${PAGE_TIMEOUT_MS / 1e3}\uCD08)`
3828
+ );
3829
+ result.set(pageNo, blocks);
3830
+ if (lines) linesOut?.set(pageNo, lines);
3831
+ if (raster) await rastersOut?.add(pageNo, raster);
3832
+ } catch (e) {
3833
+ warnings.push({
3834
+ page: pageNo,
3835
+ message: `\uD398\uC774\uC9C0 ${pageNo} OCR \uC2E4\uD328: ${e instanceof Error ? e.message : String(e)}`,
3836
+ code: "OCR_FAILED"
3837
+ });
3838
+ }
3839
+ }
3840
+ } finally {
3841
+ doc.destroy();
3842
+ pdfium.destroy();
3843
+ }
3844
+ return result;
3845
+ }
3846
+ async function ocrOnePage(page, pageNo, mode, engine, warnings, detectTables, vectorOps, regions, config = DEFAULT_BUILTIN_OCR, wantRaster = false) {
3847
+ let { originalWidth: pdfW, originalHeight: pdfH } = page.getOriginalSize();
3848
+ const renderScale = Math.min(OCR_RENDER_SCALE, Math.sqrt(MAX_OCR_PIXELS / Math.max(1, pdfW * pdfH)));
3849
+ if (renderScale < OCR_RENDER_SCALE) {
3850
+ warnings.push({ page: pageNo, code: "PARTIAL_PARSE", message: `OCR \uB798\uC2A4\uD130 \uD53D\uC140 \uC0C1\uD55C\uC73C\uB85C \uB80C\uB354 \uD574\uC0C1\uB3C4\uB97C \uCD95\uC18C\uD588\uC2B5\uB2C8\uB2E4 (\uC791\uC740 \uAE00\uC790 \uC778\uC2DD \uACB0\uC190 \uAC00\uB2A5)` });
3851
+ }
3852
+ const closer = regions && mode === "builtin" && renderScale * 2 <= Math.sqrt(MAX_OCR_PIXELS / Math.max(1, pdfW * pdfH));
3853
+ const rendered = await page.render({
3854
+ scale: closer ? renderScale * 2 : renderScale,
3855
+ render: retainPdfiumRgba
3856
+ });
3857
+ if (mode === "builtin") swapRedBlue(rendered.data);
3858
+ const hiRgba = closer ? rendered.data : null;
3859
+ let { rgba, width: rw, height: rh } = hiRgba ? halve(hiRgba, rendered.width, rendered.height) : { rgba: rendered.data, width: rendered.width, height: rendered.height };
3860
+ if (mode === "builtin") {
3861
+ let { rgba: upright, angle, dewarp } = vectorOps || regions ? { rgba, angle: 0, dewarp: void 0 } : deskewPage(rgba, rw, rh);
3862
+ const stats = { droppedLowConf: 0, ...config.lines === "all" ? { dropped: [] } : {} };
3863
+ let ruling = vectorOps ? void 0 : detectRulingLines(upright, rw, rh, rh / pdfH, { slopeTolerant: angle === 0 && verticalsStraightened(dewarp, rh) });
3864
+ if (ruling && regions) ruling = { ...ruling, horizontals: ruling.horizontals.filter((h) => !h.isolated) };
3865
+ const tuning = regions ? regionTuning(config.tuning) : vectorOps ? { ...config.tuning, orientPage: false } : config.tuning;
3866
+ let items = await recognizeOcrPage(
3867
+ engine,
3868
+ config,
3869
+ tuning,
3870
+ upright,
3871
+ rw,
3872
+ rh,
3873
+ stats,
3874
+ ruling ? [...ruling.cellDividers ?? [], ...cellEdgeVerticals(ruling)] : void 0,
3875
+ ruling ? cellEdgeHorizontals(ruling) : void 0
3876
+ );
3877
+ if (stats.pageRotation) {
3878
+ ({ rgba: upright, width: rw, height: rh } = rotateQuarter(upright, rw, rh, stats.pageRotation));
3879
+ [pdfW, pdfH] = [pdfH, pdfW];
3880
+ delete stats.pageRotation;
3881
+ dewarp = void 0;
3882
+ ruling = detectRulingLines(upright, rw, rh, rh / pdfH);
3883
+ items = await recognizeOcrPage(
3884
+ engine,
3885
+ config,
3886
+ { ...tuning, orientPage: false },
3887
+ upright,
3888
+ rw,
3889
+ rh,
3890
+ stats,
3891
+ [...ruling.cellDividers ?? [], ...cellEdgeVerticals(ruling)],
3892
+ cellEdgeHorizontals(ruling)
3893
+ );
3894
+ }
3895
+ if (ruling && !regions && !vectorOps && config.tuning.postprocess) items = [...items, ...await rescueEmptyCells(engine, tuning, upright, rw, rh, ruling, items)];
3896
+ if (stats.droppedLowConf > 0) {
3897
+ warnings.push({
3898
+ page: pageNo,
3899
+ message: `\uD398\uC774\uC9C0 ${pageNo}: \uC800\uC2E0\uB8B0 OCR \uB77C\uC778 ${stats.droppedLowConf}\uAC1C \uD3D0\uAE30 (\uC778\uC2DD \uACB0\uC190 \uAC00\uB2A5)`,
3900
+ code: "OCR_LOW_CONF"
3901
+ });
3902
+ }
3903
+ if (stats.truncatedBoxes) {
3904
+ warnings.push({ page: pageNo, message: `\uD398\uC774\uC9C0 ${pageNo}: OCR \uAC80\uCD9C \uC0C1\uC790\uAC00 \uB108\uBB34 \uB9CE\uC544 ${stats.truncatedBoxes}\uAC1C\uB294 \uC778\uC2DD\uD558\uC9C0 \uC54A\uC74C (\uC77C\uBD80 \uAE00 \uACB0\uC190)`, code: "PARTIAL_PARSE" });
3905
+ }
3906
+ const scale = rh / pdfH;
3907
+ const withLines = (blocks, kept, regionsOnly = false) => {
3908
+ if (wantRaster) swapRedBlue(upright);
3909
+ const raster2 = wantRaster ? { raster: { data: upright, width: rw, height: rh } } : void 0;
3910
+ return config.lines ? { blocks, lines: pageLines(pageNo, rw, rh, scale, angle, kept, stats.dropped, regionsOnly, dewarp), ...raster2 } : { blocks, ...raster2 };
3911
+ };
3912
+ if (regions) {
3913
+ const inside = (it, r) => {
3914
+ const cx = (it.x + it.w / 2) / scale, cy = pdfH - (it.y + it.h / 2) / scale;
3915
+ return cx >= r.x1 && cx <= r.x2 && cy >= r.y1 && cy <= r.y2;
3916
+ };
3917
+ const reads = hiRgba ? await closerReads(hiRgba, rw * 2, rh * 2, pdfH, scale * 2, regions, engine, tuning) : [];
3918
+ const used = /* @__PURE__ */ new Set();
3919
+ const reread = /* @__PURE__ */ new Set();
3920
+ const regionBlocks = regions.flatMap((r, k) => {
3921
+ let own = items.filter((it) => inside(it, r));
3922
+ const near = reads[k];
3923
+ if (near?.length && meanConfidence(near) > meanConfidence(own)) {
3924
+ own = near;
3925
+ reread.add(k);
3926
+ }
3927
+ if (!own.length) return [];
3928
+ for (const it of own) used.add(it);
3929
+ const blocks = ocrItemsToBlocks(own, pageNo, pdfW, pdfH, scale, ruling && rulingToPdfLines(ruling, scale, pdfH), detectTables, void 0, true);
3930
+ const x1 = r.x1 * scale - 2, x2 = r.x2 * scale + 2, y1 = (pdfH - r.y2) * scale - 2, y2 = (pdfH - r.y1) * scale + 2;
3931
+ const columnRules = ruling?.verticals.filter((s) => Math.min(s.x1, s.x2) >= x1 && Math.max(s.x1, s.x2) <= x2 && Math.min(s.y1, s.y2) >= y1 && Math.max(s.y1, s.y2) <= y2).length ?? 0;
3932
+ if (columnRules < 2) {
3933
+ for (const b of blocks) if (b.type === "table") UNRULED_REGION_TABLES.add(b);
3934
+ }
3935
+ return blocks;
3936
+ });
3937
+ if (stats.dropped) stats.dropped = stats.dropped.filter((it) => regions.some((r, k) => !reread.has(k) && inside(it, r)));
3938
+ return withLines(regionBlocks, [...used], true);
3939
+ }
3940
+ if (vectorOps) return withLines(ocrItemsToBlocks(items, pageNo, pdfW, pdfH, scale, void 0, detectTables, vectorOps), items);
3941
+ const extraLines = rulingToPdfLines(ruling, scale, pdfH);
3942
+ return withLines(ocrItemsToBlocks(items, pageNo, pdfW, pdfH, scale, extraLines, detectTables), items);
3943
+ }
3944
+ const raster = wantRaster ? { raster: { data: rgba, width: rw, height: rh } } : void 0;
3945
+ const sharpModRaw = await tryImport2(
3946
+ "sharp",
3947
+ () => import("sharp")
3948
+ );
3949
+ const sharpAny = sharpModRaw;
3950
+ const sharp = typeof sharpAny === "function" ? sharpAny : sharpAny.default ?? sharpAny;
3951
+ const encode = (data, width, height) => sharp(data, { raw: { width, height, channels: 4 } }).png().toBuffer();
3952
+ if (regions) {
3953
+ const blocks = [];
3954
+ for (const r of regions) {
3955
+ const crop = cropRegion(rgba, rw, rh, pdfH, rh / pdfH, r);
3956
+ if (!crop) continue;
3957
+ const text2 = (await mode(new Uint8Array(await encode(crop.rgba, crop.width, crop.height)), pageNo, "image/png")).trim();
3958
+ if (text2) blocks.push({ type: "paragraph", text: text2, pageNumber: pageNo, bbox: { page: pageNo, x: r.x1, y: r.y1, width: r.x2 - r.x1, height: r.y2 - r.y1 } });
3959
+ }
3960
+ if (!blocks.length) warnings.push({ page: pageNo, message: `\uD398\uC774\uC9C0 ${pageNo} \uADF8\uB9BC \uC601\uC5ED OCR \uACB0\uACFC \uC5C6\uC74C`, code: "OCR_FAILED" });
3961
+ return { blocks, ...raster };
3962
+ }
3963
+ const png = await encode(rgba, rw, rh);
3964
+ const text = await mode(new Uint8Array(png), pageNo, "image/png");
3965
+ if (!text.trim()) {
3966
+ warnings.push({ page: pageNo, message: `\uD398\uC774\uC9C0 ${pageNo} OCR \uACB0\uACFC \uC5C6\uC74C`, code: "OCR_FAILED" });
3967
+ return { blocks: [], ...raster };
3968
+ }
3969
+ return { blocks: [{ type: "paragraph", text: text.trim(), pageNumber: pageNo }], ...raster };
3970
+ }
3971
+ async function renderPdfPageImages(buffer, pages, out, warnings) {
3972
+ if (!pages.length) return;
3973
+ const pdfiumMod = await tryImport2("@hyzyla/pdfium", () => import("@hyzyla/pdfium"));
3974
+ const pdfium = await pdfiumMod.PDFiumLibrary.init();
3975
+ const doc = await pdfium.loadDocument(new Uint8Array(buffer));
3976
+ try {
3977
+ const count = doc.getPageCount();
3978
+ for (const pageNo of pages) {
3979
+ if (pageNo < 1 || pageNo > count) continue;
3980
+ try {
3981
+ const page = doc.getPage(pageNo - 1);
3982
+ const { originalWidth: pdfW, originalHeight: pdfH } = page.getOriginalSize();
3983
+ const scale = Math.min(OCR_RENDER_SCALE, Math.sqrt(MAX_OCR_PIXELS / Math.max(1, pdfW * pdfH)));
3984
+ if (!out.reserve(Math.ceil(pdfW * scale) * Math.ceil(pdfH * scale))) continue;
3985
+ out.push(await withTimeout((async () => {
3986
+ const { data, width, height } = await page.render({ scale, render: retainPdfiumRgba });
3987
+ return out.encode(pageNo, { data, width, height });
3988
+ })(), PAGE_TIMEOUT_MS, `pageImages \uD398\uC774\uC9C0 ${pageNo} \uD0C0\uC784\uC544\uC6C3 (${PAGE_TIMEOUT_MS / 1e3}\uCD08)`));
3989
+ } catch (e) {
3990
+ warnings.push({ page: pageNo, message: `\uD398\uC774\uC9C0 ${pageNo} pageImages \uC0DD\uB7B5: ${e instanceof Error ? e.message : String(e)}`, code: "SKIPPED_IMAGE" });
3991
+ }
3992
+ }
3993
+ } finally {
3994
+ doc.destroy();
3995
+ pdfium.destroy();
3996
+ }
3997
+ }
3998
+ function halve(src, w, h) {
3999
+ const W = w >> 1, H = h >> 1;
4000
+ const out = new Uint8Array(W * H * 4);
4001
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
4002
+ const a = (2 * y * w + 2 * x) * 4, b = a + w * 4, o = (y * W + x) * 4;
4003
+ for (let c = 0; c < 4; c++) out[o + c] = src[a + c] + src[a + 4 + c] + src[b + c] + src[b + 4 + c] + 2 >> 2;
4004
+ }
4005
+ return { rgba: out, width: W, height: H };
4006
+ }
4007
+ var REGION_TUNING = Object.freeze({ ...DEFAULT_OCR_TUNING, trimEdges: false, orientPage: false, redetect: false });
4008
+ var regionTuning = (t) => t === DEFAULT_OCR_TUNING ? REGION_TUNING : { ...t, trimEdges: false, orientPage: false, redetect: false };
4009
+ function meanConfidence(items) {
4010
+ let n = 0, sum = 0;
4011
+ for (const it of items) {
4012
+ const len = [...it.text].length;
4013
+ n += len;
4014
+ sum += it.confidence * len;
4015
+ }
4016
+ return n ? sum / n : 0;
4017
+ }
4018
+ function stretchFaintCrop(rgba) {
4019
+ const n = rgba.length >> 2;
4020
+ if (!n) return;
4021
+ const hist = new Uint32Array(256);
4022
+ for (let i = 0; i < n; i++) hist[rgba[i * 4] * 77 + rgba[i * 4 + 1] * 150 + rgba[i * 4 + 2] * 29 >> 8]++;
4023
+ let lo = 0, hi = 255;
4024
+ for (let acc = 0; lo < 255 && (acc += hist[lo]) < n * 0.01; ) lo++;
4025
+ for (let acc = 0; hi > 0 && (acc += hist[hi]) < n * 0.01; ) hi--;
4026
+ if (hi - lo >= 120 || hi - lo < 16) return;
4027
+ const k = 255 / (hi - lo);
4028
+ for (let i = 0; i < n * 4; i++) if ((i & 3) !== 3) rgba[i] = Math.max(0, Math.min(255, Math.round((rgba[i] - lo) * k)));
4029
+ }
4030
+ function cropRegion(rgba, rw, rh, pdfH, scale, r) {
4031
+ const x0 = Math.max(0, Math.floor(r.x1 * scale)), y0 = Math.max(0, Math.floor((pdfH - r.y2) * scale));
4032
+ const cw = Math.min(rw, Math.ceil(r.x2 * scale)) - x0, ch = Math.min(rh, Math.ceil((pdfH - r.y1) * scale)) - y0;
4033
+ if (cw < 16 || ch < 16) return null;
4034
+ const crop = new Uint8Array(cw * ch * 4);
4035
+ for (let y = 0; y < ch; y++) crop.set(rgba.subarray(((y0 + y) * rw + x0) * 4, ((y0 + y) * rw + x0 + cw) * 4), y * cw * 4);
4036
+ return { rgba: crop, width: cw, height: ch, x0, y0 };
4037
+ }
4038
+ async function closerReads(rgba, rw, rh, pdfH, hi, regions, engine, tuning = REGION_TUNING) {
4039
+ const out = [];
4040
+ for (const r of regions) {
4041
+ const cut = cropRegion(rgba, rw, rh, pdfH, hi, r);
4042
+ if (!cut) {
4043
+ out.push(null);
4044
+ continue;
4045
+ }
4046
+ const { rgba: crop, width: cw, height: ch, x0, y0 } = cut;
4047
+ if (cw >= ch * 6) stretchFaintCrop(crop);
4048
+ const items = await engine.recognizePage(crop, cw, ch, void 0, tuning);
4049
+ out.push(items.map((it) => {
4050
+ const half = (b) => ({ x: (b.x + x0) / 2, y: (b.y + y0) / 2, w: b.w / 2, h: b.h / 2 });
4051
+ const placed = { ...it, ...half(it), ...it.chars && { chars: it.chars.map((c) => ({ ...c, box: half(c.box) })) } };
4052
+ copyOcrTextGaps(it, placed, 0.5, x0 / 2);
4053
+ return placed;
4054
+ }));
4055
+ }
4056
+ return out;
4057
+ }
4058
+ var proseBox = (b) => {
4059
+ const t = b.text.replace(/\s/g, "");
4060
+ return b.w >= b.h * 7 && (t.match(/\d/g)?.length ?? 0) < t.length * 0.3;
4061
+ };
4062
+ function groupOcrLines(items, figureRegion = false) {
4063
+ const order = items.map((_, i) => i).sort((a, b) => items[a].y + items[a].h / 2 - (items[b].y + items[b].h / 2));
4064
+ const accepts = (l, i) => {
4065
+ const it = items[i], c = it.y + it.h / 2;
4066
+ const lc = l.reduce((s, j) => s + items[j].y + items[j].h / 2, 0) / l.length;
4067
+ const minH = Math.min(it.h, ...l.map((j) => items[j].h));
4068
+ if (Math.abs(c - lc) > minH / 2) return false;
4069
+ const hs = l.map((j) => items[j].h).sort((a, b) => a - b), med = hs[hs.length >> 1];
4070
+ const weak = it.confidence < 0.8 || l.some((j) => items[j].confidence < 0.8);
4071
+ if (weak && Math.max(it.h, med) > Math.min(it.h, med) * 2) return false;
4072
+ let nearLong = 0, gap = Infinity;
4073
+ for (const j of l) {
4074
+ const o = items[j];
4075
+ const ov = Math.min(it.x + it.w, o.x + o.w) - Math.max(it.x, o.x);
4076
+ if (ov >= Math.min(it.w, o.w) / 2) return false;
4077
+ gap = Math.min(gap, Math.max(0, -ov));
4078
+ if (proseBox(it) && proseBox(o)) nearLong = Math.min(nearLong || Infinity, Math.max(0, -ov) / Math.min(it.h, o.h));
4079
+ }
4080
+ if (figureRegion && gap > 8 * minH && Math.abs(c - lc) > minH * 0.35) return false;
4081
+ return nearLong <= 5;
4082
+ };
4083
+ const lines = [];
4084
+ for (const i of order) {
4085
+ const line = lines.find((l) => accepts(l, i));
4086
+ if (line) line.push(i);
4087
+ else lines.push([i]);
4088
+ }
4089
+ for (let k = 0; k < lines.length; k++) {
4090
+ if (lines[k].length !== 1) continue;
4091
+ const i = lines[k][0];
4092
+ const target = lines.find((l, m) => m !== k && l.length > 0 && accepts(l, i));
4093
+ if (target) {
4094
+ target.push(i);
4095
+ lines[k] = [];
4096
+ }
4097
+ }
4098
+ return lines.filter((l) => l.length > 0);
4099
+ }
4100
+ function ocrItemsToBlocks(items, pageNumber, pdfW, pdfH, scale, extraLines, detectTables = true, opList = { fnArray: [], argsArray: [] }, figureRegion = false) {
4101
+ if (!figureRegion) {
4102
+ const chart = chartPlotItems(items);
4103
+ if (chart.size) items = items.filter((_, i) => !chart.has(i));
4104
+ }
4105
+ const bottoms = items.map((it) => it.y + it.h);
4106
+ const xs = items.map((it) => ({ x: it.x, r: it.x + it.w, space: false }));
4107
+ const texts = items.map((it) => it.text);
4108
+ for (const line of groupOcrLines(items, figureRegion)) {
4109
+ if (line.length < 2) continue;
4110
+ const sorted = line.map((j) => items[j].y + items[j].h).sort((a, b) => a - b);
4111
+ for (const j of line) bottoms[j] = sorted[Math.floor(sorted.length / 2)];
4112
+ const byX = [...line].sort((a, b) => items[a].x - items[b].x);
4113
+ for (let k = 1; k < byX.length; k++) {
4114
+ const L = xs[byX[k - 1]], R = xs[byX[k]];
4115
+ if (R.x >= L.r) continue;
4116
+ const lt = [...texts[byX[k - 1]]], rt = [...texts[byX[k]]], per = items[byX[k]].w / Math.max(1, rt.length);
4117
+ for (let n = Math.min(3, rt.length, lt.length); n >= 1; n--) {
4118
+ if (lt.slice(-n).join("") === rt.slice(0, n).join("") && /[가-힣]/.test(rt[0]) && L.r - R.x >= per * n * 0.5) {
4119
+ texts[byX[k]] = rt.slice(n).join("");
4120
+ break;
4121
+ }
4122
+ }
4123
+ const mid = (R.x + L.r) / 2, half = Math.min(items[byX[k - 1]].h, items[byX[k]].h) * 0.15;
4124
+ L.r = Math.max(L.x + 1, mid - half);
4125
+ R.x = Math.min(R.r - 1, mid + half);
4126
+ R.space = true;
4127
+ }
4128
+ }
4129
+ const norm = items.map((it, i) => {
4130
+ const h = (figureRegion ? Math.max(1, bottoms[i] - it.y) : it.h) / scale;
4131
+ const normalized = {
4132
+ text: texts[i],
4133
+ x: Math.round(xs[i].x / scale),
4134
+ // NormItem.y 는 pdfjs transform[5] = 베이스라인 (bottom-up) — 잉크 하단으로 근사
4135
+ y: Math.round(pdfH - bottoms[i] / scale),
4136
+ w: Math.round((xs[i].r - xs[i].x) / scale),
4137
+ h: Math.round(h),
4138
+ // 박스는 잉크 외곽(engine tightBoxes) — 한글 줄 잉크 높이 ≈ 0.9em
4139
+ fontSize: Math.max(1, Math.round(it.h / scale / 0.9)),
4140
+ fontName: "ocr",
4141
+ isHidden: false,
4142
+ ...xs[i].space ? { hasSpaceBefore: true } : {}
4143
+ };
4144
+ copyOcrTextGaps(it, normalized, 1 / scale);
4145
+ return normalized;
4146
+ }).filter((it) => it.text);
4147
+ if (extraLines?.verticals.length && items.length) {
4148
+ const hs = items.map((it) => it.h).sort((p, q) => p - q);
4149
+ const maxLen = hs[hs.length >> 1] * 2.5 / scale;
4150
+ const boxes = items.map((it) => ({ x0: (it.x + 3) / scale, x1: (it.x + it.w - 3) / scale, yTop: pdfH - it.y / scale, yBot: pdfH - (it.y + it.h) / scale }));
4151
+ extraLines = {
4152
+ ...extraLines,
4153
+ verticals: extraLines.verticals.filter((v) => {
4154
+ const lo = Math.min(v.y1, v.y2), hi = Math.max(v.y1, v.y2);
4155
+ if (hi - lo > maxLen) return true;
4156
+ return !boxes.some((b) => v.x1 > b.x0 && v.x1 < b.x1 && Math.min(hi, b.yTop) - Math.max(lo, b.yBot) > (hi - lo) * 0.5);
4157
+ })
4158
+ };
4159
+ }
4160
+ const laid = unframeOcrLayoutTables(splitOcrJoinedHeaders(splitOcrContactColumns(splitOcrNameValueColumns(splitStackedOcrRows(extractPageBlocksWithLines(norm, pageNumber, opList, pdfW, pdfH, extraLines, detectTables))))), pdfH);
4161
+ const blocks = figureRegion ? laid : splitOcrProseRows(laid);
4162
+ if (!figureRegion) markOcrHeadings(blocks);
4163
+ return blocks;
4164
+ }
4165
+ function markOcrHeadings(blocks) {
4166
+ const sized = blocks.filter((b) => b.type === "paragraph" && b.text && b.style?.fontSize);
4167
+ const weights = sized.map((b) => [b.style.fontSize, b.text.length]);
4168
+ const total = weights.reduce((n, [, w]) => n + w, 0);
4169
+ if (total < 100) return;
4170
+ weights.sort((a, b) => a[0] - b[0]);
4171
+ let acc = 0, body = 0;
4172
+ for (const [size, w] of weights) {
4173
+ acc += w;
4174
+ if (acc >= total / 2) {
4175
+ body = size;
4176
+ break;
4177
+ }
4178
+ }
4179
+ if (!body) return;
4180
+ for (const b of sized) {
4181
+ const text = b.text.trim(), size = b.style.fontSize;
4182
+ const ratio = size / body;
4183
+ if (ratio >= 1 && ratio < 1.3 && /^제\s*\d+\s*[장절편부](?:\s+\S|(?![에의은는을를이가와과로도만\s])\S)/.test(text) && text.length <= 30 && !/[.!?。,]$|다\.?$/.test(text) && (!b.bbox || b.bbox.height <= size * 1.6)) {
4184
+ b.type = "heading";
4185
+ b.level = /^제\s*\d+\s*절/.test(text) ? 2 : 1;
4186
+ continue;
4187
+ }
4188
+ if (text.length <= 60 && /^[A-Z0-9][A-Z0-9 '’&:!,-]*$/.test(text) && (text.match(/[A-Z]/g) ?? []).length >= 12 && /[A-Z]{2,}[,:]?\s+[A-Z]{2,}/.test(text) && !/[.,]$/.test(text) && (!b.bbox || b.bbox.height <= size * 3.2)) {
4189
+ b.type = "heading";
4190
+ b.level = ratio >= 1.5 ? 1 : 2;
4191
+ continue;
4192
+ }
4193
+ if (ratio < 1.3) continue;
4194
+ if (text.length < 2 || text.length > (ratio >= 1.5 ? 60 : 40) || /[.!?。]$|다\.?$/.test(text) || /^[\d\s.,%·-]+$/.test(text)) continue;
4195
+ if (/=/.test(text) || /^[,.;:)\]}]/.test(text) || /^[a-z]/.test(text)) continue;
4196
+ if (b.bbox && b.bbox.height > size * (ratio >= 1.5 ? 3.2 : 1.6)) continue;
4197
+ b.type = "heading";
4198
+ b.level = ratio >= 1.5 ? 1 : 2;
4199
+ }
4200
+ for (let i = blocks.length - 1; i > 0; i--) {
4201
+ const a = blocks[i - 1], b = blocks[i];
4202
+ if (a.type !== "heading" || b.type !== "heading" || !a.bbox || !b.bbox) continue;
4203
+ const marker = /^(?:제\s*\d+\s*[장절편부]|chapter\s*\d+|part\s*\d+)$/i.test(a.text.trim());
4204
+ const sa = a.style?.fontSize ?? 0, sb = b.style?.fontSize ?? 0;
4205
+ if (!marker && (a.level !== b.level || Math.max(sa, sb) > Math.min(sa, sb) * 1.3)) continue;
4206
+ const gap = a.bbox.y - (b.bbox.y + b.bbox.height), size = Math.max(a.style?.fontSize ?? 0, b.style?.fontSize ?? 0);
4207
+ const across = Math.min(a.bbox.x + a.bbox.width, b.bbox.x + b.bbox.width) - Math.max(a.bbox.x, b.bbox.x);
4208
+ if (gap < 0 || gap > size * (marker ? 3 : 1.2) || across <= 0) continue;
4209
+ a.level = Math.min(a.level ?? 2, b.level ?? 2);
4210
+ a.text = `${a.text.trim()} ${b.text.trim()}`;
4211
+ const x = Math.min(a.bbox.x, b.bbox.x);
4212
+ a.bbox = { ...a.bbox, x, y: b.bbox.y, width: Math.max(a.bbox.x + a.bbox.width, b.bbox.x + b.bbox.width) - x, height: a.bbox.y + a.bbox.height - b.bbox.y };
4213
+ blocks.splice(i, 1);
4214
+ }
4215
+ }
4216
+ async function tryImport2(name, loader) {
4217
+ try {
4218
+ return await loader();
4219
+ } catch (e) {
4220
+ throw new Error(
4221
+ `OCR \uC744 \uC0AC\uC6A9\uD558\uB824\uBA74 optional dependency '${name}' \uC774 \uD544\uC694\uD569\uB2C8\uB2E4. \`npm install ${name}\` \uD6C4 \uB2E4\uC2DC \uC2E4\uD589\uD558\uC138\uC694.${OPTIONAL_DEP_INSTALL_HINT} \uC6D0\uC778: ${e.message}`
4222
+ );
4223
+ }
4224
+ }
4225
+ async function withTimeout(promise, ms, msg) {
4226
+ promise.catch(() => {
4227
+ });
4228
+ let timer;
4229
+ try {
4230
+ return await Promise.race([
4231
+ promise,
4232
+ new Promise((_, reject) => {
4233
+ timer = setTimeout(() => reject(new Error(msg)), ms);
4234
+ })
4235
+ ]);
4236
+ } finally {
4237
+ if (timer) clearTimeout(timer);
4238
+ }
4239
+ }
4240
+ async function retainPdfiumRgba({ data }) {
4241
+ return data.byteOffset === 0 && data.byteLength === data.buffer.byteLength ? data : new Uint8Array(data);
4242
+ }
4243
+ function swapRedBlue(data) {
4244
+ for (let i = 0; i < data.length; i += 4) {
4245
+ const red = data[i];
4246
+ data[i] = data[i + 2];
4247
+ data[i + 2] = red;
4248
+ }
4249
+ }
4250
+
4251
+ export {
4252
+ detectRulingLines,
4253
+ rulingToPdfLines,
4254
+ getOcrEngine,
4255
+ verticalsStraightened,
4256
+ deskewPage,
4257
+ rotateQuarter,
4258
+ straightenPhoto,
4259
+ rescueEmptyCells,
4260
+ MAX_OCR_PIXELS,
4261
+ DEFAULT_BUILTIN_OCR,
4262
+ builtinOcrConfig,
4263
+ recognizeOcrPage,
4264
+ reportModelDownload,
4265
+ toOcrLine,
4266
+ pageLines,
4267
+ cellEdgeVerticals,
4268
+ cellEdgeHorizontals,
4269
+ runPdfOcr,
4270
+ ocrOnePage,
4271
+ renderPdfPageImages,
4272
+ stretchFaintCrop,
4273
+ groupOcrLines,
4274
+ ocrItemsToBlocks,
4275
+ markOcrHeadings
4276
+ };