docling icon indicating copy to clipboard operation
docling copied to clipboard

csv: UTF-8 BOM ends up inside the first header cell

Open aniketwaghh opened this issue 3 months ago • 0 comments

Bug

CsvDocumentBackend decodes with plain utf-8, so a UTF-8 BOM (U+FEFF) survives into the first cell of the first row. Excel and Google Sheets both write one when exporting "CSV UTF-8", so it turns up in fairly ordinary files.

The header cell comes out as "\ufeffName" instead of "Name".

Writing it escaped on purpose: U+FEFF is zero-width, so pasted literally the two are indistinguishable on screen, which is the whole problem.

Because it lands in the header row it also reaches the exported document. The markdown below looks completely normal, and that is the point, the first header is not the string it appears to be:

| Name   |   Age |
|--------|-------|
| Alice  |    30 |

So the practical symptom is that downstream code matching on a header (cell.text == "Name", a dataframe column lookup, a chunker keying off the header) silently misses the first column, and nothing in the rendered output explains why.

html_backend.py already strips U+FEFF as noise (line 4603), so the CSV path looks like an oversight rather than a deliberate choice.

Decoding with utf-8-sig fixes it and is identical to utf-8 for files that have no BOM, so it shouldn't affect anything else. I checked that across comma, semicolon and single-column inputs.

The same plain-utf-8 decode exists in asciidoc_backend, boxnote_backend, webvtt_backend and md_backend. A leading BOM is mostly cosmetic in those since it just joins the first text run, whereas here it corrupts a structured field, so I've kept this to CSV. Happy to look at the others separately if you'd like.

Steps to reproduce

from io import BytesIO

from docling.backend.csv_backend import CsvDocumentBackend
from docling.datamodel.base_models import InputFormat
from docling.datamodel.document import InputDocument

# "\ufeff" is what Excel writes at the start of a "CSV UTF-8" export
data = "\ufeffName,Age\nAlice,30\n".encode("utf-8")
stream = BytesIO(data)

in_doc = InputDocument(
    path_or_stream=stream,
    format=InputFormat.CSV,
    backend=CsvDocumentBackend,
    filename="bom.csv",
)
doc = CsvDocumentBackend(in_doc=in_doc, path_or_stream=stream).convert()

print(repr(doc.tables[0].data.table_cells[0].text))
'\ufeffName'      # expected 'Name'

End to end through the converter, against main @ e5628ff:

--- excel_export.csv ---
first header cell : '\ufeffName'
all headers       : ['\ufeffName', 'Age', 'City']
lookup "Name"     : NOT FOUND  <-- silently misses the column

--- plain.csv (control, no BOM) ---
first header cell : 'Name'
all headers       : ['Name', 'Age', 'City']
lookup "Name"     : found

and with utf-8-sig, both files give 'Name' and the lookup succeeds.

Docling version

2.123.0 (main @ e5628ff)

Python version

3.12

aniketwaghh avatar Aug 28 '26 13:08 aniketwaghh