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
fix(epub): preserve spine order with prefixed OPF elements (#249)
Stamina9c108d25b0cb5
diff --git a/book_to_skill/parsers/epub.py b/book_to_skill/parsers/epub.pyindex 1cb3f65..95fd50d 100644--- a/book_to_skill/parsers/epub.py+++ b/book_to_skill/parsers/epub.py@@ -23,6 +23,19 @@ _IMAGE_EXTENSIONS = (".webp",)+# OPF package elements normally use the default OPF namespace, but XML also+# permits an explicit namespace prefix (for example ``<opf:item>``). Keep the+# existing tolerant, regex-based fallback while accepting that equivalent form.+_OPF_ELEMENT_PREFIX = r"(?:[A-Za-z_][\w.-]*:)?"+++def _opf_opening_tags(opf_text: str, local_name: str) -> list[str]:+ """Return opening tags for an OPF element, with or without a prefix."""+ return re.findall(+ rf"<{_OPF_ELEMENT_PREFIX}{re.escape(local_name)}\b[^>]*?/?>",+ opf_text,+ )+def extract_with_ebooklib(epub_path: str) -> str | None:try:@@ -96,7 +109,7 @@ def extract_with_zipfile(epub_path: str) -> str | None:# both self-closing <item .../> and <item ...></item> forms work# because all attributes live in the opening tag.manifest: dict[str, str] = {}- for item_tag in re.findall(r"<item\b[^>]*?/?>", opf_text):+ for item_tag in _opf_opening_tags(opf_text, "item"):id_m = re.search(r'\bid=["\']([^"\']+)["\']', item_tag)href_m = re.search(r'\bhref=["\']([^"\']+)["\']', item_tag)if id_m and href_m:@@ -104,8 +117,13 @@ def extract_with_zipfile(epub_path: str) -> str | None:manifest[id_m.group(1)] = resolved# Spine: ordered idrefs -> hrefs (true reading order).- for idref in re.findall(r'<itemref\b[^>]*?\bidref=["\']([^"\']+)["\']', opf_text):- href = manifest.get(idref)+ for itemref_tag in _opf_opening_tags(opf_text, "itemref"):+ idref_m = re.search(+ r'\bidref=["\']([^"\']+)["\']', itemref_tag+ )+ if not idref_m:+ continue+ href = manifest.get(idref_m.group(1))if href and href not in seen:spine_order.append(href)seen.add(href)@@ -146,7 +164,7 @@ def count_epub_chapters(epub_path: str) -> int:if not opf_path:return 0opf_text = zf.read(opf_path).decode("utf-8", errors="replace")- return len(re.findall(r'<itemref\b', opf_text))+ return len(_opf_opening_tags(opf_text, "itemref"))except Exception:return 0diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.pyindex 02131ec..f1c0779 100644--- a/tests/test_book_to_skill.py+++ b/tests/test_book_to_skill.py@@ -38,7 +38,7 @@ from book_to_skill.parsers import pdf as pdf_parserfrom book_to_skill.parsers.text import read_text_filefrom book_to_skill.parsers.docx import extract_docx_with_zipfilefrom book_to_skill.parsers.rtf import strip_rtf_fallback-from book_to_skill.parsers.epub import extract_with_zipfile+from book_to_skill.parsers.epub import count_epub_chapters, extract_with_zipfile# ═══════════════════════════════════════════════════════════════════════════@@ -1910,6 +1910,32 @@ class TestEpubSpineOrder:out = extract_with_zipfile(self._make_epub(tmp_path, opf, files))assert out.index("FIRST") < out.index("SECOND")+ def test_prefixed_opf_elements_preserve_spine_order_and_count(self, tmp_path):+ # XML namespace prefixes are semantically equivalent to the default OPF+ # namespace. File names deliberately sort opposite to the spine so a+ # missed prefixed manifest/spine cannot pass through the sorted fallback.+ opf = (+ '<opf:package xmlns:opf="http://www.idpf.org/2007/opf" version="3.0">'+ '<opf:manifest>'+ '<opf:item id="c1" href="z-first.xhtml" '+ 'media-type="application/xhtml+xml"/>'+ '<opf:item id="c2" href="a-second.xhtml" '+ 'media-type="application/xhtml+xml"/>'+ '</opf:manifest><opf:spine>'+ '<opf:itemref idref="c1"/><opf:itemref idref="c2"/>'+ '</opf:spine></opf:package>'+ )+ files = {+ "z-first.xhtml": self._doc("FIRST"),+ "a-second.xhtml": self._doc("SECOND"),+ }+ epub_path = self._make_epub(tmp_path, opf, files)++ out = extract_with_zipfile(epub_path)++ assert out.index("FIRST") < out.index("SECOND")+ assert count_epub_chapters(epub_path) == 2+def test_non_spine_doc_kept_as_safety_net_after_spine(self, tmp_path):opf = ('<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest>'