Skip to content

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

fix(epub): read content in spine order in the stdlib extractor (#64)

Shubham Srivastava48f4c4471bd6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 411d104..7a82d2c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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.
+- The dependency-free EPUB extractor (used when `ebooklib` is not installed) now
+ reads content in true spine (reading) order instead of manifest order, so
+ chapters are no longer scrambled. Content documents not listed in the spine are
+ still included (appended after the spine content).
## [1.2.0] — 2026-06-17
diff --git a/book_to_skill/parsers/epub.py b/book_to_skill/parsers/epub.py
index 71c7403..eedfd8a 100644
--- a/book_to_skill/parsers/epub.py
+++ b/book_to_skill/parsers/epub.py
@@ -56,15 +56,39 @@ def extract_with_zipfile(epub_path: str) -> str | None:
opf_path = _find_opf_path(zf)
opf_dir = posixpath.dirname(opf_path) if opf_path else ""
- # Read OPF spine to get reading order, fall back to sorted xhtml files
+ # Build reading order from the OPF spine (not the manifest's href
+ # order), then append any remaining content docs as a safety net.
spine_order: list[str] = []
+ seen: set[str] = set()
if opf_path:
opf_text = zf.read(opf_path).decode("utf-8", errors="replace")
- raw_hrefs = re.findall(r'href=["\']([^"\']+\.(?:xhtml|html))["\']', opf_text)
- # Resolve hrefs relative to the OPF directory
- for href in raw_hrefs:
- resolved = posixpath.normpath(posixpath.join(opf_dir, href)) if opf_dir else href
- spine_order.append(resolved)
+
+ # Manifest: item id -> resolved href. Parse each <item> opening
+ # tag so attribute order (id before/after href) does not matter;
+ # 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):
+ id_m = re.search(r'\bid=["\']([^"\']+)["\']', item_tag)
+ href_m = re.search(r'\bhref=["\']([^"\']+)["\']', item_tag)
+ if id_m and href_m:
+ href = href_m.group(1)
+ resolved = posixpath.normpath(posixpath.join(opf_dir, href)) if opf_dir else href
+ 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)
+ if href and href not in seen:
+ spine_order.append(href)
+ seen.add(href)
+
+ # Safety net: append remaining manifest content documents (e.g. a
+ # nav doc not in the spine) in manifest order, so nothing is lost.
+ for href in manifest.values():
+ if href.endswith((".html", ".xhtml")) and href not in seen:
+ spine_order.append(href)
+ seen.add(href)
html_files = spine_order or sorted(
n for n in names if n.endswith((".html", ".xhtml"))
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 145a566..e42b665 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -36,6 +36,7 @@ from book_to_skill.utils import (
from book_to_skill.config import SUPPORTED_EXTENSIONS
from book_to_skill.parsers.docx import extract_docx_with_zipfile
from book_to_skill.parsers.rtf import strip_rtf_fallback
+from book_to_skill.parsers.epub import extract_with_zipfile
# ═══════════════════════════════════════════════════════════════════════════
@@ -1134,3 +1135,104 @@ class TestDocxTableReconstruction:
)
out = extract_docx_with_zipfile(self._make_docx(tmp_path, body))
assert out == "Before\nInside SDT\nAfter"
+
+
+class TestEpubSpineOrder:
+ """The stdlib EPUB extractor reads content in spine order, with a safety net."""
+
+ def _make_epub(self, tmp_path, opf_xml, files, opf_name="content.opf"):
+ p = tmp_path / "book.epub"
+ with zipfile.ZipFile(p, "w") as zf:
+ zf.writestr("mimetype", "application/epub+zip")
+ zf.writestr(
+ "META-INF/container.xml",
+ '<?xml version="1.0"?>'
+ '<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">'
+ f'<rootfiles><rootfile full-path="{opf_name}" media-type="application/oebps-package+xml"/></rootfiles>'
+ '</container>',
+ )
+ zf.writestr(opf_name, opf_xml)
+ for name, html in files.items():
+ zf.writestr(name, html)
+ return str(p)
+
+ def _doc(self, text):
+ return f"<html><body><p>{text}</p></body></html>"
+
+ def test_spine_order_overrides_manifest_order(self, tmp_path):
+ opf = (
+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest>'
+ '<item id="c2" href="ch2.xhtml" media-type="application/xhtml+xml"/>'
+ '<item id="c1" href="ch1.xhtml" media-type="application/xhtml+xml"/>'
+ '</manifest><spine><itemref idref="c1"/><itemref idref="c2"/></spine></package>'
+ )
+ files = {"ch1.xhtml": self._doc("FIRST"), "ch2.xhtml": self._doc("SECOND")}
+ out = extract_with_zipfile(self._make_epub(tmp_path, opf, files))
+ assert out.index("FIRST") < out.index("SECOND")
+
+ 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>'
+ '<item id="c1" href="ch1.xhtml" media-type="application/xhtml+xml"/>'
+ '<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml"/>'
+ '</manifest><spine><itemref idref="c1"/></spine></package>'
+ )
+ files = {"ch1.xhtml": self._doc("CONTENT"), "nav.xhtml": self._doc("NAVTOC")}
+ out = extract_with_zipfile(self._make_epub(tmp_path, opf, files))
+ assert "NAVTOC" in out
+ assert out.index("CONTENT") < out.index("NAVTOC")
+
+ def test_item_attribute_order_robust(self, tmp_path):
+ opf = (
+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest>'
+ '<item href="only.xhtml" id="c1" media-type="application/xhtml+xml"/>'
+ '</manifest><spine><itemref idref="c1"/></spine></package>'
+ )
+ files = {"only.xhtml": self._doc("ONLY")}
+ out = extract_with_zipfile(self._make_epub(tmp_path, opf, files))
+ assert "ONLY" in out
+
+ def test_spine_absent_uses_safety_net(self, tmp_path):
+ # No <spine>: the manifest content doc is still included via the safety net.
+ opf = (
+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest>'
+ '<item id="a" href="a.xhtml" media-type="application/xhtml+xml"/>'
+ '</manifest></package>'
+ )
+ files = {"a.xhtml": self._doc("ALPHA")}
+ out = extract_with_zipfile(self._make_epub(tmp_path, opf, files))
+ assert "ALPHA" in out
+
+ def test_opf_in_subdir_resolves_hrefs(self, tmp_path):
+ opf = (
+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest>'
+ '<item id="c1" href="ch1.xhtml" media-type="application/xhtml+xml"/>'
+ '</manifest><spine><itemref idref="c1"/></spine></package>'
+ )
+ files = {"OEBPS/ch1.xhtml": self._doc("SUBDIR")}
+ out = extract_with_zipfile(
+ self._make_epub(tmp_path, opf, files, opf_name="OEBPS/content.opf")
+ )
+ assert "SUBDIR" in out
+
+ def test_non_self_closing_item_tag(self, tmp_path):
+ # <item ...></item> (non-self-closing) is parsed via its opening tag.
+ opf = (
+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest>'
+ '<item id="c1" href="ch1.xhtml" media-type="application/xhtml+xml"></item>'
+ '</manifest><spine><itemref idref="c1"></itemref></spine></package>'
+ )
+ files = {"ch1.xhtml": self._doc("NONSELFCLOSE")}
+ out = extract_with_zipfile(self._make_epub(tmp_path, opf, files))
+ assert "NONSELFCLOSE" in out
+
+ def test_no_opf_falls_back_to_sorted_files(self, tmp_path):
+ # No container.xml / no OPF at all: the final fallback reads sorted
+ # content files from the zip.
+ p = tmp_path / "noopf.epub"
+ with zipfile.ZipFile(p, "w") as zf:
+ zf.writestr("mimetype", "application/epub+zip")
+ zf.writestr("a.xhtml", self._doc("AAA"))
+ zf.writestr("b.xhtml", self._doc("BBB"))
+ out = extract_with_zipfile(str(p))
+ assert "AAA" in out and "BBB" in out