Metadata-Version: 2.4
Name: ocrmypdf-hebrew
Version: 0.1.1
Summary: OCRmyPDF plugin: Hebrew OCR (with embedded English and numbers) using the paddleocr-hebrew models
Author-email: Rivok Labs <ronen@rivoklabs.com>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/RivoksLab/ocrmypdf-hebrew
Project-URL: Source, https://github.com/RivoksLab/ocrmypdf-hebrew
Project-URL: Issues, https://github.com/RivoksLab/ocrmypdf-hebrew/issues
Project-URL: Write-up, https://rivoklabs.com/research/hebrew-ocr
Keywords: ocr,hebrew,ocrmypdf,pdf,rtl
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: ocrmypdf>=17.14
Requires-Dist: paddleocr-hebrew>=0.1.2
Requires-Dist: onnxruntime>=1.18
Requires-Dist: huggingface_hub>=0.23
Requires-Dist: pydantic>=2
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pdfminer.six; extra == "test"
Requires-Dist: python-bidi; extra == "test"
Dynamic: license-file

# ocrmypdf-hebrew

An [OCRmyPDF](https://github.com/ocrmypdf/OCRmyPDF) plugin for Hebrew documents, including
Hebrew with English words and numbers.

It offers three things:

- **The paddleocr-hebrew engine.** With `-l heb` it replaces Tesseract with the
  paddleocr-hebrew models.
- **Tesseract with the Hebrew word order fixed** (`--hebrew-tess-order`). OCRmyPDF's own
  Tesseract runs, with any `-l`, and the word order of Hebrew lines that contain English or
  numbers is corrected.
- **`hebrew-tess-order`**, the same word-order fix as a command-line filter for Tesseract's TSV
  or hOCR output.

## Install

```bash
pip install ocrmypdf-hebrew     # pulls OCRmyPDF 17.14 or later and paddleocr-hebrew
```

OCRmyPDF loads the plugin automatically (entry point). The install also adds the
`hebrew-tess-order` command. OCRmyPDF 17.14.0 fixed three bugs in how earlier versions write
right-to-left text into the PDF (#1781, #1782, #1783), so the plugin needs it.

## The paddleocr-hebrew engine

```bash
ocrmypdf -l heb+eng scan.pdf out.pdf        # this plugin's models
ocrmypdf -l eng scan.pdf out.pdf            # Tesseract, untouched
ocrmypdf --ocr-engine tesseract -l heb ...  # force Tesseract
```

Options: `--hebrew-pipeline word|line`, `--hebrew-rec-mode cascade|nrtr|ctc`,
`--hebrew-models DIR` (an offline model folder) and `--hebrew-no-rejoin` (below).

**Long numbers cut in two.** The word detector sometimes covers one long number, amount or e-mail
address with two overlapping boxes, so `0585769628` would come out as `058 5769628` and
`12,203.39` as `12,203 3.39`. The plugin joins such neighbours (no Hebrew, at least one digit or
`@`, touching or overlapping) and reads them again as one word. If the new reading has a space,
they were two words after all and are kept as they were. This is on by default for the word
pipeline; `--hebrew-no-rejoin` turns it off. The same pass re-reads numbers whose last `0` the box
cut off (`21,000.0C` → `21,000.00`). On our 7 example documents, numbers found go from 83.3% to
87.2%; on 20 synthetic pages and on old newspaper scans nothing gets worse.

## Tesseract with the Hebrew word order fixed: `--hebrew-tess-order`

### The problem

Tesseract chooses one direction for each paragraph. When a line has as many English words or
numbers as Hebrew words, a tie, Tesseract chooses left to right. Numbers count as left-to-right
words. Short Hebrew lines then come out with their words in the wrong order:

| on the page (read right to left) | Tesseract's text |
|---|---|
| `תאריך: 04.11.2026` | `04.11.2026 תאריך:` |
| `דוח שנתי Annual Report` | `Annual Report דוח שנתי` |
| `חיבור: Bluetooth 5.3 / USB-C` | `Bluetooth 5.3 / USB-C חיבור:` |

These are mostly headings, `key: value` fields, table cells and list items, so forms and
invoices are where it shows. Long paragraphs are rarely affected: on 34 pages of a 19th-century
Hebrew newspaper, under 3% of the Hebrew lines come out in this order with stock `heb+eng`.

### Usage

The mode is **opt-in**: without `--hebrew-tess-order`, Tesseract's output is not touched.

```bash
ocrmypdf --hebrew-tess-order -l heb+eng scan.pdf out.pdf --sidecar out.txt
ocrmypdf --hebrew-tess-order -l heb_rivok scan.pdf out.pdf     # a custom model: see setup below
```

- Tesseract runs exactly as OCRmyPDF runs it, with the same `--tesseract-*` options. After each
  page, the plugin rewrites Tesseract's hOCR before OCRmyPDF builds the text layer.
- `--ocr-engine` can be `auto` (the default) or `tesseract`. With this flag, the paddleocr-hebrew
  models are not used and not downloaded.
- `--hebrew-order-conservative`: in paragraphs of 2 or more lines, only lines with at least as
  many Hebrew letters as Latin ones are reordered. Use it for documents with English passages.
  It gives up most of the gain on forms.
- `--hebrew-order-cells` (**experimental, off by default**): lines are first cut at column gaps
  (more than 3× the word height), and the cells are read right to left. Meant for RTL tables. It
  also reverses the cell order of lines that have no Hebrew. **It has not been validated on real
  documents**, so check its output before relying on it.
- **Needs the default renderer.** It does not work with `--pdf-renderer sandwich`, where
  Tesseract writes the text layer and the sidecar itself. The plugin logs a warning.

### The rule

- **Page gate.** Only pages whose letters are at least 25% Hebrew are touched. All other pages
  keep Tesseract's output byte for byte. Without the gate, English pages that contain a Hebrew
  word would be ruined.
- **Direction.** On a Hebrew page, every line with a Hebrew letter is read right to left. Lines
  without Hebrew keep Tesseract's order.
- **English runs.** Words are taken right to left. A run of English words is kept left to right.
  A run starts and ends on an English word, and numbers and punctuation between English words
  belong to the run. A word containing Hebrew never joins a run. Punctuation or a number at the
  edge of a run stays on the Hebrew side.

### Which text gets the fix

| where the text is read | fixed? | why |
|---|---|---|
| the `--sidecar` text | **yes** | it is rebuilt from the rewritten hOCR |
| MuPDF (`mutool`, PyMuPDF), and other tools that follow the PDF's content order | **yes** (partly) | the content stream holds the corrected word order |
| pdftotext / poppler (Evince, Okular) | **no** | rebuilds each line from glyph positions, with one text direction for the whole page |
| pdfium (Chrome) | **no** | rebuilds each line from glyph positions, choosing each line's direction by letter majority |

Results on 20 synthetic pages with exact references (187 rows, character error rate), measured
with OCRmyPDF 17.14.0 and heb_rivok 1.0.1:

| | stock `heb+eng` | heb_rivok |
|---|---:|---:|
| sidecar, Tesseract → `--hebrew-tess-order` | 17.8% → **7.9%** | 10.8% → **2.7%** |
| MuPDF text | 15.9% → 9.7% | 10.6% → 5.1% |
| pdfium text | 23.2% → 22.4% | 18.2% → 17.5% |
| pdftotext text | 20.4% → 20.2% | 11.5% → 8.6% * |
| sidecar with `--hebrew-order-cells` | 7.1% | 2.2% |
| sidecar with `--hebrew-order-conservative` | 12.0% | 5.9% |

\* This gain is incidental. In Tesseract's left-to-right lines, Hebrew words carry stray
left-to-right marks (U+200E). Rewritten lines drop those marks, and on 1 of the 20 pages that
flips pdftotext's direction for the whole page to right to left. On the other pages pdftotext
barely changes.

- The 3 English pages and the 7 heb_rivok example documents come out unchanged.

### Limits

- **What 17.14.0 leaves to the PDF readers.** They rebuild right-to-left lines from the glyph
  positions, each in its own way:
  - A few words still run together. pdftotext joins a number or an English word to the Hebrew
    word after it (44 pairs on the 20 pages with stock `heb+eng`), and MuPDF a Hebrew word to
    the English word after it (6 pairs). pdfium keeps them all apart.
  - A word that mixes Hebrew with digits or Latin can come back with its parts in another
    order. MuPDF gives `48.2-ל` for `ל-48.2`, pdftotext `בAndroid-` for `ב-Android`, and pdfium
    `ל48.2-` (it keeps `ב-Android` as written). The digits and Latin letters themselves keep
    their order.
- **English passages inside Hebrew pages are flipped.** For example, an English list within a
  Hebrew report. Use `--hebrew-order-conservative`.
- **Things a word order cannot fix:**
  - Version strings: `3.8.1 (build 512)` comes out as `3.8.1 512) (build`.
  - A Hebrew prefix glued to English: `ב-Dark Mode`.
  - Hebrew misread as Latin junk.
  - The character order inside a token, as Tesseract read it: for example `:1` for `1:`.
  - English-only cells of an RTL table. Only `--hebrew-order-cells` fixes these.
- **Bidi marks in the sidecar.** Pages with a rewritten line get their sidecar text rebuilt from
  the hOCR, with no bidi marks. Other pages keep Tesseract's text, which includes them.

### Custom models (heb_rivok) with OCRmyPDF

OCRmyPDF asks Tesseract for its `hocr` and `txt` configs. A `TESSDATA_PREFIX` that holds only
your model fails with `read_params_file: Can't open hocr`. Make a folder with links to the model
and to the system `configs/`:

```bash
mkdir -p ~/tessdata-rivok
ln -s /path/to/heb_rivok.traineddata ~/tessdata-rivok/
ln -s /usr/share/tesseract-ocr/5/tessdata/configs ~/tessdata-rivok/configs
TESSDATA_PREFIX=~/tessdata-rivok ocrmypdf --hebrew-tess-order -l heb_rivok scan.pdf out.pdf
```

**Pages with more than one column:** heb_rivok 1.0.1 or later reads them right column first
with `-l heb_rivok` alone; no workaround is needed. Only heb_rivok 1.0 laid its pages out left to
right (it knows more Latin letters than Hebrew ones) and read the left column first. With 1.0, use
`-l heb+heb_rivok` (also link `/usr/share/tesseract-ocr/5/tessdata/heb.traineddata` into the
folder) or `-l heb_rivok_lite+eng` (link `heb_rivok_lite.traineddata` and `eng.traineddata`), or
better, update to 1.0.1. This is a page-layout matter that `--hebrew-tess-order` does not change,
because it reorders words within lines, not columns. See the heb_rivok model card.

## Command-line filter: `hebrew-tess-order`

It reads Tesseract's TSV or hOCR, which hold word boxes, from a file or from standard input. It
applies the same rule and page gate, and writes plain text in reading order.

```bash
tesseract page.png - -l heb+eng tsv | hebrew-tess-order > page.txt
tesseract page.png page -l heb+eng hocr && hebrew-tess-order page.hocr --emit hocr -o page.fixed.hocr
tesseract page.png - -l heb+eng tsv | hebrew-tess-order --emit tsv > page.fixed.tsv
```

- **Options:**
  - `--conservative` and `--cells`, as above.
  - `--emit text|tsv|hocr`: the rewritten input, in the same format as the input.
  - `-o FILE`: write to a file instead of standard output.
  - `-v`: a per-page summary on standard error.
- **Plain text cannot be fixed.** It has no boxes and no page context.
- **Text format:**
  - The output is Tesseract's text layout: one line per line, with a blank line between
    paragraphs and a form feed between pages.
  - It has no bidi marks.
  - In rewritten TSV/hOCR, the moved words lose their bidi marks, and hOCR lines get
    `dir='rtl'`.
- **heb_rivok with `--tessdata-dir`.** If the folder holds only the model, Tesseract cannot find
  its `tsv`/`hocr` configs and prints plain text instead. Pass the setting directly:

  ```bash
  tesseract page.png - --tessdata-dir /path/to/tessdata -l heb_rivok -c tessedit_create_tsv=1 | hebrew-tess-order
  ```

- **Results.** On the 20 synthetic pages, the CLI text goes from 19.3% to **7.2%** CER (stock
  `heb+eng`) and from 11.8% to **2.4%** (heb_rivok 1.0.1). With `--cells`: 6.5% and 1.9%.
- **Library use:** `ocrmypdf_hebrew.tessorder.reorder_tsv(text)` and `reorder_hocr(text)`.

## Born-digital PDFs with broken Hebrew text

```bash
ocrmypdf -l heb+eng --skip-text --hebrew-reocr-broken in.pdf out.pdf
```

This checks the text layer of each page. It re-OCRs only the pages whose Hebrew text is broken,
for example stored in visual order or with a broken font encoding (`ocrmypdf_hebrew.textlayer`).

## Tests

```bash
python -I -m pytest tests                                        # unit tests, no models needed
OCRMYPDF_HEBREW_E2E=1 python -I -m pytest tests/test_tessorder_e2e.py
```

The second command is an end-to-end check, about 3 minutes, for maintainers. It runs the CLI
and the plugin on the 20 synthetic pages of our word-order study (`scripts/eval_tess_order.py`),
which are not part of this repository.

## Licence

Apache-2.0.
