Extract structured data from invoices and forms into Postgres.
Take the text out of a PDF, have gemma-4-26b-a4b fill a JSON schema through response_format, check the result against itself in code (the lines add up to the subtotal, subtotal plus GST and QST equals the total), and insert it into Postgres. Anything that doesn’t add up goes to a review queue with the reason. We ran it end to end on a French Quebec invoice and an English Ontario one; what failed, and how the code handles it, is below.
Facts checked
What you’ll build
- An upload route,
POST /documents, that pulls the text out of a PDF withpdf-parse, stores it with the file’s SHA-256 (the same file twice is processed once), and answers202. - A worker that sends the text to
/v1/chat/completionswith a JSON schema. The answer matches the schema, so it parses, unless it is cut off (seefinish_reason). - Normalisation and checks in code: dates parsed from what’s printed, quantity × unit price, lines against subtotal, GST at 5%, QST at 9.975%, HST rates, total, amount due.
- Three tables: documents, invoices, invoice lines. Clean invoices are
extracted; the rest areneeds_reviewwith a list of reasons. - A review queue where a person corrects the fields; the same checks run again before the invoice is approved.
Endpoint, database and project
Create an AI endpoint with Gemma and attach it to your project; the project gets OPENAI_BASE_URL and OPENAI_API_KEY on its next deploy. Add a Postgres database (it arrives as DATABASE_URL) and run schema.sql below once.
Extraction takes Gemma tens of seconds per invoice, and longer when other requests are waiting, so it runs in a worker, never in the upload request. For a steady flow of documents, move the worker to its own Worker project (background jobs). A Worker project has its own environment variables: set DATABASE_URL and the AI endpoint variables there, and start it from a file that runs only work(). We used pdf-parse 2.4 (Apache 2.0), whose current version exports a PDFParse class rather than the single function of older tutorials; any library that returns the text layer works.
canner ai create invoices --models gemma-4-26b-a4b
canner ai attach invoices # in the project folder
npm install openai pg pdf-parse express
canner redeployThe tables
raw keeps exactly what the model returned and issues why a person should look. Money is numeric(12,2), never floating point, once it’s in the database. If you keep the PDFs themselves, put them in object storage, where every file is scanned for viruses.
CREATE TABLE documents (
id bigserial PRIMARY KEY,
filename text NOT NULL,
sha256 text NOT NULL UNIQUE, -- the same file twice is processed once
text text,
status text NOT NULL DEFAULT 'new', -- new, working, extracted, needs_review, approved
attempts int NOT NULL DEFAULT 0,
retry_at timestamptz,
raw jsonb, -- exactly what the model returned
issues text[] NOT NULL DEFAULT '{}', -- why it needs a person
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE invoices (
document_id bigint PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE,
supplier_name text,
gst_number text,
qst_number text,
invoice_number text,
invoice_date date,
due_date date,
payment_terms text,
currency text,
subtotal numeric(12,2),
gst numeric(12,2),
qst numeric(12,2),
hst numeric(12,2),
total numeric(12,2),
amount_due numeric(12,2)
);
CREATE TABLE invoice_lines (
document_id bigint NOT NULL REFERENCES invoices(document_id) ON DELETE CASCADE,
ord int NOT NULL,
description text,
quantity numeric(12,3),
unit_price numeric(12,2),
amount numeric(12,2),
PRIMARY KEY (document_id, ord)
);PDF to text, text to JSON
pdf-parse returns the text in reading order, one printed line per line: our French invoice came out as “Sous-total : 1 250,00 $” and “TPS (5 %) : 62,50 $”, table rows as “Conception de site Web (heures) 10 95,00 $ 950,00 $”. The model handled the French number format without help: 1 250,00 $ came back as 1250.
response_format with strict: true makes the answer match the schema: required keys, types, enums. It does not make the values right. temperature: 0 keeps repeated runs stable; max_tokens leaves room for long line lists, and a finish_reason of length means the answer was cut off, so the code fails loudly instead of saving half an invoice. A request takes up to 16,384 tokens of context and 2,048 of output; very long documents need splitting.
// extract.js: PDF text in, a JSON object that matches INVOICE out.
import OpenAI from "openai";
import { PDFParse } from "pdf-parse";
const ai = new OpenAI({ maxRetries: 3 });
export async function pdfToText(buffer) {
const parser = new PDFParse({ data: buffer });
try {
const { text } = await parser.getText();
return text.replace(/\n-- \d+ of \d+ --\n/g, "\n").trim(); // drop pdf-parse's page markers
} finally {
await parser.destroy();
}
}
const money = { type: ["number", "null"] };
const INVOICE = {
type: "object",
additionalProperties: false,
required: ["supplier_name", "gst_number", "qst_number", "invoice_number", "invoice_date",
"due_date", "payment_terms", "currency", "line_items", "subtotal", "taxes", "total", "amount_due"],
properties: {
supplier_name: { type: "string" },
gst_number: { type: ["string", "null"], description: "GST/HST registration number" },
qst_number: { type: ["string", "null"], description: "QST registration number" },
invoice_number: { type: "string" },
// Dates as printed, parsed in code (validate.js). A "YYYY-MM-DD" description was
// ignored, and a regex pattern produced "3112-20-03" for "3 novembre 2026".
invoice_date: { type: "string", description: "exactly as printed" },
due_date: { type: ["string", "null"], description: "exactly as printed; null if no date is printed" },
payment_terms: { type: ["string", "null"], description: "as printed, e.g. Net 30, Due on receipt" },
currency: { type: "string", enum: ["CAD", "USD", "EUR"] },
line_items: {
type: "array",
items: {
type: "object",
additionalProperties: false,
required: ["description", "quantity", "unit_price", "amount"],
properties: { description: { type: "string" }, quantity: money, unit_price: money, amount: money },
},
},
subtotal: money,
// One entry per tax line printed: separate gst/qst/hst fields got the same
// HST amount copied into both "gst" and "hst" in our tests.
taxes: {
type: "array",
items: {
type: "object",
additionalProperties: false,
required: ["name", "amount"],
properties: { name: { type: "string", enum: ["GST", "QST", "HST", "PST", "other"] }, amount: { type: "number" } },
},
},
total: { ...money, description: "Total including taxes" },
amount_due: { ...money, description: "Balance still owed, after deposits or payments" },
},
};
export async function extractInvoice(text) {
const r = await ai.chat.completions.create({
model: "gemma-4-26b-a4b",
temperature: 0,
max_tokens: 1200,
response_format: { type: "json_schema", json_schema: { name: "invoice", strict: true, schema: INVOICE } },
messages: [
{ role: "system", content: "Extract the invoice fields from the document. Use null for anything the document does not state. Amounts are plain numbers without currency signs or thousands separators. TPS is GST and TVQ is QST." },
{ role: "user", content: text.slice(0, 30000) },
],
});
const choice = r.choices[0];
if (choice.finish_reason === "length") throw new Error("answer cut off: raise max_tokens or split the document");
if (choice.finish_reason === "content_filter") throw new Error("blocked by the content policy");
return JSON.parse(choice.message.content);
}What failed in testing, and what we changed
The first schema looked like most tutorials: one field per tax and a description for the date format. Here is what Gemma did with it, and the fix in the code above.
| Field | What happened | Fix |
|---|---|---|
| Dates, with a description “YYYY-MM-DD” | Copied as printed: “3 novembre 2026”, “Nov 5, 2026”. A description is a hint, not a rule | Ask for the date as printed; parse it in code |
Dates, with a regex pattern | “Nov 5, 2026” became 2026-11-05, but “3 novembre 2026” became 3112-20-03: right shape, nonsense value | Same: no pattern, parse in code, reject impossible dates |
Separate gst, qst, hst fields | On the Ontario invoice, the HST (109.20) was copied into both gst and hst, even with “null when the invoice charges HST” in the description | One taxes array, one entry per printed tax line, with an enum for the name |
due_date on “Terms: Due on receipt” | The string “Due on receipt” in the date field, and still there after we added a payment_terms field next to it | The code recognises “on receipt” and sets the due date to the invoice date |
| Amounts, French number format, deposits | Right the first time: 1 250,00 $ → 1250; total 949.20 and balance due 749.20 after a deposit kept apart | Nothing to fix; the checks confirm it on every invoice |
Normalise and check
Dates are parsed from French and English forms (“1er décembre 2026”, “Nov 5, 2026”, ISO); a numeric date like 05/11/2026 could be May or November, so it goes to a person. Then the invoice is checked against itself, within a cent or two for rounding:
// validate.js: normalise what the model returned, then check it against itself.
const MONTHS = {
jan: 1, janv: 1, janvier: 1, january: 1, feb: 2, fev: 2, fevr: 2, fevrier: 2, february: 2,
mar: 3, mars: 3, march: 3, apr: 4, avr: 4, avril: 4, april: 4, may: 5, mai: 5,
jun: 6, juin: 6, june: 6, jul: 7, juil: 7, juillet: 7, july: 7, aug: 8, aou: 8, aout: 8, august: 8,
sep: 9, sept: 9, septembre: 9, september: 9, oct: 10, octobre: 10, october: 10,
nov: 11, novembre: 11, november: 11, dec: 12, decembre: 12, december: 12,
};
// "2026-11-03", "3 novembre 2026", "1er décembre 2026", "Nov 5, 2026" -> "YYYY-MM-DD".
// "05/11/2026" could be May 11 or November 5: returns null, and a person decides.
export function toIsoDate(s) {
if (!s) return null;
const t = s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[.,]/g, " ").trim();
let y, m, d;
let x = t.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/);
if (x) [y, m, d] = [+x[1], +x[2], +x[3]];
else if ((x = t.match(/^(\d{1,2})(?:er)?\s+([a-z]+)\s+(\d{4})$/))) [d, m, y] = [+x[1], MONTHS[x[2]], +x[3]];
else if ((x = t.match(/^([a-z]+)\s+(\d{1,2})(?:st|nd|rd|th)?\s+(\d{4})$/))) [m, d, y] = [MONTHS[x[1]], +x[2], +x[3]];
if (!m || !d || !y) return null;
const iso = `${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
const check = new Date(iso + "T00:00:00Z");
return check.getUTCDate() === d ? iso : null; // rejects 31 November
}
const cents = (n) => Math.round(n * 100);
const near = (a, b, tol = 1) => Math.abs(cents(a) - cents(b)) <= tol; // within a cent by default
export function validate(raw) {
const issues = [];
// Tax lines -> one column per tax. The same tax twice is a misread.
const sum = (name) => {
const t = raw.taxes.filter((x) => x.name === name);
if (t.length > 1) issues.push(`${name} appears ${t.length} times`);
return t.length ? t.reduce((s, x) => s + x.amount, 0) : null;
};
const inv = { ...raw, gst: sum("GST"), qst: sum("QST"), hst: sum("HST") };
if (raw.taxes.some((t) => t.name === "PST" || t.name === "other")) issues.push("a tax other than GST, QST or HST");
const out = { ...inv };
// The model returns the date as printed; parse it here and check it's a real date.
out.invoice_date = toIsoDate(inv.invoice_date);
if (!out.invoice_date) issues.push(`invoice date not understood: "${inv.invoice_date}"`);
out.due_date = toIsoDate(inv.due_date);
// "Due on receipt" lands in due_date even with a payment_terms field next to it.
const onReceipt = /receipt|réception/i.test(`${inv.payment_terms ?? ""} ${inv.due_date ?? ""}`);
if (!out.due_date && onReceipt) out.due_date = out.invoice_date;
else if (inv.due_date && !out.due_date) issues.push(`due date not understood: "${inv.due_date}"`);
// Lines: quantity x unit price = amount, and the lines add up to the subtotal.
inv.line_items.forEach((l, i) => {
if (l.quantity != null && l.unit_price != null && l.amount != null && !near(l.quantity * l.unit_price, l.amount))
issues.push(`line ${i + 1}: ${l.quantity} x ${l.unit_price} is not ${l.amount}`);
});
const lines = inv.line_items.reduce((s, l) => s + (l.amount ?? 0), 0);
if (inv.subtotal == null) issues.push("no subtotal");
else if (inv.line_items.length && !near(lines, inv.subtotal, inv.line_items.length))
issues.push(`lines add up to ${lines.toFixed(2)}, subtotal says ${inv.subtotal}`);
// Taxes: subtotal + taxes = total. GST is 5% of the price; QST is 9.975% of the
// price excluding GST; HST depends on the province (13% in Ontario).
const taxes = raw.taxes.reduce((s, t) => s + t.amount, 0);
if (inv.subtotal != null && inv.total != null && !near(inv.subtotal + taxes, inv.total, 2))
issues.push(`subtotal ${inv.subtotal} + taxes ${taxes.toFixed(2)} is not the total ${inv.total}`);
if (inv.gst != null && inv.subtotal != null && !near(inv.subtotal * 0.05, inv.gst, 2))
issues.push(`GST ${inv.gst} is not 5% of ${inv.subtotal}: exempt items, or a misread`);
if (inv.qst != null && inv.subtotal != null && !near(inv.subtotal * 0.09975, inv.qst, 2))
issues.push(`QST ${inv.qst} is not 9.975% of ${inv.subtotal}: exempt items, or a misread`);
if (inv.hst != null && inv.subtotal) {
const rate = (inv.hst / inv.subtotal) * 100;
if (![13, 14, 15].some((r) => Math.abs(rate - r) < 0.05)) issues.push(`HST is ${rate.toFixed(2)}% of the subtotal`);
}
if (inv.gst != null && inv.hst != null) issues.push("both GST and HST: HST already includes the federal part");
if (inv.qst && !inv.qst_number) issues.push("QST charged but no QST number found");
if ((inv.gst || inv.hst) && !inv.gst_number) issues.push("GST/HST charged but no GST/HST number found");
out.amount_due = inv.amount_due ?? inv.total;
if (out.amount_due != null && inv.total != null && out.amount_due > inv.total + 0.005)
issues.push(`amount due ${out.amount_due} is more than the total ${inv.total}`);
return { invoice: out, issues };
}| Check | Rule used | When it fails |
|---|---|---|
| GST † | 5% of the selling price | Review: exempt or zero-rated items, or a misread |
| QST † | 9.975% of the selling price excluding GST | Review: same |
| HST † | 13% in Ontario; the code accepts 13, 14 and 15%, the rates of the participating provinces | Review |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. GST (2026-11-23) · QST (2026-11-23) · HST (2026-11-23)
Save in one transaction
Each document is written in one transaction: the invoice, its lines and the document’s status together, so a crash never leaves half an invoice. Running it again on the same document replaces the previous result.
// db.js
import pg from "pg";
export const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 });
// save.js: one transaction per document. Clean invoices are 'extracted';
// anything with an issue goes to the review queue, with the reasons.
import { db } from "./db.js";
export async function saveInvoice(documentId, raw, invoice, issues) {
const client = await db.connect();
try {
await client.query("BEGIN");
await client.query("DELETE FROM invoices WHERE document_id = $1", [documentId]); // re-runs replace
await client.query(
`INSERT INTO invoices (document_id, supplier_name, gst_number, qst_number, invoice_number,
invoice_date, due_date, payment_terms, currency, subtotal, gst, qst, hst, total, amount_due)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`,
[documentId, invoice.supplier_name, invoice.gst_number, invoice.qst_number, invoice.invoice_number,
invoice.invoice_date, invoice.due_date, invoice.payment_terms, invoice.currency, invoice.subtotal, invoice.gst,
invoice.qst, invoice.hst, invoice.total, invoice.amount_due]);
for (const [i, l] of invoice.line_items.entries()) {
await client.query(
`INSERT INTO invoice_lines (document_id, ord, description, quantity, unit_price, amount)
VALUES ($1, $2, $3, $4, $5, $6)`,
[documentId, i + 1, l.description, l.quantity, l.unit_price, l.amount]);
}
await client.query(
"UPDATE documents SET status = $2, raw = $3, issues = $4 WHERE id = $1",
[documentId, issues.length ? "needs_review" : "extracted", JSON.stringify(raw), issues]);
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
}Upload, worker and review queue
The upload route reads the text right away (that’s fast and local) and decides whether the PDF has a text layer. The worker takes one document at a time with FOR UPDATE SKIP LOCKED. A network error or a busy service isn’t the document’s fault: it is tried again in 5 minutes, up to 3 times, before it goes to a person. In our first run, one call ended in a connection error after the SDK’s own retries; that is why the retry is there.
GET /review lists what needs a person, with the reasons and what the model read. POST /documents/:id/approve takes the corrected fields and runs the same checks: in our test, approving an invoice with the date 31/11/2026 came back 422 with the reason, and the corrected one was saved.
// server.js: upload a PDF, a worker extracts it, people clear the review queue.
import express from "express";
import { createHash } from "node:crypto";
import { db } from "./db.js";
import { pdfToText, extractInvoice } from "./extract.js";
import { validate } from "./validate.js";
import { saveInvoice } from "./save.js";
const app = express();
app.use(express.json());
// curl --data-binary @facture.pdf -H "Content-Type: application/pdf" https://your-app.example/documents?name=facture.pdf
app.post("/documents", express.raw({ type: "application/pdf", limit: "20mb" }), async (req, res) => {
const sha256 = createHash("sha256").update(req.body).digest("hex");
const text = await pdfToText(req.body);
// Under a few characters a page means no text layer: a scan or a photo.
const scanned = text.replace(/\s/g, "").length < 50;
const { rows } = await db.query(
`INSERT INTO documents (filename, sha256, text, status, issues) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (sha256) DO UPDATE SET filename = documents.filename RETURNING id, status`,
[req.query.name ?? "upload.pdf", sha256, text, scanned ? "needs_review" : "new",
scanned ? ["no text layer: run OCR first"] : []]);
res.status(202).json(rows[0]);
});
// The review queue: what the model read, and why a person should look.
app.get("/review", async (req, res) => {
const { rows } = await db.query(
`SELECT d.id, d.filename, d.issues, d.raw, i.* FROM documents d
LEFT JOIN invoices i ON i.document_id = d.id
WHERE d.status = 'needs_review' ORDER BY d.id`);
res.json(rows);
});
// A person sends the corrected fields; the same checks run again.
app.post("/documents/:id/approve", async (req, res) => {
const { invoice, issues } = validate(req.body);
if (issues.length) return res.status(422).json({ issues });
await saveInvoice(req.params.id, req.body, invoice, []);
await db.query("UPDATE documents SET status = 'approved' WHERE id = $1", [req.params.id]);
res.json({ ok: true });
});
// The worker: one document at a time, in the background.
async function work() {
for (;;) {
const { rows: [doc] } = await db.query(
`UPDATE documents SET status = 'working', attempts = attempts + 1
WHERE id = (SELECT id FROM documents
WHERE status = 'new' AND (retry_at IS NULL OR retry_at < now())
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING id, text, attempts`);
if (!doc) { await new Promise((r) => setTimeout(r, 5000)); continue; }
try {
const raw = await extractInvoice(doc.text);
const { invoice, issues } = validate(raw);
await saveInvoice(doc.id, raw, invoice, issues);
} catch (err) {
// Network errors and a busy service pass: try again in 5 minutes, 3 times.
await db.query(
`UPDATE documents SET issues = $2, retry_at = now() + interval '5 minutes',
status = CASE WHEN attempts >= 3 THEN 'needs_review' ELSE 'new' END
WHERE id = $1`, [doc.id, [`extraction failed: ${err.message}`]]);
}
}
}
app.listen(process.env.PORT || 3000);
work();Where /v1/uncertainty fits
Arithmetic can’t check a supplier name or an invoice number. For those, /v1/uncertainty asks the same question several times and measures whether the answers mean the same thing; low agreement is a reason to send the document to a person. It costs about n times one answer, so use it on the fields and documents that matter, not on every field.
It compares meaning, not text. Asked “When is this invoice due?” about the Ontario invoice, Gemma answered “Due on receipt” once and “Nov 5, 2026” twice, and the endpoint counted all three as the same answer (agreement 1): correct, since the invoice is dated November 5 and due on receipt.
// check-field.js: ask one question several times; if the answers disagree, a person checks.
import OpenAI from "openai";
const ai = new OpenAI({ maxRetries: 3 });
export async function agreement(text, question) {
const r = await ai.post("/uncertainty", {
body: {
model: "gemma-4-26b-a4b",
n: 3, // three answers: about three times the model time of one
max_tokens: 30,
messages: [{ role: "user", content: `${text.slice(0, 30000)}\n\n${question} Answer with the value only.` }],
},
});
return { answer: r.answer, agreement: r.agreement, samples: r.samples.map((s) => s.text) };
}
// In the worker, for a field no arithmetic can check:
// const who = await agreement(doc.text, "Which company issued this invoice?");
// if (who.agreement < 0.8) issues.push(`supplier unclear: ${who.samples.join(" / ")}`);What our test run did
Four uploads through the routes above, with the code above and the real endpoint:
| Upload | What came out | Status |
|---|---|---|
| French invoice, Quebec supplier: 2 lines, TPS and TVQ, net 30 | Dates 2026-11-03 and 2026-12-03, GST 62.50, QST 124.69, total 1,437.19; every check passed | extracted |
| English invoice, Ontario supplier: 3 lines, HST 13%, deposit paid | HST 109.20 only, total 949.20, amount due 749.20. “Due on receipt” in the date field sent it to review; with the fix above it goes through | needs_review, then extracted |
| Image-only PDF (no text layer) | Nothing to read; no model call made | needs_review: “no text layer: run OCR first” |
| The French invoice again | Same SHA-256: the existing row, not a second extraction | unchanged |
When this isn’t the right tool
Invoice text is processed in memory on Canner’s server in Montréal and never stored there; nothing is sent to another company or used for training. The extracted data lives in your own Postgres database.
- Scans, photos and handwriting. No text layer, nothing to read: OCR first, and expect more reviews.
- Large volumes, fast. Gemma takes tens of seconds per invoice on processors and the service answers one request at a time. Thousands of documents a day call for GPU hosting or a dedicated document-processing service.
- Long documents. 16,384 tokens of context covers an invoice or a form, not a 60-page statement: split by page or section first.
- Usage. Each invoice is one long Gemma answer, the most expensive kind of request. Usage is measured in model time with a monthly allowance per plan: see AI endpoints for current allowances. The SHA-256 check stops the same file from being extracted twice.
Questions
Can an LLM extract data from a PDF?
From the PDF’s text, yes. Extract the text layer with a library such as pdf-parse, then ask the model to fill a JSON schema. Scanned PDFs have no text layer and need OCR first.
Does structured output with a JSON schema guarantee correct data?
It guarantees the shape: every key, type and enum in the schema. Not the values: in our tests, a valid-looking date was nonsense and an HST amount was copied into the GST field. Check what you can compute and review the rest.
How do I check GST and QST on a Quebec invoice?
GST is 5% of the selling price and QST is 9.975% of the selling price excluding GST, according to Revenu Québec. Compare both to the subtotal with a cent or two of slack for rounding, and send mismatches to a person: exempt items are a legitimate reason.
Which model should I use for extraction?
gemma-4-26b-a4b: it gives the best answers of the Canner models and is the one we tested here. granite-4.2-3b is faster but better suited to short tasks like classification.
Where is the invoice text processed?
On Canner’s server in Montréal, in memory. Prompts and answers aren’t stored, sent to another company or used for training.
Related
- GuideAn assistant that answers questions from your database
- GuideSummarise email threads and meeting notes
- GuideDraft French versions of your app and emails
- GuideChatGPT, Copilot and GitHub Copilot: what they keep
- GuideGenerative AI in Quebec and Law 25
- GuideCanadian AI companies: who builds, who hosts, where prompts go
Invoices into your database, read in Montréal.
Attach an AI endpoint to a project, add a database, and the extraction worker runs next to your app.