bug/html-table-caption-dropped: partition_html drops the <caption> of a table
Describe the bug
partition_html() drops the <caption> of a <table>. The caption text isn't in the Table element's text or in metadata.text_as_html, and it doesn't come out as a separate element either, so the table's title is just gone. HTML email bodies go through the same path, so partition_email() loses it too.
TableBlock.iter_elements() in unstructured/partition/html/parser.py only looks at tr, thead, tbody and tfoot children of the table, so the caption child is skipped.
To Reproduce
from unstructured.partition.html import partition_html
html = (
"<table><caption>Quarterly revenue by region</caption>"
"<tr><th>Region</th><th>Q1</th></tr>"
"<tr><td>EMEA</td><td>4.2</td></tr></table>"
)
for e in partition_html(text=html):
print(e.category, repr(e.text), e.metadata.text_as_html)
Output on main (0b7f806):
Table 'Region Q1 EMEA 4.2' <table><tr><th>Region</th><th>Q1</th></tr><tr><td>EMEA</td><td>4.2</td></tr></table>
Expected behavior
The caption should be kept with the table. What I'd suggest:
text_as_htmlgets the caption as the first child, sanitized the same way cells are (escaped text, no attributes):<table><caption>Quarterly revenue by region</caption><tr>...Table.textstarts with the caption text:Quarterly revenue by region Region Q1 EMEA 4.2
That way anything reading the table (an LLM given text_as_html, or search over text) still knows what the table is, and the number and type of elements don't change for anyone already partitioning HTML tables. Emitting the caption as its own FigureCaption element before the table would also work, but it changes element counts, so keeping it inside the table seemed like the smaller change.
A table with only a caption and no cell text would still produce no element, same as an empty table today.
Environment Info
scripts/collect_env.py fails here with ModuleNotFoundError: No module named 'pkg_resources', so by hand: unstructured 0.27.27-dev3 (main at 0b7f806), Python 3.11.17, Linux x86_64.
Additional context
#2611 tried to add caption support in 2024 but went stale before the HTML parser rewrite, so it doesn't apply anymore.
I'll open a PR for this shortly unless you'd prefer the separate-element approach.