-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect_then_analyze.php
More file actions
58 lines (46 loc) · 2.13 KB
/
Copy pathdetect_then_analyze.php
File metadata and controls
58 lines (46 loc) · 2.13 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
<?php
/**
* Routing a mixed inbox.
*
* The pattern is detect (1 credit per 10 calls, amortised) → analyze with the chosen preset
* (normal price). Worth it when the *type* is the decision: you can refuse to spend 40
* credits on a 40-page PDF that turns out to be a scanned fax cover sheet.
*
* If you just want the data and don't care which preset produced it, skip this and pass
* 'preset' => 'auto' — classification bundled into an extraction is free.
*
* php examples/detect_then_analyze.php ./inbox
*/
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use VisionApi\Client;
use VisionApi\Result;
$inbox = $argv[1] ?? './inbox';
$vision = new Client();
// What we are willing to spend extraction credits on, and what to do otherwise.
$handled = ['invoice', 'receipt', 'purchase_order', 'packing_slip'];
$supported = ['pdf', 'png', 'jpg', 'jpeg', 'webp', 'tif', 'tiff'];
foreach (scandir($inbox) ?: [] as $name) {
if (!in_array(strtolower(pathinfo($name, PATHINFO_EXTENSION)), $supported, true)) {
continue;
}
$path = $inbox . '/' . $name;
$guess = $vision->detect(['file' => $path]);
// fallback means nothing matched confidently and the generic preset was substituted.
// That is "shape unknown", not a match — check what was rejected.
if ($guess['fallback']) {
$closest = $guess['detections'][0] ?? null;
$extra = $closest ? " (closest: {$closest['preset']} — {$closest['reason']})" : '';
echo "{$name}: unrecognised{$extra}\n";
continue;
}
if (!in_array($guess['recommended'], $handled, true)) {
echo "{$name}: {$guess['recommended']} — not a type we process, skipping\n";
continue;
}
// `recommended` is exactly what 'preset' => 'auto' would have run, so it is safe to commit.
$res = $vision->analyze(['file' => $path, 'preset' => $guess['recommended']]);
$summary = substr(json_encode(Result::unwrap($res['result'], dropNull: true)), 0, 160);
echo "{$name}: {$guess['recommended']} → {$res['credits_used']} credit(s) {$summary}\n";
}
echo "\n", $vision->credits()['balance'], " credits remaining\n";