Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions docling/backend/csv_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,17 @@ class CsvDocumentBackend(DeclarativeDocumentBackend):
def __init__(self, in_doc: "InputDocument", path_or_stream: Union[BytesIO, Path]):
super().__init__(in_doc, path_or_stream)

# Load content
# Load content. utf-8-sig drops a leading BOM, which Excel and Google
# Sheets both write when exporting "CSV UTF-8"; left in, it becomes part
# of the first header cell. It is equivalent to utf-8 when no BOM is
# present.
try:
if isinstance(self.path_or_stream, BytesIO):
self.content = StringIO(self.path_or_stream.getvalue().decode("utf-8"))
self.content = StringIO(
self.path_or_stream.getvalue().decode("utf-8-sig")
)
elif isinstance(self.path_or_stream, Path):
self.content = StringIO(self.path_or_stream.read_text("utf-8"))
self.content = StringIO(self.path_or_stream.read_text("utf-8-sig"))
self.valid = True
except Exception as e:
raise DocumentLoadError(
Expand Down
26 changes: 26 additions & 0 deletions tests/test_backend_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,29 @@ def test_empty_csv():
# The empty CSV should result in an empty document (no tables and no texts).
assert len(getattr(doc, "tables", [])) == 0
assert len(getattr(doc, "texts", [])) == 0


def test_utf8_bom_is_not_part_of_the_first_cell(tmp_path):
"""A leading UTF-8 BOM must not survive into the first header cell.

Excel and Google Sheets write a BOM when exporting "CSV UTF-8". Decoding
with plain utf-8 kept it, so the first header came back as U+FEFF followed
by "Name", and matching on that header silently missed the column. Both the
stream and the file path are covered, since each decodes separately.
"""
csv_bytes = "\ufeffName,Age\nAlice,30\n".encode()
converter = get_converter()

stream_doc = converter.convert(
DocumentStream(name="bom.csv", stream=BytesIO(csv_bytes)),
raises_on_error=True,
).document

csv_file = tmp_path / "bom.csv"
csv_file.write_bytes(csv_bytes)
file_doc = converter.convert(csv_file, raises_on_error=True).document

for doc in (stream_doc, file_doc):
cells = doc.tables[0].data.table_cells
assert cells[0].text == "Name"
assert cells[1].text == "Age"
Loading