plugin-document-understanding 1.1.12 → 1.1.13

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,491 @@
1
+ /**
2
+ * DUGate-compatible seed data: pre-configured endpoints and pipelines for all
3
+ * 6 core profiles + 3 workflow profiles.
4
+ *
5
+ * Endpoint subpaths are RELATIVE to the configured Service Config `baseUrl`
6
+ * (e.g. `http://localhost:2023/api/v1/docs`). Workflows route to
7
+ * `/api/v1/docs/workflows` automatically. To point at a different gateway,
8
+ * change the base URL in the admin UI — the seeded paths stay untouched.
9
+ */
10
+
11
+ import type { Database } from '@nocobase/database';
12
+
13
+ interface EndpointSeed {
14
+ name: string;
15
+ subpath: string;
16
+ method: 'POST';
17
+ description: string;
18
+ fileInputMode: 'none' | 'multipart' | 'base64';
19
+ fileFieldName?: string;
20
+ maxFiles: number;
21
+ executionMode: 'sync' | 'polling' | 'webhook';
22
+ discriminatorField?: string;
23
+ discriminatorValue?: string;
24
+ /** Added for every sync-capable endpoint so DUGate returns immediately. */
25
+ syncQueryParam?: string;
26
+ /** DUGate 202 response: `{name: "operations/{id}", done: false}` → extract `id` from `name`. */
27
+ taskIdExtractPath?: string;
28
+ taskIdExtractRegex?: string;
29
+ /** Polling: GET /api/v1/operations/{taskId} */
30
+ pollResultSubpath?: string;
31
+ pollTaskIdField?: string;
32
+ pollResultField?: string;
33
+ pollStatusField?: string;
34
+ pollCompletedValue?: string;
35
+ pollInterval?: number;
36
+ pollTimeout?: number;
37
+ enabled?: boolean;
38
+ }
39
+
40
+ interface PipelineSeed {
41
+ name: string;
42
+ description: string;
43
+ inputSchema?: any;
44
+ outputMapping?: any;
45
+ enabled?: boolean;
46
+ steps: Array<{
47
+ stepOrder: number;
48
+ name: string;
49
+ endpointName: string;
50
+ outputAlias?: string;
51
+ inputMapping?: any;
52
+ onError?: 'fail' | 'skip' | 'retry';
53
+ retryCount?: number;
54
+ }>;
55
+ }
56
+
57
+ const DEFAULT_POLL_INTERVAL = 3000;
58
+ const DEFAULT_POLL_TIMEOUT = 300_000;
59
+
60
+ /** Shared async config for DUGate endpoints that support async mode. */
61
+ const asyncConfig = {
62
+ taskIdExtractPath: 'name',
63
+ taskIdExtractRegex: 'operations/([^/]+)',
64
+ pollResultSubpath: '/api/v1/operations/{taskId}',
65
+ pollTaskIdField: 'id',
66
+ pollResultField: 'result',
67
+ pollStatusField: 'metadata.state',
68
+ pollCompletedValue: 'SUCCEEDED',
69
+ pollInterval: DEFAULT_POLL_INTERVAL,
70
+ pollTimeout: DEFAULT_POLL_TIMEOUT,
71
+ };
72
+
73
+ function coreEndpoint(
74
+ service: string,
75
+ discriminatorValue: string,
76
+ overrides: Partial<EndpointSeed> & { name: string },
77
+ ): EndpointSeed {
78
+ const { name, ...rest } = overrides;
79
+ return {
80
+ name,
81
+ subpath: `/api/v1/docs/${service}`,
82
+ method: 'POST',
83
+ fileInputMode: 'multipart',
84
+ fileFieldName: 'files[]',
85
+ maxFiles: 10,
86
+ executionMode: 'sync',
87
+ discriminatorField:
88
+ discriminatorValue === 'diff' || discriminatorValue === 'semantic' || discriminatorValue === 'version'
89
+ ? 'mode'
90
+ : ['parse', 'ocr', 'digitize', 'split'].includes(discriminatorValue)
91
+ ? 'mode'
92
+ : ['invoice', 'contract', 'id-card', 'receipt', 'table', 'custom'].includes(discriminatorValue)
93
+ ? 'type'
94
+ : ['classify', 'sentiment', 'compliance', 'fact-check', 'quality', 'risk', 'summarize-eval'].includes(
95
+ discriminatorValue,
96
+ )
97
+ ? 'task'
98
+ : ['convert', 'translate', 'rewrite', 'redact', 'template'].includes(discriminatorValue)
99
+ ? 'action'
100
+ : 'mode',
101
+ discriminatorValue,
102
+ syncQueryParam: 'sync',
103
+ ...asyncConfig,
104
+ ...rest,
105
+ } as EndpointSeed;
106
+ }
107
+
108
+ function workflowEndpoint(process: string, overrides: Partial<EndpointSeed> & { name: string }): EndpointSeed {
109
+ const { name, ...rest } = overrides;
110
+ return {
111
+ name,
112
+ subpath: '/api/v1/docs/workflows',
113
+ method: 'POST',
114
+ fileInputMode: 'multipart',
115
+ fileFieldName: 'files[]',
116
+ maxFiles: 10,
117
+ executionMode: 'sync', // Will detect 202 and switch to polling automatically
118
+ discriminatorField: 'process',
119
+ discriminatorValue: process,
120
+ syncQueryParam: 'sync',
121
+ ...asyncConfig,
122
+ ...rest,
123
+ } as EndpointSeed;
124
+ }
125
+
126
+ /**
127
+ * ──── CORE PROFILE ENDPOINTS ──────────────────────────────────
128
+ * 6 profiles: ingest, extract, analyze, transform, generate, compare
129
+ */
130
+ const CORE_ENDPOINTS: EndpointSeed[] = [
131
+ // ── ingest ──
132
+ coreEndpoint('ingest', 'parse', {
133
+ name: 'dugate-ingest-parse',
134
+ description:
135
+ 'Parse digital documents (PDF/DOCX native), preserve headers, footers, tables. Supports output_format (md/json/html/csv) and language.',
136
+ fileFieldName: 'files[]',
137
+ maxFiles: 5,
138
+ }),
139
+ coreEndpoint('ingest', 'ocr', {
140
+ name: 'dugate-ingest-ocr',
141
+ description: 'OCR scanned documents and images. Supports language parameter.',
142
+ fileFieldName: 'files[]',
143
+ maxFiles: 5,
144
+ }),
145
+ coreEndpoint('ingest', 'digitize', {
146
+ name: 'dugate-ingest-digitize',
147
+ description: 'Digitize handwritten forms, checkboxes.',
148
+ fileFieldName: 'files[]',
149
+ maxFiles: 5,
150
+ }),
151
+ coreEndpoint('ingest', 'split', {
152
+ name: 'dugate-ingest-split',
153
+ description: 'Split/merge PDF pages. Use pages parameter (e.g. "1-5").',
154
+ fileFieldName: 'file',
155
+ maxFiles: 1,
156
+ }),
157
+
158
+ // ── extract ──
159
+ coreEndpoint('extract', 'invoice', {
160
+ name: 'dugate-extract-invoice',
161
+ description: 'Extract structured data from Vietnamese VAT invoices / general invoices.',
162
+ fileFieldName: 'files[]',
163
+ maxFiles: 5,
164
+ }),
165
+ coreEndpoint('extract', 'contract', {
166
+ name: 'dugate-extract-contract',
167
+ description: 'Extract parties, terms, obligations, penalties, signatures from contracts.',
168
+ fileFieldName: 'files[]',
169
+ maxFiles: 5,
170
+ }),
171
+ coreEndpoint('extract', 'id-card', {
172
+ name: 'dugate-extract-id-card',
173
+ description: 'Extract identity information from CCCD/Passport.',
174
+ fileFieldName: 'files[]',
175
+ maxFiles: 5,
176
+ }),
177
+ coreEndpoint('extract', 'receipt', {
178
+ name: 'dugate-extract-receipt',
179
+ description: 'Extract merchant, items, totals from receipts.',
180
+ fileFieldName: 'files[]',
181
+ maxFiles: 5,
182
+ }),
183
+ coreEndpoint('extract', 'table', {
184
+ name: 'dugate-extract-table',
185
+ description: 'Extract all tables from documents as structured data.',
186
+ fileFieldName: 'files[]',
187
+ maxFiles: 5,
188
+ }),
189
+ coreEndpoint('extract', 'custom', {
190
+ name: 'dugate-extract-custom',
191
+ description:
192
+ 'Extract custom fields using dynamic schema. Use fields (comma-separated) or schema (JSON Schema string).',
193
+ fileFieldName: 'files[]',
194
+ maxFiles: 5,
195
+ }),
196
+
197
+ // ── analyze ──
198
+ coreEndpoint('analyze', 'classify', {
199
+ name: 'dugate-analyze-classify',
200
+ description: 'Classify documents by taxonomy. Provide categories parameter.',
201
+ maxFiles: 5,
202
+ }),
203
+ coreEndpoint('analyze', 'sentiment', {
204
+ name: 'dugate-analyze-sentiment',
205
+ description: 'Analyze document sentiment: positive, negative, neutral.',
206
+ maxFiles: 5,
207
+ }),
208
+ coreEndpoint('analyze', 'compliance', {
209
+ name: 'dugate-analyze-compliance',
210
+ description: 'Check document compliance against criteria. Provide criteria parameter (semicolon-separated rules).',
211
+ maxFiles: 5,
212
+ }),
213
+ coreEndpoint('analyze', 'fact-check', {
214
+ name: 'dugate-analyze-fact-check',
215
+ description: 'Cross-reference document claims against reference data. Provide reference_data and extract_fields.',
216
+ maxFiles: 5,
217
+ }),
218
+ coreEndpoint('analyze', 'quality', {
219
+ name: 'dugate-analyze-quality',
220
+ description: 'Score document writing quality against criteria.',
221
+ maxFiles: 5,
222
+ }),
223
+ coreEndpoint('analyze', 'risk', {
224
+ name: 'dugate-analyze-risk',
225
+ description: 'Assess document risk level.',
226
+ maxFiles: 5,
227
+ }),
228
+ coreEndpoint('analyze', 'summarize-eval', {
229
+ name: 'dugate-analyze-summarize-eval',
230
+ description: 'Generate expert summary and evaluation of document.',
231
+ maxFiles: 5,
232
+ }),
233
+
234
+ // ── transform ──
235
+ coreEndpoint('transform', 'convert', {
236
+ name: 'dugate-transform-convert',
237
+ description: 'Convert document format (DOCX -> MD/HTML). Use output_format parameter.',
238
+ fileFieldName: 'file',
239
+ maxFiles: 1,
240
+ }),
241
+ coreEndpoint('transform', 'translate', {
242
+ name: 'dugate-transform-translate',
243
+ description: 'Translate document to target language. Use target_language and tone parameters.',
244
+ fileFieldName: 'file',
245
+ maxFiles: 1,
246
+ }),
247
+ coreEndpoint('transform', 'rewrite', {
248
+ name: 'dugate-transform-rewrite',
249
+ description:
250
+ 'Rewrite/paraphrase document. Use style (academic/executive/simplified/bullet_points) and tone parameters.',
251
+ fileFieldName: 'file',
252
+ maxFiles: 1,
253
+ }),
254
+ coreEndpoint('transform', 'redact', {
255
+ name: 'dugate-transform-redact',
256
+ description: 'Redact PII from document. Use redact_patterns parameter.',
257
+ fileFieldName: 'file',
258
+ maxFiles: 1,
259
+ }),
260
+ coreEndpoint('transform', 'template', {
261
+ name: 'dugate-transform-template',
262
+ description: 'Mail merge using template. Use template parameter (JSON).',
263
+ fileFieldName: 'file',
264
+ maxFiles: 1,
265
+ }),
266
+
267
+ // ── generate ──
268
+ coreEndpoint('generate', 'summary', {
269
+ name: 'dugate-generate-summary',
270
+ description:
271
+ 'Generate condensed summary. Parameters: format (paragraph/bullets/numbered/table/mind_map), max_words, audience.',
272
+ fileFieldName: 'files[]',
273
+ maxFiles: 5,
274
+ }),
275
+ coreEndpoint('generate', 'outline', {
276
+ name: 'dugate-generate-outline',
277
+ description: 'Extract H1/H2/H3 table of contents.',
278
+ fileFieldName: 'files[]',
279
+ maxFiles: 5,
280
+ }),
281
+ coreEndpoint('generate', 'report', {
282
+ name: 'dugate-generate-report',
283
+ description: 'Generate expert analysis report.',
284
+ fileFieldName: 'files[]',
285
+ maxFiles: 5,
286
+ }),
287
+ coreEndpoint('generate', 'email', {
288
+ name: 'dugate-generate-email',
289
+ description: 'Draft email response based on document. Use tone parameter.',
290
+ fileFieldName: 'files[]',
291
+ maxFiles: 5,
292
+ }),
293
+ coreEndpoint('generate', 'minutes', {
294
+ name: 'dugate-generate-minutes',
295
+ description: 'Generate meeting minutes with action items. Use format parameter.',
296
+ fileFieldName: 'files[]',
297
+ maxFiles: 5,
298
+ }),
299
+ coreEndpoint('generate', 'qa', {
300
+ name: 'dugate-generate-qa',
301
+ description: 'Ask questions about document content (RAG-like). Use questions parameter (JSON array).',
302
+ fileFieldName: 'files[]',
303
+ maxFiles: 5,
304
+ }),
305
+
306
+ // ── compare ──
307
+ coreEndpoint('compare', 'diff', {
308
+ name: 'dugate-compare-diff',
309
+ description: 'Line-by-line text diff (git-diff style). Requires 2 files via files[]. Use output_format parameter.',
310
+ fileFieldName: 'files[]',
311
+ maxFiles: 2,
312
+ }),
313
+ coreEndpoint('compare', 'semantic', {
314
+ name: 'dugate-compare-semantic',
315
+ description: 'Semantic/legal comparison. Requires 2 files. Use focus parameter for specific concerns.',
316
+ fileFieldName: 'files[]',
317
+ maxFiles: 2,
318
+ }),
319
+ coreEndpoint('compare', 'version', {
320
+ name: 'dugate-compare-version',
321
+ description: 'Summarized changelog between versions. Requires 2 files. Use output_format parameter.',
322
+ fileFieldName: 'files[]',
323
+ maxFiles: 2,
324
+ }),
325
+ ];
326
+
327
+ /**
328
+ * ──── WORKFLOW PROFILE ENDPOINTS ──────────────────────────────
329
+ * 3 workflow profiles: disbursement, lc-checker, doc-compare
330
+ */
331
+ const WORKFLOW_ENDPOINTS: EndpointSeed[] = [
332
+ workflowEndpoint('disbursement', {
333
+ name: 'dugate-workflow-disbursement',
334
+ description:
335
+ 'Disbursement reconciliation: classify files, extract data, cross-check resolution, generate disbursement memo.',
336
+ maxFiles: 10,
337
+ }),
338
+ workflowEndpoint('lc-checker', {
339
+ name: 'dugate-workflow-lc-checker',
340
+ description:
341
+ 'Letter of Credit document checking: validate documents against LC terms, detect discrepancies per UCP 600.',
342
+ maxFiles: 10,
343
+ }),
344
+ workflowEndpoint('doc-compare', {
345
+ name: 'dugate-workflow-doc-compare',
346
+ description:
347
+ 'Advanced document comparison: OCR, extract TOC, compare sections, generate comparison report. Requires exactly 2 files.',
348
+ maxFiles: 2,
349
+ }),
350
+ ];
351
+
352
+ /**
353
+ * ──── CONVENIENCE PIPELINES ──────────────────────────────────
354
+ * Each pipeline wraps a single endpoint so users can run them via the
355
+ * admin UI playground or invoke them as AI tools.
356
+ *
357
+ * Multi-step pipelines can be added manually from the UI later.
358
+ */
359
+ function buildPipelines(epNames: string[]): PipelineSeed[] {
360
+ return epNames.map((epName) => ({
361
+ name: epName
362
+ .replace(/^dugate-/, '')
363
+ .replace(/-/g, ' ')
364
+ .replace(/\b\w/g, (c) => c.toUpperCase()),
365
+ description: `Execute the DUGate ${epName.replace(/^dugate-/, '')} profile.`,
366
+ enabled: true,
367
+ steps: [
368
+ {
369
+ stepOrder: 1,
370
+ name: 'Call DUGate API',
371
+ endpointName: epName,
372
+ outputAlias: 'result',
373
+ inputMapping: {
374
+ file_urls: '$input.file_urls',
375
+ output_format: '$input.output_format',
376
+ language: '$input.language',
377
+ categories: '$input.categories',
378
+ criteria: '$input.criteria',
379
+ reference_data: '$input.reference_data',
380
+ fields: '$input.fields',
381
+ schema: '$input.schema',
382
+ questions: '$input.questions',
383
+ target_language: '$input.target_language',
384
+ tone: '$input.tone',
385
+ style: '$input.style',
386
+ redact_patterns: '$input.redact_patterns',
387
+ template: '$input.template',
388
+ format: '$input.format',
389
+ max_words: '$input.max_words',
390
+ audience: '$input.audience',
391
+ focus: '$input.focus',
392
+ pages: '$input.pages',
393
+ resolution_data: '$input.resolution_data',
394
+ extract_fields: '$input.extract_fields',
395
+ },
396
+ },
397
+ ],
398
+ outputMapping: {
399
+ content: '$step[result].response.content',
400
+ extracted_data: '$step[result].response.extracted_data',
401
+ usage: '$step[result].response.usage',
402
+ },
403
+ }));
404
+ }
405
+
406
+ export async function seedDugateEndpoints(db: Database): Promise<void> {
407
+ const endpointsRepo = db.getRepository<any>('doc_understanding_endpoints');
408
+ const pipelinesRepo = db.getRepository<any>('doc_understanding_pipelines');
409
+ const stepsRepo = db.getRepository<any>('doc_understanding_pipeline_steps');
410
+
411
+ const allEndpoints: EndpointSeed[] = [...CORE_ENDPOINTS, ...WORKFLOW_ENDPOINTS];
412
+
413
+ // Upsert each endpoint by name
414
+ const endpointNameToId = new Map<string, number>();
415
+ for (const ep of allEndpoints) {
416
+ const existing = await endpointsRepo.findOne({ filter: { name: ep.name } });
417
+ let record;
418
+ if (existing) {
419
+ await endpointsRepo.update({ filterByTk: existing.id, values: ep });
420
+ record = await endpointsRepo.findOne({ filter: { name: ep.name } });
421
+ } else {
422
+ record = await endpointsRepo.create({ values: ep });
423
+ }
424
+ endpointNameToId.set(ep.name, record.id);
425
+ }
426
+
427
+ // Build pipelines for all single-step convenience profiles
428
+ const pipelineNames = allEndpoints.map((e) => e.name);
429
+ const pipelines = buildPipelines(pipelineNames);
430
+
431
+ for (const pipeline of pipelines) {
432
+ const existingPipeline = await pipelinesRepo.findOne({ filter: { name: pipeline.name } });
433
+ if (existingPipeline) {
434
+ // Update existing pipeline steps
435
+ await stepsRepo.destroy({ filter: { pipelineId: existingPipeline.id } });
436
+ await pipelinesRepo.update({
437
+ filterByTk: existingPipeline.id,
438
+ values: {
439
+ description: pipeline.description,
440
+ enabled: pipeline.enabled,
441
+ inputSchema: pipeline.inputSchema,
442
+ outputMapping: pipeline.outputMapping,
443
+ },
444
+ });
445
+ for (const step of pipeline.steps) {
446
+ const endpointId = endpointNameToId.get(step.endpointName);
447
+ if (endpointId) {
448
+ await stepsRepo.create({
449
+ values: {
450
+ pipelineId: existingPipeline.id,
451
+ stepOrder: step.stepOrder,
452
+ name: step.name,
453
+ endpointId,
454
+ inputMapping: step.inputMapping || null,
455
+ outputAlias: step.outputAlias || null,
456
+ onError: step.onError || 'fail',
457
+ retryCount: step.retryCount ?? 0,
458
+ },
459
+ });
460
+ }
461
+ }
462
+ } else {
463
+ const created = await pipelinesRepo.create({
464
+ values: {
465
+ name: pipeline.name,
466
+ description: pipeline.description,
467
+ enabled: pipeline.enabled,
468
+ inputSchema: pipeline.inputSchema || null,
469
+ outputMapping: pipeline.outputMapping || null,
470
+ },
471
+ });
472
+ for (const step of pipeline.steps) {
473
+ const endpointId = endpointNameToId.get(step.endpointName);
474
+ if (endpointId) {
475
+ await stepsRepo.create({
476
+ values: {
477
+ pipelineId: created.id,
478
+ stepOrder: step.stepOrder,
479
+ name: step.name,
480
+ endpointId,
481
+ inputMapping: step.inputMapping || null,
482
+ outputAlias: step.outputAlias || null,
483
+ onError: step.onError || 'fail',
484
+ retryCount: step.retryCount ?? 0,
485
+ },
486
+ });
487
+ }
488
+ }
489
+ }
490
+ }
491
+ }