@exulu/backend 5.13.0 → 5.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,8 @@ import { LiteParse } from '@llamaindex/liteparse';
16
16
  import { resolveOcr } from '@SRC/exulu/resolve-ocr';
17
17
  import type { ResolveOcrInput } from '@SRC/exulu/resolve-ocr';
18
18
  import { resolveModel } from '@SRC/exulu/resolve-model';
19
+ import type { ProgressFn } from '@SRC/exulu/document-cache/progress';
20
+ import { ocrConcurrency, type ProviderLimiters } from './limits';
19
21
 
20
22
  export type DocumentProcessorConfig = {
21
23
  vlm?: {
@@ -29,6 +31,14 @@ export type DocumentProcessorConfig = {
29
31
  model: string;
30
32
  concurrency: number;
31
33
  },
34
+ /**
35
+ * OCR settings. `concurrency` is how many OCR chunk calls ONE document runs
36
+ * at once (default 3, 1..8). Reads in chat additionally share a process-wide
37
+ * ceiling of 8 (see limits.ts); knowledge-base processing does not.
38
+ */
39
+ ocr?: {
40
+ concurrency?: number;
41
+ }
32
42
  processor: {
33
43
  name: "liteparse" | "mistral" | "officeparser"
34
44
  /**
@@ -67,6 +77,8 @@ export type ProcessedPage = {
67
77
  image?: string;
68
78
  vlm_corrected_text?: string;
69
79
  vlm_validated?: boolean;
80
+ /** Set only under tolerateVisionFailures: the vision pass failed for this page, the text is OCR only. */
81
+ vlm_failed?: boolean;
70
82
  }
71
83
  export type ProcessedDocument = ProcessedPage[];
72
84
 
@@ -163,6 +175,9 @@ async function processImage(
163
175
  paths: ProcessingPaths,
164
176
  config?: DocumentProcessorConfig,
165
177
  verbose: boolean = false,
178
+ tolerateVisionFailures: boolean = false,
179
+ onProgress?: ProgressFn,
180
+ limiters?: ProviderLimiters,
166
181
  ): Promise<ProcessorOutput> {
167
182
  try {
168
183
  // Create images directory
@@ -191,7 +206,10 @@ async function processImage(
191
206
  json,
192
207
  vlmModel,
193
208
  verbose,
194
- config!.vlm!.concurrency
209
+ config!.vlm!.concurrency,
210
+ tolerateVisionFailures,
211
+ onProgress,
212
+ limiters,
195
213
  );
196
214
 
197
215
  // Save the processed result
@@ -311,12 +329,14 @@ function reconstructHeadings(
311
329
  }
312
330
 
313
331
  /**
314
- * Validates and potentially corrects all chunks from a page using VLM
332
+ * Validates and potentially corrects all chunks from a page using VLM.
333
+ * `timeoutMs` is set on the chat path only (see ProviderLimiters.visionTimeoutMs).
315
334
  */
316
335
  async function validatePageWithVLM(
317
336
  page: ProcessedPage,
318
337
  imagePath: string,
319
- model: LanguageModel
338
+ model: LanguageModel,
339
+ timeoutMs?: number,
320
340
  ): Promise<VLMValidationResult> {
321
341
  // Read the image as base64
322
342
  const imageBuffer = await fs.promises.readFile(imagePath);
@@ -401,6 +421,8 @@ If the page contains a flow-chart, schematic, technical drawing or control board
401
421
 
402
422
  const result = await generateText({
403
423
  model: model,
424
+ // Chat path only: a stalled provider must not pin a slot. Without it the SDK default applies, as before.
425
+ ...(timeoutMs ? { abortSignal: AbortSignal.timeout(timeoutMs) } : {}),
404
426
  output: Output.object({
405
427
  schema: z.object({
406
428
  needs_correction: z.boolean(),
@@ -455,7 +477,7 @@ If the page contains a flow-chart, schematic, technical drawing or control board
455
477
  /**
456
478
  * Reconstructs table headers across pages sequentially after parallel VLM processing
457
479
  */
458
- function reconstructTableHeaders(
480
+ export function reconstructTableHeaders(
459
481
  document: ProcessedDocument,
460
482
  validationResults: Map<number, VLMValidationResult>,
461
483
  verbose: boolean = false
@@ -464,6 +486,11 @@ function reconstructTableHeaders(
464
486
 
465
487
  for (const page of document) {
466
488
  const validation = validationResults.get(page.page);
489
+ if (page.vlm_failed) {
490
+ // Nothing is known about this page's table, so headers carried from before it must not reach later pages.
491
+ lastTableHeaders = undefined;
492
+ continue;
493
+ }
467
494
  if (!validation) continue;
468
495
 
469
496
  const tableInfo = validation.current_page_table;
@@ -524,6 +551,24 @@ function reconstructTableHeaders(
524
551
  }
525
552
  }
526
553
 
554
+ /** Progress is advisory: a throwing callback must never touch processing. */
555
+ function safeProgress(onProgress: ProgressFn | undefined, p: Parameters<ProgressFn>[0]): void {
556
+ try {
557
+ onProgress?.(p);
558
+ } catch (error) {
559
+ console.warn('[EXULU] onProgress callback threw; ignored:', error instanceof Error ? error.message : String(error));
560
+ }
561
+ }
562
+
563
+ /** Whether a page gets a vision pass: it has an image and either no text yet or an image/table in its text. */
564
+ function needsVisionPass(page: ProcessedPage): boolean {
565
+ if (!page.image) return false;
566
+ if (!page.content) return true;
567
+ const hasImage = page.content.match(/\.(jpeg|jpg|png|gif|webp)/i);
568
+ const hasTable = (page.content.match(/\|/g)?.length || 0) > 1;
569
+ return Boolean(hasImage || hasTable);
570
+ }
571
+
527
572
  /**
528
573
  * Identifies pages that need VLM validation and validates them in parallel
529
574
  */
@@ -531,7 +576,10 @@ async function validateWithVLM(
531
576
  document: ProcessedDocument,
532
577
  model: LanguageModel,
533
578
  verbose: boolean = false,
534
- concurrency: number = 10
579
+ concurrency: number = 10,
580
+ tolerateVisionFailures: boolean = false,
581
+ onProgress?: ProgressFn,
582
+ limiters?: ProviderLimiters,
535
583
  ): Promise<ProcessedDocument> {
536
584
  console.log(`[EXULU] Starting VLM validation for processor output, ${document.length} pages...`);
537
585
  console.log(`[EXULU] Concurrency limit: ${concurrency}`);
@@ -542,6 +590,14 @@ async function validateWithVLM(
542
590
  // Store validation results for post-processing
543
591
  const validationResults = new Map<number, VLMValidationResult>();
544
592
 
593
+ // Progress counts the pages that actually get a vision pass.
594
+ const visionTotal = document.filter(needsVisionPass).length;
595
+ let visionDone = 0;
596
+ const reportVisionPage = () => {
597
+ visionDone++;
598
+ safeProgress(onProgress, { phase: "vision", pagesDone: visionDone, pagesTotal: visionTotal });
599
+ };
600
+
545
601
  // Track metrics
546
602
  let validatedCount = 0;
547
603
  let correctedCount = 0;
@@ -586,11 +642,14 @@ async function validateWithVLM(
586
642
  try {
587
643
  console.log(`[EXULU] Validating page ${page.page} with VLM`);
588
644
  validation = await withRetry(async () => {
589
- return await validatePageWithVLM(page, imagePath, model);
645
+ // Process-wide ceiling (chat paths only), taken per attempt so a retry queues again.
646
+ const attempt = () => validatePageWithVLM(page, imagePath, model, limiters?.visionTimeoutMs);
647
+ return await (limiters ? limiters.vision(attempt) : attempt());
590
648
  }, 3);
591
649
 
592
650
  // Store validation result for post-processing
593
651
  validationResults.set(page.page, validation);
652
+ reportVisionPage();
594
653
 
595
654
  if (verbose && validation.current_page_table) {
596
655
  console.log(`[EXULU] Page ${page.page} table info:`, {
@@ -600,6 +659,12 @@ async function validateWithVLM(
600
659
  }
601
660
  } catch (error) {
602
661
  console.error(`[EXULU] Error validating page ${page.page} with VLM more than 3 times, skipping:`, error);
662
+ if (tolerateVisionFailures) {
663
+ // The page keeps its OCR text; the caller reports it as unverified.
664
+ page.vlm_failed = true;
665
+ reportVisionPage();
666
+ return;
667
+ }
603
668
  // Throw so the job fails
604
669
  throw error;
605
670
  }
@@ -667,6 +732,9 @@ async function processDocument(
667
732
  tempDir: string,
668
733
  config?: DocumentProcessorConfig,
669
734
  verbose: boolean = false,
735
+ tolerateVisionFailures: boolean = false,
736
+ onProgress?: ProgressFn,
737
+ limiters?: ProviderLimiters,
670
738
  ): Promise<{
671
739
  content: {
672
740
  markdown: string,
@@ -712,7 +780,7 @@ async function processDocument(
712
780
  };
713
781
  break;
714
782
  case 'pdf':
715
- result = await processPdf(buffer, paths, config, verbose);
783
+ result = await processPdf(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
716
784
  break;
717
785
  case 'docx':
718
786
  result = await processDocx(buffer);
@@ -725,7 +793,7 @@ async function processDocument(
725
793
  case 'png':
726
794
  case 'gif':
727
795
  case 'webp':
728
- result = await processImage(buffer, paths, config, verbose);
796
+ result = await processImage(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
729
797
  break;
730
798
 
731
799
  // Todo other file types with docx and officeparser
@@ -746,6 +814,9 @@ async function processPdf(
746
814
  paths: ProcessingPaths,
747
815
  config?: DocumentProcessorConfig,
748
816
  verbose: boolean = false,
817
+ tolerateVisionFailures: boolean = false,
818
+ onProgress?: ProgressFn,
819
+ limiters?: ProviderLimiters,
749
820
  ): Promise<ProcessorOutput> {
750
821
  try {
751
822
  let json: ProcessedDocument = [];
@@ -770,6 +841,8 @@ async function processPdf(
770
841
  const resolved = await resolveOcr({
771
842
  model: config.processor.model ?? "mistral-ocr",
772
843
  ...config.attribution,
844
+ // Chat path only; knowledge-base processing passes no limiters and gets no explicit timeout.
845
+ ...(limiters?.ocrTimeoutMs ? { timeoutMs: limiters.ocrTimeoutMs } : {}),
773
846
  });
774
847
 
775
848
  // Split the PDF into ≤ N-page chunks before sending to OCR.
@@ -806,7 +879,9 @@ async function processPdf(
806
879
 
807
880
  // Process chunks in parallel with a concurrency cap to respect rate limits.
808
881
  // Each chunk gets a small random jitter to spread out requests.
809
- const chunkLimit = pLimit(3);
882
+ const chunkLimit = pLimit(ocrConcurrency(config));
883
+ const ocrTotal = pdfChunks.reduce((sum, c) => sum + (c.end_page - c.start_page), 0);
884
+ let ocrDone = 0;
810
885
 
811
886
  const chunkResults = await Promise.all(
812
887
  pdfChunks.map((chunk, i) =>
@@ -821,12 +896,20 @@ async function processPdf(
821
896
  const chunkBase64 = chunkBuffer.toString('base64');
822
897
 
823
898
  const chunkResponse = await withRetry(async () => {
824
- return await resolved.ocr({
899
+ // With limiters (chat paths) the per-document slot (chunkLimit) is held while
900
+ // this waits for the process-wide slot; the process-wide queue never waits on
901
+ // a per-document one, so the nesting cannot deadlock.
902
+ const attempt = () => resolved.ocr({
825
903
  type: "document_url",
826
904
  document_url: "data:application/pdf;base64," + chunkBase64,
827
905
  }, { includeImageBase64: false });
906
+ return await (limiters ? limiters.ocr(attempt) : attempt());
828
907
  }, 10);
829
908
 
909
+ // Chunks finish out of order; the shared counter keeps the reported count monotonic.
910
+ ocrDone += chunk.end_page - chunk.start_page;
911
+ safeProgress(onProgress, { phase: "ocr", pagesDone: ocrDone, pagesTotal: ocrTotal });
912
+
830
913
  return { pages: chunkResponse.pages, offset: chunk.start_page };
831
914
  })
832
915
  )
@@ -915,7 +998,10 @@ async function processPdf(
915
998
  json,
916
999
  vlmModel,
917
1000
  verbose,
918
- config!.vlm!.concurrency
1001
+ config!.vlm!.concurrency,
1002
+ tolerateVisionFailures,
1003
+ onProgress,
1004
+ limiters,
919
1005
  );
920
1006
 
921
1007
  console.log('[EXULU] \n📊 Processing Summary:');
@@ -980,6 +1066,7 @@ async function processPdf(
980
1066
  return {
981
1067
  page: e.page,
982
1068
  content: finalContent,
1069
+ ...(e.vlm_failed ? { vlm_failed: true } : {}),
983
1070
  };
984
1071
  });
985
1072
 
@@ -1046,11 +1133,23 @@ const loadFile = async (
1046
1133
  export async function documentProcessor({
1047
1134
  file,
1048
1135
  name,
1049
- config
1136
+ config,
1137
+ tolerateVisionFailures,
1138
+ onProgress,
1139
+ limiters,
1050
1140
  }: {
1051
1141
  file: string | Buffer;
1052
1142
  name: string;
1053
1143
  config?: DocumentProcessorConfig;
1144
+ /** A page whose vision pass failed keeps its OCR text and is flagged `vlm_failed` instead of failing the document. */
1145
+ tolerateVisionFailures?: boolean;
1146
+ /** Reports OCR progress per finished chunk and vision progress per finished page. */
1147
+ onProgress?: ProgressFn;
1148
+ /**
1149
+ * Process-wide ceilings on OCR and vision calls. Passed by the chat paths only (extractDocument);
1150
+ * absent for knowledge-base processing, which keeps its per-document limits unchanged.
1151
+ */
1152
+ limiters?: ProviderLimiters;
1054
1153
  }): Promise<ProcessedDocument | undefined> {
1055
1154
 
1056
1155
  const license = checkLicense()
@@ -1106,7 +1205,10 @@ export async function documentProcessor({
1106
1205
  buffer,
1107
1206
  tempDir,
1108
1207
  config,
1109
- true
1208
+ true,
1209
+ tolerateVisionFailures,
1210
+ onProgress,
1211
+ limiters,
1110
1212
  );
1111
1213
 
1112
1214
  return content.json;
@@ -0,0 +1,35 @@
1
+ import { ocrConcurrency, ocrLimiter, visionLimiter, PROCESS_WIDE_LIMIT } from "./limits";
2
+
3
+ describe("ocrConcurrency", () => {
4
+ it("defaults to 3", () => {
5
+ expect(ocrConcurrency(undefined)).toBe(3);
6
+ expect(ocrConcurrency({})).toBe(3);
7
+ expect(ocrConcurrency({ ocr: {} })).toBe(3);
8
+ });
9
+ it("reads documentProcessor.ocr.concurrency and clamps to 1..8", () => {
10
+ expect(ocrConcurrency({ ocr: { concurrency: 5 } })).toBe(5);
11
+ expect(ocrConcurrency({ ocr: { concurrency: 0 } })).toBe(1);
12
+ expect(ocrConcurrency({ ocr: { concurrency: 99 } })).toBe(8);
13
+ expect(ocrConcurrency({ ocr: { concurrency: 2.7 } })).toBe(3);
14
+ expect(ocrConcurrency({ ocr: { concurrency: Number.NaN } })).toBe(3);
15
+ });
16
+ });
17
+
18
+ describe("process-wide limiters", () => {
19
+ it.each([["ocr", ocrLimiter], ["vision", visionLimiter]] as const)("%s limiter queues beyond 8 slots instead of refusing", async (_n, limiter) => {
20
+ expect(PROCESS_WIDE_LIMIT).toBe(8);
21
+ let running = 0;
22
+ let max = 0;
23
+ await Promise.all(
24
+ Array.from({ length: 30 }, () =>
25
+ limiter(async () => {
26
+ running++;
27
+ max = Math.max(max, running);
28
+ await new Promise((r) => setTimeout(r, 5));
29
+ running--;
30
+ }),
31
+ ),
32
+ );
33
+ expect(max).toBe(8);
34
+ });
35
+ });
@@ -0,0 +1,54 @@
1
+ import pLimit from "p-limit";
2
+
3
+ /**
4
+ * Process-wide ceilings on provider calls made by the document processor.
5
+ * They apply ONLY to extractions that opt in by passing `processWideLimiters`
6
+ * to `documentProcessor` (the chat paths via extractDocument: parse_document and
7
+ * inline attachments), so two long documents read in chat at once cannot
8
+ * multiply the load on the OCR / vision endpoints. Knowledge-base processing
9
+ * calls the processor directly without them and keeps its own per-document
10
+ * limits (ocr.concurrency, vlm.concurrency) unchanged. Calls beyond the
11
+ * ceiling queue; they are never refused. Per-document limiters (ocrConcurrency, the
12
+ * VLM concurrency setting) sit OUTSIDE these and wrap a function that awaits
13
+ * them, which cannot deadlock: a queued call holds only its per-document slot.
14
+ *
15
+ * Kept free of imports beyond p-limit so it loads on an unlicensed boot.
16
+ */
17
+ export const PROCESS_WIDE_LIMIT = 8;
18
+ export const DEFAULT_OCR_CONCURRENCY = 3;
19
+
20
+ export const ocrLimiter = pLimit(PROCESS_WIDE_LIMIT);
21
+ export const visionLimiter = pLimit(PROCESS_WIDE_LIMIT);
22
+
23
+ /** Runs `fn` under a ceiling. */
24
+ export type ProviderLimiter = <T>(fn: () => Promise<T>) => Promise<T>;
25
+ /**
26
+ * What the chat paths pass to documentProcessor. The call time limits travel with the limiters:
27
+ * a stalled provider must not pin chat slots, while knowledge-base processing (which passes
28
+ * none) keeps the transport's own, longer limit exactly as before.
29
+ */
30
+ export type ProviderLimiters = {
31
+ ocr: ProviderLimiter;
32
+ vision: ProviderLimiter;
33
+ /** Longest one OCR request may take; a timeout counts as a failed attempt for the retry logic. */
34
+ ocrTimeoutMs?: number;
35
+ /** Longest one vision (page validation) call may take; same retry treatment. */
36
+ visionTimeoutMs?: number;
37
+ };
38
+
39
+ export const OCR_CALL_TIMEOUT_MS = 180_000;
40
+ export const VISION_CALL_TIMEOUT_MS = 120_000;
41
+
42
+ export const processWideLimiters: ProviderLimiters = {
43
+ ocr: ocrLimiter,
44
+ vision: visionLimiter,
45
+ ocrTimeoutMs: OCR_CALL_TIMEOUT_MS,
46
+ visionTimeoutMs: VISION_CALL_TIMEOUT_MS,
47
+ };
48
+
49
+ /** Per-document OCR concurrency from `documentProcessor.ocr.concurrency`: default 3, clamped to 1..8. */
50
+ export function ocrConcurrency(config?: { ocr?: { concurrency?: number } }): number {
51
+ const raw = config?.ocr?.concurrency;
52
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return DEFAULT_OCR_CONCURRENCY;
53
+ return Math.min(PROCESS_WIDE_LIMIT, Math.max(1, Math.round(raw)));
54
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.13.0",
4
+ "version": "5.14.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {
@@ -1,10 +0,0 @@
1
- import "dotenv/config";
2
- import {
3
- documentProcessor
4
- } from "./chunk-RNZ4IDCT.js";
5
- import "./chunk-JIZCKSJO.js";
6
- import "./chunk-4W3V7IHR.js";
7
- import "./chunk-6URU62NI.js";
8
- export {
9
- documentProcessor
10
- };