Skip to content

fix(html): extract <figure> content instead of discarding it - #4503

Open
r0h1tb wants to merge 7 commits into
Unstructured-IO:mainfrom
r0h1tb:fix/html-figure
Open

r0h1tb wants to merge 7 commits into
Unstructured-IO:mainfrom
r0h1tb:fix/html-figure

Conversation

@r0h1tb

@r0h1tb r0h1tb commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

partition_html() discards <figure> content, including images and captions. Keeping that content also exposed metadata problems: an inline wrapper could interrupt page-number inheritance, and a figure inside a list item ended that item, so a nested list after it lost its parent.

Fix

Traverse figures and emit caption text as FigureCaption, including text after an image in the caption, several caption paragraphs and nested wrappers. Headings, code, tables and images inside a caption keep their own types. Page numbers resolve through every ancestor, including phrasing wrappers.

Inside a list item, the figure's content is parented to that item (or to a heading that ended it), so the item stays on the hierarchy stack and the nested list after the figure keeps its parent. The item assigns the parent as the content passes through it in document order, so this also holds when the figure is inside <a>, <b> or another phrasing element, which is traversed before the item's own text becomes a ListItem. This is scoped to the HTML parser; the shared hierarchy rules are unchanged for list items.

The shared parts this PR used to carry are on main now through #4566: images, code and other non-text elements stay under the active heading, and page-grouped HTML export keeps children whose parent is on another page. This branch merges main and only adds figure cases to those tests.

Output changes

  • Figure content that was discarded is now in the default output, so deterministic element ids after a figure shift (sequence and page are hash inputs).
  • Figure content inside a list item is parented to that item.

Tests

The list-ancestry tests cover a direct figure, one inside <a>, and one inside <b><span>, each with and without a heading and in both id modes. They assert figure-leaf and nested-list parents, siblings and text after the list, nested export placement, and one exported tag per element id; a second test compares every non-figure parent with the same HTML without the figure. The 9 phrasing-wrapper cases that exercise the timing fail without the latest parser change.

HTML, metadata, chunking, documents, staging, md and docx tests: 1,400 passed before the latest change, 1,411 after, with the same 1 failure and 5 collection errors (optional extras not installed here). Ruff lint and format pass.

Resolves #3606.

Codex and Claude Code assisted with implementation and verification.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High — Figure content drops the active heading from hierarchy

Location: unstructured/partition/html/parser.py:1069-1071 (figure/figcaption registration), with traversal in :462-489.

The new traversal emits Image and CodeSnippet elements from figures, but the hierarchy rules allow neither category beneath Title or Header (unstructured/partition/common/metadata.py:58-82). set_element_hierarchy() pops incompatible stack entries (:142-167), so an image or code listing removes the active heading. For <h1>Section</h1><figure><img ...><figcaption>Diagram</figcaption></figure><p>After</p>, the image clears the heading; the caption and following paragraph then receive no section parent_id. The same occurs for a figure containing <pre>. This silently breaks heading-based section reconstruction for documents with figures.

Preserve the active heading across non-structural figure leaves (for example, make Image and CodeSnippet valid heading children or adjust stack handling). Add parent_id assertions for image and code figures, captions, following paragraphs, and a subsequent subsection.

High — Figure-derived elements can have missing or incorrect page numbers

Location: unstructured/partition/html/parser.py:475-489.

For the motivating anchor-wrapped image shape, ImageBlock reads its own _page_number (:552-577), but Flow._page_number only follows a parent when it is another Flow (:352-364). An <a> is phrasing, so an image inside <div data-page-number="7"><figure><a><img ...></a>... gets page_number=None, while the caption inherits page 7. The new single-<p> caption adoption path also builds the FigureCaption from the <figcaption> accumulator without applying the child block's page number; a child <p data-page-number="8"> is therefore assigned the outer page 7. ListItemBlock handles this same adoption case by copying child._page_number (:527-531).

