Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix(docx): preserve SDT wrapped paragraphs (#270)

Ha1baraA1d26a4f27ee76
diff --git a/book_to_skill/parsers/docx.py b/book_to_skill/parsers/docx.py
index 9569eea..4e78fd0 100644
--- a/book_to_skill/parsers/docx.py
+++ b/book_to_skill/parsers/docx.py
@@ -1,10 +1,25 @@
from __future__ import annotations
+from collections import Counter
import zipfile
import sys
from book_to_skill.exceptions import ExtractionError
+def _docx_inline_text(elem) -> str:
+ """Rebuild text runs without dropping explicit DOCX separators."""
+ ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
+ text_parts: list[str] = []
+ for node in elem.iter():
+ if node.tag == f"{ns}t" and node.text:
+ text_parts.append(node.text)
+ elif node.tag == f"{ns}tab":
+ text_parts.append("\t")
+ elif node.tag in {f"{ns}br", f"{ns}cr"}:
+ text_parts.append("\n")
+ return "".join(text_parts)
+
+
def extract_docx_with_python_docx(docx_path: str) -> str | None:
# Called unconditionally (not just via extract_docx()) so this function is
# self-defending when invoked directly WITH python-docx installed:
@@ -63,18 +78,6 @@ def extract_docx_with_zipfile(docx_path: str) -> str | None:
ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
parts: list[str] = []
- def inline_text(elem) -> str:
- """Rebuild text runs without dropping explicit DOCX separators."""
- text_parts: list[str] = []
- for node in elem.iter():
- if node.tag == f"{ns}t" and node.text:
- text_parts.append(node.text)
- elif node.tag == f"{ns}tab":
- text_parts.append("\t")
- elif node.tag in {f"{ns}br", f"{ns}cr"}:
- text_parts.append("\n")
- return "".join(text_parts)
-
def emit_block(elem) -> None:
# Walk block content in document order. Paragraphs join their runs;
# tables emit one tab-joined line per row (same row format as the
@@ -88,14 +91,14 @@ def extract_docx_with_zipfile(docx_path: str) -> str | None:
for child in elem:
tag = child.tag
if tag == f"{ns}p":
- paragraph = inline_text(child)
+ paragraph = _docx_inline_text(child)
if paragraph:
parts.append(paragraph)
elif tag == f"{ns}tbl":
for row in child.iter(f"{ns}tr"):
cells = []
for cell in row.iter(f"{ns}tc"):
- cells.append(inline_text(cell).strip())
+ cells.append(_docx_inline_text(cell).strip())
if any(cells):
parts.append("\t".join(cells))
else:
@@ -133,6 +136,50 @@ def validate_docx_xml_safety(docx_path: str) -> None:
raise ExtractionError(f"Error during security validation of DOCX archive: {e}")
+def _docx_sdt_text_fragments(docx_path: str) -> list[str] | None:
+ """Return non-empty paragraph text inside content controls.
+
+ This is called only after the preferred parser has validated the archive.
+ If the document XML cannot be inspected, let the caller try the stdlib
+ parser as a best-effort fallback and compare output lengths.
+ """
+ import xml.etree.ElementTree as ET
+
+ try:
+ with zipfile.ZipFile(docx_path) as zf:
+ root = ET.fromstring(zf.read("word/document.xml"))
+ except (KeyError, OSError, zipfile.BadZipFile, ET.ParseError):
+ return None
+
+ ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
+ fragments: list[str] = []
+ seen_paragraphs: set[int] = set()
+ for sdt in root.iter(f"{ns}sdt"):
+ for content in sdt.iter(f"{ns}sdtContent"):
+ for paragraph in content.iter(f"{ns}p"):
+ paragraph_id = id(paragraph)
+ if paragraph_id in seen_paragraphs:
+ continue
+ seen_paragraphs.add(paragraph_id)
+ if text := _docx_inline_text(paragraph).strip():
+ fragments.append(text)
+ return fragments
+
+
+def _sdt_coverage(text: str, fragments: list[str]) -> int:
+ """Score matching normalized paragraph occurrences in parser output."""
+ output_paragraphs = Counter(
+ normalized
+ for line in text.splitlines()
+ if (normalized := " ".join(line.split()))
+ )
+ fragment_counts = Counter(" ".join(fragment.split()) for fragment in fragments)
+ return sum(
+ len(fragment) * min(count, output_paragraphs[fragment])
+ for fragment, count in fragment_counts.items()
+ )
+
+
def extract_docx(docx_path: str) -> tuple[str, str]:
# Validation lives in each leaf parser (extract_docx_with_python_docx,
# extract_docx_with_zipfile) so it runs exactly once regardless of which
@@ -141,7 +188,21 @@ def extract_docx(docx_path: str) -> tuple[str, str]:
print("Trying python-docx...", end=" ", flush=True)
text = extract_docx_with_python_docx(docx_path)
if text and text.strip():
- print("OK")
+ sdt_fragments = _docx_sdt_text_fragments(docx_path)
+ if sdt_fragments is None or sdt_fragments:
+ print("OK; SDT content control detected")
+ print("Trying stdlib DOCX parser...", end=" ", flush=True)
+ fallback_text = extract_docx_with_zipfile(docx_path)
+ if fallback_text and (
+ (_sdt_coverage(fallback_text, sdt_fragments) > _sdt_coverage(text, sdt_fragments))
+ if sdt_fragments is not None
+ else len(fallback_text.strip()) > len(text.strip())
+ ):
+ print("OK (more complete output)")
+ return fallback_text, "zipfile-docx"
+ print("keeping python-docx result")
+ else:
+ print("OK")
return text, "python-docx"
print("not available")
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 7bc6a57..d731b68 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -1967,7 +1967,6 @@ class TestDocxTableReconstruction:
_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def _make_docx(self, tmp_path, body_xml):
- import zipfile
p = tmp_path / "t.docx"
doc = (
'<?xml version="1.0"?>'
@@ -2044,6 +2043,127 @@ class TestDocxTableReconstruction:
out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))
assert out == "Before\nInside SDT\nAfter"
+ def test_dispatcher_uses_more_complete_output_for_sdt(self, tmp_path):
+ from book_to_skill.parsers import docx as docx_parser
+
+ body = (
+ self._para("Before")
+ + "<w:sdt><w:sdtContent>" + self._para("Inside SDT") + "</w:sdtContent></w:sdt>"
+ + self._para("After")
+ )
+ docx_path = self._make_docx(tmp_path, body)
+ with mock.patch.object(
+ docx_parser,
+ "extract_docx_with_python_docx",
+ return_value="Before\nAfter",
+ ):
+ text, method = docx_parser.extract_docx(docx_path)
+
+ assert method == "zipfile-docx"
+ assert text == "Before\nInside SDT\nAfter"
+
+ def test_dispatcher_prefers_sdt_coverage_over_longer_output(self, tmp_path):
+ from book_to_skill.parsers import docx as docx_parser
+
+ body = (
+ self._para("Before")
+ + "<w:sdt><w:sdtContent>" + self._para("X") + "</w:sdtContent></w:sdt>"
+ + self._para("After")
+ )
+ docx_path = self._make_docx(tmp_path, body)
+ preferred = "Before\n" + "long ordinary paragraph " * 20 + "\nAfter"
+ with mock.patch.object(
+ docx_parser,
+ "extract_docx_with_python_docx",
+ return_value=preferred,
+ ):
+ text, method = docx_parser.extract_docx(docx_path)
+
+ assert len(text) < len(preferred)
+ assert method == "zipfile-docx"
+ assert text == "Before\nX\nAfter"
+
+ def test_dispatcher_does_not_match_sdt_paragraph_inside_another_paragraph(self, tmp_path):
+ from book_to_skill.parsers import docx as docx_parser
+
+ body = (
+ self._para("Chapter 10")
+ + "<w:sdt><w:sdtContent>" + self._para("1") + "</w:sdtContent></w:sdt>"
+ )
+ docx_path = self._make_docx(tmp_path, body)
+ preferred = "Chapter 10\n" + "long ordinary paragraph " * 20
+ with mock.patch.object(
+ docx_parser,
+ "extract_docx_with_python_docx",
+ return_value=preferred,
+ ):
+ text, method = docx_parser.extract_docx(docx_path)
+
+ assert len(text) < len(preferred)
+ assert method == "zipfile-docx"
+ assert text == "Chapter 10\n1"
+
+ def test_dispatcher_counts_repeated_sdt_paragraphs(self, tmp_path):
+ from book_to_skill.parsers import docx as docx_parser
+
+ body = (
+ "<w:sdt><w:sdtContent>"
+ + self._para("Repeated")
+ + self._para("Repeated")
+ + "</w:sdtContent></w:sdt>"
+ )
+ docx_path = self._make_docx(tmp_path, body)
+ preferred = "Repeated\n" + "long ordinary paragraph " * 20
+ with mock.patch.object(
+ docx_parser,
+ "extract_docx_with_python_docx",
+ return_value=preferred,
+ ):
+ text, method = docx_parser.extract_docx(docx_path)
+
+ assert len(text) < len(preferred)
+ assert method == "zipfile-docx"
+ assert text == "Repeated\nRepeated"
+
+ def test_dispatcher_keeps_preferred_when_fallback_adds_no_sdt_coverage(self, tmp_path):
+ from book_to_skill.parsers import docx as docx_parser
+
+ body = (
+ self._para("ordinary paragraph " * 20)
+ + "<w:sdt><w:sdtContent>" + self._para("Inside SDT") + "</w:sdtContent></w:sdt>"
+ )
+ docx_path = self._make_docx(tmp_path, body)
+ preferred = "Inside SDT"
+ with mock.patch.object(
+ docx_parser,
+ "extract_docx_with_python_docx",
+ return_value=preferred,
+ ):
+ text, method = docx_parser.extract_docx(docx_path)
+
+ assert len(docx_parser.extract_docx_with_zipfile(docx_path)) > len(preferred)
+ assert method == "python-docx"
+ assert text == preferred
+
+ def test_dispatcher_keeps_preferred_parser_without_sdt(self, tmp_path):
+ from book_to_skill.parsers import docx as docx_parser
+
+ docx_path = self._make_docx(tmp_path, self._para("Ordinary document"))
+ with mock.patch.object(
+ docx_parser,
+ "extract_docx_with_python_docx",
+ return_value="Preferred parser output",
+ ), mock.patch.object(
+ docx_parser,
+ "extract_docx_with_zipfile",
+ wraps=docx_parser.extract_docx_with_zipfile,
+ ) as fallback:
+ text, method = docx_parser.extract_docx(docx_path)
+
+ assert method == "python-docx"
+ assert text == "Preferred parser output"
+ fallback.assert_not_called()
+
class TestEpubSpineOrder:
"""The stdlib EPUB extractor reads content in spine order, with a safety net."""