Technical report · alpha package

payable-receipt-ocr pipeline

How the local Blinkit, Swiggy, and Zepto recognizer transforms a screenshot into a confirmation-only total suggestion—and what remains before it can become an expense-app service.

1 · Executive summary

The approach is viable; the product decision is still gated

Current verdict

The alpha package preserves the free, local, payment-aware v4 OCR pipeline. Its tuned 35-image exploratory corpus produced 35 exact total-and-currency matches, zero wrong results graded strong, and zero confirmation violations. This proves the parsing strategy is worth continuing.

It does not prove production accuracy. The same public corpus informed tuning, and none of those images can satisfy the authorized holdout gate. A fresh private benchmark remains the next decision point.

Exploratory exact35 / 35
False strong0
Confirmation35 / 35
Formal gateBLOCKED
Current
The Python interface and CLI accept one local image and emit a confirmation-only result.
Current
English and Devanagari Tesseract passes run locally; no receipt is uploaded to a cloud OCR API.
Blocked
The authorized 30-screenshot holdout corpus is not yet populated.
Proposed
An application may place an authenticated HTTP adapter in front of the package after the quality gate passes.

2 · System boundary

The OCR package and consuming application are separate modules

This distinction is essential. The Python package has no HTTP server, application authentication, database connection, or permission to create expenses. It reads a local file and produces evidence. The consuming application owns users, validation, review, and persistence.

Consuming application · caller-owned runtime

System of record

  • Input: authorized image and currency context
  • Review: user edits or confirms the suggestion
  • Guards: caller-owned authentication and validation
  • Persistence: caller-owned database
  • Responsibility: authorized expense creation and updates

Current package · Python runtime

Evidence-producing recognizer

  • File handling: Pillow
  • Pixel processing: NumPy and OpenCV headless
  • Recognition: Tesseract 5 through pytesseract
  • Interpretation: Python regex, Unicode normalization, Decimal
  • Responsibility: suggest a total, never persist an expense

Request path that exists now

local image → recognize(...) → Tesseract subprocesses → typed suggestion

Proposed path after holdout

application → optional HTTP adapter → package → confirmation → caller-owned persistence

3 · End-to-end pipeline

Six stages turn pixels into decision evidence

Each stage has a narrow job. Image processing improves visibility, OCR reads symbols, and deterministic business rules decide which recognized number most likely means “amount paid.”

01 · INGEST

_load_image accepts JPG, JPEG, PNG, or WebP. Pillow applies EXIF orientation, converts to RGB, and rejects images above 30 megapixels. NumPy/OpenCV receive a BGR array. Input is still only evidence; no app entity is created.

02 · PREPARE

_deskew uses grayscale, Canny edges, and probabilistic Hough lines to estimate a median angle within ±12°. _preprocess may enlarge the image toward 1800px width, normalizes contrast, and adds a white border.

03 · VARIANTS

Two views are created: normalized grayscale and adaptive threshold. The second view makes local contrast decisions, which can help dark themes and uneven illumination. OpenCV's official thresholding guide describes this image-processing behavior. Primary source

04 · OCR

_ocr_lines calls pytesseract.image_to_data with the LSTM engine (--oem 1), page segmentation modes 4, 6, and 11, and preserved interword spacing. With the local Devanagari model present, two variants × two languages × three layouts produce 12 passes. Without that model, only six English passes run and a warning is emitted. pytesseract is the wrapper; Tesseract is the reader. Primary source

05 · REBUILD

Tesseract can place a left-aligned label and its right-aligned price into different internal blocks. The package rebuilds visual rows from word geometry, overlap, and center distance before interpreting receipt meaning.

06 · DECIDE

Unicode digits and combining marks are normalized; currency and amount patterns are extracted; labels classify each row; candidates are scored and grouped across passes; the top group receives a strong, review, or none grade. The final result always sets requires_confirmation: true.

2 image variants × 2 languages × 3 PSM layouts = 12 OCR passes

4 · Candidate and decision logic

Recognition and interpretation are deliberately separate

Tesseract might correctly read several numbers while still not knowing which one the user paid. The Python layer supplies the receipt-specific meaning.

Payment labels

Amount Paid, Paid by You, Amount Payable, To Pay, Grand Total, Amount Due.

These can support a strong suggestion.

Fallback totals

Total Bill Amount, Item Total & GST, MRP Total, generic Total.

Useful when no payment label is available, but never strong.

Negative/component rows

Savings, discounts, cashback, subtotals, delivery, taxes, tip, cash, and change.

Used for context or arithmetic, not as the payable winner.

Per-candidate score

Starts with label meaning, then adds page position, OCR confidence, rightmost-amount evidence, explicit currency, and agreement with the supplied currency context. Conflicting currency evidence is penalized.

Grouped score

Same-valued candidates are merged across pass IDs. The group gains evidence from pass count, language diversity, preprocessing diversity, arithmetic agreement, and currency votes. Conflicts and suspected leading-digit corruption reduce trust.

Evidence-grade rules

