Repository navigation
feat(pdf): mark superscript and subscript text from glyph size and baseline - #4815
PeterStaar-IBM merged 12 commits into
Conversation
…seline
A PDF draws superscript and subscript text as smaller glyphs that are moved
off the baseline. The PDF pipeline keeps them as plain text, so "E = mc²"
becomes "E = mc 2" and "H₂O" becomes "H 2 O".
Add ScriptPositionOptions, off by default. When it is on, a new stage runs
after the heading-hierarchy stage. It reads the baseline and the drawn size
of each character with pypdfium2, for each PDF backend. A character is a
superscript or subscript when it is smaller than the body text of its line
and raised or lowered against it, and it touches that text. A text item
with such characters becomes an inline group of runs with formatting.script,
as the Word backend produces. The stage removes the space that the text-line
builder adds before a script ("mc 2") when the PDF draws the two characters
side by side.
Body text, list items and footnotes are handled. Headings, captions, tables,
code, formulas and OCR text do not change. With the option off, the output
does not change.
Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
…aracters Pick the body of a line from the groups set in the largest letters, so a large symbol, such as a sum sign, does not make the text around it a superscript. A line now ends where the baseline moves by most of a line height or where the pen returns to the start of the line. A superscript stacked over a wide subscript stays on its line. A script must be moved by less than its own size. This rule replaces the drop-cap rule, so a citation on the short last line of a paragraph is marked. Measure only the characters that match the item's text, so characters from a nearby line do not change the result. Join a surrogate pair from PDFium into one character. Compute every rewrite before the stage changes the document, so a failure leaves the document unchanged. Read the source and the password from typed attributes instead of with getattr. Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
A run has no whitespace at its edges, as in the Word backend. The export puts one space between runs, so a converted PDF and a Word document give the same text, and no double space appears Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
|
✅ DCO Check Passed Thanks @yashikam19, all your commits are properly signed off. 🎉 |
Merge Protections🟢 All 2 merge protections satisfied — ready to merge. Show 2 satisfied protections🟢 Enforce conventional commitMake sure that we follow https://www.conventionalcommits.org/en/v1.0.0/
🟢 Require two reviewer for test updatesWhen test data is updated, we require two reviewers
|
AI triage (advisory)Checked commit This pull request adds an opt-in pipeline stage to detect superscript and subscript text in PDF documents. The stage reads character sizes and baselines with CI safety: needs maintainer care before you approve CI.
The |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
…subscript Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com> # Conflicts: # docs/usage/advanced_options.md
There was a problem hiding this comment.
AI first review (advisory): no blocker found
This review covers the full diff at 4ca9071696. It read the code and did not run it.
New opt-in stage that marks superscript and subscript text in PDF documents. The feature is off by default. The algorithm, locking, and document-mutation order are correct. No regressions to existing behavior. The reviewer should confirm that standalone page footnotes being rewritten into inline groups (not just footnotes referenced by tables/pictures) is the intended scope.
A maintainer makes the merge decision. This review never approves the pull request.
|
@dolfim-ibm @PeterStaar-IBM @cau-git, this PR is ready for review. The branch is up to date with Analysis on the current head (
|
| Labels on PDFs with a text layer (263 labels, 56 PDFs) | Option off | Option on |
|---|---|---|
| Superscript (257) | 0 | 239 |
| Subscript (6) | 1 | 6 |
| Total | 1 | 245 (93%) |
- 10 more labels are marked, but the text inside the mark differs a little from the label (a space or a different dash from the PDF text layer), so the rule does not match. With these, 255 of 263 (97%) are marked.
- 8 labels are not marked. 4 are in headings or table cells, which the option does not change. 2 are not in the PDF text layer. 1 is a footnote marker on a line with no other letters (the text before it is redacted). For 1 label, I could not find the character it means.
- 68 more labels are on scans, image-only pages, or broken text layers. The option does not change OCR text, so they are out of scope.
False marks: the option never marked normal text
| Set | Marks | Wrong |
|---|---|---|
| The 87 labelled PDFs | 348 | 0 |
| 100 random PDFs without labels | 2 | 0 |
- There are more marks than labels, because a document often has the same superscript more than once. For example, a footnote number is marked in the sentence and again at the footnote.
- Most marks match a label. I read the others by hand, and all of them are real superscripts.
- On the 100 PDFs without labels, the only 2 marks are
m², which is correct.
Cost: for the 1-page PDFs, there is no measurable difference between off and on (about 0.25 s per document). On multi-page PDFs from tests/data: +0.26 s on 9 pages and +0.12 s on 18 pages.
Method and limits
- The scores use ParseBench's
FormattingRule, which passes a label when the output has<sup>text</sup>or<sub>text</sub>. - OCR was off, so scans have no text, and their labels cannot pass. The option does not change OCR text in any case.
- The 100 PDFs without labels were sampled at random from the ParseBench text documents.
- The timings come from single runs on one machine.
A note on the export
The option sets formatting.script on the runs in the DoclingDocument. The exporters show the runs as follows:
| Export | Option off | Option on |
|---|---|---|
| HTML | <p>Water is H2O …</p> |
<span class='inline-group'>Water is H <sub>2</sub> O …</span> |
| Markdown | Water is H2O … |
Water is H 2 O … |
docling-core's inline-group serializer puts a space between runs, and it writes an inline group as a <span> and not as a <p>. The Word backend shows the same output. So with the option on, Markdown gets a space around each subscript that had none in the PDF. Should I fix the spacing in docling-core first, or is the option acceptable as it is, since it is off by default?
Possible follow-ups
These are out of scope for this PR. I can open issues or PRs for them if they are useful.
- Headings and table cells. Ordinals in dates (
22nd) and units in tables (m²) are common there. This PR excludes them to keep the change small. - Spacing between runs in the HTML and Markdown export, so that
H₂OstaysH2Oin Markdown and becomesH<sub>2</sub>Oin HTML. This change belongs in docling-core. - Superscript and subscript in the Markdown export, for example as an option to write
<sup>and<sub>tags. This change belongs in docling-core. - OCR text. OCR engines give word boxes but no character baselines, so scans need a different method.
geoHeil
left a comment
There was a problem hiding this comment.
Reviewed 4ca90716963b154a9da48dc1869a4fff025c55ff. Two output defects remain.
- _run_prov keeps only the first page of a matched run. In a valid constructed DoclingDocument with H2O on page 1 and a continuation on page 2, the rewrite drops all page-2 provenance. Keep the provenance for each page. This reproduction checks the document model and stage; it is not a full cross-page PDF conversion.
- _apply replaces paragraph blocks with top-level InlineGroup nodes. HTML changes two source paragraphs from separate
<p>blocks to adjacent<span>elements. The browser loses their paragraph separation. Keep the paragraph blocks.
Local validation: 35 tests pass, and both defects reproduce. Current CI and Docs CI pass. Codecov patch coverage is 88.27930%, but the tests do not detect these defects. The spacing and export question in the author's comment also remains open.
Local make check stops on file-length violations that already exist on base. The other read-only checks pass. I made no source or reference-data changes.
Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
|
Thanks @geoHeil, both fixed in
Both new tests fail on In the same commit, the step now skips image input. Before, the PDF pipeline logged a false "recovery failed" warning for every image with the option on. Two limits that come from docling-core's inline-group serializer, so I left them to the maintainers: the space between runs ( Could you re-review when you have time? |
|
Hi @yashikam19, thank you for this pull request. It has a merge conflict with git fetch upstream
git rebase upstream/main
# resolve the conflicts, then:
git push --force-with-leaseWe can continue with the review and CI after that. |
…subscript Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
|
Hi @PeterStaar-IBM, I have merged |
|
@yashikam19 this is now unblocked: docling-project/docling-core#693 is released in docling-core 2.106.0, and #3891 is merged and released in docling 2.147.0, so Please merge the latest |
…subscript Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
…ipt runs docling-core 2.106.0 joins inline runs without a separator, so runs must carry their own whitespace. Keep a space beside a script only where the PDF shows a gap of at least MIN_WORD_GAP, since the parser also reports a space where a raised script touches its text. Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
Each linked run exports as a link of its own, so a linked footnote gave one link for its marker and one for its text. Set the hyperlink on baseline runs only. Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
|
@vagenas @PeterStaar-IBM @geoHeil, this is ready for re-review. I merged SpacingWith docling-core 2.106.0, each run now carries its own whitespace. A space beside a script stays only where the PDF shows a gap of at least 0.1 of the font size.
The false spaces come from I chose the threshold from 633 spaces beside scripts in 87 labelled ParseBench PDFs. At 0.1, 397 spaces are removed, and all the spaces that are real characters in the PDF stay. LinksA linked footnote now has one link, because only baseline runs get the hyperlink: Ground truthI regenerated the output for the documents from the earlier table, with the option on:
More HTML output from the ParseBench PDFs:
The e2e ground truth in ParseBench resultsI scored the HTML export of the pushed code with ParseBench's
Limits and a question
Validation
|
|
The CI failures on this PR come from
Both appear to come from #5175, which added that test. This PR does not touch AsciiDoc. On the PR head ( In the I can open a small fix for |
|
can you send a fix and stack your branch on top with i.e. stax or gh-stack ? |
|
@yashikam19 Yes, please provide the fix and notify us or follow the suggestion of @geoHeil . Either option is good! |
There was a problem hiding this comment.
Re-reviewed ec2d94e47924192f74aec43be79a1e99ef5face1 against PR base e3681a613e1be0dd3019bba61b4dc10b92e6e776.
The previous feature blockers are fixed. I found no new feature blocker. **Not ready to merge yet: required CI still fails. Fix it please as discussed
|
@geoHeil @PeterStaar-IBM the fix for |
…subscript Signed-off-by: Yashika Malhotra <106444881+yashikam19@users.noreply.github.com>
vagenas
left a comment
There was a problem hiding this comment.
Thanks @yashikam19.
On your Markdown question: 2e.g. AAPL in Markdown is fine for this PR; the script mark stays in the document, and the topic of the Markdown export is covered in docling-project/docling-core#661.
Summary
Add an option that marks superscript and subscript text in PDFs. It is off by default.
Today,
mainconvertsE = mc²toE = mc 2and21stto21 st, andH₂Oloses its subscript and becomesH2O. With the option on, these characters become runs withformatting.scriptset tosuperorsub, as Docling already does for Word documents.A PDF has no label for superscript text. So the new step measures each character: a superscript is smaller than its line and drawn higher, a subscript is smaller and drawn lower.
Changes
docling/utils/pdf_char_geometry.py: reads the size and the baseline of each character with pypdfium2, for both PDF backends. Invisible text (render modes 3 and 7) is skipped.docling/utils/script_position.py: finds the characters that are smaller than their line, raised or lowered, and next to the text they mark. Runs carry their own whitespace, and a space beside a script stays only where the PDF shows a gap of at least 0.1 of the font size.docling/models/stages/script_position/: a new stage after the heading-hierarchy stage. A text item that has such characters keeps its place and holds an inline group of its runs. A list item keeps its marker. Each run has one provenance item for each page it is on. Only baseline runs get the item's hyperlink, so a linked footnote has one link.ScriptPositionOptionsinpipeline_options.py, a docs section indocs/usage/advanced_options.md, and the new modules intach.toml.Body text, list items and footnotes are handled. Headings, captions, tables, code and formulas do not change. OCR text, invisible text, and image input are left unchanged.
Issue resolved by this Pull Request:
Resolves #520
Checklist:
Review evidence:
Before and after, with the default backend, docling-core 2.106.0 and the option on:
main, Markdownmc 2,H2O,21 stmc<sup>2</sup>,H<sub>2</sub>O,21<sup>st</sup>mc2,H2O,21stelsevier-00.pdf, authorsDuarte a,b,c,* ,Duarte <sup>a,b,c,*</sup>,Duarte a,b,c,*,2206.01062.pdf, footnote[1 https://…](url)<sup>1</sup><a href="url">https://…</a>1[https://…](url)normal_4pages.pdf, Korean note markers상해 1) 나상해<sup>1)</sup>나상해1)나The false spaces come from
docling-parse, which starts a new word when a character's baseline moves far enough, and joins words with a space. With the option off, the output is the same as onmainand keeps these spaces. With the option on, this PR removes them from the runs.ParseBench
FormattingRule, on the HTML export of the 87 PDFs with superscript or subscript labels. OCR was off.A PDF counts as having a text layer if it has at least 100 letters or digits. One label (
*) is not applicable under the rule.Known limits:
2 e.g. AAPLbecomes2e.g. AAPL.Duarte <sup>a,b,c,*</sup>.pypdfium2backend, a script can have spaces inside it. A raised script on the first line of a text block can become its own text item, and it is then not marked, such as the2ofmc2in the fixture.Screenshots from before the spacing fix: PDF page,
main, this branch (rendered)Reference data: no change. The option is off by default. With the option off, the Markdown, HTML and plain text of the four documents above are identical to
main.Tests:
tests/test_script_position.py: text that must be marked, text that must not be marked (such as%,°, small caps and the LaTeX logo), the spaces beside a script, the stage on aDoclingDocument, a linked footnote, a run that crosses a page break, and two paragraphs in a row in HTML.tests/test_script_position_pdf.py: a PDF exported from Word, with both backends. The exact Markdown and HTML of theH2Oand21stlines, with the default backend. Rotated and cropped pages, invisible text, and image input.Commands and results:
uv run pytest tests/test_script_position.py tests/test_script_position_pdf.py: 45 passed.uv run pytest tests/test_options.py tests/test_heading_hierarchy.py tests/test_heading_hierarchy_pdf.py tests/test_backend_docling_parse.py tests/test_backend_docling_parse_legacy.py tests/test_backend_pdfium.py tests/test_backend_pdfium_rotation.py tests/test_pdf_outline.py tests/test_font_style.py: 174 passed.make validate: passed.CI:
lintandrun-tests-corefail because of two failures that are also onmain, intests/test_backend_asciidoc.py. This PR does not touch that file. test(asciidoc): expect run whitespace in the hard line break test #5186 fixes them.