Metadata-Version: 2.5
Name: rimi-receipt-parsing
Version: 0.1.1
Summary: Offline, dependency-light parser for Rimi Latvia e-receipts (PDF) with checksum validation — no OCR engine, no AI.
Project-URL: Homepage, https://github.com/aleksejs1/rimi-receipt-parsing
Project-URL: Documentation, https://github.com/aleksejs1/rimi-receipt-parsing/tree/main/docs
Project-URL: Changelog, https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/aleksejs1/rimi-receipt-parsing/issues
Author: Aleksejs Kovalovs
License-Expression: MIT
License-File: LICENSE
Keywords: groceries,latvia,ocr,parser,pdf,receipt,rimi
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: Latvian
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.26
Requires-Dist: pillow>=10.1
Requires-Dist: pypdf>=4.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
Description-Content-Type: text/markdown

# rimi-receipt-parsing

[![CI](https://github.com/aleksejs1/rimi-receipt-parsing/actions/workflows/ci.yml/badge.svg)](https://github.com/aleksejs1/rimi-receipt-parsing/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/rimi-receipt-parsing)](https://pypi.org/project/rimi-receipt-parsing/)
![Python](https://img.shields.io/pypi/pyversions/rimi-receipt-parsing)
![License](https://img.shields.io/badge/license-MIT-green)

Turn **Rimi Latvia e-receipts** (the PDF attached to every *"Tavs pirkuma čeks"* e-mail) into structured data —
items, quantities, prices, discounts, VAT and payments — **offline, deterministically and with every sum verified**.

No OCR engine, no machine learning, no cloud API. Just Python, NumPy and a few kilobytes of glyph templates.

<p align="center">
  <img src="https://raw.githubusercontent.com/aleksejs1/rimi-receipt-parsing/main/docs/images/sample-receipt.png" alt="A synthetic receipt in the Rimi e-receipt format" width="300">
  <br><sub>A <a href="https://github.com/aleksejs1/rimi-receipt-parsing/tree/main/samples">synthetic sample</a> — every name and number on it is made up.</sub>
</p>

## Why another receipt parser?

The "PDF" Rimi sends is a single JPEG with no text layer, so it has to be read from pixels. General-purpose
OCR (Tesseract & co.) needs a lot of tuning for it: Latvian diacritics overlap the neighbouring lines,
`0` and `O` are identical, and a single misread digit silently corrupts your spending data. Vision LLMs
read it well, but cost money, need the network and are not reproducible.

This library exploits the fact that the image is **generated by the cash register, not scanned**. The body
text is a monospaced bitmap font on a fixed 40-column grid, so every character can be recognised by
comparing its cell with a reference template. Then the receipt's own arithmetic is used to prove the
result is right.

|                                 | rimi-receipt-parsing | Tesseract-based OCR | Vision LLM |
|---------------------------------|:--------------------:|:-------------------:|:----------:|
| Offline and free                | ✅                   | ✅                  | ❌         |
| Same input → same output        | ✅                   | ✅                  | ❌         |
| Extra system software           | none                 | Tesseract + Latvian model | — |
| Every receipt checked by its sums | ✅                 | up to you           | up to you  |

**Tested on ~1,000 real receipts from 2021–2026: every one of them adds up**, at ~0.3 s per receipt.
(They are not part of this repository — they contain personal data. See [Privacy](#privacy).)

## Installation

```bash
pip install rimi-receipt-parsing
```

Python 3.10+. Dependencies: `numpy`, `pillow`, `pypdf`.

## Quick start

### 1. Get your receipts

Every Rimi e-receipt arrives the same way — an e-mail from `noreply@rimibaltic.com` with the PDF attached.
The `fetch` command downloads them over IMAP (read-only, nothing in your mailbox is changed):

```bash
export RIMI_IMAP_HOST=imap.gmail.com RIMI_IMAP_USER=you@gmail.com
rimi-receipts fetch --folder "Rimi čeki" --out ~/rimi-receipts --dry-run   # count first
rimi-receipts fetch --folder "Rimi čeki" --out ~/rimi-receipts             # then download
```

Re-running it only downloads new e-mails. See [docs/fetching.md](https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/docs/fetching.md) for Gmail app passwords,
`.env` files and scheduling.

### 2. Check that everything parses

```bash
$ rimi-receipts check samples/
5/5 receipts add up; 0 low-confidence characters
```

Receipts that do not add up are listed with the failed checks.

### 3. Parse

```bash
rimi-receipts parse receipt.pdf                                  # pretty JSON
rimi-receipts parse ~/rimi-receipts --format jsonl > receipts.jsonl
rimi-receipts parse receipt.pdf --format text                    # the recognised text
```

<details>
<summary>Example output (<code>samples/sample-01.pdf</code>, shortened)</summary>

```json
{
  "receipt_number": "00368915",
  "issued_at": "2026-02-09T09:31:48",
  "register": "03",
  "store": "Example Store (Rīga)",
  "items": [
    {
      "name": "Āboli Gala 1. šķira kg",
      "quantity": "1.240",
      "unit": "kg",
      "unit_price_cents": 199,
      "amount_cents": 247,
      "vat_class": "F",
      "discount_cents": 0,
      "final_price_cents": null,
      "is_correction": false
    }
  ],
  "discounts": [
    { "label": "Citas akcijas", "amount_cents": -206, "receipt_level": false },
    { "label": "Jogurts ar zemenēm 2% 380g", "amount_cents": -143, "receipt_level": false },
    { "label": "Izmantotā Mans Rimi nauda", "amount_cents": -30, "receipt_level": true }
  ],
  "vat": [
    { "vat_class": "A", "rate": "21.00", "gross_cents": 2025, "net_cents": 1674, "vat_cents": 351 }
  ],
  "payments": [
    { "method": "Skaidra nauda", "amount_cents": 5000 },
    { "method": "Atlikums", "amount_cents": 2706 }
  ],
  "total_cents": 2294,
  "validation_errors": []
}
```
</details>

### Python API

```python
from rimi_receipts import parse_pdf

receipt = parse_pdf("receipt.pdf")  # path, bytes or a binary file object
assert receipt.validate() == []  # every checksum adds up

print(receipt.issued_at, receipt.store, receipt.total_cents / 100)
for item in receipt.items:
    print(f"{item.name:40} {item.quantity:>7} {item.unit:3} {item.paid_cents / 100:8.2f}")
```

All money is in **integer euro cents**; quantities are `Decimal` (pieces or kilograms). The full data model
is described in [docs/data-model.md](https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/docs/data-model.md).

## How it works

<p align="center"><img src="https://raw.githubusercontent.com/aleksejs1/rimi-receipt-parsing/main/docs/images/grid.png" alt="The character grid of a receipt" width="700"></p>

1. **Extract** the JPEG from the PDF.
2. **Find text lines** with dynamic programming: every possible line position and horizontal phase is
   scored by how well its 40 cells match the templates; the logo and large headings stay unexplained.
3. **Decode** each cell against 99 glyph templates, accounting for accents that overlap the lines above
   and below.
4. **Parse** the text into items, discounts, VAT and payments.
5. **Validate** with the receipt's own arithmetic.

The details — grid geometry, the overlap problem, why `0` and `O` cannot be told apart — are in
[docs/how-it-works.md](https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/docs/how-it-works.md).

### What is validated

| Check | Catches |
|-------|---------|
| quantity × unit price = line amount | misread digits in items |
| line amount + discount = *Gala cena* | misread discounts |
| Σ item discounts = item discounts listed under *ATLAIDES* | lost or extra discount lines |
| Σ items + Σ discounts = Σ VAT table gross | anything missing from the item list |
| VAT gross − net = VAT, for each rate | misread VAT table |
| Σ payments − change = total; card payment = *KOPĀ* | misread payments |
| promotion names repeat item names exactly | letter-case recognition errors (`č`/`Č`) |

A receipt that fails any check is reported, never silently accepted. In addition, characters recognised
with a small margin are listed in `receipt.low_confidence`.

## Limitations

- **Rimi Latvia only.** Lithuanian and Estonian Rimi receipts use other languages and probably other
  layouts; contributions are welcome.
- **`0` vs `O`.** They are the same glyph in the receipt font. Numbers are unaffected; inside words `0` is
  turned into `O` by context, which can be wrong for rare product names like `BI0`.
- **New characters.** A character the template set has never seen is reported as `�` and the receipt
  fails validation. Adding it takes a few minutes — see [docs/glyphs.md](https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/docs/glyphs.md).
- **Large-font lines** (the logo, *"Tavs ietaupījums"*, the big *"Samaksai EUR"* amount) are skipped; every
  number in them is printed again in the body text.
- **Format changes.** If Rimi changes the layout, validation will start failing loudly rather than
  producing wrong data.

## Privacy

Everything runs locally; nothing is sent anywhere. Real receipts contain the masked loyalty card and bank
card numbers, terminal and transaction IDs, the shop and the exact time of purchase — **no real receipt or
data derived from one is included in this repository.** The glyph templates are 14×8-pixel images of single
characters, and all [samples](https://github.com/aleksejs1/rimi-receipt-parsing/tree/main/samples) are synthetic, generated by `rimi-receipts synth`.

If you report a bug, please do not attach a real receipt. Paste the recognised text with personal fields
replaced, or describe the problem.

## Development

```bash
git clone https://github.com/aleksejs1/rimi-receipt-parsing && cd rimi-receipt-parsing
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest                                   # unit tests + synthetic round-trips
RIMI_CORPUS_DIR=~/rimi-receipts pytest   # also every real receipt you have locally
ruff check . && ruff format --check .
```

Contributions are welcome — see [CONTRIBUTING.md](https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/CONTRIBUTING.md).

## Prior art

The idea of digitising Rimi receipts comes from the Habr article
[«Оцифровка чеков Rimi»](https://habr.com/ru/articles/788296/) and its repository
[curious-odd-man/rimi-receipt-ocr-and-parsing](https://github.com/curious-odd-man/rimi-receipt-ocr-and-parsing)
(Java, Tesseract + OpenCV, with arithmetic checks of the parsed result). This project takes a different
route for recognition — template matching on the known character grid instead of OCR — and keeps the
idea of validating every receipt against its own sums.

## Disclaimer

This is an independent project, not affiliated with or endorsed by Rimi Baltic. "Rimi" is a trademark of
its owner and is used here only to describe which receipts the library reads.

## License

[MIT](https://github.com/aleksejs1/rimi-receipt-parsing/blob/main/LICENSE)
