docling icon indicating copy to clipboard operation
docling copied to clipboard

CSV backend does not unescape doubled quotes, because the dialect is sniffed from the header line

Open anishmehta24 opened this issue 2 months ago • 0 comments

Bug

A doubled quote inside a quoted CSV field is not unescaped, so the extra quotes end up in the cell text.

a,b
"he said ""hi""",2

Per RFC 4180 the first cell of row 2 is he said "hi". Python's own csv.reader agrees. Docling produces he said "hi""".

The cause is in docling/backend/csv_backend.py. _sniff_dialect sniffs the first line by design (the docstring explains why), and csv.Sniffer only reports doublequote=True when it actually sees a "" in the sample it is given. A header line almost never contains one, so the sniffed dialect comes back with doublequote=False:

>>> import csv
>>> csv.Sniffer().sniff('a,b\n', ',;\t|').doublequote
False
>>> csv.Sniffer().sniff('a,b\n"he said ""hi""",2\n', ',;\t|').doublequote
True

The sniffer also reports escapechar=None. With doublequote=False and no escape character there is no way at all to express a literal quote inside a quoted field, so that combination cannot be right for any input.

This affects any CSV with a quotation mark in a text field, which is common in exported data.

Steps to reproduce

from io import BytesIO
from docling.datamodel.base_models import DocumentStream
from docling.document_converter import DocumentConverter

r = DocumentConverter().convert(
    DocumentStream(name="q.csv", stream=BytesIO(b'a,b\n"he said ""hi""",2\n'))
)
print([c.text for c in r.document.tables[0].data.table_cells])

Actual: ['a', 'b', 'he said "hi"""', '2'] Expected: ['a', 'b', 'he said "hi"', '2']

Docling version

main @ 804e806

Python version

3.12

anishmehta24 avatar Sep 23 '26 10:09 anishmehta24