Skip to content

fix: preserve MathML content in HTML partitioning - #4478

Merged
cragwolfe merged 9 commits into
Unstructured-IO:mainfrom
fireblade2534:add-basic-math-support
Oct 15, 2026
Merged

cragwolfe merged 9 commits into
Unstructured-IO:mainfrom
fireblade2534:add-basic-math-support

Conversation

@fireblade2534

@fireblade2534 fireblade2534 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR adds support for preserving inline MathML content in the v1 HTML parser used by partition_html().

Previously, <math> was not assigned a custom element class. As a result, it fell back to DefaultElement, whose contents are intentionally skipped. This could silently remove mathematical expressions from otherwise valid extracted text.

For example, HTML such as:

<p>
    The error rate is
    <math>
        <semantics>
            <annotation encoding="application/x-tex">
                10^{-4}
            </annotation>
        </semantics>
    </math>
    per token.
</p>

could be extracted as:

The error rate is per token.

This PR introduces a Math phrasing element that preserves a textual representation of the expression when one is available.

Changes

  • Adds a Math class derived from Phrasing.

  • Registers <math> elements with the v1 HTML parser.

  • Searches for recognized TeX/LaTeX annotations within the MathML subtree.

  • Supports the following annotation encodings:

    • application/x-tex
    • tex
    • latex
    • application/x-latex
  • Falls back to the <math> element's alttext attribute when no supported TeX annotation is available.

  • Preserves text following the closing </math> element by emitting the element tail using the existing phrasing behavior.

The parser prefers an explicit TeX representation because flattening presentation MathML with itertext() can lose mathematical structure. For example, a superscript expression such as 10^-4 could otherwise be flattened into ambiguous plain text such as 10-4.

Why

The HTML parser's documented principle is that the browser rendering is the document.

However, before this change, standards-based MathML content could be rendered correctly by a browser while being completely removed during HTML partitioning because <math> was treated as an unrecognized element.

This is especially problematic because the failure is silent. Surrounding paragraph text remains intact, so consumers of partition_html() may receive syntactically valid but incomplete text.

Treating <math> as a specialized phrasing element allows mathematical content to participate naturally in surrounding paragraph text without requiring the parser to understand every individual Presentation MathML element such as <mrow>, <msup>, <mfrac>, <mi>, or <mn>.

Scope

This PR intentionally does not attempt to implement a complete MathML-to-text converter.

It currently preserves mathematical content when a reliable textual representation is directly available through:

  1. a recognized TeX/LaTeX <annotation>, or
  2. the <math> element's alttext attribute.

Other representations, such as Content MathML, arbitrary annotation-xml formats, OpenMath, SVG, or unsupported custom annotation encodings, are outside the scope of this change.

Example

Input:

<p>
    Complexity decreases from
    <math alttext="O(n^2)"></math>
    to
    <math>
        <semantics>
            <annotation encoding="application/x-tex">
                O(n^2/r)
            </annotation>
        </semantics>
    </math>.
</p>

Before:

Complexity decreases from to .

After:

Complexity decreases from O(n^2) to O(n^2/r).

Testing

Tests have been added for MathML behavior including:

  • extracting application/x-tex annotations,
  • supported TeX/LaTeX encoding variants,
  • falling back to alttext,
  • preferring a supported TeX annotation when both annotation and alttext are present,
  • preserving surrounding and tail text,
  • multiple inline <math> elements in one paragraph,
  • ignoring unsupported annotation encodings,
  • realistic nested Presentation MathML,
  • interaction with existing phrasing/emphasis behavior,
  • and regression coverage for ordinary phrasing elements.

Reviewer verification can also be performed with:

from unstructured.partition.html import partition_html

html = r"""
<p>
    The loss difference is on the order of
    <math>
        <semantics>
            <annotation encoding="application/x-tex">
                10^{-4}
            </annotation>
        </semantics>
    </math>.
</p>
"""

elements = partition_html(text=html)

for element in elements:
    print(element.text)

Expected output:

The loss difference is on the order of 10^{-4}.

Review in cubic

@cragwolfe

Copy link
Copy Markdown
Contributor

