fix(detect): keep tables in place and read all text in docx sidecars
docx_to_markdown wrote every paragraph first and appended all tables at the
end, so a table lost the heading it belongs to. Paragraph.text also drops
tracked insertions, content controls, fields and text boxes. And a cell's
text went into its markdown row as is, so a line break split the row and a
pipe added a column.
Walk the body in document order, read each paragraph's runs inside those
containers (skipping deleted text and the fallback copy of a text box), and
put a cell on one line with its pipes escaped.
(cherry picked from commit ee72d5256f)
This commit is contained in:
1 parent
5793226ff4
commit
e27d51d7c0
2 files changed
+216
-13
No files matched your search
+89
-13
@@ -567,18 +567,104 @@ def extract_pdf_text(path: Path) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
_W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
|
||||
_MC_FALLBACK = "{http://schemas.openxmlformats.org/markup-compatibility/2006}Fallback"
|
||||
# Content controls and custom XML wrap paragraphs and tables without changing them.
|
||||
_DOCX_WRAPPERS = frozenset({f"{_W}sdt", f"{_W}customXml"})
|
||||
# Text under these is not part of the text as the document reads: tracked deletions, text
|
||||
# moved away, the ruby guide over its base text, text boxes (read as paragraphs of their
|
||||
# own) and the fallback copy Word writes of every text box.
|
||||
_DOCX_SKIPPED = frozenset({f"{_W}del", f"{_W}moveFrom", f"{_W}rt", f"{_W}txbxContent", _MC_FALLBACK})
|
||||
# The run children python-docx's Run.text reads, each as the text it stands for.
|
||||
_DOCX_RUN_TEXT = tuple(f"{_W}{tag}" for tag in ("br", "cr", "noBreakHyphen", "ptab", "t", "tab"))
|
||||
|
||||
|
||||
def _docx_inside(element, stop, tags) -> bool:
|
||||
node = element.getparent()
|
||||
while node is not None and node is not stop:
|
||||
if node.tag in tags:
|
||||
return True
|
||||
node = node.getparent()
|
||||
return False
|
||||
|
||||
|
||||
def _docx_paragraph_text(p) -> str:
|
||||
"""Paragraph.text reads only the runs directly under the paragraph, so it drops tracked
|
||||
insertions, content controls, simple fields and smart tags."""
|
||||
return "".join(
|
||||
str(element)
|
||||
for element in p.iter(*_DOCX_RUN_TEXT)
|
||||
if not _docx_inside(element, p, _DOCX_SKIPPED)
|
||||
)
|
||||
|
||||
|
||||
def _docx_blocks(container):
|
||||
"""Yield the w:p and w:tbl elements of a container in document order, looking through
|
||||
content controls and custom XML, with each text box's content after its paragraph."""
|
||||
for child in container:
|
||||
if child.tag == f"{_W}p":
|
||||
yield child
|
||||
for box in child.iter(f"{_W}txbxContent"):
|
||||
if not _docx_inside(box, child, _DOCX_SKIPPED):
|
||||
yield from _docx_blocks(box)
|
||||
elif child.tag == f"{_W}tbl":
|
||||
yield child
|
||||
elif child.tag in _DOCX_WRAPPERS:
|
||||
content = child.find(f"{_W}sdtContent")
|
||||
yield from _docx_blocks(child if content is None else content)
|
||||
|
||||
|
||||
def _docx_children(parent, tag: str):
|
||||
for child in parent:
|
||||
if child.tag == f"{_W}{tag}":
|
||||
yield child
|
||||
elif child.tag in _DOCX_WRAPPERS:
|
||||
content = child.find(f"{_W}sdtContent")
|
||||
yield from _docx_children(child if content is None else content, tag)
|
||||
|
||||
|
||||
def _docx_cell_markdown(tc) -> str:
|
||||
"""A cell's text on one line with pipes escaped, so it cannot break its table row."""
|
||||
parts = []
|
||||
for block in _docx_blocks(tc):
|
||||
if block.tag == f"{_W}p":
|
||||
parts.append(_docx_paragraph_text(block))
|
||||
else: # a nested table, flattened into the cell
|
||||
parts.extend(
|
||||
_docx_cell_markdown(cell)
|
||||
for row in _docx_children(block, "tr")
|
||||
for cell in _docx_children(row, "tc")
|
||||
)
|
||||
return " ".join(" ".join(part.split()) for part in parts if part.strip()).replace("|", "\\|")
|
||||
|
||||
|
||||
def docx_to_markdown(path: Path) -> str:
|
||||
"""Convert a .docx file to markdown text using python-docx."""
|
||||
if not _zip_within_caps(path):
|
||||
return ""
|
||||
try:
|
||||
from docx import Document
|
||||
from docx.oxml.ns import qn
|
||||
from docx.table import Table
|
||||
from docx.text.paragraph import Paragraph
|
||||
doc = Document(str(path))
|
||||
lines = []
|
||||
for para in doc.paragraphs:
|
||||
# Walk the body in document order, so a table stays under the heading it belongs to.
|
||||
for block in _docx_blocks(doc.element.body):
|
||||
if block.tag == f"{_W}tbl":
|
||||
# python-docx's rows repeat a merged cell across the grid columns it spans,
|
||||
# which keeps the header and the rows the same width.
|
||||
rows = [[_docx_cell_markdown(cell._tc) for cell in row.cells] for row in Table(block, doc).rows]
|
||||
if not rows:
|
||||
continue
|
||||
header = "| " + " | ".join(rows[0]) + " |"
|
||||
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
|
||||
lines.extend([header, sep])
|
||||
for row in rows[1:]:
|
||||
lines.append("| " + " | ".join(row) + " |")
|
||||
continue
|
||||
para = Paragraph(block, doc)
|
||||
style = para.style.name if para.style else ""
|
||||
text = para.text.strip()
|
||||
text = _docx_paragraph_text(block).strip()
|
||||
if not text:
|
||||
lines.append("")
|
||||
continue
|
||||
@@ -592,16 +678,6 @@ def docx_to_markdown(path: Path) -> str:
|
||||
lines.append(f"- {text}")
|
||||
else:
|
||||
lines.append(text)
|
||||
# Tables
|
||||
for table in doc.tables:
|
||||
rows = [[cell.text.strip() for cell in row.cells] for row in table.rows]
|
||||
if not rows:
|
||||
continue
|
||||
header = "| " + " | ".join(rows[0]) + " |"
|
||||
sep = "| " + " | ".join("---" for _ in rows[0]) + " |"
|
||||
lines.extend([header, sep])
|
||||
for row in rows[1:]:
|
||||
lines.append("| " + " | ".join(row) + " |")
|
||||
return "\n".join(lines)
|
||||
except ImportError:
|
||||
return ""
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Tests for graphify.detect.docx_to_markdown."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
docx = pytest.importorskip("docx")
|
||||
from docx.oxml import parse_xml # noqa: E402
|
||||
from docx.shared import Inches # noqa: E402
|
||||
|
||||
from graphify.detect import docx_to_markdown # noqa: E402
|
||||
|
||||
_NAMESPACES = (
|
||||
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" '
|
||||
'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" '
|
||||
'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" '
|
||||
'xmlns:v="urn:schemas-microsoft-com:vml"'
|
||||
)
|
||||
|
||||
|
||||
def _run(text: str) -> str:
|
||||
return f'<w:r><w:t xml:space="preserve">{text}</w:t></w:r>'
|
||||
|
||||
|
||||
def _append_xml(document, *fragments: str) -> None:
|
||||
section_properties = document.element.body[-1]
|
||||
body = parse_xml(f"<w:body {_NAMESPACES}>{''.join(fragments)}</w:body>")
|
||||
for element in list(body):
|
||||
section_properties.addprevious(element)
|
||||
|
||||
|
||||
def _markdown(document, tmp_path) -> list[str]:
|
||||
path = tmp_path / "doc.docx"
|
||||
document.save(path)
|
||||
return docx_to_markdown(path).split("\n")
|
||||
|
||||
|
||||
def test_plain_paragraphs_keep_their_markdown(tmp_path):
|
||||
document = docx.Document()
|
||||
document.add_heading("Title", level=1)
|
||||
document.add_heading("Section", level=2)
|
||||
document.add_paragraph("Body text.")
|
||||
document.add_paragraph("")
|
||||
document.add_paragraph("An item", style="List Bullet")
|
||||
# A tab stop is a w:tab in the paragraph properties, not text.
|
||||
document.add_paragraph("Tab stop").paragraph_format.tab_stops.add_tab_stop(Inches(1))
|
||||
|
||||
assert _markdown(document, tmp_path) == [
|
||||
"# Title",
|
||||
"## Section",
|
||||
"Body text.",
|
||||
"",
|
||||
"- An item",
|
||||
"Tab stop",
|
||||
]
|
||||
|
||||
|
||||
def test_a_table_stays_under_its_heading(tmp_path):
|
||||
document = docx.Document()
|
||||
document.add_heading("Pricing", level=1)
|
||||
table = document.add_table(rows=2, cols=2)
|
||||
table.cell(0, 0).text = "Plan"
|
||||
table.cell(0, 1).text = "Price"
|
||||
table.cell(1, 0).text = "Basic"
|
||||
table.cell(1, 1).text = "10 EUR"
|
||||
document.add_heading("Notes", level=1)
|
||||
|
||||
assert _markdown(document, tmp_path) == [
|
||||
"# Pricing",
|
||||
"| Plan | Price |",
|
||||
"| --- | --- |",
|
||||
"| Basic | 10 EUR |",
|
||||
"# Notes",
|
||||
]
|
||||
|
||||
|
||||
def test_a_cell_stays_on_its_row(tmp_path):
|
||||
document = docx.Document()
|
||||
table = document.add_table(rows=2, cols=2)
|
||||
table.cell(0, 0).text = "Plan"
|
||||
table.cell(0, 1).text = "Price"
|
||||
table.cell(1, 0).text = "Basic | Pro"
|
||||
table.cell(1, 1).text = "10 EUR\nper month" # a line break inside the paragraph
|
||||
table.cell(1, 1).add_paragraph("billed yearly")
|
||||
|
||||
assert _markdown(document, tmp_path)[-1] == "| Basic \\| Pro | 10 EUR per month billed yearly |"
|
||||
|
||||
|
||||
def test_a_nested_table_is_flattened_into_its_cell_once(tmp_path):
|
||||
document = docx.Document()
|
||||
table = document.add_table(rows=1, cols=2)
|
||||
table.cell(0, 0).text = "Outer"
|
||||
nested = table.cell(0, 1).add_table(rows=1, cols=2)
|
||||
nested.cell(0, 0).text = "Inner A"
|
||||
nested.cell(0, 1).text = "Inner B"
|
||||
|
||||
assert _markdown(document, tmp_path)[0] == "| Outer | Inner A Inner B |"
|
||||
|
||||
|
||||
def test_tracked_changes_content_controls_and_text_boxes(tmp_path):
|
||||
box = "<w:txbxContent><w:p>" + _run("Callout") + "</w:p></w:txbxContent>"
|
||||
document = docx.Document()
|
||||
_append_xml(
|
||||
document,
|
||||
"<w:p>"
|
||||
+ _run("The fee is ")
|
||||
+ '<w:del w:id="1" w:author="a"><w:r><w:delText>ten</w:delText><w:tab/></w:r></w:del>'
|
||||
+ f'<w:ins w:id="2" w:author="a">{_run("twelve")}</w:ins>'
|
||||
+ _run(" euros.")
|
||||
+ "</w:p>",
|
||||
"<w:p>" + _run("Client: ") + f"<w:sdt><w:sdtPr/><w:sdtContent>{_run('Acme')}</w:sdtContent></w:sdt></w:p>",
|
||||
f"<w:sdt><w:sdtPr/><w:sdtContent><w:p>{_run('Block control')}</w:p></w:sdtContent></w:sdt>",
|
||||
# Word writes every text box twice: a DrawingML shape and a VML fallback copy.
|
||||
"<w:p>"
|
||||
+ _run("Host")
|
||||
+ "<w:r><mc:AlternateContent>"
|
||||
+ f'<mc:Choice Requires="wps"><w:drawing><wps:wsp><wps:txbx>{box}</wps:txbx></wps:wsp></w:drawing></mc:Choice>'
|
||||
+ f"<mc:Fallback><w:pict><v:shape><v:textbox>{box}</v:textbox></v:shape></w:pict></mc:Fallback>"
|
||||
+ "</mc:AlternateContent></w:r></w:p>",
|
||||
)
|
||||
|
||||
assert _markdown(document, tmp_path) == [
|
||||
"The fee is twelve euros.",
|
||||
"Client: Acme",
|
||||
"Block control",
|
||||
"Host",
|
||||
"Callout",
|
||||
]
|
||||
Reference in new issue
Block a user