-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_schema.php
More file actions
65 lines (52 loc) · 2.55 KB
/
Copy pathcustom_schema.php
File metadata and controls
65 lines (52 loc) · 2.55 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
55
56
57
58
59
60
61
62
63
64
65
<?php
/**
* Custom fields on top of a preset, fields injected into every line-item row, and saving
* the combination so later calls are one argument.
*
* php examples/custom_schema.php invoice.pdf
*/
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use VisionApi\Client;
use VisionApi\Exception\ConflictException;
use VisionApi\Result;
$path = $argv[1] ?? 'invoice.pdf';
$vision = new Client();
$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 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'],
];
$res = $vision->analyze(['file' => $path, 'preset' => 'invoice', 'schema' => $schema]);
$result = $res['result'];
echo 'serial: ', Result::value($result, 'machine_serial') ?? '—', "\n";
echo 'net total: ', Result::value($result, 'total_net') ?? '—', "\n";
echo 'paid: ', var_export(Result::value($result, 'is_paid'), true), "\n";
foreach (Result::rows($result, 'line_item') as $row) {
$line = Result::unwrap($row);
printf(" %s × %s = %s [lot %s]\n",
$line['quantity'] ?? '?',
$line['description'] ?? '(no description)',
$line['amount'] ?? '?',
$line['lot_number'] ?? '—');
}
// Save it, and the next call is 'schema_name' => '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 {
$vision->createSchema('our-invoices', 'invoice', $schema);
echo "\nsaved as \"our-invoices\"\n";
} catch (ConflictException) {
$vision->updateSchema('our-invoices', 'invoice', $schema);
echo "\nupdated \"our-invoices\"\n";
}
$again = $vision->analyze(['file' => $path, 'schema_name' => 'our-invoices']);
echo 'same fields via the saved schema: ', count($again['result']), "\n";