I found three correctness issues that should be addressed before merging:

  1. Default KaTeX output is duplicated. KaTeX's default htmlAndMathml output places a .katex-mathml branch beside a .katex-html visual branch. Math.iter_text_segments() now emits the TeX annotation, and normal Phrasing traversal then emits the sibling HTML as well (parser.py:735-741, registration at 1040-1041). A simple rendered 2 therefore becomes 22; structured formulas concatenate TeX with a flattened visual copy. Please recognize the paired producer structure and emit exactly one representation, while retaining HTML-only, MathML-only, unusable-MathML fallback, and two genuinely separate identical equations. Add KaTeX-shaped regression fixtures with exact occurrence counts.

  2. The annotation lookup can select a subexpression or discard a later usable representation. self.find(".//annotation[...]") searches every descendant, so an annotation belonging to a nested <semantics> operand can replace the entire outer <math> even when the outer expression has its own annotation or alttext (parser.py:724-733). The loop also breaks as soon as it finds an element, before checking whether its text is non-empty, so an empty first candidate hides later supported annotations. Finally, the PR advertises lowercase encoding="tex", but the exact XPath matching accepts only "TeX". Please limit candidates to annotations that represent the whole expression, normalize supported encoding labels, and continue until a non-empty candidate is found before falling back to alttext. Cover nested semantics, lowercase tex, and empty-first/later-nonempty cases.

  3. Display math is merged into surrounding prose. Every Math instance is unconditionally Phrasing, so <div>Before<math display="block" alttext="x=1"/>After</div> is accumulated as Beforex=1After, and adjacent display equations become one invented string (parser.py:702-741). display="block" is a defined MathML boundary and matches this parser's own block-item invariant. Please emit display math through an element-boundary path (preserving order, tails, metadata, links/emphasis) while keeping absent/inline display values inline; test prose/display/prose and adjacent display equations, including case-insensitive block.

The branch also needs the repository's release metadata update: it has no CHANGELOG.md entry and still reports 0.27.5, while current main is 0.27.6. Please update the changelog and synchronized package version after rebasing.

(authored by codex)

@fireblade2534

Copy link
Copy Markdown
Contributor Author

@cragwolfe Your issues should be fixed now

@cragwolfe

Copy link
Copy Markdown
Contributor

Follow-up content review at 1cd816fe85da019b878efb7237551ac4dffcd448: the original fixes are substantially improved, but four correctness gaps remain.

  1. High — KaTeX pruning can delete or duplicate equations in table cells (unstructured/partition/html/parser.py:785-793, parser.py:556-565). _normalize_katex() removes the visual branch when _latex is usable, but TableBlock bypasses Math and reads cells with td.itertext(). For an alttext-only pair, pruning leaves no text node and can make the table disappear; with presentation MathML plus a TeX annotation, raw itertext() can emit both forms. Please make table-cell traversal consume the selected math representation exactly once while retaining HTML fallback, and cover Table.text plus text_as_html for alttext-only, annotated, MathML-only, and unusable/HTML-only pairs.

  2. High — a direct <semantics> child is not necessarily a whole-expression representation (parser.py:713-732). In <math alttext="x+y"><semantics><mi>x</mi><annotation encoding="TeX">x</annotation></semantics><mo>+</mo><mi>y</mi></math>, the annotation describes only x, but _latex emits it for the entire root and suppresses the valid x+y fallback (and can authorize KaTeX visual removal). Require the selected semantics node to cover the root expression, including sibling-before/after and multiple-semantics cases. Also correct test_partition_html_prefers_math_alttext_over_tex_annotation (test_partition.py:1618-1640): its expected alttext contradicts both the implementation and PR description's annotation-first contract, so the checked-in test cannot pass as written.

  3. High — unusable display MathML still loses its block boundary inside KaTeX/phrasing wrappers (parser.py:646-664, 752-758, 785-788). If <math display="block"> has neither annotation nor alttext, its block emitter yields nothing; the retained .katex-html sibling is then ordinary phrasing, producing Beforex=1After instead of three elements. Preserve the Math node's explicit display intent when selecting the visual fallback, including adjacent display fallbacks and non-whitespace tails, while keeping inline fallback inline.

  4. Medium — span-wrapped display math loses page metadata (parser.py:365-376, 752-757). _page_number only recurses through a Flow parent, so the normal span-wrapped/KaTeX shape stops lookup before an enclosing data-page-number; the formula gets None while surrounding prose gets the page. This can also cause default page-grouped HTML export to skip the formula. Resolve the nearest valid page number through phrasing wrappers and add wrapped KaTeX/anchor/emphasis cases, including invalid nearer values falling back outward.

(authored by codex)

@fireblade2534

fireblade2534 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor Author

