Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(doc-to-md): preserve DOCX tables as pipe Markdown and trim mammoth over-escaping

hugohe3f9757b919e42
diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.md
index cbbc559b..1d03272f 100644
--- a/skills/ppt-master/scripts/docs/conversion.md
+++ b/skills/ppt-master/scripts/docs/conversion.md
@@ -41,7 +41,7 @@ pip install PyMuPDF
Hybrid converter: pure-Python for the common formats, pandoc fallback for the rest.
Native path (no external binary required):
-- `.docx` — via `mammoth`; OMML / Office Math equations (Word-native or MathType "Convert to Office Math") are rewritten to inline LaTeX. Classic MathType OLE objects carry no OMML and are kept only as their preview image.
+- `.docx` — via `mammoth`; text-only tables are preserved as pipe Markdown, and OMML / Office Math equations (Word-native or MathType "Convert to Office Math") are rewritten to inline LaTeX. Classic MathType OLE objects carry no OMML and are kept only as their preview image.
- `.html` / `.htm` — via `markdownify` + `beautifulsoup4`
- `.epub` — via `ebooklib` + `markdownify`
- `.ipynb` — via `nbconvert`
diff --git a/skills/ppt-master/scripts/source_to_md/doc_to_md.py b/skills/ppt-master/scripts/source_to_md/doc_to_md.py
index 8382ca18..ad3ba12c 100644
--- a/skills/ppt-master/scripts/source_to_md/doc_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/doc_to_md.py
@@ -3,7 +3,7 @@
Document to Markdown Converter (hybrid Python + Pandoc fallback)
Primary formats (pure Python, no external tools required):
- .docx → mammoth (OMML/Office Math equations rewritten to inline LaTeX)
+ .docx → mammoth (tables preserved; OMML equations rewritten to inline LaTeX)
.html → markdownify + BeautifulSoup
.epub → ebooklib + markdownify
.ipynb → nbconvert
@@ -614,6 +614,13 @@ def _make_text_run(text: str) -> ET.Element:
return run
+def _make_text_paragraph(text: str) -> ET.Element:
+ """Build a simple Word paragraph containing text."""
+ paragraph = ET.Element(f"{{{W_NS}}}p")
+ paragraph.append(_make_text_run(text))
+ return paragraph
+
+
def _docx_inject_math_latex(
input_file: Path,
) -> tuple[Path, dict[str, str]] | None:
@@ -680,6 +687,134 @@ def _docx_inject_math_latex(
return out_path, replacements
+# ─────────────────────────────────────────────────────────────
+# DOCX tables → pipe Markdown
+# ─────────────────────────────────────────────────────────────
+
+def _docx_paragraph_text(paragraph: ET.Element) -> str:
+ """Extract readable text from one Word paragraph."""
+ parts: list[str] = []
+ for elem in paragraph.iter():
+ local = _local_name(elem)
+ if local == "t":
+ parts.append(elem.text or "")
+ elif local == "tab":
+ parts.append("\t")
+ elif local in {"br", "cr"}:
+ parts.append(" ")
+ return "".join(parts).strip()
+
+
+def _docx_table_has_media(table: ET.Element) -> bool:
+ """Return whether a table contains image-bearing nodes."""
+ return any(_local_name(elem) in {"drawing", "imagedata"} for elem in table.iter())
+
+
+def _docx_table_cell_text(cell: ET.Element) -> str:
+ """Extract table-cell text, preserving paragraph breaks as Markdown breaks."""
+ paragraphs: list[str] = []
+ for child in cell:
+ if _local_name(child) == "p":
+ text = _docx_paragraph_text(child)
+ if text:
+ paragraphs.append(text)
+ return "<br>".join(paragraphs)
+
+
+def _markdown_table_cell(text: str) -> str:
+ """Escape Markdown table delimiters in one cell."""
+ text = re.sub(r"[ \t\r\n]+", " ", text).strip()
+ return text.replace("|", r"\|")
+
+
+def _docx_table_to_markdown(table: ET.Element) -> str:
+ """Convert a Word table XML node to a pipe Markdown table."""
+ rows: list[list[str]] = []
+ for row in table.findall("w:tr", DOCX_NS):
+ cells = [
+ _markdown_table_cell(_docx_table_cell_text(cell))
+ for cell in row.findall("w:tc", DOCX_NS)
+ ]
+ if cells:
+ rows.append(cells)
+ if not rows:
+ return ""
+
+ width = max(len(row) for row in rows)
+ rows = [row + [""] * (width - len(row)) for row in rows]
+ header, body = rows[0], rows[1:]
+ lines = [
+ "| " + " | ".join(header) + " |",
+ "| " + " | ".join("---" for _ in range(width)) + " |",
+ ]
+ lines.extend("| " + " | ".join(row) + " |" for row in body)
+ return "\n".join(lines)
+
+
+def _docx_inject_tables_markdown(
+ input_file: Path,
+) -> tuple[Path, dict[str, str]] | None:
+ """Replace text-only DOCX tables with Markdown placeholders in a temp DOCX."""
+ try:
+ with zipfile.ZipFile(input_file) as docx:
+ document_xml = docx.read("word/document.xml")
+ except (KeyError, zipfile.BadZipFile, OSError):
+ return None
+ try:
+ root = ET.fromstring(document_xml)
+ except ET.ParseError:
+ return None
+
+ parent_map = {child: parent for parent in root.iter() for child in parent}
+ token_base = uuid.uuid4().hex
+ replacements: dict[str, str] = {}
+ for index, table in enumerate(root.findall(".//w:tbl", DOCX_NS)):
+ if _docx_table_has_media(table):
+ continue
+ markdown = _docx_table_to_markdown(table)
+ if not markdown:
+ continue
+ parent = parent_map.get(table)
+ if parent is None:
+ continue
+ position = list(parent).index(table)
+ token = f"MARKDOWNTABLE{token_base}{index:04d}"
+ parent.remove(table)
+ parent.insert(position, _make_text_paragraph(token))
+ replacements[token] = markdown
+ if not replacements:
+ return None
+
+ for prefix, uri in DOCX_NS.items():
+ if prefix != "rel":
+ ET.register_namespace(prefix, uri)
+ patched_xml = ET.tostring(root, encoding="utf-8", xml_declaration=True)
+
+ tmp = tempfile.NamedTemporaryFile(suffix=".docx", delete=False)
+ tmp.close()
+ out_path = Path(tmp.name)
+ with zipfile.ZipFile(input_file) as zin, \
+ zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zout:
+ for item in zin.infolist():
+ data = patched_xml if item.filename == "word/document.xml" else zin.read(item.filename)
+ zout.writestr(item, data)
+ return out_path, replacements
+
+
+def _clean_mammoth_markdown(markdown: str) -> str:
+ """Remove Mammoth escapes for punctuation that is safe as literal text."""
+ def _repl(match: re.Match[str]) -> str:
+ char = match.group(1)
+ if char == ".":
+ line_start = markdown.rfind("\n", 0, match.start()) + 1
+ line_prefix = markdown[line_start:match.start()]
+ if re.fullmatch(r"\s*\d+", line_prefix):
+ return match.group(0)
+ return char
+
+ return re.sub(r"\\([.(),:])", _repl, markdown)
+
+
# ─────────────────────────────────────────────────────────────
# DOCX → Markdown (mammoth)
# ─────────────────────────────────────────────────────────────
@@ -743,7 +878,13 @@ def _convert_docx(input_file: Path, out_file: Path) -> str:
math_file, math_replacements = math_injection
else:
math_file, math_replacements = None, {}
+ table_file = None
+ table_replacements: dict[str, str] = {}
mammoth_source = math_file or input_file
+ table_injection = _docx_inject_tables_markdown(mammoth_source)
+ if table_injection is not None:
+ table_file, table_replacements = table_injection
+ mammoth_source = table_file
try:
with mammoth_source.open("rb") as f:
result = mammoth.convert_to_markdown(
@@ -751,6 +892,11 @@ def _convert_docx(input_file: Path, out_file: Path) -> str:
convert_image=mammoth.images.img_element(_save_image),
)
finally:
+ if table_file is not None:
+ try:
+ table_file.unlink()
+ except OSError:
+ pass
if math_file is not None:
try:
math_file.unlink()
@@ -758,9 +904,12 @@ def _convert_docx(input_file: Path, out_file: Path) -> str:
pass
markdown = result.value
+ for token, table_markdown in table_replacements.items():
+ markdown = markdown.replace(token, table_markdown)
for token, latex in math_replacements.items():
markdown = markdown.replace(token, latex)
markdown = _html_img_to_md(markdown)
+ markdown = _clean_mammoth_markdown(markdown)
out_file.write_text(markdown, encoding="utf-8")
if manifest: