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