File size: 24,064 Bytes
4c38fbe
eacd656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c38fbe
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Doc2Sheet — invoice & receipt extraction</title>
<meta name="description" content="Invoices and receipts to validated spreadsheet rows with a vision LLM and deterministic checks. Real results on four sample documents.">
<style>
:root {
  --bg: #f7f8f7;
  --surface: #ffffff;
  --surface-2: #f1f3f2;
  --text: #16201c;
  --muted: #5b6863;
  --line: #dfe5e2;
  --accent: #0f7a5a;
  --accent-soft: #e2f3ec;
  --ok: #157347;
  --ok-soft: #e3f4ea;
  --warn: #9a5b00;
  --warn-soft: #fff1d6;
  --bad: #b3261e;
  --bad-soft: #fde3e1;
  --code-bg: #0f1a16;
  --code-text: #d7efe5;
  --shadow: 0 1px 2px rgba(16, 32, 28, .06), 0 8px 24px rgba(16, 32, 28, .06);
}
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0e1412;
    --surface: #151d1a;
    --surface-2: #1b2521;
    --text: #e6eeea;
    --muted: #9aaaa3;
    --line: #26332e;
    --accent: #3fc796;
    --accent-soft: #163128;
    --ok: #54d18f;
    --ok-soft: #14301f;
    --warn: #f2b84b;
    --warn-soft: #3a2c10;
    --bad: #ff8a80;
    --bad-soft: #3b1a18;
    --code-bg: #0a0f0d;
    --code-text: #cfe9de;
    --shadow: none;
  }
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
  margin: 0;
  background: var(--bg);
  color: var(--text);
  font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
a { color: var(--accent); }
.wrap { max-width: 1080px; margin: 0 auto; padding: 0 16px; }

