# Thai Receipt AI [![CI](https://github.com/Yuttakarn2545/thai-receipt-ai/actions/workflows/ci.yml/badge.svg)](https://github.com/Yuttakarn2545/thai-receipt-ai/actions/workflows/ci.yml) ![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178c6) ![MCP](https://img.shields.io/badge/MCP-6%20tools-5b4bff) ![License: MIT](https://img.shields.io/badge/license-MIT-green) ![Thai Receipt AI: a receipt photo turned into JSON with cross-checks](docs/hero.png) **One TypeScript core that reads photos and PDFs of Thai receipts and tax invoices (ใบเสร็จรับเงิน / ใบกำกับภาษี / ใบกำกับภาษีอย่างย่อ) with Claude structured output. Deterministic code then checks what the model read.** It ships three ways: | Surface | Package | What it is | |---|---|---| | Library | [`@yuttakarn/thai-receipt`](packages/core) | `extractReceipt(file)` → typed JSON plus cross-checks and a `needs_review` flag | | MCP server | [`thai-receipt-mcp`](packages/mcp) | stdio server with 6 tools: `extract_receipt`, `check_receipt`, `validate_tax_id`, `parse_thai_date`, `promptpay_qr`, `baht_text` | | n8n node | [`n8n-nodes-thai-receipt`](packages/n8n) | community node, plus an [example workflow](examples/n8n/line-receipt-to-sheets.json): LINE OA photo → extract → Google Sheets → LINE reply | The model only **transcribes**. Arithmetic and validation run in plain code, so a misread digit gets *flagged* rather than trusted: - **Tax ID:** 13-digit checksum (`Σ dᵢ·(13−i)`, check = `(11 − sum mod 11) mod 10`), accepting dashes and Thai digits (๐–๙) - **Dates:** พ.ศ. → ISO (`15 มี.ค. 68`, `๑๕/๐๓/๒๕๖๘`, `15/03/2568 14:32`, `15 Mar 2025` …), with impossible dates rejected - **Line items:** qty × unit price = amount, and the items sum to the printed subtotal - **VAT 7%:** VAT-exclusive (`(subtotal − discount) × 7%`) and VAT-inclusive (`total × 7/107`) - **Totals:** subtotal − discount + VAT = grand total - **Amount in words:** the printed `(…บาทถ้วน)` must match the number, checked with `thai-baht-text` ## Evals `evals/` holds **32 synthetic receipts** from 12 fictional shop types. They are rendered HTML → PNG/JPG/PDF in four styles: clean scan, phone photo on a table, low-light/blurred photo, and vector PDF. Each has ground-truth JSON. The set covers thermal POS slips, A4 tax invoices, a handwritten cash bill (บิลเงินสด), a bilingual hotel invoice, Thai-digit documents, discounts, fractional fuel litres, and **4 trap receipts** whose printed numbers are deliberately wrong (bad VAT, invalid tax-ID checksum, items that don't sum, amount-in-words mismatch). On a trap, the right behaviour is to transcribe faithfully *and* raise `needs_review`. > **Live model accuracy: not measured yet.** The harness is complete. Run `npm run eval` with an `ANTHROPIC_API_KEY` to print the field-level accuracy table and API cost, and paste it here from `evals/results/*.md`. A full run on `claude-opus-5-5` (effort medium) should cost roughly US$1–2; that is an estimate from image sizes, not a measurement. > > **What is verified offline** (`npm run check`, no API calls): > - The scorer gives 100% on perfect transcriptions and catches injected errors. > - Run on the ground truth, the deterministic cross-checks raise `needs_review` on all 3 trap types visible from numbers alone (wrong VAT, invalid tax-ID checksum, items that don't sum). They raise no false alarm on the 28 normal receipts. > - The 4th trap (amount-in-words mismatch) is only detectable once the words are read from the image. How scoring works ([`evals/score.ts`](evals/score.ts), unit-tested): - Text fields are compared after removing whitespace and punctuation. Money fields must match within ±0.01 THB. Dates must be the exact ISO string. - Items are matched by amount. A receipt passes `items_amounts` only when the count and every amount match. Descriptions need ≥ 0.85 character similarity. - `needs_review` is scored against the truth: true only for the 4 trap receipts. - A **fully correct** receipt has every applicable field right. No real data is used. Every shop, address and person is invented. Tax IDs are generated with province code **99**, which does not exist, so they pass the checksum but cannot match a registered business ([`evals/test/score.test.ts`](evals/test/score.test.ts) enforces this). The set is deterministic: `npm run receipts` regenerates identical files from a fixed seed. ## Architecture ```mermaid flowchart LR subgraph Inputs A[Photo / scan
jpg · png · webp] B[PDF] L[LINE OA photo] end subgraph core["@yuttakarn/thai-receipt"] X["extractReceipt()
Claude Opus 5.5
structured output (Zod)"] N["normalize
tax ID → digits
พ.ศ. → ISO"] C["crossCheck()
checksum · items · VAT 7%
totals · baht words"] S["score()
confidence · needs_review"] X --> N --> C --> S end subgraph Surfaces M[MCP server
stdio · 6 tools] W[n8n node] P[your code] end A --> X B --> X L -->|"@aotoki/n8n-nodes-line-messaging"| W S --> P S --> M S --> W W --> G[(Google Sheets)] M --> D[Claude Desktop / Claude Code / any MCP client] ``` - **Model:** `claude-opus-5-5` by default, with adaptive thinking and configurable effort. The schema goes through `client.beta.messages.parse` with `betaZodOutputFormat`, so the response is schema-valid JSON. The server-side refusal fallback (`fallbacks: "default"`) is on by default; pass `fallbacks: false` on platforms that don't support it. - **PDFs** are sent as `document` blocks and images as `image` blocks, both base64. No OCR step is needed. ## Quick start You need Node ≥ 22 and an [Anthropic API key](https://platform.claude.com/). It works on Windows, macOS and Linux (CI covers Ubuntu and Windows). > The packages are **not on the npm registry yet**. Build them from source once, and every surface below installs from the local tarballs in `release/`. ```bash git clone https://github.com/Yuttakarn2545/thai-receipt-ai cd thai-receipt-ai npm install npm run build npm run pack:all # → release/yuttakarn-thai-receipt-0.1.0.tgz, thai-receipt-mcp-0.1.0.tgz, n8n-nodes-thai-receipt-0.1.0.tgz ``` ### 1. Library ```bash # in your own project npm install /path/to/thai-receipt-ai/release/yuttakarn-thai-receipt-0.1.0.tgz ``` ```ts import { extractReceipt, validateTaxId, parseThaiDate, promptPayQr, bahtText } from "@yuttakarn/thai-receipt"; const r = await extractReceipt("./receipt.jpg"); // reads ANTHROPIC_API_KEY console.log(r.receipt.seller_name, r.receipt.date, r.receipt.total); if (r.needs_review) console.warn(r.review_reasons); // e.g. ["vat_math: VAT 26.70, expected 23.97"] // Offline helpers (no API call) validateTaxId("0-1055-12345-67-8"); // { valid, expectedCheckDigit, formatted, … } parseThaiDate("15 มี.ค. 68"); // "2025-03-15" bahtText(1070); // "หนึ่งพันเจ็ดสิบบาทถ้วน" await promptPayQr("0812345678", { amount: 107 }); // { payload, image: "