Metadata-Version: 2.4
Name: legereocr
Version: 0.3.0
Summary: General-purpose multilingual OCR on ONNX Runtime, with text, table and searchable-PDF outputs
Author-email: Cristian Camilo Robledo Cuellar <cristiancamilorobledo@gmail.com>
License-Expression: Apache-2.0 AND MIT
Project-URL: Homepage, https://github.com/legere-ocr-full/legereocr
Project-URL: Repository, https://github.com/legere-ocr-full/legereocr
Project-URL: Issues, https://github.com/legere-ocr-full/legereocr/issues
Project-URL: Changelog, https://github.com/legere-ocr-full/legereocr/blob/main/CHANGELOG.md
Keywords: ocr,onnx,onnxruntime,document-ai,pdf,searchable-pdf,table-extraction,paddleocr,scanned-documents,llm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Text Processing
Classifier: Topic :: Multimedia :: Graphics :: Capture :: Scanners
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
License-File: licencias/Adobe-AFM.txt
License-File: licencias/MIT-DocRes.txt
License-File: licencias/MIT-GPT2.txt
License-File: licencias/MIT-docling-ibm-models.txt
Requires-Dist: onnxruntime>=1.31; python_version >= "3.11" and (sys_platform != "darwin" or platform_machine == "arm64")
Requires-Dist: onnxruntime; python_version < "3.11" or (sys_platform == "darwin" and platform_machine != "arm64")
Requires-Dist: onnx>=1.23
Requires-Dist: numpy>=1.22
Requires-Dist: opencv-python-headless>=4.8.1.78
Requires-Dist: pypdfium2
Requires-Dist: pikepdf>=2.10.0
Requires-Dist: pillow>=12.3.0
Requires-Dist: py-cpuinfo
Requires-Dist: rapidfuzz>=3.0
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pip-audit; extra == "dev"
Requires-Dist: bandit; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: urllib3>=2.8.0; extra == "dev"
Requires-Dist: msgpack>=1.2.1; extra == "dev"
Provides-Extra: benchmark
Provides-Extra: beam
Requires-Dist: pyctcdecode; extra == "beam"
Provides-Extra: traducir
Requires-Dist: sentencepiece>=0.2.0; extra == "traducir"
Provides-Extra: traducir-conversion
Requires-Dist: optimum[onnxruntime]; extra == "traducir-conversion"
Requires-Dist: torch; extra == "traducir-conversion"
Requires-Dist: transformers; extra == "traducir-conversion"
Requires-Dist: sentencepiece>=0.2.0; extra == "traducir-conversion"
Provides-Extra: excel
Requires-Dist: openpyxl; extra == "excel"
Provides-Extra: word
Requires-Dist: python-docx; extra == "word"
Provides-Extra: codigos
Requires-Dist: zxing-cpp>=3.1; extra == "codigos"
Provides-Extra: rapido
Requires-Dist: openvino>=2026.4; extra == "rapido"
Provides-Extra: heic
Requires-Dist: pillow-heif>=1.3.0; extra == "heic"
Provides-Extra: gpu
Requires-Dist: onnxruntime-directml; sys_platform == "win32" and extra == "gpu"
Requires-Dist: onnxruntime-gpu; sys_platform != "win32" and extra == "gpu"
Provides-Extra: graficos-modelo
Requires-Dist: torch>=2.4; extra == "graficos-modelo"
Requires-Dist: transformers<5,>=4.57; extra == "graficos-modelo"
Requires-Dist: safetensors>=0.4; extra == "graficos-modelo"
Provides-Extra: servicio
Requires-Dist: starlette>=1.3.1; extra == "servicio"
Requires-Dist: uvicorn>=0.30; extra == "servicio"
Dynamic: license-file

<div align="center">

<img src="https://raw.githubusercontent.com/Legere-Ocr-Full/legereocr/v0.3.0/.github/assets/logo.svg" alt="LegereOCR logo" width="112">

# LegereOCR

**Accurate OCR for real-world scans, on CPU — no GPU, no cloud.**

