@heripo/pdf-parser 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,19 +30,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- DEFAULT_VLM_MODEL: () => DEFAULT_VLM_MODEL,
34
33
  ImagePdfFallbackError: () => ImagePdfFallbackError,
35
34
  PDFParser: () => PDFParser,
36
- VLM_MODELS: () => VLM_MODELS,
37
- resolveVlmModel: () => resolveVlmModel
35
+ VlmResponseValidator: () => VlmResponseValidator
38
36
  });
39
37
  module.exports = __toCommonJS(src_exports);
40
38
 
41
39
  // src/core/pdf-parser.ts
42
- var import_docling_sdk2 = require("docling-sdk");
40
+ var import_docling_sdk = require("docling-sdk");
43
41
  var import_node_child_process3 = require("child_process");
44
- var import_node_os3 = require("os");
45
- var import_node_path6 = require("path");
42
+ var import_node_os2 = require("os");
43
+ var import_node_path8 = require("path");
46
44
 
47
45
  // src/config/constants.ts
48
46
  var PDF_PARSER = {
@@ -93,22 +91,42 @@ var IMAGE_PDF_CONVERTER = {
93
91
  */
94
92
  QUALITY: 100
95
93
  };
96
- var VLM_ENVIRONMENT = {
97
- /**
98
- * Timeout for VLM dependency installation (pip install) in milliseconds (3 hours).
99
- * VLM packages can be very large and may require extended download times
100
- * depending on network conditions.
101
- */
102
- SETUP_TIMEOUT_MS: 108e5,
103
- /**
104
- * Timeout for VLM model download in milliseconds (3 hours).
105
- * Large VLM models (e.g., multi-GB weights) need sufficient time to download.
106
- */
107
- MODEL_DOWNLOAD_TIMEOUT_MS: 108e5
108
- };
109
94
 
110
95
  // ../shared/dist/index.mjs
111
96
  var import_child_process = require("child_process");
97
+ var import_ai = require("ai");
98
+ var ConcurrentPool = class {
99
+ /**
100
+ * Process items concurrently using a worker pool pattern.
101
+ *
102
+ * Spawns up to `concurrency` workers that pull items from a shared queue.
103
+ * Each worker processes one item at a time; when it finishes, it immediately
104
+ * takes the next available item. Results maintain the original item order.
105
+ *
106
+ * @param items - Array of items to process
107
+ * @param concurrency - Maximum number of concurrent workers
108
+ * @param processFn - Async function to process each item
109
+ * @param onItemComplete - Optional callback fired after each item completes
110
+ * @returns Array of results in the same order as the input items
111
+ */
112
+ static async run(items, concurrency, processFn, onItemComplete) {
113
+ const results = new Array(items.length);
114
+ let nextIndex = 0;
115
+ async function worker() {
116
+ while (nextIndex < items.length) {
117
+ const index = nextIndex++;
118
+ results[index] = await processFn(items[index], index);
119
+ onItemComplete?.(results[index], index);
120
+ }
121
+ }
122
+ const workers = Array.from(
123
+ { length: Math.min(concurrency, items.length) },
124
+ () => worker()
125
+ );
126
+ await Promise.all(workers);
127
+ return results;
128
+ }
129
+ };
112
130
  function spawnAsync(command, args, options = {}) {
113
131
  const {
114
132
  captureStdout = true,
@@ -135,10 +153,456 @@ function spawnAsync(command, args, options = {}) {
135
153
  proc.on("error", reject);
136
154
  });
137
155
  }
156
+ function detectProvider(model) {
157
+ const providerId = model.provider;
158
+ if (!providerId || typeof providerId !== "string") return "unknown";
159
+ if (providerId.includes("openai")) return "openai";
160
+ if (providerId.includes("google")) return "google";
161
+ if (providerId.includes("anthropic")) return "anthropic";
162
+ if (providerId.includes("together")) return "togetherai";
163
+ return "unknown";
164
+ }
165
+ var LLMCaller = class {
166
+ /**
167
+ * Extract model name from LanguageModel object
168
+ *
169
+ * Attempts to get model ID from various possible fields in the LanguageModel object.
170
+ */
171
+ static extractModelName(model) {
172
+ const modelObj = model;
173
+ if (typeof modelObj.modelId === "string") return modelObj.modelId;
174
+ if (typeof modelObj.id === "string") return modelObj.id;
175
+ if (typeof modelObj.model === "string") return modelObj.model;
176
+ if (typeof modelObj.name === "string") return modelObj.name;
177
+ return String(model);
178
+ }
179
+ /**
180
+ * Build usage information from response
181
+ */
182
+ static buildUsage(config, modelName, response, usedFallback) {
183
+ return {
184
+ component: config.component,
185
+ phase: config.phase,
186
+ model: usedFallback ? "fallback" : "primary",
187
+ modelName,
188
+ inputTokens: response.usage?.inputTokens ?? 0,
189
+ outputTokens: response.usage?.outputTokens ?? 0,
190
+ totalTokens: response.usage?.totalTokens ?? 0
191
+ };
192
+ }
193
+ /**
194
+ * Maximum number of retries when structured output generation fails.
195
+ * Total attempts = MAX_STRUCTURED_OUTPUT_RETRIES + 1.
196
+ *
197
+ * Applied to both:
198
+ * - `Output.object()` path: retries on NoObjectGeneratedError (schema mismatch)
199
+ * - Tool call path: retries when model does not produce a tool call
200
+ */
201
+ static MAX_STRUCTURED_OUTPUT_RETRIES = 10;
202
+ /**
203
+ * Generate structured output via forced tool call.
204
+ *
205
+ * Used for providers (Together AI, unknown) that do not reliably support
206
+ * `Output.object()`. Forces the model to call a tool whose inputSchema
207
+ * is the target Zod schema, then extracts the parsed input.
208
+ *
209
+ * Retries up to MAX_STRUCTURED_OUTPUT_RETRIES times when the model does not
210
+ * produce a tool call, for a total of MAX_STRUCTURED_OUTPUT_RETRIES + 1 attempts.
211
+ *
212
+ * @throws NoObjectGeneratedError when all attempts fail to produce a tool call
213
+ */
214
+ static async generateViaToolCall(model, schema, promptParams) {
215
+ const submitTool = (0, import_ai.tool)({
216
+ description: "Submit the structured result",
217
+ inputSchema: schema
218
+ });
219
+ let lastResult;
220
+ for (let attempt = 0; attempt <= this.MAX_STRUCTURED_OUTPUT_RETRIES; attempt++) {
221
+ lastResult = await (0, import_ai.generateText)({
222
+ ...promptParams,
223
+ model,
224
+ tools: { submitResult: submitTool },
225
+ toolChoice: { type: "tool", toolName: "submitResult" },
226
+ stopWhen: (0, import_ai.hasToolCall)("submitResult")
227
+ });
228
+ const toolCall = lastResult.toolCalls?.[0];
229
+ if (toolCall) {
230
+ return {
231
+ output: toolCall.input,
232
+ usage: lastResult.usage
233
+ };
234
+ }
235
+ }
236
+ throw new import_ai.NoObjectGeneratedError({
237
+ message: "Model did not produce a tool call for structured output",
238
+ text: lastResult.text ?? "",
239
+ response: lastResult.response,
240
+ usage: lastResult.usage,
241
+ finishReason: lastResult.finishReason
242
+ });
243
+ }
244
+ /**
245
+ * Generate structured output with provider-aware strategy.
246
+ *
247
+ * Strategy per provider:
248
+ * - OpenAI / Anthropic / Google Gemini: `Output.object()` with schema retry
249
+ * - Together AI / unknown: forced tool call pattern
250
+ *
251
+ * Retries up to MAX_STRUCTURED_OUTPUT_RETRIES times on NoObjectGeneratedError
252
+ * (schema mismatch), re-throwing the last error if all attempts fail.
253
+ */
254
+ static async generateStructuredOutput(model, schema, promptParams) {
255
+ const providerType = detectProvider(model);
256
+ if (providerType === "togetherai" || providerType === "unknown") {
257
+ return this.generateViaToolCall(model, schema, promptParams);
258
+ }
259
+ let lastError;
260
+ for (let attempt = 0; attempt <= this.MAX_STRUCTURED_OUTPUT_RETRIES; attempt++) {
261
+ try {
262
+ return await (0, import_ai.generateText)({
263
+ model,
264
+ output: import_ai.Output.object({ schema }),
265
+ ...promptParams
266
+ });
267
+ } catch (error) {
268
+ if (import_ai.NoObjectGeneratedError.isInstance(error)) {
269
+ lastError = error;
270
+ continue;
271
+ }
272
+ throw error;
273
+ }
274
+ }
275
+ throw lastError;
276
+ }
277
+ /**
278
+ * Execute LLM call with fallback support
279
+ *
280
+ * Common execution logic for both text and vision calls.
281
+ * Logs additional details when NoObjectGeneratedError occurs.
282
+ */
283
+ static async executeWithFallback(config, generateFn) {
284
+ const primaryModelName = this.extractModelName(config.primaryModel);
285
+ try {
286
+ const response = await generateFn(config.primaryModel);
287
+ return {
288
+ output: response.output,
289
+ usage: this.buildUsage(config, primaryModelName, response, false),
290
+ usedFallback: false
291
+ };
292
+ } catch (primaryError) {
293
+ if (config.abortSignal?.aborted) {
294
+ throw primaryError;
295
+ }
296
+ if (!config.fallbackModel) {
297
+ throw primaryError;
298
+ }
299
+ const fallbackModelName = this.extractModelName(config.fallbackModel);
300
+ const response = await generateFn(config.fallbackModel);
301
+ return {
302
+ output: response.output,
303
+ usage: this.buildUsage(config, fallbackModelName, response, true),
304
+ usedFallback: true
305
+ };
306
+ }
307
+ }
308
+ /**
309
+ * Call LLM with retry and fallback support
310
+ *
311
+ * Retry Strategy:
312
+ * 1. Try primary model up to maxRetries times
313
+ * 2. If all fail and fallbackModel provided, try fallback up to maxRetries times
314
+ * 3. Throw error if all attempts exhausted
315
+ *
316
+ * Provider-aware strategy is automatically applied based on the model's provider field.
317
+ *
318
+ * @template TOutput - Output type from schema validation
319
+ * @param config - LLM call configuration
320
+ * @returns Result with parsed object and usage information
321
+ * @throws Error if all retry attempts fail
322
+ */
323
+ static async call(config) {
324
+ return this.executeWithFallback(
325
+ config,
326
+ (model) => this.generateStructuredOutput(model, config.schema, {
327
+ system: config.systemPrompt,
328
+ prompt: config.userPrompt,
329
+ temperature: config.temperature,
330
+ maxRetries: config.maxRetries,
331
+ abortSignal: config.abortSignal
332
+ })
333
+ );
334
+ }
335
+ /**
336
+ * Call LLM for vision tasks with message format support
337
+ *
338
+ * Same retry and fallback logic as call(), but using message format instead of system/user prompts.
339
+ * Provider-aware strategy is automatically applied based on the model's provider field.
340
+ *
341
+ * @template TOutput - Output type from schema validation
342
+ * @param config - LLM vision call configuration
343
+ * @returns Result with parsed object and usage information
344
+ * @throws Error if all retry attempts fail
345
+ */
346
+ static async callVision(config) {
347
+ return this.executeWithFallback(
348
+ config,
349
+ (model) => this.generateStructuredOutput(model, config.schema, {
350
+ messages: config.messages,
351
+ temperature: config.temperature,
352
+ maxRetries: config.maxRetries,
353
+ abortSignal: config.abortSignal
354
+ })
355
+ );
356
+ }
357
+ };
358
+ function formatTokens(usage) {
359
+ return `${usage.inputTokens} input, ${usage.outputTokens} output, ${usage.totalTokens} total`;
360
+ }
361
+ var LLMTokenUsageAggregator = class {
362
+ usage = {};
363
+ /**
364
+ * Track token usage from an LLM call
365
+ *
366
+ * @param usage - Extended token usage with component/phase/model information
367
+ */
368
+ track(usage) {
369
+ if (!this.usage[usage.component]) {
370
+ this.usage[usage.component] = {
371
+ component: usage.component,
372
+ phases: {},
373
+ total: {
374
+ inputTokens: 0,
375
+ outputTokens: 0,
376
+ totalTokens: 0
377
+ }
378
+ };
379
+ }
380
+ const component = this.usage[usage.component];
381
+ if (!component.phases[usage.phase]) {
382
+ component.phases[usage.phase] = {
383
+ total: {
384
+ inputTokens: 0,
385
+ outputTokens: 0,
386
+ totalTokens: 0
387
+ }
388
+ };
389
+ }
390
+ const phase = component.phases[usage.phase];
391
+ if (usage.model === "primary") {
392
+ if (!phase.primary) {
393
+ phase.primary = {
394
+ modelName: usage.modelName,
395
+ inputTokens: 0,
396
+ outputTokens: 0,
397
+ totalTokens: 0
398
+ };
399
+ }
400
+ phase.primary.inputTokens += usage.inputTokens;
401
+ phase.primary.outputTokens += usage.outputTokens;
402
+ phase.primary.totalTokens += usage.totalTokens;
403
+ } else if (usage.model === "fallback") {
404
+ if (!phase.fallback) {
405
+ phase.fallback = {
406
+ modelName: usage.modelName,
407
+ inputTokens: 0,
408
+ outputTokens: 0,
409
+ totalTokens: 0
410
+ };
411
+ }
412
+ phase.fallback.inputTokens += usage.inputTokens;
413
+ phase.fallback.outputTokens += usage.outputTokens;
414
+ phase.fallback.totalTokens += usage.totalTokens;
415
+ }
416
+ phase.total.inputTokens += usage.inputTokens;
417
+ phase.total.outputTokens += usage.outputTokens;
418
+ phase.total.totalTokens += usage.totalTokens;
419
+ component.total.inputTokens += usage.inputTokens;
420
+ component.total.outputTokens += usage.outputTokens;
421
+ component.total.totalTokens += usage.totalTokens;
422
+ }
423
+ /**
424
+ * Get aggregated usage grouped by component
425
+ *
426
+ * @returns Array of component aggregates with phase breakdown
427
+ */
428
+ getByComponent() {
429
+ return Object.values(this.usage);
430
+ }
431
+ /**
432
+ * Get token usage report in structured JSON format
433
+ *
434
+ * Converts internal usage data to external TokenUsageReport format suitable
435
+ * for serialization and reporting. The report includes component breakdown,
436
+ * phase-level details, and both primary and fallback model usage.
437
+ *
438
+ * @returns Structured token usage report with components and total
439
+ */
440
+ getReport() {
441
+ const components = [];
442
+ for (const component of Object.values(this.usage)) {
443
+ const phases = [];
444
+ for (const [phaseName, phaseData] of Object.entries(component.phases)) {
445
+ const phaseReport = {
446
+ phase: phaseName,
447
+ total: {
448
+ inputTokens: phaseData.total.inputTokens,
449
+ outputTokens: phaseData.total.outputTokens,
450
+ totalTokens: phaseData.total.totalTokens
451
+ }
452
+ };
453
+ if (phaseData.primary) {
454
+ phaseReport.primary = {
455
+ modelName: phaseData.primary.modelName,
456
+ inputTokens: phaseData.primary.inputTokens,
457
+ outputTokens: phaseData.primary.outputTokens,
458
+ totalTokens: phaseData.primary.totalTokens
459
+ };
460
+ }
461
+ if (phaseData.fallback) {
462
+ phaseReport.fallback = {
463
+ modelName: phaseData.fallback.modelName,
464
+ inputTokens: phaseData.fallback.inputTokens,
465
+ outputTokens: phaseData.fallback.outputTokens,
466
+ totalTokens: phaseData.fallback.totalTokens
467
+ };
468
+ }
469
+ phases.push(phaseReport);
470
+ }
471
+ components.push({
472
+ component: component.component,
473
+ phases,
474
+ total: {
475
+ inputTokens: component.total.inputTokens,
476
+ outputTokens: component.total.outputTokens,
477
+ totalTokens: component.total.totalTokens
478
+ }
479
+ });
480
+ }
481
+ const totalUsage = this.getTotalUsage();
482
+ return {
483
+ components,
484
+ total: {
485
+ inputTokens: totalUsage.inputTokens,
486
+ outputTokens: totalUsage.outputTokens,
487
+ totalTokens: totalUsage.totalTokens
488
+ }
489
+ };
490
+ }
491
+ /**
492
+ * Get total usage across all components and phases
493
+ *
494
+ * @returns Aggregated token usage totals
495
+ */
496
+ getTotalUsage() {
497
+ let totalInput = 0;
498
+ let totalOutput = 0;
499
+ let totalTokens = 0;
500
+ for (const component of Object.values(this.usage)) {
501
+ totalInput += component.total.inputTokens;
502
+ totalOutput += component.total.outputTokens;
503
+ totalTokens += component.total.totalTokens;
504
+ }
505
+ return {
506
+ inputTokens: totalInput,
507
+ outputTokens: totalOutput,
508
+ totalTokens
509
+ };
510
+ }
511
+ /**
512
+ * Log comprehensive token usage summary
513
+ *
514
+ * Outputs usage grouped by component, with phase and model breakdown.
515
+ * Shows primary and fallback token usage separately for each phase.
516
+ * Call this once at the end of document processing.
517
+ *
518
+ * @param logger - Logger instance for output
519
+ */
520
+ logSummary(logger) {
521
+ const components = this.getByComponent();
522
+ if (components.length === 0) {
523
+ logger.info("[DocumentProcessor] No token usage to report");
524
+ return;
525
+ }
526
+ logger.info("[DocumentProcessor] Token usage summary:");
527
+ logger.info("");
528
+ let grandInputTokens = 0;
529
+ let grandOutputTokens = 0;
530
+ let grandTotalTokens = 0;
531
+ let grandPrimaryInputTokens = 0;
532
+ let grandPrimaryOutputTokens = 0;
533
+ let grandPrimaryTotalTokens = 0;
534
+ let grandFallbackInputTokens = 0;
535
+ let grandFallbackOutputTokens = 0;
536
+ let grandFallbackTotalTokens = 0;
537
+ for (const component of components) {
538
+ logger.info(`${component.component}:`);
539
+ for (const [phase, phaseData] of Object.entries(component.phases)) {
540
+ logger.info(` - ${phase}:`);
541
+ if (phaseData.primary) {
542
+ logger.info(
543
+ ` primary (${phaseData.primary.modelName}): ${formatTokens(phaseData.primary)}`
544
+ );
545
+ grandPrimaryInputTokens += phaseData.primary.inputTokens;
546
+ grandPrimaryOutputTokens += phaseData.primary.outputTokens;
547
+ grandPrimaryTotalTokens += phaseData.primary.totalTokens;
548
+ }
549
+ if (phaseData.fallback) {
550
+ logger.info(
551
+ ` fallback (${phaseData.fallback.modelName}): ${formatTokens(phaseData.fallback)}`
552
+ );
553
+ grandFallbackInputTokens += phaseData.fallback.inputTokens;
554
+ grandFallbackOutputTokens += phaseData.fallback.outputTokens;
555
+ grandFallbackTotalTokens += phaseData.fallback.totalTokens;
556
+ }
557
+ logger.info(` subtotal: ${formatTokens(phaseData.total)}`);
558
+ }
559
+ logger.info(
560
+ ` ${component.component} total: ${formatTokens(component.total)}`
561
+ );
562
+ logger.info("");
563
+ grandInputTokens += component.total.inputTokens;
564
+ grandOutputTokens += component.total.outputTokens;
565
+ grandTotalTokens += component.total.totalTokens;
566
+ }
567
+ logger.info("--- Summary ---");
568
+ if (grandPrimaryTotalTokens > 0) {
569
+ logger.info(
570
+ `Primary total: ${formatTokens({
571
+ inputTokens: grandPrimaryInputTokens,
572
+ outputTokens: grandPrimaryOutputTokens,
573
+ totalTokens: grandPrimaryTotalTokens
574
+ })}`
575
+ );
576
+ }
577
+ if (grandFallbackTotalTokens > 0) {
578
+ logger.info(
579
+ `Fallback total: ${formatTokens({
580
+ inputTokens: grandFallbackInputTokens,
581
+ outputTokens: grandFallbackOutputTokens,
582
+ totalTokens: grandFallbackTotalTokens
583
+ })}`
584
+ );
585
+ }
586
+ logger.info(
587
+ `Grand total: ${formatTokens({
588
+ inputTokens: grandInputTokens,
589
+ outputTokens: grandOutputTokens,
590
+ totalTokens: grandTotalTokens
591
+ })}`
592
+ );
593
+ }
594
+ /**
595
+ * Reset all tracked usage
596
+ *
597
+ * Call this at the start of a new document processing run.
598
+ */
599
+ reset() {
600
+ this.usage = {};
601
+ }
602
+ };
138
603
 
139
604
  // src/environment/docling-environment.ts
140
605
  var import_node_child_process = require("child_process");
141
- var import_node_os = require("os");
142
606
  var import_node_path = require("path");
143
607
 
144
608
  // src/utils/python-version.ts
@@ -180,7 +644,6 @@ var DoclingEnvironment = class _DoclingEnvironment {
180
644
  venvPath;
181
645
  port;
182
646
  killExistingProcess;
183
- vlmDependenciesInstalled = false;
184
647
  constructor(options) {
185
648
  this.logger = options.logger;
186
649
  this.venvPath = options.venvPath;
@@ -299,7 +762,11 @@ var DoclingEnvironment = class _DoclingEnvironment {
299
762
  }
300
763
  async installDoclingServe() {
301
764
  const pipPath = (0, import_node_path.join)(this.venvPath, "bin", "pip");
302
- const result = await spawnAsync(pipPath, ["install", "docling-serve"]);
765
+ const result = await spawnAsync(pipPath, [
766
+ "install",
767
+ "--upgrade",
768
+ "docling-serve"
769
+ ]);
303
770
  if (result.code !== 0) {
304
771
  this.logger.error(
305
772
  "[DoclingEnvironment] Failed to install docling-serve:",
@@ -310,81 +777,6 @@ var DoclingEnvironment = class _DoclingEnvironment {
310
777
  );
311
778
  }
312
779
  }
313
- /**
314
- * Install VLM-specific dependencies for the Docling VLM pipeline.
315
- *
316
- * Installs:
317
- * 1. docling-serve[vlm] - VLM model support for docling-serve
318
- * 2. mlx + mlx-lm (macOS ARM64 only) - Apple Silicon optimized inference
319
- *
320
- * This is idempotent - subsequent calls skip if already installed.
321
- */
322
- async setupVlmDependencies() {
323
- if (this.vlmDependenciesInstalled) {
324
- this.logger.info(
325
- "[DoclingEnvironment] VLM dependencies already installed, skipping"
326
- );
327
- return;
328
- }
329
- if (await this.isVlmReady()) {
330
- this.vlmDependenciesInstalled = true;
331
- this.logger.info(
332
- "[DoclingEnvironment] VLM dependencies already installed, skipping"
333
- );
334
- return;
335
- }
336
- this.logger.info("[DoclingEnvironment] Installing VLM dependencies...");
337
- const pipPath = (0, import_node_path.join)(this.venvPath, "bin", "pip");
338
- this.logger.info("[DoclingEnvironment] Installing docling[vlm]...");
339
- const vlmResult = await spawnAsync(
340
- pipPath,
341
- ["install", "docling-serve[vlm]"],
342
- { timeout: VLM_ENVIRONMENT.SETUP_TIMEOUT_MS }
343
- );
344
- if (vlmResult.code !== 0) {
345
- this.logger.error(
346
- "[DoclingEnvironment] Failed to install docling-serve[vlm]:",
347
- vlmResult.stderr
348
- );
349
- throw new Error(
350
- `Failed to install docling-serve[vlm]. Exit code: ${vlmResult.code}`
351
- );
352
- }
353
- if ((0, import_node_os.platform)() === "darwin" && (0, import_node_os.arch)() === "arm64") {
354
- this.logger.info(
355
- "[DoclingEnvironment] Installing mlx + mlx-lm for Apple Silicon..."
356
- );
357
- const mlxResult = await spawnAsync(
358
- pipPath,
359
- ["install", "mlx", "mlx-lm"],
360
- { timeout: VLM_ENVIRONMENT.SETUP_TIMEOUT_MS }
361
- );
362
- if (mlxResult.code !== 0) {
363
- this.logger.error(
364
- "[DoclingEnvironment] Failed to install mlx/mlx-lm:",
365
- mlxResult.stderr
366
- );
367
- throw new Error(
368
- `Failed to install mlx/mlx-lm. Exit code: ${mlxResult.code}`
369
- );
370
- }
371
- }
372
- this.vlmDependenciesInstalled = true;
373
- this.logger.info(
374
- "[DoclingEnvironment] VLM dependencies installed successfully"
375
- );
376
- }
377
- /**
378
- * Check if VLM dependencies are ready by verifying Python module imports
379
- */
380
- async isVlmReady() {
381
- const pythonPath = (0, import_node_path.join)(this.venvPath, "bin", "python");
382
- const result = await spawnAsync(pythonPath, [
383
- "-c",
384
- "import docling_core; import docling"
385
- ]);
386
- return result.code === 0;
387
- }
388
780
  async isPortInUse(port) {
389
781
  try {
390
782
  const result = await spawnAsync("lsof", ["-ti", `:${port}`]);
@@ -455,8 +847,13 @@ var DoclingEnvironment = class _DoclingEnvironment {
455
847
  const doclingProcess = (0, import_node_child_process.spawn)(doclingServePath, args, {
456
848
  detached: true,
457
849
  // Detached from parent process
458
- stdio: "ignore"
850
+ stdio: "ignore",
459
851
  // Remove stdio pipes to prevent event loop from hanging
852
+ env: {
853
+ ...process.env,
854
+ // Enable remote API calls for API VLM models
855
+ DOCLING_SERVE_ENABLE_REMOTE_SERVICES: "true"
856
+ }
460
857
  });
461
858
  doclingProcess.unref();
462
859
  doclingProcess.on("error", (error) => {
@@ -471,126 +868,11 @@ var DoclingEnvironment = class _DoclingEnvironment {
471
868
  };
472
869
 
473
870
  // src/core/pdf-converter.ts
474
- var import_docling_sdk = require("docling-sdk");
475
871
  var import_es_toolkit = require("es-toolkit");
476
- var import_node_fs4 = require("fs");
477
- var import_node_path5 = require("path");
478
- var import_promises = require("stream/promises");
479
-
480
- // src/config/vlm-models.ts
481
- var VLM_MODELS = {
482
- // ── DocTags models (specialized document structure output) ──────────
483
- "granite-docling-258M-mlx": {
484
- repo_id: "ibm-granite/granite-docling-258M-mlx",
485
- inference_framework: "mlx",
486
- response_format: "doctags",
487
- transformers_model_type: "automodel-vision2seq",
488
- description: "Granite Docling 258M (MLX, Apple Silicon optimized, ~6s/page)"
489
- },
490
- "granite-docling-258M": {
491
- repo_id: "ibm-granite/granite-docling-258M",
492
- inference_framework: "transformers",
493
- response_format: "doctags",
494
- transformers_model_type: "automodel-vision2seq",
495
- description: "Granite Docling 258M (Transformers, cross-platform)"
496
- },
497
- "smoldocling-256M-mlx": {
498
- repo_id: "docling-project/SmolDocling-256M-preview-mlx-bf16",
499
- inference_framework: "mlx",
500
- response_format: "doctags",
501
- transformers_model_type: "automodel-vision2seq",
502
- description: "SmolDocling 256M (MLX, fastest option)"
503
- },
504
- "smoldocling-256M": {
505
- repo_id: "docling-project/SmolDocling-256M-preview",
506
- inference_framework: "transformers",
507
- response_format: "doctags",
508
- transformers_model_type: "automodel-vision2seq",
509
- description: "SmolDocling 256M (Transformers)"
510
- },
511
- // ── Markdown models (general-purpose vision LLMs) ──────────────────
512
- "granite-vision-2B": {
513
- repo_id: "ibm-granite/granite-vision-3.2-2b",
514
- inference_framework: "transformers",
515
- response_format: "markdown",
516
- transformers_model_type: "automodel-vision2seq",
517
- description: "Granite Vision 3.2 2B (IBM, higher accuracy)"
518
- },
519
- "qwen25-vl-3B-mlx": {
520
- repo_id: "mlx-community/Qwen2.5-VL-3B-Instruct-bf16",
521
- inference_framework: "mlx",
522
- response_format: "markdown",
523
- transformers_model_type: "automodel-vision2seq",
524
- description: "Qwen 2.5 VL 3B (MLX, multilingual, good KCJ support)"
525
- },
526
- phi4: {
527
- repo_id: "microsoft/Phi-4-multimodal-instruct",
528
- inference_framework: "transformers",
529
- response_format: "markdown",
530
- transformers_model_type: "automodel",
531
- description: "Phi-4 Multimodal (Microsoft, CausalLM)"
532
- },
533
- "pixtral-12B-mlx": {
534
- repo_id: "mlx-community/pixtral-12b-bf16",
535
- inference_framework: "mlx",
536
- response_format: "markdown",
537
- transformers_model_type: "automodel-vision2seq",
538
- description: "Pixtral 12B (MLX, Mistral, high accuracy)"
539
- },
540
- "pixtral-12B": {
541
- repo_id: "mistral-community/pixtral-12b",
542
- inference_framework: "transformers",
543
- response_format: "markdown",
544
- transformers_model_type: "automodel-vision2seq",
545
- description: "Pixtral 12B (Transformers, Mistral)"
546
- },
547
- got2: {
548
- repo_id: "stepfun-ai/GOT-OCR-2.0-hf",
549
- inference_framework: "transformers",
550
- response_format: "markdown",
551
- transformers_model_type: "automodel-vision2seq",
552
- description: "GOT-OCR 2.0 (StepFun, OCR-specialized)"
553
- },
554
- "gemma3-12B-mlx": {
555
- repo_id: "mlx-community/gemma-3-12b-it-bf16",
556
- inference_framework: "mlx",
557
- response_format: "markdown",
558
- transformers_model_type: "automodel-vision2seq",
559
- description: "Gemma 3 12B (MLX, Google)"
560
- },
561
- "gemma3-27B-mlx": {
562
- repo_id: "mlx-community/gemma-3-27b-it-bf16",
563
- inference_framework: "mlx",
564
- response_format: "markdown",
565
- transformers_model_type: "automodel-vision2seq",
566
- description: "Gemma 3 27B (MLX, Google, highest accuracy)"
567
- },
568
- dolphin: {
569
- repo_id: "ByteDance/Dolphin",
570
- inference_framework: "transformers",
571
- response_format: "markdown",
572
- transformers_model_type: "automodel-vision2seq",
573
- description: "Dolphin (ByteDance, document-oriented)"
574
- }
575
- };
576
- var DEFAULT_VLM_MODEL = "granite-docling-258M-mlx";
577
- function resolveVlmModel(model) {
578
- if (typeof model === "string") {
579
- const preset = VLM_MODELS[model];
580
- if (!preset) {
581
- throw new Error(
582
- `Unknown VLM model preset: "${model}". Available presets: ${Object.keys(VLM_MODELS).join(", ")}`
583
- );
584
- }
585
- return {
586
- repo_id: preset.repo_id,
587
- inference_framework: preset.inference_framework,
588
- response_format: preset.response_format,
589
- transformers_model_type: preset.transformers_model_type
590
- };
591
- }
592
- return model;
593
- }
872
+ var import_node_fs7 = require("fs");
873
+ var import_promises = require("fs/promises");
874
+ var import_node_path7 = require("path");
875
+ var import_promises2 = require("stream/promises");
594
876
 
595
877
  // src/errors/image-pdf-fallback-error.ts
596
878
  var ImagePdfFallbackError = class extends Error {
@@ -882,51 +1164,952 @@ var ImageExtractor = class _ImageExtractor {
882
1164
  }
883
1165
  };
884
1166
 
885
- // src/utils/local-file-server.ts
1167
+ // src/processors/page-renderer.ts
886
1168
  var import_node_fs2 = require("fs");
887
- var import_node_http = require("http");
888
1169
  var import_node_path3 = require("path");
889
- var LocalFileServer = class {
890
- server = null;
891
- port = 0;
1170
+ var DEFAULT_DPI = 300;
1171
+ var PageRenderer = class {
1172
+ constructor(logger) {
1173
+ this.logger = logger;
1174
+ }
892
1175
  /**
893
- * Start serving a file and return the URL
1176
+ * Render all pages of a PDF to individual PNG files.
894
1177
  *
895
- * @param filePath Absolute path to the file to serve
896
- * @returns URL to access the file
1178
+ * @param pdfPath - Absolute path to the source PDF file
1179
+ * @param outputDir - Directory where pages/ subdirectory will be created
1180
+ * @param options - Rendering options
1181
+ * @returns Render result with page count and file paths
897
1182
  */
898
- async start(filePath) {
899
- const filename = (0, import_node_path3.basename)(filePath);
900
- const stat = (0, import_node_fs2.statSync)(filePath);
901
- return new Promise((resolve, reject) => {
902
- this.server = (0, import_node_http.createServer)((req, res) => {
903
- if (req.url === `/${filename}`) {
904
- res.writeHead(200, {
905
- "Content-Type": "application/pdf",
906
- "Content-Length": stat.size
907
- });
908
- (0, import_node_fs2.createReadStream)(filePath).pipe(res);
909
- } else {
910
- res.writeHead(404);
911
- res.end("Not Found");
912
- }
913
- });
914
- this.server.on("error", reject);
915
- this.server.listen(0, "127.0.0.1", () => {
916
- const address = this.server.address();
917
- if (typeof address === "object" && address !== null) {
918
- this.port = address.port;
919
- resolve(`http://127.0.0.1:${this.port}/${filename}`);
920
- } else {
921
- reject(new Error("Failed to get server address"));
922
- }
923
- });
924
- });
1183
+ async renderPages(pdfPath, outputDir, options) {
1184
+ const dpi = options?.dpi ?? DEFAULT_DPI;
1185
+ const pagesDir = (0, import_node_path3.join)(outputDir, "pages");
1186
+ if (!(0, import_node_fs2.existsSync)(pagesDir)) {
1187
+ (0, import_node_fs2.mkdirSync)(pagesDir, { recursive: true });
1188
+ }
1189
+ this.logger.info(`[PageRenderer] Rendering PDF at ${dpi} DPI...`);
1190
+ const outputPattern = (0, import_node_path3.join)(pagesDir, "page_%d.png");
1191
+ const result = await spawnAsync("magick", [
1192
+ "-density",
1193
+ dpi.toString(),
1194
+ pdfPath,
1195
+ "-background",
1196
+ "white",
1197
+ "-alpha",
1198
+ "remove",
1199
+ "-alpha",
1200
+ "off",
1201
+ outputPattern
1202
+ ]);
1203
+ if (result.code !== 0) {
1204
+ throw new Error(
1205
+ `[PageRenderer] Failed to render PDF pages: ${result.stderr || "Unknown error"}`
1206
+ );
1207
+ }
1208
+ const pageFiles = (0, import_node_fs2.readdirSync)(pagesDir).filter((f) => f.startsWith("page_") && f.endsWith(".png")).sort((a, b) => {
1209
+ const numA = parseInt(a.replace("page_", "").replace(".png", ""), 10);
1210
+ const numB = parseInt(b.replace("page_", "").replace(".png", ""), 10);
1211
+ return numA - numB;
1212
+ }).map((f) => (0, import_node_path3.join)(pagesDir, f));
1213
+ this.logger.info(
1214
+ `[PageRenderer] Rendered ${pageFiles.length} pages to ${pagesDir}`
1215
+ );
1216
+ return {
1217
+ pageCount: pageFiles.length,
1218
+ pagesDir,
1219
+ pageFiles
1220
+ };
1221
+ }
1222
+ };
1223
+
1224
+ // src/processors/pdf-text-extractor.ts
1225
+ var PdfTextExtractor = class {
1226
+ constructor(logger) {
1227
+ this.logger = logger;
925
1228
  }
926
1229
  /**
927
- * Stop the server
1230
+ * Extract text from all pages of a PDF.
1231
+ *
1232
+ * @param pdfPath - Absolute path to the source PDF file
1233
+ * @param totalPages - Total number of pages in the PDF
1234
+ * @returns Map of 1-based page numbers to extracted text strings
928
1235
  */
929
- stop() {
1236
+ async extractText(pdfPath, totalPages) {
1237
+ this.logger.info(
1238
+ `[PdfTextExtractor] Extracting text from ${totalPages} pages...`
1239
+ );
1240
+ const pageTexts = /* @__PURE__ */ new Map();
1241
+ for (let page = 1; page <= totalPages; page++) {
1242
+ const text = await this.extractPageText(pdfPath, page);
1243
+ pageTexts.set(page, text);
1244
+ }
1245
+ const nonEmptyCount = [...pageTexts.values()].filter(
1246
+ (t) => t.trim().length > 0
1247
+ ).length;
1248
+ this.logger.info(
1249
+ `[PdfTextExtractor] Extracted text from ${nonEmptyCount}/${totalPages} pages`
1250
+ );
1251
+ return pageTexts;
1252
+ }
1253
+ /**
1254
+ * Get total page count of a PDF using pdfinfo.
1255
+ * Returns 0 on failure.
1256
+ */
1257
+ async getPageCount(pdfPath) {
1258
+ const result = await spawnAsync("pdfinfo", [pdfPath]);
1259
+ if (result.code !== 0) {
1260
+ this.logger.warn(
1261
+ `[PdfTextExtractor] pdfinfo failed: ${result.stderr || "Unknown error"}`
1262
+ );
1263
+ return 0;
1264
+ }
1265
+ const match = result.stdout.match(/^Pages:\s+(\d+)/m);
1266
+ return match ? parseInt(match[1], 10) : 0;
1267
+ }
1268
+ /**
1269
+ * Extract text from the entire PDF in a single pdftotext invocation.
1270
+ * Returns empty string on failure (logged as warning).
1271
+ */
1272
+ async extractFullText(pdfPath) {
1273
+ const result = await spawnAsync("pdftotext", ["-layout", pdfPath, "-"]);
1274
+ if (result.code !== 0) {
1275
+ this.logger.warn(
1276
+ `[PdfTextExtractor] pdftotext (full) failed: ${result.stderr || "Unknown error"}`
1277
+ );
1278
+ return "";
1279
+ }
1280
+ return result.stdout;
1281
+ }
1282
+ /**
1283
+ * Extract text from a single PDF page using pdftotext.
1284
+ * Returns empty string on failure (logged as warning).
1285
+ */
1286
+ async extractPageText(pdfPath, page) {
1287
+ const result = await spawnAsync("pdftotext", [
1288
+ "-f",
1289
+ page.toString(),
1290
+ "-l",
1291
+ page.toString(),
1292
+ "-layout",
1293
+ pdfPath,
1294
+ "-"
1295
+ ]);
1296
+ if (result.code !== 0) {
1297
+ this.logger.warn(
1298
+ `[PdfTextExtractor] pdftotext failed for page ${page}: ${result.stderr || "Unknown error"}`
1299
+ );
1300
+ return "";
1301
+ }
1302
+ return result.stdout;
1303
+ }
1304
+ };
1305
+
1306
+ // src/processors/vlm-text-corrector.ts
1307
+ var import_node_fs3 = require("fs");
1308
+ var import_node_path4 = require("path");
1309
+
1310
+ // src/types/vlm-text-correction-schema.ts
1311
+ var import_v4 = require("zod/v4");
1312
+ var vlmTextCorrectionSchema = import_v4.z.object({
1313
+ /** Text element corrections (substitution-based) */
1314
+ tc: import_v4.z.array(
1315
+ import_v4.z.object({
1316
+ /** Text element index (from prompt) */
1317
+ i: import_v4.z.number().int().nonnegative(),
1318
+ /** Substitutions: find/replace pairs applied left-to-right */
1319
+ s: import_v4.z.array(
1320
+ import_v4.z.object({
1321
+ /** Exact garbled substring to find */
1322
+ f: import_v4.z.string(),
1323
+ /** Corrected replacement text */
1324
+ r: import_v4.z.string()
1325
+ })
1326
+ )
1327
+ })
1328
+ ),
1329
+ /** Table cell corrections */
1330
+ cc: import_v4.z.array(
1331
+ import_v4.z.object({
1332
+ /** Table index (within the page) */
1333
+ ti: import_v4.z.number().int().nonnegative(),
1334
+ /** Row index */
1335
+ r: import_v4.z.number().int().nonnegative(),
1336
+ /** Column index */
1337
+ c: import_v4.z.number().int().nonnegative(),
1338
+ /** Corrected cell text */
1339
+ t: import_v4.z.string()
1340
+ })
1341
+ )
1342
+ });
1343
+
1344
+ // src/processors/vlm-text-corrector.ts
1345
+ var LANGUAGE_DISPLAY_NAMES = {
1346
+ ko: "Korean (\uD55C\uAD6D\uC5B4)",
1347
+ ja: "Japanese (\u65E5\u672C\u8A9E)",
1348
+ zh: "Chinese (\u4E2D\u6587)",
1349
+ en: "English",
1350
+ fr: "French (Fran\xE7ais)",
1351
+ de: "German (Deutsch)",
1352
+ es: "Spanish (Espa\xF1ol)",
1353
+ pt: "Portuguese (Portugu\xEAs)",
1354
+ ru: "Russian (\u0420\u0443\u0441\u0441\u043A\u0438\u0439)",
1355
+ uk: "Ukrainian (\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430)",
1356
+ it: "Italian (Italiano)"
1357
+ };
1358
+ var REFERENCE_MATCH_THRESHOLD = 0.4;
1359
+ var DEFAULT_CONCURRENCY = 1;
1360
+ var DEFAULT_MAX_RETRIES = 3;
1361
+ var DEFAULT_TEMPERATURE = 0;
1362
+ var LABEL_TO_TYPE_CODE = {
1363
+ section_header: "sh",
1364
+ text: "tx",
1365
+ caption: "ca",
1366
+ footnote: "fn",
1367
+ list_item: "li",
1368
+ page_header: "ph",
1369
+ page_footer: "pf"
1370
+ };
1371
+ var TEXT_LABELS = new Set(Object.keys(LABEL_TO_TYPE_CODE));
1372
+ var TEXT_CORRECTION_SYSTEM_PROMPT = `You are a text correction engine for OCR output from Korean archaeological (\u8003\u53E4\u5B78) report PDFs. Compare OCR text against the page image and reference text to fix errors.
1373
+
1374
+ The OCR engine cannot read Chinese characters (\u6F22\u5B57/Hanja) correctly. These errors appear as:
1375
+ - Random ASCII letters/symbols: \u718A\u6D25 \u2192 "M", \u5C0F\u4EAC\u5236 \u2192 "5\u2606", \u6545\u5740 \u2192 "Bbt"
1376
+ - Meaningless Korean syllables: \u6771\u660E \u2192 "\uD587\uBC30", \u91D1\u61B2\u660C \u2192 "\uC232", \u7E3D\u7BA1 \u2192 "3\uC501"
1377
+ - Number/symbol noise: \u718A\u5DDD\u5DDE \u2192 "IEJIM", \u6E6F\u4E95\u90E1 \u2192 "3#"
1378
+ - Hanja dropped entirely: (\u682A)\u97D3\u570B\u7E96\u7DAD \u2192 (\uC8FC), (\u8CA1)\u5FE0\u6DF8\u6587\u5316\u8CA1\u784F\u7A76\u9662 \u2192 (\uC7AC)\uCDA9\uB0A8\uBB38\uD654\uC7AC\uC5F0\uAD6C\uC6D0
1379
+ - Phonetic reading substitution (\u97F3\u8B80): \u6F22\u5B57 replaced by Korean pronunciation, e.g. \u5FE0\u6DF8\u6587\u5316\u8CA1\u784F\u7A76\u9662 \u2192 \uCDA9\uB0A8\uBB38\uD654\uC7AC\uC5F0\uAD6C\uC6D0, \u5BE6\u7389\u6D1E\u907A\u8E5F \u2192 \uC2E4\uC625\uB3D9\uC720\uC801
1380
+
1381
+ FIX: garbled/wrong Chinese characters, mojibake, encoding artifacts, random ASCII/Korean replacing Hanja, dropped Hanja, phonetic reading substitutions
1382
+ KEEP: correct text, structure, punctuation, whitespace
1383
+
1384
+ Input format:
1385
+ T: (text elements) index|type|text
1386
+ Optional: index|ref|reference_text (PDF text layer for the above element)
1387
+ C: (table cells) tableIndex|row,col|text
1388
+ Optional: C_REF: (unused pdftotext blocks as table reference)
1389
+
1390
+ FOOTNOTE (fn) SPECIAL INSTRUCTIONS:
1391
+ - Footnotes in archaeological reports contain institution names with Hanja that are severely garbled
1392
+ - Common pattern: (\u8CA1)\u6A5F\u95DC\u540D\u784F\u7A76\u9662 \u2192 (W)#X1CR003T or (W): 103 or similar ASCII noise
1393
+ - When OCR shows patterns like (W), (M), or random ASCII where an institution name should be, READ THE IMAGE directly
1394
+ - Institution names follow patterns like: (\u8CA1)OO\u6587\u5316\u8CA1\u784F\u7A76\u9662, (\u682A)OO, (\u793E)OO\u5B78\u6703
1395
+
1396
+ TABLE CELL (C:) SPECIAL INSTRUCTIONS:
1397
+ - Table headers often contain Hanja that OCR cannot read: \u767C\u520A\u65E5, \u6642\u4EE3, \u8ABF\u67FB\u7DE3\u7531, \u8ABF\u67FB\u6A5F\u95DC, \u907A\u8E5F\u540D, \u985E\u578B \uBC0F \u57FA\u6578
1398
+ - When OCR shows garbled characters like "\u20A9 A", "#\uCA6F\uBC0F\uD45C\uBF70" in table cells, READ THE IMAGE directly
1399
+ - If C_REF is present, use it as additional context for correcting table cells
1400
+
1401
+ When a |ref| line is present:
1402
+ - It shows text extracted directly from the PDF text layer for that element
1403
+ - If OCR text contains garbled characters but ref text looks correct, USE the ref text
1404
+ - For long paragraphs, align OCR and ref text segment by segment to identify and fix each garbled portion
1405
+ - IMPORTANT: If BOTH OCR and ref text are garbled (e.g. CJK font encoding issues), IGNORE the ref text and READ THE IMAGE directly
1406
+
1407
+ When NO |ref| line is present:
1408
+ - The PDF text layer could not be matched to this element
1409
+ - READ THE IMAGE directly to determine the correct text
1410
+
1411
+ Output JSON with corrections:
1412
+ tc=[{i:index, s:[{f:"garbled_substring",r:"corrected_text"}, ...]}] for text
1413
+ cc=[{ti:tableIndex, r:row, c:col, t:corrected}] for table cells
1414
+
1415
+ Substitution rules for tc:
1416
+ - 'f': exact garbled/wrong substring from the input text (must match exactly)
1417
+ - 'r': the corrected replacement
1418
+ - Include ALL garbled portions for each element as separate s entries
1419
+ - Order substitutions left-to-right as they appear in the text
1420
+ - Do NOT include unchanged text \u2014 only the specific substrings that need fixing
1421
+
1422
+ If all correct: {"tc":[],"cc":[]}`;
1423
+ var VlmTextCorrector = class {
1424
+ constructor(logger) {
1425
+ this.logger = logger;
1426
+ }
1427
+ /**
1428
+ * Read DoclingDocument from output directory, correct text via VLM,
1429
+ * and save the corrected document back.
1430
+ *
1431
+ * @param outputDir - Directory containing result.json and pages/
1432
+ * @param model - Vision language model for text correction
1433
+ * @param options - Processing options
1434
+ * @returns Correction statistics
1435
+ */
1436
+ async correctAndSave(outputDir, model, options) {
1437
+ this.logger.info("[VlmTextCorrector] Starting text correction...");
1438
+ const resultPath = (0, import_node_path4.join)(outputDir, "result.json");
1439
+ const doc = JSON.parse((0, import_node_fs3.readFileSync)(resultPath, "utf-8"));
1440
+ let pageNumbers = this.getPageNumbers(doc);
1441
+ if (pageNumbers.length === 0) {
1442
+ this.logger.info("[VlmTextCorrector] No pages to process");
1443
+ return {
1444
+ textCorrections: 0,
1445
+ cellCorrections: 0,
1446
+ pagesProcessed: 0,
1447
+ pagesFailed: 0
1448
+ };
1449
+ }
1450
+ if (options?.koreanHanjaMixPages && options.koreanHanjaMixPages.length > 0) {
1451
+ const totalPageCount = pageNumbers.length;
1452
+ const hanjaSet = new Set(options.koreanHanjaMixPages);
1453
+ pageNumbers = pageNumbers.filter((p) => hanjaSet.has(p));
1454
+ this.logger.info(
1455
+ `[VlmTextCorrector] Filtering to ${pageNumbers.length} Korean-Hanja mix pages out of ${totalPageCount} total`
1456
+ );
1457
+ }
1458
+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY;
1459
+ this.logger.info(
1460
+ `[VlmTextCorrector] Processing ${pageNumbers.length} pages (concurrency: ${concurrency})...`
1461
+ );
1462
+ const results = await ConcurrentPool.run(
1463
+ pageNumbers,
1464
+ concurrency,
1465
+ (pageNo) => this.correctPage(outputDir, doc, pageNo, model, options),
1466
+ () => {
1467
+ if (options?.onTokenUsage && options?.aggregator) {
1468
+ options.onTokenUsage(
1469
+ options.aggregator.getReport()
1470
+ );
1471
+ }
1472
+ }
1473
+ );
1474
+ let totalTextCorrections = 0;
1475
+ let totalCellCorrections = 0;
1476
+ let pagesFailed = 0;
1477
+ for (const result of results) {
1478
+ if (result === null) {
1479
+ pagesFailed++;
1480
+ } else {
1481
+ totalTextCorrections += result.tc.length;
1482
+ totalCellCorrections += result.cc.length;
1483
+ }
1484
+ }
1485
+ for (let i = 0; i < pageNumbers.length; i++) {
1486
+ const corrections = results[i];
1487
+ if (corrections === null) continue;
1488
+ this.applyCorrections(doc, pageNumbers[i], corrections);
1489
+ }
1490
+ (0, import_node_fs3.writeFileSync)(resultPath, JSON.stringify(doc, null, 2));
1491
+ this.logger.info(
1492
+ `[VlmTextCorrector] Correction complete: ${totalTextCorrections} text, ${totalCellCorrections} cell corrections across ${pageNumbers.length} pages (${pagesFailed} failed)`
1493
+ );
1494
+ return {
1495
+ textCorrections: totalTextCorrections,
1496
+ cellCorrections: totalCellCorrections,
1497
+ pagesProcessed: pageNumbers.length,
1498
+ pagesFailed
1499
+ };
1500
+ }
1501
+ /**
1502
+ * Get sorted page numbers from the document.
1503
+ */
1504
+ getPageNumbers(doc) {
1505
+ return Object.values(doc.pages).map((p) => p.page_no).sort((a, b) => a - b);
1506
+ }
1507
+ /**
1508
+ * Correct text on a single page via VLM.
1509
+ * Returns null if VLM call fails (graceful degradation).
1510
+ */
1511
+ async correctPage(outputDir, doc, pageNo, model, options) {
1512
+ try {
1513
+ const pageTexts = this.getPageTexts(doc, pageNo);
1514
+ const pageTables = this.getPageTables(doc, pageNo);
1515
+ if (pageTexts.length === 0 && pageTables.length === 0) {
1516
+ this.logger.debug(
1517
+ `[VlmTextCorrector] Page ${pageNo}: no text content, skipping`
1518
+ );
1519
+ return { tc: [], cc: [] };
1520
+ }
1521
+ const imageBase64 = this.readPageImage(outputDir, pageNo);
1522
+ const pageText = options?.pageTexts?.get(pageNo);
1523
+ let references;
1524
+ let tableContext;
1525
+ if (pageText) {
1526
+ const { references: refs, unusedBlocks } = this.matchTextToReferenceWithUnused(pageTexts, pageText);
1527
+ references = refs;
1528
+ if (pageTables.length > 0 && unusedBlocks.length > 0) {
1529
+ tableContext = unusedBlocks.join("\n");
1530
+ }
1531
+ }
1532
+ const userPrompt = this.buildUserPrompt(
1533
+ pageTexts,
1534
+ pageTables,
1535
+ references,
1536
+ tableContext
1537
+ );
1538
+ const systemPrompt = this.buildLanguageAwareSystemPrompt(
1539
+ options?.documentLanguages
1540
+ );
1541
+ const fullPrompt = systemPrompt + "\n\n" + userPrompt;
1542
+ const result = await LLMCaller.callVision({
1543
+ schema: vlmTextCorrectionSchema,
1544
+ messages: [
1545
+ {
1546
+ role: "user",
1547
+ content: [
1548
+ {
1549
+ type: "text",
1550
+ text: fullPrompt
1551
+ },
1552
+ {
1553
+ type: "image",
1554
+ image: `data:image/png;base64,${imageBase64}`
1555
+ }
1556
+ ]
1557
+ }
1558
+ ],
1559
+ primaryModel: model,
1560
+ maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES,
1561
+ temperature: options?.temperature ?? DEFAULT_TEMPERATURE,
1562
+ abortSignal: options?.abortSignal,
1563
+ component: "VlmTextCorrector",
1564
+ phase: "text-correction"
1565
+ });
1566
+ if (options?.aggregator) {
1567
+ options.aggregator.track(result.usage);
1568
+ }
1569
+ const output = result.output;
1570
+ if (output.tc.length > 0 || output.cc.length > 0) {
1571
+ this.logger.debug(
1572
+ `[VlmTextCorrector] Page ${pageNo}: ${output.tc.length} text, ${output.cc.length} cell corrections`
1573
+ );
1574
+ }
1575
+ return output;
1576
+ } catch (error) {
1577
+ if (options?.abortSignal?.aborted) {
1578
+ throw error;
1579
+ }
1580
+ this.logger.warn(
1581
+ `[VlmTextCorrector] Page ${pageNo}: VLM correction failed, keeping OCR text`,
1582
+ error
1583
+ );
1584
+ return null;
1585
+ }
1586
+ }
1587
+ /**
1588
+ * Get text items on a specific page, with their indices for prompt building.
1589
+ */
1590
+ getPageTexts(doc, pageNo) {
1591
+ const results = [];
1592
+ for (let i = 0; i < doc.texts.length; i++) {
1593
+ const item = doc.texts[i];
1594
+ if (!TEXT_LABELS.has(item.label)) continue;
1595
+ if (item.prov.some((p) => p.page_no === pageNo)) {
1596
+ results.push({ index: i, item });
1597
+ }
1598
+ }
1599
+ return results;
1600
+ }
1601
+ /**
1602
+ * Get table items on a specific page, with their indices.
1603
+ */
1604
+ getPageTables(doc, pageNo) {
1605
+ const results = [];
1606
+ for (let i = 0; i < doc.tables.length; i++) {
1607
+ const item = doc.tables[i];
1608
+ if (item.prov.some((p) => p.page_no === pageNo)) {
1609
+ results.push({ index: i, item });
1610
+ }
1611
+ }
1612
+ return results;
1613
+ }
1614
+ /**
1615
+ * Build compact user prompt for a page.
1616
+ *
1617
+ * Format:
1618
+ * T:
1619
+ * 0|sh|제1장 조사개요
1620
+ * 1|tx|본 보고서는 ...
1621
+ * C:
1622
+ * 0|0,0|유구명
1623
+ * 0|1,0|1호 住居址
1624
+ */
1625
+ buildUserPrompt(pageTexts, pageTables, references, tableContext) {
1626
+ const parts = [];
1627
+ if (pageTexts.length > 0) {
1628
+ const textLines = [];
1629
+ pageTexts.forEach((entry, promptIndex) => {
1630
+ const typeCode = LABEL_TO_TYPE_CODE[entry.item.label] ?? "tx";
1631
+ textLines.push(`${promptIndex}|${typeCode}|${entry.item.text}`);
1632
+ const ref = references?.get(promptIndex);
1633
+ if (ref) {
1634
+ textLines.push(`${promptIndex}|ref|${ref}`);
1635
+ }
1636
+ });
1637
+ parts.push("T:\n" + textLines.join("\n"));
1638
+ }
1639
+ if (pageTables.length > 0) {
1640
+ const cellLines = [];
1641
+ for (let tablePromptIndex = 0; tablePromptIndex < pageTables.length; tablePromptIndex++) {
1642
+ const table = pageTables[tablePromptIndex].item;
1643
+ for (const cell of table.data.table_cells) {
1644
+ if (!cell.text || cell.text.trim().length === 0) continue;
1645
+ cellLines.push(
1646
+ `${tablePromptIndex}|${cell.start_row_offset_idx},${cell.start_col_offset_idx}|${cell.text}`
1647
+ );
1648
+ }
1649
+ }
1650
+ if (cellLines.length > 0) {
1651
+ const cellSection = "C:\n" + cellLines.join("\n");
1652
+ if (tableContext) {
1653
+ parts.push(cellSection + "\nC_REF:\n" + tableContext);
1654
+ } else {
1655
+ parts.push(cellSection);
1656
+ }
1657
+ }
1658
+ }
1659
+ return parts.join("\n");
1660
+ }
1661
+ /**
1662
+ * Build a language-aware system prompt by prepending language context.
1663
+ */
1664
+ buildLanguageAwareSystemPrompt(documentLanguages) {
1665
+ if (!documentLanguages?.length) {
1666
+ return TEXT_CORRECTION_SYSTEM_PROMPT;
1667
+ }
1668
+ const primaryBase = documentLanguages[0].split("-")[0];
1669
+ const primaryName = LANGUAGE_DISPLAY_NAMES[primaryBase] ?? documentLanguages[0];
1670
+ const otherNames = documentLanguages.slice(1).map((code) => LANGUAGE_DISPLAY_NAMES[code.split("-")[0]] ?? code);
1671
+ const languageDesc = otherNames.length > 0 ? `primarily written in ${primaryName}, with ${otherNames.join(", ")} also present` : `written in ${primaryName}`;
1672
+ const prefix = `LANGUAGE CONTEXT: This document is ${languageDesc}. Focus on correcting characters that do not match this language.
1673
+
1674
+ `;
1675
+ return prefix + TEXT_CORRECTION_SYSTEM_PROMPT;
1676
+ }
1677
+ /**
1678
+ * Match pdftotext paragraph blocks to OCR elements using character multiset overlap.
1679
+ * Returns a map from prompt index to the best-matching reference block.
1680
+ */
1681
+ matchTextToReference(pageTexts, pageText) {
1682
+ return this.matchTextToReferenceWithUnused(pageTexts, pageText).references;
1683
+ }
1684
+ /**
1685
+ * Match pdftotext paragraph blocks to OCR elements and also return unused blocks.
1686
+ * Unused blocks are those that were not consumed by any text element match.
1687
+ */
1688
+ matchTextToReferenceWithUnused(pageTexts, pageText) {
1689
+ const references = /* @__PURE__ */ new Map();
1690
+ const refBlocks = this.mergeIntoBlocks(pageText);
1691
+ if (refBlocks.length === 0) {
1692
+ return { references, unusedBlocks: [] };
1693
+ }
1694
+ const available = new Set(refBlocks.map((_, i) => i));
1695
+ for (let promptIndex = 0; promptIndex < pageTexts.length; promptIndex++) {
1696
+ const ocrText = pageTexts[promptIndex].item.text;
1697
+ let bestScore = 0;
1698
+ let bestBlockIndex = -1;
1699
+ for (const blockIndex of available) {
1700
+ const score = this.computeCharOverlap(ocrText, refBlocks[blockIndex]);
1701
+ if (score > bestScore) {
1702
+ bestScore = score;
1703
+ bestBlockIndex = blockIndex;
1704
+ }
1705
+ }
1706
+ if (bestBlockIndex >= 0 && bestScore >= REFERENCE_MATCH_THRESHOLD) {
1707
+ if (refBlocks[bestBlockIndex] !== ocrText) {
1708
+ references.set(promptIndex, refBlocks[bestBlockIndex]);
1709
+ }
1710
+ available.delete(bestBlockIndex);
1711
+ }
1712
+ }
1713
+ const unusedBlocks = [...available].sort((a, b) => a - b).map((i) => refBlocks[i]);
1714
+ return { references, unusedBlocks };
1715
+ }
1716
+ /**
1717
+ * Merge pdftotext output into paragraph blocks separated by blank lines.
1718
+ * Consecutive non-empty lines are joined with a space.
1719
+ */
1720
+ mergeIntoBlocks(pageText) {
1721
+ const blocks = [];
1722
+ let currentLines = [];
1723
+ for (const rawLine of pageText.split("\n")) {
1724
+ const trimmed = rawLine.trim();
1725
+ if (trimmed.length === 0) {
1726
+ if (currentLines.length > 0) {
1727
+ blocks.push(currentLines.join(" "));
1728
+ currentLines = [];
1729
+ }
1730
+ } else {
1731
+ currentLines.push(trimmed);
1732
+ }
1733
+ }
1734
+ if (currentLines.length > 0) {
1735
+ blocks.push(currentLines.join(" "));
1736
+ }
1737
+ return blocks;
1738
+ }
1739
+ /**
1740
+ * Compute character multiset overlap ratio between two strings.
1741
+ * Returns a value between 0.0 and 1.0.
1742
+ */
1743
+ computeCharOverlap(a, b) {
1744
+ if (a.length === 0 || b.length === 0) return 0;
1745
+ const freqA = /* @__PURE__ */ new Map();
1746
+ for (const ch of a) {
1747
+ freqA.set(ch, (freqA.get(ch) ?? 0) + 1);
1748
+ }
1749
+ const freqB = /* @__PURE__ */ new Map();
1750
+ for (const ch of b) {
1751
+ freqB.set(ch, (freqB.get(ch) ?? 0) + 1);
1752
+ }
1753
+ let overlap = 0;
1754
+ for (const [ch, countA] of freqA) {
1755
+ const countB = freqB.get(ch) ?? 0;
1756
+ overlap += Math.min(countA, countB);
1757
+ }
1758
+ return overlap / Math.max(a.length, b.length);
1759
+ }
1760
+ /**
1761
+ * Read page image as base64.
1762
+ * Page images are 0-indexed: page_no N → pages/page_{N-1}.png
1763
+ */
1764
+ readPageImage(outputDir, pageNo) {
1765
+ const imagePath = (0, import_node_path4.join)(outputDir, "pages", `page_${pageNo - 1}.png`);
1766
+ return (0, import_node_fs3.readFileSync)(imagePath).toString("base64");
1767
+ }
1768
+ /**
1769
+ * Apply VLM corrections to the DoclingDocument.
1770
+ */
1771
+ applyCorrections(doc, pageNo, corrections) {
1772
+ if (corrections.tc.length > 0) {
1773
+ const pageTexts = this.getPageTexts(doc, pageNo);
1774
+ for (const correction of corrections.tc) {
1775
+ if (correction.i >= 0 && correction.i < pageTexts.length) {
1776
+ const docIndex = pageTexts[correction.i].index;
1777
+ let text = doc.texts[docIndex].text;
1778
+ for (const sub of correction.s) {
1779
+ const idx = text.indexOf(sub.f);
1780
+ if (idx >= 0) {
1781
+ text = text.substring(0, idx) + sub.r + text.substring(idx + sub.f.length);
1782
+ } else {
1783
+ this.logger.warn(
1784
+ `[VlmTextCorrector] Page ${pageNo}, text ${correction.i}: find string not found, skipping substitution`
1785
+ );
1786
+ }
1787
+ }
1788
+ if (text !== doc.texts[docIndex].text) {
1789
+ doc.texts[docIndex].text = text;
1790
+ doc.texts[docIndex].orig = text;
1791
+ }
1792
+ }
1793
+ }
1794
+ }
1795
+ if (corrections.cc.length > 0) {
1796
+ const pageTables = this.getPageTables(doc, pageNo);
1797
+ for (const correction of corrections.cc) {
1798
+ if (correction.ti >= 0 && correction.ti < pageTables.length) {
1799
+ const table = pageTables[correction.ti].item;
1800
+ for (const cell of table.data.table_cells) {
1801
+ if (cell.start_row_offset_idx === correction.r && cell.start_col_offset_idx === correction.c) {
1802
+ cell.text = correction.t;
1803
+ break;
1804
+ }
1805
+ }
1806
+ const gridRow = table.data.grid[correction.r];
1807
+ if (gridRow) {
1808
+ const gridCell = gridRow[correction.c];
1809
+ if (gridCell) {
1810
+ gridCell.text = correction.t;
1811
+ }
1812
+ }
1813
+ }
1814
+ }
1815
+ }
1816
+ }
1817
+ };
1818
+
1819
+ // src/samplers/ocr-strategy-sampler.ts
1820
+ var import_node_fs4 = require("fs");
1821
+ var import_v42 = require("zod/v4");
1822
+ var SAMPLE_DPI = 150;
1823
+ var EDGE_TRIM_RATIO = 0.1;
1824
+ var DEFAULT_MAX_SAMPLE_PAGES = 15;
1825
+ var DEFAULT_MAX_RETRIES2 = 3;
1826
+ var CJK_REGEX = /[\u4E00-\u9FFF]/;
1827
+ var HANGUL_REGEX = /[\uAC00-\uD7AF]/;
1828
+ var koreanHanjaMixSchema = import_v42.z.object({
1829
+ hasKoreanHanjaMix: import_v42.z.boolean().describe(
1830
+ "Whether the page contains any Hanja (\u6F22\u5B57/Chinese characters) mixed with Korean text"
1831
+ ),
1832
+ detectedLanguages: import_v42.z.array(import_v42.z.string()).describe(
1833
+ 'BCP 47 language tags of languages found on this page, ordered by prevalence (e.g., ["ko-KR", "en-US"])'
1834
+ )
1835
+ });
1836
+ var KOREAN_HANJA_MIX_PROMPT = `Look at this page image carefully. Does it contain any Hanja (\u6F22\u5B57/Chinese characters) mixed with Korean text?
1837
+
1838
+ Hanja examples: \u907A\u8E5F, \u767C\u6398, \u8ABF\u67FB, \u5831\u544A\u66F8, \u6587\u5316\u8CA1
1839
+ Note: Hanja are Chinese characters used in Korean documents, different from modern Korean (\uD55C\uAE00).
1840
+
1841
+ Answer whether any Hanja characters are present on this page.
1842
+
1843
+ Also identify all languages present on this page. Return an array of BCP 47 language tags ordered by prevalence (primary language first).
1844
+ Examples: ["ko-KR", "en-US"], ["ja-JP"], ["zh-TW", "en-US"]`;
1845
+ var OcrStrategySampler = class {
1846
+ logger;
1847
+ pageRenderer;
1848
+ textExtractor;
1849
+ constructor(logger, pageRenderer, textExtractor) {
1850
+ this.logger = logger;
1851
+ this.pageRenderer = pageRenderer;
1852
+ this.textExtractor = textExtractor ?? new PdfTextExtractor(logger);
1853
+ }
1854
+ /**
1855
+ * Sample pages from a PDF and determine the OCR strategy.
1856
+ *
1857
+ * @param pdfPath - Path to the PDF file
1858
+ * @param outputDir - Directory for temporary rendered pages
1859
+ * @param model - Vision language model for Korean-Hanja mix detection
1860
+ * @param options - Sampling options
1861
+ * @returns OcrStrategy with method ('ocrmac' or 'vlm') and metadata
1862
+ */
1863
+ async sample(pdfPath, outputDir, model, options) {
1864
+ const maxSamplePages = options?.maxSamplePages ?? DEFAULT_MAX_SAMPLE_PAGES;
1865
+ this.logger.info("[OcrStrategySampler] Starting OCR strategy sampling...");
1866
+ const preCheckResult = await this.preCheckHanjaFromTextLayer(pdfPath);
1867
+ if (preCheckResult) {
1868
+ return preCheckResult;
1869
+ }
1870
+ const renderResult = await this.pageRenderer.renderPages(
1871
+ pdfPath,
1872
+ outputDir,
1873
+ { dpi: SAMPLE_DPI }
1874
+ );
1875
+ if (renderResult.pageCount === 0) {
1876
+ this.logger.info("[OcrStrategySampler] No pages found in PDF");
1877
+ return {
1878
+ method: "ocrmac",
1879
+ reason: "No pages found in PDF",
1880
+ sampledPages: 0,
1881
+ totalPages: 0
1882
+ };
1883
+ }
1884
+ const sampleIndices = this.selectSamplePages(
1885
+ renderResult.pageCount,
1886
+ maxSamplePages
1887
+ );
1888
+ this.logger.info(
1889
+ `[OcrStrategySampler] Sampling ${sampleIndices.length} of ${renderResult.pageCount} pages: [${sampleIndices.map((i) => i + 1).join(", ")}]`
1890
+ );
1891
+ let sampledCount = 0;
1892
+ let detectedLanguages;
1893
+ for (const idx of sampleIndices) {
1894
+ sampledCount++;
1895
+ const pageFile = renderResult.pageFiles[idx];
1896
+ const pageAnalysis = await this.analyzeSamplePage(
1897
+ pageFile,
1898
+ idx + 1,
1899
+ model,
1900
+ options
1901
+ );
1902
+ detectedLanguages = pageAnalysis.detectedLanguages;
1903
+ if (pageAnalysis.hasKoreanHanjaMix) {
1904
+ this.logger.info(
1905
+ `[OcrStrategySampler] Korean-Hanja mix detected on page ${idx + 1} \u2192 VLM strategy`
1906
+ );
1907
+ return {
1908
+ method: "vlm",
1909
+ detectedLanguages,
1910
+ reason: `Korean-Hanja mix detected on page ${idx + 1}`,
1911
+ sampledPages: sampledCount,
1912
+ totalPages: renderResult.pageCount
1913
+ };
1914
+ }
1915
+ }
1916
+ this.logger.info(
1917
+ "[OcrStrategySampler] No Korean-Hanja mix detected \u2192 ocrmac strategy"
1918
+ );
1919
+ return {
1920
+ method: "ocrmac",
1921
+ detectedLanguages,
1922
+ reason: `No Korean-Hanja mix detected in ${sampledCount} sampled pages`,
1923
+ sampledPages: sampledCount,
1924
+ totalPages: renderResult.pageCount
1925
+ };
1926
+ }
1927
+ /**
1928
+ * Pre-check for Hangul-Hanja mix in PDF text layer using pdftotext.
1929
+ * Extracts full document text in a single process and checks at document level.
1930
+ * Only makes a definitive decision for Korean (Hangul) documents:
1931
+ * - Hangul + Hanja (anywhere in document) → VLM (confirmed Korean-Hanja mix)
1932
+ * - Hangul only → ocrmac with ko-KR (confirmed Korean)
1933
+ * - No Hangul (English, Japanese, etc.) → null (delegates to VLM for language detection)
1934
+ */
1935
+ async preCheckHanjaFromTextLayer(pdfPath) {
1936
+ try {
1937
+ const totalPages = await this.textExtractor.getPageCount(pdfPath);
1938
+ if (totalPages === 0) return null;
1939
+ const fullText = await this.textExtractor.extractFullText(pdfPath);
1940
+ if (fullText.trim().length === 0) {
1941
+ this.logger.debug(
1942
+ "[OcrStrategySampler] No Hangul in text layer, falling back to VLM sampling"
1943
+ );
1944
+ return null;
1945
+ }
1946
+ const hasHangul = HANGUL_REGEX.test(fullText);
1947
+ const hasHanja = CJK_REGEX.test(fullText);
1948
+ if (!hasHangul) {
1949
+ this.logger.debug(
1950
+ "[OcrStrategySampler] No Hangul in text layer, falling back to VLM sampling"
1951
+ );
1952
+ return null;
1953
+ }
1954
+ if (hasHanja) {
1955
+ const pageTextArray = fullText.split("\f");
1956
+ const koreanHanjaMixPages = [];
1957
+ for (let i = 0; i < pageTextArray.length; i++) {
1958
+ if (CJK_REGEX.test(pageTextArray[i])) {
1959
+ koreanHanjaMixPages.push(i + 1);
1960
+ }
1961
+ }
1962
+ this.logger.info(
1963
+ `[OcrStrategySampler] Hangul-Hanja mix detected in text layer \u2192 VLM strategy (${koreanHanjaMixPages.length} pages with Hanja)`
1964
+ );
1965
+ return {
1966
+ method: "vlm",
1967
+ detectedLanguages: ["ko-KR"],
1968
+ reason: "Hangul-Hanja mix found in PDF text layer",
1969
+ koreanHanjaMixPages,
1970
+ sampledPages: totalPages,
1971
+ totalPages
1972
+ };
1973
+ }
1974
+ this.logger.info(
1975
+ "[OcrStrategySampler] No Hangul-Hanja mix in text layer \u2192 ocrmac strategy"
1976
+ );
1977
+ return {
1978
+ method: "ocrmac",
1979
+ detectedLanguages: ["ko-KR"],
1980
+ reason: `No Hangul-Hanja mix in PDF text layer (${totalPages} pages checked)`,
1981
+ sampledPages: totalPages,
1982
+ totalPages
1983
+ };
1984
+ } catch {
1985
+ this.logger.debug(
1986
+ "[OcrStrategySampler] Text layer pre-check failed, falling back to VLM sampling"
1987
+ );
1988
+ return null;
1989
+ }
1990
+ }
1991
+ /**
1992
+ * Select page indices for sampling.
1993
+ * Trims front/back edges and distributes samples evenly.
1994
+ *
1995
+ * @param totalPages - Total number of pages
1996
+ * @param maxSamples - Maximum number of samples
1997
+ * @returns Array of 0-based page indices
1998
+ */
1999
+ selectSamplePages(totalPages, maxSamples) {
2000
+ if (totalPages === 0) return [];
2001
+ if (totalPages <= maxSamples) {
2002
+ return Array.from({ length: totalPages }, (_, i) => i);
2003
+ }
2004
+ const trimCount = Math.max(1, Math.ceil(totalPages * EDGE_TRIM_RATIO));
2005
+ const start = trimCount;
2006
+ const end = totalPages - trimCount;
2007
+ const eligibleCount = end - start;
2008
+ if (eligibleCount <= 0) {
2009
+ return [Math.floor(totalPages / 2)];
2010
+ }
2011
+ if (eligibleCount <= maxSamples) {
2012
+ return Array.from({ length: eligibleCount }, (_, i) => start + i);
2013
+ }
2014
+ const indices = [];
2015
+ const step = eligibleCount / maxSamples;
2016
+ for (let i = 0; i < maxSamples; i++) {
2017
+ indices.push(start + Math.floor(i * step));
2018
+ }
2019
+ return indices;
2020
+ }
2021
+ /**
2022
+ * Analyze a single sample page for Korean-Hanja mixed script and primary language.
2023
+ *
2024
+ * @returns Object with Korean-Hanja detection result and detected languages
2025
+ */
2026
+ async analyzeSamplePage(pageFile, pageNo, model, options) {
2027
+ this.logger.debug(
2028
+ `[OcrStrategySampler] Analyzing page ${pageNo} for Korean-Hanja mix and language...`
2029
+ );
2030
+ const base64Image = (0, import_node_fs4.readFileSync)(pageFile).toString("base64");
2031
+ const messages = [
2032
+ {
2033
+ role: "user",
2034
+ content: [
2035
+ { type: "text", text: KOREAN_HANJA_MIX_PROMPT },
2036
+ {
2037
+ type: "image",
2038
+ image: `data:image/png;base64,${base64Image}`
2039
+ }
2040
+ ]
2041
+ }
2042
+ ];
2043
+ const result = await LLMCaller.callVision({
2044
+ schema: koreanHanjaMixSchema,
2045
+ messages,
2046
+ primaryModel: model,
2047
+ fallbackModel: options?.fallbackModel,
2048
+ maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES2,
2049
+ temperature: options?.temperature ?? 0,
2050
+ abortSignal: options?.abortSignal,
2051
+ component: "OcrStrategySampler",
2052
+ phase: "korean-hanja-mix-detection"
2053
+ });
2054
+ if (options?.aggregator) {
2055
+ options.aggregator.track(result.usage);
2056
+ }
2057
+ const output = result.output;
2058
+ this.logger.debug(
2059
+ `[OcrStrategySampler] Page ${pageNo}: hasKoreanHanjaMix=${output.hasKoreanHanjaMix}, detectedLanguages=${output.detectedLanguages.join(",")}`
2060
+ );
2061
+ return {
2062
+ hasKoreanHanjaMix: output.hasKoreanHanjaMix,
2063
+ detectedLanguages: output.detectedLanguages
2064
+ };
2065
+ }
2066
+ };
2067
+
2068
+ // src/utils/local-file-server.ts
2069
+ var import_node_fs5 = require("fs");
2070
+ var import_node_http = require("http");
2071
+ var import_node_path5 = require("path");
2072
+ var LocalFileServer = class {
2073
+ server = null;
2074
+ port = 0;
2075
+ /**
2076
+ * Start serving a file and return the URL
2077
+ *
2078
+ * @param filePath Absolute path to the file to serve
2079
+ * @returns URL to access the file
2080
+ */
2081
+ async start(filePath) {
2082
+ const filename = (0, import_node_path5.basename)(filePath);
2083
+ const stat = (0, import_node_fs5.statSync)(filePath);
2084
+ return new Promise((resolve, reject) => {
2085
+ this.server = (0, import_node_http.createServer)((req, res) => {
2086
+ if (req.url === `/${filename}`) {
2087
+ res.writeHead(200, {
2088
+ "Content-Type": "application/pdf",
2089
+ "Content-Length": stat.size
2090
+ });
2091
+ (0, import_node_fs5.createReadStream)(filePath).pipe(res);
2092
+ } else {
2093
+ res.writeHead(404);
2094
+ res.end("Not Found");
2095
+ }
2096
+ });
2097
+ this.server.on("error", reject);
2098
+ this.server.listen(0, "127.0.0.1", () => {
2099
+ const address = this.server.address();
2100
+ if (typeof address === "object" && address !== null) {
2101
+ this.port = address.port;
2102
+ resolve(`http://127.0.0.1:${this.port}/${filename}`);
2103
+ } else {
2104
+ reject(new Error("Failed to get server address"));
2105
+ }
2106
+ });
2107
+ });
2108
+ }
2109
+ /**
2110
+ * Stop the server
2111
+ */
2112
+ stop() {
930
2113
  return new Promise((resolve) => {
931
2114
  if (this.server) {
932
2115
  this.server.close(() => {
@@ -942,9 +2125,9 @@ var LocalFileServer = class {
942
2125
  };
943
2126
 
944
2127
  // src/core/image-pdf-converter.ts
945
- var import_node_fs3 = require("fs");
946
- var import_node_os2 = require("os");
947
- var import_node_path4 = require("path");
2128
+ var import_node_fs6 = require("fs");
2129
+ var import_node_os = require("os");
2130
+ var import_node_path6 = require("path");
948
2131
  var ImagePdfConverter = class {
949
2132
  constructor(logger) {
950
2133
  this.logger = logger;
@@ -959,9 +2142,9 @@ var ImagePdfConverter = class {
959
2142
  */
960
2143
  async convert(pdfUrl, reportId) {
961
2144
  const timestamp = Date.now();
962
- const tempDir = (0, import_node_os2.tmpdir)();
963
- const inputPath = (0, import_node_path4.join)(tempDir, `${reportId}-${timestamp}-input.pdf`);
964
- const outputPath = (0, import_node_path4.join)(tempDir, `${reportId}-${timestamp}-image.pdf`);
2145
+ const tempDir = (0, import_node_os.tmpdir)();
2146
+ const inputPath = (0, import_node_path6.join)(tempDir, `${reportId}-${timestamp}-input.pdf`);
2147
+ const outputPath = (0, import_node_path6.join)(tempDir, `${reportId}-${timestamp}-image.pdf`);
965
2148
  try {
966
2149
  this.logger.info("[ImagePdfConverter] Downloading PDF from URL...");
967
2150
  await this.downloadPdf(pdfUrl, inputPath);
@@ -970,8 +2153,8 @@ var ImagePdfConverter = class {
970
2153
  this.logger.info("[ImagePdfConverter] Image PDF created:", outputPath);
971
2154
  return outputPath;
972
2155
  } finally {
973
- if ((0, import_node_fs3.existsSync)(inputPath)) {
974
- (0, import_node_fs3.rmSync)(inputPath, { force: true });
2156
+ if ((0, import_node_fs6.existsSync)(inputPath)) {
2157
+ (0, import_node_fs6.rmSync)(inputPath, { force: true });
975
2158
  }
976
2159
  }
977
2160
  }
@@ -1018,22 +2201,17 @@ var ImagePdfConverter = class {
1018
2201
  * Cleanup the temporary image PDF file
1019
2202
  */
1020
2203
  cleanup(imagePdfPath) {
1021
- if ((0, import_node_fs3.existsSync)(imagePdfPath)) {
2204
+ if ((0, import_node_fs6.existsSync)(imagePdfPath)) {
1022
2205
  this.logger.info(
1023
2206
  "[ImagePdfConverter] Cleaning up temp file:",
1024
2207
  imagePdfPath
1025
2208
  );
1026
- (0, import_node_fs3.rmSync)(imagePdfPath, { force: true });
2209
+ (0, import_node_fs6.rmSync)(imagePdfPath, { force: true });
1027
2210
  }
1028
2211
  }
1029
2212
  };
1030
2213
 
1031
2214
  // src/core/pdf-converter.ts
1032
- var _origAssertValidConversionOptions = import_docling_sdk.ValidationUtils.assertValidConversionOptions.bind(import_docling_sdk.ValidationUtils);
1033
- import_docling_sdk.ValidationUtils.assertValidConversionOptions = (options) => {
1034
- const { pipeline: _pipeline, ...rest } = options;
1035
- _origAssertValidConversionOptions(rest);
1036
- };
1037
2215
  var PDFConverter = class {
1038
2216
  constructor(logger, client, enableImagePdfFallback = false, timeout = PDF_CONVERTER.DEFAULT_TIMEOUT_MS) {
1039
2217
  this.logger = logger;
@@ -1043,9 +2221,232 @@ var PDFConverter = class {
1043
2221
  }
1044
2222
  async convert(url, reportId, onComplete, cleanupAfterCallback, options, abortSignal) {
1045
2223
  this.logger.info("[PDFConverter] Converting:", url);
2224
+ if (options.forceImagePdf) {
2225
+ return this.convertViaImagePdf(
2226
+ url,
2227
+ reportId,
2228
+ onComplete,
2229
+ cleanupAfterCallback,
2230
+ options,
2231
+ abortSignal
2232
+ );
2233
+ }
2234
+ return this.convertWithFallback(
2235
+ url,
2236
+ reportId,
2237
+ onComplete,
2238
+ cleanupAfterCallback,
2239
+ options,
2240
+ abortSignal
2241
+ );
2242
+ }
2243
+ /**
2244
+ * Convert a PDF using OCR strategy sampling to decide between ocrmac and VLM.
2245
+ *
2246
+ * Flow:
2247
+ * 1. Determine strategy (forced, skipped, or sampled via VLM)
2248
+ * 2. If VLM → OCR pipeline + VlmTextCorrector (text correction)
2249
+ * 3. If ocrmac → existing Docling conversion
2250
+ *
2251
+ * @returns ConvertWithStrategyResult with the chosen strategy and token report
2252
+ */
2253
+ async convertWithStrategy(url, reportId, onComplete, cleanupAfterCallback, options, abortSignal) {
2254
+ this.logger.info("[PDFConverter] Starting strategy-based conversion:", url);
2255
+ const aggregator = options.aggregator ?? new LLMTokenUsageAggregator();
2256
+ const trackedOptions = { ...options, aggregator };
2257
+ const pdfPath = url.startsWith("file://") ? url.slice(7) : null;
2258
+ const strategy = await this.determineStrategy(
2259
+ pdfPath,
2260
+ reportId,
2261
+ trackedOptions,
2262
+ abortSignal
2263
+ );
2264
+ this.logger.info(
2265
+ `[PDFConverter] OCR strategy: ${strategy.method} (${strategy.reason})`
2266
+ );
2267
+ if (trackedOptions.onTokenUsage) {
2268
+ const samplingReport = this.buildTokenReport(aggregator);
2269
+ if (samplingReport) {
2270
+ trackedOptions.onTokenUsage(samplingReport);
2271
+ }
2272
+ }
2273
+ if (strategy.method === "vlm") {
2274
+ await this.convertWithVlm(
2275
+ pdfPath,
2276
+ reportId,
2277
+ onComplete,
2278
+ cleanupAfterCallback,
2279
+ trackedOptions,
2280
+ abortSignal,
2281
+ strategy.detectedLanguages,
2282
+ strategy.koreanHanjaMixPages
2283
+ );
2284
+ return {
2285
+ strategy,
2286
+ tokenUsageReport: this.buildTokenReport(aggregator)
2287
+ };
2288
+ }
2289
+ const ocrmacOptions = strategy.detectedLanguages ? { ...trackedOptions, ocr_lang: strategy.detectedLanguages } : trackedOptions;
2290
+ await this.convert(
2291
+ url,
2292
+ reportId,
2293
+ onComplete,
2294
+ cleanupAfterCallback,
2295
+ ocrmacOptions,
2296
+ abortSignal
2297
+ );
2298
+ return {
2299
+ strategy,
2300
+ tokenUsageReport: this.buildTokenReport(aggregator)
2301
+ };
2302
+ }
2303
+ /**
2304
+ * Build a token usage report from the aggregator.
2305
+ * Returns null when no LLM calls were tracked (e.g. forced ocrmac without sampling).
2306
+ */
2307
+ buildTokenReport(aggregator) {
2308
+ const report = aggregator.getReport();
2309
+ if (report.components.length === 0) {
2310
+ return null;
2311
+ }
2312
+ return report;
2313
+ }
2314
+ /**
2315
+ * Determine the OCR strategy based on options and page sampling.
2316
+ *
2317
+ * When sampling is possible (strategySamplerModel + local file), it always
2318
+ * runs — even with forcedMethod — so that detectedLanguages are available
2319
+ * for OCR engine configuration. The forced method simply overrides the
2320
+ * sampled method choice.
2321
+ */
2322
+ async determineStrategy(pdfPath, reportId, options, abortSignal) {
2323
+ if (options.skipSampling || !options.strategySamplerModel || !pdfPath) {
2324
+ const method = options.forcedMethod ?? "ocrmac";
2325
+ const reason = options.forcedMethod ? `Forced: ${options.forcedMethod}` : !pdfPath ? "Non-local URL, sampling skipped" : "Sampling skipped";
2326
+ return { method, reason, sampledPages: 0, totalPages: 0 };
2327
+ }
2328
+ const samplingDir = (0, import_node_path7.join)(process.cwd(), "output", reportId, "_sampling");
2329
+ const sampler = new OcrStrategySampler(
2330
+ this.logger,
2331
+ new PageRenderer(this.logger),
2332
+ new PdfTextExtractor(this.logger)
2333
+ );
2334
+ try {
2335
+ const strategy = await sampler.sample(
2336
+ pdfPath,
2337
+ samplingDir,
2338
+ options.strategySamplerModel,
2339
+ {
2340
+ aggregator: options.aggregator,
2341
+ abortSignal
2342
+ }
2343
+ );
2344
+ if (options.forcedMethod) {
2345
+ return {
2346
+ ...strategy,
2347
+ method: options.forcedMethod,
2348
+ reason: `Forced: ${options.forcedMethod} (${strategy.reason})`
2349
+ };
2350
+ }
2351
+ return strategy;
2352
+ } finally {
2353
+ if ((0, import_node_fs7.existsSync)(samplingDir)) {
2354
+ (0, import_node_fs7.rmSync)(samplingDir, { recursive: true, force: true });
2355
+ }
2356
+ }
2357
+ }
2358
+ /**
2359
+ * Execute VLM-enhanced PDF conversion.
2360
+ *
2361
+ * Runs the standard OCR pipeline (Docling) first, then applies VLM text
2362
+ * correction to fix garbled Chinese characters (漢字/Hanja) in OCR output.
2363
+ */
2364
+ async convertWithVlm(pdfPath, reportId, onComplete, cleanupAfterCallback, options, abortSignal, detectedLanguages, koreanHanjaMixPages) {
2365
+ if (!options.vlmProcessorModel) {
2366
+ throw new Error("vlmProcessorModel is required when OCR strategy is VLM");
2367
+ }
2368
+ if (!pdfPath) {
2369
+ throw new Error("VLM conversion requires a local file (file:// URL)");
2370
+ }
2371
+ const url = `file://${pdfPath}`;
2372
+ const wrappedCallback = async (outputDir) => {
2373
+ let pageTexts;
2374
+ try {
2375
+ const resultPath2 = (0, import_node_path7.join)(outputDir, "result.json");
2376
+ const doc = JSON.parse((0, import_node_fs7.readFileSync)(resultPath2, "utf-8"));
2377
+ const totalPages = Object.keys(doc.pages).length;
2378
+ const textExtractor = new PdfTextExtractor(this.logger);
2379
+ pageTexts = await textExtractor.extractText(pdfPath, totalPages);
2380
+ } catch {
2381
+ this.logger.warn(
2382
+ "[PDFConverter] pdftotext extraction failed, proceeding without text reference"
2383
+ );
2384
+ }
2385
+ const resultPath = (0, import_node_path7.join)(outputDir, "result.json");
2386
+ const ocrOriginPath = (0, import_node_path7.join)(outputDir, "result_ocr_origin.json");
2387
+ (0, import_node_fs7.copyFileSync)(resultPath, ocrOriginPath);
2388
+ const corrector = new VlmTextCorrector(this.logger);
2389
+ await corrector.correctAndSave(outputDir, options.vlmProcessorModel, {
2390
+ concurrency: options.vlmConcurrency,
2391
+ aggregator: options.aggregator,
2392
+ abortSignal,
2393
+ onTokenUsage: options.onTokenUsage,
2394
+ documentLanguages: detectedLanguages,
2395
+ pageTexts,
2396
+ koreanHanjaMixPages
2397
+ });
2398
+ await onComplete(outputDir);
2399
+ };
2400
+ const vlmOptions = detectedLanguages ? { ...options, ocr_lang: detectedLanguages } : options;
2401
+ await this.convert(
2402
+ url,
2403
+ reportId,
2404
+ wrappedCallback,
2405
+ cleanupAfterCallback,
2406
+ vlmOptions,
2407
+ abortSignal
2408
+ );
2409
+ this.logger.info("[PDFConverter] VLM conversion completed successfully");
2410
+ }
2411
+ /**
2412
+ * Convert by first creating an image PDF, then running the conversion.
2413
+ * Used when forceImagePdf option is enabled.
2414
+ */
2415
+ async convertViaImagePdf(url, reportId, onComplete, cleanupAfterCallback, options, abortSignal) {
2416
+ this.logger.info(
2417
+ "[PDFConverter] Force image PDF mode: converting to image PDF first..."
2418
+ );
2419
+ const imagePdfConverter = new ImagePdfConverter(this.logger);
2420
+ let imagePdfPath = null;
2421
+ try {
2422
+ imagePdfPath = await imagePdfConverter.convert(url, reportId);
2423
+ const localUrl = `file://${imagePdfPath}`;
2424
+ this.logger.info(
2425
+ "[PDFConverter] Image PDF ready, starting conversion:",
2426
+ localUrl
2427
+ );
2428
+ return await this.performConversion(
2429
+ localUrl,
2430
+ reportId,
2431
+ onComplete,
2432
+ cleanupAfterCallback,
2433
+ options,
2434
+ abortSignal
2435
+ );
2436
+ } finally {
2437
+ if (imagePdfPath) {
2438
+ imagePdfConverter.cleanup(imagePdfPath);
2439
+ }
2440
+ }
2441
+ }
2442
+ /**
2443
+ * Convert directly with optional image PDF fallback on failure.
2444
+ * Used by standard (OCR) pipeline.
2445
+ */
2446
+ async convertWithFallback(url, reportId, onComplete, cleanupAfterCallback, options, abortSignal) {
1046
2447
  let originalError = null;
1047
2448
  try {
1048
- await this.performConversion(
2449
+ return await this.performConversion(
1049
2450
  url,
1050
2451
  reportId,
1051
2452
  onComplete,
@@ -1053,7 +2454,6 @@ var PDFConverter = class {
1053
2454
  options,
1054
2455
  abortSignal
1055
2456
  );
1056
- return;
1057
2457
  } catch (error) {
1058
2458
  if (abortSignal?.aborted) {
1059
2459
  throw error;
@@ -1071,7 +2471,7 @@ var PDFConverter = class {
1071
2471
  imagePdfPath = await imagePdfConverter.convert(url, reportId);
1072
2472
  const localUrl = `file://${imagePdfPath}`;
1073
2473
  this.logger.info("[PDFConverter] Retrying with image PDF:", localUrl);
1074
- await this.performConversion(
2474
+ const report = await this.performConversion(
1075
2475
  localUrl,
1076
2476
  reportId,
1077
2477
  onComplete,
@@ -1080,6 +2480,7 @@ var PDFConverter = class {
1080
2480
  abortSignal
1081
2481
  );
1082
2482
  this.logger.info("[PDFConverter] Fallback conversion succeeded");
2483
+ return report;
1083
2484
  } catch (fallbackError) {
1084
2485
  this.logger.error(
1085
2486
  "[PDFConverter] Fallback conversion also failed:",
@@ -1094,15 +2495,10 @@ var PDFConverter = class {
1094
2495
  }
1095
2496
  async performConversion(url, reportId, onComplete, cleanupAfterCallback, options, abortSignal) {
1096
2497
  const startTime = Date.now();
1097
- const pipelineType = options.pipeline ?? "standard";
1098
- const conversionOptions = pipelineType === "vlm" ? this.buildVlmConversionOptions(options) : this.buildConversionOptions(options);
1099
- if (pipelineType === "vlm") {
1100
- this.logger.info("[PDFConverter] Using VLM pipeline");
1101
- } else {
1102
- this.logger.info(
1103
- `[PDFConverter] OCR languages: ${JSON.stringify(conversionOptions.ocr_options?.lang)}`
1104
- );
1105
- }
2498
+ const conversionOptions = this.buildConversionOptions(options);
2499
+ this.logger.info(
2500
+ `[PDFConverter] OCR languages: ${JSON.stringify(conversionOptions.ocr_options?.lang)}`
2501
+ );
1106
2502
  this.logger.info(
1107
2503
  "[PDFConverter] Converting document with Async Source API..."
1108
2504
  );
@@ -1130,9 +2526,9 @@ var PDFConverter = class {
1130
2526
  }
1131
2527
  }
1132
2528
  const cwd = process.cwd();
1133
- const zipPath = (0, import_node_path5.join)(cwd, "result.zip");
1134
- const extractDir = (0, import_node_path5.join)(cwd, "result_extracted");
1135
- const outputDir = (0, import_node_path5.join)(cwd, "output", reportId);
2529
+ const zipPath = (0, import_node_path7.join)(cwd, "result.zip");
2530
+ const extractDir = (0, import_node_path7.join)(cwd, "result_extracted");
2531
+ const outputDir = (0, import_node_path7.join)(cwd, "output", reportId);
1136
2532
  try {
1137
2533
  await this.processConvertedFiles(zipPath, extractDir, outputDir);
1138
2534
  if (abortSignal?.aborted) {
@@ -1148,28 +2544,38 @@ var PDFConverter = class {
1148
2544
  this.logger.info("[PDFConverter] Total time:", duration, "ms");
1149
2545
  } finally {
1150
2546
  this.logger.info("[PDFConverter] Cleaning up temporary files...");
1151
- if ((0, import_node_fs4.existsSync)(zipPath)) {
1152
- (0, import_node_fs4.rmSync)(zipPath, { force: true });
2547
+ if ((0, import_node_fs7.existsSync)(zipPath)) {
2548
+ (0, import_node_fs7.rmSync)(zipPath, { force: true });
1153
2549
  }
1154
- if ((0, import_node_fs4.existsSync)(extractDir)) {
1155
- (0, import_node_fs4.rmSync)(extractDir, { recursive: true, force: true });
2550
+ if ((0, import_node_fs7.existsSync)(extractDir)) {
2551
+ (0, import_node_fs7.rmSync)(extractDir, { recursive: true, force: true });
1156
2552
  }
1157
2553
  if (cleanupAfterCallback) {
1158
2554
  this.logger.info(
1159
2555
  "[PDFConverter] Cleaning up output directory:",
1160
2556
  outputDir
1161
2557
  );
1162
- if ((0, import_node_fs4.existsSync)(outputDir)) {
1163
- (0, import_node_fs4.rmSync)(outputDir, { recursive: true, force: true });
2558
+ if ((0, import_node_fs7.existsSync)(outputDir)) {
2559
+ (0, import_node_fs7.rmSync)(outputDir, { recursive: true, force: true });
1164
2560
  }
1165
2561
  } else {
1166
2562
  this.logger.info("[PDFConverter] Output preserved at:", outputDir);
1167
2563
  }
1168
2564
  }
2565
+ return null;
1169
2566
  }
1170
2567
  buildConversionOptions(options) {
1171
2568
  return {
1172
- ...(0, import_es_toolkit.omit)(options, ["num_threads", "pipeline", "vlm_model"]),
2569
+ ...(0, import_es_toolkit.omit)(options, [
2570
+ "num_threads",
2571
+ "forceImagePdf",
2572
+ "strategySamplerModel",
2573
+ "vlmProcessorModel",
2574
+ "skipSampling",
2575
+ "forcedMethod",
2576
+ "aggregator",
2577
+ "onTokenUsage"
2578
+ ]),
1173
2579
  to_formats: ["json", "html"],
1174
2580
  image_export_mode: "embedded",
1175
2581
  ocr_engine: "ocrmac",
@@ -1195,31 +2601,6 @@ var PDFConverter = class {
1195
2601
  }
1196
2602
  };
1197
2603
  }
1198
- /**
1199
- * Build conversion options for VLM pipeline.
1200
- *
1201
- * VLM pipeline uses a Vision Language Model instead of traditional OCR,
1202
- * providing better accuracy for KCJ characters and complex layouts.
1203
- */
1204
- buildVlmConversionOptions(options) {
1205
- const vlmModel = resolveVlmModel(options.vlm_model ?? DEFAULT_VLM_MODEL);
1206
- this.logger.info(
1207
- `[PDFConverter] VLM model: ${vlmModel.repo_id} (framework: ${vlmModel.inference_framework}, format: ${vlmModel.response_format})`
1208
- );
1209
- return {
1210
- ...(0, import_es_toolkit.omit)(options, ["num_threads", "pipeline", "vlm_model", "ocr_lang"]),
1211
- to_formats: ["json", "html"],
1212
- image_export_mode: "embedded",
1213
- pipeline: "vlm",
1214
- vlm_pipeline_model_local: vlmModel,
1215
- generate_picture_images: true,
1216
- images_scale: 2,
1217
- accelerator_options: {
1218
- device: "mps",
1219
- num_threads: options.num_threads
1220
- }
1221
- };
1222
- }
1223
2604
  async startConversionTask(url, conversionOptions) {
1224
2605
  const task = await this.client.convertSourceAsync({
1225
2606
  sources: [
@@ -1286,25 +2667,64 @@ var PDFConverter = class {
1286
2667
  return;
1287
2668
  }
1288
2669
  if (status.task_status === "failure") {
1289
- throw new Error("Task failed with status: failure");
2670
+ const errorDetails = await this.getTaskFailureDetails(task);
2671
+ const elapsed = Math.round((Date.now() - conversionStartTime) / 1e3);
2672
+ this.logger.error(
2673
+ `
2674
+ [PDFConverter] Task failed after ${elapsed}s: ${errorDetails}`
2675
+ );
2676
+ throw new Error(`Task failed: ${errorDetails}`);
1290
2677
  }
1291
2678
  await new Promise(
1292
2679
  (resolve) => setTimeout(resolve, PDF_CONVERTER.POLL_INTERVAL_MS)
1293
2680
  );
1294
2681
  }
1295
2682
  }
2683
+ /**
2684
+ * Fetch detailed error information from a failed task result.
2685
+ */
2686
+ async getTaskFailureDetails(task) {
2687
+ try {
2688
+ const result = await task.getResult();
2689
+ if (result.errors?.length) {
2690
+ return result.errors.map((e) => e.message).join("; ");
2691
+ }
2692
+ return `status: ${result.status ?? "unknown"}`;
2693
+ } catch (err) {
2694
+ this.logger.error("[PDFConverter] Failed to retrieve task result:", err);
2695
+ return "unable to retrieve error details";
2696
+ }
2697
+ }
1296
2698
  async downloadResult(taskId) {
1297
2699
  this.logger.info(
1298
2700
  "\n[PDFConverter] Task completed, downloading ZIP file..."
1299
2701
  );
1300
2702
  const zipResult = await this.client.getTaskResultFile(taskId);
1301
- if (!zipResult.success || !zipResult.fileStream) {
1302
- throw new Error("Failed to get ZIP file result");
1303
- }
1304
- const zipPath = (0, import_node_path5.join)(process.cwd(), "result.zip");
2703
+ const zipPath = (0, import_node_path7.join)(process.cwd(), "result.zip");
1305
2704
  this.logger.info("[PDFConverter] Saving ZIP file to:", zipPath);
1306
- const writeStream = (0, import_node_fs4.createWriteStream)(zipPath);
1307
- await (0, import_promises.pipeline)(zipResult.fileStream, writeStream);
2705
+ if (zipResult.fileStream) {
2706
+ const writeStream = (0, import_node_fs7.createWriteStream)(zipPath);
2707
+ await (0, import_promises2.pipeline)(zipResult.fileStream, writeStream);
2708
+ return;
2709
+ }
2710
+ if (zipResult.data) {
2711
+ await (0, import_promises.writeFile)(zipPath, zipResult.data);
2712
+ return;
2713
+ }
2714
+ this.logger.warn(
2715
+ "[PDFConverter] SDK file result unavailable, falling back to direct download..."
2716
+ );
2717
+ const baseUrl = this.client.getConfig().baseUrl;
2718
+ const response = await fetch(`${baseUrl}/v1/result/${taskId}`, {
2719
+ headers: { Accept: "application/zip" }
2720
+ });
2721
+ if (!response.ok) {
2722
+ throw new Error(
2723
+ `Failed to download ZIP file: ${response.status} ${response.statusText}`
2724
+ );
2725
+ }
2726
+ const buffer = new Uint8Array(await response.arrayBuffer());
2727
+ await (0, import_promises.writeFile)(zipPath, buffer);
1308
2728
  }
1309
2729
  async processConvertedFiles(zipPath, extractDir, outputDir) {
1310
2730
  await ImageExtractor.extractAndSaveDocumentsFromZip(
@@ -1344,7 +2764,7 @@ var PDFParser = class {
1344
2764
  this.baseUrl = void 0;
1345
2765
  }
1346
2766
  this.timeout = timeout;
1347
- this.venvPath = venvPath || (0, import_node_path6.join)(process.cwd(), ".venv");
2767
+ this.venvPath = venvPath || (0, import_node_path8.join)(process.cwd(), ".venv");
1348
2768
  this.killExistingProcess = killExistingProcess;
1349
2769
  this.enableImagePdfFallback = enableImagePdfFallback;
1350
2770
  }
@@ -1363,7 +2783,7 @@ var PDFParser = class {
1363
2783
  }
1364
2784
  if (this.baseUrl) {
1365
2785
  this.logger.info("[PDFParser] Using external server:", this.baseUrl);
1366
- this.client = new import_docling_sdk2.Docling({
2786
+ this.client = new import_docling_sdk.Docling({
1367
2787
  api: { baseUrl: this.baseUrl, timeout: this.timeout }
1368
2788
  });
1369
2789
  await this.waitForServerReady();
@@ -1379,7 +2799,7 @@ var PDFParser = class {
1379
2799
  });
1380
2800
  await this.environment.setup();
1381
2801
  const clientUrl = `http://localhost:${this.port}`;
1382
- this.client = new import_docling_sdk2.Docling({
2802
+ this.client = new import_docling_sdk.Docling({
1383
2803
  api: {
1384
2804
  baseUrl: clientUrl,
1385
2805
  timeout: this.timeout
@@ -1393,9 +2813,9 @@ var PDFParser = class {
1393
2813
  }
1394
2814
  }
1395
2815
  checkOperatingSystem() {
1396
- if ((0, import_node_os3.platform)() !== "darwin") {
2816
+ if ((0, import_node_os2.platform)() !== "darwin") {
1397
2817
  throw new Error(
1398
- "PDFParser is only supported on macOS. Current platform: " + (0, import_node_os3.platform)()
2818
+ "PDFParser is only supported on macOS. Current platform: " + (0, import_node_os2.platform)()
1399
2819
  );
1400
2820
  }
1401
2821
  }
@@ -1454,8 +2874,12 @@ var PDFParser = class {
1454
2874
  */
1455
2875
  isConnectionRefusedError(error) {
1456
2876
  if (error instanceof Error) {
1457
- const errorStr = JSON.stringify(error);
1458
- return errorStr.includes("ECONNREFUSED");
2877
+ if (error.message.includes("ECONNREFUSED")) {
2878
+ return true;
2879
+ }
2880
+ if (error.cause instanceof Error && error.cause.message.includes("ECONNREFUSED")) {
2881
+ return true;
2882
+ }
1459
2883
  }
1460
2884
  return false;
1461
2885
  }
@@ -1479,7 +2903,7 @@ var PDFParser = class {
1479
2903
  });
1480
2904
  await environment.startServer();
1481
2905
  this.client?.destroy();
1482
- this.client = new import_docling_sdk2.Docling({
2906
+ this.client = new import_docling_sdk.Docling({
1483
2907
  api: {
1484
2908
  baseUrl: `http://localhost:${this.port}`,
1485
2909
  timeout: this.timeout
@@ -1523,11 +2947,20 @@ var PDFParser = class {
1523
2947
  "PDFParser is not initialized. Call init() before using parse()"
1524
2948
  );
1525
2949
  }
1526
- if (options.pipeline === "vlm" && this.environment && !this.baseUrl) {
1527
- this.logger.info(
1528
- "[PDFParser] VLM pipeline requested, ensuring VLM dependencies..."
2950
+ if (options.forceImagePdf && !this.baseUrl) {
2951
+ this.checkImageMagickInstalled();
2952
+ this.checkGhostscriptInstalled();
2953
+ }
2954
+ const useStrategyFlow = options.strategySamplerModel !== void 0 || options.forcedMethod !== void 0;
2955
+ if (useStrategyFlow) {
2956
+ return this.parseWithStrategy(
2957
+ url,
2958
+ reportId,
2959
+ onComplete,
2960
+ cleanupAfterCallback,
2961
+ options,
2962
+ abortSignal
1529
2963
  );
1530
- await this.environment.setupVlmDependencies();
1531
2964
  }
1532
2965
  const canRecover = !this.baseUrl && this.port !== void 0;
1533
2966
  const maxAttempts = PDF_PARSER.MAX_SERVER_RECOVERY_ATTEMPTS;
@@ -1564,6 +2997,53 @@ var PDFParser = class {
1564
2997
  throw error;
1565
2998
  }
1566
2999
  }
3000
+ return null;
3001
+ }
3002
+ /**
3003
+ * Parse a PDF using OCR strategy sampling to decide between ocrmac and VLM.
3004
+ * Delegates to PDFConverter.convertWithStrategy() and returns the token usage report.
3005
+ *
3006
+ * Server recovery (restart on ECONNREFUSED) is preserved because
3007
+ * the ocrmac path still uses the Docling server.
3008
+ */
3009
+ async parseWithStrategy(url, reportId, onComplete, cleanupAfterCallback, options, abortSignal) {
3010
+ const canRecover = !this.baseUrl && this.port !== void 0;
3011
+ const maxAttempts = PDF_PARSER.MAX_SERVER_RECOVERY_ATTEMPTS;
3012
+ let attempt = 0;
3013
+ while (attempt <= maxAttempts) {
3014
+ try {
3015
+ const effectiveFallbackEnabled = this.enableImagePdfFallback && !this.baseUrl;
3016
+ const converter = new PDFConverter(
3017
+ this.logger,
3018
+ this.client,
3019
+ effectiveFallbackEnabled,
3020
+ this.timeout
3021
+ );
3022
+ const result = await converter.convertWithStrategy(
3023
+ url,
3024
+ reportId,
3025
+ onComplete,
3026
+ cleanupAfterCallback,
3027
+ options,
3028
+ abortSignal
3029
+ );
3030
+ return result.tokenUsageReport;
3031
+ } catch (error) {
3032
+ if (abortSignal?.aborted) {
3033
+ throw error;
3034
+ }
3035
+ if (canRecover && this.isConnectionRefusedError(error) && attempt < maxAttempts) {
3036
+ this.logger.warn(
3037
+ "[PDFParser] Connection refused, attempting server recovery..."
3038
+ );
3039
+ await this.restartServer();
3040
+ attempt++;
3041
+ continue;
3042
+ }
3043
+ throw error;
3044
+ }
3045
+ }
3046
+ return null;
1567
3047
  }
1568
3048
  /**
1569
3049
  * Dispose the parser instance.
@@ -1585,12 +3065,174 @@ var PDFParser = class {
1585
3065
  }
1586
3066
  }
1587
3067
  };
3068
+
3069
+ // src/validators/vlm-response-validator.ts
3070
+ var MIN_CONTENT_LENGTH = 20;
3071
+ var KOREAN_SCRIPT_RATIO_THRESHOLD = 0.1;
3072
+ var PLACEHOLDER_PATTERNS = [
3073
+ /lorem\s+ipsum/i,
3074
+ /dolor\s+sit\s+amet/i,
3075
+ /consectetur\s+adipiscing/i,
3076
+ /sed\s+do\s+eiusmod/i,
3077
+ /ut\s+labore\s+et\s+dolore/i
3078
+ ];
3079
+ var META_DESCRIPTION_PATTERNS_KO = [
3080
+ /이미지\s*해상도/,
3081
+ /판독하기?\s*어렵/,
3082
+ /해상도가?\s*(매우\s*)?(낮|부족)/,
3083
+ /텍스트를?\s*판독/,
3084
+ /글자를?\s*읽기?\s*어렵/,
3085
+ /정확한?\s*판독이?\s*(불가|어렵)/
3086
+ ];
3087
+ var META_DESCRIPTION_PATTERNS_EN = [
3088
+ /the image contains/i,
3089
+ /unable to (read|transcribe)/i,
3090
+ /resolution.*(too low|insufficient)/i,
3091
+ /cannot (read|make out|decipher)/i,
3092
+ /text is (not |un)?(legible|readable)/i,
3093
+ /exact transcription is not possible/i
3094
+ ];
3095
+ var REPETITIVE_PATTERN_RATIO_THRESHOLD = 0.3;
3096
+ var REPETITIVE_PATTERN_MIN_REPEATS = 5;
3097
+ var HANGUL_REGEX2 = /[\uAC00-\uD7AF\u1100-\u11FF]/g;
3098
+ var CJK_REGEX2 = /[\u4E00-\u9FFF]/g;
3099
+ var VlmResponseValidator = class {
3100
+ /**
3101
+ * Validate VLM page result quality.
3102
+ *
3103
+ * @param elements - Extracted page elements to validate
3104
+ * @param documentLanguages - BCP 47 language tags (e.g., ['ko-KR', 'en-US'])
3105
+ * @returns Validation result with issues list
3106
+ */
3107
+ static validate(elements, documentLanguages) {
3108
+ const issues = [];
3109
+ const textElements = elements.filter(
3110
+ (el) => el.type !== "picture" && el.content.length > 0
3111
+ );
3112
+ if (textElements.length === 0) {
3113
+ return { isValid: true, issues: [] };
3114
+ }
3115
+ const placeholderIssue = this.detectPlaceholderText(textElements);
3116
+ if (placeholderIssue) {
3117
+ issues.push(placeholderIssue);
3118
+ }
3119
+ if (documentLanguages?.[0]?.startsWith("ko")) {
3120
+ const scriptIssue = this.detectScriptAnomaly(textElements);
3121
+ if (scriptIssue) {
3122
+ issues.push(scriptIssue);
3123
+ }
3124
+ }
3125
+ const metaIssue = this.detectMetaDescription(textElements);
3126
+ if (metaIssue) {
3127
+ issues.push(metaIssue);
3128
+ }
3129
+ const repetitiveIssue = this.detectRepetitivePattern(textElements);
3130
+ if (repetitiveIssue) {
3131
+ issues.push(repetitiveIssue);
3132
+ }
3133
+ return { isValid: issues.length === 0, issues };
3134
+ }
3135
+ /**
3136
+ * Detect known placeholder / filler text in elements.
3137
+ */
3138
+ static detectPlaceholderText(elements) {
3139
+ const affectedElements = [];
3140
+ for (const el of elements) {
3141
+ for (const pattern of PLACEHOLDER_PATTERNS) {
3142
+ if (pattern.test(el.content)) {
3143
+ affectedElements.push(el.order);
3144
+ break;
3145
+ }
3146
+ }
3147
+ }
3148
+ if (affectedElements.length === 0) return null;
3149
+ return {
3150
+ type: "placeholder_text",
3151
+ message: `Detected placeholder text (e.g., Lorem ipsum) in ${affectedElements.length} element(s)`,
3152
+ affectedElements
3153
+ };
3154
+ }
3155
+ /**
3156
+ * Detect script anomaly: expected Korean content but found mostly Latin text.
3157
+ * Counts Hangul + CJK characters and flags if the ratio is below threshold.
3158
+ */
3159
+ static detectScriptAnomaly(elements) {
3160
+ const allContent = elements.map((el) => el.content).join("");
3161
+ const nonWhitespace = allContent.replace(/\s/g, "");
3162
+ if (nonWhitespace.length < MIN_CONTENT_LENGTH) {
3163
+ return null;
3164
+ }
3165
+ const hangulCount = allContent.match(HANGUL_REGEX2)?.length ?? 0;
3166
+ const cjkCount = allContent.match(CJK_REGEX2)?.length ?? 0;
3167
+ const koreanCjkCount = hangulCount + cjkCount;
3168
+ const ratio = koreanCjkCount / nonWhitespace.length;
3169
+ if (ratio < KOREAN_SCRIPT_RATIO_THRESHOLD) {
3170
+ return {
3171
+ type: "script_anomaly",
3172
+ message: `Expected Korean text but found ${(ratio * 100).toFixed(1)}% Korean/CJK characters (threshold: ${KOREAN_SCRIPT_RATIO_THRESHOLD * 100}%)`,
3173
+ affectedElements: elements.map((el) => el.order)
3174
+ };
3175
+ }
3176
+ return null;
3177
+ }
3178
+ /**
3179
+ * Detect meta description: VLM described the image/resolution instead
3180
+ * of transcribing actual text content.
3181
+ */
3182
+ static detectMetaDescription(elements) {
3183
+ const affectedElements = [];
3184
+ const allPatterns = [
3185
+ ...META_DESCRIPTION_PATTERNS_KO,
3186
+ ...META_DESCRIPTION_PATTERNS_EN
3187
+ ];
3188
+ for (const el of elements) {
3189
+ for (const pattern of allPatterns) {
3190
+ if (pattern.test(el.content)) {
3191
+ affectedElements.push(el.order);
3192
+ break;
3193
+ }
3194
+ }
3195
+ }
3196
+ if (affectedElements.length === 0) return null;
3197
+ return {
3198
+ type: "meta_description",
3199
+ message: `Detected meta-description of image instead of text transcription in ${affectedElements.length} element(s)`,
3200
+ affectedElements
3201
+ };
3202
+ }
3203
+ /**
3204
+ * Detect repetitive character patterns (e.g., `: : : : :` or `= = = = =`).
3205
+ * Flags when the same character repeats with spaces 5+ times and the
3206
+ * repetitive portion exceeds 30% of total content.
3207
+ */
3208
+ static detectRepetitivePattern(elements) {
3209
+ const allContent = elements.map((el) => el.content).join("\n");
3210
+ if (allContent.trim().length === 0) return null;
3211
+ const repetitiveRegex = /(\S)(\s+\1){4,}/g;
3212
+ let totalRepetitiveLength = 0;
3213
+ let match;
3214
+ while ((match = repetitiveRegex.exec(allContent)) !== null) {
3215
+ const repeatedChar = match[1];
3216
+ const segment = match[0];
3217
+ const parts = segment.split(/\s+/).filter((p) => p === repeatedChar);
3218
+ if (parts.length >= REPETITIVE_PATTERN_MIN_REPEATS) {
3219
+ totalRepetitiveLength += segment.length;
3220
+ }
3221
+ }
3222
+ if (totalRepetitiveLength === 0) return null;
3223
+ const ratio = totalRepetitiveLength / allContent.length;
3224
+ if (ratio < REPETITIVE_PATTERN_RATIO_THRESHOLD) return null;
3225
+ return {
3226
+ type: "repetitive_pattern",
3227
+ message: `Detected repetitive character patterns (${(ratio * 100).toFixed(0)}% of content)`,
3228
+ affectedElements: elements.map((el) => el.order)
3229
+ };
3230
+ }
3231
+ };
1588
3232
  // Annotate the CommonJS export names for ESM import in node:
1589
3233
  0 && (module.exports = {
1590
- DEFAULT_VLM_MODEL,
1591
3234
  ImagePdfFallbackError,
1592
3235
  PDFParser,
1593
- VLM_MODELS,
1594
- resolveVlmModel
3236
+ VlmResponseValidator
1595
3237
  });
1596
3238
  //# sourceMappingURL=index.cjs.map