From a7319a1b4d6ca09e8bba49570d3313b37b406eb7 Mon Sep 17 00:00:00 2001 From: zuizhuai Date: Fri, 27 Nov 2026 15:28:17 +0800 Subject: [PATCH] fix(docreader): escape table cell pipes in DOCX tables MarkItDown's DocxConverter builds a table through mammoth HTML and then writes it with markdownify, which leaves a "|" inside a cell's text as it is. The reader takes that pipe for a column delimiter, so a cell holding "10 | USD" splits into two columns and every later cell shifts right. CSV (#5392), EPUB (#5523) and PPTX (#6019) already wrap their converter for this reason; DOCX still went through the stock converter. The fallback DocxParser escapes pipes itself, so only the default MarkItDown path was affected. DocxConverter hands the mammoth HTML to the _html_converter instance attribute, so replacing that attribute with one that escapes the cells first is enough: the conversion itself stays MarkItDown's, and a document without a table takes the untouched path. --- docreader/parser/docx_converter.py | 35 +++++++++++++++++++ docreader/parser/markitdown_parser.py | 3 ++ docreader/tests/test_docx_table_cells.py | 43 ++++++++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 docreader/parser/docx_converter.py create mode 100644 docreader/tests/test_docx_table_cells.py diff --git a/docreader/parser/docx_converter.py b/docreader/parser/docx_converter.py new file mode 100644 index 00000000000..f1b5ad6afcd --- /dev/null +++ b/docreader/parser/docx_converter.py @@ -0,0 +1,35 @@ +"""Keep DOCX table cell boundaries intact in MarkItDown's Markdown tables.""" + +from bs4 import BeautifulSoup +from markitdown.converters import DocxConverter, HtmlConverter + +from docreader.parser.mhtml_parser import MHTMLParser + + +class _EscapingHtmlConverter(HtmlConverter): + """Escape table cell pipes before markdownify turns the HTML into a table. + + MarkItDown converts a DOCX to HTML with mammoth and then writes the table + with markdownify, which leaves a ``|`` in a cell's text as it is. The + reader then takes that pipe for a column delimiter, so every cell after it + shifts one column right and the row gains a column. MarkItDown's PPTX and + CSV converters are wrapped in this package for the same reason; a DOCX + goes through this converter instead. + """ + + def convert_string(self, html_content, **kwargs): + # Unchanged behaviour (and no parse cost) for documents without a + # table, which is the common case. + if "