fix(docreader): preserve vertically merged table cells (#2657)
* fix(docreader): preserve vertically merged table cells * test(docreader): cover docx preprocessing boundaries * test(docreader): isolate separate vertical merge groupsmain
parent
4c397ffc4d
commit
ffd1b043d2
|
|
@ -0,0 +1,177 @@
|
|||
"""Expand vertically merged DOCX table cells before Markdown conversion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import io
|
||||
import logging
|
||||
import zipfile
|
||||
|
||||
from lxml import etree
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_WORD_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
||||
_W = f"{{{_WORD_NAMESPACE}}}"
|
||||
_TC_PR = f"{_W}tcPr"
|
||||
_VMERGE = f"{_W}vMerge"
|
||||
_GRID_SPAN = f"{_W}gridSpan"
|
||||
_TR_PR = f"{_W}trPr"
|
||||
_GRID_BEFORE = f"{_W}gridBefore"
|
||||
_VAL = f"{_W}val"
|
||||
|
||||
|
||||
def fill_vertical_merged_cells_docx(content: bytes) -> bytes:
|
||||
"""Repeat a vertical merge's master content in every covered table row.
|
||||
|
||||
DOCX stores vertical merges as a ``vMerge=restart`` cell followed by empty
|
||||
``vMerge=continue`` cells. Mammoth preserves that as an HTML ``rowspan``,
|
||||
but Markdown tables cannot represent row spans and the later rows lose the
|
||||
merged value. This rewrites only Word XML parts that contain ``vMerge``;
|
||||
all other package parts and documents without vertical merges pass through
|
||||
unchanged.
|
||||
"""
|
||||
source = io.BytesIO(content)
|
||||
if not zipfile.is_zipfile(source):
|
||||
return content
|
||||
|
||||
with zipfile.ZipFile(source, "r") as archive:
|
||||
normalized_names = {
|
||||
info.filename.replace("\\", "/") for info in archive.infolist()
|
||||
}
|
||||
if "word/document.xml" not in normalized_names:
|
||||
return content
|
||||
|
||||
rewritten_parts: dict[str, bytes] = {}
|
||||
filled_count = 0
|
||||
for info in archive.infolist():
|
||||
name = info.filename.replace("\\", "/")
|
||||
if not name.startswith("word/") or not name.endswith(".xml"):
|
||||
continue
|
||||
|
||||
data = archive.read(info.filename)
|
||||
if b"vMerge" not in data:
|
||||
continue
|
||||
rewritten, part_filled_count = _fill_vertical_merges_in_xml(data)
|
||||
if rewritten is not None:
|
||||
rewritten_parts[info.filename] = rewritten
|
||||
filled_count += part_filled_count
|
||||
|
||||
if not rewritten_parts:
|
||||
return content
|
||||
|
||||
output = io.BytesIO()
|
||||
with zipfile.ZipFile(output, "w") as rewritten_archive:
|
||||
for info in archive.infolist():
|
||||
data = rewritten_parts.get(info.filename)
|
||||
if data is None:
|
||||
data = archive.read(info.filename)
|
||||
rewritten_archive.writestr(info, data)
|
||||
|
||||
logger.info(
|
||||
"Expanded %d vertically merged DOCX continuation cells before parse",
|
||||
filled_count,
|
||||
)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def _fill_vertical_merges_in_xml(data: bytes) -> tuple[bytes | None, int]:
|
||||
parser = etree.XMLParser(resolve_entities=False, no_network=True)
|
||||
try:
|
||||
root = etree.fromstring(data, parser=parser)
|
||||
except etree.XMLSyntaxError:
|
||||
return None, 0
|
||||
|
||||
changed = False
|
||||
filled_count = 0
|
||||
# Process nested tables first so copied cell content is already normalized.
|
||||
for table in reversed(root.xpath(".//w:tbl", namespaces={"w": _WORD_NAMESPACE})):
|
||||
table_changed, table_filled_count = _fill_table_vertical_merges(table)
|
||||
changed = changed or table_changed
|
||||
filled_count += table_filled_count
|
||||
|
||||
if not changed:
|
||||
return None, 0
|
||||
return etree.tostring(root, xml_declaration=True, encoding="UTF-8"), filled_count
|
||||
|
||||
|
||||
def _fill_table_vertical_merges(table: etree._Element) -> tuple[bool, int]:
|
||||
active_merges: dict[int, tuple[etree._Element, ...]] = {}
|
||||
changed = False
|
||||
filled_count = 0
|
||||
|
||||
for row in table.findall(f"{_W}tr"):
|
||||
next_active_merges: dict[int, tuple[etree._Element, ...]] = {}
|
||||
column = _grid_before(row)
|
||||
|
||||
for cell in row.findall(f"{_W}tc"):
|
||||
cell_properties = cell.find(_TC_PR)
|
||||
span = _grid_span(cell_properties)
|
||||
occupied_columns = range(column, column + span)
|
||||
vertical_merge = (
|
||||
cell_properties.find(_VMERGE) if cell_properties is not None else None
|
||||
)
|
||||
|
||||
if vertical_merge is not None:
|
||||
merge_type = vertical_merge.get(_VAL, "continue")
|
||||
if merge_type == "restart":
|
||||
template = tuple(
|
||||
copy.deepcopy(child) for child in cell if child.tag != _TC_PR
|
||||
)
|
||||
for occupied_column in occupied_columns:
|
||||
next_active_merges[occupied_column] = template
|
||||
cell_properties.remove(vertical_merge)
|
||||
changed = True
|
||||
else:
|
||||
template = next(
|
||||
(
|
||||
active_merges[occupied_column]
|
||||
for occupied_column in occupied_columns
|
||||
if occupied_column in active_merges
|
||||
),
|
||||
None,
|
||||
)
|
||||
if template is not None:
|
||||
for child in list(cell):
|
||||
if child.tag != _TC_PR:
|
||||
cell.remove(child)
|
||||
for child in template:
|
||||
cell.append(copy.deepcopy(child))
|
||||
for occupied_column in occupied_columns:
|
||||
next_active_merges[occupied_column] = template
|
||||
cell_properties.remove(vertical_merge)
|
||||
changed = True
|
||||
filled_count += 1
|
||||
|
||||
column += span
|
||||
|
||||
active_merges = next_active_merges
|
||||
|
||||
return changed, filled_count
|
||||
|
||||
|
||||
def _grid_span(cell_properties: etree._Element | None) -> int:
|
||||
if cell_properties is None:
|
||||
return 1
|
||||
grid_span = cell_properties.find(_GRID_SPAN)
|
||||
if grid_span is None:
|
||||
return 1
|
||||
return _positive_int(grid_span.get(_VAL), default=1)
|
||||
|
||||
|
||||
def _grid_before(row: etree._Element) -> int:
|
||||
row_properties = row.find(_TR_PR)
|
||||
if row_properties is None:
|
||||
return 0
|
||||
grid_before = row_properties.find(_GRID_BEFORE)
|
||||
if grid_before is None:
|
||||
return 0
|
||||
return _positive_int(grid_before.get(_VAL), default=0)
|
||||
|
||||
|
||||
def _positive_int(value: str | None, default: int) -> int:
|
||||
try:
|
||||
parsed = int(value or "")
|
||||
except ValueError:
|
||||
return default
|
||||
return parsed if parsed >= 0 else default
|
||||
|
|
@ -8,6 +8,7 @@ from docreader.models.document import Document
|
|||
from docreader.parser.base_parser import BaseParser
|
||||
from docreader.parser.chain_parser import PipelineParser
|
||||
from docreader.parser.concurrency import parser_worker_limit
|
||||
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
|
||||
from docreader.parser.pptx_media import (
|
||||
|
|
@ -43,7 +44,9 @@ class StdMarkitdownParser(BaseParser):
|
|||
content, ext = normalize_ppt_bytes(content, ft)
|
||||
pptx_bytes = content
|
||||
ft = "pptx"
|
||||
elif ext and not ext.startswith("."):
|
||||
elif ft == "docx":
|
||||
content = fill_vertical_merged_cells_docx(content)
|
||||
if ext and not ext.startswith("."):
|
||||
ext = "." + ext
|
||||
|
||||
with parser_worker_limit("markitdown", CONFIG.markitdown_max_workers):
|
||||
|
|
@ -61,7 +64,9 @@ class StdMarkitdownParser(BaseParser):
|
|||
text, images = attach_pptx_media_to_markdown(text, pptx_bytes)
|
||||
return Document(content=text, images=images)
|
||||
|
||||
def _convert_markitdown(self, content: bytes, ext: str | None, *, keep_data_uris: bool):
|
||||
def _convert_markitdown(
|
||||
self, content: bytes, ext: str | None, *, keep_data_uris: bool
|
||||
):
|
||||
try:
|
||||
return self.markitdown.convert(
|
||||
io.BytesIO(content),
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
"""Generate the real DOCX regression fixture for GitHub issue #2634."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
|
||||
|
||||
OUTPUT = Path(__file__).with_name("issue_2634_vertical_merge.docx")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
document = Document()
|
||||
document.add_heading("遗传病检测项目表", level=1)
|
||||
document.add_paragraph(
|
||||
"回归场景:检测方法纵向合并,但每条检测项目在转换后都必须保留该方法。"
|
||||
)
|
||||
|
||||
rows = [
|
||||
("Q0101", "遗传性乳腺癌", "BRCA1", "15个工作日"),
|
||||
("Q0102", "遗传性卵巢癌", "BRCA2", "15个工作日"),
|
||||
("Q0103", "林奇综合征", "MLH1", "15个工作日"),
|
||||
("Q0104", "家族性腺瘤性息肉病", "APC", "15个工作日"),
|
||||
]
|
||||
method = (
|
||||
"检测方法:提取外周血基因组 DNA,采用高通量测序,并对候选位点进行"
|
||||
"Sanger 测序验证;检测结果需结合临床表现综合判断。"
|
||||
)
|
||||
|
||||
table = document.add_table(rows=len(rows) + 1, cols=5)
|
||||
table.style = "Table Grid"
|
||||
headers = ("项目编号", "检测项目", "相关基因", "周期", "检测方法")
|
||||
for column, value in enumerate(headers):
|
||||
table.cell(0, column).text = value
|
||||
|
||||
for row_index, row in enumerate(rows, start=1):
|
||||
for column, value in enumerate(row):
|
||||
table.cell(row_index, column).text = value
|
||||
|
||||
merged_method = table.cell(1, 4).merge(table.cell(len(rows), 4))
|
||||
merged_method.text = method
|
||||
merged_method.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
|
||||
|
||||
document.add_paragraph("非合并对照表:相邻单元格内容允许相同,但不应被当作合并。")
|
||||
control = document.add_table(rows=2, cols=3)
|
||||
control.style = "Table Grid"
|
||||
for column, value in enumerate(("列A", "列B", "列C")):
|
||||
control.cell(0, column).text = value
|
||||
for column, value in enumerate(("相同值", "相同值", "独立值")):
|
||||
control.cell(1, column).text = value
|
||||
|
||||
document.save(OUTPUT)
|
||||
print(f"generated={OUTPUT}")
|
||||
print(f"size={OUTPUT.stat().st_size}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Binary file not shown.
|
|
@ -0,0 +1,187 @@
|
|||
import io
|
||||
import unittest
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from docx import Document as WordDocument
|
||||
from lxml import etree
|
||||
|
||||
from docreader.parser.docx2_parser import Docx2Parser
|
||||
from docreader.parser.docx_merge import fill_vertical_merged_cells_docx
|
||||
from docreader.parser.markitdown_parser import StdMarkitdownParser
|
||||
|
||||
FIXTURE = Path(__file__).with_name("fixtures") / "issue_2634_vertical_merge.docx"
|
||||
METHOD_PREFIX = "检测方法:提取外周血基因组 DNA"
|
||||
PROJECT_CODES = ("Q0101", "Q0102", "Q0103", "Q0104")
|
||||
WORD_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
|
||||
|
||||
|
||||
class DocxVerticalMergeFillTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.fixture_bytes = FIXTURE.read_bytes()
|
||||
|
||||
def test_fixture_is_a_real_docx_with_vertical_merge(self):
|
||||
self.assertTrue(zipfile.is_zipfile(io.BytesIO(self.fixture_bytes)))
|
||||
with zipfile.ZipFile(io.BytesIO(self.fixture_bytes)) as archive:
|
||||
self.assertIsNone(archive.testzip())
|
||||
root = etree.fromstring(archive.read("word/document.xml"))
|
||||
|
||||
vertical_merges = root.xpath(
|
||||
".//w:tbl[1]//w:vMerge", namespaces={"w": WORD_NAMESPACE}
|
||||
)
|
||||
merge_values = [
|
||||
node.get(f"{{{WORD_NAMESPACE}}}val", "continue") for node in vertical_merges
|
||||
]
|
||||
self.assertEqual(
|
||||
merge_values,
|
||||
["restart", "continue", "continue", "continue"],
|
||||
)
|
||||
|
||||
def test_fill_repeats_master_content_in_every_covered_row(self):
|
||||
filled = fill_vertical_merged_cells_docx(self.fixture_bytes)
|
||||
document = WordDocument(io.BytesIO(filled))
|
||||
table = document.tables[0]
|
||||
|
||||
for row_index, project_code in enumerate(PROJECT_CODES, start=1):
|
||||
self.assertEqual(table.cell(row_index, 0).text, project_code)
|
||||
self.assertIn(METHOD_PREFIX, table.cell(row_index, 4).text)
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(filled)) as archive:
|
||||
root = etree.fromstring(archive.read("word/document.xml"))
|
||||
self.assertEqual(
|
||||
root.xpath("count(.//w:vMerge)", namespaces={"w": WORD_NAMESPACE}),
|
||||
0.0,
|
||||
)
|
||||
|
||||
def test_non_merged_equal_cells_are_not_collapsed(self):
|
||||
filled = fill_vertical_merged_cells_docx(self.fixture_bytes)
|
||||
document = WordDocument(io.BytesIO(filled))
|
||||
control_row = document.tables[1].rows[1]
|
||||
self.assertEqual(len(control_row.cells), 3)
|
||||
self.assertEqual(
|
||||
[cell.text for cell in control_row.cells],
|
||||
["相同值", "相同值", "独立值"],
|
||||
)
|
||||
|
||||
def test_non_docx_bytes_pass_through_unchanged(self):
|
||||
content = b"not a docx package"
|
||||
self.assertIs(fill_vertical_merged_cells_docx(content), content)
|
||||
|
||||
def test_docx_without_vertical_merges_passes_through_unchanged(self):
|
||||
document = WordDocument()
|
||||
table = document.add_table(rows=1, cols=2)
|
||||
table.cell(0, 0).text = "left"
|
||||
table.cell(0, 1).text = "right"
|
||||
output = io.BytesIO()
|
||||
document.save(output)
|
||||
content = output.getvalue()
|
||||
|
||||
self.assertIs(fill_vertical_merged_cells_docx(content), content)
|
||||
|
||||
def test_horizontal_merge_only_passes_through_unchanged(self):
|
||||
document = WordDocument()
|
||||
table = document.add_table(rows=1, cols=3)
|
||||
table.cell(0, 0).merge(table.cell(0, 1)).text = "horizontal merge"
|
||||
table.cell(0, 2).text = "independent"
|
||||
output = io.BytesIO()
|
||||
document.save(output)
|
||||
content = output.getvalue()
|
||||
|
||||
self.assertIs(fill_vertical_merged_cells_docx(content), content)
|
||||
|
||||
def test_separate_merge_groups_keep_distinct_values_and_other_columns(self):
|
||||
document = WordDocument()
|
||||
table = document.add_table(rows=6, cols=2)
|
||||
table.cell(0, 0).text = "group"
|
||||
table.cell(0, 1).text = "item"
|
||||
for row_index in range(1, 6):
|
||||
table.cell(row_index, 1).text = f"item-{row_index}"
|
||||
|
||||
table.cell(1, 0).merge(table.cell(2, 0)).text = "group-a"
|
||||
table.cell(3, 0).text = "standalone"
|
||||
table.cell(4, 0).merge(table.cell(5, 0)).text = "group-b"
|
||||
|
||||
output = io.BytesIO()
|
||||
document.save(output)
|
||||
filled = fill_vertical_merged_cells_docx(output.getvalue())
|
||||
parsed_table = WordDocument(io.BytesIO(filled)).tables[0]
|
||||
|
||||
self.assertEqual(
|
||||
[parsed_table.cell(row_index, 0).text for row_index in range(1, 6)],
|
||||
["group-a", "group-a", "standalone", "group-b", "group-b"],
|
||||
)
|
||||
self.assertEqual(
|
||||
[parsed_table.cell(row_index, 1).text for row_index in range(1, 6)],
|
||||
[f"item-{row_index}" for row_index in range(1, 6)],
|
||||
)
|
||||
|
||||
|
||||
class DocxMarkitdownDispatchTest(unittest.TestCase):
|
||||
def test_non_docx_types_do_not_run_docx_preprocessor(self):
|
||||
for file_type in ("doc", "txt", "md"):
|
||||
with self.subTest(file_type=file_type):
|
||||
parser = StdMarkitdownParser(file_type=file_type)
|
||||
result = SimpleNamespace(text_content="parsed")
|
||||
with (
|
||||
patch(
|
||||
"docreader.parser.markitdown_parser.fill_vertical_merged_cells_docx"
|
||||
) as preprocess,
|
||||
patch.object(parser, "_convert_markitdown", return_value=result),
|
||||
):
|
||||
document = parser.parse_into_text(b"payload")
|
||||
|
||||
self.assertEqual(document.content, "parsed")
|
||||
preprocess.assert_not_called()
|
||||
|
||||
def test_uppercase_docx_type_runs_docx_preprocessor(self):
|
||||
parser = StdMarkitdownParser(file_type=".DOCX")
|
||||
result = SimpleNamespace(text_content="parsed")
|
||||
with (
|
||||
patch(
|
||||
"docreader.parser.markitdown_parser.fill_vertical_merged_cells_docx",
|
||||
return_value=b"preprocessed",
|
||||
) as preprocess,
|
||||
patch.object(parser, "_convert_markitdown", return_value=result) as convert,
|
||||
):
|
||||
document = parser.parse_into_text(b"payload")
|
||||
|
||||
self.assertEqual(document.content, "parsed")
|
||||
preprocess.assert_called_once_with(b"payload")
|
||||
convert.assert_called_once_with(b"preprocessed", ".DOCX", keep_data_uris=True)
|
||||
|
||||
|
||||
class Issue2634ParserRegressionTest(unittest.TestCase):
|
||||
def test_markitdown_output_repeats_merged_value_for_every_data_row(self):
|
||||
document = StdMarkitdownParser(
|
||||
file_name=FIXTURE.name, file_type="docx"
|
||||
).parse_into_text(FIXTURE.read_bytes())
|
||||
|
||||
data_lines = {
|
||||
project_code: next(
|
||||
line for line in document.content.splitlines() if project_code in line
|
||||
)
|
||||
for project_code in PROJECT_CODES
|
||||
}
|
||||
for line in data_lines.values():
|
||||
self.assertIn(METHOD_PREFIX, line)
|
||||
self.assertEqual(document.content.count(METHOD_PREFIX), len(PROJECT_CODES))
|
||||
self.assertIn("| 相同值 | 相同值 | 独立值 |", document.content)
|
||||
|
||||
def test_full_docx_entry_keeps_context_on_all_four_rows(self):
|
||||
document = Docx2Parser(
|
||||
file_name=FIXTURE.name, file_type="docx"
|
||||
).parse_into_text(FIXTURE.read_bytes())
|
||||
|
||||
for project_code in PROJECT_CODES:
|
||||
data_line = next(
|
||||
line for line in document.content.splitlines() if project_code in line
|
||||
)
|
||||
self.assertIn(METHOD_PREFIX, data_line)
|
||||
self.assertEqual(document.content.count(METHOD_PREFIX), len(PROJECT_CODES))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue