Skip to content

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

feat(reading): add explicit bilingual EPUB pairing

XZH410711bf7b8c
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index d02d0e909..d5c01716b 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -16,6 +16,7 @@ pulling the whole file before rendering page one.
from __future__ import annotations
+import asyncio
import logging
from pathlib import Path
import shutil
@@ -165,6 +166,11 @@ class SupportedFormats(BaseModel):
raw_view_extensions: list[str]
+class EpubPairingRequest(BaseModel):
+ english_material_id: str
+ chinese_material_id: str
+
+
# === Routes ===================================================================
@@ -240,6 +246,52 @@ async def get_material(material_id: str) -> MaterialDetail:
raise _http_error(exc) from exc
[email protected]("/materials/{material_id}/epub-pairing-candidates")
+async def epub_pairing_candidates(material_id: str) -> list[dict[str, Any]]:
+ from deeptutor.reading.epub_bilingual import recommend_epub_candidates
+
+ try:
+ return await asyncio.to_thread(recommend_epub_candidates, _store(), material_id)
+ except Exception as exc:
+ raise _http_error(exc) from exc
+
+
[email protected]("/epub-pairings")
+async def epub_pairings() -> list[dict[str, Any]]:
+ from deeptutor.reading.epub_bilingual import list_epub_pairings
+
+ return list_epub_pairings(_store())
+
+
[email protected]("/epub-pairings")
+async def create_epub_pairing(payload: EpubPairingRequest) -> dict[str, Any]:
+ from deeptutor.reading.epub_bilingual import create_epub_pairing
+
+ try:
+ pairing = await asyncio.to_thread(
+ create_epub_pairing,
+ _store(),
+ payload.english_material_id,
+ payload.chinese_material_id,
+ )
+ return {"pairing": pairing}
+ except Exception as exc:
+ raise _http_error(exc) from exc
+
+
[email protected]("/epub-pairings/{pairing_id}")
+async def remove_epub_pairing(pairing_id: str) -> dict[str, Any]:
+ from deeptutor.reading.epub_bilingual import delete_epub_pairing
+
+ try:
+ removed = await asyncio.to_thread(delete_epub_pairing, _store(), pairing_id)
+ except Exception as exc:
+ raise _http_error(exc) from exc
+ if not removed:
+ raise HTTPException(status_code=404, detail="EPUB pairing not found")
+ return {"status": "ok", "pairing_id": pairing_id}
+
+
@router.delete("/materials/{material_id}")
async def delete_material(material_id: str) -> dict[str, Any]:
store = _store()
diff --git a/deeptutor/reading/__init__.py b/deeptutor/reading/__init__.py
index 2101de7b2..e820f26a6 100644
--- a/deeptutor/reading/__init__.py
+++ b/deeptutor/reading/__init__.py
@@ -23,6 +23,12 @@ is testable on its own and the capability that drives it
from __future__ import annotations
+from deeptutor.reading.epub_bilingual import (
+ create_epub_pairing,
+ delete_epub_pairing,
+ list_epub_pairings,
+ recommend_epub_candidates,
+)
from deeptutor.reading.export import ExportFormat, ExportResult, export_material
from deeptutor.reading.extract import Extraction, extract_material
from deeptutor.reading.models import (
@@ -77,11 +83,15 @@ __all__ = [
"UnitKind",
"UnitReference",
"content_hash",
+ "create_epub_pairing",
+ "delete_epub_pairing",
"export_material",
"extract_material",
+ "list_epub_pairings",
"material_summary",
"parse_locators",
"render_outline",
+ "recommend_epub_candidates",
"render_units",
"search_material",
"search_units",
diff --git a/deeptutor/reading/epub_bilingual.py b/deeptutor/reading/epub_bilingual.py
new file mode 100644
index 000000000..a84ce3860
--- /dev/null
+++ b/deeptutor/reading/epub_bilingual.py
@@ -0,0 +1,220 @@
+"""Explicit EPUB pairing metadata.
+
+Pairing is deliberately two-step: DeepTutor recommends likely language
+editions, but a reader explicitly confirms the pair before any downstream
+bilingual rendering or study behavior is enabled. This module stores only that
+confirmation; derived EPUB generation belongs to a later feature.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import threading
+from typing import Any
+import uuid
+import xml.etree.ElementTree as ET
+import zipfile
+
+from deeptutor.reading.models import MaterialManifest, ReadingError
+from deeptutor.reading.store import ReadingStore
+
+PAIRINGS_NAME = "_epub_pairings.json"
+_PAIRING_WRITE_LOCK = threading.Lock()
+
+
+def _local_name(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1].casefold()
+
+
+def _metadata(epub: Path) -> dict[str, str]:
+ """Read enough OPF metadata to rank, never to pair automatically."""
+ try:
+ with zipfile.ZipFile(epub) as archive:
+ opf_name = next(name for name in archive.namelist() if name.casefold().endswith(".opf"))
+ root = ET.fromstring(archive.read(opf_name))
+ except (OSError, StopIteration, zipfile.BadZipFile, ET.ParseError):
+ return {}
+
+ wanted = ("title", "creator", "identifier", "language")
+ values: dict[str, str] = {}
+ for element in root.iter():
+ name = _local_name(element.tag)
+ if name in wanted and name not in values:
+ values[name] = " ".join((element.text or "").split())
+ return values
+
+
+def _language(value: str) -> str:
+ return value.strip().casefold().split("-", 1)[0]
+
+
+def _tokens(value: str) -> set[str]:
+ return set(re.findall(r"[\w\u3400-\u9fff]+", value.casefold()))
+
+
+def _outline_titles(store: ReadingStore, material_id: str) -> set[str]:
+ return {row.title.casefold() for row in store.outline(material_id) if row.title}
+
+
+def recommend_epub_candidates(store: ReadingStore, material_id: str) -> list[dict[str, Any]]:
+ """Return likely alternate-language editions for explicit confirmation."""
+ source = store.manifest(material_id)
+ _require_epub(source, "EPUB pairing")
+ source_path = _raw_epub(store, material_id, "The source EPUB is unavailable.")
+ source_meta = _metadata(source_path)
+ source_titles = _outline_titles(store, material_id)
+ source_language = _language(source_meta.get("language") or "")
+
+ candidates: list[dict[str, Any]] = []
+ for candidate in store.list_materials():
+ if candidate.material_id == material_id or candidate.render_mode != "epub":
+ continue
+ try:
+ candidate_path = _raw_epub(
+ store, candidate.material_id, "The candidate EPUB is unavailable."
+ )
+ except ReadingError:
+ continue
+ metadata = _metadata(candidate_path)
+ title_a = _tokens(source_meta.get("title") or source.title)
+ title_b = _tokens(metadata.get("title") or candidate.title)
+ title_score = len(title_a & title_b) / max(1, len(title_a | title_b))
+ candidate_titles = _outline_titles(store, candidate.material_id)
+ toc_score = len(source_titles & candidate_titles) / max(
+ 1, len(source_titles | candidate_titles)
+ )
+ identifier_match = bool(
+ source_meta.get("identifier")
+ and source_meta.get("identifier") == metadata.get("identifier")
+ )
+ author_match = bool(
+ source_meta.get("author")
+ and source_meta.get("author").casefold() == metadata.get("creator", "").casefold()
+ )
+ candidate_language = _language(metadata.get("language") or "")
+ language_bonus = float(
+ bool(source_language)
+ and bool(candidate_language)
+ and source_language != candidate_language
+ )
+ score = (
+ 0.4 * title_score
+ + 0.2 * toc_score
+ + 0.2 * float(identifier_match)
+ + 0.1 * float(author_match)
+ + 0.1 * language_bonus
+ )
+ candidates.append(
+ {
+ "material_id": candidate.material_id,
+ "title": candidate.title,
+ "filename": candidate.filename,
+ "language": metadata.get("language", ""),
+ "author": metadata.get("creator", ""),
+ "score": round(score, 4),
+ "reasons": {
+ "title": round(title_score, 4),
+ "toc": round(toc_score, 4),
+ "identifier": identifier_match,
+ "author": author_match,
+ "different_language": bool(language_bonus),
+ },
+ }
+ )
+ return sorted(candidates, key=lambda row: (-row["score"], row["title"]))
+
+
+def _require_epub(manifest: MaterialManifest, action: str) -> None:
+ if manifest.render_mode != "epub":
+ raise ReadingError(f"{action} is only available for EPUB materials.")
+
+
+def _raw_epub(store: ReadingStore, material_id: str, error: str) -> Path:
+ path = store.raw_path(material_id)
+ if path is None:
+ raise ReadingError(error)
+ return path
+
+
+def _pairing_path(store: ReadingStore) -> Path:
+ return store.root / PAIRINGS_NAME
+
+
+def _atomic_write(path: Path, payload: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = path.parent / f".{path.name}.{uuid.uuid4().hex[:8]}.tmp"
+ try:
+ temporary.write_text(payload, encoding="utf-8")
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def list_epub_pairings(store: ReadingStore) -> list[dict[str, Any]]:
+ try:
+ rows = json.loads(_pairing_path(store).read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, json.JSONDecodeError):
+ return []
+ return rows if isinstance(rows, list) else []
+
+
+def create_epub_pairing(
+ store: ReadingStore, english_material_id: str, chinese_material_id: str
+) -> dict[str, Any]:
+ """Record an explicit reader-confirmed pair without deriving a material."""
+ english = store.manifest(english_material_id)
+ chinese = store.manifest(chinese_material_id)
+ _require_epub(english, "The English pairing source")
+ _require_epub(chinese, "The Chinese pairing source")
+ if english.material_id == chinese.material_id:
+ raise ReadingError("Choose two different EPUB editions.")
+ english_path = _raw_epub(store, english.material_id, "The English EPUB is unavailable.")
+ chinese_path = _raw_epub(store, chinese.material_id, "The Chinese EPUB is unavailable.")
+ english_language = _language(_metadata(english_path).get("language") or "")
+ chinese_language = _language(_metadata(chinese_path).get("language") or "")
+ if english_language == chinese_language:
+ raise ReadingError("Pair an English EPUB with a different-language edition.")
+
+ pairing_id = hashlib.sha256(
+ f"{english.material_id}\0{chinese.material_id}".encode("utf-8")
+ ).hexdigest()[:16]
+ row = {
+ "pairing_id": pairing_id,
+ "english_material_id": english.material_id,
+ "english_title": english.title,
+ "english_language": english_language,
+ "chinese_material_id": chinese.material_id,
+ "chinese_title": chinese.title,
+ "chinese_language": chinese_language,
+ "status": "confirmed",
+ "confirmed_at": datetime.now(timezone.utc).isoformat(),
+ }
+ with _PAIRING_WRITE_LOCK:
+ rows = [item for item in list_epub_pairings(store) if item.get("pairing_id") != pairing_id]
+ rows.append(row)
+ _atomic_write(_pairing_path(store), json.dumps(rows, ensure_ascii=False, indent=2))
+ return row
+
+
+def delete_epub_pairing(store: ReadingStore, pairing_id: str) -> bool:
+ """Remove the pairing record while preserving both source materials."""
+ rows = list_epub_pairings(store)
+ with _PAIRING_WRITE_LOCK:
+ remaining = [row for row in rows if row.get("pairing_id") != pairing_id]
+ if len(remaining) == len(rows):
+ return False
+ _atomic_write(_pairing_path(store), json.dumps(remaining, ensure_ascii=False, indent=2))
+ return True
+
+
+__all__ = [
+ "create_epub_pairing",
+ "delete_epub_pairing",
+ "list_epub_pairings",
+ "recommend_epub_candidates",
+]
diff --git a/tests/reading/test_epub_bilingual.py b/tests/reading/test_epub_bilingual.py
new file mode 100644
index 000000000..33ef8d057
--- /dev/null
+++ b/tests/reading/test_epub_bilingual.py
@@ -0,0 +1,129 @@
+"""Engine tests for explicit bilingual EPUB pairing."""
+
+from __future__ import annotations
+
+import base64
+from pathlib import Path
+import zipfile
+
+from deeptutor.reading.epub_bilingual import (
+ create_epub_pairing,
+ delete_epub_pairing,
+ list_epub_pairings,
+ recommend_epub_candidates,
+)
+from deeptutor.reading.store import ReadingStore
+
+PNG_BYTES = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
+)
+
+
+def _write_epub(
+ path: Path,
+ *,
+ language: str,
+ chapter: str,
+ paragraph: str,
+ include_image: bool = False,
+) -> Path:
+ image_manifest = (
+ "<item id='picture' href='picture.png' media-type='image/png'/>" if include_image else ""
+ )
+ image_body = (
+ "<img src='picture.png' alt='source illustration' width='240' height='80'/>"
+ if include_image
+ else ""
+ )
+ with zipfile.ZipFile(path, "w") as archive:
+ archive.writestr("mimetype", "application/epub+zip", zipfile.ZIP_STORED)
+ archive.writestr(
+ "META-INF/container.xml",
+ "<container xmlns='urn:oasis:names:tc:opendocument:xmlns:container'>"
+ "<rootfiles><rootfile full-path='OPS/book.opf'/></rootfiles></container>",
+ )
+ archive.writestr(
+ "OPS/book.opf",
+ "<package xmlns='http://www.idpf.org/2007/opf' "
+ "xmlns:dc='http://purl.org/dc/elements/1.1/' version='3.0'>"
+ "<metadata><dc:identifier>urn:uuid:bilingual-test</dc:identifier>"
+ f"<dc:title>Bilingual test</dc:title><dc:language>{language}</dc:language>"
+ "<dc:creator>Fixture Author</dc:creator></metadata>"
+ f"<manifest><item id='one' href='one.xhtml' media-type='application/xhtml+xml'/>{image_manifest}</manifest>"
+ "<spine><itemref idref='one'/></spine></package>",
+ )
+ archive.writestr(
+ "OPS/one.xhtml",
+ "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>"
+ f"{chapter}</title></head><body><h1>{chapter}</h1>"
+ f"<p>{paragraph}</p>{image_body}</body></html>",
+ )
+ if include_image:
+ archive.writestr("OPS/picture.png", PNG_BYTES)
+ return path
+
+
+def test_candidates_rank_a_different_language_edition_without_auto_pairing(
+ tmp_path: Path,
+) -> None:
+ store = ReadingStore(root=tmp_path / "materials")
+ english = store.ingest(
+ _write_epub(
+ tmp_path / "english.epub",
+ language="en",
+ chapter="Illustrated chapter",
+ paragraph="English source paragraph.",
+ include_image=True,
+ )
+ )
+ chinese = store.ingest(
+ _write_epub(
+ tmp_path / "chinese.epub",
+ language="zh-CN",
+ chapter="插图章节",
+ paragraph="中文来源段落。",
+ )
+ )
+
+ candidates = recommend_epub_candidates(store, english.material_id)
+
+ assert candidates[0]["material_id"] == chinese.material_id
+ assert candidates[0]["reasons"]["identifier"] is True
+ assert candidates[0]["reasons"]["different_language"] is True
+ assert list_epub_pairings(store) == []
+
+
+def test_explicit_pairing_stores_metadata_without_deriving_material(tmp_path: Path) -> None:
+ store = ReadingStore(root=tmp_path / "materials")
+ english = store.ingest(
+ _write_epub(
+ tmp_path / "english.epub",
+ language="en",
+ chapter="Illustrated chapter",
+ paragraph="English source paragraph.",
+ include_image=True,
+ )
+ )
+ chinese = store.ingest(
+ _write_epub(
+ tmp_path / "chinese.epub",
+ language="zh",
+ chapter="插图章节",
+ paragraph="中文来源段落。",
+ )
+ )
+
+ material_ids = {row.material_id for row in store.list_materials()}
+ pairing = create_epub_pairing(store, english.material_id, chinese.material_id)
+
+ assert pairing["english_material_id"] == english.material_id
+ assert pairing["chinese_material_id"] == chinese.material_id
+ assert pairing["english_language"] == "en"
+ assert pairing["chinese_language"] == "zh"
+ assert pairing["status"] == "confirmed"
+ assert list_epub_pairings(store) == [pairing]
+ assert {row.material_id for row in store.list_materials()} == material_ids
+
+ assert delete_epub_pairing(store, pairing["pairing_id"]) is True
+ assert list_epub_pairings(store) == []
+ assert {row.material_id for row in store.list_materials()} == material_ids
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index 7fb380bfc..73a4ecad3 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -59,7 +59,7 @@ def _upload(client: TestClient, name: str = "attention.pdf", data: bytes | None
return response.json()
-def _epub_bytes() -> bytes:
+def _epub_bytes(*, language: str = "en", paragraph: str = "Readable EPUB text.") -> bytes:
stream = io.BytesIO()
with zipfile.ZipFile(stream, "w") as archive:
archive.writestr("mimetype", "application/epub+zip")
@@ -69,10 +69,16 @@ def _epub_bytes() -> bytes:
)
archive.writestr(
"OPS/book.opf",
- "<package><manifest><item id='one' href='one.xhtml'/></manifest><spine><itemref idref='one'/></spine></package>",
+ "<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>"
+ f"<dc:language>{language}</dc:language></metadata>"
+ "<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>"
+ "OPS/one.xhtml",
+ f"<html><body><h1>Opening</h1><p>{paragraph}</p></body></html>",
)
return stream.getvalue()
@@ -190,6 +196,59 @@ 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_pairing_requires_confirmation_and_preserves_source_materials(
+ client: TestClient,
+) -> None:
+ english = _upload(client, name="english.epub", data=_epub_bytes())
+ chinese = _upload(
+ client,
+ name="chinese.epub",
+ data=_epub_bytes(language="zh", paragraph="可读的 EPUB 文本。"),
+ )
+
+ candidates = client.get(
+ f"/api/v1/reading/materials/{english['material_id']}/epub-pairing-candidates"
+ )
+ assert candidates.status_code == 200
+ assert candidates.json()[0]["material_id"] == chinese["material_id"]
+ assert client.get("/api/v1/reading/epub-pairings").json() == []
+
+ created = client.post(
+ "/api/v1/reading/epub-pairings",
+ json={
+ "english_material_id": english["material_id"],
+ "chinese_material_id": chinese["material_id"],
+ },
+ )
+ assert created.status_code == 200, created.text
+ body = created.json()
+ assert body["pairing"]["status"] == "confirmed"
+ assert body["pairing"]["english_material_id"] == english["material_id"]
+ assert body["pairing"]["chinese_material_id"] == chinese["material_id"]
+ assert client.get("/api/v1/reading/epub-pairings").json() == [body["pairing"]]
+ assert len(client.get("/api/v1/reading/materials").json()) == 2
+
+ removed = client.delete(f"/api/v1/reading/epub-pairings/{body['pairing']['pairing_id']}")
+ assert removed.status_code == 200
+ assert client.get("/api/v1/reading/epub-pairings").json() == []
+ assert len(client.get("/api/v1/reading/materials").json()) == 2
+
+
+def test_epub_pairing_rejects_the_same_language(client: TestClient) -> None:
+ english = _upload(client, name="english.epub", data=_epub_bytes())
+ other = _upload(client, name="other.epub", data=_epub_bytes())
+
+ response = client.post(
+ "/api/v1/reading/epub-pairings",
+ json={
+ "english_material_id": english["material_id"],
+ "chinese_material_id": other["material_id"],
+ },
+ )
+
+ assert response.status_code == 400
+
+
# ---------------------------------------------------------------------------
# unit text and raw bytes
# ---------------------------------------------------------------------------