Skip to content

fix(csv): read CSV and TSV cells as the file holds them - #4574

Merged
cragwolfe merged 2 commits into
Unstructured-IO:mainfrom
L4XB:fix/csv-cells-as-written
Oct 22, 2026
Merged

cragwolfe merged 2 commits into
Unstructured-IO:mainfrom
L4XB:fix/csv-cells-as-written

Conversation

@L4XB

@L4XB L4XB commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

read_delimited_text(), which reads every CSV and TSV upload, calls pd.read_csv() with Pandas' default cell interpretation. That changes what the file says in three ways:

cell main this PR
N/A, NULL, None (and NA, nan, n/a, …) empty N/A, NULL, None
12 in a column that has an empty cell, with include_header=True 12.0 12
007 in a column of codes that has an empty cell, with include_header=True 7.0 007

Probe file name,qty,status,code / Pen,12,N/A,007 / Ink,,NULL,010 / Pad,7,ok,. On main with include_header=True it reads name qty status code Pen 12.0 7.0 Ink 10.0 Pad 7.0 ok, and with include_header=False it reads name qty status code Pen 12 007 Ink 010 Pad 7 ok. With this PR it reads name qty status code Pen 12 N/A 007 Ink NULL 010 Pad 7 ok. Without a header row, the header strings already make each column object, so only the N/A / NULL loss shows there.

Change

Both pd.read_csv() calls in read_delimited_text() pass dtype=str, keep_default_na=False. Every cell is the text the file holds, and an empty field is an empty string. The HTML table still writes an empty cell as empty. Delimiter sniffing, the lone-\r reader and the cell-count limit are unchanged.

Related: #4505 does the same for XLSX (keep_default_na=False), and #4556 keeps XLSX whole numbers (dtype=object). Each PR only adds read options to its own reader.

Testing

  • New test_partition_csv_reads_each_cell_as_written (both include_header values) and test_partition_tsv_reads_each_cell_as_written fail on main.
  • The rest of test_csv.py and test_tsv.py passes (97 in total).
  • The 12 CSV/TSV files in example-docs partition to exactly the same element text and HTML as on main.
  • ruff 0.15.10 check and format are clean, and scripts/version-sync.sh -c passes with 0.27.34-dev1.

View guided diff

@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 0fd87536e740371da78bc86b5f0937d36bf1e1d2 with GPT Pro. No actionable production defects found. Both parser engines apply the same cell-preservation options, TSV shares the helper, and delimiter/header/quoting decisions remain consistent with the cell-count guard. The numeric and NA-marker output changes match the stated behavior.

This is a code-review approval. Required test/lint CI is not verified: workflow runs require action, and successful Socket checks do not establish test success. No local tests or reproductions were run.

(authored by codex)

@cragwolfe
cragwolfe merged commit 42fa45a into Unstructured-IO:main Oct 22, 2026
52 checks passed
@CyMule CyMule mentioned this pull request Oct 22, 2026
linhongyu510 pushed a commit to linhongyu510/unstructured that referenced this pull request Oct 22, 2026
Drops the `-dev6` suffix so 0.27.34 can be tagged and published. There
are no code changes.

Since 0.27.33, this release contains:

- Free decode buffers sooner when restoring original elements (Unstructured-IO#4524)
- Free image buffers sooner during figure extraction (Unstructured-IO#4523)
- Honor `encoding=` in `partition_json` and `partition_ndjson` (Unstructured-IO#4483)
- Read a PowerPoint line break as a newline (Unstructured-IO#4571)
- Drop the empty entry of an email address group (Unstructured-IO#4576)
- Read CSV and TSV cells as the file holds them (Unstructured-IO#4574)
- Classify text as an email address only when all of it is one (Unstructured-IO#4577)

After merge, create the `0.27.34` GitHub release from the merge commit.
That publishes to PyPI.

<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4582?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. -->
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. -->
Bensonluo added a commit to Bensonluo/unstructured that referenced this pull request Nov 13, 2026
## Summary

`read_delimited_text()`, which reads every CSV and TSV upload, gets its
header labels from `pd.read_csv()`, which makes a repeated label unique
as it reads it. A header row `name,name,age` therefore yields the labels
`name`, `name.1`, `age`; when a genuine `name.1` label is also present,
Pandas names the repeated `name` column `name.2`. The fabricated labels
appear in the `Table` element's `text` and `metadata.text_as_html`, the
same class of corruption Unstructured-IO#4574 fixed for data cells.

| header row | `main` labels | this PR labels |
|---|---|---|
| `name,name,age` | `name name.1 age` | `name name age` |
| `name,name,name.1` | `name name.2 name.1` | `name name name.1` |

Fixes Unstructured-IO#4708.

## Change

`read_delimited_text()` peeks the first header line once (the delimiter
sniff already reads it) and, after the read,
`_restore_repeated_header_labels()` gives the data-frame back the labels
the file holds when they repeat. An empty header cell keeps the
`Unnamed: n` label Pandas gives it, which is the current emitted
behavior (pinned by existing tests). No pandas option can disable the
renaming (`mangle_dupe_cols` was removed in pandas 2.0), and
reassembling the read with `header=None` would change the index and
`Unnamed: n` semantics, so the labels are restored after the read.

The restoration is best-effort and gives up (leaving Pandas' labels)
rather than mis-read or fail, per the review:

- the header line is peeked within a bounded budget of 1 Mi decoded
characters inspected, including a blank prefix and text already queued
by delimiter detection. An oversized header or prefix leaves Pandas'
labels in place before the new splitter allocates fields; the existing
new-fill budget and unbounded delimiter-sniffing behavior are unchanged;
- the peek skips only the lines the read itself skips, so a header
record of empty tab-separated cells (`\t\nA\tA\n`) keeps its `Unnamed`
labels instead of taking the data row's values — on the sniffed path the
line is re-peeked with the sniffed delimiter;
- a header line that does not hold a complete record, a quoted cell
spanning lines, is left alone (its field count alone cannot tell, when
the spanning cell is last);
- the record is split by `_split_header_record()`, an in-module
quote-aware scanner, instead of `csv.reader`, so a field past the csv
module's field-size limit is restored too and the labels no longer
depend on the process-wide limit `partition_csv()` raises for its own
read — no global CSV state is read or set on this path (per the
re-review).

## Compatibility

Restoring the file's repeated labels changes `Table.text` and
`metadata.text_as_html` for any file whose header row repeats a label —
that is the fix. For documents re-processed after this change, the
changed text also changes any default element ID derived from that text,
so a consumer that upserts by ID may need to reconcile or re-ingest the
older elements (raised in review). Files whose header labels do not
repeat keep `main`'s output, pinned by the existing tests. Whether to
accept this behavior change, and what release or migration guidance to
attach, is for the maintainers to decide.

## Validation

`test_unstructured/partition/test_csv.py` and `test_tsv.py`: 136 passed,
9 skipped, covering a repeated label (text and `text_as_html`), a
genuine `name.1` label, a repeated label beside an empty header cell
(`Unnamed: n` kept), a quoted repeated label, CRLF endings, and — from
the review rounds — a quoted header cell spanning lines (labels left
alone, no text lost), a header record of empty cells (explicit and
sniffed delimiter), a blank prefix past the peek budget, the budget
itself (white-box), label restoration independent of the ambient
field-size limit (same text and HTML at a 1 KiB limit and at the ambient
one), and a differential test checking the in-module splitter against
the csv module over every single-line record it can be reached with
(strings through length 7 over a four-symbol alphabet, three line
endings, both delimiters). The first seven fail on `main` with the
fabricated label; the first review round's tests fail on this PR's first
commit and pass on the second; the re-review's tests fail on the second
and pass on the third. The latest review adds 14 parameterized cases for
a prefilled header/prefix (including an unterminated line), the budget
boundary, input replay after giving up, and the sniffed
`partition_csv()` path with large non-ASCII repeated/unique labels;
those same cases produce 9 failures and 5 passes on `56c11c0` and all
pass with the fix. The fourth review round's regression holds only while
the unbounded sniff sample is still bound through `pd.read_csv()` on a
headerless sniffed read (red on `5b54e9b`, green with the sample back to
a temporary); nothing else changes. Repository-wide `ruff check .` and
`ruff format --check .` pass. The branch includes current `main`
(`ad56303`); its separate detection-metrics regression test could not
collect in this CSV test environment because `torch` is not installed.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/Unstructured-IO/unstructured/pull/4709?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->

---------

Signed-off-by: Benson LUO <[email protected]>
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