-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse-invoice.mjs
More file actions
99 lines (81 loc) · 2.55 KB
/
parse-invoice.mjs
File metadata and controls
99 lines (81 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Simple Node.js example for calling the Parserdata API with a multipart upload
import fs from "fs";
import path from "path";
import fetch from "node-fetch";
import FormData from "form-data";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Config
const apiKey = process.env.PARSERDATA_API_KEY;
const apiUrl = "https://api.parserdata.com/v1/extract";
// Allow passing file path as CLI argument, default to ./invoice.pdf
const inputFilePath = process.argv[2]
? path.resolve(process.argv[2])
: path.join(__dirname, "invoice.pdf");
// Basic safety checks
if (!apiKey || apiKey === "YOUR_API_KEY") {
console.error(
"Missing PARSERDATA_API_KEY.\n" +
" Set it as an environment variable, for example:\n" +
" export PARSERDATA_API_KEY=\"your_api_key_here\""
);
process.exit(1);
}
if (!fs.existsSync(inputFilePath)) {
console.error(
`Input file not found: ${inputFilePath}\n` +
" Place an invoice file in the repo root as invoice.pdf\n" +
" or pass a path explicitly: node parse-invoice.mjs ./path/to/file.pdf"
);
process.exit(1);
}
// Main logic
async function run() {
console.log("Using file:", inputFilePath);
console.log("Sending request to Parserdata API...");
const form = new FormData();
// Natural-language prompt describing what to extract
form.append(
"prompt",
"Extract invoice number, invoice date, supplier name, total amount, and line items (description, quantity, unit price, net amount)."
);
// Optional extraction options
form.append(
"options",
JSON.stringify({
return_schema: false,
return_selected_fields: false,
})
);
// Attach the file stream
form.append("file", fs.createReadStream(inputFilePath));
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"X-API-Key": apiKey,
...form.getHeaders(),
},
body: form,
});
if (!response.ok) {
const errorText = await response.text().catch(() => "");
console.error("Request failed with status:", response.status, response.statusText);
if (errorText) {
console.error("Response body:");
console.error(errorText);
}
process.exit(1);
}
const data = await response.json();
console.log("Parsed data:\n");
console.log(JSON.stringify(data, null, 2));
} catch (err) {
console.error("Unexpected error while calling Parserdata API:");
console.error(err);
process.exit(1);
}
}
// Run the script
run();