Grade Meaning Required behavior
strong Winner has a payment label, no ranking warning, supported currency, a safe score gap, and independent repeated-language or multi-pass arithmetic evidence. Pre-fill the suggestion; user still confirms.
review A plausible winner exists, but one or more strong-evidence conditions are absent. Show the suggestion and its warning; user reviews carefully.
none No acceptable payment or fallback group exists. Do not invent a total; ask for manual entry.

5 · Output contract

The service-shaped output is evidence-rich JSON

The current CLI already returns a useful future-service contract. The compact result can drive the UI, while the candidate and pass evidence remains available for debugging and audits.

{
  "schema_version": "payable-receipt-ocr/v1",
  "alpha": true,
  "source": {
    "filename": "zepto-checkout.png",
    "dimensions": [1179, 2556]
  },
  "processing": {
    "currency_context": "INR",
    "pass_count": 12,
    "languages": ["eng", "Devanagari"],
    "psm_modes": [4, 6, 11],
    "variants": ["normalized-grayscale", "adaptive-threshold"]
  },
  "result": {
    "total": "289.86",
    "currency": "INR",
    "evidence_grade": "review",
    "requires_confirmation": true,
    "needs_review": true,
    "matched_label": "to pay",
    "matched_line": "To Pay ... 289.86"
  },
  "candidate_groups": ["ranked amount evidence"],
  "ocr": { "passes": ["raw text and geometry for each pass"] },
  "warnings": ["evidence or currency warnings"]
}

UI-facing fields

total, currency, evidence_grade, requires_confirmation, matched_label, and warnings are sufficient to render a safe suggestion.

Diagnostic fields

Candidate groups, individual candidates, pass IDs, raw OCR lines, confidence, languages, and preprocessing metadata explain why the winner was chosen. These should not all be sent to an ordinary client by default in production.

6 · Benchmark and current evidence

The gate separates promising behavior from deployable evidence

The benchmark reads a labeled manifest, runs every ready image, records per-case JSON, and computes exact total-and-currency accuracy plus safety violations.

eligible ≥ 30 AND each app ≥ 10 AND exact ≥ 90% AND false-strong = 0 AND confirmation = 100%

Exploratory result · observed

35/35 exact on the tuned public corpus

  • Blinkit: 11/11
  • Swiggy: 10/10
  • Zepto: 14/14
  • Wrong + strong: 0
  • Confirmation violations: 0

Formal gate · blocked

0 authorized screenshots are ready

Public availability is not redistribution permission, so the internet images are marked unverified-public and excluded from gate metrics. They were also used during tuning, which makes 100% an in-sample result rather than an unbiased estimate of future performance.

7 · Privacy and operational behavior

The POC is local by design, but a service adds new obligations

What the current POC protects

  • Receipt pixels and OCR text are not sent to an external recognition API.
  • Private inputs, downloaded models, and generated reports are Git-ignored.
  • The Devanagari model is downloaded from a pinned URL and verified by SHA-256.
  • The recognizer has no database credentials and cannot create an expense.
  • The model download is the only required setup network request.

What a hosted service must add

  • Authenticated internal calls and strict image MIME, size, and dimension checks.
  • Request timeouts, CPU/memory limits, concurrency control, and temporary-file deletion.
  • Log redaction: never log raw OCR text or receipt images by default.
  • Retention policy for uploads and diagnostic evidence.
  • Monitoring for latency, errors, review rate, and user-correction rate.

8 · Risks and explicit limits

What the proof does not cover

Area Current status Impact Required response
Generalization Unproven The 35/35 result may be overfit. Run the frozen authorized holdout.
Latency and capacity Unmeasured Twelve CPU OCR passes may be slow or expensive under concurrency. Profile p50/p95 time, CPU, RAM, and queue depth.
App integration Not built No upload route, service API, confirmation UI, or deployment exists. Integrate only after the quality gate passes.
Input scope Narrow PDF, HEIC, multiple pages, handwriting, and generic invoices are unsupported. Keep product copy and validation aligned with the supported scope.
Extraction scope Total only Merchant, date, tax, and line items are not reliable outputs. Do not imply full receipt understanding.
Automatic writes Contained The package always requires confirmation and has no persistence. Preserve this boundary in the service design.

9 · Recommended path to a feature

Use evidence to unlock each engineering step

STEP 1

Freeze an authorized holdout. At least 30 unseen screenshots, at least 10 per app, with dark/light, cropped, compressed, decimal, discount, and long-order cases.

STEP 2

Run the quality gate once. Proceed only at ≥90% exact total+currency, zero wrong strong results, and confirmation required for every case. If it fails, diagnose the misses before changing engines.

STEP 3

Measure operational cost. Capture per-image p50/p95 latency, CPU, memory, model startup cost, and safe concurrent request count on the intended free/self-hosted machine.

STEP 4

Wrap a narrow HTTP suggestion endpoint. Accept one validated image and expense currency context; return the compact result contract. Add timeouts, deletion, authentication, and structured error codes. Do not add database access.

STEP 5

Integrate confirmation into the expense form. The consuming application supplies the image, shows the suggested total and evidence grade, lets the user edit it, and only then sends its ordinary validated expense payload to persistence.

STEP 6

Monitor corrections, not invented confidence. Track success, review rate, latency, and the difference between OCR suggestions and confirmed values without retaining raw receipts by default.

10 · Sources and code map

Where every conclusion comes from