openvibers/openvibe.finance serverreceipt.js

receipt.js

main 5.1 KB · 90 lines · javascript

1'use strict';
2/**
3 * A receipt photo → a transaction to check (plan §L.2: "receipt photos … always free"). The picture is read on this
4 * server by Tesseract (the same local reader OpenVibe Vision uses first), from memory to memory: it is never written to
5 * disk, sent anywhere, or kept. The person checks the store, the day and the total before anything is added.
6 *
7 * ocr(buffer, { timeoutMs }) → text (tesseract stdin stdout; throws ReceiptError when it cannot read)
8 * readReceipt(text, { today }) → { payee, posted_on, amount_cents, found: { payee, date, total } }
9 * amount_cents is money out (negative); null when no total was found. found says which parts were read, so the page
10 * can say what to check.
11 */
12const { spawn } = require('node:child_process');
13
14class ReceiptError extends Error {}
15
16function ocr(buffer, { timeoutMs = 20000, bin = '/usr/bin/tesseract' } = {}) {
17 return new Promise((resolve, reject) => {
18 let child;
19 try {
20 child = spawn(bin, ['stdin', 'stdout', '-l', 'eng', '--psm', '6'], { stdio: ['pipe', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin', OMP_THREAD_LIMIT: '1' } });
21 } catch { return reject(new ReceiptError('The receipt reader is not available on this server.')); }
22 const out = [];
23 let size = 0;
24 const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new ReceiptError('Reading the receipt took too long. Try a closer, sharper photo.')); }, timeoutMs);
25 child.stdout.on('data', (d) => { size += d.length; if (size < 512 * 1024) out.push(d); });
26 child.stderr.on('data', () => {});
27 child.on('error', () => { clearTimeout(timer); reject(new ReceiptError('The receipt reader is not available on this server.')); });
28 child.on('close', (code) => {
29 clearTimeout(timer);
30 if (code !== 0) return reject(new ReceiptError('That photo could not be read. A JPEG or PNG of the whole receipt works best.'));
31 resolve(Buffer.concat(out).toString('utf8'));
32 });
33 child.stdin.on('error', () => {});
34 child.stdin.end(buffer);
35 });
36}
37
38const MONTHS = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
39const MONEY = /(-)?[$£€]?\s?(\d{1,3}(?:[,\s]\d{3})*|\d+)[.,](\d{2})(?!\d)/g;
40const TOTAL = /\b(grand\s+total|total\s+due|amount\s+due|balance\s+due|total)\b/i;
41const NOT_TOTAL = /\b(sub\s*-?\s*total|tax|savings|discount|you\s+saved|items?\s+sold|tip|change)\b/i;
42const NOT_PAYEE = /\b(receipt|welcome|thank|store\s*#|tel|phone|www\.|http|cashier|register|order|invoice|date|time)\b/i;
43const pad = (n) => String(n).padStart(2, '0');
44const realDay = (y, m, d) => { const t = new Date(Date.UTC(y, m - 1, d)); return t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d; };
45
46function dateOf(text, today) {
47 const s = String(text || '');
48 const tries = [
49 [/\b(20\d{2})-(\d{1,2})-(\d{1,2})\b/, (m) => [+m[1], +m[2], +m[3]]],
50 [/\b(\d{1,2})[/.-](\d{1,2})[/.-](20\d{2}|\d{2})\b/, (m) => { const y = m[3].length === 2 ? 2000 + +m[3] : +m[3]; return +m[1] > 12 ? [y, +m[2], +m[1]] : [y, +m[1], +m[2]]; }],
51 [/\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s+(\d{1,2}),?\s+(20\d{2})\b/i, (m) => [+m[3], MONTHS[m[1].toLowerCase().slice(0, 3)], +m[2]]],
52 [/\b(\d{1,2})\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?,?\s+(20\d{2})\b/i, (m) => [+m[3], MONTHS[m[2].toLowerCase().slice(0, 3)], +m[1]]],
53 ];
54 for (const [re, pick] of tries) {
55 const m = re.exec(s);
56 if (!m) continue;
57 const [y, mo, d] = pick(m);
58 if (realDay(y, mo, d) && `${y}-${pad(mo)}-${pad(d)}` <= today) return `${y}-${pad(mo)}-${pad(d)}`;
59 }
60 return null;
61}
62
63const amountsOf = (line) => [...String(line).matchAll(MONEY)].map((m) => Number(m[2].replace(/[,\s]/g, '')) * 100 + Number(m[3]));
64
65function readReceipt(text, { today = new Date().toISOString().slice(0, 10) } = {}) {
66 const lines = String(text || '').split(/\r?\n/).map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean);
67 // The total: the first line that says total (never a subtotal, tax or change) with an amount; else the largest
68 // amount on the receipt.
69 let total = null;
70 for (const l of lines) {
71 if (!TOTAL.test(l) || NOT_TOTAL.test(l)) continue;
72 const a = amountsOf(l);
73 if (a.length) { total = a[a.length - 1]; break; }
74 }
75 let foundTotal = total != null;
76 if (total == null) {
77 const all = lines.flatMap(amountsOf).filter((c) => c > 0 && c < 1e8);
78 if (all.length) total = Math.max(...all);
79 }
80 // The store: the first of the top lines that reads as a name (letters, not an address or a greeting).
81 const payee = lines.slice(0, 6).find((l) => /[A-Za-z]{3,}/.test(l) && !NOT_PAYEE.test(l) && !/^\d/.test(l) && (l.match(/\d/g) || []).length < l.length / 3) || '';
82 const date = dateOf(lines.join('\n'), today);
83 return {
84 payee: payee.slice(0, 60), posted_on: date || today, amount_cents: total == null ? null : -total,
85 found: { payee: Boolean(payee), date: Boolean(date), total: foundTotal },
86 };
87}
88
89module.exports = { ocr, readReceipt, ReceiptError };
90