@exulu/backend 5.7.2 → 5.8.1

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.
@@ -0,0 +1,946 @@
1
+ import "dotenv/config";
2
+ import {
3
+ validatePythonEnvironment
4
+ } from "./chunk-JIZCKSJO.js";
5
+ import {
6
+ buildTags,
7
+ checkLicense,
8
+ isLiteLLMEnabled,
9
+ provisionDefaultUserBudget,
10
+ resolveModel,
11
+ waitForLiteLLMReady,
12
+ withRetry
13
+ } from "./chunk-4W3V7IHR.js";
14
+ import {
15
+ resolveLiteLLMTarget
16
+ } from "./chunk-6URU62NI.js";
17
+
18
+ // ee/python/documents/processing/doc_processor.ts
19
+ import * as fs from "fs";
20
+ import * as path from "path";
21
+ import { generateText, Output } from "ai";
22
+ import { z } from "zod";
23
+ import pLimit from "p-limit";
24
+ import { randomUUID } from "crypto";
25
+ import * as mammoth from "mammoth";
26
+ import TurndownService from "turndown";
27
+ import WordExtractor from "word-extractor";
28
+ import { parseOfficeAsync } from "officeparser";
29
+
30
+ // src/utils/python-executor.ts
31
+ import { exec } from "child_process";
32
+ import { promisify } from "util";
33
+ import { resolve, join, dirname } from "path";
34
+ import { existsSync, readFileSync } from "fs";
35
+ import { fileURLToPath } from "url";
36
+ var execAsync = promisify(exec);
37
+ function getPackageRoot() {
38
+ const currentFile = fileURLToPath(import.meta.url);
39
+ let currentDir = dirname(currentFile);
40
+ let attempts = 0;
41
+ const maxAttempts = 10;
42
+ while (attempts < maxAttempts) {
43
+ const packageJsonPath = join(currentDir, "package.json");
44
+ if (existsSync(packageJsonPath)) {
45
+ try {
46
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
47
+ if (packageJson.name === "@exulu/backend") {
48
+ return currentDir;
49
+ }
50
+ } catch {
51
+ }
52
+ }
53
+ const parentDir = resolve(currentDir, "..");
54
+ if (parentDir === currentDir) {
55
+ break;
56
+ }
57
+ currentDir = parentDir;
58
+ attempts++;
59
+ }
60
+ return resolve(dirname(fileURLToPath(import.meta.url)), "../..");
61
+ }
62
+ var PythonEnvironmentError = class extends Error {
63
+ constructor(message) {
64
+ super(message);
65
+ this.name = "PythonEnvironmentError";
66
+ }
67
+ };
68
+ var PythonExecutionError = class extends Error {
69
+ stdout;
70
+ stderr;
71
+ exitCode;
72
+ constructor(message, stdout, stderr, exitCode) {
73
+ super(message);
74
+ this.name = "PythonExecutionError";
75
+ this.stdout = stdout;
76
+ this.stderr = stderr;
77
+ this.exitCode = exitCode;
78
+ }
79
+ };
80
+ function getVenvPath(packageRoot) {
81
+ return resolve(packageRoot, "ee/python/.venv");
82
+ }
83
+ function getPythonExecutable(packageRoot) {
84
+ const venvPath = getVenvPath(packageRoot);
85
+ return join(venvPath, "bin", "python");
86
+ }
87
+ async function validatePythonEnvironmentForExecution(packageRoot) {
88
+ const validation = await validatePythonEnvironment(packageRoot);
89
+ if (!validation.valid) {
90
+ throw new PythonEnvironmentError(validation.message);
91
+ }
92
+ }
93
+ async function executePythonScript(config) {
94
+ const {
95
+ scriptPath,
96
+ args = [],
97
+ packageRoot = getPackageRoot(),
98
+ cwd = process.cwd(),
99
+ timeout = 3e5,
100
+ // 5 minutes default
101
+ env = {},
102
+ validateEnvironment = true
103
+ } = config;
104
+ if (validateEnvironment) {
105
+ await validatePythonEnvironmentForExecution(packageRoot);
106
+ }
107
+ const resolvedScriptPath = resolve(packageRoot, scriptPath);
108
+ if (!existsSync(resolvedScriptPath)) {
109
+ throw new PythonExecutionError(
110
+ `Python script not found: ${resolvedScriptPath}`,
111
+ "",
112
+ "",
113
+ 1
114
+ );
115
+ }
116
+ const pythonExecutable = getPythonExecutable(packageRoot);
117
+ const quotedArgs = args.map((arg) => {
118
+ return arg.includes(" ") ? `"${arg}"` : arg;
119
+ });
120
+ const command = `${pythonExecutable} "${resolvedScriptPath}" ${quotedArgs.join(" ")}`;
121
+ try {
122
+ const { stdout, stderr } = await execAsync(command, {
123
+ cwd,
124
+ timeout,
125
+ env: {
126
+ ...process.env,
127
+ ...env,
128
+ // Ensure Python doesn't write bytecode files
129
+ PYTHONDONTWRITEBYTECODE: "1"
130
+ },
131
+ maxBuffer: 50 * 1024 * 1024
132
+ // 50MB buffer for output (increased from 10MB)
133
+ });
134
+ return {
135
+ stdout: stdout.trim(),
136
+ stderr: stderr.trim(),
137
+ exitCode: 0,
138
+ success: true
139
+ };
140
+ } catch (error) {
141
+ const stdout = error.stdout?.toString() ?? "";
142
+ const stderr = error.stderr?.toString() ?? "";
143
+ const exitCode = error.code ?? 1;
144
+ let errorMessage = `Python script execution failed: ${error.message}`;
145
+ if (stderr) {
146
+ errorMessage += `
147
+
148
+ Stderr:
149
+ ${stderr}`;
150
+ }
151
+ if (stdout) {
152
+ errorMessage += `
153
+
154
+ Stdout:
155
+ ${stdout}`;
156
+ }
157
+ errorMessage += `
158
+
159
+ Command executed:
160
+ ${command}`;
161
+ throw new PythonExecutionError(
162
+ errorMessage,
163
+ stdout,
164
+ stderr,
165
+ exitCode
166
+ );
167
+ }
168
+ }
169
+
170
+ // ee/python/documents/processing/doc_processor.ts
171
+ import { LiteParse } from "@llamaindex/liteparse";
172
+
173
+ // src/exulu/resolve-ocr.ts
174
+ var ResolveOcrError = class extends Error {
175
+ constructor(code, message) {
176
+ super(message);
177
+ this.code = code;
178
+ this.name = "ResolveOcrError";
179
+ }
180
+ };
181
+ async function resolveOcr(input) {
182
+ const { model, contextId, contextName, user, userId, roleId, project, agent, routine } = input;
183
+ if (!isLiteLLMEnabled()) {
184
+ throw new ResolveOcrError(
185
+ "LITELLM_NOT_CONFIGURED",
186
+ "resolveOcr requires EXULU_USE_LITELLM=true \u2014 OCR is served exclusively through the LiteLLM proxy."
187
+ );
188
+ }
189
+ try {
190
+ await waitForLiteLLMReady();
191
+ } catch (err) {
192
+ throw new ResolveOcrError(
193
+ "LITELLM_NOT_READY",
194
+ `LiteLLM is not ready: ${err.message}`
195
+ );
196
+ }
197
+ const { baseUrl, authHeaders } = resolveLiteLLMTarget();
198
+ const resolvedUserId = user?.id ?? userId;
199
+ if (resolvedUserId) await provisionDefaultUserBudget(resolvedUserId);
200
+ const role = user?.role;
201
+ const tags = buildTags({
202
+ user_id: resolvedUserId,
203
+ role_id: role?.id ?? roleId,
204
+ project_id: (project ?? user?.project)?.id,
205
+ agent_id: agent?.id,
206
+ team_id: user?.team?.id,
207
+ routine_id: routine?.id,
208
+ context_id: contextId,
209
+ user_name: !user ? void 0 : user.type === "api" ? user.firstname ?? user.email : user.email,
210
+ role_name: role?.name,
211
+ project_name: (project ?? user?.project)?.name,
212
+ agent_name: agent?.name,
213
+ team_name: user?.team?.name,
214
+ routine_name: routine?.name,
215
+ context_name: contextName
216
+ });
217
+ const endpoint = `${baseUrl}/v1/ocr`;
218
+ const ocr = async (document, opts) => {
219
+ const res = await fetch(endpoint, {
220
+ method: "POST",
221
+ headers: {
222
+ ...authHeaders,
223
+ "Content-Type": "application/json"
224
+ },
225
+ body: JSON.stringify({
226
+ model,
227
+ document,
228
+ // Mistral OCR optional params — only sent when provided.
229
+ ...opts?.pages ? { pages: opts.pages } : {},
230
+ ...opts?.includeImageBase64 !== void 0 ? { include_image_base64: opts.includeImageBase64 } : {},
231
+ ...opts?.imageLimit !== void 0 ? { image_limit: opts.imageLimit } : {},
232
+ ...opts?.imageMinSize !== void 0 ? { image_min_size: opts.imageMinSize } : {},
233
+ // LiteLLM reads metadata.tags for tag-based spend tracking — same
234
+ // mechanism createTaggedFetch / resolveEmbedder use.
235
+ metadata: { tags }
236
+ })
237
+ });
238
+ if (!res.ok) {
239
+ const text = await res.text().catch(() => "");
240
+ throw new Error(
241
+ `[EXULU] LiteLLM /v1/ocr returned ${res.status} for model "${model}": ${text}`
242
+ );
243
+ }
244
+ const json = await res.json();
245
+ if (!Array.isArray(json.pages)) {
246
+ throw new Error(
247
+ `[EXULU] LiteLLM /v1/ocr returned no pages for model "${model}".`
248
+ );
249
+ }
250
+ return json;
251
+ };
252
+ return { model, ocr };
253
+ }
254
+
255
+ // ee/python/documents/processing/doc_processor.ts
256
+ async function processDocx(file) {
257
+ const html = await mammoth.convertToHtml({ buffer: file });
258
+ const turndownService = new TurndownService();
259
+ let markdown = turndownService.turndown(html.value);
260
+ markdown = markdown.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
261
+ return {
262
+ json: [{
263
+ page: 1,
264
+ content: markdown,
265
+ headings: []
266
+ }],
267
+ markdown
268
+ };
269
+ }
270
+ async function processWord(file) {
271
+ const extractor = new WordExtractor();
272
+ const extracted = await extractor.extract(file);
273
+ let content = extracted.getBody();
274
+ content = content.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
275
+ return {
276
+ json: [{
277
+ page: 1,
278
+ content,
279
+ headings: []
280
+ }],
281
+ markdown: content
282
+ };
283
+ }
284
+ async function resolveVlmModel(config) {
285
+ const modelId = config?.vlm?.model;
286
+ if (!modelId) return void 0;
287
+ const { languageModel } = await resolveModel({
288
+ modelId,
289
+ user: config?.attribution?.user,
290
+ project: config?.attribution?.project,
291
+ agent: config?.attribution?.agent,
292
+ routine: config?.attribution?.routine,
293
+ rbacBypass: true
294
+ });
295
+ return languageModel;
296
+ }
297
+ async function processImage(buffer, paths, config, verbose = false) {
298
+ try {
299
+ await fs.promises.mkdir(paths.images, { recursive: true });
300
+ const imagePath = path.join(paths.images, "1.png");
301
+ await fs.promises.writeFile(imagePath, buffer);
302
+ console.log(`[EXULU] Image saved to: ${imagePath}`);
303
+ let json = [{
304
+ page: 1,
305
+ content: "",
306
+ // Empty initially, will be populated by VLM if enabled
307
+ image: imagePath,
308
+ headings: []
309
+ }];
310
+ const vlmModel = await resolveVlmModel(config);
311
+ if (vlmModel) {
312
+ console.log("[EXULU] Extracting content from image using VLM...");
313
+ json = await validateWithVLM(
314
+ json,
315
+ vlmModel,
316
+ verbose,
317
+ config.vlm.concurrency
318
+ );
319
+ await fs.promises.writeFile(
320
+ paths.json,
321
+ JSON.stringify(json, null, 2),
322
+ "utf-8"
323
+ );
324
+ console.log("[EXULU] VLM content extraction complete");
325
+ const correctedCount = json.filter((p) => p.vlm_corrected_text).length;
326
+ console.log(`[EXULU] Content extracted: ${correctedCount > 0 ? "Yes" : "No"}`);
327
+ } else {
328
+ console.log("[EXULU] No VLM configured, image saved without content extraction");
329
+ console.log("[EXULU] Note: Enable VLM in config to extract text/content from images");
330
+ await fs.promises.writeFile(
331
+ paths.json,
332
+ JSON.stringify(json, null, 2),
333
+ "utf-8"
334
+ );
335
+ }
336
+ const markdown = json.map((p) => p.vlm_corrected_text ?? p.content).join("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
337
+ await fs.promises.writeFile(paths.markdown, markdown, "utf-8");
338
+ return {
339
+ markdown,
340
+ json
341
+ };
342
+ } catch (error) {
343
+ console.error("[EXULU] Error processing image:", error);
344
+ throw error;
345
+ }
346
+ }
347
+ function normalizeMarkdownContent(content) {
348
+ const lines = content.split("\n");
349
+ const normalizedLines = [];
350
+ for (const line of lines) {
351
+ if (line.includes("|")) {
352
+ const parts = line.split("|");
353
+ const cleanedParts = parts.map((part) => part.trim());
354
+ const normalizedLine = cleanedParts.join(" | ");
355
+ normalizedLines.push(normalizedLine);
356
+ } else {
357
+ normalizedLines.push(line.trimEnd());
358
+ }
359
+ }
360
+ return normalizedLines.join("\n");
361
+ }
362
+ function reconstructHeadings(correctedText, headingsHierarchy) {
363
+ if (!headingsHierarchy || typeof headingsHierarchy !== "object") {
364
+ return correctedText;
365
+ }
366
+ let result = correctedText;
367
+ function extractHeadingsWithLevels(hierarchy, level = 2) {
368
+ const headings2 = [];
369
+ for (const [key, value] of Object.entries(hierarchy)) {
370
+ headings2.push({ text: key, level });
371
+ if (value && typeof value === "object") {
372
+ headings2.push(...extractHeadingsWithLevels(value, level + 1));
373
+ }
374
+ }
375
+ return headings2;
376
+ }
377
+ const headings = extractHeadingsWithLevels(headingsHierarchy);
378
+ for (const { text, level } of headings) {
379
+ const markdownPrefix = "#".repeat(level);
380
+ const escapedText = text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
381
+ const regex = new RegExp(
382
+ `^(${escapedText})$`,
383
+ "gm"
384
+ );
385
+ result = result.replace(regex, `${markdownPrefix} $1`);
386
+ }
387
+ return result;
388
+ }
389
+ async function validatePageWithVLM(page, imagePath, model) {
390
+ const imageBuffer = await fs.promises.readFile(imagePath);
391
+ const imageBase64 = imageBuffer.toString("base64");
392
+ const mimeType = "image/png";
393
+ const prompt = `You are a document validation assistant. Your task is to analyze a page image and correct the output of an OCR/parsing pipeline. The content may include tables, technical diagrams, schematics, and structured text.
394
+
395
+ ---
396
+ ## CURRENT OCR OUTPUT
397
+
398
+ ${page.content}
399
+ ---
400
+
401
+ ## YOUR TASK
402
+
403
+ Compare the page image to the OCR output above. Identify errors, omissions, and formatting issues, then return a structured validation result (see OUTPUT FORMAT below).
404
+
405
+ ---
406
+ ## VALIDATION CHECKLIST
407
+
408
+ Work through these checks in order:
409
+
410
+ ### 1. Text Accuracy
411
+ - Verify all text is correctly transcribed.
412
+ - For minor character-level OCR errors (e.g. "\xF6" vs "\xFC", "rn" vs "m"), **prefer the original OCR output** unless you are certain of an error. Do not silently "fix" characters based on guesswork.
413
+
414
+ ### 2. Heading Levels
415
+ - Verify that headings use correct Markdown levels (#, ##, ###, ####, #####, ######).
416
+ - Determine heading level using the following priority:
417
+ 1. **Hierarchical numbering** (strongest signal): e.g. "1" \u2192 #, "2.1" \u2192 ##, "2.1.1" \u2192 ###, "2.1.2.5" \u2192 ####
418
+ 2. Font size (larger = higher level)
419
+ 3. Indentation
420
+ 4. Bold/emphasis styling
421
+
422
+ ### 3. Tables
423
+
424
+ **First, decide whether the table should be Markdown or plain text:**
425
+ - Use **Markdown table format** if the table has a consistent, clear header structure and uniform column layout throughout.
426
+ - Use **plain text structured description** if the table:
427
+ - Lacks a clear header row
428
+ - Uses mixed or irregular column structures across rows
429
+ - Functions more like a certificate, form, or label layout
430
+
431
+ **If using Markdown format**, follow these rules strictly:
432
+ - Every table must have: header row \u2192 separator row \u2192 data rows
433
+ - Use simple separators only: \`| --- | --- |\` (NOT \`|---|---|\` or long dashes)
434
+ - Example:
435
+ \`\`\`
436
+ | Column 1 | Column 2 |
437
+ | --- | --- |
438
+ | Data 1 | Data 2 |
439
+ \`\`\`
440
+ - Important: do not use the | character as part of the data inside a cell, this would break the table, if a cell contains a | character, use a capital I.
441
+
442
+ **Symbol translation rules for table cells:**
443
+ - Black/filled dot \u2192 \`+\` (active); White/empty dot \u2192 \`-\` (inactive)
444
+ *(e.g. Rufe-LED columns)*
445
+ - Green or black checkmark \u2192 \`+\` (active); Red or black cross \u2192 \`-\` (inactive)
446
+
447
+ ### 4. Multi-Page Table Continuity
448
+ - If this page contains a table with a header row that runs to the bottom of the page (suggesting it may continue on the next page), extract the header row and include it in the \`current_page_table.headers\` field.
449
+ - If this page contains a table WITHOUT a header row (suggesting it's a continuation from a previous page), set \`current_page_table.is_continuation\` to true and try to identify what the headers might be based on the data structure. Include your best guess for headers in \`current_page_table.headers\`.
450
+
451
+ ### 5. Technical Diagrams & Schematics
452
+ If the page contains a flow-chart, schematic, technical drawing or control board layout that is **absent or poorly described** in the OCR output do the following:
453
+ - Open a <diagram> tag with the following content:
454
+ <diagram>
455
+ <description>
456
+ Add a detailed description of the diagram here.
457
+ </description>
458
+ <mermaid>
459
+ Add a mermaid diagram schema here that in detail describes the diagram.
460
+ </mermaid>
461
+ </diagram>
462
+
463
+ ### 6. Captions, Icons & Symbols
464
+ - Verify that image captions, labels, icons, and checkmarks are present and correctly transcribed.
465
+
466
+ ### 7. Only populate \`corrected_text\` when \`needs_correction\` is true. If the OCR output is accurate, return \`needs_correction: false\` and \`corrected_content: null\`.
467
+ `;
468
+ const result = await generateText({
469
+ model,
470
+ output: Output.object({
471
+ schema: z.object({
472
+ needs_correction: z.boolean(),
473
+ corrected_text: z.string().nullable(),
474
+ current_page_table: z.object({
475
+ headers: z.array(z.string()),
476
+ is_continuation: z.boolean()
477
+ }).nullable(),
478
+ confidence: z.enum(["high", "medium", "low"]),
479
+ reasoning: z.string()
480
+ })
481
+ }),
482
+ messages: [
483
+ {
484
+ role: "user",
485
+ content: [
486
+ { type: "text", text: prompt },
487
+ {
488
+ type: "image",
489
+ image: `data:${mimeType};base64,${imageBase64}`
490
+ }
491
+ ]
492
+ }
493
+ ]
494
+ });
495
+ const parsedOutput = result.output;
496
+ const validation = {
497
+ needs_correction: parsedOutput.needs_correction,
498
+ corrected_text: parsedOutput.corrected_text || void 0,
499
+ confidence: parsedOutput.confidence,
500
+ current_page_table: parsedOutput.current_page_table || void 0,
501
+ reasoning: parsedOutput.reasoning
502
+ };
503
+ console.log(`[EXULU] VLM validation result: ${JSON.stringify(validation)}`);
504
+ return validation;
505
+ }
506
+ function reconstructTableHeaders(document, validationResults, verbose = false) {
507
+ let lastTableHeaders = void 0;
508
+ for (const page of document) {
509
+ const validation = validationResults.get(page.page);
510
+ if (!validation) continue;
511
+ const tableInfo = validation.current_page_table;
512
+ if (tableInfo && tableInfo.headers.length > 0) {
513
+ if (tableInfo.is_continuation && lastTableHeaders) {
514
+ if (verbose) {
515
+ console.log(`[EXULU] Page ${page.page}: Reconstructing table headers from previous page`);
516
+ console.log(`[EXULU] Previous headers: ${lastTableHeaders.join(" | ")}`);
517
+ }
518
+ const contentToModify = page.vlm_corrected_text || page.content;
519
+ const lines = contentToModify.split("\n");
520
+ const firstTableLineIndex = lines.findIndex((line) => line.trim().startsWith("|"));
521
+ if (firstTableLineIndex !== -1) {
522
+ const headerRow = `| ${lastTableHeaders.join(" | ")} |`;
523
+ const separatorRow = `| ${lastTableHeaders.map(() => "---").join(" | ")} |`;
524
+ lines.splice(firstTableLineIndex, 0, headerRow, separatorRow);
525
+ const reconstructedContent = lines.join("\n");
526
+ if (page.vlm_corrected_text) {
527
+ page.vlm_corrected_text = reconstructedContent;
528
+ } else {
529
+ page.content = reconstructedContent;
530
+ }
531
+ if (verbose) {
532
+ console.log(`[EXULU] Page ${page.page}: Added table headers successfully`);
533
+ }
534
+ }
535
+ if (!tableInfo.is_continuation) {
536
+ lastTableHeaders = tableInfo.headers;
537
+ }
538
+ } else {
539
+ lastTableHeaders = tableInfo.headers;
540
+ if (verbose) {
541
+ console.log(`[EXULU] Page ${page.page}: Storing table headers for potential continuation`);
542
+ console.log(`[EXULU] Headers: ${lastTableHeaders.join(" | ")}`);
543
+ }
544
+ }
545
+ } else {
546
+ lastTableHeaders = void 0;
547
+ }
548
+ }
549
+ }
550
+ async function validateWithVLM(document, model, verbose = false, concurrency = 10) {
551
+ console.log(`[EXULU] Starting VLM validation for processor output, ${document.length} pages...`);
552
+ console.log(`[EXULU] Concurrency limit: ${concurrency}`);
553
+ const limit = pLimit(concurrency);
554
+ const validationResults = /* @__PURE__ */ new Map();
555
+ let validatedCount = 0;
556
+ let correctedCount = 0;
557
+ const validationTasks = document.map(
558
+ (page) => limit(async () => {
559
+ await new Promise((resolve2) => setImmediate(resolve2));
560
+ const imagePath = page.image;
561
+ if (!imagePath) {
562
+ console.warn(`[EXULU] Page ${page.page}: No image found, skipping validation`);
563
+ return;
564
+ }
565
+ if (page.content) {
566
+ const hasImage = page.content.match(/\.(jpeg|jpg|png|gif|webp)/i);
567
+ const hasTable = (page.content.match(/\|/g)?.length || 0) > 1;
568
+ if (!hasImage && !hasTable) {
569
+ if (verbose) {
570
+ console.log(`[EXULU] Page ${page.page}: No image or table found, SKIPPING VLM validation`);
571
+ }
572
+ return;
573
+ }
574
+ } else {
575
+ if (verbose) {
576
+ console.log(`[EXULU] Page ${page.page}: Standalone image, proceeding with VLM content extraction`);
577
+ }
578
+ }
579
+ let validation;
580
+ try {
581
+ console.log(`[EXULU] Validating page ${page.page} with VLM`);
582
+ validation = await withRetry(async () => {
583
+ return await validatePageWithVLM(page, imagePath, model);
584
+ }, 3);
585
+ validationResults.set(page.page, validation);
586
+ if (verbose && validation.current_page_table) {
587
+ console.log(`[EXULU] Page ${page.page} table info:`, {
588
+ headers: validation.current_page_table.headers,
589
+ is_continuation: validation.current_page_table.is_continuation
590
+ });
591
+ }
592
+ } catch (error) {
593
+ console.error(`[EXULU] Error validating page ${page.page} with VLM more than 3 times, skipping:`, error);
594
+ throw error;
595
+ }
596
+ if (validation.needs_correction && validation.corrected_text) {
597
+ page.vlm_validated = true;
598
+ const normalizedText = normalizeMarkdownContent(validation.corrected_text);
599
+ const correctedWithHeadings = reconstructHeadings(
600
+ normalizedText,
601
+ page.headings
602
+ );
603
+ page.vlm_corrected_text = correctedWithHeadings;
604
+ correctedCount++;
605
+ if (verbose) {
606
+ console.log(
607
+ `[EXULU] Page ${page.page}: Corrected (${validation.confidence} confidence)`
608
+ );
609
+ console.log(`[EXULU] Reason: ${validation.reasoning}`);
610
+ }
611
+ } else {
612
+ if (verbose) {
613
+ console.log(
614
+ `[EXULU] Page ${page.page}: No correction needed (${validation.confidence} confidence)`
615
+ );
616
+ }
617
+ }
618
+ validatedCount++;
619
+ })
620
+ );
621
+ await Promise.all(validationTasks);
622
+ console.log(`[EXULU] VLM validation complete (parallel processing):`);
623
+ console.log(`[EXULU] Validated: ${validatedCount} pages`);
624
+ console.log(`[EXULU] Corrected: ${correctedCount} pages`);
625
+ console.log(`[EXULU] Starting sequential table header reconstruction...`);
626
+ reconstructTableHeaders(document, validationResults, verbose);
627
+ console.log(`[EXULU] Table header reconstruction complete`);
628
+ return document;
629
+ }
630
+ async function processDocument(filePath, fileType, buffer, tempDir, config, verbose = false) {
631
+ console.log("Starting document processing...");
632
+ console.log(`${fileType}: ${filePath}`);
633
+ const paths = {
634
+ json: path.join(tempDir, `processed.json`),
635
+ markdown: path.join(tempDir, `markdown.md`),
636
+ images: path.join(tempDir, "images"),
637
+ source: filePath
638
+ };
639
+ const stripped = filePath.split(".").pop()?.trim().toLowerCase();
640
+ let result;
641
+ switch (stripped) {
642
+ case "txt":
643
+ case "md":
644
+ let content = buffer.toString();
645
+ content = content.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
646
+ result = {
647
+ markdown: content,
648
+ json: [{
649
+ page: 1,
650
+ content,
651
+ headings: []
652
+ }]
653
+ };
654
+ break;
655
+ case "pdf":
656
+ result = await processPdf(buffer, paths, config, verbose);
657
+ break;
658
+ case "docx":
659
+ result = await processDocx(buffer);
660
+ break;
661
+ case "doc":
662
+ result = await processWord(buffer);
663
+ break;
664
+ case "jpg":
665
+ case "jpeg":
666
+ case "png":
667
+ case "gif":
668
+ case "webp":
669
+ result = await processImage(buffer, paths, config, verbose);
670
+ break;
671
+ // Todo other file types with docx and officeparser
672
+ default:
673
+ throw new Error(`[EXULU] Unsupported file type: ${fileType}`);
674
+ }
675
+ return {
676
+ content: result,
677
+ files: {
678
+ markdown: paths.markdown,
679
+ json: paths.json
680
+ }
681
+ };
682
+ }
683
+ async function processPdf(buffer, paths, config, verbose = false) {
684
+ try {
685
+ let json = [];
686
+ if (config?.processor.name === "officeparser") {
687
+ const text = await parseOfficeAsync(buffer, {
688
+ outputErrorToConsole: false,
689
+ newlineDelimiter: "\n"
690
+ });
691
+ json = [{
692
+ page: 1,
693
+ content: text,
694
+ headings: []
695
+ }];
696
+ } else if (config?.processor.name === "mistral") {
697
+ const resolved = await resolveOcr({
698
+ model: config.processor.model ?? "mistral-ocr",
699
+ ...config.attribution
700
+ });
701
+ const maxPagesPerChunk = config.processor.maxPagesPerChunk ?? 25;
702
+ const chunksDir = path.join(path.dirname(paths.json), "ocr_chunks");
703
+ const splitResult = await executePythonScript({
704
+ scriptPath: "ee/python/documents/processing/split_pdf.py",
705
+ args: [paths.source, chunksDir, "--chunk-size", String(maxPagesPerChunk), "--max-size-mb", "25"],
706
+ timeout: 5 * 60 * 1e3
707
+ });
708
+ let pdfChunks;
709
+ try {
710
+ pdfChunks = JSON.parse(splitResult.stdout);
711
+ } catch (err) {
712
+ throw new Error(
713
+ `[EXULU] split_pdf.py returned invalid JSON on stdout: ${err.message}
714
+ stdout: ${splitResult.stdout.slice(0, 500)}
715
+ stderr: ${splitResult.stderr.slice(-1e3)}`
716
+ );
717
+ }
718
+ console.log(`[EXULU] PDF split into ${pdfChunks.length} chunk(s) for OCR (max ${maxPagesPerChunk} pages each)`);
719
+ const chunkLimit = pLimit(3);
720
+ const chunkResults = await Promise.all(
721
+ pdfChunks.map(
722
+ (chunk, i) => chunkLimit(async () => {
723
+ await new Promise((resolve2) => setImmediate(resolve2));
724
+ await new Promise((resolve2) => setTimeout(resolve2, Math.floor(Math.random() * 1e3) + 200));
725
+ console.log(`[EXULU] OCR chunk ${i + 1}/${pdfChunks.length}: pages ${chunk.start_page}\u2013${chunk.end_page - 1}`);
726
+ const chunkBuffer = await fs.promises.readFile(chunk.path);
727
+ const chunkBase64 = chunkBuffer.toString("base64");
728
+ const chunkResponse = await withRetry(async () => {
729
+ return await resolved.ocr({
730
+ type: "document_url",
731
+ document_url: "data:application/pdf;base64," + chunkBase64
732
+ }, { includeImageBase64: false });
733
+ }, 10);
734
+ return { pages: chunkResponse.pages, offset: chunk.start_page };
735
+ })
736
+ )
737
+ );
738
+ const mergedPages = chunkResults.sort((a, b) => a.offset - b.offset).flatMap(
739
+ ({ pages, offset }) => pages.map((p) => ({ ...p, index: p.index + offset }))
740
+ );
741
+ const parser = new LiteParse();
742
+ const screenshots = await parser.screenshot(paths.source, void 0);
743
+ await fs.promises.mkdir(paths.images, { recursive: true });
744
+ for (const screenshot of screenshots) {
745
+ await fs.promises.writeFile(
746
+ path.join(
747
+ paths.images,
748
+ `${screenshot.pageNum}.png`
749
+ ),
750
+ screenshot.imageBuffer
751
+ );
752
+ screenshot.imagePath = path.join(paths.images, `${screenshot.pageNum}.png`);
753
+ }
754
+ json = mergedPages.map((page) => ({
755
+ page: page.index + 1,
756
+ content: page.markdown,
757
+ image: screenshots.find((s) => s.pageNum === page.index + 1)?.imagePath,
758
+ headings: []
759
+ }));
760
+ fs.writeFileSync(paths.json, JSON.stringify(json, null, 2));
761
+ } else if (config?.processor.name === "liteparse") {
762
+ const parser = new LiteParse();
763
+ const result = await parser.parse(paths.source);
764
+ const screenshots = await parser.screenshot(paths.source, void 0);
765
+ console.log(`[EXULU] Liteparse screenshots: ${JSON.stringify(screenshots)}`);
766
+ await fs.promises.mkdir(paths.images, { recursive: true });
767
+ for (const screenshot of screenshots) {
768
+ await fs.promises.writeFile(path.join(paths.images, `${screenshot.pageNum}.png`), screenshot.imageBuffer);
769
+ screenshot.imagePath = path.join(paths.images, `${screenshot.pageNum}.png`);
770
+ }
771
+ json = result.pages.map((page) => ({
772
+ page: page.pageNum,
773
+ content: page.text,
774
+ image: screenshots.find((s) => s.pageNum === page.pageNum)?.imagePath
775
+ }));
776
+ fs.writeFileSync(paths.json, JSON.stringify(json, null, 2));
777
+ } else {
778
+ const configured = String(config?.processor?.name ?? "");
779
+ throw new Error(
780
+ configured === "" ? "[EXULU] No document processor configured. Set processor.name to one of: mistral, liteparse, officeparser." : `[EXULU] Unknown document processor "${configured}". Supported processors are: mistral, liteparse, officeparser.` + (configured === "docling" ? ' The "docling" processor was removed: it depended on PyMuPDF, which is AGPL-licensed. Use "mistral" for PDF OCR.' : "")
781
+ );
782
+ }
783
+ console.log(`[EXULU]
784
+ \u2713 Document processing completed successfully`);
785
+ console.log(`[EXULU] Total pages: ${json.length}`);
786
+ console.log(`[EXULU] Output file: ${paths.json}`);
787
+ const vlmModel = config?.vlm?.model ? await resolveVlmModel(config) : void 0;
788
+ if (vlmModel && json.length > 0) {
789
+ json = await validateWithVLM(
790
+ json,
791
+ vlmModel,
792
+ verbose,
793
+ config.vlm.concurrency
794
+ );
795
+ console.log("[EXULU] \n\u{1F4CA} Processing Summary:");
796
+ console.log(`[EXULU] Total pages: ${json.length}`);
797
+ const validatedPages = json.filter((p) => p.vlm_validated);
798
+ const correctedPages = json.filter((p) => p.vlm_corrected_text);
799
+ console.log(`[EXULU] VLM validated pages: ${validatedPages.length}`);
800
+ console.log(`[EXULU] VLM corrected pages: ${correctedPages.length}`);
801
+ if (correctedPages.length > 0) {
802
+ console.log("\n\u{1F527} Example Corrections:");
803
+ correctedPages.slice(0, 2).forEach((page) => {
804
+ console.log(`[EXULU]
805
+ Page ${page.page} (Page ${page.page}):`);
806
+ console.log(`[EXULU] Original: ${page.content.substring(0, 150)}...`);
807
+ console.log(`[EXULU] Corrected: ${page.vlm_corrected_text.substring(0, 150)}...`);
808
+ });
809
+ }
810
+ await fs.promises.writeFile(
811
+ paths.json,
812
+ JSON.stringify(json, null, 2),
813
+ "utf-8"
814
+ );
815
+ }
816
+ const markdownStream = fs.createWriteStream(paths.markdown, { encoding: "utf-8" });
817
+ for (let i = 0; i < json.length; i++) {
818
+ const p = json[i];
819
+ if (!p) continue;
820
+ const content = p.vlm_corrected_text ?? p.content;
821
+ markdownStream.write(content);
822
+ if (i < json.length - 1) {
823
+ markdownStream.write("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
824
+ }
825
+ }
826
+ await new Promise((resolve2, reject) => {
827
+ markdownStream.end(() => resolve2());
828
+ markdownStream.on("error", reject);
829
+ });
830
+ console.log(`[EXULU] Validated output saved to: ${paths.json}`);
831
+ console.log(`[EXULU] Validated markdown saved to: ${paths.markdown}`);
832
+ const markdown = await fs.promises.readFile(paths.markdown, "utf-8");
833
+ const processedJson = json.map((e) => {
834
+ const finalContent = e.vlm_corrected_text ?? e.content;
835
+ return {
836
+ page: e.page,
837
+ content: finalContent
838
+ };
839
+ });
840
+ json.length = 0;
841
+ json = [];
842
+ const memUsage = process.memoryUsage();
843
+ console.log(`[EXULU] Memory after document processing: ${Math.round(memUsage.heapUsed / 1024 / 1024)}MB / ${Math.round(memUsage.heapTotal / 1024 / 1024)}MB`);
844
+ return {
845
+ markdown,
846
+ json: processedJson
847
+ };
848
+ } catch (error) {
849
+ console.error("[EXULU] Error processing document:", error);
850
+ throw error;
851
+ }
852
+ }
853
+ var loadFile = async (file, name, tempDir) => {
854
+ let filePath = file;
855
+ let fileType = name?.split(".").pop();
856
+ if (!fileType) {
857
+ throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
858
+ }
859
+ const UUID = randomUUID();
860
+ let buffer;
861
+ if (Buffer.isBuffer(file)) {
862
+ filePath = path.join(tempDir, `${UUID}.${fileType}`);
863
+ await fs.promises.writeFile(filePath, file);
864
+ buffer = file;
865
+ } else {
866
+ filePath = filePath.trim();
867
+ if (filePath.startsWith("http")) {
868
+ const response = await fetch(filePath);
869
+ const array = await response.arrayBuffer();
870
+ const tempFilePath = path.join(tempDir, `${UUID}.${fileType}`);
871
+ await fs.promises.writeFile(tempFilePath, Buffer.from(array));
872
+ buffer = Buffer.from(array);
873
+ filePath = tempFilePath;
874
+ } else {
875
+ buffer = await fs.promises.readFile(file);
876
+ }
877
+ }
878
+ return { filePath, fileType, buffer };
879
+ };
880
+ async function documentProcessor({
881
+ file,
882
+ name,
883
+ config
884
+ }) {
885
+ const license = checkLicense();
886
+ if (!license["advanced-document-processing"]) {
887
+ throw new Error("Advanced document processing is an enterprise feature, please add a valid Exulu enterprise license key to use it.");
888
+ }
889
+ const uuid = randomUUID();
890
+ const tempDir = path.join(process.cwd(), "temp", uuid);
891
+ const localFilesAndFoldersToDelete = [tempDir];
892
+ console.log(`[EXULU] Temporary directory for processing document ${name}: ${tempDir}`);
893
+ await fs.promises.mkdir(tempDir, { recursive: true });
894
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
895
+ await fs.promises.writeFile(path.join(tempDir, "created_at.txt"), timestamp);
896
+ try {
897
+ const {
898
+ filePath,
899
+ fileType,
900
+ buffer
901
+ } = await loadFile(file, name, tempDir);
902
+ let supportedTypes = [];
903
+ switch (config?.processor.name) {
904
+ case "officeparser":
905
+ supportedTypes = ["docx", "pptx", "xlsx", "odt", "odp", "ods", "pdf", "rtf", "csv", "md", "html"];
906
+ break;
907
+ case "liteparse":
908
+ supportedTypes = ["pdf", "doc", "docx", "docm", "odt", "rtf", "ppt", "pptx", "pptm", "odp", "xls", "xlsx", "xlsm", "ods", "csv", "tsv"];
909
+ break;
910
+ case "mistral":
911
+ supportedTypes = ["pdf", "docx", "doc", "txt", "md", "jpg", "jpeg", "png", "gif", "webp"];
912
+ break;
913
+ }
914
+ if (!supportedTypes.includes(fileType.toLowerCase())) {
915
+ throw new Error(`[EXULU] Unsupported file type: ${fileType.toLowerCase()} for Exulu document processor, the ${config?.processor.name} processor only supports the following file types: ${supportedTypes.join(", ")}.`);
916
+ }
917
+ const { content } = await processDocument(
918
+ filePath,
919
+ fileType,
920
+ buffer,
921
+ tempDir,
922
+ config,
923
+ true
924
+ );
925
+ return content.json;
926
+ } catch (error) {
927
+ console.error("Error during chunking:", error);
928
+ throw error;
929
+ } finally {
930
+ if (config?.debugging?.deleteTempFiles !== false) {
931
+ for (const file2 of localFilesAndFoldersToDelete) {
932
+ try {
933
+ await fs.promises.rm(file2, { recursive: true });
934
+ console.log(`[EXULU] Deleted file or folder: ${file2}`);
935
+ } catch (error) {
936
+ console.error(`[EXULU] Error deleting file or folder: ${file2}`, error);
937
+ console.log(`[EXULU] File or folder still exists: ${file2}`);
938
+ }
939
+ }
940
+ }
941
+ }
942
+ }
943
+
944
+ export {
945
+ documentProcessor
946
+ };