Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.
Python agent-skillsai-agentsbook-to-skillcontext-engineeringdocument-processingedtechknowledge-baseknowledge-managementllmpdf-to-markdownragself-studystudy-tools
feat(docx): reconstruct tables as tab-joined rows in the stdlib fallback (#61)
Shubham Srivastava94e7b82bdbdd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 32461b5..411d104 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The stdlib HTML parser (the fallback for HTML files and EPUB extraction whenBeautifulSoup is not installed) no longer decodes HTML entities twice, sodouble-encoded entities such as `&amp;` survive intact.+- The dependency-free DOCX fallback (used when `python-docx` is not installed)+ now reconstructs tables as tab-joined rows in document order, instead of+ flattening each cell onto its own line.## [1.2.0] — 2026-06-17diff --git a/book_to_skill/parsers/docx.py b/book_to_skill/parsers/docx.pyindex 52bf22b..879d8d1 100644--- a/book_to_skill/parsers/docx.py+++ b/book_to_skill/parsers/docx.py@@ -30,12 +30,38 @@ def extract_docx_with_zipfile(docx_path: str) -> str | None:with zipfile.ZipFile(docx_path) as zf:xml_bytes = zf.read("word/document.xml")root = ET.fromstring(xml_bytes)- namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"+ ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"parts: list[str] = []- for paragraph in root.iter(f"{namespace}p"):- texts = [node.text for node in paragraph.iter(f"{namespace}t") if node.text]- if texts:- parts.append("".join(texts))++ 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+ # python-docx path, but order-preserving — python-docx appends all+ # tables last). Unknown wrappers (e.g. <w:sdt> content controls) are+ # recursed into so their paragraphs/tables are not lost; <w:p> and+ # <w:tbl> are NOT recursed into, so table-cell paragraphs are not+ # double-counted. Cell text concatenates the cell's runs; nested+ # tables fold into the parent cell and are also emitted standalone+ # (rare; best-effort).+ for child in elem:+ tag = child.tag+ if tag == f"{ns}p":+ texts = [t.text for t in child.iter(f"{ns}t") if t.text]+ if texts:+ parts.append("".join(texts))+ elif tag == f"{ns}tbl":+ for row in child.iter(f"{ns}tr"):+ cells = []+ for cell in row.iter(f"{ns}tc"):+ cell_texts = [t.text for t in cell.iter(f"{ns}t") if t.text]+ cells.append("".join(cell_texts).strip())+ if any(cells):+ parts.append("\t".join(cells))+ else:+ emit_block(child)++ body = root.find(f"{ns}body")+ emit_block(body if body is not None else root)return "\n".join(parts) if parts else Noneexcept Exception as e:print(f" [warn] extract_docx_with_zipfile failed: {type(e).__name__}: {e}", file=sys.stderr)diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.pyindex e8cfdef..145a566 100644--- a/tests/test_book_to_skill.py+++ b/tests/test_book_to_skill.py@@ -34,6 +34,7 @@ from book_to_skill.utils import (main,)from book_to_skill.config import SUPPORTED_EXTENSIONS+from book_to_skill.parsers.docx import extract_docx_with_zipfilefrom book_to_skill.parsers.rtf import strip_rtf_fallback@@ -1065,3 +1066,71 @@ class TestHtmlEntityDecoding:def test_skip_tag_content_excluded(self):# Confirms the change didn't disturb skip-tag handling.assert self._text("<style>x{}</style>keep") == "keep"+++class TestDocxTableReconstruction:+ """The stdlib DOCX fallback tab-joins table rows and preserves order."""++ _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"?>'+ f'<w:document xmlns:w="{self._NS}"><w:body>{body_xml}</w:body></w:document>'+ )+ with zipfile.ZipFile(p, "w") as zf:+ zf.writestr("word/document.xml", doc)+ return str(p)++ def _para(self, text):+ return f"<w:p><w:r><w:t>{text}</w:t></w:r></w:p>"++ def _cell(self, text):+ return f"<w:tc><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:tc>"++ def test_table_rows_are_tab_joined(self, tmp_path):+ body = (+ self._para("Intro")+ + "<w:tbl><w:tr>" + self._cell("Name") + self._cell("Value") + "</w:tr>"+ + "<w:tr>" + self._cell("foo") + self._cell("1") + "</w:tr></w:tbl>"+ )+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))+ assert "Name\tValue" in out+ assert "foo\t1" in out++ def test_document_order_preserved(self, tmp_path):+ body = (+ self._para("Before")+ + "<w:tbl><w:tr>" + self._cell("R1C1") + self._cell("R1C2") + "</w:tr></w:tbl>"+ + self._para("After")+ )+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))+ assert out.index("Before") < out.index("R1C1") < out.index("After")++ def test_paragraph_only_document_unchanged(self, tmp_path):+ body = self._para("Just a paragraph") + self._para("And another")+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))+ assert out == "Just a paragraph\nAnd another"++ def test_empty_cell_still_tab_joined(self, tmp_path):+ body = (+ "<w:tbl><w:tr>" + self._cell("A")+ + "<w:tc><w:p></w:p></w:tc></w:tr></w:tbl>"+ )+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))+ # "\t".join(["A", ""]) -> "A\t"; the empty cell becomes an empty field.+ assert out == "A\t"++ def test_sdt_wrapped_content_is_preserved(self, tmp_path):+ # Word wraps TOC/cover-page/form content in <w:sdt> content controls,+ # which are direct children of <w:body> but not <w:p>/<w:tbl>. The+ # recursive walk must still find paragraphs/tables inside them.+ body = (+ self._para("Before")+ + "<w:sdt><w:sdtContent>" + self._para("Inside SDT") + "</w:sdtContent></w:sdt>"+ + self._para("After")+ )+ out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))+ assert out == "Before\nInside SDT\nAfter"