Skip to content

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

fix(reading): normalize packaged EPUB archives

XZH28aa40ff4542
diff --git a/deeptutor/reading/extract.py b/deeptutor/reading/extract.py
index 27f67c052..84eb8c789 100644
--- a/deeptutor/reading/extract.py
+++ b/deeptutor/reading/extract.py
@@ -77,12 +77,14 @@ class Extraction:
return sum(len(u) for u in self.units)
-def extract_material(path: str | Path) -> Extraction:
+def extract_material(path: str | Path, *, data: bytes | None = None) -> Extraction:
"""Cut *path* into units, dispatching on its extension.
Raises :class:`ReadingError` when the file cannot be read at all, or when
it yields no text — an image-only scan, for instance, which the reader
- would otherwise present as an empty document with no explanation.
+ would otherwise present as an empty document with no explanation. For an
+ EPUB, ``data`` may contain already-normalized archive bytes so callers can
+ extract and store exactly what they read.
"""
source = Path(path)
if not source.is_file():
@@ -92,7 +94,12 @@ def extract_material(path: str | Path) -> Extraction:
if suffix == ".pdf":
extraction = _extract_pdf(source)
elif suffix == ".epub":
- extraction = _extract_epub(source)
+ if data is None:
+ try:
+ data = source.read_bytes()
+ except OSError as exc:
+ raise ReadingError(f"{source.name}: could not be read ({exc})") from exc
+ extraction = _extract_epub(data, source.name)
elif suffix == ".pptx":
extraction = _extract_slides(source)
else:
@@ -140,14 +147,14 @@ def _extract_pdf(source: Path) -> Extraction:
)
-def _extract_epub(source: Path) -> Extraction:
+def _extract_epub(data: bytes, filename: str) -> Extraction:
"""Preserve EPUB spine order so browser and assistant locators agree."""
from deeptutor.utils.document_extractor import DocumentExtractionError, extract_epub_spine
try:
- units, navigation = extract_epub_spine(source.read_bytes(), source.name)
+ units, navigation = extract_epub_spine(data, filename)
except (OSError, DocumentExtractionError) as exc:
- raise ReadingError(f"{source.name}: failed to read EPUB ({exc})") from exc
+ raise ReadingError(f"{filename}: failed to read EPUB ({exc})") from exc
refs = tuple(
UnitReference(locator=index, source_href=unit.href, title=unit.title)
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index d9c142464..d586da69b 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -232,6 +232,18 @@ class ReadingStore:
if not data:
raise ReadingError(f"{path.name} is empty")
+ is_epub = path.suffix.lower() == ".epub"
+ if is_epub:
+ from deeptutor.utils.document_extractor import (
+ DocumentExtractionError,
+ normalize_epub_archive,
+ )
+
+ try:
+ data = normalize_epub_archive(data, path.name)
+ except DocumentExtractionError as exc:
+ raise ReadingError(f"{path.name}: failed to read EPUB ({exc})") from exc
+
material_id = content_hash(data)
display_name = (filename or path.name).strip() or path.name
@@ -249,7 +261,7 @@ class ReadingStore:
"Export those annotations before replacing it with the source-faithful version."
)
- extraction = extract_material(path)
+ extraction = extract_material(path, data=data if is_epub else None)
material_dir = self._dir(material_id)
stage_dir = self.root / f".{material_id}.{uuid.uuid4().hex[:8]}.staging"
backup_dir = self.root / f".{material_id}.{uuid.uuid4().hex[:8]}.backup"
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index 7171c4568..6bb30ee1b 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -881,6 +881,67 @@ def extract_epub_spine(
return tuple(units), tuple(outline)
+def normalize_epub_archive(data: bytes, filename: str) -> bytes:
+ """Return an EPUB archive that browser OCF readers can open directly.
+
+ The text extractor understands Finder-style packages with a top-level
+ directory and ``__MACOSX`` residue. Browser EPUB readers are stricter: they
+ expect ``META-INF/container.xml`` at the archive root. Repack only those
+ non-conforming archives so ordinary books keep their original bytes.
+ """
+ try:
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ _validate_epub_archive(zf, filename)
+ infos = [info for info in zf.infolist() if not info.is_dir()]
+ useful = [info for info in infos if not _epub_is_packaging_residue(info.filename)]
+ has_residue = len(useful) != len(infos)
+ container = next(
+ (info.filename for info in useful if info.filename.endswith(_EPUB_CONTAINER_PATH)),
+ "",
+ )
+ prefix = container[: -len(_EPUB_CONTAINER_PATH)] if container else ""
+ if prefix and not all(info.filename.startswith(prefix) for info in useful):
+ # A package document buried among unrelated root files is not
+ # a wrapped book. Leave it for the extractor's fallback path.
+ prefix = ""
+ if not prefix and not has_residue:
+ return data
+
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as normalized:
+ mimetype_name = f"{prefix}mimetype"
+ mimetype_info = next(
+ (info for info in useful if info.filename == mimetype_name), None
+ )
+ if mimetype_info is None:
+ normalized.writestr(
+ "mimetype",
+ b"application/epub+zip",
+ compress_type=zipfile.ZIP_STORED,
+ )
+ else:
+ normalized.writestr(
+ "mimetype",
+ zf.read(mimetype_info),
+ compress_type=zipfile.ZIP_STORED,
+ )
+
+ for info in useful:
+ name = info.filename[len(prefix) :] if prefix else info.filename
+ if not name or name == "mimetype":
+ continue
+ normalized.writestr(name, zf.read(info), compress_type=zipfile.ZIP_DEFLATED)
+ return output.getvalue()
+ except zipfile.BadZipFile as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to open Office ZIP package ({exc})", filename=filename
+ ) from exc
+ except OSError as exc:
+ raise CorruptDocumentError(
+ f"{filename}: failed to normalize EPUB archive ({exc})", filename=filename
+ ) from exc
+
+
def _extract_epub(data: bytes, filename: str) -> str:
"""Extract the reading text of an EPUB with only the standard library."""
units, _ = extract_epub_spine(data, filename)
diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.py
index dc563a343..91cb72d80 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -6,6 +6,7 @@ path service, a user workspace, or an LLM.
from __future__ import annotations
+import io
import json
from pathlib import Path
import zipfile
@@ -20,6 +21,7 @@ from deeptutor.reading import (
Rect,
TextPositionSelector,
TextQuoteSelector,
+ content_hash,
export_material,
parse_locators,
render_outline,
@@ -82,6 +84,22 @@ def _write_epub(path: Path) -> Path:
return path
+def _wrap_epub_for_finder(path: Path) -> Path:
+ """Model the package macOS Finder makes when it compresses an EPUB."""
+ data = path.read_bytes()
+ with zipfile.ZipFile(io.BytesIO(data)) as source:
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w") as target:
+ for info in source.infolist():
+ target.writestr(f"MyBook/{info.filename}", source.read(info))
+ target.writestr(
+ "__MACOSX/OEBPS/._one.xhtml",
+ b"\x00\x05\x16\x07" + b"\x00" * 60,
+ )
+ path.write_bytes(output.getvalue())
+ return path
+
+
@pytest.fixture
def pdf_path(tmp_path: Path) -> Path:
return _write_pdf(
@@ -258,6 +276,33 @@ def test_epub_store_keeps_original_but_legacy_pdf_flag_stays_false(
assert store.unit_references(manifest.material_id)[1].source_href.endswith("two.xhtml")
+def test_epub_store_normalizes_finder_packages_for_browser_readers(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ path = _wrap_epub_for_finder(_write_epub(tmp_path / "book.epub"))
+
+ manifest = store.ingest(path)
+
+ raw = store.raw_path(manifest.material_id)
+ assert raw is not None
+ normalized = raw.read_bytes()
+ assert manifest.byte_size == len(normalized)
+ assert manifest.source_hash == content_hash(normalized)
+ assert [ref.source_href for ref in store.unit_references(manifest.material_id)] == [
+ "OEBPS/chapters/one.xhtml",
+ "OEBPS/chapters/two.xhtml",
+ ]
+ with zipfile.ZipFile(io.BytesIO(normalized)) as archive:
+ infos = archive.infolist()
+ assert archive.read("mimetype") == b"application/epub+zip"
+ assert infos[0].filename == "mimetype"
+ assert infos[0].compress_type == zipfile.ZIP_STORED
+ assert all(
+ "__MACOSX" not in info.filename and not info.filename.startswith("MyBook/")
+ for info in infos
+ )
+
+
def test_position_round_trip_validates_locator_and_anchor(
store: ReadingStore, tmp_path: Path
) -> None:
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index e59d78266..22a15b081 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -60,16 +60,22 @@ def _upload(client: TestClient, name: str = "attention.pdf", data: bytes | None
return response.json()
-def _epub_bytes(*, language: str = "en", paragraph: str = "Readable EPUB text.") -> bytes:
+def _epub_bytes(
+ *,
+ language: str = "en",
+ paragraph: str = "Readable EPUB text.",
+ finder_package: bool = False,
+) -> bytes:
stream = io.BytesIO()
+ root = "MyBook/" if finder_package else ""
with zipfile.ZipFile(stream, "w") as archive:
- archive.writestr("mimetype", "application/epub+zip")
+ archive.writestr(f"{root}mimetype", "application/epub+zip")
archive.writestr(
- "META-INF/container.xml",
+ f"{root}META-INF/container.xml",
"<container><rootfiles><rootfile full-path='OPS/book.opf'/></rootfiles></container>",
)
archive.writestr(
- "OPS/book.opf",
+ f"{root}OPS/book.opf",
"<package xmlns:dc='http://purl.org/dc/elements/1.1/'>"
"<metadata><dc:identifier>urn:uuid:router-bilingual</dc:identifier>"
"<dc:title>Router book</dc:title>"
@@ -78,9 +84,11 @@ def _epub_bytes(*, language: str = "en", paragraph: str = "Readable EPUB text.")
"<spine><itemref idref='one'/></spine></package>",
)
archive.writestr(
- "OPS/one.xhtml",
+ f"{root}OPS/one.xhtml",
f"<html><body><h1>Opening</h1><p>{paragraph}</p></body></html>",
)
+ if finder_package:
+ archive.writestr("__MACOSX/OPS/._one.xhtml", b"\x00" * 8)
return stream.getvalue()
@@ -354,6 +362,25 @@ def test_epub_contract_exposes_source_refs_original_and_position(client: TestCli
assert client.put(base, json={"locator": 2, "percentage": 0}).status_code == 400
+def test_epub_raw_response_is_normalized_for_browser_readers(client: TestClient) -> None:
+ material = _upload(
+ client,
+ name="finder-book.epub",
+ data=_epub_bytes(finder_package=True),
+ )
+
+ raw = client.get(f"/api/reading/materials/{material['material_id']}/raw")
+
+ assert raw.status_code == 200
+ with zipfile.ZipFile(io.BytesIO(raw.content)) as archive:
+ infos = archive.infolist()
+ assert archive.read("mimetype") == b"application/epub+zip"
+ assert infos[0].filename == "mimetype"
+ assert infos[0].compress_type == zipfile.ZIP_STORED
+ assert "META-INF/container.xml" in {info.filename for info in infos}
+ assert all("__MACOSX" not in info.filename for info in infos)
+
+
def test_epub_pairing_requires_confirmation_and_preserves_source_materials(
client: TestClient,
) -> None:
diff --git a/tests/utils/test_document_extractor.py b/tests/utils/test_document_extractor.py
index 65d8965f3..83d39bfec 100644
--- a/tests/utils/test_document_extractor.py
+++ b/tests/utils/test_document_extractor.py
@@ -25,6 +25,7 @@ from deeptutor.utils.document_extractor import (
extract_text_from_bytes,
extract_text_from_path,
is_document_extension,
+ normalize_epub_archive,
)
# ---------------------------------------------------------------------------
@@ -112,7 +113,7 @@ def _make_epub(
root = f"{wrapper}/" if wrapper else ""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
- zf.writestr("mimetype", "application/epub+zip")
+ zf.writestr(f"{root}mimetype", "application/epub+zip")
if with_container:
zf.writestr(f"{root}META-INF/container.xml", _CONTAINER_XML.format(opf=opf_path))
if with_opf:
@@ -329,6 +330,37 @@ class TestExtractEpub:
assert [unit.href for unit in units] == ["OEBPS/a.xhtml"]
+ def test_archive_normalization_preserves_a_root_level_book(self) -> None:
+ data = _make_epub({"a.xhtml": "<p>Readable.</p>"})
+
+ assert normalize_epub_archive(data, "book.epub") is data
+
+ def test_archive_normalization_rejects_a_bad_zip(self) -> None:
+ with pytest.raises(CorruptDocumentError, match="failed to open"):
+ normalize_epub_archive(b"not a zip", "book.epub")
+
+ def test_archive_normalization_repairs_a_finder_package(self) -> None:
+ data = _make_epub(
+ {"a.xhtml": "<p>Readable.</p>"},
+ wrapper="MyBook",
+ with_macosx=True,
+ )
+
+ normalized = normalize_epub_archive(data, "book.epub")
+
+ with zipfile.ZipFile(io.BytesIO(normalized)) as zf:
+ infos = zf.infolist()
+ mimetype = zf.read("mimetype")
+
+ assert [info.filename for info in infos] == [
+ "mimetype",
+ "META-INF/container.xml",
+ "OEBPS/content.opf",
+ "OEBPS/a.xhtml",
+ ]
+ assert infos[0].compress_type == zipfile.ZIP_STORED
+ assert mimetype == b"application/epub+zip"
+
def test_malformed_xhtml_uses_tolerant_html_fallback(self) -> None:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf: