Skip to content

[models] Add font style classification of words: emphasis, colors, handwriting and font family - #2237

Merged
felixdittrich92 merged 5 commits into
mindee:mainfrom
felixdittrich92:font-style
Nov 27, 2026
Merged

felixdittrich92 merged 5 commits into
mindee:mainfrom
felixdittrich92:font-style

Conversation

@felixdittrich92

@felixdittrich92 felixdittrich92 commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2025
Closes #868

This PR adds font style classification of words: a lightweight classifier, run on every word next to the
recognition model, predicts how each word is set. It's opt-in (detect_font_style=True). The emphasis ends up in
the text exports, so it reaches downstream consumers such as LLMs (#2025), and each word says whether it's
handwritten (#868).

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

model = ocr_predictor(pretrained=True, detect_font_style=True)
result = model(DocumentFile.from_pdf("path/to/doc.pdf"))

word = result.pages[0].blocks[0].lines[0].words[0]
word.font_style  # {"bold": {"value": True, "confidence": 0.98}, ..., "family": {"value": "Tinos", "confidence": 0.61}}
word.style("underline")  # "double"
print(result.export_as_markdown())  # **Total amount** is <u style="text-decoration-style: double">due</u> ...

What is predicted

Attribute Classes
bold, italic, strikethrough, handwritten False / True
underline none, single, double
color black, gray, white, red, orange, brown, yellow, green, blue, purple
highlight none, yellow, green, pink, blue, orange
category sans_serif, serif, display, handwriting, monospace, unknown
family the closest of 378 font families (doctr.datasets.FONT_FAMILIES), one class per design, including free metric-compatible clones of the common document fonts (Times → Tinos, Arial / Helvetica → Arimo, Courier → Cousine, Cambria → Caladea, Calibri → Lato, Computer Modern → Latin Modern)

handwritten is True when the word is written by hand. Script and casual typefaces set as type (a script logo,
Comic Sans) are printed. The training data is synthetic: handwriting fonts drawn with the variation of a pen, and
script typefaces both written and set as type.

Changes

  • Model: mobilenet_v3_small_font_style (MobileNetV3-Small, 64 x 256 RGB input). It outputs the logits of all
    attributes concatenated, and cfg["classes"] maps each attribute to its classes, so any classification backbone
    can be trained for it. The weights are font_style_mnv3s-9d4a1aca.pt (v1.2.0 release assets).
  • Predictors: FontStylePredictor / font_style_predictor (standalone, chunked like the orientation
    predictors), and detect_font_style on ocr_predictor / kie_predictor.
    • The OCR predictor crops every word again for the classifier, with a margin of 0.15 x the box height
      (doctr.utils.geometry.expand_boxes). The recognition crops are too tight and cut out underlines.
    • With rotated pages, these crops are rectified like the recognition crops.
  • Elements: Word.font_style (also on Prediction) and Word.style(attribute). font_style is part of the
    JSON export, and exports without it still load.
  • Exports: Markdown (**, *, ~~, <u>, <mark>), HTML (<strong>, <em>, <s>, <u>, <mark>, text
    color) and AsciiDoc (roles) mark up the styles. Consecutive words with the same style share one span. hOCR wraps
    bold / italic words in <strong> / <em> and adds x_font. The text export and render() stay plain.
    font_style=False (export_as_markdown, export_as_asciidoc, export_as_html, export_as_xml, export_as, on
    pages, KIE pages and documents) leaves the markup out while the predictions keep the font style.
  • Interfaces: --detect_font_style and --font_style_markup / --no-font_style_markup in the CLI,
    detect_font_style and font_style in the API, and a checkbox in the demo.
  • Datasets / transforms:
    • FontStyleDataset and encode_font_style.
    • New RandomLowResolution, JPEGCompression and RandomColorCast transforms.
    • RandomPad and Resize now leave class targets (1-D arrays) unchanged.
  • References:
    • references/classification/train_font_style.py reports per-attribute accuracy / macro F1 and keeps the
      checkpoint with the best mean F1.
    • --class-weights can now be limited to selected attributes.
    • Color-safe augmentations.
    • A train-font-style-classification CI job on the new toy set (toy_font_style_set-071088e5.zip).
  • Docs: models overview, standalone predictors, results, exporting, CLI, training (data format, custom models),
    API pages and the pipeline diagram.

Evaluation

The released checkpoint was evaluated through the full OCR pipeline (ocr_predictor, default detection and
recognition models):

Data bold italic underline strikethrough color highlight handwritten category family
Synthetic validation set (100k word crops) 0.96 0.99 0.99 0.99 0.81 0.99 0.99 0.93 0.79
Rendered documents with a known style per word (4.7k words) 0.96 1.00 0.98 1.00 0.99 1.00 0.99 0.94 0.84
Same documents, scan-degraded 0.90 1.00 0.98 0.98 0.98 1.00 0.98 0.89 0.69
12 real born-digital PDFs at 144 dpi (20.8k words, truth from the text layer) 0.91 1.00 – – 0.98 – 1.00 0.99 0.73

The rendered documents were made with LibreOffice and read from PDF. Accuracy on the synthetic validation set was
measured on the word crops alone, without detection. On the real PDFs, family counts the clones of a design as
that design (Times 0.74, Arial 0.61, Roboto 0.55, Latin Modern 0.47).

Real handwriting was measured on the word crops of the HierText validation split (8k handwritten, 24k printed;
used for evaluation only): AUC 0.87, precision 0.82, recall 0.38, and 2.9% of the printed words called handwritten.

The rendered documents were also read rotated by 90 / 180 / 270 degrees and skewed by +7 / -12 degrees, with
assume_straight_pages=False and with straighten_pages=True. Every attribute stays within 3 points of the upright
pages. The Markdown / HTML / AsciiDoc / hOCR / JSON exports were checked for consistency with the predictions, and
the CLI was run with every export format.

Known limitations

  • Bold on small text. In a single crop of a page rendered at 144 dpi (~20 px words), regular words can look
    bold: precision of bold on the real PDFs is 0.35 (recall 0.93), and 0.74 at 288 dpi (accuracy 0.98).
  • Phone captures. Captures with strong sharpening make most words look bold, and printed form labels in
    photographed forms can be called handwritten.
  • handwritten recall. Real handwriting is found at a moderate rate (recall 0.38 at the default threshold):
    the model ranks it well (AUC 0.87) but stays conservative to keep printed text printed.
  • family on look-alikes. Old-style serifs (Wittgenstein, TeX Gyre Pagella, EB Garamond) are confused with
    Times on real pages. category is reliable.
  • Gray text. It's mostly predicted as black.

…ndwriting and font family

A MobileNetV3-Small classifier (`mobilenet_v3_small_font_style`) predicts the font style of each word crop:
bold, italic, underline (none / single / double), strikethrough, text color, highlight color, handwritten,
font category and the closest of 339 font families, each with a confidence. It is trained on synthetic word
crops (docTR-Synth-Generator) and opt-in in the OCR / KIE predictors with `detect_font_style=True`.

- `Word.font_style` / `Word.style(attribute)`, exported to JSON (older exports still load)
- Markdown, HTML, AsciiDoc and hOCR exports mark up the styles; the text export stays plain
- the words are cropped again for the classifier with a margin around their box (`expand_boxes`), so that
  the underline of a word is not cut out by a tight text box
- `font_style_predictor`, `FontStylePredictor`, `FontStyleDataset`, `--detect_font_style` in the CLI,
  `detect_font_style` in the API and the demo
- `RandomLowResolution`, `JPEGCompression` and `RandomColorCast` transforms; `RandomPad` and `Resize` leave
  class targets unchanged
- `references/classification/train_font_style.py`, with a CI job on a toy set
@felixdittrich92 felixdittrich92 added module: models Related to doctr.models module: io Related to doctr.io ext: tests Related to tests folder module: datasets Related to doctr.datasets ext: demo Related to demo folder ext: references Related to references folder module: transforms Related to doctr.transforms ext: api Related to api folder type: new feature New feature ext: docs Related to docs folder labels Nov 25, 2026
@felixdittrich92 felixdittrich92 self-assigned this Nov 25, 2026
@felixdittrich92 felixdittrich92 added this to the 1.3.0 milestone Nov 25, 2026
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.40828% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.28%. Comparing base (1434fde) to head (aebd786).

Files with missing lines Patch % Lines
doctr/transforms/modules/pytorch.py 96.49% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2237      +/-   ##
==========================================
+ Coverage   98.25%   98.28%   +0.02%     
==========================================
  Files         181      182       +1     
  Lines       12863    13165     +302     
==========================================
+ Hits        12639    12939     +300     
- Misses        224      226       +2     
Flag Coverage Δ
unittests 98.28% <99.40%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…hands and pen variation

- weights trained on 2M synthetic crops (font_style_mnv3s-4242f1e2.pt)
- handwritten: handwriting-style fonts count, typeset casual fonts (Comic Sans like) do not
- class weights without bold, italic and handwritten
…dwritten, better family on real documents

- one class per design (Times, Helvetica and Lato clones, widths and versions of a family)
- serif faces made for another script no longer read as Times
- script typefaces set as type are printed: handwritten means written by hand
- new toy set for the font style CI job
…subscripts, fractions, math operators, typographic quotes and marks
…tributes

- font_style=False leaves the detected font style out of the Markdown, AsciiDoc, HTML and hOCR exports
- --font_style_markup / --no-font_style_markup in the CLI
- encode_font_style and FontStyleDataset default to FONT_STYLE_ATTRIBUTES through None
@felixdittrich92
felixdittrich92 merged commit 656ea4e into mindee:main Nov 27, 2026
60 of 62 checks passed
@felixdittrich92
felixdittrich92 deleted the font-style branch November 27, 2026 07:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ext: api Related to api folder ext: demo Related to demo folder ext: docs Related to docs folder ext: references Related to references folder ext: tests Related to tests folder module: datasets Related to doctr.datasets module: io Related to doctr.io module: models Related to doctr.models module: transforms Related to doctr.transforms type: new feature New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add font style information to the Word class Classify blocks as handwritten or printed text

1 participant