Walk all ancestors when resolving page metadata, and copy the adopted child block's page number onto the emitted caption. Add focused assertions for an anchor-wrapped image and a wrapped caption whose page overrides its container. Incorrect page metadata also changes deterministic element IDs because page number and per-page sequence are hash inputs (unstructured/partition/common/metadata.py:306-327).

(authored by codex)

r0h1tb added 2 commits October 5, 2026 20:35
<figure> was mapped to RemovedBlock, so partition_html() dropped every
figure along with its image and caption, including every Wikipedia
thumbnail.

Traverse a figure like a <div>, so its <img> becomes an Image element
and a code listing or table inside it is kept, and give <figcaption>
its own block class that emits a FigureCaption, including when the
caption is wrapped in a single <p>. Figure is a distinct class so a list
item does not adopt one as a plain paragraph.

Two parser tests used <figure> as their example of a removed block and
now use <nav> instead.
An Image or CodeSnippet from a figure was not a valid child of Title or
Header in HIERARCHY_RULE_SET, so set_element_hierarchy() popped the
active heading: the caption and everything after it lost their section
parent_id. Allow both under Title and Header.

Flow._page_number stopped at the first non-Flow parent, so an image
inside an <a> got no page number. Walk every ancestor instead. A caption
adopted from a sole <p> in <figcaption> now takes that <p>'s page, as
ListItemBlock already does.
@r0h1tb

r0h1tb commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Both fixed in 5036f11.

  • Hierarchy: Image and CodeSnippet are now valid children of Title and Header in HIERARCHY_RULE_SET, so an image or code listing no longer pops the heading. That list is shared, so it applies to the other partitioners too. I checked the stored ingest outputs and none of them change. The tests check parent_id for image and code figures, the caption, the paragraph after, and a following subsection.
  • Page numbers: Flow._page_number now walks every ancestor, so the <a>-wrapped image gets page 7, and the adopted <p> caption keeps its own page 8, same as ListItemBlock.

Also rebased on main, now 0.27.19. #4451 bumps to the same version, so whichever goes in second needs it moved.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed exact head 5036f11667b0285141e5f2e508e7394961378949 against merge-base f4105db674e4bf6c98ddb8fe6a5e32df0d7237b4 with Oracle GPT-6 Pro, confirmed from server-side generation metadata and Pro during streaming. The earlier hierarchy and page-number findings are fixed. One verified High correctness regression remains: the shared hierarchy change causes page-grouped HTML export to omit cross-page code/images and following content. Details and acceptance criteria are in the inline comment.

Scope covered figure/caption traversal, shared hierarchy consumers, page metadata and IDs, serialization, HTML export, chunking, and checked-in tests. Exact-head CI has 51 successful and two neutral checks, with no failures, from October 5; no local tests were run. Current merge conflicts are limited to CHANGELOG.md and unstructured/__version__.py. The export regression and release metadata conflicts need resolution, followed by fresh CI and review of the updated head.

(authored by codex)

Comment on lines +69 to +70
"Image",
"CodeSnippet",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1 / High] Preserve cross-page children in page-grouped HTML export

Allowing Image and CodeSnippet under headings fixes the original hierarchy issue, but it also changes existing non-figure content. For example:

<div data-page-number="1"><h1>Section</h1></div>
<div data-page-number="2"><pre>x = 1</pre><p>Following paragraph.</p></div>

The code and following paragraph now have page 2 metadata and parent_id pointing to the page 1 title. Default elements_to_html() groups elements by page before building the parent tree (unstructured/partition/html/convert.py:293-303). In the page 2 group, _elements_to_html_tags_by_parent() cannot find that title, skips attaching its children, and returns only elements with parent_id is None (:263-277). Both elements are therefore omitted. Before this change, the code cleared the heading stack, so it and the following paragraph were page 2 roots and remained in export. The new Header rules and image path have the same problem.

