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): decode UTF-16 XML in stdlib fallback (#311)
Stamina97540eefbe749
diff --git a/book_to_skill/parsers/epub.py b/book_to_skill/parsers/epub.pyindex f3caa14..8118a6d 100644--- a/book_to_skill/parsers/epub.py+++ b/book_to_skill/parsers/epub.py@@ -1,5 +1,6 @@from __future__ import annotations+import codecsimport htmlimport posixpathimport re@@ -29,6 +30,17 @@ _IMAGE_EXTENSIONS = (_OPF_ELEMENT_PREFIX = r"(?:[A-Za-z_][\w.-]*:)?"+def _decode_epub_xml(data: bytes) -> str:+ """Decode BOM-marked UTF-16 XML, retaining the existing UTF-8 fallback."""+ # UTF-32 LE starts with the UTF-16 LE BOM. EPUB XML requires UTF-8 or+ # UTF-16; leave UTF-32 on the historical UTF-8 replacement path.+ if not data.startswith(codecs.BOM_UTF32_LE) and data.startswith(+ (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)+ ):+ return data.decode("utf-16", errors="replace")+ return data.decode("utf-8", errors="replace")++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(@@ -84,7 +96,7 @@ def _find_opf_path(zf: zipfile.ZipFile) -> str | None:"""# Spec-defined: read container.xml for the rootfile pathtry:- container = zf.read("META-INF/container.xml").decode("utf-8", errors="replace")+ container = _decode_epub_xml(zf.read("META-INF/container.xml"))match = re.search(r'full-path=["\']([^"\']+\.opf)["\']', container)if match:return match.group(1)@@ -122,7 +134,7 @@ def extract_with_zipfile(epub_path: str) -> str | None:spine_order: list[str] = []seen: set[str] = set()if opf_path:- opf_text = zf.read(opf_path).decode("utf-8", errors="replace")+ opf_text = _decode_epub_xml(zf.read(opf_path))# Manifest: item id -> resolved href. Parse each <item> opening# tag so attribute order (id before/after href) does not matter;@@ -164,7 +176,7 @@ def extract_with_zipfile(epub_path: str) -> str | None:parts = []for name in html_files:try:- raw = zf.read(name).decode("utf-8", errors="replace")+ raw = _decode_epub_xml(zf.read(name))parser = _HTMLTextExtractor()parser.feed(raw)parts.append(parser.get_text())@@ -183,7 +195,7 @@ def count_epub_chapters(epub_path: str) -> int:opf_path = _find_opf_path(zf)if not opf_path:return 0- opf_text = zf.read(opf_path).decode("utf-8", errors="replace")+ opf_text = _decode_epub_xml(zf.read(opf_path))return len(_opf_opening_tags(opf_text, "itemref"))except Exception:return 0diff --git a/tests/test_epub_utf16.py b/tests/test_epub_utf16.pynew file mode 100644index 0000000..cc817a5--- /dev/null+++ b/tests/test_epub_utf16.py@@ -0,0 +1,128 @@+"""Synthetic EPUBs exercise UTF-16 XML in the stdlib fallback."""++import codecs+import json+import os+import subprocess+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path+from unittest.mock import patch++from book_to_skill import utils+from book_to_skill.parsers import epub+++ROOT = Path(__file__).resolve().parent.parent+++def _encode_xml(text: str, encoding: str) -> bytes:+ declaration = '<?xml version="1.0" encoding="{}"?>'.format(+ "UTF-8" if encoding == "utf-8" else "UTF-16"+ )+ data = (declaration + text).encode(encoding)+ if encoding == "utf-16-le":+ return codecs.BOM_UTF16_LE + data+ if encoding == "utf-16-be":+ return codecs.BOM_UTF16_BE + data+ return data+++def _make_epub(path: Path, *, opf_encoding: str, chapter_encoding: str,+ container_encoding: str = "utf-8") -> None:+ container = (+ '<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0">'+ '<rootfiles><rootfile full-path="OEBPS/book.opf" '+ 'media-type="application/oebps-package+xml"/></rootfiles></container>'+ )+ opf = (+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0">'+ '<manifest><item id="first" href="z.xhtml" media-type="application/xhtml+xml"/>'+ '<item id="second" href="a.xhtml" media-type="application/xhtml+xml"/>'+ '</manifest><spine><itemref idref="first"/><itemref idref="second"/>'+ '</spine></package>'+ )+ first = '<html xmlns="http://www.w3.org/1999/xhtml"><body><p>FIRST 中文</p></body></html>'+ second = '<html xmlns="http://www.w3.org/1999/xhtml"><body><p>SECOND café</p></body></html>'+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("mimetype", "application/epub+zip")+ archive.writestr("META-INF/container.xml", _encode_xml(container, container_encoding))+ # A decoy comes first so a failed container lookup cannot accidentally+ # pick the intended OPF via the fallback archive scan.+ archive.writestr("decoy.opf", '<package><manifest/></package>')+ archive.writestr("OEBPS/book.opf", _encode_xml(opf, opf_encoding))+ archive.writestr("OEBPS/z.xhtml", _encode_xml(first, chapter_encoding))+ archive.writestr("OEBPS/a.xhtml", _encode_xml(second, chapter_encoding))+++class TestEpubUtf16Fallback(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.path = Path(self.temporary.name) / "synthetic.epub"++ def assert_complete(self):+ text = epub.extract_with_zipfile(str(self.path))+ self.assertIsNotNone(text)+ self.assertEqual(text, "FIRST 中文\n\nSECOND café")+ self.assertEqual(epub.count_epub_chapters(str(self.path)), 2)++ def test_utf16_content_documents_preserve_text_and_spine_order(self):+ for encoding in ("utf-16-le", "utf-16-be"):+ with self.subTest(encoding=encoding):+ _make_epub(self.path, opf_encoding="utf-8", chapter_encoding=encoding)+ self.assert_complete()++ def test_utf16_package_document_preserves_spine_order_and_count(self):+ for encoding in ("utf-16-le", "utf-16-be"):+ with self.subTest(encoding=encoding):+ _make_epub(self.path, opf_encoding=encoding, chapter_encoding="utf-8")+ self.assert_complete()++ def test_utf16_container_uses_declared_package_instead_of_decoy(self):+ for encoding in ("utf-16-le", "utf-16-be"):+ with self.subTest(encoding=encoding):+ _make_epub(self.path, opf_encoding="utf-8", chapter_encoding="utf-8",+ container_encoding=encoding)+ self.assert_complete()++ def test_existing_utf8_archive_is_unchanged(self):+ _make_epub(self.path, opf_encoding="utf-8", chapter_encoding="utf-8")+ self.assert_complete()++ def test_utf32_le_bom_does_not_trigger_utf16_detection(self):+ # UTF-32 is not an EPUB XML encoding, but its LE BOM begins with the+ # UTF-16 LE BOM. Preserve the old UTF-8 replacement behavior.+ raw = codecs.BOM_UTF32_LE + "<p>Example</p>".encode("utf-32-le")+ self.assertEqual(epub._decode_epub_xml(raw), raw.decode("utf-8", errors="replace"))++ def test_dispatcher_reports_zipfile_and_utf16_spine_count(self):+ _make_epub(self.path, opf_encoding="utf-16-le", chapter_encoding="utf-16-be")+ with patch.object(utils, "prepare_dependencies"), patch.object(+ utils, "extract_with_ebooklib", return_value=None+ ):+ result = utils.extract_single_file(self.path, "text", "no")+ self.assertEqual(result["extraction_method"], "zipfile")+ self.assertEqual(result["spine_items"], 2)+ self.assertEqual(result["text"], "FIRST 中文\n\nSECOND café")++ def test_real_cli_without_optional_dependencies(self):+ _make_epub(self.path, opf_encoding="utf-16-be", chapter_encoding="utf-16-le")+ output = Path(self.temporary.name) / "work"+ env = os.environ.copy()+ env["BOOK_SKILL_WORKDIR"] = str(output)+ result = subprocess.run(+ [sys.executable, "-B", "-S", str(ROOT / "scripts" / "extract.py"),+ str(self.path), "--mode", "text", "--install-missing", "no"],+ cwd=ROOT, env=env, capture_output=True, text=True, encoding="utf-8",+ errors="replace", timeout=60,+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ corpus = (output / "full_text.txt").read_text(encoding="utf-8")+ metadata = json.loads((output / "metadata.json").read_text(encoding="utf-8"))+ self.assertIn("FIRST 中文\n\nSECOND café", corpus)+ self.assertEqual(metadata["sources"][0]["extraction_method"], "zipfile")+ self.assertEqual(metadata["sources"][0]["pages_label"], "spine_items")+ self.assertEqual(metadata["sources"][0]["pages"], 2)