Skip to content
Open
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
35 changes: 35 additions & 0 deletions docreader/parser/docx_converter.py
Original file line number Diff line number Diff line change
@@ -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 "<table" not in html_content:
return super().convert_string(html_content, **kwargs)
soup = BeautifulSoup(html_content, "html.parser")
MHTMLParser._escape_table_cell_pipes(soup)
return super().convert_string(str(soup), **kwargs)


class EscapedDocxConverter(DocxConverter):
def __init__(self):
super().__init__()
# DocxConverter hands the mammoth HTML to this instance attribute, so
# replacing it is enough; the conversion itself stays MarkItDown's.
self._html_converter = _EscapingHtmlConverter()
3 changes: 3 additions & 0 deletions docreader/parser/markitdown_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from docreader.parser.chain_parser import PipelineParser
from docreader.parser.concurrency import parser_worker_limit
from docreader.parser.csv_converter import EscapedCSVConverter
from docreader.parser.docx_converter import EscapedDocxConverter
from docreader.parser.docx_merge import fill_vertical_merged_cells_docx
from docreader.parser.markdown_parser import MarkdownParser
from docreader.parser.ppt_convert import normalize_ppt_bytes
Expand Down Expand Up @@ -41,6 +42,8 @@ def __init__(self, *args, **kwargs):
ft = self.file_type.lower().lstrip(".")
if ft == "csv":
self.markitdown.register_converter(EscapedCSVConverter())
elif ft == "docx":
self.markitdown.register_converter(EscapedDocxConverter())
elif ft in ("ppt", "pptx"):
self.markitdown.register_converter(EscapedPptxConverter())

Expand Down
43 changes: 43 additions & 0 deletions docreader/tests/test_docx_table_cells.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import unittest
from io import BytesIO

from docx import Document

from docreader.parser.parser import Parser


def _docx(rows):
doc = Document()
table = doc.add_table(rows=len(rows), cols=len(rows[0]))
for r, row in enumerate(rows):
for c, value in enumerate(row):
table.cell(r, c).text = value
buf = BytesIO()
doc.save(buf)
return buf.getvalue()


class DOCXTableCellTests(unittest.TestCase):
def test_pipe_in_cell_stays_in_one_column(self):
content = Parser().parse_file(
"table.docx",
"docx",
_docx(
[
["Plan", "Price | Currency", "Notes"],
["Basic", "10 | USD", "x"],
]
),
).content
self.assertIn("| Plan | Price \\| Currency | Notes |", content)
self.assertIn("| Basic | 10 \\| USD | x |", content)

def test_plain_table_is_unchanged(self):
content = Parser().parse_file(
"table.docx", "docx", _docx([["A", "B"], ["x", "2"]])
).content
self.assertIn("| A | B |\n| --- | --- |\n| x | 2 |", content)


if __name__ == "__main__":
unittest.main()
Loading