Skip to content

v1.2.0

Latest

Choose a tag to compare

@felixdittrich92 felixdittrich92 released this 24 Nov 14:03
· 1 commit to main since this release
6a0c945

Note: docTR 1.2.0 requires python >= 3.11, torch >= 2.11.0 and torchvision >= 0.26.0

Note

docTR now reads formulas and handles very long documents. v1.2.0 adds formula recognition (LaTeX output in every export format) and lazy, chunked and streaming prediction, so a 1000+ page PDF runs in one call without the memory growing with the page count. It also ships new table structure and layout checkpoints, much better reading order, figure export, faster recognition and loop-based ONNX export for the autoregressive models.

Important

SAR and MASTER were less accurate in v1.1.0. A shared activation module silently dropped one ReLU from the ResNet31 stem of sar_resnet31 and master. This is fixed: on IIIT5K, master goes from 67.8% back to 76.7% word accuracy and sar_resnet31 from 64.1% back to 76.1%. If you use either model, please upgrade. Thanks to @Zephyr4772 for finding and fixing it (#2232).

What's Changed

Breaking Changes 🛠

  • The minimum supported versions were raised from torch 2.0.0 to torch 2.11.0 and from torchvision 0.15.0 to torchvision 0.26.0
  • Word confidences changed for crnn_*, viptr_tiny, sar_resnet31 and master. Only the probabilities of the predicted characters are aggregated now: CTC blank frames and the positions after <eos> are ignored. The decoded words are the same, but the confidences are higher, so thresholds tuned on v1.1.0 confidences may need to be adjusted. vitstr_* and parseq are unchanged. An empty prediction now has a confidence of 0.
  • VOCABS["latex"] was removed and replaced by doctr.datasets.LATEX_TOKENS (a token-list vocab used by the new formula model).
  • When the layout model runs, the Markdown / AsciiDoc / HTML exports now add a <!-- image --> placeholder for every detected figure. Pass images="none" to leave them out.
  • Tables are now built from the predicted cells and the words of the page. A table can have more cells than the model predicted, and rows/columns without text are removed. TableCell.objectness_score is None for a cell built from words.
  • Checkpoints are now loaded with torch.load(..., weights_only=True). Checkpoints that pickle arbitrary Python objects can no longer be loaded. Plain state_dicts are not affected.
  • doctr.models.modules.transformer.scaled_dot_product_attention now returns None in place of the attention weights, since it uses PyTorch's fused F.scaled_dot_product_attention.

New features

  • Formula recognition with the new FormulaNet architecture and an HGNetV2 backbone, with LaTeX output in every export format, by @felixdittrich92
  • Lazy page sources & chunked / streaming predictors for long documents and large image collections, by @felixdittrich92
  • Better tables: grids are built from the cells and the words of the page, a new TableCenterNet checkpoint is available, and the HTML export writes rowspan / colspan. By @felixdittrich92 and @sibisrinivasb
  • lw_detr_m checkpoint, the larger layout model, by @felixdittrich92
  • Figure export (FigureEncoder): figures found by the layout model are placed in the reading order and can be embedded in or linked from the Markdown / HTML / AsciiDoc exports. By @felixdittrich92
  • Configurable word confidence aggregation (confidence_aggregation=...), by @felixdittrich92
  • ONNX export of the decoding loops with export_model_to_onnx(..., dynamo=True) for formulanet, parseq and master, by @felixdittrich92
  • New augmentations for photographed pages: RandomPerspective, RandomGlare and RandomLighting, by @fercho1999leon

✨ Formula Recognition ✨

formula_example

Left: the two Formula regions found on page 5 of "Attention Is All You Need". Right: page.export_as_html(), with the LaTeX predicted by formulanet rendered by KaTeX (equation number included).

docTR can now read mathematical formulas. In the OCR pipeline, each region the layout model labels as a Formula is removed from text detection, cropped and passed to the new formulanet model, which predicts its LaTeX source. The model follows the PP-FormulaNet design: an HGNetV2-B4 encoder with a small autoregressive transformer decoder. It was written from scratch under Apache-2.0 and trained on the printed and handwritten formulas of UniMER-1M.

Architecture Input shape # params Exact match Edit similarity BLEU
formulanet (256, 768, 3) 26.4 M 44.40 91.30 0.840

Metrics are produced by references/formula/evaluate.py with the new FormulaMetric on the full UniMER-Test set (23,757 formulas), computed on LaTeX tokens.

Inside the OCR pipeline

from doctr.io import DocumentFile
from doctr.models import ocr_predictor

predictor = ocr_predictor(pretrained=True, detect_formulas=True)
result = predictor(DocumentFile.from_pdf("attention_is_all_you_need.pdf"))  # arXiv:1706.03762

formula = result.pages[4].formulas[0]
print(formula.value)
# \mathrm { F F N } ( x ) = \operatorname* { m a x } ( 0 , x W _ { 1 } + b _ { 1 } ) W _ { 2 } + b _ { 2 } \tag { $ 2 $ }
print(formula.confidence)  # 0.98

print(result.export_as_markdown())  # formulas are exported as $$ ... $$ display math

Formulas are placed in the reading order with the text and are never also read by the text recognition model, so they are not returned twice. Each export format renders them:

Export Rendering
render() the LaTeX source
Markdown $$, the LaTeX source and $$ on their own lines
HTML <div class="formula">$$...$$</div> (renders with MathJax / KaTeX auto-render)
AsciiDoc a [latexmath] passthrough block
hOCR an ocr_math element
JSON the formulas key of each page

Equation numbers are predicted as \tag{...}, so they render in KaTeX-based Markdown and HTML viewers.

Standalone usage

from doctr.models import formula_predictor, layout_predictor

predictor = formula_predictor("formulanet", pretrained=True)
out = predictor([formula_image])
# out[0] -> ('J ( u , y ) = \\int _ { 0 } ^ { 1 } \\frac { | u | ^ { 2 } } { 2 } \\, d x + \\Psi ( y )', 0.98)

# Or read the formula regions of whole pages straight from the layout predictions
regions = layout_predictor("lw_detr_s", pretrained=True)(pages)
formulas = predictor.predict_regions(pages, regions)
# formulas[0][0] -> {'geometry': ..., 'value': '\\frac { a } { b ^ { 2 } }', 'confidence': 0.97, 'score': 0.91}

Formula recognition is also available in the CLI (--detect_formulas), the API (detect_formulas in the /ocr request) and the demo. The reference training scripts are in references/formula/.


✨ Long documents: lazy, chunked & streaming prediction ✨

Before this release, every page was decoded into memory up front, so a 300-page PDF could be enough to get the process OOM-killed. docTR can now process 1000+ page documents and large image collections in a single call, and the memory used does not grow with the number of pages. Everything is opt-in and backward compatible.

Open a document lazily: pages are only decoded when they are accessed:

from doctr.io import DocumentFile
from doctr.models import ocr_predictor

predictor = ocr_predictor(pretrained=True)

doc = DocumentFile.from_pdf("path/to/1000_pages.pdf", lazy=True)
result = predictor(doc)  # one call, processed chunk by chunk

# Folders of images and any mix of PDFs / images / folders / URLs work too
doc = DocumentFile.from_images("path/to/scans/", lazy=True)
doc = DocumentFile.from_files(["contracts/", "annex.pdf", "signature.png"], lazy=True)

Stream the results: write each page as soon as it is processed instead of keeping a whole Document in memory:

with open("result.txt", "w") as f:
    for page in predictor.stream(doc):
        f.write(f"--- page {page.page_idx + 1} ---\n{page.render()}\n")

Tune the memory footprint: the predictors process page_chunk_size pages at a time and decode the next chunk in a background thread while the models run:

predictor = ocr_predictor(pretrained=True, page_chunk_size=8)

for page in predictor.stream(doc, page_chunk_size=4, prefetch_pages=False):
    ...

The task-specific predictors (detection, recognition, layout, table structure, page and crop orientation) accept the same lazy inputs and chunk them too:

from doctr.models import recognition_predictor

crops = DocumentFile.from_images("path/to/word_crops/", lazy=True)
words = recognition_predictor(pretrained=True, chunk_size=2048)(crops)

The page sources (PDFSource, ImageSource, ConcatSource) behave like lists: they support slicing, concatenation with +, and iter_batches(n).

memory_example

Peak RAM of the default ocr_predictor on PDFs of 25 to 400 pages. v1.1.0 grows by about 65 MB per page and reaches 28.4 GB at 400 pages. Streaming a lazy source with v1.2.0 stays flat at about 3.6 GB. A plain predictor(pages) call also needs much less memory than before (5.1 GB), because it is processed in chunks too.


✨ Table Structure Recognition: new checkpoint & word-aware grids ✨

table_example

Left: the 58 cells predicted by tablecenternet on Table 2 of "Attention Is All You Need", with the merged header cells in green. Right: the HTML export of page.tables[0], which writes colspan for the merged cells.

New tablecenternet checkpoint. The training targets used to stop at 300 cells, so the model learned to stop detecting cells in dense tables. This is fixed, and a new geometric post-processing step (geometric_logic=True, the default) corrects the row/column indices that drift on borderless tables.

Architecture Input shape # params Recall Precision F1 Structure acc sec/it (B: 1)
tablecenternet (v1.1.0) (1024, 1024, 3) 7.1 M 82.31 96.01 88.64 77.53 0.5
tablecenternet (v1.2.0) (1024, 1024, 3) 7.1 M 96.41 96.50 96.46 78.85 0.5

Grids follow the text. In the OCR pipeline, tables are now assembled from the predicted cells and the words of the page. Cells the model missed are added, as are header rows and totals that lie outside the predicted cells. Rows the model split are merged, and rows it merged are split along their text lines.

Merged cells in HTML. The HTML export now writes rowspan / colspan for merged cells:

<table>
<tr><th rowspan="2">Item</th><th colspan="2">Revenue</th></tr>
<tr><td>2023</td><td>2024</td></tr>
<tr><td>Widgets</td><td>10</td><td>12</td></tr>
</table>

Use it with your own OCR. TablePredictor.predict_regions crops the table regions of a layout prediction and assigns your words to the cells:

from doctr.models import layout_predictor, table_predictor

regions = layout_predictor("lw_detr_s", pretrained=True)(pages)
tables = table_predictor("tablecenternet", pretrained=True).predict_regions(pages, regions, word_boxes)

tables[0][0]["cells"][0]["words"]  # indices of the words of the cell in `word_boxes[0]`, in reading order

The table model's cell scores are also exposed as TableCell.objectness_score.


✨ Layout Analysis: lw_detr_m ✨

The larger layout model now has pretrained weights:

Architecture Input shape # params mAP@[.5:.95] AP@[.5] AP@[.75] sec/it (B: 1) - CPU
lw_detr_s (1024, 1024, 3) 15.1 M 66.89 82.83 73.75 0.5
lw_detr_m (1024, 1024, 3) 29.5 M 69.20 84.48 75.71 0.7
from doctr.models import ocr_predictor

model = ocr_predictor(pretrained=True, detect_layout=True, layout_arch="lw_detr_m")

✨ Reading order & figure export ✨

Much better reading order. Words are now grouped into lines and lines into reading order more reliably on skewed scans, multi-column pages and receipts. On 365 pages (CORD / SROIE receipts, XFUND-de forms, OmniDocBench, multi-column and skewed PDFs) plus a 169-page held-out set, with detect_layout=True:

v1.1.0 v1.2.0
Reading-order edit distance (original / held-out), lower is better 0.311 / 0.523 0.153 / 0.119
Ground-truth lines read intact (original / held-out) 84.5% / 80.2% 96.4% / 96.4%
Text error of page.render() (original / held-out) 0.384 / 0.537 0.247 / 0.167

On CORD receipts the edit distance drops from 0.465 to 0.058. Without the layout model it still drops from 0.313 to 0.167 (original set).

reading_order_example

Reading order on the first page of a two-column arXiv paper, with detect_layout=True (the arrows follow page.items_in_reading_order()). v1.1.0 reads line by line across both columns. v1.2.0 reads the abstract, then the rest of the left column, then the right column.

Figures in the exports. Figures detected by the layout model now take part in the reading order: their caption follows them, and the text inside a figure is no longer split into the surrounding paragraphs. The Markdown, AsciiDoc and HTML exports can render them:

from doctr.io import FigureEncoder

markdown = result.export_as_markdown(images="placeholder")  # default: a <!-- image --> comment per figure
markdown = result.export_as_markdown(images="none")         # no figure markup
markdown = result.export_as_markdown(images="embedded")     # crops inlined as base64 data URIs
markdown = result.export_as_markdown(images=FigureEncoder("referenced", image_dir="assets"))  # crops written to disk and linked

figure_example

Left: the regions found by lw_detr_s on page 4 of "Attention Is All You Need". Right: page.export_as_html(images="embedded"). The figure is cut out and embedded with its caption, and the formula is rendered as display math.

When a figure is embedded or referenced, its caption becomes the alt text and stays visible. hOCR exports figures as ocr_photo areas. The CLI gains --images, --image_dir and --image_format:

doctr-cli --input_path report.pdf --detect_layout --output report.md --images referenced

✨ Word confidence aggregation ✨

You can now choose how the character probabilities of a word are combined into its confidence: "mean", "min", "max", "median", "geometric_mean", "harmonic_mean", or any callable that takes the 1D array of probabilities and returns a float.

from doctr.models import ocr_predictor

predictor = ocr_predictor(pretrained=True, confidence_aggregation="geometric_mean")

# or afterwards
predictor.reco_predictor.model.postprocessor.confidence_aggregation = "min"

It is also available in recognition_predictor, kie_predictor and the CLI (--confidence_aggregation). By default each architecture keeps the method it used before. The confidences themselves are now computed only over the predicted characters (see Breaking Changes), which makes them much better at telling correct words from misread ones (AUROC on 565 real word crops):

Model v1.1.0 v1.2.0
crnn_vgg16_bn 0.727 0.841
crnn_mobilenet_v3_large 0.800 0.863
viptr_tiny 0.777 0.866
sar_resnet31 0.602 0.852
master 0.766 0.858

✨ Faster inference & loop-based ONNX export ✨

Speed. MASTER and PARSeq now decode incrementally with a key/value cache, attention uses PyTorch's fused scaled_dot_product_attention, and the pre-/post-processing no longer uses thread pools that only competed for the GIL. Predictions are unchanged.

1,024 real word crops v1.1.0 v1.2.0
master, ONNX CPU 84.1 s 16.7 s (5.0×)
master, PyTorch GPU / CPU 2.45 s / 48.5 s 1.06 s / 18.5 s
parseq, PyTorch GPU / CPU 0.82 s / 10.9 s 0.65 s / 9.5 s

End to end, the latency per page drops by 9-19% depending on the document type (RTX 4080, db_mobilenet_v3_large + parseq).

ONNX export with dynamo=True. The default ONNX exporter unrolls autoregressive decoding over every step. With the new dynamo=True option, the decoding of formulanet, parseq and master is exported as ONNX Loop nodes that stop once every sequence is complete, as in PyTorch. This needs onnxscript.

import torch
from doctr.models import formulanet
from doctr.models.utils import export_model_to_onnx

model = formulanet(pretrained=True, exportable=True)
dummy_input = torch.rand((1, *model.cfg["input_shape"]), dtype=torch.float32)
model_path = export_model_to_onnx(model, model_name="formulanet", dummy_input=dummy_input, dynamo=True)
  • formulanet must be exported with dynamo=True. Unrolled, its 2048 decoding steps give a graph far too large to load.
  • For parseq / master, the loop export is much smaller (master: 186 vs 23,701 nodes) and as fast or faster on CPU, but about 2× slower on GPU with onnxruntime-gpu. The default therefore stays dynamo=False.
  • The default exporter now runs under torch.no_grad(). The output files are byte-identical and the export needs much less memory (about 6 GB less for tablecenternet).

Further improvements

  • Augmentations for photographed pages: RandomPerspective (warps the image and its boxes/polygons/mask), RandomGlare and RandomLighting, plus RandomPad. Fine-tuning LW-DETR on receipts with them raised mAP@[.5:.95] from 68.8 to 70.8 and made the model usable on phone photos.
  • Split word crops: very wide word crops are split, read part by part and merged. Repeated stretches (0000001, ENDORSEMENT, PARTICIPANTS) no longer gain or lose characters at the joins. By @pbstriker38
  • hOCR export now estimates x_size and x_fsize. By @WSHAPER
  • Reference scripts: device selection and AMP dtype for every training/evaluation script, batched Hungarian matching for LW-DETR, run metadata saved next to the checkpoints, and DDP fixes (multi-GPU evaluation, W&B / ClearML logging). By @fercho1999leon and @felixdittrich92
  • Robustness: a long list of edge-case fixes across io, utils, transforms, datasets and metrics: empty inputs and batches, grayscale / 16-bit / float / transparent images, zero-area and out-of-image boxes, interrupted downloads, and clear errors instead of crashes. Many thanks to @RavSinghChandan, @MohammadHijjawi97, @linhongyu510, @raashish1601, @AryanRG and @RaphaelFakhri
  • Synthetic text: fonts fall back to system fonts for characters they cannot draw. By @ousamabenyounes
  • Documentation was restructured with a new user guide, model pages and a deployment section: https://mindee.github.io/doctr/latest/
  • API: dependencies are now managed with uv instead of poetry
  • CI/CD: torch.compile artifacts are cached for the PyTorch unit tests. By @quotentiroler

What's Changed

Breaking Changes 🛠

  • [models] Export the autoregressive decoding of FormulaNet, PARSeq and MASTER as ONNX loops with dynamo=True by @felixdittrich92 in #2230

New Features

  • [transforms] RandomPerspective, RandomGlare and RandomLighting for photographed pages by @fercho1999leon in #2143
  • [models] Configurable word confidence aggregation for the recognition models by @felixdittrich92 in #2162
  • [io] Lazy page sources & chunked/streaming predictors for long documents and large image collections by @felixdittrich92 in #2208
  • [models] Add formula recognition (FormulaNet) with LaTeX export, HGNetV2 backbone and training references by @felixdittrich92 in #2227

Bug Fixes

Improvements

Miscellaneous

New Contributors

Full Changelog: v1.1.0...v1.2.0

What's Changed

Breaking Changes 🛠

  • [models] Export the autoregressive decoding of FormulaNet, PARSeq and MASTER as ONNX loops with dynamo=True by @felixdittrich92 in #2230

New Features

  • [transforms] RandomPerspective, RandomGlare and RandomLighting for photographed pages by @fercho1999leon in #2143
  • [models] Configurable word confidence aggregation for the recognition models by @felixdittrich92 in #2162
  • [io] Lazy page sources & chunked/streaming predictors for long documents and large image collections by @felixdittrich92 in #2208
  • [models] Add formula recognition (FormulaNet) with LaTeX export, HGNetV2 backbone and training references by @felixdittrich92 in #2227

Bug Fixes

Improvements

Miscellaneous

New Contributors

Full Changelog: v1.1.0...v1.2.0