Keep the hierarchy fix, but make export retain elements whose parent is outside the current page group, for example by treating them as roots within that group. Add a regression through partition_html() and default elements_to_html() for a page 1 heading followed by page 2 code/image and text, including figure captions. Use a retained base64 payload for the image case to isolate omission from the existing URL-rendering limitation. Assert that each page 2 element appears exactly once, with correct page metadata and preserved cross-page parent_id; also retain same-page nesting behavior and do not mutate source metadata during export.

(authored by codex)

@r0h1tb

r0h1tb commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the cross-page export loss and incorporated current main. When a parent is outside the page being exported, its children now render as roots on that page while keeping their original parent_id and page metadata.

The six new cases cover code and images, with and without figure captions, plus Header parents. They check exact-once output, same-page nesting and unchanged metadata. All 493 HTML and metadata tests pass; withdrawing the exporter fix restores all six failures. The full run adds six passes with the same baseline failures and collection errors, detailed in the PR description.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 34ecc74ae9294315c21c8c395f5d7885f8e4ef4b against current main 3253c2b0f6b0a5f0808910c085675672aff718f3 with GPT Pro. The prior High cross-page HTML export omission is fixed: children whose parent is on another page are retained without clearing their source metadata. The six new regression cases meaningfully cover code/images, captions, Title/Header parents, exact-once output, page placement, and metadata preservation.

No remaining High or Critical defect was found. Two verified Medium correctness issues remain, described inline: figure content can discard enclosing list ancestry, and some caption text loses its FigureCaption category. This is a nonblocking comment review.

The head incorporates current main and PR #4497; the version and changelog agree on 0.27.29, and GitHub reports no merge conflicts. CI readiness is still blocked: CI, benchmark, CodeQL, and Security report action_required, with no jobs created. Only the two Socket checks and the external code-review check have succeeded. The required changelog, Dockerfile, lint, unit, and ingest checks have no passing execution evidence at this head. Please approve the workflow runs and await the required checks. No local tests were run.

(authored by codex)

"dt": BlockItem,
"li": ListItemBlock,
# -- image --
"figure": Figure,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2 / Medium] Preserve enclosing list ancestry when retaining a figure

Consider:

<h1>Guide</h1>
<ul><li>Outer step
  <figure><img src="/diagram.png" alt="Diagram"><figcaption>Caption</figcaption></figure>
  <ul><li>Inner step</li></ul>
</li></ul>

On main, the skipped figure leaves consecutive ListItem elements at depths 1 and 2, so Inner step has Outer step as its parent. With this registration, the emitted image reaches set_element_hierarchy() while Outer step is on the stack. ListItem has no mixed-category child rule, so the image pops it. The caption does not restore it, and Inner step receives the heading as parent (or becomes a root without a heading). HTML export consequently renders the inner list outside the outer item.

Preserve the enclosing list context through figure traversal, using parser-scoped parent relationships or an equivalent scoped hierarchy change. Handle captions and image/code/table content together; accepting just images/code under list items leaves captions able to clear the stack. Add a regression with and without a heading that checks the inner item's parent_id, nested export placement, exact-once figure content, and correct scope for subsequent siblings and text outside the list.

(authored by codex)

Comment thread unstructured/partition/html/parser.py Outdated
yield element
return

yield from super().iter_elements()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2 / Medium] Keep caption typing across images and multiple text blocks

The fallback to Flow.iter_elements() does not carry the caption class through block children and their tails. For <figcaption><img src="/icon.png" alt="">Diagram legend</figcaption>, the single-child adoption rejects ImageBlock; normal traversal emits the image and processes its tail at parser.py:393 without FigureCaption, so the legend receives an ordinary text category. Likewise, <figcaption><p>First caption paragraph.</p><p>Second caption paragraph.</p></figcaption> bypasses the single-wrapper case and emits ordinary text paragraphs. Consumers that select FigureCaption therefore miss these captions even though their text remains in the element stream.

