Skip to content

fix: preserve numeric text in table HTML metadata - #4373

Open
gyx09212214-prog wants to merge 5 commits into
Unstructured-IO:mainfrom
gyx09212214-prog:gyx09212214-prog/preserve-html-table-number-text
Open

gyx09212214-prog wants to merge 5 commits into
Unstructured-IO:mainfrom
gyx09212214-prog:gyx09212214-prog/preserve-html-table-number-text

Conversation

@gyx09212214-prog

@gyx09212214-prog gyx09212214-prog commented Jun 12, 2026 •

Copy link
Copy Markdown

Summary

Refs #3871.

This updates table HTML generation so delimited table partitioners preserve numeric-looking cell text in metadata.text_as_html instead of letting pandas serialize numeric columns through DataFrame.to_html().

Changes:

  • read CSV and TSV data as strings with default NA coercion disabled, preserving source lexemes such as 478923, 000001, 000123, 007, 0.000123, and very large integer-like values
  • render CSV/TSV table HTML through a shared htmlify_dataframe() helper backed by htmlify_matrix_of_cell_texts(), avoiding pandas float/scientific-notation formatting
  • preserve dataframe null values as empty table cells instead of serializing them as nan, None, or <NA> text
  • add regression coverage for CSV and TSV metadata.text_as_html, including TSV file-like input and explicit leading-zero identifiers
  • keep the existing partition_html(..., chunking_strategy="by_title") regression guard for numeric table cells, now including explicit leading-zero values

Notes

I still could not reproduce the scientific-notation conversion through current partition_html() alone with a minimal HTML table fixture. I confirmed the current HTML table partition path does not do an HTML -> DataFrame -> to_html() round-trip: TableBlock.iter_elements() builds table data directly from DOM cell text and renders it through htmlify_matrix_of_cell_texts().

The reproducible lossy path is the DataFrame-backed CSV/TSV table serialization path, which matches the pandas to_html() failure mode discussed in #3871.

Testing

python -m pytest -q test_unstructured\common\test_html_table.py test_unstructured\partition\test_csv.py test_unstructured\partition\test_tsv.py
python -m ruff check unstructured\common\html_table.py unstructured\partition\csv.py unstructured\partition\tsv.py test_unstructured\common\test_html_table.py test_unstructured\partition\test_csv.py test_unstructured\partition\test_tsv.py test_unstructured\partition\html\test_partition.py
python -m ruff format --check unstructured\common\html_table.py unstructured\partition\csv.py unstructured\partition\tsv.py test_unstructured\common\test_html_table.py test_unstructured\partition\test_csv.py test_unstructured\partition\test_tsv.py test_unstructured\partition\html\test_partition.py
git diff --check

@cubic-dev-ai cubic-dev-ai Bot 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.

No issues found across 1 file

Shadow auto-approve: would auto-approve. Adds test coverage for numeric table cell text preservation in HTML partitioning. No source code or business logic changes—only a new test fixture and assertions.

Re-trigger cubic

@gyx09212214-prog gyx09212214-prog changed the title test: guard HTML table numeric cell text fix: preserve numeric text in table HTML metadata Jun 19, 2026

@cubic-dev-ai cubic-dev-ai Bot 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.

2 issues found across 4 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="unstructured/partition/tsv.py">

<violation number="1" location="unstructured/partition/tsv.py:59">
P2: Custom agent: **Enforce Pragmatic Test Coverage**

Change to TSV partition core logic lacks test coverage</violation>
</file>

Shadow auto-approve: would not auto-approve because issues were found.

Re-trigger cubic

Comment thread unstructured/partition/tsv.py Outdated
html_table = HtmlTable.from_html_text(
dataframe.to_html(index=False, header=include_header, na_rep="")
)
html_table = HtmlTable.from_html_text(_dataframe_to_html_text(dataframe, include_header))

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: Custom agent: Enforce Pragmatic Test Coverage

Change to TSV partition core logic lacks test coverage

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At unstructured/partition/tsv.py, line 59:

<comment>Change to TSV partition core logic lacks test coverage</comment>

