@exulu/backend 5.12.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.
@@ -6,11 +6,12 @@ import {
6
6
  buildTags,
7
7
  checkLicense,
8
8
  isLiteLLMEnabled,
9
+ ocrConcurrency,
9
10
  provisionDefaultUserBudget,
10
11
  resolveModel,
11
12
  waitForLiteLLMReady,
12
13
  withRetry
13
- } from "./chunk-4W3V7IHR.js";
14
+ } from "./chunk-NBDSN45T.js";
14
15
  import {
15
16
  resolveLiteLLMTarget
16
17
  } from "./chunk-6URU62NI.js";
@@ -179,7 +180,7 @@ var ResolveOcrError = class extends Error {
179
180
  }
180
181
  };
181
182
  async function resolveOcr(input) {
182
- const { model, contextId, contextName, user, userId, roleId, project, agent, routine } = input;
183
+ const { model, contextId, contextName, user, userId, roleId, project, agent, routine, timeoutMs } = input;
183
184
  if (!isLiteLLMEnabled()) {
184
185
  throw new ResolveOcrError(
185
186
  "LITELLM_NOT_CONFIGURED",
@@ -218,6 +219,7 @@ async function resolveOcr(input) {
218
219
  const ocr = async (document, opts) => {
219
220
  const res = await fetch(endpoint, {
220
221
  method: "POST",
222
+ ...timeoutMs ? { signal: AbortSignal.timeout(timeoutMs) } : {},
221
223
  headers: {
222
224
  ...authHeaders,
223
225
  "Content-Type": "application/json"
@@ -294,7 +296,7 @@ async function resolveVlmModel(config) {
294
296
  });
295
297
  return languageModel;
296
298
  }
297
- async function processImage(buffer, paths, config, verbose = false) {
299
+ async function processImage(buffer, paths, config, verbose = false, tolerateVisionFailures = false, onProgress, limiters) {
298
300
  try {
299
301
  await fs.promises.mkdir(paths.images, { recursive: true });
300
302
  const imagePath = path.join(paths.images, "1.png");
@@ -314,7 +316,10 @@ async function processImage(buffer, paths, config, verbose = false) {
314
316
  json,
315
317
  vlmModel,
316
318
  verbose,
317
- config.vlm.concurrency
319
+ config.vlm.concurrency,
320
+ tolerateVisionFailures,
321
+ onProgress,
322
+ limiters
318
323
  );
319
324
  await fs.promises.writeFile(
320
325
  paths.json,
@@ -386,7 +391,7 @@ function reconstructHeadings(correctedText, headingsHierarchy) {
386
391
  }
387
392
  return result;
388
393
  }
389
- async function validatePageWithVLM(page, imagePath, model) {
394
+ async function validatePageWithVLM(page, imagePath, model, timeoutMs) {
390
395
  const imageBuffer = await fs.promises.readFile(imagePath);
391
396
  const imageBase64 = imageBuffer.toString("base64");
392
397
  const mimeType = "image/png";
@@ -467,6 +472,8 @@ If the page contains a flow-chart, schematic, technical drawing or control board
467
472
  `;
468
473
  const result = await generateText({
469
474
  model,
475
+ // Chat path only: a stalled provider must not pin a slot. Without it the SDK default applies, as before.
476
+ ...timeoutMs ? { abortSignal: AbortSignal.timeout(timeoutMs) } : {},
470
477
  output: Output.object({
471
478
  schema: z.object({
472
479
  needs_correction: z.boolean(),
@@ -507,6 +514,10 @@ function reconstructTableHeaders(document, validationResults, verbose = false) {
507
514
  let lastTableHeaders = void 0;
508
515
  for (const page of document) {
509
516
  const validation = validationResults.get(page.page);
517
+ if (page.vlm_failed) {
518
+ lastTableHeaders = void 0;
519
+ continue;
520
+ }
510
521
  if (!validation) continue;
511
522
  const tableInfo = validation.current_page_table;
512
523
  if (tableInfo && tableInfo.headers.length > 0) {
@@ -547,11 +558,31 @@ function reconstructTableHeaders(document, validationResults, verbose = false) {
547
558
  }
548
559
  }
549
560
  }
550
- async function validateWithVLM(document, model, verbose = false, concurrency = 10) {
561
+ function safeProgress(onProgress, p) {
562
+ try {
563
+ onProgress?.(p);
564
+ } catch (error) {
565
+ console.warn("[EXULU] onProgress callback threw; ignored:", error instanceof Error ? error.message : String(error));
566
+ }
567
+ }
568
+ function needsVisionPass(page) {
569
+ if (!page.image) return false;
570
+ if (!page.content) return true;
571
+ const hasImage = page.content.match(/\.(jpeg|jpg|png|gif|webp)/i);
572
+ const hasTable = (page.content.match(/\|/g)?.length || 0) > 1;
573
+ return Boolean(hasImage || hasTable);
574
+ }
575
+ async function validateWithVLM(document, model, verbose = false, concurrency = 10, tolerateVisionFailures = false, onProgress, limiters) {
551
576
  console.log(`[EXULU] Starting VLM validation for processor output, ${document.length} pages...`);
552
577
  console.log(`[EXULU] Concurrency limit: ${concurrency}`);
553
578
  const limit = pLimit(concurrency);
554
579
  const validationResults = /* @__PURE__ */ new Map();
580
+ const visionTotal = document.filter(needsVisionPass).length;
581
+ let visionDone = 0;
582
+ const reportVisionPage = () => {
583
+ visionDone++;
584
+ safeProgress(onProgress, { phase: "vision", pagesDone: visionDone, pagesTotal: visionTotal });
585
+ };
555
586
  let validatedCount = 0;
556
587
  let correctedCount = 0;
557
588
  const validationTasks = document.map(
@@ -580,9 +611,11 @@ async function validateWithVLM(document, model, verbose = false, concurrency = 1
580
611
  try {
581
612
  console.log(`[EXULU] Validating page ${page.page} with VLM`);
582
613
  validation = await withRetry(async () => {
583
- return await validatePageWithVLM(page, imagePath, model);
614
+ const attempt = () => validatePageWithVLM(page, imagePath, model, limiters?.visionTimeoutMs);
615
+ return await (limiters ? limiters.vision(attempt) : attempt());
584
616
  }, 3);
585
617
  validationResults.set(page.page, validation);
618
+ reportVisionPage();
586
619
  if (verbose && validation.current_page_table) {
587
620
  console.log(`[EXULU] Page ${page.page} table info:`, {
588
621
  headers: validation.current_page_table.headers,
@@ -591,6 +624,11 @@ async function validateWithVLM(document, model, verbose = false, concurrency = 1
591
624
  }
592
625
  } catch (error) {
593
626
  console.error(`[EXULU] Error validating page ${page.page} with VLM more than 3 times, skipping:`, error);
627
+ if (tolerateVisionFailures) {
628
+ page.vlm_failed = true;
629
+ reportVisionPage();
630
+ return;
631
+ }
594
632
  throw error;
595
633
  }
596
634
  if (validation.needs_correction && validation.corrected_text) {
@@ -627,7 +665,7 @@ async function validateWithVLM(document, model, verbose = false, concurrency = 1
627
665
  console.log(`[EXULU] Table header reconstruction complete`);
628
666
  return document;
629
667
  }
630
- async function processDocument(filePath, fileType, buffer, tempDir, config, verbose = false) {
668
+ async function processDocument(filePath, fileType, buffer, tempDir, config, verbose = false, tolerateVisionFailures = false, onProgress, limiters) {
631
669
  console.log("Starting document processing...");
632
670
  console.log(`${fileType}: ${filePath}`);
633
671
  const paths = {
@@ -653,7 +691,7 @@ async function processDocument(filePath, fileType, buffer, tempDir, config, verb
653
691
  };
654
692
  break;
655
693
  case "pdf":
656
- result = await processPdf(buffer, paths, config, verbose);
694
+ result = await processPdf(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
657
695
  break;
658
696
  case "docx":
659
697
  result = await processDocx(buffer);
@@ -666,7 +704,7 @@ async function processDocument(filePath, fileType, buffer, tempDir, config, verb
666
704
  case "png":
667
705
  case "gif":
668
706
  case "webp":
669
- result = await processImage(buffer, paths, config, verbose);
707
+ result = await processImage(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
670
708
  break;
671
709
  // Todo other file types with docx and officeparser
672
710
  default:
@@ -680,7 +718,7 @@ async function processDocument(filePath, fileType, buffer, tempDir, config, verb
680
718
  }
681
719
  };
682
720
  }
683
- async function processPdf(buffer, paths, config, verbose = false) {
721
+ async function processPdf(buffer, paths, config, verbose = false, tolerateVisionFailures = false, onProgress, limiters) {
684
722
  try {
685
723
  let json = [];
686
724
  if (config?.processor.name === "officeparser") {
@@ -696,7 +734,9 @@ async function processPdf(buffer, paths, config, verbose = false) {
696
734
  } else if (config?.processor.name === "mistral") {
697
735
  const resolved = await resolveOcr({
698
736
  model: config.processor.model ?? "mistral-ocr",
699
- ...config.attribution
737
+ ...config.attribution,
738
+ // Chat path only; knowledge-base processing passes no limiters and gets no explicit timeout.
739
+ ...limiters?.ocrTimeoutMs ? { timeoutMs: limiters.ocrTimeoutMs } : {}
700
740
  });
701
741
  const maxPagesPerChunk = config.processor.maxPagesPerChunk ?? 25;
702
742
  const chunksDir = path.join(path.dirname(paths.json), "ocr_chunks");
@@ -716,7 +756,9 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
716
756
  );
717
757
  }
718
758
  console.log(`[EXULU] PDF split into ${pdfChunks.length} chunk(s) for OCR (max ${maxPagesPerChunk} pages each)`);
719
- const chunkLimit = pLimit(3);
759
+ const chunkLimit = pLimit(ocrConcurrency(config));
760
+ const ocrTotal = pdfChunks.reduce((sum, c) => sum + (c.end_page - c.start_page), 0);
761
+ let ocrDone = 0;
720
762
  const chunkResults = await Promise.all(
721
763
  pdfChunks.map(
722
764
  (chunk, i) => chunkLimit(async () => {
@@ -726,11 +768,14 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
726
768
  const chunkBuffer = await fs.promises.readFile(chunk.path);
727
769
  const chunkBase64 = chunkBuffer.toString("base64");
728
770
  const chunkResponse = await withRetry(async () => {
729
- return await resolved.ocr({
771
+ const attempt = () => resolved.ocr({
730
772
  type: "document_url",
731
773
  document_url: "data:application/pdf;base64," + chunkBase64
732
774
  }, { includeImageBase64: false });
775
+ return await (limiters ? limiters.ocr(attempt) : attempt());
733
776
  }, 10);
777
+ ocrDone += chunk.end_page - chunk.start_page;
778
+ safeProgress(onProgress, { phase: "ocr", pagesDone: ocrDone, pagesTotal: ocrTotal });
734
779
  return { pages: chunkResponse.pages, offset: chunk.start_page };
735
780
  })
736
781
  )
@@ -790,7 +835,10 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
790
835
  json,
791
836
  vlmModel,
792
837
  verbose,
793
- config.vlm.concurrency
838
+ config.vlm.concurrency,
839
+ tolerateVisionFailures,
840
+ onProgress,
841
+ limiters
794
842
  );
795
843
  console.log("[EXULU] \n\u{1F4CA} Processing Summary:");
796
844
  console.log(`[EXULU] Total pages: ${json.length}`);
@@ -834,7 +882,8 @@ stderr: ${splitResult.stderr.slice(-1e3)}`
834
882
  const finalContent = e.vlm_corrected_text ?? e.content;
835
883
  return {
836
884
  page: e.page,
837
- content: finalContent
885
+ content: finalContent,
886
+ ...e.vlm_failed ? { vlm_failed: true } : {}
838
887
  };
839
888
  });
840
889
  json.length = 0;
@@ -880,7 +929,10 @@ var loadFile = async (file, name, tempDir) => {
880
929
  async function documentProcessor({
881
930
  file,
882
931
  name,
883
- config
932
+ config,
933
+ tolerateVisionFailures,
934
+ onProgress,
935
+ limiters
884
936
  }) {
885
937
  const license = checkLicense();
886
938
  if (!license["advanced-document-processing"]) {
@@ -920,7 +972,10 @@ async function documentProcessor({
920
972
  buffer,
921
973
  tempDir,
922
974
  config,
923
- true
975
+ true,
976
+ tolerateVisionFailures,
977
+ onProgress,
978
+ limiters
924
979
  );
925
980
  return content.json;
926
981
  } catch (error) {
@@ -942,5 +997,6 @@ async function documentProcessor({
942
997
  }
943
998
 
944
999
  export {
1000
+ reconstructTableHeaders,
945
1001
  documentProcessor
946
1002
  };
@@ -1117,6 +1117,26 @@ async function resolveModel(input) {
1117
1117
  };
1118
1118
  }
1119
1119
 
1120
+ // ee/python/documents/processing/limits.ts
1121
+ import pLimit from "p-limit";
1122
+ var PROCESS_WIDE_LIMIT = 8;
1123
+ var DEFAULT_OCR_CONCURRENCY = 3;
1124
+ var ocrLimiter = pLimit(PROCESS_WIDE_LIMIT);
1125
+ var visionLimiter = pLimit(PROCESS_WIDE_LIMIT);
1126
+ var OCR_CALL_TIMEOUT_MS = 18e4;
1127
+ var VISION_CALL_TIMEOUT_MS = 12e4;
1128
+ var processWideLimiters = {
1129
+ ocr: ocrLimiter,
1130
+ vision: visionLimiter,
1131
+ ocrTimeoutMs: OCR_CALL_TIMEOUT_MS,
1132
+ visionTimeoutMs: VISION_CALL_TIMEOUT_MS
1133
+ };
1134
+ function ocrConcurrency(config) {
1135
+ const raw = config?.ocr?.concurrency;
1136
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return DEFAULT_OCR_CONCURRENCY;
1137
+ return Math.min(PROCESS_WIDE_LIMIT, Math.max(1, Math.round(raw)));
1138
+ }
1139
+
1120
1140
  // src/utils/with-retry.ts
1121
1141
  async function withRetry(generateFn, maxRetries = 3, opts = {}) {
1122
1142
  const { shouldRetry, baseDelayMs = 1e3 } = opts;
@@ -1162,5 +1182,7 @@ export {
1162
1182
  checkLicense,
1163
1183
  ResolveModelError,
1164
1184
  resolveModel,
1185
+ processWideLimiters,
1186
+ ocrConcurrency,
1165
1187
  withRetry
1166
1188
  };