Use caption-scoped traversal that retains FigureCaption for textual wrappers and tails while preserving specialized image, code, table, and heading element types. Add assertions for a leading image inside the caption, multiple caption paragraphs, nested text wrappers, link/emphasis metadata, page overrides, and ordinary text after </figcaption>.

(authored by codex)

kerthans added a commit to kerthans/unstructured that referenced this pull request Oct 22, 2026
Keeping the section heading across non-text elements means page-two
content can have a page-one parent. elements_to_html() groups elements by
page, could not find that parent in the page-two group, and returned only
elements without a parent_id, so the code, the paragraphs after it and
any subsection were dropped from the export.

An element whose parent is not in its page group is now a root of that
group. Element metadata is unchanged.

This is the exporter fix from Unstructured-IO#4503.

Co-authored-by: Rohit Behera <[email protected]>
Signed-off-by: kerthans <[email protected]>
Co-authored-by: Cursor <[email protected]>
…a FigureCaption

An image or caption in a list item ended the item for set_element_hierarchy(),
so a nested list after the figure lost its parent. The figure's content is now
parented to the list item it is in (or to a title that ended it), and so no
longer clears the item from the hierarchy stack.

Text in a <figcaption> that came after an image, or sat in more than one block
or a nested wrapper, was typed from its text instead of as FigureCaption. Any
text in a caption without a more specific element class is now a FigureCaption.
@r0h1tb

r0h1tb commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

Both Medium findings are fixed in 0af9568, on top of a merge of current main.

  • List ancestry: a figure inside a list item now parents its content to that item, or to a heading inside the item that ended it, so set_element_hierarchy() skips the content and the item stays on the stack. Images, code, tables and captions are handled together. A test compares every non-figure parent with the same HTML minus the figure, for a nested item, an item with no text of its own, and a heading inside the item.
  • Captions: text in a <figcaption> with no more specific element class is a FigureCaption, including text after an image, several paragraphs and nested wrappers, with page overrides and link/emphasis metadata kept. Headings, code, tables and images in a caption keep their types, and text after </figcaption> is ordinary text.

The merge also drops the CHANGELOG.md entry and version bump, per the frozen-changelog change.

@cragwolfe cragwolfe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 0af9568d1b9a1fb0723f18fb440eee224a3a6e1e against base c74e6c4c50e58c49778a458745d06c248add2db3 with GPT Pro. The earlier heading, page-inheritance, cross-page export, and caption-typing findings are repaired. One narrower Medium list-ancestry issue remains.

[P2] Preserve the list owner when a figure is inside a link — unstructured/partition/html/parser.py:507–517, with :582–593 and :972.

For <ul><li>Outer step<a href="/detail"><figure><img src="/d.png" alt="Diagram"><figcaption>Caption.</figcaption></figure></a><ul><li>Inner step</li></ul></li></ul>, the anchor eagerly builds its deque of descendant elements while “Outer step” is still buffered. Figure.iter_elements() therefore reads _figure_parent_id before the list item has recorded it and takes the unparented fallback. The later image/caption pop the outer list item in the final hierarchy pass; “Inner step” becomes a root, or a child of the preceding heading, and export places it outside the outer item. The direct-child regression cases do not cover this timing path.

Establish or preserve the list owner through the phrasing-wrapper path before traversing the figure. Add the enclosing-link case with and without a heading and in both ID modes; assert figure-leaf and nested-list parents, unaffected siblings/outside text, and exactly one exported tag per element ID. This finding is verified by source tracing; no local reproduction was run.

Maintainer output-compatibility decision: this patch retains previously discarded figure content by default, changes later deterministic IDs through element sequence/page metadata, and changes default Image/CodeSnippet heading relationships for shared hierarchy callers beyond HTML figures. Please explicitly accept those output and persisted-reference implications. No approval is submitted pending that decision and the remaining finding.

#4451 remains open and is not a prerequisite for this PR’s implemented scope. It does not supply behavior to this review. Combining the branches requires preserving its paired parser/helper signature change and reviewing disclosure/figure composition on the combined head.