/* Hero */
.hero { padding: 56px 0 28px; }
.eyebrow { font-size: 13px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--accent); }
h1 { font-size: clamp(34px, 6vw, 52px); line-height: 1.05; margin: 10px 0 14px; letter-spacing: -.02em; }
.lede { font-size: clamp(17px, 2.2vw, 20px); color: var(--muted); max-width: 720px; margin: 0 0 22px; }
.lede strong { color: var(--text); }
.cta { display: flex; flex-wrap: wrap; gap: 10px; }
.btn {
  display: inline-flex; align-items: center; gap: 8px; padding: 10px 16px; border-radius: 10px;
  border: 1px solid var(--line); background: var(--surface); color: var(--text);
  font-weight: 600; text-decoration: none; font-size: 15px;
}
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
@media (prefers-color-scheme: dark) { .btn.primary { color: #06140f; } }
.btn:hover { filter: brightness(1.05); }
.note {
  margin: 22px 0 0; padding: 10px 14px; border-left: 3px solid var(--accent); background: var(--accent-soft);
  border-radius: 0 8px 8px 0; font-size: 14px; color: var(--text); max-width: 760px;
}

/* Stats */
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin: 8px 0 28px; }
.stat { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; }
.stat b { display: block; font-size: 26px; line-height: 1.1; font-variant-numeric: tabular-nums; }
.stat span { font-size: 13px; color: var(--muted); }
@media (max-width: 720px) { .stats { grid-template-columns: repeat(2, 1fr); } }

/* Explorer */
h2 { font-size: 22px; margin: 0 0 6px; letter-spacing: -.01em; }
.section { margin: 0 0 44px; }
.section > p.sub { color: var(--muted); margin: 0 0 16px; }
.tabs { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 14px; }
@media (max-width: 820px) { .tabs { grid-template-columns: repeat(2, 1fr); } }
.tab {
  text-align: left; display: flex; gap: 10px; align-items: center; padding: 8px; border-radius: 12px;
  border: 1px solid var(--line); background: var(--surface); color: var(--text); cursor: pointer; font: inherit; min-width: 0;
}
.tab[aria-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }
.tab img { width: 44px; height: 56px; object-fit: cover; object-position: top; border-radius: 6px; border: 1px solid var(--line); flex: none; background: #fff; }
.tab .t { min-width: 0; }
.tab .name { font-size: 13px; font-weight: 600; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.pill { display: inline-block; font-size: 11.5px; font-weight: 700; padding: 1px 8px; border-radius: 99px; margin-top: 3px; text-transform: uppercase; letter-spacing: .03em; }
.pill.ok { background: var(--ok-soft); color: var(--ok); }
.pill.review { background: var(--warn-soft); color: var(--warn); }
.pill.failed { background: var(--bad-soft); color: var(--bad); }

.panel {
  display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 0;
  background: var(--surface); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; box-shadow: var(--shadow);
}
@media (max-width: 820px) { .panel { grid-template-columns: 1fr; } }
.doc { margin: 0; background: var(--surface-2); padding: 16px; display: flex; flex-direction: column; gap: 10px; border-right: 1px solid var(--line); }
@media (max-width: 820px) { .doc { border-right: 0; border-bottom: 1px solid var(--line); } }
.doc a { display: block; }
.doc img { width: 100%; height: auto; max-height: 560px; object-fit: contain; border-radius: 8px; background: #fff; border: 1px solid var(--line); }
.doc figcaption { font-size: 13px; color: var(--muted); }
.data { padding: 18px 20px 20px; min-width: 0; }
.verdict { display: flex; gap: 10px; align-items: flex-start; padding: 12px 14px; border-radius: 10px; font-size: 14.5px; margin-bottom: 16px; }
.verdict.ok { background: var(--ok-soft); color: var(--ok); }
.verdict.review { background: var(--warn-soft); color: var(--warn); }
.verdict.failed { background: var(--bad-soft); color: var(--bad); }
.verdict .icon { font-weight: 800; flex: none; }
.verdict .msg { color: var(--text); }
.verdict .msg b { color: inherit; }
.fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 18px; margin: 0 0 16px; }
.fields div { min-width: 0; }
.fields dt { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
.fields dd { margin: 1px 0 0; font-weight: 600; overflow-wrap: anywhere; }
.fields dd.none { color: var(--muted); font-weight: 400; }
.tablewrap { overflow-x: auto; margin: 0 0 12px; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
th, td { padding: 7px 8px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }
th { font-size: 12px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
td.muted { color: var(--muted); }
.totals { margin-left: auto; max-width: 340px; }
.totals td { border-bottom: 0; padding: 4px 8px; }
.totals tr.grand td { border-top: 1px solid var(--line); font-weight: 800; padding-top: 8px; }
.totals tr.flag td { color: var(--bad); }
details { margin-top: 12px; }
summary { cursor: pointer; color: var(--muted); font-size: 14px; }
pre { background: var(--code-bg); color: var(--code-text); padding: 14px; border-radius: 10px; overflow: auto; font-size: 12.5px; line-height: 1.5; }
.meta { font-size: 12.5px; color: var(--muted); margin-top: 10px; }

/* How it works */
.steps { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; counter-reset: s; }
@media (max-width: 900px) { .steps { grid-template-columns: 1fr; } }
.step { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 14px; position: relative; }
.step::before { counter-increment: s; content: counter(s); display: inline-grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: var(--accent-soft); color: var(--accent); font-weight: 800; font-size: 13px; margin-bottom: 8px; }
.step b { display: block; margin-bottom: 4px; }
.step span { font-size: 14px; color: var(--muted); }

.checks { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
@media (max-width: 720px) { .checks { grid-template-columns: 1fr; } }
.check { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; font-size: 14.5px; }
.check code { font-size: 12.5px; color: var(--accent); }
.check p { margin: 4px 0 0; color: var(--muted); }

.run pre { margin: 0 0 12px; }
.run p { color: var(--muted); }
footer { border-top: 1px solid var(--line); padding: 22px 0 40px; color: var(--muted); font-size: 14px; }
footer a { color: inherit; }
</style>
</head>
<body>
<main class="wrap">
  <header class="hero">
    <div class="eyebrow">Portfolio project · document automation</div>
    <h1>Doc2Sheet</h1>
    <p class="lede">Turn invoices and receipts (PDFs, scans, phone photos) into clean spreadsheet rows.
      A vision LLM reads each document, and <strong>deterministic checks re-do the arithmetic</strong>, so a wrong
      total gets flagged instead of slipping into your books.</p>
    <div class="cta">
      <a class="btn primary" id="gh" href="#">View the code on GitHub</a>
      <a class="btn" href="#run">Run it yourself</a>
    </div>
    <p class="note" id="provenance"></p>
  </header>

  <section class="stats" id="stats" aria-label="Summary"></section>

  <section class="section" aria-labelledby="results-h">
    <h2 id="results-h">Real results on four sample documents</h2>
    <p class="sub">Pick a document to see what was extracted and what the checks said. All four samples are fictional.</p>
    <div class="tabs" id="tabs" role="tablist" aria-label="Sample documents"></div>
    <div class="panel" id="panel" role="tabpanel"></div>
  </section>

  <section class="section" aria-labelledby="how-h">
    <h2 id="how-h">How it works</h2>
    <p class="sub">One model call per document, surrounded by plain code that doesn't trust the model.</p>
    <div class="steps">
      <div class="step"><b>Load</b><span>PDF pages are rendered to images; a digital PDF's text layer is kept too.</span></div>
      <div class="step"><b>Read</b><span>Any OpenAI-compatible vision model returns JSON against a strict schema.</span></div>
      <div class="step"><b>Validate</b><span>Pydantic parses money and dates (1.234,50 € · 01.09.2026). Malformed output gets one repair round.</span></div>
      <div class="step"><b>Check</b><span>Line maths, items vs subtotal, subtotal − discount + charges + tax = total, dates, currency.</span></div>
      <div class="step"><b>Export</b><span>Colour-coded Excel (Documents · Line items · Issues), CSV and JSON.</span></div>
    </div>
  </section>

  <section class="section" aria-labelledby="checks-h">
    <h2 id="checks-h">What the checks catch</h2>
    <p class="sub">Each document ends up <span class="pill ok">ok</span>, <span class="pill review">review</span> or <span class="pill failed">failed</span>.</p>
    <div class="checks">
      <div class="check"><code>total_mismatch</code><p>Subtotal, discount, charges and tax don't add up to the printed total. Tax-inclusive pricing is recognised.</p></div>
      <div class="check"><code>line_math</code> · <code>items_vs_subtotal</code><p>A quantity × unit price that doesn't match its line, or lines that don't sum to the subtotal.</p></div>
      <div class="check"><code>due_before_issue</code> · <code>future_date</code><p>Impossible dates. Ambiguous ones like 05/03/2026 are refused rather than guessed.</p></div>
      <div class="check"><code>missing_*</code> · <code>invalid_currency</code><p>No total, vendor, date or ISO currency code, so a person should take a look.</p></div>
    </div>
  </section>

  <section class="section run" id="run" aria-labelledby="run-h">
    <h2 id="run-h">Run it yourself</h2>
    <p class="sub">Web UI, batch CLI and Python API. Works with Hugging Face Inference Providers, OpenAI, Gemini, OpenRouter, or fully offline with Ollama.</p>
<pre><code>git clone <span id="clone"></span>
cd doc2sheet
pip install -e ".[app]"
# put HF_TOKEN=hf_... in .env (or point DOC2SHEET_BASE_URL at Ollama)
python app.py                                  # web UI on http://127.0.0.1:7860
python -m doc2sheet invoices/ -o results.xlsx  # a whole folder → one workbook</code></pre>
    <p>Hosting a live Gradio demo on Hugging Face now requires a paid plan, so this page shows recorded results instead.</p>
  </section>

  <footer>
    Built by <a id="author" href="#">yesyesyanyan</a> · MIT licence · <a id="gh2" href="#">source &amp; docs</a>
  </footer>
</main>

<script id="data" type="application/json">{"model": "google/gemma-4-31B-it", "recorded": "27 Sep 2026", "github": "https://github.com/yesyesyanyan/doc2sheet", "author_url": "https://github.com/yesyesyanyan", "results": [{"source": "invoice_pixel_pine_eur.pdf", "document": {"document_type": "invoice", "vendor_name": "Pixel & Pine Design Studio SARL", "vendor_address": "14 Rue des Exemples\n69002 Lyon, France", "vendor_tax_id": "FR00999999999", "customer_name": "Maple Street Bakery Ltd", "document_number": "INV-2026-0142", "issue_date": "2026-09-01", "due_date": "2026-10-01", "currency": "EUR", "subtotal": 2575.0, "discount": null, "other_charges": null, "tax": 515.0, "total": 3090.0, "line_items": [{"description": "Brand identity workshop (half day)", "quantity": 1.0, "unit_price": 850.0, "amount": 850.0}, {"description": "Logo design - 3 concepts, 2 revisions", "quantity": 1.0, "unit_price": 1200.0, "amount": 1200.0}, {"description": "Business card layout", "quantity": 2.0, "unit_price": 150.0, "amount": 300.0}, {"description": "Social media templates", "quantity": 5.0, "unit_price": 45.0, "amount": 225.0}]}, "issues": [], "model": "google/gemma-4-31B-it", "pages": 1, "elapsed_seconds": 42.09, "error": null, "status": "ok"}, {"source": "invoice_harbor_vine_scanned.pdf", "document": {"document_type": "invoice", "vendor_name": "Harbor & Vine Catering Pty Ltd", "vendor_address": "3/18 Example Wharf\nSydney NSW 2000, Australia", "vendor_tax_id": "00 000 000 000", "customer_name": "Lumen Analytics", "document_number": "1045", "issue_date": "2026-07-22", "due_date": "2026-08-05", "currency": "AUD", "subtotal": 630.0, "discount": null, "other_charges": 35.0, "tax": 66.5, "total": 731.5, "line_items": [{"description": "Canape platter (serves 20)", "quantity": 3.0, "unit_price": 120.0, "amount": 360.0}, {"description": "Event staff (hours)", "quantity": 6.0, "unit_price": 45.0, "amount": 270.0}]}, "issues": [], "model": "google/gemma-4-31B-it", "pages": 1, "elapsed_seconds": 48.7, "error": null, "status": "ok"}, {"source": "receipt_blue_heron_photo.png", "document": {"document_type": "receipt", "vendor_name": "BLUE HERON COFFEE CO.", "vendor_address": "400 Example Ave, Seattle WA", "vendor_tax_id": null, "customer_name": null, "document_number": "A-3317", "issue_date": "2026-09-14", "due_date": null, "currency": "USD", "subtotal": 27.75, "discount": null, "other_charges": 4.0, "tax": 2.87, "total": 34.62, "line_items": [{"description": "Oat Latte", "quantity": 2.0, "unit_price": null, "amount": 10.5}, {"description": "Blueberry Scone", "quantity": 1.0, "unit_price": 3.75, "amount": 3.75}, {"description": "Cold Brew", "quantity": 1.0, "unit_price": 4.5, "amount": 4.5}, {"description": "Avocado Toast", "quantity": 1.0, "unit_price": 9.0, "amount": 9.0}]}, "issues": [], "model": "google/gemma-4-31B-it", "pages": 1, "elapsed_seconds": 29.13, "error": null, "status": "ok"}, {"source": "invoice_kestrel_total_error.pdf", "document": {"document_type": "invoice", "vendor_name": "Kestrel Logistics Ltd", "vendor_address": "Unit 4, Example Trading Estate\nManchester M00 0AA, United Kingdom", "vendor_tax_id": "GB000000000", "customer_name": "Oakridge Garden Supplies", "document_number": "KL-88213", "issue_date": "2026-08-12", "due_date": "2026-09-11", "currency": "GBP", "subtotal": 383.4, "discount": null, "other_charges": null, "tax": 76.68, "total": 469.08, "line_items": [{"description": "Pallet freight Manchester -> Leeds", "quantity": 4.0, "unit_price": 85.0, "amount": 340.0}, {"description": "Tail-lift surcharge", "quantity": 1.0, "unit_price": 25.0, "amount": 25.0}, {"description": "Fuel surcharge", "quantity": 1.0, "unit_price": 18.4, "amount": 18.4}]}, "issues": [{"level": "error", "code": "total_mismatch", "message": "Totals don't add up: subtotal 383.40 + tax 76.68 = 460.08, but the document total is 469.08.", "field": "total"}], "model": "google/gemma-4-31B-it", "pages": 1, "elapsed_seconds": 20.24, "error": null, "status": "review"}], "samples": {"invoice_pixel_pine_eur.pdf": {"title": "Studio invoice · EUR", "note": "Digital PDF with European formatting: 2 575,00 € and dd.mm.yyyy dates.", "image": "assets/invoice_pixel_pine_eur.jpg", "thumb": "assets/invoice_pixel_pine_eur_thumb.jpg"}, "invoice_harbor_vine_scanned.pdf": {"title": "Scanned invoice · AUD", "note": "Image-only scan, slightly rotated, with no text layer. Delivery is a separate charge plus 10% GST.", "image": "assets/invoice_harbor_vine_scanned.jpg", "thumb": "assets/invoice_harbor_vine_scanned_thumb.jpg"}, "receipt_blue_heron_photo.png": {"title": "Receipt photo · USD", "note": "Phone photo of a till receipt, with sales tax and a tip. '2 x Oat Latte $10.50' is a line total.", "image": "assets/receipt_blue_heron_photo.jpg", "thumb": "assets/receipt_blue_heron_photo_thumb.jpg"}, "invoice_kestrel_total_error.pdf": {"title": "Wrong total · GBP", "note": "Built with a deliberate £9.00 error in the printed total. The model copies it faithfully and the check catches it.", "image": "assets/invoice_kestrel_total_error.jpg", "thumb": "assets/invoice_kestrel_total_error_thumb.jpg"}}}</script>
<script>
(function () {
  var DATA = JSON.parse(document.getElementById("data").textContent);
  var R = DATA.results;
  function esc(s) {
    return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
      return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
    });
  }
  function money(v, cur) {
    if (v == null) return null;
    try {
      return new Intl.NumberFormat("en-GB", { style: "currency", currency: cur || "XXX", currencyDisplay: "code" }).format(v).replace("XXX", "").trim();
    } catch (e) { return Number(v).toFixed(2); }
  }
  function num(v) { return v == null ? "" : Number(v).toLocaleString("en-GB", { maximumFractionDigits: 3 }); }
  function amt(v) { return v == null ? "—" : Number(v).toLocaleString("en-GB", { minimumFractionDigits: 2, maximumFractionDigits: 3 }); }

  // Links
  ["gh", "gh2"].forEach(function (id) { document.getElementById(id).href = DATA.github; });
  document.getElementById("author").href = DATA.author_url;
  document.getElementById("clone").textContent = DATA.github + ".git";
  document.getElementById("provenance").innerHTML =
    "Everything below is <b>real output from <code>" + esc(DATA.model) + "</code></b> (via Hugging Face Inference Providers), recorded on " +
    esc(DATA.recorded) + ". Nothing on this page calls a model; the page just displays that saved run.";

  // Stats
  var ok = R.filter(function (r) { return r.status === "ok"; }).length;
  var review = R.filter(function (r) { return r.status === "review"; }).length;
  var avg = R.reduce(function (a, r) { return a + (r.elapsed_seconds || 0); }, 0) / Math.max(R.length, 1);
  document.getElementById("stats").innerHTML = [
    [R.length, "documents: PDF, scan and photo"],
    [ok, "passed every check"],
    [review, "flagged for a human to review"],
    [Math.round(avg) + " s", "average model time per document"]
  ].map(function (s) { return '<div class="stat"><b>' + esc(s[0]) + "</b><span>" + esc(s[1]) + "</span></div>"; }).join("");

  // Tabs
  var tabs = document.getElementById("tabs");
  tabs.innerHTML = R.map(function (r, i) {
    var s = DATA.samples[r.source] || {};
    return '<button class="tab" role="tab" id="tab-' + i + '" aria-controls="panel" aria-selected="false" data-i="' + i + '">' +
      '<img src="' + esc(s.thumb) + '" alt="">' +
      '<span class="t"><span class="name">' + esc(s.title || r.source) + '</span>' +
      '<span class="pill ' + esc(r.status) + '">' + esc(r.status) + "</span></span></button>";
  }).join("");

  function field(label, value) {
    var empty = value == null || value === "";
    return "<div><dt>" + esc(label) + '</dt><dd class="' + (empty ? "none" : "") + '">' + (empty ? "not on document" : esc(value)) + "</dd></div>";
  }

  function render(i) {
    var r = R[i], d = r.document || {}, s = DATA.samples[r.source] || {}, cur = d.currency;
    Array.prototype.forEach.call(tabs.children, function (b, j) { b.setAttribute("aria-selected", String(i === j)); });
    document.getElementById("panel").setAttribute("aria-labelledby", "tab-" + i);

    var verdict;
    if (r.status === "ok") {
      verdict = '<div class="verdict ok"><span class="icon">✓</span><span class="msg"><b>All checks passed.</b> Totals, line maths, dates and currency are consistent.</span></div>';
    } else if (r.status === "review") {
      verdict = '<div class="verdict review"><span class="icon">!</span><span class="msg"><b>Needs review.</b> ' +
        r.issues.map(function (x) { return esc(x.message); }).join("<br>") + "</span></div>";
    } else {
      verdict = '<div class="verdict failed"><span class="icon">×</span><span class="msg"><b>Failed.</b> ' + esc(r.error) + "</span></div>";
    }

    var flagged = r.issues.some(function (x) { return x.code === "total_mismatch"; });
    var items = (d.line_items || []).map(function (it) {
      return "<tr><td>" + esc(it.description) + '</td><td class="num">' + esc(num(it.quantity)) + '</td><td class="num ' + (it.unit_price == null ? "muted" : "") + '">' +
        esc(amt(it.unit_price)) + '</td><td class="num">' + esc(amt(it.amount)) + "</td></tr>";
    }).join("");
    var totals = [["Subtotal", d.subtotal], ["Discount", d.discount], ["Other charges", d.other_charges], ["Tax", d.tax]]
      .filter(function (t) { return t[1] != null; })
      .map(function (t) { return "<tr><td>" + t[0] + '</td><td class="num">' + esc(money(t[1], cur)) + "</td></tr>"; }).join("") +
      '<tr class="grand' + (flagged ? " flag" : "") + '"><td>Total</td><td class="num">' + esc(money(d.total, cur) || "—") + "</td></tr>";

    var json = JSON.stringify({ status: r.status, document: d, issues: r.issues }, null, 2);

    document.getElementById("panel").innerHTML =
      '<figure class="doc"><a href="' + esc(s.image) + '" target="_blank" rel="noopener"><img src="' + esc(s.image) + '" alt="' + esc(s.title) + '"></a>' +
      "<figcaption>" + esc(s.note) + "</figcaption></figure>" +
      '<div class="data">' + verdict +
      '<dl class="fields">' +
        field("Vendor", d.vendor_name) + field("Customer", d.customer_name) +
        field("Number", d.document_number) + field("Type", d.document_type) +
        field("Issue date", d.issue_date) + field("Due date", d.due_date) +
        field("Currency", d.currency) + field("Vendor tax ID", d.vendor_tax_id) +
      "</dl>" +
      '<div class="tablewrap"><table><thead><tr><th>Line item</th><th class="num">Qty</th><th class="num">Unit</th><th class="num">Amount</th></tr></thead><tbody>' +
        items + "</tbody></table></div>" +
      '<table class="totals"><tbody>' + totals + "</tbody></table>" +
      "<details><summary>Show the JSON</summary><pre>" + esc(json) + "</pre></details>" +
      '<div class="meta">' + esc(r.source) + " · " + esc(r.pages) + " page(s) · " + esc(r.elapsed_seconds) + " s · " + esc(r.model) + "</div>" +
      "</div>";
  }

  tabs.addEventListener("click", function (e) {
    var b = e.target.closest(".tab");
    if (b) render(Number(b.getAttribute("data-i")));
  });
  tabs.addEventListener("keydown", function (e) {
    var cur = Array.prototype.findIndex.call(tabs.children, function (b) { return b.getAttribute("aria-selected") === "true"; });
    var next = e.key === "ArrowRight" ? cur + 1 : e.key === "ArrowLeft" ? cur - 1 : null;
    if (next == null) return;
    next = (next + R.length) % R.length;
    render(next);
    tabs.children[next].focus();
  });
  render(0);
})();
</script>
</body>
</html>