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,1173 @@
1
+ import { createRequire as __hwpx2fRequire } from 'node:module'; const require = __hwpx2fRequire(import.meta.url);
2
+ import {
3
+ createOrtSession,
4
+ disableOrtTelemetry
5
+ } from "./chunk-UOXPGSFH.js";
6
+ import {
7
+ ALL_FORMULA_MODELS,
8
+ MFD_MODEL,
9
+ MFR_DECODER_MODEL,
10
+ MFR_ENCODER_MODEL,
11
+ MFR_TOKENIZER,
12
+ ensureFormulaModels,
13
+ ensureSingleModel,
14
+ getFormulaModelStatus,
15
+ getFormulaModelsDir
16
+ } from "./chunk-B6MTS4XP.js";
17
+ import "./chunk-OYXOOP2U.js";
18
+ import "./chunk-RYJRNK5Z.js";
19
+
20
+ // node_modules/kordoc/dist/formula-LC62GV4D.js
21
+ import { join } from "path";
22
+ var TRAILING_WHITESPACE_CMDS = [
23
+ "\\,",
24
+ "\\:",
25
+ "\\;",
26
+ "\\!",
27
+ "\\ ",
28
+ "\\quad",
29
+ "\\qquad",
30
+ "\\enspace",
31
+ "\\thinspace"
32
+ ];
33
+ function postProcessLatex(latex) {
34
+ let s = stripTrailingWhitespace(latex);
35
+ s = collapseSpaces(s);
36
+ for (let i = 0; i < 10; i++) {
37
+ const next = stripEmptyGroups(s);
38
+ if (next === s) break;
39
+ s = next;
40
+ }
41
+ s = stripUnpairedLeftRight(s);
42
+ s = fixLatexSpacing(s);
43
+ s = normalizeFormulaSpacing(s);
44
+ s = doubleBarNorms(s);
45
+ s = s.trim();
46
+ if ((s.match(/\\+$/)?.[0].length ?? 0) % 2) s = s.slice(0, -1).trimEnd();
47
+ if (isTrivialFormula(s)) return "";
48
+ return textModeCommands(uprightCapitalGreek(s));
49
+ }
50
+ function doubleBarNorms(s) {
51
+ return s.replace(/(?<![\\|])\|\|([^|]+?)(?<!\\)\|\|(?!\|)/g, "\\|$1\\|").replace(/(?<!\\)\|\\,((?:(?!\\\||\|).)*?)\\\|/g, "\\|$1\\|");
52
+ }
53
+ function uprightCapitalGreek(s) {
54
+ return s.replace(/\\var(Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?![A-Za-z])/g, "\\$1");
55
+ }
56
+ function textModeCommands(s) {
57
+ let out = "";
58
+ for (let i = 0; i < s.length; ) {
59
+ const at = s.indexOf("\\mathrm{\\boldmath", i);
60
+ if (at < 0) {
61
+ out += s.slice(i);
62
+ break;
63
+ }
64
+ let depth = 0, j = at + "\\mathrm".length;
65
+ for (; j < s.length; j++) {
66
+ if (s[j] === "\\") {
67
+ j++;
68
+ continue;
69
+ }
70
+ if (s[j] === "{") depth++;
71
+ else if (s[j] === "}" && --depth === 0) break;
72
+ }
73
+ if (j >= s.length) {
74
+ out += s.slice(i);
75
+ break;
76
+ }
77
+ const inner = s.slice(at + "\\mathrm{\\boldmath".length, j).replace(/^~+|~+$/g, "");
78
+ out += s.slice(i, at) + `\\mathbf{${inner}}`;
79
+ i = j + 1;
80
+ }
81
+ return out.replace(/(?<!\\)\\\.(?![A-Za-z])/g, ".");
82
+ }
83
+ function stripUnpairedLeftRight(s) {
84
+ const open = [];
85
+ const drop = /* @__PURE__ */ new Set();
86
+ for (const m of s.matchAll(/\\(left|right)(?![A-Za-z])/g)) {
87
+ if (m[1] === "left") open.push(m.index);
88
+ else if (open.length) open.pop();
89
+ else drop.add(m.index);
90
+ }
91
+ for (const i of open) drop.add(i);
92
+ if (drop.size === 0) return s;
93
+ let out = "";
94
+ let at = 0;
95
+ for (const i of [...drop].sort((a, b) => a - b)) {
96
+ out += s.slice(at, i);
97
+ at = i + (s.startsWith("\\left", i) ? 5 : 6);
98
+ }
99
+ return out + s.slice(at);
100
+ }
101
+ function stripTrailingWhitespace(s) {
102
+ let t = s;
103
+ for (; ; ) {
104
+ const trimmed = t.replace(/[\s]+$/, "");
105
+ let changed = false;
106
+ for (const p of TRAILING_WHITESPACE_CMDS) {
107
+ if (trimmed.endsWith(p)) {
108
+ t = trimmed.slice(0, trimmed.length - p.length);
109
+ changed = true;
110
+ break;
111
+ }
112
+ }
113
+ if (!changed) return trimmed;
114
+ }
115
+ }
116
+ function collapseSpaces(s) {
117
+ let out = "";
118
+ let prevSpace = false;
119
+ for (const c of s) {
120
+ if (/\s/.test(c)) {
121
+ if (!prevSpace) {
122
+ out += " ";
123
+ prevSpace = true;
124
+ }
125
+ } else {
126
+ out += c;
127
+ prevSpace = false;
128
+ }
129
+ }
130
+ return out;
131
+ }
132
+ function stripEmptyGroups(s) {
133
+ let out = "";
134
+ let i = 0;
135
+ const bytes = s;
136
+ while (i < bytes.length) {
137
+ const ch = bytes[i];
138
+ if (ch === "{") {
139
+ let j = i + 1;
140
+ while (j < bytes.length && /\s/.test(bytes[j])) j++;
141
+ if (j < bytes.length && bytes[j] === "}") {
142
+ while (out.endsWith(" ") || out.endsWith(" ")) {
143
+ out = out.slice(0, -1);
144
+ }
145
+ if (out.endsWith("^") || out.endsWith("_")) {
146
+ out = out.slice(0, -1);
147
+ } else {
148
+ let k = out.length;
149
+ while (k > 0 && /[A-Za-z]/.test(out[k - 1])) k--;
150
+ if (k > 0 && out[k - 1] === "\\" && k < out.length) {
151
+ out = out.slice(0, k - 1);
152
+ }
153
+ }
154
+ i = j + 1;
155
+ continue;
156
+ }
157
+ }
158
+ out += ch;
159
+ i++;
160
+ }
161
+ return out;
162
+ }
163
+ var KNOWN_LATEX_CMDS = /* @__PURE__ */ new Set([
164
+ // 연산자
165
+ "cdot",
166
+ "cdots",
167
+ "ldots",
168
+ "dots",
169
+ "vdots",
170
+ "ddots",
171
+ "times",
172
+ "div",
173
+ "pm",
174
+ "mp",
175
+ "ast",
176
+ "star",
177
+ "circ",
178
+ "bullet",
179
+ "oplus",
180
+ "ominus",
181
+ "otimes",
182
+ "odot",
183
+ // 관계
184
+ "approx",
185
+ "equiv",
186
+ "neq",
187
+ "ne",
188
+ "sim",
189
+ "simeq",
190
+ "cong",
191
+ "leq",
192
+ "geq",
193
+ "le",
194
+ "ge",
195
+ "ll",
196
+ "gg",
197
+ "prec",
198
+ "succ",
199
+ "preceq",
200
+ "succeq",
201
+ "propto",
202
+ "parallel",
203
+ "perp",
204
+ // 집합/논리
205
+ "in",
206
+ "notin",
207
+ "ni",
208
+ "subset",
209
+ "supset",
210
+ "subseteq",
211
+ "supseteq",
212
+ "cap",
213
+ "cup",
214
+ "bigcap",
215
+ "bigcup",
216
+ "emptyset",
217
+ "varnothing",
218
+ "forall",
219
+ "exists",
220
+ "nexists",
221
+ "neg",
222
+ "lnot",
223
+ "land",
224
+ "lor",
225
+ "vee",
226
+ "wedge",
227
+ // 그리스 소문자
228
+ "alpha",
229
+ "beta",
230
+ "gamma",
231
+ "delta",
232
+ "epsilon",
233
+ "varepsilon",
234
+ "zeta",
235
+ "eta",
236
+ "theta",
237
+ "vartheta",
238
+ "iota",
239
+ "kappa",
240
+ "lambda",
241
+ "mu",
242
+ "nu",
243
+ "xi",
244
+ "omicron",
245
+ "pi",
246
+ "varpi",
247
+ "rho",
248
+ "varrho",
249
+ "sigma",
250
+ "varsigma",
251
+ "tau",
252
+ "upsilon",
253
+ "phi",
254
+ "varphi",
255
+ "chi",
256
+ "psi",
257
+ "omega",
258
+ // 그리스 대문자
259
+ "Gamma",
260
+ "Delta",
261
+ "Theta",
262
+ "Lambda",
263
+ "Xi",
264
+ "Pi",
265
+ "Sigma",
266
+ "Upsilon",
267
+ "Phi",
268
+ "Psi",
269
+ "Omega",
270
+ // 화살표
271
+ "to",
272
+ "gets",
273
+ "mapsto",
274
+ "rightarrow",
275
+ "leftarrow",
276
+ "leftrightarrow",
277
+ "Rightarrow",
278
+ "Leftarrow",
279
+ "Leftrightarrow",
280
+ "uparrow",
281
+ "downarrow",
282
+ "longrightarrow",
283
+ "longleftarrow",
284
+ "longmapsto",
285
+ // 큰 연산자
286
+ "sum",
287
+ "prod",
288
+ "coprod",
289
+ "int",
290
+ "iint",
291
+ "iiint",
292
+ "oint",
293
+ "bigoplus",
294
+ "bigotimes",
295
+ // 함수명
296
+ "sin",
297
+ "cos",
298
+ "tan",
299
+ "sec",
300
+ "csc",
301
+ "cot",
302
+ "arcsin",
303
+ "arccos",
304
+ "arctan",
305
+ "sinh",
306
+ "cosh",
307
+ "tanh",
308
+ "log",
309
+ "ln",
310
+ "lg",
311
+ "exp",
312
+ "lim",
313
+ "liminf",
314
+ "limsup",
315
+ "sup",
316
+ "inf",
317
+ "max",
318
+ "min",
319
+ "arg",
320
+ "det",
321
+ "dim",
322
+ "gcd",
323
+ "deg",
324
+ "hom",
325
+ "ker",
326
+ "mod",
327
+ // 특수 기호/수식
328
+ "infty",
329
+ "partial",
330
+ "nabla",
331
+ "prime",
332
+ "aleph",
333
+ "ell",
334
+ "hbar",
335
+ "Re",
336
+ "Im",
337
+ "top",
338
+ "bot",
339
+ "angle",
340
+ "vdash",
341
+ "dashv",
342
+ // 기타
343
+ "left",
344
+ "right",
345
+ "big",
346
+ "Big",
347
+ "bigg",
348
+ "Bigg",
349
+ // 크기 붙은 괄호·나머지 — 아는 접두(\Big·\pm) 뒤 한두 글자라 아래 분리 규칙에 걸린다
350
+ "bigl",
351
+ "bigr",
352
+ "Bigl",
353
+ "Bigr",
354
+ "biggl",
355
+ "biggr",
356
+ "Biggl",
357
+ "Biggr",
358
+ "pmod",
359
+ "bmod"
360
+ ]);
361
+ function fixLatexSpacing(s) {
362
+ let out = "";
363
+ let i = 0;
364
+ while (i < s.length) {
365
+ if (s[i] === "\\" && i + 1 < s.length && /[A-Za-z]/.test(s[i + 1])) {
366
+ let j = i + 1;
367
+ while (j < s.length && /[A-Za-z]/.test(s[j])) j++;
368
+ const full = s.slice(i + 1, j);
369
+ const nextChar = j < s.length ? s[j] : "";
370
+ if (nextChar === "{") {
371
+ out += "\\" + full;
372
+ i = j;
373
+ continue;
374
+ }
375
+ let splitAt = full.length;
376
+ if (!KNOWN_LATEX_CMDS.has(full) && full.length >= 3) {
377
+ for (let len = full.length - 1; len >= 2; len--) {
378
+ if (KNOWN_LATEX_CMDS.has(full.slice(0, len))) {
379
+ splitAt = len;
380
+ break;
381
+ }
382
+ }
383
+ }
384
+ if (full.length - splitAt > 2) splitAt = full.length;
385
+ out += "\\" + full.slice(0, splitAt);
386
+ if (splitAt < full.length) {
387
+ out += " " + full.slice(splitAt);
388
+ }
389
+ i = j;
390
+ } else {
391
+ out += s[i];
392
+ i++;
393
+ }
394
+ }
395
+ return out;
396
+ }
397
+ function isTrivialFormula(s) {
398
+ const t = s.trim();
399
+ if (t.length === 0) return true;
400
+ const stripped = t.replace(/[\s{}]/g, "");
401
+ if (stripped.length <= 2) return true;
402
+ if (/^\\[A-Za-z]+$/.test(t)) return true;
403
+ if (/^\\(?:mathrm|textrm|text|operatorname|mathit|mathbf|mathcal|mathsf|mathtt)\{[A-Za-z]{1,6}\}$/.test(
404
+ t
405
+ ))
406
+ return true;
407
+ const tokens = tokenizeLatex(t);
408
+ if (tokens.length >= 3) {
409
+ const freq = /* @__PURE__ */ new Map();
410
+ for (const tok of tokens) freq.set(tok, (freq.get(tok) ?? 0) + 1);
411
+ let maxCount = 0;
412
+ for (const c of freq.values()) if (c > maxCount) maxCount = c;
413
+ if (maxCount >= 3 && maxCount / tokens.length >= 0.5) return true;
414
+ }
415
+ if (tokens.length >= 2 && tokens.length <= 4) {
416
+ const hasOpOrNum = tokens.some(
417
+ (tok) => /^[=+\-/*<>]$/.test(tok) || /^[0-9]$/.test(tok)
418
+ );
419
+ if (!hasOpOrNum) return true;
420
+ }
421
+ if (hasHighRepetition(t) && hasHighRepetition(t.replace(/([_^])\{[^{}]*\}/g, "$1"))) return true;
422
+ if (t.includes("\\square")) return true;
423
+ if (/^[-+]?\d+\.?\d*$/.test(t.replace(/[\s{}\\]/g, ""))) return true;
424
+ if (/(\([^()]{2,15}\))\s*\1/.test(t)) return true;
425
+ if (/(\{(?:[^{}]|\{[^{}]*\})+\})\s*\1/.test(t)) return true;
426
+ const argMatch = t.match(/^[A-Za-z\\][A-Za-z]*\(([^()]+)\)$/);
427
+ if (argMatch) {
428
+ const args = argMatch[1].split(",").map((a) => a.trim());
429
+ if (args.length >= 2) {
430
+ const freq = /* @__PURE__ */ new Map();
431
+ for (const a of args) if (a) freq.set(a, (freq.get(a) ?? 0) + 1);
432
+ for (const [, c] of freq) {
433
+ if (c >= 2 && c / args.length >= 0.5) return true;
434
+ }
435
+ }
436
+ }
437
+ if (/\\frac\{([^{}]+)\}\{\1\}/.test(t)) return true;
438
+ if (/(\\[A-Za-z]+|\b[A-Za-z])\s*\/\s*\1\b/.test(t)) return true;
439
+ if (/\\begin\{(?:matrix|pmatrix|bmatrix|vmatrix)\}/.test(t)) {
440
+ const cdotsCount = (t.match(/\\cdots/g) ?? []).length;
441
+ if (cdotsCount >= 2) return true;
442
+ }
443
+ if (tokens.length <= 12) {
444
+ const mathrmCount = (t.match(/\\mathrm\{/g) ?? []).length;
445
+ if (mathrmCount >= 2) {
446
+ const hasRealMath = /[=+\-*/<>^]/.test(t) && /\d/.test(t);
447
+ if (!hasRealMath) return true;
448
+ }
449
+ }
450
+ if (/^[a-zA-Z]{2,3}_\{\\mathrm\{[a-zA-Z]{3,}\}\}$/.test(t)) return true;
451
+ if (/^\\mathrm\{[a-z]{2,}\}[-+][-+]?(?:\\[a-zA-Z]+|[a-zA-Z0-9])$/.test(t)) return true;
452
+ if (/\\(?:mathsf|mathtt|texttt)\{/.test(t)) return true;
453
+ if (/\\begin\{aligned\}/.test(t) && !/[=<>]|\\(?:leq?|geq?|leqslant|geqslant|lesssim|gtrsim|ll|gg|approx|sim|simeq|cong|equiv|neq?|propto|triangleq|implies|iff|Longleftrightarrow)(?![A-Za-z])/.test(t)) return true;
454
+ if (/\\begin\{matrix\}/.test(t) && (t.match(/\\downarrow/g) ?? []).length >= 2) return true;
455
+ return false;
456
+ }
457
+ function hasHighRepetition(s) {
458
+ if (s.length < 15) return false;
459
+ for (let len = 5; len <= 15; len++) {
460
+ if (len * 3 > s.length) break;
461
+ const seen = /* @__PURE__ */ new Map();
462
+ for (let i = 0; i <= s.length - len; i++) {
463
+ const sub = s.slice(i, i + len);
464
+ if (!/[a-zA-Z]/.test(sub)) continue;
465
+ seen.set(sub, (seen.get(sub) ?? 0) + 1);
466
+ }
467
+ for (const [, count] of seen) {
468
+ if (count < 3) continue;
469
+ if (count * len / s.length >= 0.6) return true;
470
+ }
471
+ }
472
+ return false;
473
+ }
474
+ function tokenizeLatex(s) {
475
+ const result = [];
476
+ let i = 0;
477
+ while (i < s.length) {
478
+ const c = s[i];
479
+ if (c === "\\") {
480
+ let j = i + 1;
481
+ while (j < s.length && /[A-Za-z]/.test(s[j])) j++;
482
+ if (j === i + 1 && j < s.length) j++;
483
+ result.push(s.slice(i, j));
484
+ i = j;
485
+ } else if (/\s/.test(c)) {
486
+ i++;
487
+ } else {
488
+ result.push(c);
489
+ i++;
490
+ }
491
+ }
492
+ return result;
493
+ }
494
+ function normalizeFormulaSpacing(s) {
495
+ const tokens = [];
496
+ let i = 0;
497
+ while (i < s.length) {
498
+ const c = s[i];
499
+ if (c === "\\") {
500
+ let j = i + 1;
501
+ while (j < s.length && /[A-Za-z]/.test(s[j])) j++;
502
+ if (j === i + 1 && j < s.length) j++;
503
+ tokens.push(s.slice(i, j));
504
+ i = j;
505
+ } else if (/\s/.test(c)) {
506
+ tokens.push(" ");
507
+ i++;
508
+ } else {
509
+ tokens.push(c);
510
+ i++;
511
+ }
512
+ }
513
+ const out = [];
514
+ for (let k = 0; k < tokens.length; k++) {
515
+ if (tokens[k] !== " ") {
516
+ out.push(tokens[k]);
517
+ continue;
518
+ }
519
+ let prev = "";
520
+ for (let p = k - 1; p >= 0; p--) {
521
+ if (tokens[p] !== " ") {
522
+ prev = tokens[p];
523
+ break;
524
+ }
525
+ }
526
+ let next = "";
527
+ for (let q = k + 1; q < tokens.length; q++) {
528
+ if (tokens[q] !== " ") {
529
+ next = tokens[q];
530
+ break;
531
+ }
532
+ }
533
+ const prevIsCmd = /^\\[A-Za-z]+$/.test(prev);
534
+ const nextIsAlpha = /^[A-Za-z]$/.test(next);
535
+ if (prevIsCmd && nextIsAlpha) {
536
+ if (out.length === 0 || out[out.length - 1] !== " ") {
537
+ out.push(" ");
538
+ }
539
+ }
540
+ }
541
+ while (out.length > 0 && out[0] === " ") out.shift();
542
+ while (out.length > 0 && out[out.length - 1] === " ") out.pop();
543
+ return out.join("");
544
+ }
545
+ function dropNestedDisplays(regions) {
546
+ const display = regions.filter((r) => r.kind === "display" && r.latex.trim());
547
+ const nested = (r) => display.some((o) => {
548
+ if (o === r || o.bbox.y2 - o.bbox.y1 < (r.bbox.y2 - r.bbox.y1) * 1.5) return false;
549
+ const w = Math.min(r.bbox.x2, o.bbox.x2) - Math.max(r.bbox.x1, o.bbox.x1);
550
+ const h = Math.min(r.bbox.y2, o.bbox.y2) - Math.max(r.bbox.y1, o.bbox.y1);
551
+ return w > 0 && h > 0 && w * h >= (r.bbox.x2 - r.bbox.x1) * (r.bbox.y2 - r.bbox.y1) * 0.85;
552
+ });
553
+ return regions.filter((r) => !(r.kind === "display" && r.latex.trim() && nested(r)));
554
+ }
555
+ function unwrapAligned(latex) {
556
+ const t = latex.trim();
557
+ const m = /^\\begin\{aligned\}([\s\S]*)\\end\{aligned\}$/.exec(t);
558
+ return m ? m[1].trim() : t;
559
+ }
560
+ function mergeContinuationLines(regions) {
561
+ const CONT = /^\s*(?:=|<|>|\+|\\(?:leq?|geq?|leqslant|geqslant|approx|sim|simeq|equiv|cdot|times|neq?|lesssim|gtrsim|propto|qquad|quad)(?![A-Za-z]))/;
562
+ const display = regions.filter((r) => r.kind === "display" && r.latex.trim()).sort((a, b) => a.bbox.y1 - b.bbox.y1);
563
+ const drop = /* @__PURE__ */ new Set();
564
+ const merged = /* @__PURE__ */ new Map();
565
+ let head = null;
566
+ for (const r of display) {
567
+ const h = head ? merged.get(head) : null;
568
+ if (head && h) {
569
+ const gap = r.bbox.y1 - h.bbox.y2;
570
+ const minH = Math.min(r.bbox.y2 - r.bbox.y1, head.bbox.y2 - head.bbox.y1);
571
+ const overlap = Math.min(r.bbox.x2, h.bbox.x2) - Math.max(r.bbox.x1, h.bbox.x1);
572
+ const narrow = Math.min(r.bbox.x2 - r.bbox.x1, h.bbox.x2 - h.bbox.x1);
573
+ if (gap >= -minH * 0.3 && gap <= minH && overlap >= narrow * 0.5 && CONT.test(unwrapAligned(r.latex).replace(/^[\s{&]+/, ""))) {
574
+ h.lines.push(unwrapAligned(r.latex));
575
+ h.bbox = { x1: Math.min(h.bbox.x1, r.bbox.x1), y1: h.bbox.y1, x2: Math.max(h.bbox.x2, r.bbox.x2), y2: Math.max(h.bbox.y2, r.bbox.y2) };
576
+ drop.add(r);
577
+ continue;
578
+ }
579
+ }
580
+ head = r;
581
+ merged.set(r, { bbox: { ...r.bbox }, lines: [unwrapAligned(r.latex)] });
582
+ }
583
+ if (!drop.size) return regions;
584
+ return regions.filter((r) => !drop.has(r)).map((r) => {
585
+ const m = merged.get(r);
586
+ if (!m || m.lines.length < 2) return r;
587
+ return { ...r, bbox: m.bbox, latex: `\\begin{aligned}${m.lines.join(" \\\\ ")}\\end{aligned}` };
588
+ });
589
+ }
590
+ var MFD_IMG_SIZE = 768;
591
+ var MFD_NUM_CLASSES = 2;
592
+ var MFD_CHANNELS = 4 + MFD_NUM_CLASSES;
593
+ var MFD_CONF_INLINE = 0.3;
594
+ var MFD_CONF_DISPLAY = 0.4;
595
+ var MFD_IOU_THRESHOLD = 0.45;
596
+ var MFD_CONF_DISPLAY_GROW = 0.1;
597
+ var MFD_MIN_AREA = 80;
598
+ var PAD_VALUE = 114 / 255;
599
+ async function detectFormulaRegions(session, frame, ort) {
600
+ const { scale, padX, padY, tensor } = letterbox(frame, MFD_IMG_SIZE);
601
+ const input = new ort.Tensor("float32", tensor, [1, 3, MFD_IMG_SIZE, MFD_IMG_SIZE]);
602
+ const feeds = { images: input };
603
+ const outputs = await session.run(feeds);
604
+ const firstKey = Object.keys(outputs)[0];
605
+ const out = outputs[firstKey];
606
+ if (!out || out.type !== "float32") {
607
+ throw new Error("MFD \uCD9C\uB825 \uC5C6\uC74C \uB610\uB294 dtype \uBD88\uC77C\uCE58");
608
+ }
609
+ const outDims = out.dims;
610
+ if (outDims.length !== 3) {
611
+ throw new Error(`MFD \uCD9C\uB825 \uCC28\uC6D0 \uC608\uC0C1 3, \uC2E4\uC81C ${outDims.length}: [${outDims.join(",")}]`);
612
+ }
613
+ const channels = outDims[1];
614
+ const anchors = outDims[2];
615
+ if (channels !== MFD_CHANNELS) {
616
+ throw new Error(`MFD \uCC44\uB110 \uC218 \uC608\uC0C1 ${MFD_CHANNELS}, \uC2E4\uC81C ${channels}`);
617
+ }
618
+ if (anchors <= 0) return [];
619
+ const data = out.data;
620
+ const candidates = [];
621
+ for (let a = 0; a < anchors; a++) {
622
+ const cx = data[a];
623
+ const cy = data[anchors + a];
624
+ const w = data[2 * anchors + a];
625
+ const h = data[3 * anchors + a];
626
+ let bestCls = 0;
627
+ let bestScore = 0;
628
+ for (let c = 0; c < MFD_NUM_CLASSES; c++) {
629
+ const s = data[(4 + c) * anchors + a];
630
+ if (s > bestScore) {
631
+ bestScore = s;
632
+ bestCls = c;
633
+ }
634
+ }
635
+ const threshold = bestCls === 1 ? MFD_CONF_DISPLAY_GROW : MFD_CONF_INLINE;
636
+ if (bestScore < threshold) continue;
637
+ let x1 = (cx - w / 2 - padX) / scale;
638
+ let y1 = (cy - h / 2 - padY) / scale;
639
+ let x2 = (cx + w / 2 - padX) / scale;
640
+ let y2 = (cy + h / 2 - padY) / scale;
641
+ x1 = clamp(x1, 0, frame.width - 1);
642
+ y1 = clamp(y1, 0, frame.height - 1);
643
+ x2 = clamp(x2, 0, frame.width - 1);
644
+ y2 = clamp(y2, 0, frame.height - 1);
645
+ if (x2 - x1 < 2 || y2 - y1 < 2) continue;
646
+ if ((x2 - x1) * (y2 - y1) < MFD_MIN_AREA) continue;
647
+ candidates.push({
648
+ x1,
649
+ y1,
650
+ x2,
651
+ y2,
652
+ kind: bestCls === 1 ? "display" : "inline",
653
+ score: bestScore
654
+ });
655
+ }
656
+ const kept = [];
657
+ for (const kind of ["inline", "display"]) {
658
+ const subset = candidates.filter((c) => c.kind === kind && (kind === "inline" || c.score >= MFD_CONF_DISPLAY));
659
+ kept.push(...nms(subset, MFD_IOU_THRESHOLD));
660
+ }
661
+ const grown = growDisplays(kept, candidates);
662
+ grown.sort((a, b) => a.y1 - b.y1 || a.x1 - b.x1);
663
+ return grown.map((d) => ({
664
+ bbox: { x1: d.x1, y1: d.y1, x2: d.x2, y2: d.y2 },
665
+ kind: d.kind,
666
+ score: d.score
667
+ }));
668
+ }
669
+ function growDisplays(kept, candidates) {
670
+ const low = nms(candidates.filter((c) => c.kind === "display" && c.score < MFD_CONF_DISPLAY), MFD_IOU_THRESHOLD);
671
+ const area = (a) => (a.x2 - a.x1) * (a.y2 - a.y1);
672
+ for (const d of kept) {
673
+ if (d.kind !== "display") continue;
674
+ const h = d.y2 - d.y1;
675
+ let best = null;
676
+ for (const c of low) {
677
+ const ch = c.y2 - c.y1;
678
+ if (ch < h * 1.5 || ch > h * 5) continue;
679
+ const iw = Math.min(d.x2, c.x2) - Math.max(d.x1, c.x1), ih = Math.min(d.y2, c.y2) - Math.max(d.y1, c.y1);
680
+ if (iw <= 0 || ih <= 0 || iw * ih < (d.x2 - d.x1) * h * 0.85) continue;
681
+ if (!best || c.score > best.score) best = c;
682
+ }
683
+ if (!best) continue;
684
+ const b = best;
685
+ const clash = kept.some((o) => {
686
+ if (o === d || o.kind !== "display") return false;
687
+ const iw = Math.min(o.x2, b.x2) - Math.max(o.x1, b.x1), ih = Math.min(o.y2, b.y2) - Math.max(o.y1, b.y1);
688
+ return iw > 0 && ih > 0 && iw * ih > Math.min(area(o), area(b)) * 0.2;
689
+ });
690
+ if (!clash) Object.assign(d, { x1: b.x1, y1: b.y1, x2: b.x2, y2: b.y2 });
691
+ }
692
+ return [...kept.filter((d) => d.kind === "inline"), ...nms(kept.filter((d) => d.kind === "display"), MFD_IOU_THRESHOLD)];
693
+ }
694
+ function letterbox(frame, target) {
695
+ const w = frame.width;
696
+ const h = frame.height;
697
+ const scale = Math.min(target / w, target / h);
698
+ const newW = Math.max(1, Math.round(w * scale));
699
+ const newH = Math.max(1, Math.round(h * scale));
700
+ const padX = (target - newW) / 2;
701
+ const padY = (target - newH) / 2;
702
+ const offX = Math.floor(padX);
703
+ const offY = Math.floor(padY);
704
+ const ts = target;
705
+ const tensor = new Float32Array(3 * ts * ts);
706
+ tensor.fill(PAD_VALUE);
707
+ const src = frame.data;
708
+ const srcW = frame.width;
709
+ const srcH = frame.height;
710
+ for (let y = 0; y < newH; y++) {
711
+ const sy = Math.min(srcH - 1, Math.floor((y + 0.5) / newH * srcH));
712
+ for (let x = 0; x < newW; x++) {
713
+ const sx = Math.min(srcW - 1, Math.floor((x + 0.5) / newW * srcW));
714
+ const srcIdx = (sy * srcW + sx) * 4;
715
+ const r = src[srcIdx];
716
+ const g = src[srcIdx + 1];
717
+ const b = src[srcIdx + 2];
718
+ const tx = x + offX;
719
+ const ty = y + offY;
720
+ const idx = ty * ts + tx;
721
+ tensor[idx] = r / 255;
722
+ tensor[ts * ts + idx] = g / 255;
723
+ tensor[2 * ts * ts + idx] = b / 255;
724
+ }
725
+ }
726
+ return { scale, padX, padY, tensor };
727
+ }
728
+ function nms(cands, iouThreshold) {
729
+ const sorted = [...cands].sort((a, b) => b.score - a.score);
730
+ const kept = [];
731
+ for (const cand of sorted) {
732
+ let keep = true;
733
+ for (const k of kept) {
734
+ if (iou(cand, k) > iouThreshold) {
735
+ keep = false;
736
+ break;
737
+ }
738
+ }
739
+ if (keep) kept.push(cand);
740
+ }
741
+ return kept;
742
+ }
743
+ function iou(a, b) {
744
+ const x1 = Math.max(a.x1, b.x1);
745
+ const y1 = Math.max(a.y1, b.y1);
746
+ const x2 = Math.min(a.x2, b.x2);
747
+ const y2 = Math.min(a.y2, b.y2);
748
+ const interW = Math.max(0, x2 - x1);
749
+ const interH = Math.max(0, y2 - y1);
750
+ const inter = interW * interH;
751
+ const areaA = Math.max(0, a.x2 - a.x1) * Math.max(0, a.y2 - a.y1);
752
+ const areaB = Math.max(0, b.x2 - b.x1) * Math.max(0, b.y2 - b.y1);
753
+ const union = areaA + areaB - inter;
754
+ return union <= 0 ? 0 : inter / union;
755
+ }
756
+ function clamp(v, lo, hi) {
757
+ if (v < lo) return lo;
758
+ if (v > hi) return hi;
759
+ return v;
760
+ }
761
+ var MFR_IMG_SIZE = 384;
762
+ var MFR_ENC_HIDDEN = 384;
763
+ var MFR_MAX_NEW_TOKENS = 512;
764
+ var MFR_LOOP_CHECK_FROM = 256;
765
+ var MFR_EOS_ID = 2;
766
+ var MFR_PAD_ID = 0;
767
+ async function recognizeFormula(deps, crop) {
768
+ const tensor = deitPreprocess(crop, MFR_IMG_SIZE);
769
+ const { ort, encoder, decoder, tokenizer } = deps;
770
+ const pixelInput = new ort.Tensor("float32", tensor, [1, 3, MFR_IMG_SIZE, MFR_IMG_SIZE]);
771
+ const encOut = await encoder.run({ pixel_values: pixelInput });
772
+ const encKey = Object.keys(encOut).find((k) => k.includes("hidden")) ?? Object.keys(encOut)[0];
773
+ const encTensor = encOut[encKey];
774
+ if (!encTensor || encTensor.type !== "float32") {
775
+ throw new Error("MFR encoder \uCD9C\uB825 \uC5C6\uC74C");
776
+ }
777
+ const encDims = encTensor.dims;
778
+ if (encDims.length !== 3) {
779
+ throw new Error(`MFR encoder \uCC28\uC6D0 \uC608\uC0C1 3, \uC2E4\uC81C ${encDims.length}`);
780
+ }
781
+ const encSeq = encDims[1];
782
+ const encHidden = encDims[2];
783
+ if (encHidden !== MFR_ENC_HIDDEN) {
784
+ throw new Error(`MFR encoder hidden \uC608\uC0C1 ${MFR_ENC_HIDDEN}, \uC2E4\uC81C ${encHidden}`);
785
+ }
786
+ const encData = encTensor.data;
787
+ const tokens = [MFR_EOS_ID];
788
+ for (let step = 0; step < MFR_MAX_NEW_TOKENS; step++) {
789
+ const seqLen = tokens.length;
790
+ const idsArr = BigInt64Array.from(tokens.map((t) => BigInt(t)));
791
+ const idsTensor = new ort.Tensor("int64", idsArr, [1, seqLen]);
792
+ const hidCopy = new Float32Array(encData);
793
+ const hidTensor = new ort.Tensor("float32", hidCopy, [1, encSeq, encHidden]);
794
+ const decOut = await decoder.run({
795
+ input_ids: idsTensor,
796
+ encoder_hidden_states: hidTensor
797
+ });
798
+ const logitKey = Object.keys(decOut).find((k) => k.includes("logit")) ?? Object.keys(decOut)[0];
799
+ const logitsTensor = decOut[logitKey];
800
+ if (!logitsTensor || logitsTensor.type !== "float32") {
801
+ throw new Error("MFR decoder logits \uC5C6\uC74C");
802
+ }
803
+ const dims = logitsTensor.dims;
804
+ if (dims.length !== 3) {
805
+ throw new Error(`MFR decoder \uCC28\uC6D0 \uC608\uC0C1 3, \uC2E4\uC81C ${dims.length}`);
806
+ }
807
+ const decSeq = dims[1];
808
+ const vocab = dims[2];
809
+ const logitsData = logitsTensor.data;
810
+ const lastOffset = (decSeq - 1) * vocab;
811
+ let bestId = 0;
812
+ let bestVal = -Infinity;
813
+ for (let v = 0; v < vocab; v++) {
814
+ const val = logitsData[lastOffset + v];
815
+ if (val > bestVal) {
816
+ bestVal = val;
817
+ bestId = v;
818
+ }
819
+ }
820
+ tokens.push(bestId);
821
+ if (bestId === MFR_EOS_ID) break;
822
+ const loop = step >= MFR_LOOP_CHECK_FROM ? repeatingTail(tokens) : 0;
823
+ if (loop > 0) {
824
+ while (tokens.length > 1 + loop && tokens.slice(-loop).every((t, i) => t === tokens[tokens.length - 2 * loop + i])) tokens.length -= loop;
825
+ tokens.length -= loop;
826
+ break;
827
+ }
828
+ }
829
+ const body = [];
830
+ for (let i = 1; i < tokens.length; i++) {
831
+ const t = tokens[i];
832
+ if (t === MFR_EOS_ID) break;
833
+ if (t === MFR_PAD_ID) continue;
834
+ if (t < 0) continue;
835
+ body.push(t);
836
+ }
837
+ const raw = tokenizer.decode(body, { skip_special_tokens: true, clean_up_tokenization_spaces: null });
838
+ return postProcessLatex(raw);
839
+ }
840
+ function deitPreprocess(crop, target) {
841
+ const ts = target;
842
+ const out = new Float32Array(3 * ts * ts);
843
+ const { data: src, width: srcW, height: srcH } = crop;
844
+ for (let y = 0; y < ts; y++) {
845
+ const sy = Math.min(srcH - 1, Math.max(0, Math.floor((y + 0.5) / ts * srcH)));
846
+ for (let x = 0; x < ts; x++) {
847
+ const sx = Math.min(srcW - 1, Math.max(0, Math.floor((x + 0.5) / ts * srcW)));
848
+ const srcIdx = (sy * srcW + sx) * 4;
849
+ const r = src[srcIdx];
850
+ const g = src[srcIdx + 1];
851
+ const b = src[srcIdx + 2];
852
+ const idx = y * ts + x;
853
+ out[idx] = r / 127.5 - 1;
854
+ out[ts * ts + idx] = g / 127.5 - 1;
855
+ out[2 * ts * ts + idx] = b / 127.5 - 1;
856
+ }
857
+ }
858
+ return out;
859
+ }
860
+ function repeatingTail(tokens) {
861
+ for (let p = 1; p <= 40; p++) {
862
+ if (p * 4 > tokens.length || p * 4 < 24) continue;
863
+ let ok = true;
864
+ for (let i = 1; i <= p * 3 && ok; i++) ok = tokens[tokens.length - i] === tokens[tokens.length - i - p];
865
+ if (ok) return p;
866
+ }
867
+ return 0;
868
+ }
869
+ var RENDER_SCALE = 2;
870
+ function capFormulaRegions(regions, max) {
871
+ if (regions.length <= max) return regions;
872
+ const kept = new Set([...regions.filter((r) => r.kind === "display"), ...regions.filter((r) => r.kind !== "display")].slice(0, max));
873
+ return regions.filter((r) => kept.has(r));
874
+ }
875
+ var FormulaPipeline = class _FormulaPipeline {
876
+ mfd;
877
+ encoder;
878
+ decoder;
879
+ tokenizer;
880
+ ort;
881
+ sharp;
882
+ pdfium;
883
+ opts;
884
+ constructor(parts) {
885
+ this.mfd = parts.mfd;
886
+ this.encoder = parts.encoder;
887
+ this.decoder = parts.decoder;
888
+ this.tokenizer = parts.tokenizer;
889
+ this.ort = parts.ort;
890
+ this.sharp = parts.sharp;
891
+ this.pdfium = parts.pdfium;
892
+ this.opts = parts.opts;
893
+ }
894
+ /**
895
+ * 수식 OCR 엔진 초기화. 모델 파일이 로컬에 없으면 즉시 실패 — 호출자가
896
+ * `ensureFormulaModels()` 를 먼저 돌려야 한다.
897
+ */
898
+ static async create(options) {
899
+ disableOrtTelemetry();
900
+ const opts = {
901
+ scale: options?.scale ?? RENDER_SCALE,
902
+ maxRegionsPerPage: options?.maxRegionsPerPage ?? 50,
903
+ pageTimeoutMs: options?.pageTimeoutMs ?? 6e4
904
+ };
905
+ const [ortMod, sharpModRaw, hfMod, pdfiumMod] = await Promise.all([
906
+ tryImport(
907
+ "onnxruntime-node",
908
+ () => import("onnxruntime-node")
909
+ ),
910
+ tryImport(
911
+ "sharp",
912
+ () => import("sharp")
913
+ ),
914
+ tryImport(
915
+ "@huggingface/tokenizers",
916
+ () => import("@huggingface/tokenizers")
917
+ ),
918
+ tryImport(
919
+ "@hyzyla/pdfium",
920
+ () => import("@hyzyla/pdfium")
921
+ )
922
+ ]);
923
+ const sharpAny = sharpModRaw;
924
+ const sharpMod = typeof sharpAny === "function" ? sharpAny : sharpAny.default ?? sharpAny;
925
+ const modelsDir = getFormulaModelsDir();
926
+ const mfdPath = join(modelsDir, MFD_MODEL.filename);
927
+ const encPath = join(modelsDir, MFR_ENCODER_MODEL.filename);
928
+ const decPath = join(modelsDir, MFR_DECODER_MODEL.filename);
929
+ const tokPath = join(modelsDir, MFR_TOKENIZER.filename);
930
+ const sessionOpts = {
931
+ graphOptimizationLevel: "all"
932
+ };
933
+ const [mfd, encoder, decoder] = await Promise.all([
934
+ createOrtSession((o) => ortMod.InferenceSession.create(mfdPath, o), sessionOpts),
935
+ createOrtSession((o) => ortMod.InferenceSession.create(encPath, o), sessionOpts),
936
+ createOrtSession((o) => ortMod.InferenceSession.create(decPath, o), sessionOpts)
937
+ ]);
938
+ const { readFile } = await import("fs/promises");
939
+ const tokenizerJson = JSON.parse(await readFile(tokPath, "utf-8"));
940
+ const tokenizer = new hfMod.Tokenizer(tokenizerJson, {});
941
+ const pdfium = await pdfiumMod.PDFiumLibrary.init();
942
+ return new _FormulaPipeline({
943
+ mfd,
944
+ encoder,
945
+ decoder,
946
+ tokenizer,
947
+ ort: ortMod,
948
+ sharp: sharpMod,
949
+ pdfium,
950
+ opts
951
+ });
952
+ }
953
+ /** 리소스 해제 — 더 이상 사용하지 않을 때 호출. ONNX 세션은 onnxruntime-node 1.14+ release() 로 (구버전은 GC — ocr/engine.ts destroy 와 같은 방식) */
954
+ async destroy() {
955
+ for (const s of [this.mfd, this.encoder, this.decoder]) {
956
+ const rel = s.release;
957
+ if (typeof rel === "function") {
958
+ try {
959
+ await rel.call(s);
960
+ } catch {
961
+ }
962
+ }
963
+ }
964
+ try {
965
+ this.pdfium.destroy();
966
+ } catch {
967
+ }
968
+ }
969
+ /**
970
+ * PDF 버퍼를 열어 페이지별 수식 영역을 인식한다.
971
+ * 실패한 페이지는 skip (에러 전파 없음 — 로그만).
972
+ *
973
+ * @param pageFilter null 이면 전체 페이지. Set 이면 1-based 페이지 번호 일치만.
974
+ */
975
+ async runOnBuffer(buffer, pageFilter = null, onPageProgress) {
976
+ const view = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
977
+ const doc = await this.pdfium.loadDocument(view);
978
+ try {
979
+ const pages = [];
980
+ const count = doc.getPageCount();
981
+ const pageNos = pageFilter ? [...pageFilter].filter((p) => p >= 1 && p <= count).sort((a, b) => a - b) : Array.from({ length: count }, (_, i) => i + 1);
982
+ for (const pageNo of pageNos) {
983
+ const page = doc.getPage(pageNo - 1);
984
+ onPageProgress?.(pageNo, count);
985
+ try {
986
+ const result = await withTimeout(
987
+ this.processPage(pageNo, page),
988
+ this.opts.pageTimeoutMs,
989
+ `formula page ${pageNo} timed out after ${this.opts.pageTimeoutMs}ms`
990
+ );
991
+ if (result) pages.push(result);
992
+ } catch (e) {
993
+ process.stderr.write(
994
+ `[kordoc-formula] page ${pageNo} skipped: ${e.message}
995
+ `
996
+ );
997
+ }
998
+ }
999
+ return pages;
1000
+ } finally {
1001
+ doc.destroy();
1002
+ }
1003
+ }
1004
+ async processPage(pageNumber, page) {
1005
+ const { originalWidth: pdfWidth, originalHeight: pdfHeight } = page.getOriginalSize();
1006
+ const rendered = await page.render({
1007
+ scale: this.opts.scale,
1008
+ render: async ({ data, width, height }) => {
1009
+ return data;
1010
+ }
1011
+ });
1012
+ const { data: bgra, width: rw, height: rh } = rendered;
1013
+ const rgba = bgraToRgba(bgra);
1014
+ const regions = await this.recognizeFrame({ width: rw, height: rh, data: rgba }, pageNumber);
1015
+ return {
1016
+ pageNumber,
1017
+ renderedWidth: rw,
1018
+ renderedHeight: rh,
1019
+ pdfWidth,
1020
+ pdfHeight,
1021
+ regions
1022
+ };
1023
+ }
1024
+ /** 래스터 한 장(RGBA)의 수식 영역을 검출·인식한다 — PDF 쪽 렌더와 이미지 OCR 이 같이 쓴다. 좌표는 입력 픽셀 */
1025
+ async recognizeFrame(pageFrame, pageNumber = 1) {
1026
+ const { width: rw, height: rh, data: rgba } = pageFrame;
1027
+ const sharpCtor = this.sharp;
1028
+ const regions0 = await detectFormulaRegions(this.mfd, pageFrame, this.ort);
1029
+ if (regions0.length === 0) return [];
1030
+ const capped = capFormulaRegions(regions0, this.opts.maxRegionsPerPage);
1031
+ const regions = [];
1032
+ for (const r of capped) {
1033
+ const x1 = Math.floor(Math.max(0, r.bbox.x1));
1034
+ const y1 = Math.floor(Math.max(0, r.bbox.y1));
1035
+ const x2 = Math.ceil(Math.min(rw, r.bbox.x2));
1036
+ const y2 = Math.ceil(Math.min(rh, r.bbox.y2));
1037
+ const cw = x2 - x1;
1038
+ const ch = y2 - y1;
1039
+ if (cw < 4 || ch < 4) continue;
1040
+ const cropRgba = await sharpCtor(rgba, {
1041
+ raw: { width: rw, height: rh, channels: 4 }
1042
+ }).extract({ left: x1, top: y1, width: cw, height: ch }).raw().toBuffer();
1043
+ const cropFrame = { width: cw, height: ch, data: new Uint8Array(cropRgba) };
1044
+ let latex = "";
1045
+ try {
1046
+ const deps = { encoder: this.encoder, decoder: this.decoder, tokenizer: this.tokenizer, ort: this.ort };
1047
+ const bands = r.kind === "display" ? lineBands(cropFrame, this.opts.scale) : [];
1048
+ if (bands.length >= MIN_SPLIT_LINES) {
1049
+ const lines = [];
1050
+ for (const [b0, b1] of bands) {
1051
+ const band = { width: cw, height: b1 - b0, data: cropFrame.data.slice(b0 * cw * 4, b1 * cw * 4) };
1052
+ const l = (await recognizeFormula(deps, band)).trim();
1053
+ if (l) lines.push(l);
1054
+ }
1055
+ latex = lines.length > 1 ? `\\begin{aligned}${lines.join(" \\\\ ")}\\end{aligned}` : lines.join("");
1056
+ } else latex = await recognizeFormula(deps, cropFrame);
1057
+ } catch (e) {
1058
+ process.stderr.write(
1059
+ `[kordoc-formula] recognize failed at page ${pageNumber} ${JSON.stringify(r.bbox)}: ${e.message}
1060
+ `
1061
+ );
1062
+ latex = "";
1063
+ }
1064
+ regions.push({ ...r, latex });
1065
+ }
1066
+ return mergeContinuationLines(dropNestedDisplays(regions));
1067
+ }
1068
+ };
1069
+ async function tryImport(name, loader) {
1070
+ try {
1071
+ return await loader();
1072
+ } catch (e) {
1073
+ throw new Error(
1074
+ `\uC218\uC2DD 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. \uC6D0\uC778: ${e.message}`
1075
+ );
1076
+ }
1077
+ }
1078
+ async function withTimeout(promise, ms, msg) {
1079
+ promise.catch(() => {
1080
+ });
1081
+ let timer;
1082
+ try {
1083
+ return await Promise.race([
1084
+ promise,
1085
+ new Promise((_, reject) => {
1086
+ timer = setTimeout(() => reject(new Error(msg)), ms);
1087
+ })
1088
+ ]);
1089
+ } finally {
1090
+ if (timer) clearTimeout(timer);
1091
+ }
1092
+ }
1093
+ function bgraToRgba(bgra) {
1094
+ const out = new Uint8Array(bgra.length);
1095
+ for (let i = 0; i < bgra.length; i += 4) {
1096
+ out[i] = bgra[i + 2];
1097
+ out[i + 1] = bgra[i + 1];
1098
+ out[i + 2] = bgra[i];
1099
+ out[i + 3] = bgra[i + 3];
1100
+ }
1101
+ return out;
1102
+ }
1103
+ var MIN_SPLIT_LINES = 5;
1104
+ function lineBands(f, pxPerPt) {
1105
+ const { width: w, height: h, data } = f;
1106
+ const ink = new Uint8Array(w * h);
1107
+ for (let i = 0; i < w * h; i++) ink[i] = Math.min(data[i * 4], data[i * 4 + 1], data[i * 4 + 2]) < 160 ? 1 : 0;
1108
+ const tall = 22.5 * pxPerPt;
1109
+ for (let x = 0; x < w; x++) for (let y = 0; y < h; ) {
1110
+ if (!ink[y * w + x]) {
1111
+ y++;
1112
+ continue;
1113
+ }
1114
+ let e = y;
1115
+ while (e < h && ink[e * w + x]) e++;
1116
+ if (e - y >= tall) for (let k = y; k < e; k++) ink[k * w + x] = 2;
1117
+ y = e;
1118
+ }
1119
+ const filled = (y) => {
1120
+ let n = 0;
1121
+ for (let x = 0; x < w && n < 2; x++) if (ink[y * w + x] === 1) n++;
1122
+ return n >= 2;
1123
+ };
1124
+ const runs = [];
1125
+ for (let y = 0; y < h; ) {
1126
+ if (!filled(y)) {
1127
+ y++;
1128
+ continue;
1129
+ }
1130
+ let e = y;
1131
+ while (e < h && filled(e)) e++;
1132
+ runs.push([y, e]);
1133
+ y = e;
1134
+ }
1135
+ if (runs.length < 2) return [];
1136
+ const hs = runs.map((r) => r[1] - r[0]).sort((a, b) => a - b);
1137
+ const med = hs[hs.length >> 1];
1138
+ const bands = [[runs[0][0], runs[0][1]]];
1139
+ for (const r of runs.slice(1)) {
1140
+ const last = bands[bands.length - 1];
1141
+ if (r[0] - last[1] < Math.max(3, med * 0.15)) last[1] = r[1];
1142
+ else bands.push([r[0], r[1]]);
1143
+ }
1144
+ const tallest = () => Math.max(...bands.map((b) => b[1] - b[0]));
1145
+ for (let i = 0; i < bands.length && bands.length > 1; i++) {
1146
+ const b = bands[i];
1147
+ if (b[1] - b[0] >= tallest() * 0.5) continue;
1148
+ const up = i > 0 ? b[0] - bands[i - 1][1] : Infinity, dn = i < bands.length - 1 ? bands[i + 1][0] - b[1] : Infinity;
1149
+ if (up <= dn) bands[i - 1][1] = b[1];
1150
+ else bands[i + 1][0] = b[0];
1151
+ bands.splice(i--, 1);
1152
+ }
1153
+ const maxGap = Math.max(0, ...bands.slice(1).map((b, i) => b[0] - bands[i][1]));
1154
+ for (let i = 1; i < bands.length; i++) {
1155
+ if (bands[i][0] - bands[i - 1][1] >= maxGap * 0.6) continue;
1156
+ bands[i - 1][1] = bands[i][1];
1157
+ bands.splice(i--, 1);
1158
+ }
1159
+ return bands.map(([a, b]) => [Math.max(0, a - 2), Math.min(h, b + 2)]);
1160
+ }
1161
+ export {
1162
+ ALL_FORMULA_MODELS,
1163
+ FormulaPipeline,
1164
+ MFD_MODEL,
1165
+ MFR_DECODER_MODEL,
1166
+ MFR_ENCODER_MODEL,
1167
+ MFR_TOKENIZER,
1168
+ ensureFormulaModels,
1169
+ ensureSingleModel,
1170
+ getFormulaModelStatus,
1171
+ getFormulaModelsDir,
1172
+ postProcessLatex
1173
+ };