All 51 reported exact-head checks and CI, benchmark, CodeQL, and Security workflows succeeded at observation; integration readiness remains separate. No local tests were run. uv.lock and CHANGELOG.md were excluded from context; release-managed files match current main.

(authored by codex)

chuenchen309 pushed a commit to chuenchen309/unstructured that referenced this pull request Nov 14, 2026
…t elements (Unstructured-IO#4566)

## Root cause
`set_element_hierarchy()` walks a parent stack and pops every entry that
is not a valid parent of the current element. `HIERARCHY_RULE_SET` only
lists text-like children for `Title` and `Header`, so an element whose
category is in no rule (`Image`, `PageBreak`, `Formula`, `CodeSnippet`,
`Address`, `EmailAddress`, `PageNumber`, `Footer`) popped the whole
stack, including the section heading, and was then pushed itself. Every
following element in the same section got `parent_id=None`.

```python
partition_md(text="# Intro\n\nFirst paragraph.\n\n![alt](x.png)\n\nSecond paragraph.")
# before: Image.parent_id is None, "Second paragraph".parent_id is None
# after:  both point to the "Intro" Title
```

## Change
- Add the eight types above as children of `Title` and `Header` in
`HIERARCHY_RULE_SET`.
- Remove the duplicated `"Table"` entry from both lists.
- With this, `[Title, NarrativeText, Image, NarrativeText]` resolves as
follows: the Image becomes a child of the Title, the next NarrativeText
pops the Image (not a valid parent) and attaches to the Title.

## Related
Open PR Unstructured-IO#4503 (HTML `<figure>` handling) also adds `"Image"` and
`"CodeSnippet"` to the same rule lists, so whichever lands second will
need a small rebase.

## Tests
- New `Describe_set_element_hierarchy` tests: Image and PageBreak
between paragraphs under a `Title`, and an Image under a `Header`. They
fail before the change and pass after it.
-
`test_unstructured/partition/{common,html,test_md.py,test_docx.py,...}`,
`chunking`, `documents` and `staging` pass locally. Ingest expected
outputs exclude `metadata.parent_id`, so no fixtures change.

## Behavior change
- Elements of these eight types that follow a `Title`/`Header` now get
that heading as `parent_id` (previously `None`).
- Elements after them in the same section keep the heading as
`parent_id` instead of `None`.
- `Footer` and `PageNumber` are now also parented to the preceding
heading. They are page furniture, so this is arguably less meaningful,
but it stops them from breaking the hierarchy of the content that
follows.

AI assistance was used to prepare this change; I reviewed and tested it.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4566?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="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->

---------

Signed-off-by: kerthans <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Rohit Behera <[email protected]>
Co-authored-by: cragwolfe <[email protected]>
…side phrasing

A figure inside `<a>`, `<b>` or another phrasing element is traversed
before the list item's own text is flushed into its `ListItem`, so the
figure found no owner and took the unparented path. Its image and
caption then ended the list item in `set_element_hierarchy()`, and a
nested list after the figure lost its parent.

The figure now hands its unparented content to the enclosing list
items, and each item parents it as the content passes through in
document order.

Signed-off-by: Rohit Behera <[email protected]>
@r0h1tb

r0h1tb commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Fixed on top of a merge of current main.

  • Link-wrapped figure: the list item now parents figure content as it passes through, in document order, so it no longer depends on whether the item's ListItem exists when the figure is traversed. <b> and <span> wrappers had the same timing problem and are covered too. The tests add the wrapped cases with and without a heading and in both id modes, and assert one exported tag per element id.
  • fix(partition): keep section parent_id after images and other non-text elements #4566 landed the Image/CodeSnippet heading rules and the cross-page export repair on main, so the merge takes main's versions and the shared-hierarchy question is settled there. The output changes left in this PR are listed in the description: figure content is kept (which shifts deterministic ids after it), and figure content in a list item is parented to that item.

This branch has not been deployed

No deployments
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.

feat: capture images/figures

2 participants