Skip to content

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

feat(reading): add source-faithful EPUB contract

XZHd3b19f3a2e04
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index ba892d981..d02d0e909 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -32,7 +32,9 @@ from deeptutor.reading import (
Annotation,
MaterialNotFound,
ReadingError,
+ ReadingPosition,
ReadingStore,
+ ReadingUpgradeConflict,
export_material,
render_outline,
)
@@ -61,6 +63,8 @@ def _http_error(exc: Exception) -> HTTPException:
"""
if isinstance(exc, MaterialNotFound):
return HTTPException(status_code=404, detail=str(exc))
+ if isinstance(exc, ReadingUpgradeConflict):
+ return HTTPException(status_code=409, detail=str(exc))
if isinstance(exc, ReadingError):
return HTTPException(status_code=400, detail=str(exc))
logger.warning("unexpected reading error", exc_info=True)
@@ -81,12 +85,14 @@ class MaterialInfo(BaseModel):
char_count: int = 0
created_at: float = 0.0
has_raw_view: bool = False
+ render_mode: Literal["text", "pdf", "epub"] = "text"
annotation_count: int = 0
class MaterialDetail(MaterialInfo):
outline: list[dict[str, Any]] = Field(default_factory=list)
outline_text: str = ""
+ unit_refs: list[dict[str, Any]] = Field(default_factory=list)
class UnitText(BaseModel):
@@ -111,6 +117,7 @@ class AnnotationPayload(BaseModel):
quote: str = ""
note: str = ""
rects: list[list[float]] = Field(default_factory=list)
+ source_anchor: str = Field(default="", max_length=4096)
def to_annotation(self) -> Annotation:
return Annotation.from_dict(
@@ -122,6 +129,7 @@ class AnnotationPayload(BaseModel):
"quote": self.quote,
"note": self.note,
"rects": self.rects,
+ "source_anchor": self.source_anchor,
"author": "user",
}
)
@@ -135,11 +143,22 @@ class AnnotationInfo(BaseModel):
quote: str
note: str
rects: list[list[float]]
+ source_anchor: str = ""
author: str
created_at: float
updated_at: float
+class PositionPayload(BaseModel):
+ locator: int = Field(ge=1)
+ source_anchor: str = Field(default="", max_length=4096)
+ percentage: float = Field(default=0.0, ge=0.0, le=1.0)
+
+
+class PositionInfo(PositionPayload):
+ updated_at: float = 0.0
+
+
class SupportedFormats(BaseModel):
extensions: list[str]
max_bytes: int
@@ -279,6 +298,34 @@ async def list_annotations(material_id: str) -> list[AnnotationInfo]:
raise _http_error(exc) from exc
[email protected]("/materials/{material_id}/position", response_model=PositionInfo)
+async def get_position(material_id: str) -> PositionInfo:
+ """Return the user's last durable viewport for this material."""
+ store = _store()
+ try:
+ return PositionInfo(**store.position(material_id).to_dict())
+ except Exception as exc:
+ raise _http_error(exc) from exc
+
+
[email protected]("/materials/{material_id}/position", response_model=PositionInfo)
+async def save_position(material_id: str, payload: PositionPayload) -> PositionInfo:
+ """Persist a validated numeric locator plus an optional renderer anchor."""
+ store = _store()
+ try:
+ saved = store.save_position(
+ material_id,
+ ReadingPosition(
+ locator=payload.locator,
+ source_anchor=payload.source_anchor,
+ percentage=payload.percentage,
+ ),
+ )
+ return PositionInfo(**saved.to_dict())
+ except Exception as exc:
+ raise _http_error(exc) from exc
+
+
@router.put("/materials/{material_id}/annotations", response_model=AnnotationInfo)
async def save_annotation(material_id: str, payload: AnnotationPayload) -> AnnotationInfo:
"""Create or update one annotation (id absent = create)."""
@@ -345,6 +392,7 @@ def _detail(store: ReadingStore, manifest: Any) -> MaterialDetail:
"annotation_count": len(store.annotations(manifest.material_id)),
"outline": [entry.to_dict() for entry in outline],
"outline_text": render_outline(store, manifest.material_id),
+ "unit_refs": [entry.to_dict() for entry in store.unit_references(manifest.material_id)],
}
)
diff --git a/deeptutor/reading/__init__.py b/deeptutor/reading/__init__.py
index 4c7ed34aa..2101de7b2 100644
--- a/deeptutor/reading/__init__.py
+++ b/deeptutor/reading/__init__.py
@@ -33,9 +33,13 @@ from deeptutor.reading.models import (
MaterialNotFound,
OutlineEntry,
ReadingError,
+ ReadingPosition,
+ ReadingUpgradeConflict,
Rect,
+ RenderMode,
SearchHit,
UnitKind,
+ UnitReference,
)
from deeptutor.reading.search import SearchResult, search_units
from deeptutor.reading.service import (
@@ -62,12 +66,16 @@ __all__ = [
"OutlineEntry",
"QuoteCheck",
"ReadingError",
+ "ReadingPosition",
+ "ReadingUpgradeConflict",
"ReadingStore",
"Rect",
"RenderedUnits",
"SearchHit",
"SearchResult",
+ "RenderMode",
"UnitKind",
+ "UnitReference",
"content_hash",
"export_material",
"extract_material",
diff --git a/deeptutor/reading/extract.py b/deeptutor/reading/extract.py
index b651f3b96..4698f95e5 100644
--- a/deeptutor/reading/extract.py
+++ b/deeptutor/reading/extract.py
@@ -33,7 +33,7 @@ import logging
from pathlib import Path
import re
-from deeptutor.reading.models import OutlineEntry, ReadingError, UnitKind
+from deeptutor.reading.models import OutlineEntry, ReadingError, RenderMode, UnitKind, UnitReference
logger = logging.getLogger(__name__)
@@ -68,6 +68,8 @@ class Extraction:
# Otherwise the outline is synthesised later from unit first lines, so that
# a material without bookmarks is still navigable by meaning.
outline: tuple[OutlineEntry, ...] = field(default_factory=tuple)
+ render_mode: RenderMode = "text"
+ unit_refs: tuple[UnitReference, ...] = field(default_factory=tuple)
@property
def char_count(self) -> int:
@@ -88,6 +90,8 @@ def extract_material(path: str | Path) -> Extraction:
suffix = source.suffix.lower()
if suffix == ".pdf":
extraction = _extract_pdf(source)
+ elif suffix == ".epub":
+ extraction = _extract_epub(source)
elif suffix == ".pptx":
extraction = _extract_slides(source)
else:
@@ -131,6 +135,42 @@ def _extract_pdf(source: Path) -> Extraction:
has_raw_view=True,
title=title,
outline=outline,
+ render_mode="pdf",
+ )
+
+
+def _extract_epub(source: Path) -> 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)
+ except (OSError, DocumentExtractionError) as exc:
+ raise ReadingError(f"{source.name}: failed to read EPUB ({exc})") from exc
+
+ refs = tuple(
+ UnitReference(locator=index, source_href=unit.href, title=unit.title)
+ for index, unit in enumerate(units, start=1)
+ )
+ outline = tuple(
+ OutlineEntry(locator=row.locator, title=row.title, level=row.level) for row in navigation
+ )
+ if not outline:
+ outline = tuple(
+ OutlineEntry(
+ locator=ref.locator,
+ title=ref.title or Path(ref.source_href).stem,
+ synthesised=not bool(ref.title),
+ )
+ for ref in refs
+ )
+ return Extraction(
+ units=tuple(unit.text for unit in units),
+ unit="chapter",
+ extractor="epub-spine",
+ outline=outline,
+ render_mode="epub",
+ unit_refs=refs,
)
diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py
index ee0c1bd85..220b422bc 100644
--- a/deeptutor/reading/models.py
+++ b/deeptutor/reading/models.py
@@ -22,6 +22,7 @@ from typing import Any, Literal
# What one locator addresses, per source format. Purely presentational for the
# model and the UI ("page 12" vs "chapter 3"); the addressing is identical.
UnitKind = Literal["page", "chapter", "slide", "section"]
+RenderMode = Literal["text", "pdf", "epub"]
AnnotationKind = Literal["highlight", "underline", "note"]
@@ -52,6 +53,10 @@ class MaterialNotFound(ReadingError):
"""The requested material id does not exist in this user's store."""
+class ReadingUpgradeConflict(ReadingError):
+ """A source-faithful upgrade would invalidate existing annotations."""
+
+
@dataclass(frozen=True, slots=True)
class Rect:
"""A normalised rectangle within one unit: 0..1, origin top-left."""
@@ -135,6 +140,30 @@ class OutlineEntry:
}
+@dataclass(frozen=True, slots=True)
+class UnitReference:
+ """Source address for one numeric locator in a faithful renderer."""
+
+ locator: int
+ source_href: str = ""
+ title: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "locator": self.locator,
+ "source_href": self.source_href,
+ "title": self.title,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "UnitReference":
+ return cls(
+ locator=max(1, int(data.get("locator") or 1)),
+ source_href=str(data.get("source_href") or ""),
+ title=str(data.get("title") or ""),
+ )
+
+
@dataclass(frozen=True, slots=True)
class SearchHit:
"""One search match, addressed by locator with surrounding context."""
@@ -172,6 +201,9 @@ class MaterialManifest:
# (today: PDF). Other formats read from extracted text, so the reader shows
# its text view and the export falls back to a Markdown excerpt.
has_raw_view: bool = False
+ # Selects the faithful renderer without overloading ``has_raw_view``.
+ # The legacy boolean remains PDF-only until every client understands EPUB.
+ render_mode: RenderMode = "text"
def to_dict(self) -> dict[str, Any]:
return {
@@ -187,11 +219,15 @@ class MaterialManifest:
"char_count": self.char_count,
"created_at": self.created_at,
"has_raw_view": self.has_raw_view,
+ "render_mode": self.render_mode,
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "MaterialManifest":
unit = str(data.get("unit") or "page")
+ render_mode = str(data.get("render_mode") or "")
+ if render_mode not in ("text", "pdf", "epub"):
+ render_mode = "pdf" if data.get("has_raw_view") else "text"
return cls(
material_id=str(data.get("material_id") or ""),
filename=str(data.get("filename") or ""),
@@ -205,6 +241,7 @@ class MaterialManifest:
char_count=int(data.get("char_count") or 0),
created_at=float(data.get("created_at") or 0.0),
has_raw_view=bool(data.get("has_raw_view")),
+ render_mode=render_mode, # type: ignore[arg-type]
)
@@ -225,6 +262,8 @@ class Annotation:
quote: str = ""
note: str = ""
rects: tuple[Rect, ...] = ()
+ # Opaque renderer-native position. EPUB clients store a CFI here.
+ source_anchor: str = ""
author: str = "user"
created_at: float = field(default_factory=time.time)
updated_at: float = field(default_factory=time.time)
@@ -241,6 +280,7 @@ class Annotation:
"quote": self.quote,
"note": self.note,
"rects": [r.to_list() for r in self.rects],
+ "source_anchor": self.source_anchor,
"author": self.author,
"created_at": self.created_at,
"updated_at": self.updated_at,
@@ -263,12 +303,40 @@ class Annotation:
quote=str(data.get("quote") or ""),
note=str(data.get("note") or ""),
rects=rects,
+ source_anchor=str(data.get("source_anchor") or ""),
author=str(data.get("author") or "user"),
created_at=float(data.get("created_at") or 0.0),
updated_at=float(data.get("updated_at") or 0.0),
)
+@dataclass(frozen=True, slots=True)
+class ReadingPosition:
+ """Last durable viewport for a material."""
+
+ locator: int = 1
+ source_anchor: str = ""
+ percentage: float = 0.0
+ updated_at: float = field(default_factory=time.time)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "locator": self.locator,
+ "source_anchor": self.source_anchor,
+ "percentage": self.percentage,
+ "updated_at": self.updated_at,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict[str, Any]) -> "ReadingPosition":
+ return cls(
+ locator=max(1, int(data.get("locator") or 1)),
+ source_anchor=str(data.get("source_anchor") or ""),
+ percentage=min(1.0, max(0.0, float(data.get("percentage") or 0.0))),
+ updated_at=float(data.get("updated_at") or 0.0),
+ )
+
+
__all__ = [
"ANNOTATION_COLORS",
"DEFAULT_ANNOTATION_COLOR",
@@ -278,7 +346,11 @@ __all__ = [
"MaterialNotFound",
"OutlineEntry",
"ReadingError",
+ "ReadingPosition",
+ "ReadingUpgradeConflict",
+ "RenderMode",
"Rect",
"SearchHit",
"UnitKind",
+ "UnitReference",
]
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index 6c0e2f0ff..5fc839632 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -46,6 +46,9 @@ from deeptutor.reading.models import (
MaterialNotFound,
OutlineEntry,
ReadingError,
+ ReadingPosition,
+ ReadingUpgradeConflict,
+ UnitReference,
)
logger = logging.getLogger(__name__)
@@ -53,6 +56,8 @@ logger = logging.getLogger(__name__)
MANIFEST_NAME = "manifest.json"
OUTLINE_NAME = "outline.json"
ANNOTATIONS_NAME = "annotations.json"
+POSITION_NAME = "position.json"
+UNIT_REFS_NAME = "unit_refs.json"
UNITS_DIR = "units"
RAW_DIR = "raw"
@@ -162,32 +167,42 @@ class ReadingStore:
with self._locked(material_id):
existing = self._load_manifest(material_id)
if existing is not None and self._is_complete(material_id, existing):
- return existing
+ wants_epub_upgrade = (
+ path.suffix.lower() == ".epub" and existing.render_mode != "epub"
+ )
+ if not wants_epub_upgrade:
+ return existing
+ if self.annotations(material_id):
+ raise ReadingUpgradeConflict(
+ "This EPUB was imported by the legacy text reader and has annotations. "
+ "Export those annotations before replacing it with the source-faithful version."
+ )
extraction = extract_material(path)
material_dir = self._dir(material_id)
- units_dir = material_dir / UNITS_DIR
- # A previous partial ingest (crash between unit writes) must not
- # leave stale units behind that would read as real content.
- if units_dir.exists():
- shutil.rmtree(units_dir, ignore_errors=True)
+ stage_dir = self.root / f".{material_id}.{uuid.uuid4().hex[:8]}.staging"
+ backup_dir = self.root / f".{material_id}.{uuid.uuid4().hex[:8]}.backup"
+ units_dir = stage_dir / UNITS_DIR
units_dir.mkdir(parents=True, exist_ok=True)
for index, unit in enumerate(extraction.units, start=1):
- self._unit_file(material_dir, index).write_text(unit, encoding="utf-8")
+ self._unit_file(stage_dir, index).write_text(unit, encoding="utf-8")
- raw_path: Path | None = None
- if extraction.has_raw_view:
- raw_dir = material_dir / RAW_DIR
+ if extraction.render_mode != "text":
+ raw_dir = stage_dir / RAW_DIR
raw_dir.mkdir(parents=True, exist_ok=True)
raw_path = raw_dir / _safe_filename(display_name, fallback=path.name)
raw_path.write_bytes(data)
outline = extraction.outline or synthesise_outline(extraction.units)
_atomic_write(
- material_dir / OUTLINE_NAME,
+ stage_dir / OUTLINE_NAME,
json.dumps([entry.to_dict() for entry in outline], ensure_ascii=False),
)
+ _atomic_write(
+ stage_dir / UNIT_REFS_NAME,
+ json.dumps([entry.to_dict() for entry in extraction.unit_refs], ensure_ascii=False),
+ )
manifest = MaterialManifest(
material_id=material_id,
@@ -201,14 +216,41 @@ class ReadingStore:
byte_size=len(data),
char_count=extraction.char_count,
created_at=time.time(),
- has_raw_view=raw_path is not None,
+ # Compatibility: old clients route this boolean directly to
+ # pdf.js. EPUB dispatch is carried by ``render_mode`` instead.
+ has_raw_view=extraction.render_mode == "pdf",
+ render_mode=extraction.render_mode,
)
# Manifest last: its presence is the "this material is usable"
# signal, so it must not appear before the units it describes.
_atomic_write(
- material_dir / MANIFEST_NAME,
+ stage_dir / MANIFEST_NAME,
json.dumps(manifest.to_dict(), ensure_ascii=False, indent=2),
)
+
+ # A repair or compatible re-ingest keeps user-owned state. EPUB
+ # legacy upgrades with annotations were rejected above because
+ # their old locators cannot be mapped safely to the spine.
+ for state_name in (ANNOTATIONS_NAME, POSITION_NAME):
+ source_state = material_dir / state_name
+ if source_state.is_file():
+ shutil.copy2(source_state, stage_dir / state_name)
+
+ # Install the fully written directory in one swap. If the second
+ # rename fails, put the previous material back before surfacing the
+ # error; readers never observe a half-written unit set.
+ try:
+ if material_dir.exists():
+ os.replace(material_dir, backup_dir)
+ try:
+ os.replace(stage_dir, material_dir)
+ except Exception:
+ if backup_dir.exists() and not material_dir.exists():
+ os.replace(backup_dir, material_dir)
+ raise
+ finally:
+ shutil.rmtree(stage_dir, ignore_errors=True)
+ shutil.rmtree(backup_dir, ignore_errors=True)
return manifest
def _is_complete(self, material_id: str, manifest: MaterialManifest) -> bool:
@@ -218,7 +260,7 @@ class ReadingStore:
return False
if not self._unit_file(material_dir, manifest.unit_count).exists():
return False
- if manifest.has_raw_view and self._find_raw(material_dir) is None:
+ if manifest.render_mode != "text" and self._find_raw(material_dir) is None:
return False
return True
@@ -341,10 +383,45 @@ class ReadingStore:
def raw_path(self, material_id: str) -> Path | None:
"""The stored original file, or None for text-only materials."""
manifest = self.manifest(material_id)
- if not manifest.has_raw_view:
+ if manifest.render_mode == "text":
return None
return self._find_raw(self._dir(material_id))
+ def unit_references(self, material_id: str) -> list[UnitReference]:
+ """Source-native addresses aligned with the numeric locator space."""
+ manifest = self.manifest(material_id)
+ rows = _read_json(self._dir(material_id) / UNIT_REFS_NAME)
+ if not isinstance(rows, list):
+ return [UnitReference(locator=index) for index in range(1, manifest.unit_count + 1)]
+ refs = [UnitReference.from_dict(row) for row in rows if isinstance(row, dict)]
+ return [row for row in refs if 1 <= row.locator <= manifest.unit_count]
+
+ def position(self, material_id: str) -> ReadingPosition:
+ """Return the last viewport, defaulting to the first locator."""
+ self.manifest(material_id)
+ row = _read_json(self._dir(material_id) / POSITION_NAME)
+ return ReadingPosition.from_dict(row) if isinstance(row, dict) else ReadingPosition()
+
+ def save_position(self, material_id: str, position: ReadingPosition) -> ReadingPosition:
+ """Validate and atomically persist a material viewport."""
+ manifest = self.manifest(material_id)
+ if not 1 <= position.locator <= manifest.unit_count:
+ raise ReadingError(
+ f"{manifest.unit} {position.locator} is out of range — "
+ f"this material has {manifest.unit_count}."
+ )
+ if len(position.source_anchor) > 4096:
+ raise ReadingError("source anchor is too long")
+ if not 0.0 <= position.percentage <= 1.0:
+ raise ReadingError("position percentage must be between 0 and 1")
+ stored = dataclass_replace(position, updated_at=time.time())
+ with self._locked(material_id):
+ _atomic_write(
+ self._dir(material_id) / POSITION_NAME,
+ json.dumps(stored.to_dict(), ensure_ascii=False, indent=2),
+ )
+ return stored
+
@staticmethod
def _find_raw(material_dir: Path) -> Path | None:
raw_dir = material_dir / RAW_DIR
@@ -396,6 +473,8 @@ class ReadingStore:
f"{manifest.unit} {annotation.locator} is out of range — "
f"this material has {manifest.unit_count}."
)
+ if len(annotation.source_anchor) > 4096:
+ raise ReadingError("source anchor is too long")
with self._locked(material_id):
existing = self.annotations(material_id)
stored = annotation
diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.py
index 1de8973f2..d2049d9a3 100644
--- a/deeptutor/utils/document_extractor.py
+++ b/deeptutor/utils/document_extractor.py
@@ -21,6 +21,7 @@ from __future__ import annotations
import base64
from collections.abc import Iterable
+from dataclasses import dataclass
from html.parser import HTMLParser
import io
import logging
@@ -152,6 +153,29 @@ class DocumentTooLargeError(DocumentExtractionError):
pass
+@dataclass(frozen=True, slots=True)
+class EpubSpineUnit:
+ """One EPUB spine document in package reading order.
+
+ ``href`` is the normalised archive-member path. Keeping the source address
+ next to its extracted text lets a faithful browser rendition and the
+ server's numeric locator space refer to the same chapter.
+ """
+
+ href: str
+ text: str
+ title: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class EpubOutlineItem:
+ """One EPUB navigation entry resolved to a spine locator."""
+
+ locator: int
+ title: str
+ level: int = 1
+
+
def is_document_extension(filename: str) -> bool:
return _ext(filename) in SUPPORTED_DOC_EXTENSIONS
@@ -498,7 +522,7 @@ def _epub_render_text(element: Any, parts: list[str]) -> None:
paragraph break; ``script``/``style`` subtrees are dropped entirely.
"""
tag = _local_name(element.tag) if isinstance(element.tag, str) else ""
- if tag in {"script", "style"}:
+ if tag in {"head", "script", "style"}:
return
if element.text:
parts.append(element.text)
@@ -609,16 +633,174 @@ def _epub_content_files(zf: zipfile.ZipFile, filename: str) -> list[str]:
return ordered or _epub_html_members(names)
-def _extract_epub(data: bytes, filename: str) -> str:
- """Extract the reading text of an EPUB with only the standard library."""
+def _epub_element_text(node: Any) -> str:
+ return re.sub(r"\s+", " ", "".join(node.itertext())).strip()
+
+
+def _epub_package_navigation(
+ zf: zipfile.ZipFile,
+ filename: str,
+ 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)
+ if opf_root is None:
+ return []
+
+ opf_dir = posixpath.dirname(opf_path)
+ nav_member = ""
+ ncx_member = ""
+ spine_toc = ""
+ manifest: dict[str, tuple[str, str]] = {}
+ for node in opf_root.iter():
+ name = _local_name(node.tag)
+ if name == "item":
+ item_id = str(node.get("id") or "")
+ href = str(node.get("href") or "")
+ properties = str(node.get("properties") or "")
+ media_type = str(node.get("media-type") or "")
+ if item_id and href:
+ manifest[item_id] = (href, media_type)
+ if "nav" in properties.split():
+ nav_member = posixpath.normpath(
+ posixpath.join(opf_dir, unquote(href.split("#", 1)[0]))
+ )
+ elif name == "spine":
+ spine_toc = str(node.get("toc") or "")
+
+ if spine_toc in manifest:
+ href, media_type = manifest[spine_toc]
+ if media_type == "application/x-dtbncx+xml" or href.lower().endswith(".ncx"):
+ ncx_member = posixpath.normpath(posixpath.join(opf_dir, unquote(href.split("#", 1)[0])))
+
+ locator_by_member = {member: index for index, member in enumerate(spine_members, start=1)}
+
+ def resolve_locator(href: str, base_member: str) -> int:
+ path = unquote(href.split("#", 1)[0])
+ member = posixpath.normpath(posixpath.join(posixpath.dirname(base_member), path))
+ return locator_by_member.get(member, 0)
+
+ rows: list[EpubOutlineItem] = []
+ if nav_member:
+ nav_root = _epub_parse_member(zf, nav_member, filename)
+ if nav_root is not None:
+ nav_nodes = [node for node in nav_root.iter() if _local_name(node.tag) == "nav"]
+ toc_nav = next(
+ (
+ node
+ for node in nav_nodes
+ if "toc"
+ in str(
+ node.get("{http://www.idpf.org/2007/ops}type")
+ or node.get("epub:type")
+ or ""
+ ).split()
+ ),
+ nav_nodes[0] if nav_nodes else None,
+ )
+
+ def walk_nav(node: Any, level: int) -> None:
+ for child in node:
+ name = _local_name(child.tag)
+ if name == "li":
+ link = next(
+ (item for item in child if _local_name(item.tag) in {"a", "span"}),
+ None,
+ )
+ href = str(link.get("href") or "") if link is not None else ""
+ title = _epub_element_text(link) if link is not None else ""
+ locator = resolve_locator(href, nav_member) if href else 0
+ if locator and title:
+ rows.append(EpubOutlineItem(locator, title, max(1, level)))
+ for item in child:
+ if _local_name(item.tag) == "ol":
+ walk_nav(item, level + 1)
+ elif name == "ol":
+ walk_nav(child, level)
+
+ if toc_nav is not None:
+ walk_nav(toc_nav, 1)
+
+ if not rows and ncx_member:
+ ncx_root = _epub_parse_member(zf, ncx_member, filename)
+ if ncx_root is not None:
+
+ def walk_ncx(node: Any, level: int) -> None:
+ for point in node:
+ if _local_name(point.tag) != "navPoint":
+ continue
+ label = next(
+ (item for item in point.iter() if _local_name(item.tag) == "navLabel"),
+ None,
+ )
+ content = next(
+ (item for item in point if _local_name(item.tag) == "content"),
+ None,
+ )
+ title = _epub_element_text(label) if label is not None else ""
+ href = str(content.get("src") or "") if content is not None else ""
+ locator = resolve_locator(href, ncx_member) if href else 0
+ if locator and title:
+ rows.append(EpubOutlineItem(locator, title, max(1, level)))
+ walk_ncx(point, level + 1)
+
+ nav_map = next(
+ (node for node in ncx_root.iter() if _local_name(node.tag) == "navMap"),
+ None,
+ )
+ if nav_map is not None:
+ walk_ncx(nav_map, 1)
+ return rows
+
+
+def extract_epub_spine(
+ data: bytes,
+ filename: str,
+) -> tuple[tuple[EpubSpineUnit, ...], tuple[EpubOutlineItem, ...]]:
+ """Return safe, source-addressed EPUB spine units and its nested outline."""
+ _check_magic(".epub", data, filename)
with _open_ooxml(data, filename) as zf:
_validate_epub_archive(zf, filename)
- chapters: list[str] = []
- for member in _epub_content_files(zf, filename):
+ members = _epub_content_files(zf, filename)
+ units: list[EpubSpineUnit] = []
+ for member in members:
text = _epub_chapter_text(zf, member, filename)
- if text:
- chapters.append(text)
- return "\n\n".join(chapters)
+ heading = ""
+ root = _epub_parse_member(zf, member, filename)
+ if root is not None:
+ heading_node = next(
+ (
+ node
+ for node in root.iter()
+ if _local_name(node.tag) in {"h1", "h2", "title"}
+ and _epub_element_text(node)
+ ),
+ None,
+ )
+ if heading_node is not None:
+ heading = _epub_element_text(heading_node)
+ units.append(EpubSpineUnit(href=member, text=text, title=heading))
+ outline = _epub_package_navigation(zf, filename, members)
+ return tuple(units), tuple(outline)
+
+
+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)
+ return "\n\n".join(unit.text for unit in units if unit.text)
def _validate_epub_archive(zf: zipfile.ZipFile, filename: str) -> None:
diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.py
index 4428d8f2b..c1e686886 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -6,7 +6,9 @@ path service, a user workspace, or an LLM.
from __future__ import annotations
+import json
from pathlib import Path
+import zipfile
import pytest
@@ -51,6 +53,32 @@ def _write_pdf(path: Path, pages: list[str], *, toc: list | None = None) -> Path
return path
+def _write_epub(path: Path) -> Path:
+ with zipfile.ZipFile(path, "w") as archive:
+ archive.writestr("mimetype", "application/epub+zip")
+ archive.writestr(
+ "META-INF/container.xml",
+ """<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>""",
+ )
+ archive.writestr(
+ "OEBPS/content.opf",
+ """<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0"><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="one" href="chapters/one.xhtml" media-type="application/xhtml+xml"/><item id="two" href="chapters/two.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="one"/><itemref idref="two"/></spine></package>""",
+ )
+ archive.writestr(
+ "OEBPS/nav.xhtml",
+ """<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li><a href="chapters/one.xhtml">Part One</a><ol><li><a href="chapters/two.xhtml">Second Chapter</a></li></ol></li></ol></nav></body></html>""",
+ )
+ archive.writestr(
+ "OEBPS/chapters/one.xhtml",
+ "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>One</title></head><body><h1>First Chapter</h1><p>Alpha source text.</p><script>ignore me</script></body></html>",
+ )
+ archive.writestr(
+ "OEBPS/chapters/two.xhtml",
+ "<html xmlns='http://www.w3.org/1999/xhtml'><body><h1>Second Chapter</h1><p>Beta source text.</p></body></html>",
+ )
+ return path
+
+
@pytest.fixture
def pdf_path(tmp_path: Path) -> Path:
return _write_pdf(
@@ -117,6 +145,26 @@ def test_text_file_is_cut_into_sections_on_paragraph_boundaries(tmp_path: Path)
assert all(unit.startswith("Dense prose") for unit in extraction.units)
+def test_epub_preserves_spine_units_source_hrefs_and_nested_outline(tmp_path: Path) -> None:
+ extraction = extract_material(_write_epub(tmp_path / "book.epub"))
+
+ assert extraction.render_mode == "epub"
+ assert extraction.has_raw_view is False
+ assert extraction.unit == "chapter"
+ assert extraction.units == (
+ "First Chapter\nAlpha source text.",
+ "Second Chapter\nBeta source text.",
+ )
+ assert [ref.source_href for ref in extraction.unit_refs] == [
+ "OEBPS/chapters/one.xhtml",
+ "OEBPS/chapters/two.xhtml",
+ ]
+ assert [(row.locator, row.title, row.level) for row in extraction.outline] == [
+ (1, "Part One", 1),
+ (2, "Second Chapter", 2),
+ ]
+
+
def test_pptx_slides_become_units_when_the_extractor_marks_them(tmp_path: Path) -> None:
pytest.importorskip("pptx")
from pptx import Presentation
@@ -181,6 +229,78 @@ def test_ingest_writes_units_raw_and_manifest(store: ReadingStore, pdf_path: Pat
assert raw is not None and raw.read_bytes()[:5] == b"%PDF-"
+def test_epub_store_keeps_original_but_legacy_pdf_flag_stays_false(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ path = _write_epub(tmp_path / "book.epub")
+ manifest = store.ingest(path)
+
+ assert manifest.render_mode == "epub"
+ assert manifest.has_raw_view is False
+ assert store.raw_path(manifest.material_id) is not None
+ assert store.unit_references(manifest.material_id)[1].source_href.endswith("two.xhtml")
+
+
+def test_position_round_trip_validates_locator_and_anchor(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ from deeptutor.reading import ReadingPosition
+
+ manifest = store.ingest(_write_epub(tmp_path / "book.epub"))
+ saved = store.save_position(
+ manifest.material_id,
+ ReadingPosition(locator=2, source_anchor="epubcfi(/6/4)", percentage=0.6),
+ )
+
+ assert saved.updated_at > 0
+ assert store.position(manifest.material_id).source_anchor == "epubcfi(/6/4)"
+ with pytest.raises(ReadingError):
+ store.save_position(manifest.material_id, ReadingPosition(locator=99))
+
+
+def _downgrade_epub_manifest_to_legacy_text(store: ReadingStore, material_id: str) -> None:
+ material_dir = store.root / material_id
+ manifest_path = material_dir / "manifest.json"
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
+ data.pop("render_mode", None)
+ data["has_raw_view"] = False
+ manifest_path.write_text(json.dumps(data), encoding="utf-8")
+ raw_dir = material_dir / "raw"
+ if raw_dir.exists():
+ for child in raw_dir.iterdir():
+ child.unlink()
+ raw_dir.rmdir()
+
+
+def test_reupload_upgrades_legacy_epub_when_it_has_no_annotations(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ path = _write_epub(tmp_path / "book.epub")
+ first = store.ingest(path)
+ _downgrade_epub_manifest_to_legacy_text(store, first.material_id)
+
+ upgraded = store.ingest(path)
+
+ assert upgraded.render_mode == "epub"
+ assert store.raw_path(upgraded.material_id) is not None
+
+
+def test_reupload_rejects_legacy_epub_upgrade_with_annotations(
+ store: ReadingStore, tmp_path: Path
+) -> None:
+ from deeptutor.reading import ReadingUpgradeConflict
+
+ path = _write_epub(tmp_path / "book.epub")
+ first = store.ingest(path)
+ store.save_annotation(first.material_id, Annotation(annotation_id="", locator=1, quote="Alpha"))
+ _downgrade_epub_manifest_to_legacy_text(store, first.material_id)
+
+ with pytest.raises(ReadingUpgradeConflict):
+ store.ingest(path)
+
+ assert [row.quote for row in store.annotations(first.material_id)] == ["Alpha"]
+
+
def test_reingesting_the_same_bytes_reuses_the_material_and_its_annotations(
store: ReadingStore, pdf_path: Path, tmp_path: Path
) -> None:
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index 30d90f10c..7fb380bfc 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import io
from pathlib import Path
+import zipfile
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -58,6 +59,24 @@ def _upload(client: TestClient, name: str = "attention.pdf", data: bytes | None
return response.json()
+def _epub_bytes() -> bytes:
+ stream = io.BytesIO()
+ with zipfile.ZipFile(stream, "w") as archive:
+ archive.writestr("mimetype", "application/epub+zip")
+ archive.writestr(
+ "META-INF/container.xml",
+ "<container><rootfiles><rootfile full-path='OPS/book.opf'/></rootfiles></container>",
+ )
+ archive.writestr(
+ "OPS/book.opf",
+ "<package><manifest><item id='one' href='one.xhtml'/></manifest><spine><itemref idref='one'/></spine></package>",
+ )
+ archive.writestr(
+ "OPS/one.xhtml", "<html><body><h1>Opening</h1><p>Readable EPUB text.</p></body></html>"
+ )
+ return stream.getvalue()
+
+
# ---------------------------------------------------------------------------
# materials
# ---------------------------------------------------------------------------
@@ -149,6 +168,28 @@ def test_supported_formats_names_pdf_as_the_faithful_view(client: TestClient) ->
assert body["max_bytes"] > 0
+def test_epub_contract_exposes_source_refs_original_and_position(client: TestClient) -> None:
+ material = _upload(client, name="book.epub", data=_epub_bytes())
+
+ assert material["render_mode"] == "epub"
+ assert material["has_raw_view"] is False
+ assert material["unit_refs"] == [
+ {"locator": 1, "source_href": "OPS/one.xhtml", "title": "Opening"}
+ ]
+ raw = client.get(f"/api/v1/reading/materials/{material['material_id']}/raw")
+ assert raw.status_code == 200
+ assert raw.headers["content-type"] == "application/epub+zip"
+
+ base = f"/api/v1/reading/materials/{material['material_id']}/position"
+ saved = client.put(
+ base,
+ json={"locator": 1, "source_anchor": "epubcfi(/6/2)", "percentage": 0.4},
+ )
+ assert saved.status_code == 200
+ assert client.get(base).json()["source_anchor"] == "epubcfi(/6/2)"
+ assert client.put(base, json={"locator": 2, "percentage": 0}).status_code == 400
+
+
# ---------------------------------------------------------------------------
# unit text and raw bytes
# ---------------------------------------------------------------------------
@@ -218,11 +259,13 @@ def test_annotation_create_update_list_delete_round_trip(client: TestClient) ->
"quote": "scaled dot-product",
"note": "core",
"rects": [[0.1, 0.2, 0.6, 0.24]],
+ "source_anchor": "epubcfi(/6/4)",
},
).json()
assert created["annotation_id"]
assert created["author"] == "user"
assert created["rects"] == [[0.1, 0.2, 0.6, 0.24]]
+ assert created["source_anchor"] == "epubcfi(/6/4)"
updated = client.put(
base,