Preventing Rounding Drift & Excel Formula Injection in Automated Receipt OCR Pipelines (Python Decimal + Volatile RAM)
Most receipt-scanning scripts fail in production for three boring engineering reasons — none of which have to do with the OCR model itself: IEEE-754 floating-point drift when checking subtotal + tax + tip == total acr
Most receipt-scanning scripts fail in production for three boring engineering reasons — none of which have to do with the OCR model itself:
-
IEEE-754 floating-point drift when checking
subtotal + tax + tip == totalacross dozens of receipts (18.50 + 1.48 + 2.00looks harmless until VAT rates and 30-row sums produce a0.01reconciliation mismatch). -
CSV / Excel formula injection (
DDE/=HYPERLINK) when untrusted OCR text from a receipt memo or merchant header starts with=,+,-, or@and gets written verbatim into an.xlsxor.csvcell. -
Unnecessary cloud retention & broken print layouts — finance teams still ask for printable A4 receipt voucher sheets (
4-Upper page) with IDs matching Excel row numbers (R-01..R-30), yet most tools dump 30 loose phone photos into a zip file or persist private receipts in S3 buckets.
Here is the minimal deterministic pattern we used to build a zero-account, volatile-RAM batch receipt pipeline (and four free local browser accounting utilities).
1. Exact Cent Math With Decimal (Never float)
Every parsed receipt amount should be quantized with ROUND_HALF_UP to Decimal("0.01") before running the tax integrity check:
from decimal import Decimal, ROUND_HALF_UP
CENT = Decimal("0.01")
def q2(val: str | Decimal | None) -> Decimal:
if val is None or str(val).strip() == "":
return Decimal("0.00")
return Decimal(str(val)).quantize(CENT, rounding=ROUND_HALF_UP)
def verify_receipt_math(subtotal: Decimal, tax: Decimal, tip: Decimal, total: Decimal) -> dict:
expected = (subtotal + tax + tip).quantize(CENT, rounding=ROUND_HALF_UP)
diff = (total - expected).quantize(CENT, rounding=ROUND_HALF_UP)
return {
"expected_total": str(expected),
"variance": str(diff),
"status": "VERIFIED" if diff == Decimal("0.00") else "DISCREPANCY",
}
Why this matters in practice: when thermal ink fades on a gas-station or hotel receipt, OCR often misreads 8 as 3 or drops a digit on the tax line. A deterministic Subtotal + Tax + Tip == Total gate catches 90%+ of silent OCR misreads before an accountant sees the spreadsheet, and lets the user fix the single flagged cell side-by-side with the original image.
2. Neutralizing Excel & CSV Formula Injection on Untrusted OCR Strings
OCR text extracted from arbitrary receipts or supplier invoices is untrusted user input. A merchant name or memo string starting with =, +, -, @, \t, or \r will be evaluated as an active formula when opened in Microsoft Excel or LibreOffice Calc.
Always sanitize non-numeric text cells before exporting to .xlsx or .csv:
DANGEROUS_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
def safe_excel_text(value: str) -> str:
s = (value or "").strip()
if s and s[0] in DANGEROUS_PREFIXES:
return "'" + s
return s
At the same time, keep real computed formulas (=SUM(...), =COUNTIF(...), =SUMIFS(...)) strictly generated by your exporter on known coordinate ranges — never interpolated from user text.
3. Native In-Memory iPhone .HEIC Decoding, EXIF Auto-Rotation & Zero-Cache PWA Capture
In real-world expense workflows, 60%+ of mobile uploads arrive as native iPhone .HEIC/.HEIF images carrying sideways EXIF orientation flags (such as EXIF tag 6). Asking users to install a heavy $15/mo App Store client or convert .HEIC to .JPG by hand kills adoption.
The clean web-native solution keeps everything strictly inside RAM:
import io
import pillow_heif
from PIL import Image, ImageOps
pillow_heif.register_heif_opener()
def decode_receipt_in_ram(raw_bytes: bytes) -> Image.Image:
# Decodes JPEG, PNG, WebP, and native iPhone .HEIC/.HEIF straight from RAM
with Image.open(io.BytesIO(raw_bytes)) as img:
return ImageOps.exif_transpose(img).convert("RGB")
Pair that with an installable Home-Screen PWA (manifest.webmanifest) whose Service Worker (sw.js) is strictly pass-through (zero Cache API storage of financial images or API responses) plus a mobile-only <input type="file" accept="image/*,.heic,.heif,.pdf" capture="environment"> rear-camera trigger. Users snap paper receipts directly on their phone with zero App Store download and zero cloud retention.
4. Volatile-RAM Processing + 4-Up A4 Printable Vouchers
Instead of writing uploaded photos to disk or object storage, process every uploaded byte stream inside io.BytesIO, run OCR in memory, and composite the 4-Up A4 PDF (2 × 2 grid with R-01 .. R-N numbered headers matching Sheet 1 of the Excel workbook) straight into an in-memory PDF buffer returned over HTTPS. When the request finishes, the Python garbage collector drops the bytes — zero S3 buckets, zero cleanup cron jobs, zero account database to leak.
Try It Live (Zero Signup, Instant Sample Downloads + Free Local Tools)
-
Batch Receipt & Invoice Scanner (Native iPhone HEIC + Camera PWA + Excel
=SUM/=SUMIFS+ 4-Up A4 PDF, with instant sample outputs): https://stmtverify.com/receipts/ - StmtVerify — Bank, Credit Card & Wise/PayPal PDF/Photo → Verified Excel / QBO / Xero / DATEV / MT940: https://stmtverify.com/
- 100% Free Browser-Only Zero-Upload Accounting Tools (run strictly in local JavaScript):
- MIT Open-Source Format Specification & Python CLI: https://github.com/lerenhuan-hash/bank-statement-format-spec
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.