albertobarnabo commited on
Commit
3f7d117
·
verified ·
1 Parent(s): e015e78

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ fonts/IBMPlexMono-Bold.ttf filter=lfs diff=lfs merge=lfs -text
62
+ fonts/JetBrainsMono-Variable.ttf filter=lfs diff=lfs merge=lfs -text
63
+ fonts/IBMPlexMono-Regular.ttf filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - de
6
+ - it
7
+ - fr
8
+ task_categories:
9
+ - image-to-text
10
+ - object-detection
11
+ size_categories:
12
+ - 10K<n<100K
13
+ tags:
14
+ - ocr
15
+ - receipts-ocr
16
+ - receipt
17
+ - receipts
18
+ - invoice
19
+ - document-ai
20
+ - kie
21
+ - key-information-extraction
22
+ - document-parsing
23
+ - bounding-boxes
24
+ - synthetic
25
+ - donut
26
+ - layoutlm
27
+ - text-recognition
28
+ pretty_name: "Synthetic Receipts OCR — 32k receipts, word boxes, structured fields"
29
+ ---
30
+
31
+ # synthetic-receipts-ocr
32
+
33
+ **32,000 synthetic thermal receipts across 5 locales (US/UK/DE/IT/FR), each with pixel-exact word bounding boxes, full transcription, and structured key-information fields — as both a clean render and a photo-degraded pair.** Built for training and evaluating receipt OCR, document KIE (Donut/LayoutLM-style), text detection, and denoising models.
34
+
35
+ Every number on every receipt **adds up**: line totals × quantities, per-class contained VAT (`ENTH. MwSt 7%`, `DONT TVA 5,5%`, `DI CUI IVA 22%`), US sales tax, cash tendered and change. Models trained on receipts whose math is wrong learn to hallucinate totals; these don't lie.
36
+
37
+ ## What's in a sample?
38
+
39
+ | column | what |
40
+ |---|---|
41
+ | `image_clean` | PNG, the rendered receipt (thermal-printer aesthetic, 2 font families) |
42
+ | `image_photo` | JPEG, photo-realistic degradation: perspective on a surface, uneven lighting, shadow bands, thermal fade, noise, blur, JPEG grunge |
43
+ | `full_text` | exact printed text, line by line |
44
+ | `words` | word-level boxes on `image_clean` — **exact by construction** (captured during rendering, never re-OCR'd) |
45
+ | `words_photo` | the same boxes mapped into `image_photo` space (axis-aligned hulls) |
46
+ | `homography` | the 3×3 matrix mapping clean → photo coordinates, so you can map anything else |
47
+ | `fields` | structured KIE ground truth: merchant, address, phone, tax id (P.IVA / USt-IdNr / SIRET / VAT No), date, time, receipt no, line items (name, qty, unit price, total, tax rate, **source product title**), subtotal, per-class taxes, total, payment, tendered, change, loyalty |
48
+ | `locale`, `font`, `degradations`, `n_items` | metadata for slicing |
49
+
50
+ **The ground-truth contract: a field is non-null if and only if its value is printed on the image.** No invisible labels to hallucinate.
51
+
52
+ ## Why synthetic — and what that honestly means
53
+
54
+ Real receipt datasets are small (CORD ~1k, SROIE ~1k) because receipts are private. Synthetic generation trades realism risk for three things you can't otherwise have: **scale, perfect labels, and zero privacy exposure**. This dataset is **100% synthetic and says so** — no synthetic data is presented as real. What makes it less artificial than most:
55
+
56
+ - **Line items are real product vocabulary**: 60,000 product titles from the Amazon ESCI dataset (Apache-2.0), run through a thermal-printer abbreviator (`NNSTCK FRY PAN 12`), with the untruncated source title kept in the ground truth — every item name traces to a real product.
57
+ - **Locale realism is enforced, not decorative**: real VAT rate structures per country, locale-true currency/decimal/date formats (`1.234,56 EUR`, `5,5%`), localized section labels (SCONTRINO/BELEG/TICKET, TOTALE/SUMME, RESTO/RUECKGELD), locale-correct phone formats and address order, printed tax registration numbers.
58
+ - **It was adversarially QA'd across three review rounds before publication**: independent inspectors recomputed every number from pixels and ground truth, checked box alignment at 4× zoom, and audited locale consistency — first on a pilot batch (7 systematic defect classes found and fixed: misbound quantity lines, glyph-clipping boxes, a VAT-label rounding bug, unprintable ground truth), then again on samples drawn from the actual production run (2 more: a printed-name/label desync on narrow layouts, a trademarked footer slogan — both fixed, all 32,000 samples regenerated). Category-blind VAT assignment and anglophone merchant names on EU receipts were also caught and fixed (reduced VAT rates now go to food-adjacent items only; Italian receipts are issued by MERCATO ROSSI, not ROSSI'S GROCERY). Finally, every sample passed a machine validation gate — arithmetic, label-locale conventions, and the printed-only contract — shipped in this repo as `generator/validate.py`.
59
+
60
+ **Limitations, plainly**: monospace thermal-style receipts only — no proportional-font layouts, no handwriting, no 3D crumple, no logos/barcodes yet. Five locales, Latin script. The degradations are parametric, not photographs. **Transfer to real receipt photos is plausible but unmeasured until someone evaluates on real data** — if you do, please share numbers in a discussion.
61
+
62
+ ## The eval split measures generalization, not memorization
63
+
64
+ `eval` (2,000 receipts) shares **no font** (JetBrains Mono, unseen in train), **no product title** (held-out vocabulary slice), and **no merchant surname** with `train` (30,000). Same generator, disjoint surface distribution — so eval performance means your model learned receipt structure, not these particular pixels.
65
+
66
+ ## How do I use it?
67
+
68
+ ```python
69
+ from datasets import load_dataset
70
+ import json, io
71
+ from PIL import Image
72
+
73
+ ds = load_dataset("albertobarnabo/synthetic-receipts-ocr", split="train")
74
+ s = ds[0]
75
+ img = Image.open(io.BytesIO(s["image_photo"]))
76
+ fields = json.loads(s["fields"])
77
+ words = json.loads(s["words_photo"])
78
+ print(fields["merchant"], fields["total"], len(words), "words")
79
+ ```
80
+
81
+ Train a Donut-style KIE model on (`image_photo`, `fields`); an OCR/text-recognition model on (`image_photo`, `full_text`); a text detector on (`image_photo`, `words_photo`); a denoiser on (`image_photo` → `image_clean`). The homography supports anything geometric.
82
+
83
+ ## Provenance & reproduction
84
+
85
+ The **entire generator ships in this repo** (`generator/`): content model, renderer, degradation pipeline, validation gate, and the OFL fonts. Every receipt is a pure function of `(seed, index)` — regenerate, extend to new locales, or scale to millions. Product vocabulary derives from [tasksource/esci](https://huggingface.co/datasets/tasksource/esci) (Apache-2.0). Fonts: Space Mono, IBM Plex Mono, JetBrains Mono (OFL).
86
+
87
+ Related work from the same author: [the e-commerce search stack](https://huggingface.co/collections/albertobarnabo/the-e-commerce-search-stack-6a61ce392b12ab400f276b31) — the ESCI-trained retrieval models whose corpus supplies this dataset's product vocabulary.
data/eval-0000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e924aa73d8b77531a3241555a2ba8c1e4b397060ae4a2fde1416ff006e5af18a
3
+ size 239484303
data/train-0000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0a1298c0ebc8dbf8d7880f739ea97916538d493b288ae30b30a3ce59d501838
3
+ size 241797273
data/train-0001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d291b08d8175cf4d7f0a15e490f79fd52a27877c0ddbf46d62d2a723f684138
3
+ size 243076181
data/train-0002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e9ffcae89f1e7185b4d9050bab0acc39ddd490817061d5abf7a15afb49e3c3d
3
+ size 244539495
data/train-0003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7fc43128a09bbe889f7b619a665bb634934c3570cd60027ff25e6823bf31c9e8
3
+ size 242766418
data/train-0004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc7e4f5ca8a7fa5c0ad6722be654b4b1c963345d7df560f0f2a67939904f2cab
3
+ size 242987176
data/train-0005.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9cd58b34a8dcec5f9a8290a48fb9367754b007bab5d824f5c2a06a31de79421
3
+ size 239180397
data/train-0006.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bfca189bcbf73b40253494f3e23a9ec19eed2b56625b58aaf0a2da671e6e066
3
+ size 241453161
data/train-0007.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f6cdec9c9c5513205c2709307bfb0190d10f883d66f50c01211e89780ee336a
3
+ size 242550293
data/train-0008.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a2ee8f7222462dc8d6f172847f7c174aa41b93adbb77ea9270db6a7354c5104e
3
+ size 239833279
data/train-0009.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a72b27bc6fd190d21875110db3cf5899a026cc05b9f6b21b7df9426511922eab
3
+ size 241627631
data/train-0010.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:185fc34c2cd3b2cc9eff364fcc15509c18952858ad2a49d2f875790171d7f3ae
3
+ size 244395540
data/train-0011.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:926795094e6e511b731926a09788c0698278d09c6190b32ef81b659e390bbbdc
3
+ size 241101809
data/train-0012.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e76d3b1de019af047407a10619ec296f3de383c80aa37d4df837961ee1c97586
3
+ size 242663649
data/train-0013.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cafe148f424976176f7866104a3395092f6af299dfe62e411315ac26134efaa
3
+ size 241166700
data/train-0014.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8ecbb43c2b96dc5978ff99db0050f3a5696a4f3a6fefe2451ca07d007295122
3
+ size 241842613
fonts/IBMPlexMono-Bold.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac27abd6450a64dd94467580a02fe6235156d5b92f2926ebbc8e7489df64e0be
3
+ size 137784
fonts/IBMPlexMono-Regular.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a3412f058c7d8dfd9170c41e85ade48e5156ecb89356110ca57a0a27734af46
3
+ size 135580
fonts/JetBrainsMono-Variable.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48715a42ec242c21e9f02692891e147d022299a52e48d5e413e1a942193ffeda
3
+ size 187208
fonts/SpaceMono-Bold.ttf ADDED
Binary file (98.2 kB). View file
 
fonts/SpaceMono-Regular.ttf ADDED
Binary file (99.4 kB). View file
 
generator/build.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble the dataset: (clean, degraded, text, words, fields) -> parquet.
2
+
3
+ Split policy — eval generalization is measured, not assumed:
4
+ train: SpaceMono + IBM Plex fonts, product vocab [0:55000], merchant pool A
5
+ eval: JetBrains Mono ONLY, product vocab [55000:60000], merchant pool B
6
+ so an eval receipt shares no font, no product string, and no merchant surname
7
+ with train. Same generator code, disjoint surface distribution.
8
+
9
+ Usage: build.py --split train --n 30000 --out data/shards [--workers 8]
10
+ build.py --split eval --n 2000 --out data/shards
11
+ """
12
+ import argparse
13
+ import io
14
+ import json
15
+ import random
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
20
+ from content import ContentGenerator, Receipt
21
+ from degrade import degrade, map_boxes
22
+ from render import ReceiptRenderer
23
+ import render as render_mod
24
+
25
+ SPLIT_CFG = {
26
+ "train": dict(seed=11, vocab_lo=0, vocab_hi=55000,
27
+ fonts=[("SpaceMono-Regular.ttf", "SpaceMono-Bold.ttf"),
28
+ ("IBMPlexMono-Regular.ttf", "IBMPlexMono-Bold.ttf")],
29
+ surnames=["ROSSI", "MUELLER", "SMITH", "DUBOIS", "LOPEZ", "JANSEN"]),
30
+ "eval": dict(seed=77, vocab_lo=55000, vocab_hi=60000,
31
+ fonts=[("JetBrainsMono-Variable.ttf", "JetBrainsMono-Variable.ttf")],
32
+ surnames=["KOWALSKI", "BROWN", "GARCIA", "WEBER", "MORETTI", "LARSEN"]),
33
+ }
34
+
35
+
36
+ def fields_of(r: Receipt) -> dict:
37
+ """GT contract: a field is non-null IFF its value is printed on the image."""
38
+ return {
39
+ "locale": r.locale, "merchant": r.merchant, "address": r.address,
40
+ "phone": r.phone if r.show_phone else None,
41
+ "tax_id": r.tax_id,
42
+ "date": r.date, "time": r.time,
43
+ "receipt_no": r.receipt_no, "cashier": r.cashier,
44
+ "currency": "USD" if r.locale == "US" else ("GBP" if r.locale == "UK" else "EUR"),
45
+ "lines": [{"name": l.name, "qty": l.qty, "unit_price": l.unit_price,
46
+ "total": l.total, "tax_rate": l.tax_rate,
47
+ "source_title": l.source_title} for l in r.lines],
48
+ "subtotal": r.subtotal if r.show_subtotal else None,
49
+ "taxes": [{"label": lab, "rate": rate, "amount": amt} for lab, rate, amt in r.tax_lines],
50
+ "tax_included": r.tax_included,
51
+ "total": r.total, "payment": r.payment,
52
+ "tendered": r.tendered, "change": r.change,
53
+ "loyalty": r.loyalty,
54
+ }
55
+
56
+
57
+ def png_bytes(img) -> bytes:
58
+ b = io.BytesIO(); img.save(b, "PNG", optimize=True); return b.getvalue()
59
+
60
+
61
+ def jpg_bytes(img) -> bytes:
62
+ b = io.BytesIO(); img.convert("L").save(b, "JPEG", quality=90); return b.getvalue()
63
+
64
+
65
+ def make_sample(args):
66
+ idx, split = args
67
+ cfg = SPLIT_CFG[split]
68
+ gen = _GEN[split]
69
+ ren = _REN[split]
70
+ r = gen.generate(idx)
71
+ out = ren.render(r, idx)
72
+ rng = random.Random((cfg["seed"] << 24) ^ idx)
73
+ deg, H3, notes = degrade(out.image, rng)
74
+ return {
75
+ "id": f"{split}-{idx:06d}",
76
+ "image_clean": png_bytes(out.image),
77
+ "image_photo": jpg_bytes(deg),
78
+ "full_text": out.full_text,
79
+ "words": json.dumps(out.words),
80
+ "words_photo": json.dumps(map_boxes(out.words, H3)),
81
+ "homography": json.dumps([[round(float(x), 6) for x in row] for row in H3]),
82
+ "fields": json.dumps(fields_of(r)),
83
+ "locale": r.locale,
84
+ "degradations": ",".join(notes),
85
+ "font": out.meta["font"],
86
+ "n_items": len(r.lines),
87
+ "split_policy": "heldout-font+vocab+merchants" if split == "eval" else "train",
88
+ }
89
+
90
+
91
+ _GEN, _REN = {}, {}
92
+
93
+
94
+ def _init(split):
95
+ cfg = SPLIT_CFG[split]
96
+ g = ContentGenerator(seed=cfg["seed"])
97
+ g.vocab = g.vocab[cfg["vocab_lo"]:cfg["vocab_hi"]]
98
+ g._surnames = cfg["surnames"]
99
+ render_mod.FONT_FILES = cfg["fonts"]
100
+ _GEN[split] = g
101
+ _REN[split] = ReceiptRenderer(seed=cfg["seed"])
102
+
103
+
104
+ def main():
105
+ ap = argparse.ArgumentParser()
106
+ ap.add_argument("--split", choices=["train", "eval"], required=True)
107
+ ap.add_argument("--n", type=int, required=True)
108
+ ap.add_argument("--out", default="data/shards")
109
+ ap.add_argument("--shard-size", type=int, default=2000)
110
+ args = ap.parse_args()
111
+
112
+ _init(args.split)
113
+ outdir = Path(args.out); outdir.mkdir(parents=True, exist_ok=True)
114
+ import pyarrow as pa, pyarrow.parquet as pq
115
+
116
+ buf, shard = [], 0
117
+ for i in range(args.n):
118
+ buf.append(make_sample((i, args.split)))
119
+ if len(buf) >= args.shard_size or i == args.n - 1:
120
+ table = pa.Table.from_pylist(buf)
121
+ pq.write_table(table, outdir / f"{args.split}-{shard:04d}.parquet",
122
+ compression="zstd")
123
+ print(f"shard {shard}: {len(buf)} samples (through {i+1}/{args.n})", flush=True)
124
+ buf, shard = [], shard + 1
125
+ print("DONE", args.split, args.n)
126
+
127
+
128
+ if __name__ == "__main__":
129
+ main()
generator/content.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Receipt content model v2 — everything printed, nothing unprintable in GT.
2
+
3
+ Post-QA fixes baked in (24-sample adversarial review, 2026-07-24):
4
+ - US: ONE sales-tax rate per receipt (a store has one jurisdiction); GT rate
5
+ always reproduces the printed amount exactly.
6
+ - EU labels localized (TOTALE/SUMME, CONTANTI/BAR/ESPECES, RESTO/RUECKGELD),
7
+ VAT % formatted exactly (5.5% never becomes 6%).
8
+ - Payment methods, phone formats (+39/+49/+1...), and address order are
9
+ locale-consistent; EC-KARTE can no longer pay for a New York deli run.
10
+ - Printed-only ground truth: phone/subtotal/loyalty appear in fields ONLY if
11
+ the renderer prints them (decided here via show_* flags).
12
+ - VAT-registered locales print a tax id (P.IVA / USt-IdNr / SIRET / VAT No),
13
+ which is also a labeled KIE field.
14
+ - Dates capped at 2025 (no future receipts in a 2026 build).
15
+ """
16
+ import json
17
+ import random
18
+ import re
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ DATA = Path(__file__).resolve().parent.parent / "data"
23
+
24
+ LOCALES = {
25
+ "US": dict(cur="$", cur_pos="pre", dec=".", thou=",", date="{m:02d}/{d:02d}/{y}",
26
+ tax_name="TAX", tax_rates=(0.04, 0.06, 0.0725, 0.0825, 0.095), tax_incl=False),
27
+ "UK": dict(cur="£", cur_pos="pre", dec=".", thou=",", date="{d:02d}/{m:02d}/{y}",
28
+ tax_name="VAT", tax_rates=(0.20,), tax_incl=True),
29
+ "DE": dict(cur="EUR", cur_pos="post", dec=",", thou=".", date="{d:02d}.{m:02d}.{y}",
30
+ tax_name="MwSt", tax_rates=(0.19, 0.07), tax_incl=True),
31
+ "IT": dict(cur="EUR", cur_pos="post", dec=",", thou=".", date="{d:02d}/{m:02d}/{y}",
32
+ tax_name="IVA", tax_rates=(0.22, 0.10, 0.04), tax_incl=True),
33
+ "FR": dict(cur="EUR", cur_pos="post", dec=",", thou=" ", date="{d:02d}/{m:02d}/{y}",
34
+ tax_name="TVA", tax_rates=(0.20, 0.055), tax_incl=True),
35
+ }
36
+
37
+ STORE_KINDS = {
38
+ "US": ["MARKET", "SUPERMARKET", "MINIMART", "TRADING", "STORES", "EXPRESS", "CORNER SHOP"],
39
+ "UK": ["MARKET", "SUPERMARKET", "MINIMART", "STORES", "EXPRESS", "CORNER SHOP"],
40
+ "DE": ["MARKT", "SUPERMARKT", "KAUFHAUS", "HANDEL"],
41
+ "IT": ["MERCATO", "SUPERMERCATO", "EMPORIO", "MERCERIA"],
42
+ "FR": ["MARCHE", "SUPERMARCHE", "BAZAR", "COMPTOIR"],
43
+ }
44
+
45
+ FLAVOR = {
46
+ "US": dict(streets=["MAIN ST", "ELM AVE", "OAK BLVD", "5TH AVENUE", "MAPLE DR", "BROADWAY"],
47
+ addr="num-first",
48
+ cashiers=["ANNA", "MIKE", "J.SMITH", "OP-04", "TILL 3", "REG 02"],
49
+ rcpt="RECEIPT",
50
+ payments=["CASH", "VISA DEBIT", "VISA CREDIT", "MASTERCARD", "AMEX",
51
+ "CONTACTLESS", "APPLE PAY"],
52
+ labels=dict(subtotal="SUBTOTAL", total="TOTAL", cash="CASH", change="CHANGE",
53
+ incl="INCL"),
54
+ loyalty="LOYALTY PTS +{n}",
55
+ phone="us",
56
+ tax_id=None,
57
+ footers=["THANK YOU FOR SHOPPING WITH US", "PLEASE COME AGAIN", "HAVE A NICE DAY",
58
+ "RETURNS WITHIN 30 DAYS WITH RECEIPT", "ALL ITEMS SUBJECT TO AVAILABILITY"]),
59
+ "UK": dict(streets=["HIGH STREET", "STATION RD", "KING ST", "PARK LANE", "CHURCH LANE"],
60
+ addr="num-first",
61
+ cashiers=["TILL 3", "TILL 1", "S. PATEL", "OP-11", "EMMA"],
62
+ rcpt="RECEIPT",
63
+ payments=["CASH", "VISA DEBIT", "MASTERCARD", "CONTACTLESS", "APPLE PAY", "MAESTRO"],
64
+ labels=dict(subtotal="SUBTOTAL", total="TOTAL", cash="CASH", change="CHANGE",
65
+ incl="INCL"),
66
+ loyalty="LOYALTY PTS +{n}",
67
+ phone="uk",
68
+ tax_id="uk",
69
+ footers=["THANK YOU FOR SHOPPING WITH US", "KEEP RECEIPT FOR RETURNS", "PLEASE COME AGAIN"]),
70
+ "DE": dict(streets=["BAHNHOFSTR.", "HAUPTSTR.", "GARTENWEG", "MARKTPLATZ", "SCHILLERSTR."],
71
+ addr="street-first",
72
+ cashiers=["KASSE 2", "KASSE 1", "S. WEBER", "BED. 04"],
73
+ rcpt="BELEG",
74
+ payments=["BAR", "EC-KARTE", "GIROCARD", "VISA", "MASTERCARD", "KONTAKTLOS"],
75
+ labels=dict(subtotal="ZWISCHENSUMME", total="SUMME", cash="BAR",
76
+ change="RUECKGELD", incl="ENTH."),
77
+ loyalty="PUNKTE +{n}",
78
+ phone="de",
79
+ tax_id="de",
80
+ footers=["VIELEN DANK FUER IHREN EINKAUF", "AUF WIEDERSEHEN", "BITTE BELEG AUFBEWAHREN"]),
81
+ "IT": dict(streets=["VIA ROMA", "CORSO ITALIA", "VIA GARIBALDI", "PIAZZA DANTE", "VIA VERDI"],
82
+ addr="street-first",
83
+ cashiers=["CASSA 2", "CASSA 1", "LUCIA", "OP. 03"],
84
+ rcpt="SCONTRINO",
85
+ payments=["CONTANTI", "BANCOMAT", "VISA", "MASTERCARD", "CARTA CONTACTLESS"],
86
+ labels=dict(subtotal="SUBTOTALE", total="TOTALE", cash="CONTANTI",
87
+ change="RESTO", incl="DI CUI"),
88
+ loyalty="PUNTI +{n}",
89
+ phone="it",
90
+ tax_id="it",
91
+ footers=["GRAZIE E ARRIVEDERCI", "CONSERVARE LO SCONTRINO", "GRAZIE PER LA VISITA"]),
92
+ "FR": dict(streets=["RUE DE LA GARE", "AVENUE VICTOR HUGO", "RUE DU MARCHE", "BD SAINT-MICHEL"],
93
+ addr="street-first",
94
+ cashiers=["CAISSE 1", "CAISSE 2", "MARIE", "OP. 07"],
95
+ rcpt="TICKET",
96
+ payments=["ESPECES", "CB", "VISA", "MASTERCARD", "SANS CONTACT"],
97
+ labels=dict(subtotal="SOUS-TOTAL", total="TOTAL", cash="ESPECES",
98
+ change="RENDU", incl="DONT"),
99
+ loyalty="POINTS FIDELITE +{n}",
100
+ phone="fr",
101
+ tax_id="fr",
102
+ footers=["MERCI DE VOTRE VISITE", "A BIENTOT", "CONSERVEZ VOTRE TICKET"]),
103
+ }
104
+
105
+ _PHONE = {
106
+ "us": lambda rng: f"+1 ({rng.randint(201,989)}) {rng.randint(200,999)}-{rng.randint(1000,9999)}",
107
+ "uk": lambda rng: f"+44 {rng.randint(1200,7999)} {rng.randint(100000,999999)}",
108
+ "de": lambda rng: f"+49 {rng.randint(30,89)} {rng.randint(1000000,9999999)}",
109
+ "it": lambda rng: f"+39 0{rng.randint(2,9)} {rng.randint(1000000,9999999)}",
110
+ "fr": lambda rng: f"+33 {rng.randint(1,5)} " + " ".join(f"{rng.randint(10,99)}" for _ in range(4)),
111
+ }
112
+ _TAX_ID = {
113
+ "uk": lambda rng: f"VAT NO GB{rng.randint(100000000,999999999)}",
114
+ "de": lambda rng: f"USt-IdNr DE{rng.randint(100000000,999999999)}",
115
+ "it": lambda rng: f"P.IVA {rng.randint(10000000000,99999999999)}",
116
+ "fr": lambda rng: f"SIRET {rng.randint(10000000000000,99999999999999)}",
117
+ }
118
+
119
+ _VOWELS = str.maketrans("", "", "aeiouAEIOU")
120
+ _CASH_WORDS = {"CASH", "BAR", "CONTANTI", "ESPECES"}
121
+ _FOOD_WORDS = re.compile(r"\b(coffee|tea|chocolate|candy|snack|cookie|biscuit|pasta|sauce|"
122
+ r"oil|olive|milk|juice|water|soda|cereal|granola|honey|jam|spice|"
123
+ r"seasoning|flour|sugar|rice|bean|nut|dried|organic|gluten.free|"
124
+ r"protein|vitamin|supplement|food|grocery)\b", re.I)
125
+
126
+
127
+ def _abbrev_word(w: str, rng: random.Random) -> str:
128
+ if len(w) <= 4 or w.isdigit():
129
+ return w
130
+ style = rng.random()
131
+ if style < 0.35:
132
+ return (w[0] + w[1:].translate(_VOWELS))[:8]
133
+ if style < 0.7:
134
+ return w[: rng.choice((3, 4, 5, 6))]
135
+ return w
136
+
137
+
138
+ def receipt_item_name(title: str, brand: str, rng: random.Random) -> tuple[str, str]:
139
+ """(printed item text, exact source title) — both stored, pair auditable."""
140
+ clean_title = title.strip()
141
+ words = re.sub(r"[^\w\s%/.-]", " ", clean_title).split()
142
+ lead = ""
143
+ if brand and rng.random() < 0.6:
144
+ lead = brand.upper().split()[0][:8]
145
+ words = [w for w in words if w.lower() != lead.lower()]
146
+ keep = [w for w in words if len(w) > 2 or w.isdigit()][: rng.choice((2, 3, 3, 4))]
147
+ out = " ".join(_abbrev_word(w, rng).upper() for w in keep)
148
+ out = (f"{lead} {out}" if lead else out).strip()
149
+ return out[:24] or "ITEM", clean_title
150
+
151
+
152
+ @dataclass
153
+ class Line:
154
+ name: str
155
+ qty: int
156
+ unit_price: float
157
+ total: float
158
+ tax_rate: float
159
+ source_title: str
160
+
161
+
162
+ @dataclass
163
+ class Receipt:
164
+ locale: str
165
+ merchant: str
166
+ address: str
167
+ phone: str
168
+ show_phone: bool
169
+ tax_id: str | None
170
+ date: str
171
+ time: str
172
+ receipt_no: str
173
+ cashier: str
174
+ rcpt_word: str
175
+ labels: dict
176
+ lines: list = field(default_factory=list)
177
+ subtotal: float = 0.0
178
+ show_subtotal: bool = False
179
+ tax_lines: list = field(default_factory=list) # (printed_label, rate, amount)
180
+ total: float = 0.0
181
+ payment: str = ""
182
+ tendered: float | None = None
183
+ change: float | None = None
184
+ loyalty: str | None = None
185
+ footer: str = ""
186
+ tax_included: bool = False
187
+
188
+
189
+ def _pct(rate: float, dec: str = ".") -> str:
190
+ out = f"{rate * 100:g}%" # 0.055 -> '5.5%', 0.20 -> '20%'
191
+ return out.replace(".", dec) # FR/DE/IT receipts write '5,5%'
192
+
193
+
194
+ class ContentGenerator:
195
+ def __init__(self, seed: int = 0):
196
+ self.vocab = json.loads((DATA / "product_vocab.json").read_text())
197
+ self.brands = json.loads((DATA / "brand_vocab.json").read_text())
198
+ self.seed = seed
199
+
200
+ def merchant_name(self, rng: random.Random, locale: str) -> str:
201
+ kinds = STORE_KINDS[locale]
202
+ if rng.random() < 0.4:
203
+ base = rng.choice(self.brands) or "ACME"
204
+ base = re.sub(r"[^A-Za-z ]", "", base).strip().upper() or "ACME"
205
+ name = base.split()[0]
206
+ else:
207
+ pool = getattr(self, "_surnames", ["ROSSI", "MUELLER", "SMITH", "DUBOIS", "LOPEZ",
208
+ "JANSEN", "KOWALSKI", "BROWN", "GARCIA", "WEBER",
209
+ "MORETTI", "LARSEN"])
210
+ name = rng.choice(pool)
211
+ if locale in ("US", "UK"):
212
+ # possessive only in anglophone locales
213
+ lead = f"{name}'S" if rng.random() < 0.6 else name
214
+ return f"{lead} {rng.choice(kinds)}"[:28]
215
+ # romance/germanic order: SUPERMERCATO ROSSI / MARKT WEBER
216
+ return f"{rng.choice(kinds)} {name}"[:28]
217
+
218
+ def generate(self, idx: int) -> Receipt:
219
+ rng = random.Random((self.seed << 20) ^ idx)
220
+ locale = rng.choices(list(LOCALES), weights=[40, 15, 15, 15, 15])[0]
221
+ L, F = LOCALES[locale], FLAVOR[locale]
222
+
223
+ y, m, d = rng.randint(2019, 2025), rng.randint(1, 12), rng.randint(1, 28)
224
+ n_items = rng.choices((1, 2, 3, 4, 5, 6, 8, 10, 13),
225
+ weights=(5, 10, 16, 18, 16, 12, 10, 8, 5))[0]
226
+
227
+ # US: one jurisdiction, one rate per receipt. EU: per-item VAT class.
228
+ us_rate = rng.choice(L["tax_rates"])
229
+ lines, subtotal = [], 0.0
230
+ buckets: dict = {}
231
+ for _ in range(n_items):
232
+ v = rng.choice(self.vocab)
233
+ qty = rng.choices((1, 1, 1, 2, 3), weights=(60, 15, 10, 10, 5))[0]
234
+ unit = round(rng.choice((0.49, 0.79, 0.99, 1.29, 1.49, 1.99, 2.49, 2.99, 3.49,
235
+ 4.99, 5.99, 7.99, 9.99, 12.99, 14.99, 19.99, 24.99,
236
+ 29.99, 49.99)) * rng.choice((1, 1, 1, 1, 2)), 2)
237
+ if not L["tax_incl"]:
238
+ rate = us_rate
239
+ else:
240
+ rates = L["tax_rates"]
241
+ if len(rates) > 1 and _FOOD_WORDS.search(v["t"]):
242
+ rate = rng.choice(rates[1:]) # reduced classes: food-adjacent only
243
+ else:
244
+ rate = rates[0] # standard rate for general goods
245
+ name, src = receipt_item_name(v["t"], v["b"], rng)
246
+ tot = round(qty * unit, 2)
247
+ lines.append(Line(name, qty, unit, tot, rate, src))
248
+ subtotal = round(subtotal + tot, 2)
249
+ buckets[rate] = round(buckets.get(rate, 0.0) + tot, 2)
250
+
251
+ tax_lines = []
252
+ if L["tax_incl"]:
253
+ for rate, gross in sorted(buckets.items()):
254
+ amt = round(gross - gross / (1 + rate), 2)
255
+ tax_lines.append((f"{L['tax_name']} {_pct(rate, L['dec'])}", rate, amt))
256
+ total = subtotal
257
+ else:
258
+ amt = round(subtotal * us_rate, 2)
259
+ label = f"{L['tax_name']} {_pct(us_rate, L['dec'])}" if rng.random() < 0.5 else L["tax_name"]
260
+ tax_lines.append((label, us_rate, amt))
261
+ total = round(subtotal + amt, 2)
262
+
263
+ payment = rng.choice(F["payments"])
264
+ tendered = change = None
265
+ if payment in _CASH_WORDS:
266
+ step = 5.0
267
+ tendered = float(int(total // step + 1) * step) if total % step else total
268
+ if rng.random() < 0.3:
269
+ tendered = round(total + rng.choice((0.01, 0.50, 1.00, 2.00)), 2)
270
+ change = round(tendered - total, 2)
271
+
272
+ street = rng.choice(F["streets"])
273
+ num = rng.randint(1, 299)
274
+ return Receipt(
275
+ locale=locale, merchant=self.merchant_name(rng, locale),
276
+ address=f"{num} {street}" if F["addr"] == "num-first" else f"{street} {num}",
277
+ phone=_PHONE[F["phone"]](rng), show_phone=rng.random() < 0.7,
278
+ tax_id=(_TAX_ID[F["tax_id"]](rng) if (F["tax_id"] and rng.random() < 0.8) else None),
279
+ date=L["date"].format(d=d, m=m, y=y),
280
+ time=f"{rng.randint(7,22):02d}:{rng.randint(0,59):02d}",
281
+ receipt_no=f"{rng.randint(1,9)}-{rng.randint(10000,99999)}-{rng.randint(100,999)}",
282
+ cashier=rng.choice(F["cashiers"]), rcpt_word=F["rcpt"], labels=F["labels"],
283
+ lines=lines, subtotal=subtotal, show_subtotal=not L["tax_incl"],
284
+ tax_lines=tax_lines, total=total, payment=payment,
285
+ tendered=tendered, change=change,
286
+ loyalty=(F["loyalty"].format(n=rng.randint(1,99)) if rng.random() < 0.35 else None),
287
+ footer=rng.choice(F["footers"]), tax_included=L["tax_incl"],
288
+ )
289
+
290
+
291
+ def fmt_money(x: float, locale: str) -> str:
292
+ L = LOCALES[locale]
293
+ s = f"{x:,.2f}"
294
+ if L["dec"] == ",":
295
+ s = s.replace(",", "@SEP@").replace(".", ",").replace("@SEP@", L["thou"])
296
+ return f"{L['cur']}{s}" if L["cur_pos"] == "pre" else f"{s} {L['cur']}"
generator/degrade.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Photo-realistic degradation of clean receipt renders.
2
+
3
+ Every sample ships as a PAIR (clean, degraded) plus the 3x3 homography H that
4
+ maps clean-image coordinates to degraded-image coordinates. Word boxes are
5
+ exact on the clean image by construction; degraded-space boxes are the
6
+ axis-aligned hull of the box corners mapped through H — stated as such, never
7
+ pretended to be tight rotated boxes.
8
+
9
+ Degradations (each applied with probability, severity seeded):
10
+ geometric: small rotation, perspective keystone, translation on a larger
11
+ "table" background
12
+ photometric: uneven lighting gradient, hard shadow band, thermal fade bands
13
+ (the classic dying-receipt look), gaussian + salt noise, mild
14
+ blur, JPEG round-trip
15
+ """
16
+ import io
17
+ import random
18
+
19
+ import numpy as np
20
+ from PIL import Image, ImageFilter
21
+
22
+
23
+ def _perspective_coeffs(src, dst):
24
+ A = []
25
+ for (x, y), (u, v) in zip(src, dst):
26
+ A.append([x, y, 1, 0, 0, 0, -u * x, -u * y])
27
+ A.append([0, 0, 0, x, y, 1, -v * x, -v * y])
28
+ A = np.asarray(A, dtype=np.float64)
29
+ b = np.asarray([c for pt in dst for c in pt], dtype=np.float64)
30
+ h = np.linalg.solve(A, b)
31
+ return h # 8 coeffs for PIL, maps DST->SRC when used with Image.transform
32
+
33
+
34
+ def degrade(img: Image.Image, rng: random.Random):
35
+ """Returns (degraded RGB image, H 3x3 clean->degraded, notes list)."""
36
+ notes = []
37
+ w, h = img.size
38
+ # place on a slightly larger background ("photo of a receipt on a surface")
39
+ mx, my = int(w * rng.uniform(0.04, 0.14)), int(h * rng.uniform(0.03, 0.10))
40
+ W, H_ = w + 2 * mx, h + 2 * my
41
+ bg_shade = rng.randint(120, 210)
42
+ bg = Image.new("L", (W, H_), bg_shade)
43
+ bg.paste(img, (mx, my))
44
+
45
+ # target quad: perspective jitter of the pasted receipt's corners
46
+ jx, jy = w * 0.06, h * 0.03
47
+ src = [(mx, my), (mx + w, my), (mx + w, my + h), (mx, my + h)]
48
+ dst = [(sx + rng.uniform(-jx, jx), sy + rng.uniform(-jy, jy)) for sx, sy in src]
49
+ if rng.random() < 0.25: # sometimes keep it flat-scanned
50
+ dst = src
51
+ notes.append("flat")
52
+ else:
53
+ notes.append("perspective")
54
+ coeffs = _perspective_coeffs(dst, src) # PIL wants dst->src
55
+ warped = bg.transform((W, H_), Image.PERSPECTIVE, coeffs, resample=Image.BICUBIC,
56
+ fillcolor=bg_shade)
57
+
58
+ # H mapping clean (x,y) -> degraded: translate then the src->dst homography.
59
+ A = []
60
+ for (x, y), (u, v) in zip(src, dst):
61
+ A.append([x, y, 1, 0, 0, 0, -u * x, -u * y])
62
+ A.append([0, 0, 0, x, y, 1, -v * x, -v * y])
63
+ hcoef = np.linalg.solve(np.asarray(A, float),
64
+ np.asarray([c for pt in dst for c in pt], float))
65
+ Hm = np.array([[hcoef[0], hcoef[1], hcoef[2]],
66
+ [hcoef[3], hcoef[4], hcoef[5]],
67
+ [hcoef[6], hcoef[7], 1.0]])
68
+ T = np.array([[1, 0, mx], [0, 1, my], [0, 0, 1.0]])
69
+ H3 = Hm @ T
70
+
71
+ arr = np.asarray(warped, dtype=np.float32)
72
+
73
+ # uneven lighting: low-frequency MULTIPLICATIVE gradient (additive version
74
+ # clipped to a hard white band across paper AND background — QA finding)
75
+ if rng.random() < 0.8:
76
+ gx = np.linspace(rng.uniform(-1, 1), rng.uniform(-1, 1), arr.shape[1])
77
+ gy = np.linspace(rng.uniform(-1, 1), rng.uniform(-1, 1), arr.shape[0])
78
+ grad = 1.0 + np.outer(gy, gx) * rng.uniform(0.04, 0.11)
79
+ arr = arr * grad
80
+ notes.append("lighting")
81
+
82
+ # hard shadow band (phone photo classic)
83
+ if rng.random() < 0.35:
84
+ x0 = rng.randint(0, arr.shape[1] - 1)
85
+ width = rng.randint(arr.shape[1] // 6, arr.shape[1] // 2)
86
+ mask = np.zeros(arr.shape[1]); mask[x0:x0 + width] = 1
87
+ mask = np.convolve(mask, np.ones(31) / 31, mode="same")
88
+ arr = arr - mask[None, :] * rng.uniform(15, 45)
89
+ notes.append("shadow")
90
+
91
+ # thermal fade: vertical bands where the print is dying
92
+ if rng.random() < 0.4:
93
+ n_bands = rng.randint(1, 3)
94
+ for _ in range(n_bands):
95
+ y0 = rng.randint(0, arr.shape[0] - 1)
96
+ bh = rng.randint(arr.shape[0] // 12, arr.shape[0] // 5)
97
+ fade = np.zeros(arr.shape[0]); fade[y0:y0 + bh] = 1
98
+ fade = np.convolve(fade, np.ones(21) / 21, mode="same")
99
+ # push dark pixels toward paper (ink fading), leave paper alone
100
+ dark = arr < 150
101
+ arr = np.where(dark, arr + fade[:, None] * rng.uniform(40, 110), arr)
102
+ notes.append("thermal_fade")
103
+
104
+ # noise
105
+ if rng.random() < 0.85:
106
+ arr = arr + np.random.default_rng(rng.getrandbits(32)).normal(
107
+ 0, rng.uniform(2, 9), arr.shape)
108
+ notes.append("noise")
109
+
110
+ arr = np.clip(arr, 0, 255).astype(np.uint8)
111
+ out = Image.fromarray(arr, "L")
112
+
113
+ if rng.random() < 0.5:
114
+ out = out.filter(ImageFilter.GaussianBlur(rng.uniform(0.4, 1.1)))
115
+ notes.append("blur")
116
+
117
+ # JPEG round-trip grunge
118
+ q = rng.randint(55, 92)
119
+ buf = io.BytesIO()
120
+ out.convert("RGB").save(buf, "JPEG", quality=q)
121
+ out = Image.open(buf).convert("L")
122
+ notes.append(f"jpeg{q}")
123
+
124
+ return out, H3, notes
125
+
126
+
127
+ def map_boxes(words, H3):
128
+ """Clean-space word boxes -> degraded-space axis-aligned hulls."""
129
+ out = []
130
+ for wd in words:
131
+ corners = np.array([[wd["x0"], wd["y0"], 1], [wd["x1"], wd["y0"], 1],
132
+ [wd["x1"], wd["y1"], 1], [wd["x0"], wd["y1"], 1]], float).T
133
+ p = H3 @ corners
134
+ p = p[:2] / p[2]
135
+ out.append({"text": wd["text"],
136
+ "x0": float(p[0].min()), "y0": float(p[1].min()),
137
+ "x1": float(p[0].max()), "y1": float(p[1].max())})
138
+ return out
generator/render.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pillow renderer v2: Receipt -> thermal image + ink-accurate word boxes.
2
+
3
+ Post-QA fixes:
4
+ - word box y-extent comes from draw.textbbox of the actual line (real ink,
5
+ ascenders+descenders), not the nominal font size — boxes were clipping
6
+ glyph bottoms by 15-50% before
7
+ - quantity detail line ('2 x $24.99') prints UNDER its item, as real
8
+ printers do — it visually bound to the WRONG item before
9
+ - localized section labels (TOTALE / SUMME / RESTO ...), tax-id line,
10
+ phone printed iff Receipt.show_phone (GT mirrors print exactly)
11
+ """
12
+ import random
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+
16
+ from PIL import Image, ImageDraw, ImageFont
17
+
18
+ from content import Receipt, fmt_money
19
+
20
+ FONTS = Path(__file__).resolve().parent.parent / "fonts"
21
+ FONT_FILES = [("SpaceMono-Regular.ttf", "SpaceMono-Bold.ttf"),
22
+ ("IBMPlexMono-Regular.ttf", "IBMPlexMono-Bold.ttf")]
23
+
24
+
25
+ @dataclass
26
+ class Rendered:
27
+ image: Image.Image
28
+ full_text: str
29
+ words: list = field(default_factory=list)
30
+ meta: dict = field(default_factory=dict)
31
+
32
+
33
+ class ReceiptRenderer:
34
+ def __init__(self, seed: int = 0):
35
+ self.seed = seed
36
+
37
+ def render(self, r: Receipt, idx: int) -> Rendered:
38
+ rng = random.Random((self.seed << 21) ^ (idx * 2654435761))
39
+ cols = rng.choice((32, 38, 42, 48))
40
+ fsize = rng.choice((20, 22, 24))
41
+ reg_f, bold_f = FONT_FILES[rng.randrange(len(FONT_FILES))]
42
+ font = ImageFont.truetype(str(FONTS / reg_f), fsize)
43
+ bold = ImageFont.truetype(str(FONTS / bold_f), fsize)
44
+ cw = font.getbbox("M")[2]
45
+ lh = int(fsize * rng.uniform(1.25, 1.45))
46
+ pad = rng.randint(14, 30)
47
+
48
+ lines = self._layout(r, cols, rng)
49
+ W = cols * cw + 2 * pad
50
+ H = len(lines) * lh + 2 * pad + rng.randint(0, 40)
51
+ paper = rng.randint(238, 252)
52
+ img = Image.new("L", (W, H), paper)
53
+ draw = ImageDraw.Draw(img)
54
+
55
+ words, out_lines = [], []
56
+ y = pad
57
+ for text, style in lines:
58
+ f = bold if style == "bold" else font
59
+ x0 = pad + (max(0, (cols - len(text)) // 2) * cw if style == "center" else 0)
60
+ draw.text((x0, y), text, font=f, fill=rng.randint(20, 70))
61
+ if text.strip():
62
+ # real ink extent of this line (ascenders + descenders)
63
+ bb = draw.textbbox((x0, y), text, font=f)
64
+ iy0, iy1 = bb[1], bb[3]
65
+ col = 0
66
+ for w in text.split(" "):
67
+ if w and set(w) != {"-"}:
68
+ wx0 = x0 + col * cw
69
+ words.append({"text": w, "x0": wx0, "y0": iy0,
70
+ "x1": wx0 + len(w) * cw, "y1": iy1})
71
+ col += len(w) + 1
72
+ out_lines.append(text)
73
+ y += lh
74
+ return Rendered(image=img, full_text="\n".join(out_lines), words=words,
75
+ meta={"cols": cols, "font": reg_f, "fontsize": fsize})
76
+
77
+ def _layout(self, r: Receipt, cols: int, rng: random.Random):
78
+ L = []
79
+ lab = r.labels
80
+ money = lambda x: fmt_money(x, r.locale)
81
+
82
+ def kv(left: str, right: str, style="plain"):
83
+ gap = cols - len(left) - len(right)
84
+ L.append((left + " " * max(1, gap) + right if gap > 0
85
+ else (left[: cols - len(right) - 1] + " " + right), style))
86
+
87
+ L.append((r.merchant[:cols], "bold" if rng.random() < 0.8 else "center"))
88
+ L.append((r.address[:cols], "center"))
89
+ if r.show_phone:
90
+ L.append((f"TEL {r.phone}"[:cols], "center"))
91
+ if r.tax_id:
92
+ L.append((r.tax_id[:cols], "center"))
93
+ L.append(("-" * cols, "plain"))
94
+ kv(r.date, r.time)
95
+ kv(f"{r.rcpt_word} {r.receipt_no}"[: cols - 8], r.cashier)
96
+ L.append(("-" * cols, "plain"))
97
+ for ln in r.lines:
98
+ price = money(ln.total)
99
+ printed = ln.name[: cols - len(price) - 1].rstrip()
100
+ # drop a trailing bare-digit token: 'SWEET HOME 7 9,98' reads as 79,98
101
+ toks = printed.split(" ")
102
+ if len(toks) > 1 and toks[-1].isdigit():
103
+ printed = " ".join(toks[:-1])
104
+ ln.name = printed # GT stores EXACTLY what is printed
105
+ kv(printed, price)
106
+ if ln.qty > 1: # multiplier goes UNDER its item
107
+ L.append((f" {ln.qty} x {money(ln.unit_price)}"[: cols], "plain"))
108
+ L.append(("-" * cols, "plain"))
109
+ if r.show_subtotal:
110
+ kv(lab["subtotal"], money(r.subtotal))
111
+ for label, _, amt in r.tax_lines:
112
+ kv(label, money(amt))
113
+ kv(lab["total"], money(r.total), "bold")
114
+ if r.tax_included:
115
+ for label, _, amt in r.tax_lines:
116
+ kv(f"{lab['incl']} {label}", money(amt))
117
+ L.append((" ", "plain"))
118
+ kv(r.payment, money(r.tendered if r.tendered is not None else r.total))
119
+ if r.change is not None:
120
+ kv(lab["change"], money(r.change))
121
+ if r.loyalty:
122
+ L.append((r.loyalty[:cols], "plain"))
123
+ L.append((" ", "plain"))
124
+ L.append((r.footer[:cols], "center"))
125
+ return L
generator/validate.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Machine gate over every generated shard — run before any upload."""
2
+ import json, sys
3
+ from pathlib import Path
4
+ import pyarrow.parquet as pq
5
+
6
+ n = bad = 0
7
+ for shard in sorted(Path(sys.argv[1]).glob("*.parquet")):
8
+ for s in pq.read_table(shard).to_pylist():
9
+ n += 1
10
+ try:
11
+ f = json.loads(s["fields"])
12
+ sub = round(sum(l["total"] for l in f["lines"]), 2)
13
+ for l in f["lines"]:
14
+ assert abs(l["qty"] * l["unit_price"] - l["total"]) < 0.005
15
+ if f["tax_included"]:
16
+ assert f["subtotal"] is None and abs(sub - f["total"]) < 0.005
17
+ for t in f["taxes"]:
18
+ base = round(sum(l["total"] for l in f["lines"]
19
+ if abs(l["tax_rate"] - t["rate"]) < 1e-9), 2)
20
+ assert abs(round(base - base / (1 + t["rate"]), 2) - t["amount"]) < 0.011
21
+ assert not (s["locale"] != "US" and "." in t["label"])
22
+ else:
23
+ t = f["taxes"][0]
24
+ assert abs(round(f["subtotal"] * t["rate"], 2) - t["amount"]) < 0.005
25
+ assert abs(f["subtotal"] + t["amount"] - f["total"]) < 0.005
26
+ if f["change"] is not None:
27
+ assert abs(f["tendered"] - f["total"] - f["change"]) < 0.005
28
+ tel_printed = any(l.strip().startswith("TEL ") for l in s["full_text"].split("\n"))
29
+ assert (f["phone"] is not None) == tel_printed
30
+ for l in f["lines"]:
31
+ assert l["name"] in s["full_text"], ("GT name not printed", l["name"])
32
+ if f["loyalty"]: assert f["loyalty"] in s["full_text"]
33
+ words = json.loads(s["words"])
34
+ assert len(words) > 10 and all(w["x1"] > w["x0"] and w["y1"] > w["y0"] for w in words)
35
+ except AssertionError as e:
36
+ bad += 1
37
+ print("FAIL", s["id"], e)
38
+ print(f"validated {n} samples, {bad} failures")
39
+ sys.exit(1 if bad else 0)