Skip to content

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

feat(reading): persist W3C text selectors

XZH4f94c6f1f9fa
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index d02d0e909..02c7b660d 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -25,7 +25,7 @@ from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Query, UploadFile
from fastapi.params import File
from fastapi.responses import FileResponse, Response
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
from deeptutor.reading import (
ANNOTATION_COLORS,
@@ -101,6 +101,25 @@ class UnitText(BaseModel):
text: str
+class TextQuoteSelectorPayload(BaseModel):
+ type: Literal["TextQuoteSelector"]
+ exact: str = Field(min_length=1, max_length=2000)
+ prefix: str = Field(default="", max_length=128)
+ suffix: str = Field(default="", max_length=128)
+
+
+class TextPositionSelectorPayload(BaseModel):
+ type: Literal["TextPositionSelector"]
+ start: int = Field(ge=0)
+ end: int = Field(gt=0)
+
+ @model_validator(mode="after")
+ def ordered(self) -> "TextPositionSelectorPayload":
+ if self.end <= self.start:
+ raise ValueError("selector end must be greater than start")
+ return self
+
+
class AnnotationPayload(BaseModel):
"""An annotation as the reader sends it.
@@ -114,10 +133,14 @@ class AnnotationPayload(BaseModel):
locator: int = Field(ge=1)
kind: Literal["highlight", "underline", "note"] = "highlight"
color: str = "yellow"
- quote: str = ""
+ quote: str = Field(default="", max_length=2000)
note: str = ""
rects: list[list[float]] = Field(default_factory=list)
source_anchor: str = Field(default="", max_length=4096)
+ selectors: list[TextQuoteSelectorPayload | TextPositionSelectorPayload] = Field(
+ default_factory=list,
+ max_length=2,
+ )
def to_annotation(self) -> Annotation:
return Annotation.from_dict(
@@ -130,6 +153,7 @@ class AnnotationPayload(BaseModel):
"note": self.note,
"rects": self.rects,
"source_anchor": self.source_anchor,
+ "selectors": [selector.model_dump() for selector in self.selectors],
"author": "user",
}
)
@@ -144,6 +168,7 @@ class AnnotationInfo(BaseModel):
note: str
rects: list[list[float]]
source_anchor: str = ""
+ selectors: list[dict[str, Any]] = Field(default_factory=list)
author: str
created_at: float
updated_at: float
diff --git a/deeptutor/reading/__init__.py b/deeptutor/reading/__init__.py
index 2101de7b2..01c9ebc7d 100644
--- a/deeptutor/reading/__init__.py
+++ b/deeptutor/reading/__init__.py
@@ -38,6 +38,9 @@ from deeptutor.reading.models import (
Rect,
RenderMode,
SearchHit,
+ TextPositionSelector,
+ TextQuoteSelector,
+ TextSelector,
UnitKind,
UnitReference,
)
@@ -74,6 +77,9 @@ __all__ = [
"SearchHit",
"SearchResult",
"RenderMode",
+ "TextPositionSelector",
+ "TextQuoteSelector",
+ "TextSelector",
"UnitKind",
"UnitReference",
"content_hash",
diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py
index 220b422bc..509b5b231 100644
--- a/deeptutor/reading/models.py
+++ b/deeptutor/reading/models.py
@@ -25,6 +25,7 @@ UnitKind = Literal["page", "chapter", "slide", "section"]
RenderMode = Literal["text", "pdf", "epub"]
AnnotationKind = Literal["highlight", "underline", "note"]
+TextSelectorType = Literal["TextQuoteSelector", "TextPositionSelector"]
# Palette offered by the reader toolbar. Kept server-side too so an annotation
# arriving from an older client (or a tool call) can be validated rather than
@@ -245,6 +246,70 @@ class MaterialManifest:
)
+@dataclass(frozen=True, slots=True)
+class TextQuoteSelector:
+ """W3C TextQuoteSelector used to re-anchor text after content reflows."""
+
+ exact: str
+ prefix: str = ""
+ suffix: str = ""
+ type: Literal["TextQuoteSelector"] = "TextQuoteSelector"
+
+ def to_dict(self) -> dict[str, Any]:
+ row: dict[str, Any] = {"type": self.type, "exact": self.exact}
+ if self.prefix:
+ row["prefix"] = self.prefix
+ if self.suffix:
+ row["suffix"] = self.suffix
+ return row
+
+
+@dataclass(frozen=True, slots=True)
+class TextPositionSelector:
+ """W3C TextPositionSelector in a rendered unit's text-content space."""
+
+ start: int
+ end: int
+ type: Literal["TextPositionSelector"] = "TextPositionSelector"
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"type": self.type, "start": self.start, "end": self.end}
+
+
+TextSelector = TextQuoteSelector | TextPositionSelector
+
+
+def parse_text_selectors(value: Any) -> tuple[TextSelector, ...]:
+ """Parse only the two bounded selector shapes supported by the reader."""
+
+ if not isinstance(value, (list, tuple)):
+ return ()
+ parsed: list[TextSelector] = []
+ for raw in value[:2]:
+ if not isinstance(raw, dict):
+ continue
+ selector_type = str(raw.get("type") or "")
+ if selector_type == "TextQuoteSelector":
+ exact = str(raw.get("exact") or "")[:2000]
+ if exact:
+ parsed.append(
+ TextQuoteSelector(
+ exact=exact,
+ prefix=str(raw.get("prefix") or "")[-128:],
+ suffix=str(raw.get("suffix") or "")[:128],
+ )
+ )
+ elif selector_type == "TextPositionSelector":
+ try:
+ start = max(0, int(raw.get("start") or 0))
+ end = max(start, int(raw.get("end") or 0))
+ except (TypeError, ValueError):
+ continue
+ if end > start:
+ parsed.append(TextPositionSelector(start=start, end=end))
+ return tuple(parsed)
+
+
@dataclass(frozen=True, slots=True)
class Annotation:
"""One user (or model) mark on a material.
@@ -264,6 +329,9 @@ class Annotation:
rects: tuple[Rect, ...] = ()
# Opaque renderer-native position. EPUB clients store a CFI here.
source_anchor: str = ""
+ # Portable W3C selectors for reflowing text. Existing annotations omit
+ # them and continue to resolve through ``quote`` and/or ``rects``.
+ selectors: tuple[TextSelector, ...] = ()
author: str = "user"
created_at: float = field(default_factory=time.time)
updated_at: float = field(default_factory=time.time)
@@ -281,6 +349,7 @@ class Annotation:
"note": self.note,
"rects": [r.to_list() for r in self.rects],
"source_anchor": self.source_anchor,
+ "selectors": [selector.to_dict() for selector in self.selectors],
"author": self.author,
"created_at": self.created_at,
"updated_at": self.updated_at,
@@ -304,6 +373,7 @@ class Annotation:
note=str(data.get("note") or ""),
rects=rects,
source_anchor=str(data.get("source_anchor") or ""),
+ selectors=parse_text_selectors(data.get("selectors")),
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),
@@ -351,6 +421,10 @@ __all__ = [
"RenderMode",
"Rect",
"SearchHit",
+ "TextPositionSelector",
+ "TextQuoteSelector",
+ "TextSelector",
+ "TextSelectorType",
"UnitKind",
"UnitReference",
]
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index a8b7bcc0d..f5be2846a 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -49,6 +49,7 @@ from deeptutor.reading.models import (
ReadingPosition,
ReadingUpgradeConflict,
UnitReference,
+ TextQuoteSelector,
)
logger = logging.getLogger(__name__)
@@ -481,6 +482,18 @@ class ReadingStore:
)
if len(annotation.source_anchor) > 4096:
raise ReadingError("source anchor is too long")
+ quote_selector = next(
+ (
+ selector
+ for selector in annotation.selectors
+ if isinstance(selector, TextQuoteSelector)
+ ),
+ None,
+ )
+ if quote_selector and annotation.quote and quote_selector.exact != annotation.quote:
+ raise ReadingError("annotation quote does not match its TextQuoteSelector")
+ if quote_selector and not annotation.quote:
+ annotation = dataclass_replace(annotation, quote=quote_selector.exact)
with self._locked(material_id):
existing = self.annotations(material_id)
stored = annotation
diff --git a/tests/reading/test_engine.py b/tests/reading/test_engine.py
index b626c0d4d..0c0135ed1 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -18,6 +18,8 @@ from deeptutor.reading import (
ReadingError,
ReadingStore,
Rect,
+ TextPositionSelector,
+ TextQuoteSelector,
export_material,
parse_locators,
render_outline,
@@ -427,6 +429,53 @@ def test_annotations_round_trip_with_generated_ids(store: ReadingStore, pdf_path
assert stored[0].rects[0].to_list() == [0.1, 0.2, 0.5, 0.25]
+def test_w3c_text_selectors_round_trip_and_can_supply_the_quote(
+ store: ReadingStore, pdf_path: Path
+) -> None:
+ manifest = store.ingest(pdf_path)
+
+ saved = store.save_annotation(
+ manifest.material_id,
+ Annotation(
+ annotation_id="",
+ locator=1,
+ selectors=(
+ TextQuoteSelector(exact="Introduction", suffix=" to attention"),
+ TextPositionSelector(start=0, end=12),
+ ),
+ ),
+ )
+
+ assert saved.quote == "Introduction"
+ assert [
+ selector.to_dict() for selector in store.annotations(manifest.material_id)[0].selectors
+ ] == [
+ {
+ "type": "TextQuoteSelector",
+ "exact": "Introduction",
+ "suffix": " to attention",
+ },
+ {"type": "TextPositionSelector", "start": 0, "end": 12},
+ ]
+
+
+def test_mismatched_quote_and_text_quote_selector_are_rejected(
+ store: ReadingStore, pdf_path: Path
+) -> None:
+ manifest = store.ingest(pdf_path)
+
+ with pytest.raises(ReadingError, match="does not match"):
+ store.save_annotation(
+ manifest.material_id,
+ Annotation(
+ annotation_id="",
+ locator=1,
+ quote="Introduction",
+ selectors=(TextQuoteSelector(exact="different text"),),
+ ),
+ )
+
+
def test_saving_the_same_id_updates_in_place_and_keeps_created_at(
store: ReadingStore, pdf_path: Path
) -> None:
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index 7fb380bfc..10cc92f2b 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -286,6 +286,74 @@ def test_annotation_create_update_list_delete_round_trip(client: TestClient) ->
assert client.delete(f"{base}/{created['annotation_id']}").status_code == 404
+def test_annotation_round_trips_w3c_text_selectors(client: TestClient) -> None:
+ material = _upload(client)
+ base = f"/api/v1/reading/materials/{material['material_id']}/annotations"
+
+ created = client.put(
+ base,
+ json={
+ "locator": 1,
+ "quote": "Sequence models",
+ "selectors": [
+ {
+ "type": "TextQuoteSelector",
+ "exact": "Sequence models",
+ "suffix": " are",
+ },
+ {"type": "TextPositionSelector", "start": 0, "end": 15},
+ ],
+ },
+ )
+
+ assert created.status_code == 200
+ assert created.json()["selectors"] == [
+ {
+ "type": "TextQuoteSelector",
+ "exact": "Sequence models",
+ "suffix": " are",
+ },
+ {"type": "TextPositionSelector", "start": 0, "end": 15},
+ ]
+
+
+def test_annotation_rejects_mismatched_quote_selector(client: TestClient) -> None:
+ material = _upload(client)
+ response = client.put(
+ f"/api/v1/reading/materials/{material['material_id']}/annotations",
+ json={
+ "locator": 1,
+ "quote": "Sequence models",
+ "selectors": [
+ {"type": "TextQuoteSelector", "exact": "different text"},
+ ],
+ },
+ )
+
+ assert response.status_code == 400
+ assert "does not match" in response.json()["detail"]
+
+
+ "selector",
+ [
+ {"type": "TextPositionSelector", "start": 5, "end": 5},
+ {"type": "TextPositionSelector", "start": 6, "end": 5},
+ ],
+)
+def test_annotation_rejects_invalid_text_positions(
+ client: TestClient,
+ selector: dict,
+) -> None:
+ material = _upload(client)
+ response = client.put(
+ f"/api/v1/reading/materials/{material['material_id']}/annotations",
+ json={"locator": 1, "quote": "x", "selectors": [selector]},
+ )
+
+ assert response.status_code == 422
+
+
def test_annotation_on_an_out_of_range_locator_is_a_400(client: TestClient) -> None:
material = _upload(client)