[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](#installation)
[![Version 0.3.0](https://img.shields.io/badge/version-0.3.0-informational.svg)](CHANGELOG.md)
[![Runs on CPU, no GPU](https://img.shields.io/badge/runs%20on-CPU%2C%20no%20GPU-brightgreen.svg)](#profiles-and-hardware)

[Installation](#installation) · [Quick start](#quick-start) · [See it in action](#see-it-in-action) · [Key numbers](#key-numbers) · [Documentation](#documentation) · [Español](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/README.es.md)

</div>

> *Legere* — Latin: **to read**.

**A general-purpose library that makes any scanned document readable, on CPU: PP-OCRv5/v6 OCR on ONNX Runtime or OpenVINO (no PaddlePaddle; the optional Tesela engine is faster), image enhancement, structured output for LLMs, searchable PDF, Word and Excel.**

**For developers and teams that need to read scanned documents (contracts, invoices, forms, photos) without a GPU or a
cloud service:** one `pip install`, accurate text with positions, and ready-made outputs for LLMs, searchable PDF, Word and
Excel. It runs on CPU, handles degraded scans better than PaddleOCR itself and works offline once the models are downloaded.

Minimal example (after the [installation](#installation) steps; `scan.jpg` is any image or PDF of yours):

```python
from legereocr import Legere

with Legere() as ocr:
    print(ocr.text("scan.jpg"))
```

> The detailed documentation (`docs/`) is written in Spanish. The entry-point files (this README, `SECURITY.md`,
> `CONTRIBUTING.md`, `CHANGELOG.md`, `LICENSES.md`, `NOTICE`) are in English.

## See it in action

Real LegereOCR output on [`ejemplos/factura_foto.jpg`](https://raw.githubusercontent.com/Legere-Ocr-Full/legereocr/v0.3.0/ejemplos/factura_foto.jpg), a synthetic phone photo of an invoice:
every name and number in it is fictitious, and `ejemplos/generar_foto_factura.py` rebuilds it. It is one sample, not a
benchmark; the measured numbers are in [Key numbers](#key-numbers).

<img src="https://raw.githubusercontent.com/Legere-Ocr-Full/legereocr/v0.3.0/.github/assets/showcase-photo-en.jpg" alt="A phone photo of an invoice next to the page LegereOCR flattened and cleaned, with every detected line boxed; 0 wrong letters or digits, 1.3 s per page on CPU" width="100%">

<img src="https://raw.githubusercontent.com/Legere-Ocr-Full/legereocr/v0.3.0/.github/assets/showcase-table-en.jpg" alt="The invoice table in the photo next to the records LegereOCR extracted, with the subtotal and the total checked arithmetically" width="100%">

<img src="https://raw.githubusercontent.com/Legere-Ocr-Full/legereocr/v0.3.0/.github/assets/showcase-fields-en.jpg" alt="Label and value pairs detected on the invoice and the same fields as JSON" width="100%">

To reproduce it (the time was measured on a Ryzen 9 9900X):

```powershell
.venv\Scripts\legere.exe enhance ejemplos\factura_foto.jpg -o page.png
.venv\Scripts\legere.exe tables ejemplos\factura_foto.jpg --json
.venv\Scripts\legere.exe structure ejemplos\factura_foto.jpg --json - --json-keys en
```

**[See all outputs →](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/GALLERY.md)** One example per output: searchable, presentable and transcribed PDF, Word, Excel,
Markdown, translation, SVG, compare, locate, batch split and anonymization.

## What it is and why

PaddleOCR ships the best open-source OCR models, but as a product it leaves a lot on the table. On degraded scans it
loses badly: CER 0.31-0.42 on the `heavy` variant of the 172-image ground truth (see the note under the table), against 0.11 for Legere. Its default
path (PaddlePaddle) is 20-40 times slower than its own ONNX Runtime path. And with the server detector and its defaults,
30 of 172 large pages come out empty ([docs/COMPARATIVA-PADDLEOCR.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/COMPARATIVA-PADDLEOCR.md)).

**LegereOCR does not compete with Baidu's models: it uses them better.** It does not train new networks; it builds a
better inference engine and document pipeline around them:

```
PDF/image → ingestion (native text layer if present, render otherwise) → preprocessing driven by a diagnosis
          → PP-OCRv5/v6 detection + recognition (ONNX Runtime, OpenVINO or the optional Tesela)
          → orientation, reading order, re-OCR of doubtful lines, confidence filter
          → text · JSON · blocks and fields · tables · PDF · Word · Excel
```

It is not tied to a document type, language or project. `lang=` accepts 113 codes (Paddle's ~106 languages plus
aliases): 88 are measured and 62 reach level A (CER <= 0.03 on a clean page and <= 0.10 on a degraded one).
Anything domain-specific (lexicons, language models, field validators) lives in **optional domain packages**; the core
behaves the same for invoices, books, receipts or forms.

Four products on a shared core:

1. **OCR**: image/PDF → text and JSON with positions. A PDF that already has a text layer uses that layer and its
   geometry, with no OCR pass.
2. **Image enhancement**: dark, skewed or dirty scans → clean images (usable without OCR).
3. **Structured output**: layout-preserving text for LLMs, semantic Markdown, JSON of blocks and fields
   (label → value), tables as records (Markdown, CSV or JSON), Excel, editable Word with native tables, hOCR 1.2 and
   ALTO v4. Opt-in: bar and pie charts → table.
4. **Searchable PDF**: a scan where nothing can be searched → a PDF you can search, select and copy from. Three modes:
   **faithful** (the untouched scan + an invisible text layer), **presentable** (corrected image, optional MRC-lite and
   PDF/A-2B) and **transcribed** (rebuilt from the recognized text, like a born-digital file).

## Key numbers

Same images, ground truth and metrics on both sides (`paddlepaddle 3.3.1` + `paddleocr 3.7.0` + `paddlex 3.7.2`,
`engine onnxruntime`; paired 95% CI). Paddle is the reference, not the goal. Methods and ceilings are in
[docs/COMPARATIVA-PADDLEOCR.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/COMPARATIVA-PADDLEOCR.md) (Spanish).

| Function (benchmark, metric) | LegereOCR | PaddleOCR | Ceiling |
|---|---|---|---|
| Reading, 172-image ground truth (CER) | **0.04733** (`balanced`) | 0.118 (best) · 0.140 (default v6) | — |
| Degraded page, `heavy` (CER) | **0.11001** | 0.31-0.42 | 0.026 (the same page, clean) |
| Clean page (CER) | 0.02603 | 0.032-0.039 (a tie except against v5 mobile) | — |
| XFUND: loose F1 / free-order CER | 0.9233 / **0.0638** | 0.9190 / 0.0880 (F1 tied) | — |
| 13 hard cases | **10/13** | 9/13 (v5 mobile) · 7/13 (v6) | — |
| 180° line orientation (recall) | **1.000** | 0.271 | 1.0 |
| Photos: CER on 3 benchmarks (UVDoc / SmartDoc-QA / CORD) | **0.081 / 0.147 / 0.090** | 0.321 / 0.251 / 0.229 | — |
| Cropped tables, FinTabNet / PubTabNet (TEDS) | **0.804 / 0.899** | 0.663 / 0.736 (v2) | — |
| Tables in the page, OmniDocBench (TEDS, historical sample) | **67.2** (structure 79.6) | 47.7 (not re-measured) | 68.6 |
| Full-page text, OmniDocBench (ED, tuning / test, historical) | **0.046 / 0.055** | 0.078 / 0.091 (not re-measured) | 0.0675 (other variant) |
| Extreme photometry: 132-image set / hard 186-image set (CER) | **0.0068** / 0.1623 by default (0.0964 with the opt-in rescue) | 0.0251 / **0.0928** | 0.0002 / 0.0683 |
| Table merging across pages (P / R) | **1.00 / 1.00** | 0.52 / 1.00 | reached |
| Stamps with arc-shaped text (CER) | **0.284** | 0.813 | — |
| Checkboxes (F1) | **0.993** | 0.069 | — |
| Word: median position error · Excel: cell F1 | **1.9 pt · 0.99** | 123 pt · 0.66 | — |
| Synthetic tables (12): cell-F1 / Jaccard | **0.9939 / 0.9940** | — | — |
| Time per page, ONNX Runtime 1.31 on both sides | **0.844 s** (`balanced`) | 0.880 s (v5 mobile) | — |
| Time per page with the `rapido` extra (OpenVINO) | **0.695 s** (`balanced`) | — | — |
| Time per page with the optional Tesela engine (separate run: ONNX Runtime 0.719 s, OpenVINO 0.586 s) | **0.427 s** (`balanced`) | — | — |
| Peak RAM in the ONNX Runtime 1.31 run (0.844 s row) · installed size | **0.538 GB · 242 MB** | 1.496 GB · 758 MB | — |

Full public benchmarks with their official evaluators (not a head-to-head with Paddle):

| Benchmark | Result |
|---|---|
| OmniDocBench v1.6, 1651 pages | Text Edit **0.10756**; TEDS **73.70**; structure **85.41**; reading-order Edit **0.19917**; formula Edit **0.77639**; 3.4 s/page |
| OmniDocBench with CDM | Overall **65.18** by default and **76.26** with the opt-in formula module (`LEGERE_FORMULAS=1`) |
| olmOCR-bench, 1403 PDFs, 8413 tests | base **45.0% ± 1.0%**; rasterized **46.7% ± 0.9%** |

**Which rows you can reproduce.** The 172-image ground truth (the reading, `heavy` and clean rows) is built from
synthetic pages and from 112 pages rendered from a private collection of real documents (65% of the bank), which is not
published: only aggregate results are. The "13 hard cases" row comes from crops of private documents and reports only pass/fail
counts. The XFUND, OmniDocBench, olmOCR, photo and cropped-table (FinTabNet, PubTabNet) rows use public datasets; the 180° orientation, extreme-photometry
(132-image set), table-merging, Word/Excel, synthetic-table, stamp and checkbox rows use synthetic data; all of these can
be rerun with the scripts in [benchmark/](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/benchmark/README.md). Timings are the median of three interleaved rounds of 20
pages of the ground-truth bank (a mix of synthetic pages and pages from the private collection), and RAM the maximum of those rounds. They come from one machine (Ryzen 9 9900X, 8 cores,
96 GB, Windows, with other workloads running: indicative times; compare only figures from the same run).

A rerun on a private collection of real documents (32 documents, 117 pages, not published) gave 30/32 read correctly
(the other 2 are encrypted PDFs) and 0 pages with errors.

**Where Legere loses**, stated plainly: chart-to-table quality on ChartQA (it is opt-in and much faster per chart); the
hard photometry benchmark by default (0.1623 against 0.0928; with the opt-in rescue, 0.0964, they tie); and formula
reading against specialized systems. It has no document VLM like PaddleOCR-VL. On clean forms (XFUND) the advantage
shrinks to character errors.

## Installation

Requires **Python 3.10 or newer**; development and measurements use 3.12 (onnxruntime 1.31 needs 3.11+: on 3.10 pip
installs the latest version it can find). Commands are PowerShell (Windows); on Linux they are analogous
(`python3.12`, `.venv/bin/`).

```powershell
py -3.12 -m venv .venv
.venv\Scripts\python.exe -m pip install -U pip
.venv\Scripts\python.exe -m pip install legereocr
```

With extras: `pip install "legereocr[rapido,word,excel]"`.

The models are not part of the package: they are downloaded from their sources with sha256 verification (this includes
`det_v6_tiny`, the default detector):

```powershell
.venv\Scripts\python.exe -m legereocr.motores.descarga
```

They are stored in `modelos/` (or in the folder named by `LEGERE_MODELOS`). To try it on the synthetic scanned PDFs in
`ejemplos/` (clone the repository to get them):

```powershell
.venv\Scripts\legere.exe info
.venv\Scripts\legere.exe ocr ejemplos\acta_inicio_escaneada.pdf --summary
.venv\Scripts\legere.exe markdown ejemplos\registro_tabla_escaneado.pdf --tables
.venv\Scripts\legere.exe pdf ejemplos\certificado_presupuestal_escaneado.pdf
```

Optional extras (`pip install "legereocr[extra]"`):

| extra | what for |
|---|---|
| `rapido` | OpenVINO engine (f32): same text; 0.695 vs 0.844 s/page with ORT |
| `word` / `excel` | `legere docx` / `legere xlsx` (python-docx / openpyxl) |
| `beam` | beam decoding with hotwords and LM (pyctcdecode; kenlm separately) |
| `codigos` | QR and barcodes (`legere ocr --barcodes`; zxing-cpp) |
| `heic` | iPhone HEIC/HEIF photos |
| `gpu` | DirectML (Windows) or CUDA; replaces the CPU onnxruntime |
| `traducir` | local document translation ([docs/TRADUCCION.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/TRADUCCION.md)) |
| `servicio` | HTTP service with a job queue (`legere-servicio`); `legere-mcp` (MCP) does not need it |
| `dev` | pytest and audit tooling (`rapidfuzz` is now a base dependency; `benchmark` is an empty compatibility extra) |

## Quick start

**English API.** Every public name of the main API has an English name (`Legere(profile="balanced")`, `doc.pages`, `line.text`,
`legere pdf --output`, `X-Legere-Keys: en`…) and the Spanish names stay valid forever. The two are listed side by
side in [docs/API-EN.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/API-EN.md). The chart reader's own types (`chart.tabla()`, `kind`/`values` fields named `tipo`/`valores`) are still Spanish only.

By default the engine runs plain and general: it assumes no domain language, document type or data to look for.

```python
from legereocr import Legere

with Legere() as ocr:                      # profile "auto": adapts to the hardware
    text = ocr.text("document.pdf")        # plain text in reading order
    doc = ocr.analyze("scan.jpg")          # Document: lines, boxes, confidences, order
    chart = ocr.read_chart("bars.png")     # chart type and values with confidence; `chart.tabla()` = [[category, series, value]]
    print(doc.pages[0].lines[0].text)
```

```powershell
legere text document.pdf                # the same from the terminal
legere pdf scan.pdf                     # searchable PDF (the image is left untouched)
legere layout document.pdf              # text with spatial layout, ideal for LLMs
legere markdown document.pdf --tables   # semantic Markdown: headings, fields, real tables
legere tables scan.pdf --md             # tables as records (headers + rows), no re-OCR
legere xlsx scan.pdf -o tables.xlsx     # tables → Excel (cells rebuilt from the real lines)
legere docx scan.pdf -o out.docx        # rebuild as EDITABLE Word: paragraphs + native tables + images
legere pdf scan.pdf --presentable --mrc --pdfa  # rebuilt PDF + MRC-lite compression + PDF/A-2B
legere pdf scan.pdf --transcribed       # "born-digital" style PDF: real selectable text + bold titles; complex tables as an
                                        #   image with invisible text; signatures, stamps, logos and photos as images
legere svg photo.jpg -o photo.svg       # VECTOR output: letters traced with Bezier curves, not a pasted image;
                                        #   --mode calco|calco_buscable|mixto, --pdf for a vector PDF
                                        #   (limits LEGERE_SVG_MAX_CONTORNOS/CURVAS/SEGUNDOS/BYTES; see docs/CONFIGURACION.md)
legere segments scan.pdf --json seg.json  # translation hook (NO model): paragraphs, titles and cells with id,
                                        #   text, box and "do not translate" spans (numbers, amounts, dates, codes, URLs)
legere reinsert scan.pdf trans.json -o es_en.docx  # {id: translated text} -> .md / .json / .docx / transcribed PDF with the layout
legere hocr document.pdf                # hOCR 1.2 for archive tools (and `legere alto`: ALTO v4)
legere locate scan.jpg --value 202600000926  # is what the LLM said really there? (or --extraction llm.json) page, box (px and PDF pt) or "absent"
legere pdf scan.pdf -o readable.pdf --manifest  # + readable.pdf.manifiesto.json: sha256 of source/output/models, profile
legere verify readable.pdf.manifiesto.json  # recomputes the sha256 against disk (exit code 1 if anything changed)
legere info                             # hardware, chosen profile and optional capabilities
```

The Spanish command names (`legere texto`, `legere tablas`, `legere excel`…) are aliases of the English ones.

### Outputs

Plain text, JSON with positions, layout text, Markdown, blocks and fields, tables (Markdown/CSV/JSON), Excel, Word,
searchable PDF (faithful, presentable, transcribed), vector SVG, hOCR, ALTO, translation segments, and a manifest with
sha256 hashes for provenance. Every command accepts `--help`.

### Profiles and hardware

`legere info` shows the detected hardware, the chosen profile and the optional capabilities. `auto` resolves to
`balanced` on any machine with 6 GB or more (below that, `light`); `accurate` is the highest-quality profile. All three
profiles use the PP-OCRv6 detector `det_v6_tiny`; `det_server` stays available through `Legere(det_model="det_server")`
or `LEGERE_DET_MODELO`. INT8 quantization was measured and rejected (opt-in only, `LEGERE_INT8=1`). All `LEGERE_*`
variables and the `Legere()` parameters are in [docs/CONFIGURACION.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/CONFIGURACION.md), and how to get the most
out of it (profiles, engine, parallelism, containers) in [docs/GUIA-SACARLE-EL-100.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/GUIA-SACARLE-EL-100.md).

### Inference engines

Legere runs on **ONNX Runtime by default**. The `rapido` extra adds OpenVINO, which `LEGERE_MOTOR=auto` uses when it is
installed. A third engine, [**Tesela**](https://github.com/tesela-engine/tesela), is **optional**: a CPU inference
engine written in Rust, built for the PP-OCR models Legere runs and for the whole OCR page around them. Legere gives
the same results and works the same with or without it; you only need it if you want the extra speed.

| Engine | How to select it | Time per page | Peak RAM |
|---|---|---|---|
| ONNX Runtime (f32) | default | 0.719 s | 522 MB |
| OpenVINO (f32) | `rapido` extra | 0.586 s | 1622 MB |
| Tesela (f32), optional | `LEGERE_MOTOR=pagina`, automatic without AVX512_BF16 | 0.476 s | 664 MB |
| Tesela (bf16), optional | `LEGERE_MOTOR=pagina` | **0.427 s** | 689 MB |

`balanced` profile on a Ryzen 9 9900X with 8 cores, 20 pages, median of three interleaved rounds (machine with other
workloads: indicative times). This is a separate run from the Key numbers table, so compare these times only with each
other. The f32 row forces f32 on the same CPU; CPUs without AVX-512 were not measured. In that run Tesela takes 41% less
time per page than ONNX Runtime and 27% less than OpenVINO.

These times are not the ones in Tesela's own README (0.294 s/page for Tesela and 0.739 s/page for LegereOCR + ONNX Runtime).
Those measure the native engine alone on the full page, through Tesela's command line, in a separate run. The times here
measure a whole LegereOCR call (`LEGERE_MOTOR=pagina`), including the Python around the engine (ingestion, page
orientation, word assembly and result), on 20 images with interleaved rounds. The two sets answer different questions
and should not be mixed.

To use Tesela, build its Python extension (module `tesela`, Python 3.12 or later, a recent stable Rust toolchain) in the
same virtual environment as Legere; there is no prebuilt package:

```powershell
git clone https://github.com/tesela-engine/tesela
cd tesela\crates\py
python -m pip install maturin
maturin develop --release
$env:LEGERE_MOTOR = "pagina"      # then run Legere as usual
```

Tesela's own [README](https://github.com/tesela-engine/tesela#readme) explains the build and how to reproduce its
measurements.

- **Default:** `LEGERE_MOTOR=auto` never loads Tesela. It uses OpenVINO if the `rapido` extra is installed and ONNX
  Runtime otherwise. Selecting Tesela without its extension installed stops at startup with a clear error.
- **Accuracy:** on the 172-image ground truth, CER is 0.04731 with Tesela and 0.04733 with ONNX Runtime. 41 of those
  pages have at least one different line, because re-OCR of doubtful lines is not ported to Tesela.
- **Fallback:** if Tesela fails to start or fails on a page, Legere continues on the normal path.

### Optional domains

The mechanism is generic: a domain is pluggable content, not part of the engine, and nothing runs by default. The first
one is `es-legal` (legal/administrative Spanish): contracting-related hotwords and field validators (tax IDs with check
digit, dates, amounts in figures and words, budget documents). **The domain's KenLM language model is not included**
in the package: the domain works without it, and you can supply your own with `lm_path=`.

```python
ocr = Legere(domain="es-legal")         # explicit opt-in
```

```python
ocr = Legere(hotwords=["ACME S.A.S.", "EXP-2026-001"])  # your own expected words
ocr = Legere(lm_path="my_model.bin")                    # your own KenLM language model
```

Hotwords act through the beam decoder: with `hotwords=` and `pyctcdecode` installed, the beam rises to `dudosas`
(doubtful lines only) even with no LM; without `pyctcdecode`, the beam stays `off`. See [docs/CONFIGURACION.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/CONFIGURACION.md) §4.

Anyone can write a domain package (medical, invoices, another language): see `legereocr/dominios/`.

### PaddleOCR compatibility

`legereocr.compat.paddle` is a PaddleOCR 3.x adapter on top of the Legere engine (no `paddlepaddle`). To migrate, replace
`from paddleocr import PaddleOCR` with `from legereocr.compat.paddle import PaddleOCR`; `predict(path)` and `ocr(path)`
return results with the same keys (`rec_texts`, `rec_scores`, `rec_boxes`…).

## Documentation

The detailed documentation is in Spanish.

| Document | Contents |
|---|---|
| [docs/COMPARATIVA-PADDLEOCR.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/COMPARATIVA-PADDLEOCR.md) | Function-by-function comparison with PaddleOCR 3.7: reading, structure, tables, outputs, speed |
| [docs/CONFIGURACION.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/CONFIGURACION.md) | Every `LEGERE_*` variable and the `Legere()` parameters |
| [docs/API-EN.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/API-EN.md) | English API: Python, CLI, HTTP and MCP, with the Spanish equivalents |
| [docs/GUIA-SACARLE-EL-100.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/GUIA-SACARLE-EL-100.md) | Profiles, engine, parallelism, containers, an LLM on top |
| [docs/TRADUCCION.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/TRADUCCION.md) | Local document translation (opt-in) |
| [docs/WORD-EXCEL.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/WORD-EXCEL.md) | Word and Excel reconstruction |
| [docs/DISENO.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/DISENO.md) | Design: architecture and technical decisions |
| [docs/INVENTARIO.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/docs/INVENTARIO.md) | Feature inventory |
| [benchmark/README.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/benchmark/README.md) | Benchmarks and how to reproduce the measurements |
| [SEGURIDAD.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/SEGURIDAD.md) | Threat model and defenses against hostile documents (Spanish) |
| [SECURITY.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/SECURITY.md) | How to report a vulnerability |
| [CONTRIBUTING.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/CONTRIBUTING.md) · [CHANGELOG.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/CHANGELOG.md) | How to contribute · change history |
| [LICENSES.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/LICENSES.md) | Licenses of models, ported code, resources and fonts |

## Security

OCR opens untrusted documents. See [SEGURIDAD.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/SEGURIDAD.md) (threat model, input limits, output escaping, model
hashes, and the recommendation to deploy in a sandbox with bounded resources) and [SECURITY.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/SECURITY.md) to report
vulnerabilities. `with Legere() as ocr:` releases the sessions on exit.

## Author

Created and maintained by **Cristian Camilo Robledo Cuellar** · [soft-solutions.org](https://soft-solutions.org) · cristiancamilorobledo@gmail.com

Need OCR, document data extraction or an LLM pipeline built for your documents? I build custom software and do consulting: get in touch through the website or by email.

## License

LegereOCR is free software under the [Apache License 2.0](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/LICENSE), © 2026 Cristian Camilo Robledo Cuellar, and includes
some third-party MIT-licensed code (see [`NOTICE`](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/NOTICE)). You may use, modify and redistribute it, commercially too,
keeping `LICENSE` and `NOTICE`.

The models are not part of the package: they are downloaded from their official sources and keep their authors' licenses
(PP-OCR and the other PaddlePaddle models: Apache-2.0; TableFormer: CDLA-Permissive-2.0; Opus-MT: CC-BY-4.0). Code
ported from PaddleX (Apache-2.0) and `docling-ibm-models` (MIT), the bundled resources and the downloaded fonts are
detailed in [LICENSES.md](https://github.com/Legere-Ocr-Full/legereocr/blob/v0.3.0/LICENSES.md).
