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 paragraph and table order (#265)

Ha1baraA1313bf68a6700
diff --git a/book_to_skill/parsers/docx.py b/book_to_skill/parsers/docx.py
index a8e3a6c..9569eea 100644
--- a/book_to_skill/parsers/docx.py
+++ b/book_to_skill/parsers/docx.py
@@ -22,12 +22,20 @@ def extract_docx_with_python_docx(docx_path: str) -> str | None:
import docx
validate_docx_xml_safety(docx_path)
document = docx.Document(docx_path)
- parts = [paragraph.text for paragraph in document.paragraphs if paragraph.text]
- for table in document.tables:
- for row in table.rows:
- cells = [cell.text.strip() for cell in row.cells]
- if any(cells):
- parts.append("\t".join(cells))
+ iter_inner_content = getattr(document, "iter_inner_content", None)
+ if not callable(iter_inner_content):
+ # Older python-docx releases lack the ordered block iterator. Let
+ # extract_docx() use its order-preserving stdlib fallback instead.
+ return None
+ parts = []
+ for block in iter_inner_content():
+ if hasattr(block, "rows"):
+ for row in block.rows:
+ cells = [cell.text.strip() for cell in row.cells]
+ if any(cells):
+ parts.append("\t".join(cells))
+ elif hasattr(block, "text") and block.text:
+ parts.append(block.text)
return "\n".join(parts)
except ImportError:
return None
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 1937e29..3816375 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -1514,7 +1514,40 @@ class TestHtmlExtraction:
class TestDocxExtraction:
- """Tests for DOCX extraction via the zipfile fallback."""
+ """Tests for the preferred python-docx parser and the stdlib fallback."""
+
+ def test_extract_docx_python_docx_preserves_document_order(self, tmp_path):
+ from types import SimpleNamespace
+
+ from book_to_skill.parsers.docx import extract_docx_with_python_docx
+
+ docx_path = _make_minimal_docx(tmp_path / "interleaved.docx")
+ document = mock.Mock()
+ document.iter_inner_content.return_value = [
+ SimpleNamespace(text="Chapter 1: Validation"),
+ SimpleNamespace(
+ rows=[
+ SimpleNamespace(
+ cells=[
+ SimpleNamespace(text="CH1_RULE"),
+ SimpleNamespace(text="Reject negative balances."),
+ ]
+ )
+ ]
+ ),
+ SimpleNamespace(text="Chapter 2: Settlement"),
+ ]
+ python_docx = mock.Mock()
+ python_docx.Document.return_value = document
+
+ with mock.patch.dict(sys.modules, {"docx": python_docx}):
+ result = extract_docx_with_python_docx(str(docx_path))
+
+ assert result == (
+ "Chapter 1: Validation\n"
+ "CH1_RULE\tReject negative balances.\n"
+ "Chapter 2: Settlement"
+ )
def test_extract_docx_zipfile_fallback(self, tmp_path):
docx = _make_minimal_docx(tmp_path / "test.docx")