Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(reading): read an EPUB that macOS re-zipped as the book it is

Bingxi Zhao (Frank)752fba35d44e
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index 0dcda29d9..7171c4568 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -96,6 +96,8 @@ _PDF_MAGIC = b"%PDF-"
_OOXML_MAGIC = b"PK\x03\x04"
_EPUB_CONTENT_EXTENSIONS: frozenset[str] = frozenset({".xhtml", ".html", ".htm"})
+#: Where an EPUB declares its package document, relative to the book root.
+_EPUB_CONTAINER_PATH = "META-INF/container.xml"
_EPUB_MAX_MEMBERS = 4096
_EPUB_MAX_MEMBER_BYTES = 20 * 1024 * 1024
_EPUB_MAX_TOTAL_UNCOMPRESSED_BYTES = 200 * 1024 * 1024
@@ -642,29 +644,61 @@ def _epub_html_members(names: list[str]) -> list[str]:
return [name for name in names if _ext(name) in _EPUB_CONTENT_EXTENSIONS]
-def _epub_content_files(zf: zipfile.ZipFile, filename: str) -> list[str]:
- """Resolve the XHTML content documents of an EPUB in reading order.
+def _epub_is_packaging_residue(name: str) -> bool:
+ """Whether an archive member is packaging leftovers, not book content.
- Follows the standard chain ``META-INF/container.xml`` -> OPF package
- document -> spine ``itemref`` order. Falls back to every HTML/XHTML
- member in archive order when package metadata is missing or unusable.
+ macOS writes a ``__MACOSX/`` tree of AppleDouble resource forks (``._x``)
+ alongside the real files. They carry the content file's extension while
+ holding binary metadata, so a fallback that matches on extension alone
+ reads them as chapters.
"""
- names = zf.namelist()
- name_set = set(names)
+ return any(part == "__MACOSX" or part.startswith(".") for part in name.split("/") if part)
- container_root = _epub_parse_member(zf, "META-INF/container.xml", filename)
+
+def _epub_open_package(
+ zf: zipfile.ZipFile,
+ filename: str,
+) -> tuple[list[str], str, Any | None]:
+ """Locate an EPUB's package document: content members, OPF path, OPF root.
+
+ The standard chain is ``META-INF/container.xml`` -> ``rootfile`` -> OPF.
+ Finder's "Compress" wraps the selection in a folder, which puts that whole
+ chain one level down; looking only at the archive root made every such
+ book fall back to extension matching, losing spine order and picking up
+ ``__MACOSX`` resource forks as chapters (#1447). Resolving the wrapper
+ here keeps both readers of the package — spine and navigation — agreeing
+ on where the book is.
+ """
+ names = [name for name in zf.namelist() if not _epub_is_packaging_residue(name)]
+ container = next((name for name in names if name.endswith(_EPUB_CONTAINER_PATH)), "")
+ if not container:
+ return names, "", None
+ prefix = container[: -len(_EPUB_CONTAINER_PATH)]
+
+ container_root = _epub_parse_member(zf, container, filename)
if container_root is None:
- return _epub_html_members(names)
+ return names, "", None
- opf_path = ""
+ rootfile = ""
for node in container_root.iter():
if _local_name(node.tag) == "rootfile":
- opf_path = node.get("full-path") or ""
+ rootfile = node.get("full-path") or ""
break
- if not opf_path or opf_path not in name_set:
- return _epub_html_members(names)
+ opf_path = f"{prefix}{rootfile}" if rootfile else ""
+ if not opf_path or opf_path not in set(names):
+ return names, "", None
+
+ return names, opf_path, _epub_parse_member(zf, opf_path, filename)
- opf_root = _epub_parse_member(zf, opf_path, filename)
+
+def _epub_content_files(zf: zipfile.ZipFile, filename: str) -> list[str]:
+ """Resolve the XHTML content documents of an EPUB in reading order.
+
+ Falls back to every HTML/XHTML member in archive order when package
+ metadata is missing or unusable.
+ """
+ names, opf_path, opf_root = _epub_open_package(zf, filename)
+ name_set = set(names)
if opf_root is None:
return _epub_html_members(names)
@@ -706,20 +740,7 @@ def _epub_package_navigation(
spine_members: list[str],
) -> list[EpubOutlineItem]:
"""Read EPUB3 nav or EPUB2 NCX entries and map them to spine locators."""
- container_root = _epub_parse_member(zf, "META-INF/container.xml", filename)
- if container_root is None:
- return []
- opf_path = next(
- (
- str(node.get("full-path") or "")
- for node in container_root.iter()
- if _local_name(node.tag) == "rootfile"
- ),
- "",
- )
- if not opf_path:
- return []
- opf_root = _epub_parse_member(zf, opf_path, filename)
+ _, opf_path, opf_root = _epub_open_package(zf, filename)
if opf_root is None:
return []
diff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.py
index 3562ed4cd..65d8965f3 100644
--- a/tests/utils/test_document_extractor.py
+++ b/tests/utils/test_document_extractor.py
@@ -21,6 +21,7 @@ from deeptutor.utils.document_extractor import (
EmptyDocumentError,
UnsupportedDocumentError,
extract_documents_from_records,
+ extract_epub_spine,
extract_text_from_bytes,
extract_text_from_path,
is_document_extension,
@@ -82,12 +83,18 @@ def _make_epub(
opf_dir: str = "OEBPS",
with_container: bool = True,
with_opf: bool = True,
+ wrapper: str = "",
+ with_macosx: bool = False,
) -> bytes:
"""Build a minimal EPUB in memory.
``chapters`` maps member names (relative to ``opf_dir``) to XHTML body
markup. ``spine`` is an ordered subset of chapter keys controlling the
reading order; it defaults to the dict order.
+
+ ``wrapper`` nests the whole book under one directory and ``with_macosx``
+ adds AppleDouble resource forks — together, what macOS Finder's "Compress"
+ produces.
"""
opf_path = f"{opf_dir}/content.opf"
manifest = "".join(
@@ -102,18 +109,23 @@ def _make_epub(
'<package xmlns="http://www.idpf.org/2007/opf" version="3.0">'
f"<manifest>{manifest}</manifest><spine>{spine_xml}</spine></package>"
)
+ root = f"{wrapper}/" if wrapper else ""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("mimetype", "application/epub+zip")
if with_container:
- zf.writestr("META-INF/container.xml", _CONTAINER_XML.format(opf=opf_path))
+ zf.writestr(f"{root}META-INF/container.xml", _CONTAINER_XML.format(opf=opf_path))
if with_opf:
- zf.writestr(opf_path, opf)
+ zf.writestr(f"{root}{opf_path}", opf)
for name, body in chapters.items():
zf.writestr(
- f"{opf_dir}/{name}",
+ f"{root}{opf_dir}/{name}",
f'<html xmlns="http://www.w3.org/1999/xhtml"><body>{body}</body></html>',
)
+ if with_macosx:
+ # AppleDouble: the content file's name and extension, binary
+ # resource-fork bytes inside.
+ zf.writestr(f"__MACOSX/{opf_dir}/._{name}", b"\x00\x05\x16\x07" + b"\x00" * 60)
return buf.getvalue()
@@ -281,6 +293,42 @@ class TestExtractEpub:
assert "Solo chapter." in text
+ def test_a_finder_compressed_epub_still_reads_as_the_book_it_is(self) -> None:
+ """macOS "Compress" wraps the book in a folder and adds ``__MACOSX``.
+
+ Both together used to defeat the package lookup: the container was no
+ longer at the archive root, so resolution fell back to matching file
+ extensions, which picked up the AppleDouble forks as chapters. The
+ reader then reported "Could not load this section" on binary members
+ that were never part of the book (#1447).
+ """
+ data = _make_epub(
+ {
+ "index_split_000.xhtml": "<h1>Chapter One</h1><p>Alpha text.</p>",
+ "index_split_001.xhtml": "<h1>Chapter Two</h1><p>Beta text.</p>",
+ },
+ spine=["index_split_001.xhtml", "index_split_000.xhtml"],
+ wrapper="MyBook",
+ with_macosx=True,
+ )
+
+ units, _ = extract_epub_spine(data, "book.epub")
+
+ assert [unit.title for unit in units] == ["Chapter Two", "Chapter One"]
+ assert all("__MACOSX" not in unit.href for unit in units)
+
+ def test_resource_forks_are_not_chapters_even_without_a_package(self) -> None:
+ """The extension-matching fallback must not read AppleDouble bytes."""
+ data = _make_epub(
+ {"a.xhtml": "<p>First member.</p>"},
+ with_container=False,
+ with_macosx=True,
+ )
+
+ units, _ = extract_epub_spine(data, "book.epub")
+
+ assert [unit.href for unit in units] == ["OEBPS/a.xhtml"]
+
def test_malformed_xhtml_uses_tolerant_html_fallback(self) -> None:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf: