-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom-schema.mjs
More file actions
54 lines (44 loc) · 2.4 KB
/
Copy pathcustom-schema.mjs
File metadata and controls
54 lines (44 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Custom fields on top of a preset, fields injected into every line-item row, and saving
* the combination so later calls are one argument.
*
* node examples/custom-schema.mjs invoice.pdf
*/
import { VisionAPI, ConflictError, rows, unwrap, value } from '@devrobotlabs/visionapi';
const [path = 'invoice.pdf'] = process.argv.slice(2);
const vision = new VisionAPI();
const schema = {
// Plain form: the string is the description. Descriptions are the prompt — the more
// precisely you say what you want, the better the extraction.
machine_serial: 'Serial number of the machine being invoiced, without the "SN:" prefix',
// Typed form. Numbers come back as JSON numbers, dates as ISO YYYY-MM-DD.
total_net: { type: 'number', description: 'Total before tax' },
is_paid: { type: 'boolean', description: 'Whether the invoice is stamped or marked PAID' },
reference_numbers: { type: 'array', description: 'All reference numbers', items: 'string' },
// `line_item` is reserved: these become extra columns on every row of the preset's
// line-item array. Only meaningful with a preset that has line items; with a bare
// custom schema there is nothing to inject into.
line_item: { lot_number: 'The lot number printed on this line, if present' },
};
const res = await vision.analyze({ file: path, preset: 'invoice', schema });
console.log('serial:', value(res.result, 'machine_serial'));
console.log('net total:', value(res.result, 'total_net'));
console.log('paid:', value(res.result, 'is_paid'));
for (const row of rows(res.result, 'line_item')) {
const line = unwrap(row);
console.log(` ${line.quantity ?? '?'} × ${line.description ?? '(no description)'} ` +
`= ${line.amount ?? '?'} [lot ${line.lot_number ?? '—'}]`);
}
// Save it and the next call is `{ schemaName: 'our-invoices' }`. The definition is
// compiled before it is stored, so an invalid schema fails here rather than on the first
// extraction that uses it.
try {
await vision.createSchema({ name: 'our-invoices', preset: 'invoice', schema });
console.log('\nsaved as "our-invoices"');
} catch (err) {
if (!(err instanceof ConflictError)) throw err;
await vision.updateSchema('our-invoices', { preset: 'invoice', schema });
console.log('\nupdated "our-invoices"');
}
const again = await vision.analyze({ file: path, schemaName: 'our-invoices' });
console.log('same fields via the saved schema:', Object.keys(again.result).length);