Repository navigation
[models] Add font style classification of words: emphasis, colors, handwriting and font family - #2237
Merged
Merged
Conversation
…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
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 inthe text exports, so it reaches downstream consumers such as LLMs (#2025), and each word says whether it's
handwritten (#868).
What is predicted
bold,italic,strikethrough,handwrittenFalse/Trueunderlinenone,single,doublecolorblack,gray,white,red,orange,brown,yellow,green,blue,purplehighlightnone,yellow,green,pink,blue,orangecategorysans_serif,serif,display,handwriting,monospace,unknownfamilydoctr.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)handwrittenisTruewhen 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
mobilenet_v3_small_font_style(MobileNetV3-Small, 64 x 256 RGB input). It outputs the logits of allattributes concatenated, and
cfg["classes"]maps each attribute to its classes, so any classification backbonecan be trained for it. The weights are
font_style_mnv3s-9d4a1aca.pt(v1.2.0 release assets).FontStylePredictor/font_style_predictor(standalone, chunked like the orientationpredictors), and
detect_font_styleonocr_predictor/kie_predictor.(
doctr.utils.geometry.expand_boxes). The recognition crops are too tight and cut out underlines.Word.font_style(also onPrediction) andWord.style(attribute).font_styleis part of theJSON export, and exports without it still load.
**,*,~~,<u>,<mark>), HTML (<strong>,<em>,<s>,<u>,<mark>, textcolor) 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 addsx_font. The text export andrender()stay plain.font_style=False(export_as_markdown,export_as_asciidoc,export_as_html,export_as_xml,export_as, onpages, KIE pages and documents) leaves the markup out while the predictions keep the font style.
--detect_font_styleand--font_style_markup/--no-font_style_markupin the CLI,detect_font_styleandfont_stylein the API, and a checkbox in the demo.FontStyleDatasetandencode_font_style.RandomLowResolution,JPEGCompressionandRandomColorCasttransforms.RandomPadandResizenow leave class targets (1-D arrays) unchanged.references/classification/train_font_style.pyreports per-attribute accuracy / macro F1 and keeps thecheckpoint with the best mean F1.
--class-weightscan now be limited to selected attributes.train-font-style-classificationCI job on the new toy set (toy_font_style_set-071088e5.zip).API pages and the pipeline diagram.
Evaluation
The released checkpoint was evaluated through the full OCR pipeline (
ocr_predictor, default detection andrecognition models):
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,
familycounts the clones of a design asthat 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=Falseand withstraighten_pages=True. Every attribute stays within 3 points of the uprightpages. 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: precision of
boldon the real PDFs is 0.35 (recall 0.93), and 0.74 at 288 dpi (accuracy 0.98).photographed forms can be called handwritten.
handwrittenrecall. 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.
familyon look-alikes. Old-style serifs (Wittgenstein, TeX Gyre Pagella, EB Garamond) are confused withTimes on real pages.
categoryis reliable.black.