@cragwolfe Thanks for the follow-up review. I agree that #2 is a correctness issue in the MathML representation-selection logic added by this PR, and I’ll address that by only treating a <semantics> annotation as authoritative when it represents the whole <math> expression.

For #1, #3, and #4, though, I think we are expanding beyond the intended scope of this PR.

The goal of this change is to add basic MathML/KaTeX support to a parser that previously had no MathML-specific handling at all. Previously, <math> was not registered and fell through to the generic unknown-element behavior, so MathML content was generally skipped or only happened to be recovered indirectly through surrounding KaTeX HTML.

For #1, TableBlock has an independent extraction path based on raw td.itertext() and does not use the parser's Flow/Phrasing traversal. Making table cells understand MathML representation selection, annotations, alttext, and fallback semantics would require changing table parsing itself. I agree that the new KaTeX normalization should not make existing table behavior worse, so I can avoid pruning the visual KaTeX branch inside tables. That preserves the existing table behavior without turning this PR into a table-parser refactor.

For #3, preserving display="block" when MathML is unusable would require associating the failed <math> node with a separate .katex-html sibling and transferring the Math node's layout semantics onto that phrasing element. There is currently no parser abstraction for transferring block/inline semantics between alternate DOM representations. That seems like a broader fallback/layout feature rather than a correctness fix to the basic MathML extraction introduced here.

For #4, page-number inheritance currently only walks through Flow parents. That behavior predates this PR and is not specific to MathML. Changing it to walk transparently through spans, anchors, emphasis, invalid nearer page values, etc. changes generic metadata inheritance behavior across the parser and should be handled separately.

I’d prefer to keep this PR bounded to introducing basic MathML support and fixing regressions directly caused by that implementation. Otherwise this is effectively growing from basic MathML extraction into a much broader MathML/KaTeX parser integration, including tables, fallback layout propagation, and generic metadata ancestry.

@fireblade2534

Copy link
Copy Markdown
Contributor Author

@cragwolfe any updates

@cragwolfe

Copy link
Copy Markdown
Contributor

Thanks for the thoughtful scope breakdown and the updates at 89be3beaa578b8e83a3ce6e749752554590cff63. I rechecked the current head. The whole-expression annotation selection is fixed, and the table guard is sufficient to avoid regressing existing table extraction. I also agree that carrying display semantics onto an unusable MathML visual fallback can be handled separately.

There is one narrow blocker remaining. In the normal div[data-page-number] > span.katex > span.katex-mathml > math[display=block] structure, this change prunes the visual branch and emits a separate Math element, but page-number lookup stops at the immediate phrasing wrapper. The emitted formula therefore receives page_number=None; default page-grouped elements_to_html() skips elements without a page number, so the formula can disappear from that output. Although the generic ancestry limitation predates this PR, the content loss becomes newly observable when this PR replaces the former page-bearing visual representation.

Please add a narrowly scoped page-number ancestor lookup for Math through phrasing wrappers, plus a regression using the normal span-wrapped KaTeX structure and page-grouped HTML export. This does not require changing generic metadata ancestry. With that focused fix, the content changes otherwise look ready from my review.

(authored by codex)

@fireblade2534

Copy link
Copy Markdown
Contributor Author

@cragwolfe Done

@fireblade2534

Copy link
Copy Markdown
Contributor Author

@cragwolfe

@fireblade2534

Copy link
Copy Markdown
Contributor Author

@cragwolfe any updates?

@cragwolfe
cragwolfe merged commit 347fbbf into Unstructured-IO:main Oct 15, 2026
52 checks passed
huuufu added a commit to huuufu/unstructured that referenced this pull request Oct 15, 2026
Unstructured-IO#4478 registered `"math": Math`. This branch had registered
`"math": RemovedPhrasing` later in the same lookup dict, so after the
merge the later entry won: formulas were silently dropped, and for paired
KaTeX output outside a table `Math._normalize_katex()` read `._latex` on a
RemovedPhrasing instance and raised AttributeError, failing the whole
partition_html() call.

Remove this branch's mapping so `<math>` keeps the single Math
registration, and drop `<math>` from the RemovedPhrasing test cases and
the CHANGELOG list. Math still skips MathML that has no TeX annotation or
alttext while keeping its tail; that is now covered under Math, bare and
inside unrecognized wrappers.

Add combined coverage inside a newly transparent `<font>` or custom
element: each formula appears once (TeX annotation and paired KaTeX),
KaTeX HTML is kept when its MathML is unusable, and display math keeps
its element boundaries and page number.
cragwolfe pushed a commit that referenced this pull request Oct 15, 2026
### Summary

Fixes #4496. Resolves #3842 (#3708 was closed in its favor).

The v1 HTML parser gives every tag it has no class for a
`DefaultElement`, and `DefaultElement` emits only the element's tail:
its own text and everything inside it are dropped without a trace.
Before the parser rewrite in #3218 (0.15.0) the legacy parser listed
`font` in its `TEXT_TAGS`, so for `<font>` this is also a regression. In
practice this loses:

- `<font>`, still common in email HTML (Outlook and Gmail reply
headers).
- Inline XBRL, required in SEC 10-K/10-Q filings: `<ix:nonFraction>`
wraps the numbers inside sentences, and
`<ix:nonNumeric>`/`<ix:continuation>` wrap whole notes, tables included.
- Custom elements (`<my-card>`, the `<hauptteil_AB>` from #3708),
`<ins>`, `<nobr>`, `<ruby>`, `<picture>`.

Everything routed through `partition_html()` is affected: `.html`,
`.md`, `.eml`/`.msg` HTML bodies, `.epub`, `.rst`, `.org`.

Measured on the repo's fixtures. "Token coverage" is the share of word
tokens from a reference text, built from each fixture's own HTML, that
appear in the output; the reference approximates, but is not, what a
browser displays (method in **Testing**).

| fixture | elements, main → this PR | token coverage, main → this PR |
|---|---|---|
| `example-10k.html` (same for `-utf-16`) | 314 → 466 | 66.0% → 100.0%
of 27,619 tokens |
| `example-10k-1p.html` | 23 → 24 | 97.3% → 100.0% |
| `example-steelJIS-datasheet.html` (same for `-utf-16`) | 12 → 19 |
75.0% → 88.7% |
| `eml/email-no-utf8-2008-07-16.062410.eml`, HTML body | 2 → 22 | 31.5%
→ 93.8% |

On `main` the 10-K loses its cover-page values (form type, fiscal year
end, registrant name, shares outstanding) and all of Notes 1–14. The
email keeps two quoted paragraphs; the replies and their `From:`/`Sent:`
headers are inside `<font>`. The other 40 HTML-routed fixtures in
`example-docs` produce identical output.

### Change

`DefaultElement` drops its two overrides and inherits
`Phrasing.iter_text_segments()` and `Flow.iter_elements()`, so an
unrecognized element is transparent.

On the block-vs-inline question in #3842, no guess is needed. The
element keeps identifying as phrasing, which is how a browser renders an
unknown element (`display: inline`), and the parser already turns each
block nested inside phrasing into its own element, as for a `<p>` inside
a `<span>`. So `<font>` around two words joins the sentence, and
`<ix:nonNumeric>` around a note with headings and tables yields the same
elements as the note without the wrapper. Checked on the real filing:
`example-10k.html` with every `ix:` wrapper stripped (content kept)
partitions to the same 466 elements; 448 are identical, and the other 18
are tables whose text differs only in whitespace from `TableBlock` code
this PR doesn't touch. Text mixed with blocks
(`<x>before<p>para</p>after</x>`) and emphasis and link annotations come
out exactly as they do inside a `<span>`.

Elements whose content is not rendered as text now have to be skipped
explicitly. They are registered as `RemovedPhrasing`, which behaves
exactly like the old `DefaultElement`, so their output does not change:

- metadata: `head`, `title`, and legacy `xml` data islands (such as
Office document properties);
- fallback content: `object`, `iframe`, `audio`, `video`, `canvas`,
`noembed`, `noframes`;
- form-control internals: `select`, `datalist`, `textarea`;
- `dialog`, which is hidden until opened and on static pages is mostly
popup UI;
- `svg`, `math`, and Inline XBRL's hidden `ix:header` (facts, contexts
and units that filings put in a `display:none` `<div>`).

Each entry has a test that leaks text if the entry is removed. Judgment
calls:

- `math` stays skipped so this doesn't pre-empt #4478, which adds a
`Math` class. Whichever PR lands second deletes that line; ruff's F601
flags the duplicate key otherwise.
- `dialog` is skipped whether or not it has `open`, which keeps today's
output for both. An `open`-aware class would be a small follow-up if you
want open dialogs included.
- `embed`, `source` and `track` are left transparent: libxml2 nests the
*following* content inside these void elements (`<p>See <embed src=x>
for details.</p>` puts "for details." inside `<embed>`), so skipping
them would keep losing that text.
- Tags that are already registered (`button`, `label`, `details`, `dl`,
`figure`, `form`, `nav`, `template`, …) are untouched.

`Flow._page_number` now walks ancestors in a loop instead of recursing,
with the same result. `DefaultElement` is a `Flow`, so a block inside N
nested unknown elements now looks up N ancestors while the phrasing
traversal is itself about 2N frames deep; without this, a `<p>` inside
250 nested unknown elements raised `RecursionError`.

The v2 parser (`html_parser_version="v2"`) is not affected; it keeps
unknown-tag text as `UncategorizedText`.

### Before / after

```python
from unstructured.partition.html import partition_html

for html in [
    "<p><font face=Arial>Quarterly revenue</font> rose 12%.</p>",
    '<p>Revenue was $<ix:nonFraction name="us-gaap:Revenues">4,213</ix:nonFraction> million.</p>',
    "<my-card><h2>Pricing</h2><p>Plans start at $10.</p></my-card>",
]:
    print([str(e) for e in partition_html(text=html)])
```

Before:
```
['rose 12%.']
['Revenue was $ million.']
[]
```

After:
```
['Quarterly revenue rose 12%.']
['Revenue was $4,213 million.']
['Pricing', 'Plans start at $10.']
```

### Testing

- `test_parser.py`: the three `DescribeDefaultElement` tests that pinned
the old behavior now assert transparency. New tests cover blocks inside
`<foobar>`, `<ix:nonNumeric>` and nested `<my-card><font>` (same
elements and metadata as without the wrapper), text mixed with a block
(same as inside `<span>`), annotations, each newly skipped tag
(parametrized, including open and closed `<dialog>`, plus `head` via a
body-less document), and the page number of a block nested in 250
unknown elements.
- `test_partition.py`: end-to-end tests for `<font>` and for Inline XBRL
(inline fact, block `ix:nonNumeric` note with a table, `ix:header`
content that must not appear).
- Against `main`'s code, all 36 new or changed parser tests and both
end-to-end tests fail.
- `test_unstructured/partition/html/`: 402 passed, 1 failed on this
branch; 367 passed, 1 failed on `main`. The failure is the same test on
both, from my Windows checkout's CRLF fixtures.
- `ruff check .` and `ruff format --check` on the changed files pass.

<details>
<summary>Other suites compared on main and this branch</summary>

Compared test-by-test; every test present on both has the same outcome.

| suite | main | this branch |
|---|---|---|
| `test_md.py` / `test_email.py` | 39 / 72 passed | 39 / 72 passed |
| `test_msg.py` | 49 passed, 1 failed | 49 passed, 1 failed |
| `test_epub.py` + `test_rst.py` + `test_org.py` | 46 passed, 1 failed |
46 passed, 1 failed |
| `chunking/test_title.py` | 46 passed, 7 skipped | 46 passed, 7 skipped
|

The failures are the same tests on both sides and come from my
environment (missing image/PDF extras, CRLF fixtures).
</details>

<details>
<summary>How token coverage was measured</summary>

The reference is each fixture's HTML (for `.eml`, the HTML body
`partition_email()` uses) parsed with lxml's HTML parser, with `<head>`,
`<script>`, `<style>`, `<noscript>`, `<template>` and `hidden`/inline
`display:none` elements removed, split into `\w+` tokens. Coverage is
the share of reference tokens, counted as a multiset, found in the
concatenated element text. It does not apply stylesheets, so it is an
approximation of what a browser shows.

No fixture gains output tokens that aren't in the reference, and I read
every newly emitted element. Every token still missing on this branch
was already missing on `main`: one-character page numbers (skipped by
design), text in a few table cells, and an antivirus footer the email
places after `</html>`.
</details>

### Limitations and not verified

- `ix:header` is matched by its conventional `ix` prefix, because
libxml2's HTML parser has no namespaces. A filing that binds the Inline
XBRL namespace to another prefix would have its hidden header emitted.
The repo's filing fixture uses `ix`.
- Other XML vocabularies embedded in HTML, such as Confluence `ac:`
macros, now contribute their text like any unrecognized element. I have
no such fixture.
- As with `<span>`, adjacent unknown elements with no whitespace between
them are joined: `<x-a>foo</x-a><x-b>bar</x-b>` gives `foobar`, which is
also how a browser renders them.
- The `azure/spring-weather.html` ingest fixture, whose source isn't in
the repo; `test_auto.py` doesn't collect in my environment.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4497?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants