# Schema Reference: `payable-receipt-ocr/1`

This is the normative contract for the JSON produced by both the Python API (`result.to_dict()`)
and the CLI. The `schema_version` field identifies it:

```json
"schema_version": "payable-receipt-ocr/1"
```

Note: there is no `v` in the version string. The old alpha schema used `"payable-receipt-ocr/v1"`;
see [Migration from the old alpha schema](#migration-from-the-old-alpha-schema).

---

## `recognize()` signature

```python
from payable_receipt_ocr import recognize

result = recognize(
    image,                           # str | Path — required
    *,
    currency: str = "INR",           # ISO currency; only "INR" is supported
    tessdata_dir = None,             # str | Path | None — explicit model directory
    diagnostics: bool = False,       # opt-in; enables raw OCR text in result
    deadline_seconds: float = 5.0,   # total call wall-time limit
    pass_timeout_seconds: float = 2.0,  # per-OCR-pass timeout
    runtime_policy = "development",  # "development" | "conformant"
) -> RecognitionResult
```

`recognize()` performs no network requests and writes no persistent files. It always returns a
`RecognitionResult` or raises a controlled error (see [Errors](#errors)).

---

## Full JSON example

A typical result from a Blinkit/Swiggy/Zepto checkout screenshot:

```json
{
  "schema_version": "payable-receipt-ocr/1",
  "source": {
    "filename": "zepto-checkout.png",
    "dimensions": [1080, 1920]
  },
  "processing": {
    "passes_planned": 12,
    "passes_completed": 10,
    "passes_failed": 0,
    "degraded": false,
    "deadline_exceeded": false,
    "duration_ms": 2843
  },
  "runtime": {
    "baseline_id": "linux-noble-amd64-2026-08",
    "conformant": false,
    "tesseract_version": "tesseract 5.5.0",
    "model_sha256": {
      "eng": "7d4322bd2a7749724879683fc3912cb542f19906c83bcc1a52132556427170b2",
      "Devanagari": "3bbb87c1de2a6a2ef0a97dc041e6eea2723a1c22d638f5e38157a5cd441c12b7"
    }
  },
  "result": {
    "total": "289.86",
    "currency": "INR",
    "evidence_grade": "strong",
    "requires_confirmation": true,
    "authorizes_persistence": false,
    "matched_label": "to pay",
    "label_kind": "payment"
  },
  "warnings": []
}
```

A `"none"` evidence result:

```json
{
  "schema_version": "payable-receipt-ocr/1",
  "source": {
    "filename": "blurry.png",
    "dimensions": [600, 900]
  },
  "processing": {
    "passes_planned": 12,
    "passes_completed": 12,
    "passes_failed": 0,
    "degraded": false,
    "deadline_exceeded": false,
    "duration_ms": 3120
  },
  "runtime": {
    "baseline_id": "linux-noble-amd64-2026-08",
    "conformant": false,
    "tesseract_version": "tesseract 5.5.0",
    "model_sha256": {
      "eng": "7d4322bd2a7749724879683fc3912cb542f19906c83bcc1a52132556427170b2",
      "Devanagari": "3bbb87c1de2a6a2ef0a97dc041e6eea2723a1c22d638f5e38157a5cd441c12b7"
    }
  },
  "result": {
    "total": null,
    "currency": null,
    "evidence_grade": "none",
    "requires_confirmation": true,
    "authorizes_persistence": false,
    "matched_label": null,
    "label_kind": null
  },
  "warnings": [
    {"code": "no_candidate", "message": "No payment or fallback total label with a monetary value was extracted."}
  ]
}
```

---

## Field reference

### Top-level

| Field | Type | Description |
|---|---|---|
| `schema_version` | `string` | Always `"payable-receipt-ocr/1"` |
| `source` | object | Source image metadata |
| `processing` | object | Pipeline execution metrics |
| `runtime` | object | OCR runtime identity |
| `result` | object | The recognition suggestion |
| `warnings` | array | Zero or more warning objects |
| `diagnostics` | object | Present only when `diagnostics=True`; contains raw OCR text |

### `source`

| Field | Type | Description |
|---|---|---|
| `filename` | `string` | Basename of the input image path |
| `dimensions` | `[int, int]` | `[width, height]` of the decoded source image in pixels |

### `processing`

| Field | Type | Description |
|---|---|---|
| `passes_planned` | `int` | Number of OCR passes scheduled |
| `passes_completed` | `int` | Number of passes that returned a result |
| `passes_failed` | `int` | Number of passes that timed out or raised an error |
| `degraded` | `bool` | `true` if any pass failed, malformed OCR records were discarded, or the deadline was reached |
| `deadline_exceeded` | `bool` | `true` if the total deadline was reached before all passes completed |
| `duration_ms` | `int` | Total wall time for the `recognize()` call in milliseconds |

### `runtime`

| Field | Type | Description |
|---|---|---|
| `baseline_id` | `string` | The baseline identifier from `runtime-baseline.toml` |
| `conformant` | `bool` | `true` if OS, arch, and Tesseract version all match the baseline tuple |
| `tesseract_version` | `string` | First line of `tesseract --version` output |
| `model_sha256` | object | `{"eng": "<hex>", "Devanagari": "<hex>"}` — checksums of the verified model files |

### `result`

| Field | Type | Description |
|---|---|---|
| `total` | `string \| null` | Decimal string (e.g. `"289.86"`); `null` when `evidence_grade="none"` |
| `currency` | `string \| null` | ISO currency code; `null` when `evidence_grade="none"` |
| `evidence_grade` | `string` | One of `"strong"`, `"review"`, `"none"` |
| `requires_confirmation` | `true` | Always `true`; never changes |
| `authorizes_persistence` | `false` | Always `false`; never changes |
| `matched_label` | `string \| null` | The payment or fallback label text that anchored the suggestion |
| `label_kind` | `"payment" \| "fallback" \| null` | Whether the matched label was a payment label or fallback total |

### Warnings

Each warning is an object:

```json
{"code": "weak_evidence", "message": "Independent OCR evidence did not meet the strong-suggestion gate."}
```

| Field | Type | Description |
|---|---|---|
| `code` | `string` | Stable identifier; safe to branch on in code |
| `message` | `string` | Human-readable description; may change across versions |

**Stable warning codes:**

| Code | Meaning |
|---|---|
| `no_candidate` | No payment or fallback total was extracted |
| `weak_evidence` | Grade is not `"strong"` |
| `currency_conflict` | Conflicting explicit currency markers in OCR output |
| `competing_total` | A competing total has equal or greater cross-pass support |
| `currency_context_mismatch` | Best-supported total conflicts with the supplied currency context |
| `ranking_warning` | Possible digit corruption in a candidate |
| `degraded_processing` | One or more passes failed, malformed OCR records were discarded, or the deadline was reached |
| `pass_timeout` | An individual OCR pass timed out |
| `pass_failed` | An individual OCR pass raised an error |
| `ocr_malformed_records` | A completed pass discarded malformed TSV records; the warning contains a count, never the discarded text |
| `deadline_exceeded` | The total deadline was reached |

A pass with a valid TSV header and some malformed records remains completed; its valid words are
retained, `degraded` is true, and the evidence grade cannot exceed `review`. A missing or invalid
header fails that pass. If every pass fails, recognition raises the controlled `OcrEngineError`.

New warning codes may be added in additive updates without a schema version bump. Consumers should
not treat an unrecognized warning code as an error.

---

## Evidence grade semantics

| Grade | Meaning | `total` | `currency` |
|---|---|---|---|
| `"strong"` | Payment-labelled, INR-confirmed, multi-pass agreement, no conflicts | non-null | non-null |
| `"review"` | A total was found but did not meet strict corroboration | non-null | non-null |
| `"none"` | No supported total extracted | `null` | `null` |

`"strong"` evidence still requires human confirmation before an expense is persisted. See
[ADR-0003](../adr/0003-evidence-and-partial-failure-semantics.md).

---

## Diagnostic opt-in

Pass `diagnostics=True` to `recognize()` to include raw OCR text in the result:

```python
result = recognize("receipt.png", currency="INR", diagnostics=True)
output = result.to_dict(include_diagnostics=True)
# output["diagnostics"]["ocr"]["passes"][0]["raw_text"] — full OCR text
```

Calling `to_dict(include_diagnostics=True)` on a result produced without `diagnostics=True` raises
`ValueError`. Diagnostics are not available after the fact.

The `diagnostics` key is never present by default. See
[ADR-0005](../adr/0005-diagnostic-privacy-boundary.md).

---

## Errors

Controlled errors all inherit from `ReceiptOcrError`. The CLI prints the error code to stderr and
exits with the corresponding code; the result JSON is not printed.

| Class | Code | CLI exit | When raised |
|---|---|---|---|
| `InputFileError` | `input_file` | 3 | Image path does not exist or is unreadable |
| `UnsupportedImageError` | `unsupported_image` | 4 | Unsupported format, file > 10 MiB, decoded > 12 MP |
| `ConfigurationError` | `configuration` | 5 | Invalid `currency` or `runtime_policy` argument |
| `RuntimeBaselineError` | `runtime_baseline` | 5 | Missing models, checksum mismatch, or conformant policy + runtime mismatch |
| `OcrEngineError` | `ocr_engine` | 6 | Tesseract unavailable or all passes failed |
| Unexpected | — | 1 | Unhandled exception in CLI |

All errors exit 0 for success in the CLI. The holdout evaluator additionally uses exit code 1 for
gate failure and 2 for manifest parse errors; these are separate from the main CLI contract.

---

## Python `RecognitionResult` properties

In addition to the JSON-serializable fields, the Python object exposes two backward-compatible
properties:

| Property | Type | Value |
|---|---|---|
| `needs_review` | `bool` | `evidence_grade != "strong"` — available for compat; not in JSON |
| `pass_count` | `int` | Alias for `passes_completed` — available for compat; not in JSON |

---

## Compatibility and migration from old alpha schema

Consumers who parsed the old alpha JSON must update:

### 1. `schema_version` string changed

```diff
-"schema_version": "payable-receipt-ocr/v1"
+"schema_version": "payable-receipt-ocr/1"
```

### 2. `result.needs_review` removed from JSON

```diff
-"needs_review": true
```

Use `evidence_grade != "strong"` instead. The `needs_review` Python property still exists for
backward compatibility but is not serialized.

### 3. `result.matched_line` removed entirely

```diff
-"matched_line": "To Pay ... 289.86"
```

There is no replacement in the current schema.

### 4. `warnings` changed from string array to object array

```diff
-"warnings": ["weak_evidence"]
+"warnings": [{"code": "weak_evidence", "message": "Independent OCR evidence did not meet the strong-suggestion gate."}]
```

### 5. `pass_count` moved out of `result`

```diff
-"result": { ..., "pass_count": 6 }
+"processing": { ..., "passes_completed": 6 }
```

### Post-v1 policy

After v1, additive changes (new optional fields, new warning codes) will not bump the schema
version. Consumers **must** ignore unknown fields to remain forward-compatible.