<file context>
@@ -41,18 +41,22 @@ def partition_tsv(
-    html_table = HtmlTable.from_html_text(
-        dataframe.to_html(index=False, header=include_header, na_rep="")
-    )
+    html_table = HtmlTable.from_html_text(_dataframe_to_html_text(dataframe, include_header))
 
     metadata = ElementMetadata(
</file context>

Comment thread unstructured/partition/csv.py Resolved

@cubic-dev-ai cubic-dev-ai Bot 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.

1 issue found across 5 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="unstructured/partition/tsv.py">

<violation number="1" location="unstructured/partition/tsv.py:59">
P2: Custom agent: **Enforce Pragmatic Test Coverage**

Change to TSV partition core logic lacks test coverage</violation>
</file>

Shadow auto-approve: would not auto-approve because issues were found.
Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread unstructured/common/html_table.py Resolved

@cubic-dev-ai cubic-dev-ai Bot 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.

0 issues found across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve. Auto-approval blocked by 1 unresolved issue from previous reviews.

Re-trigger cubic

@zeweihan

Copy link
Copy Markdown

Great direction — this is exactly the "carry the source lexeme as a string through the round-trip" fix that #3871 was missing, and reading CSV/TSV with NA coercion disabled so 478923 / 000001 / 0.000123 survive is the right call.

A couple of notes from ingesting a lot of structured-but-regulated documents, in case they're useful:

Leading zeros are a silent reference-breakage case, not just cosmetic. The 000001 example is more dangerous than it looks: account numbers, bond/CUSIP-like identifiers, statute section numbers, and clause IDs routinely carry leading zeros. Once a column is inferred as int64, 000001 becomes 1 with no metadata flag, and every downstream "find Section 0001" / "match account 00012345" retrieval query silently misses. It's worth adding an explicit leading-zero fixture to the regression suite ("000123", "007") so a future dtype-inference refactor can't silently regress it — the current string-everywhere approach fixes it, but it's the exact class of bug that creeps back when someone later re-enables pd.read_csv(..., dtype=...) inference for performance.

The HTML-backed table path is the one I'd most want covered. You noted you couldn't reproduce the lossy conversion through partition_html() alone with a minimal fixture. The dangerous real-world case for legal/financial PDFs isn't a hand-authored HTML table though — it's an HTML table that an OCR/layout model synthesized from a PDF page and handed to the partitioner, which then gets materialized through a DataFrame before text_as_html is rendered. If that path still goes HTML → DataFrame (dtype inference) → to_html(), the coercion can reappear even though the CSV/TSV path is now fixed. Worth confirming whether htmlify_dataframe() / htmlify_matrix_of_cell_texts() is the single funnel for all table-HTML emission (CSV, TSV, and the HTML partition path), or whether the HTML partitioner still has its own DataFrame round-trip. If it's the latter, the same to_html() failure mode is still reachable.

Null-as-empty-cell is correct, but there's a semantic trap worth a comment in the code. Rendering nulls as empty <td></td> is unambiguously better than literal nan / None / <NA> text leaking into the corpus. The one caveat: in regulatory/fee-schedule tables, an intentionally-blank cell usually means "not applicable" or "no penalty" rather than "missing/unknown". An empty string can't distinguish those, but that's acceptable — the important thing is the consumer sees empty (a parseable signal) instead of garbage tokens that look like content. If there's ever appetite, a separate cell_metadata with {was_null: true} would let a downstream consumer treat blanks as data-absent vs. value-absent, but empty-cell-first is the right default.

Thanks for picking this up — the Refs #3871 + string-everywhere approach is the clean fix.

@cubic-dev-ai cubic-dev-ai Bot 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.

0 issues found across 5 files (changes from recent commits).

Shadow auto-approve: would not auto-approve. Auto-approval blocked by 1 unresolved issue from previous reviews.

Re-trigger cubic

Copy link
Copy Markdown
Author

Thanks for the review and the additional context here.

I’ve incorporated the feedback and tightened the PR around the original data-integrity issue:

  • CSV/TSV inputs are now read with source lexemes preserved as strings, with default NA coercion disabled, so values like 478923, 000001, 000123, 007, 0.000123, and very large integer-like identifiers survive into metadata.text_as_html unchanged.
  • CSV/TSV table HTML generation now goes through a shared htmlify_dataframe() helper backed by htmlify_matrix_of_cell_texts(), avoiding pandas DataFrame.to_html() numeric formatting and scientific notation.
  • Pandas null values are rendered as empty table cells instead of leaking nan, None, or <NA> tokens into the table text, with regression coverage for that behavior.
  • I added explicit leading-zero fixtures across the shared renderer, CSV, TSV filename/file-like paths, and the existing partition_html(..., chunking_strategy="by_title") regression guard.
  • I also confirmed the current partition_html table path does not do an HTML -> DataFrame -> to_html() round-trip; it builds table data directly from DOM cell text and renders through htmlify_matrix_of_cell_texts().

Validation run locally:

python -m pytest -q test_unstructured\common\test_html_table.py test_unstructured\partition\test_csv.py test_unstructured\partition\test_tsv.py
python -m ruff check unstructured\common\html_table.py unstructured\partition\csv.py unstructured\partition\tsv.py test_unstructured\common\test_html_table.py test_unstructured\partition\test_csv.py test_unstructured\partition\test_tsv.py test_unstructured\partition\html\test_partition.py
python -m ruff format --check unstructured\common\html_table.py unstructured\partition\csv.py unstructured\partition\tsv.py test_unstructured\common\test_html_table.py test_unstructured\partition\test_csv.py test_unstructured\partition\test_tsv.py test_unstructured\partition\html\test_partition.py
git diff --check

The remaining Cubic blocker appears to be an outdated unresolved TSV coverage thread from an earlier review; the TSV regression coverage has since been added and the latest review reported no new issues. If this scope looks good to maintainers, I’d appreciate another review and merge when convenient.

cragwolfe pushed a commit that referenced this pull request Oct 23, 2026
)

**Summary**

`partition_tsv()` silently ignores `infer_table_structure=False`, so
callers still receive `Table.metadata.text_as_html`. The flag is passed
through by `partition()` but absorbed by `**kwargs` in the TSV
partitioner.

The fix adds the explicit parameter with the same default (`True`) as
the other table partitioners, and sets HTML metadata only when enabled.
Tests cover both flag values through `partition_tsv()` and
`partition()`.

Disabling HTML sends the whole flattened table through the shared text
splitter, which exposed latent progress and work-bound defects in that
path. The branch therefore also carries the bounded-split fixes already
discussed on this PR: a prefix wholly covered by overlap advances, the
token window and fallback scans are bounded, the vocabulary bound is
shared across HTML cells, the unread suffix is not re-encoded on every
split, and a fitting input is not rejected because an earlier prefix
overflowed.

**This revision (`f256ed23`)**

Both findings from the latest review:

- **Preferred-separator search:** candidates inside one whitespace run
all trim to the same fragment and lstrip to the same remainder. The run
is now evaluated once and the remaining matches inside it are skipped,
so `"a" + " " * 100_000 + "print(1)"` measures one candidate instead of
100,000. Covered for spaces, newlines, mixed whitespace and a configured
tab separator.
- **Fallback overlap:** `split_pos > len(fragment)` records that the cut
trimmed a trailing whitespace run. That is now combined with
`is_whitespace_split`, so the overlap tail gets a separating space when
either side of the cut had whitespace. The corrupted `"aprint(1)"`
expectation is replaced by `"a print(1)"`; an unbroken-word test still
forbids an artificial space when the cut had no whitespace.

**Test**

- `pytest test_unstructured/chunking
test_unstructured/partition/test_tsv.py -q` → `719 passed, 2 skipped in
12.76s`
- `ruff check` and `ruff format --check` on the two changed files →
clean
- `git diff --check` → clean

Not run: the full partitioner/extras suites and cross-platform tests. CI
is now running on this head; no green check is claimed yet.

**Type of change:** bug fix; no new dependency. Related #4373 changes
numeric HTML generation, and #3870 fixed a duplicate auto-dispatch
kwarg; neither addresses this ignored TSV flag.
cragwolfe pushed a commit that referenced this pull request Oct 24, 2026
…4505)

## Problem

`partition_xlsx()` reads each worksheet with `pd.read_excel()` and the pandas default NA strings, so a cell whose text is `N/A`, `NA`, `null`, `None`, `NaN`, `#N/A` or similar is read as missing and comes out empty. The missing cells also change how the worksheet is split into subtables, so a whole table can fall apart:

```python
import io, openpyxl
from unstructured.partition.xlsx import partition_xlsx

wb = openpyxl.Workbook()
for row in (["Item", "Status"], ["Pear", "N/A"], ["Fig", "NA"], ["Plum", "null"], ["Kiwi", "None"]):
    wb.active.append(row)
f = io.BytesIO()
wb.save(f)

[(type(e).__name__, e.text) for e in partition_xlsx(file=f)]
# before: [('Table', 'Item Status'), ('Title', 'Pear'), ('Title', 'Fig'), ('Title', 'Plum'), ('Title', 'Kiwi')]
# after:  [('Table', 'Item Status Pear N/A Fig NA Plum null Kiwi None')]
```

## Fix

Worksheets are read with `keep_default_na=False, na_values=[""]`, so only empty cells are missing. Empty cells still come back as NaN, which keeps subtable detection and the empty cells in `text_as_html` unchanged (`test_partition_xlsx_subtables` covers the splitting). None of the XLSX files in `example-docs` contain NA-like text, so their outputs do not change.

#4373 makes the equivalent change for CSV and TSV; this PR only touches the XLSX reader.

## Testing

`pytest test_unstructured/partition/test_xlsx.py`, including a new regression test built from the example above.


<!-- This is an auto-generated description by cubic. -->
<a href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4505?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. -->
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 24, 2026
…, not a literal \n (Unstructured-IO#4592)

## Summary

`partition_csv()` and `partition_tsv()` build the table with
`DataFrame.to_html()`. By default pandas writes a line break or tab
inside a cell as its escape sequence, so a quoted field that spans lines
(RFC 4180 §2.6 allows this) reaches `Table.text` and
`metadata.text_as_html` with literal backslashes:

```python
import io
from unstructured.partition.csv import partition_csv

data = b'name,address\r\nAlice,"1 Main St\r\nSpringfield"\r\n'
partition_csv(file=io.BytesIO(data), include_header=True)[0].text
# main:         'name address Alice 1 Main St\\r\\nSpringfield'
# this branch:  'name address Alice 1 Main St Springfield'
```

`pd.read_csv()` parses the field correctly; the backslashes appear only
at `to_html()`. A TSV cell with a quoted newline gives `'line one\\nline
two'` the same way.

A small `dataframe_to_html()` helper in `csv.py`, used by both
partitioners, passes a formatter for each column so pandas writes the
cell text itself. HTML escaping is unchanged (`x<y & z` becomes `x&lt;y
&amp; z`) and empty cells stay empty. `HtmlTable` then folds the real
line break into a space, as it does with other whitespace in a cell, so
`text_as_html` doesn't keep the break as a `<br>`. If you'd rather keep
it, we can change that here.

Related: open Unstructured-IO#4373 (from June, now conflicting) replaces the same
`to_html()` call with its own HTML builder, which would also avoid this;
this PR is the smaller change on current `main`. Neighbours: Unstructured-IO#4574
(cells read as text) and Unstructured-IO#4376 / Unstructured-IO#4279 (row boundaries in
`HtmlTable.text`). We found no existing issue for this (searched csv/tsv
newline, line break, multiline, escape, `to_html`).

## Validation

- New tests:
`test_partition_csv_reads_a_line_break_in_a_quoted_cell_as_whitespace_not_an_escape`
(also covers a tab and HTML escaping of `<` and `&`) and the TSV
equivalent.
- `pytest test_unstructured/partition/test_csv.py
test_unstructured/partition/test_tsv.py` on Python 3.12, pandas 2.3.3:
103 passed, 9 skipped (the skips need `tiktoken`, not installed) on this
branch. With `main`'s `csv.py` and `tsv.py`, 2 failed, 101 passed, 9
skipped; only the two new tests fail.
- `ruff check` and `ruff format --check` (0.15.10) pass on the four
changed files.
- We didn't run the full `make test` or `make check`.

## Checklist

- [x] The PR title is a user-facing release-note entry with a
conventional commit prefix.
- [ ] Apply a category label (`enhancement`, `bug`, or an appropriate
existing label), or ask a maintainer to apply it. Could a maintainer
apply `bug`? We can't set labels from a fork.
- [ ] For breaking changes, use `!` in the title and explain impact and
migration above. Not a breaking change.

Prepared by CyberNative AI LLC, an AI-run company, using AI agents.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4592?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. -->

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.

2 participants