Skip to content

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

fix(reading): keep selector anchors coherent

Bingxi Zhao (Frank)ebe8e147f413
diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py
index 671c6fb85..c5fd458eb 100644
--- a/deeptutor/reading/models.py
+++ b/deeptutor/reading/models.py
@@ -296,7 +296,10 @@ def parse_text_selectors(value: Any) -> tuple[TextSelector, ...]:
parsed.append(
TextQuoteSelector(
exact=exact,
- prefix=str(raw.get("prefix") or "")[:128],
+ # W3C prefix is the text immediately before ``exact``;
+ # when legacy data exceeds the bound, its tail is the
+ # part that still touches the selection.
+ prefix=str(raw.get("prefix") or "")[-128:],
suffix=str(raw.get("suffix") or "")[:128],
)
)
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index 58bdfb804..1f052d83e 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -75,6 +75,38 @@ _ID_LENGTH = 16
MAX_READ_CHARS = 60_000
+def _normalise_selector_text(value: str) -> str:
+ return re.sub(r"\s+", " ", value).strip()
+
+
+def _find_quote_span(text: str, selector: TextQuoteSelector) -> tuple[int, int] | None:
+ """Resolve a quote while preserving offsets into the unnormalised source."""
+
+ words = re.findall(r"\S+", selector.exact)
+ if not words:
+ return None
+ pattern = re.compile(r"\s+".join(re.escape(word) for word in words))
+ for match in pattern.finditer(text):
+ span = (match.start(), match.end())
+ if _quote_context_matches(text, span, selector):
+ return span
+ return None
+
+
+def _quote_context_matches(
+ text: str,
+ span: tuple[int, int],
+ selector: TextQuoteSelector,
+) -> bool:
+ wanted_prefix = _normalise_selector_text(selector.prefix)
+ wanted_suffix = _normalise_selector_text(selector.suffix)
+ preceding = _normalise_selector_text(text[: span[0]])
+ following = _normalise_selector_text(text[span[1] :])
+ return (not wanted_prefix or preceding.endswith(wanted_prefix)) and (
+ not wanted_suffix or following.startswith(wanted_suffix)
+ )
+
+
def _atomic_write(path: Path, payload: str) -> None:
"""Write *payload* to *path* atomically within the same directory."""
path.parent.mkdir(parents=True, exist_ok=True)
@@ -484,33 +516,65 @@ 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,
- )
+ quote_selectors = [
+ selector for selector in annotation.selectors if isinstance(selector, TextQuoteSelector)
+ ]
+ position_selectors = [
+ selector
+ for selector in annotation.selectors
+ if isinstance(selector, TextPositionSelector)
+ ]
+ if len(quote_selectors) > 1 or len(position_selectors) > 1:
+ raise ReadingError("annotations may contain at most one selector of each type")
+ quote_selector = quote_selectors[0] if quote_selectors else None
+ position_selector = position_selectors[0] if position_selectors else None
if annotation.selectors:
unit_text = self.unit_text(material_id, annotation.locator)
else:
unit_text = ""
+ position_text = ""
+ if position_selector:
+ if position_selector.end > len(unit_text):
+ raise ReadingError("TextPositionSelector extends past this reading unit")
+ if position_selector.end - position_selector.start > MAX_TEXT_SELECTOR_CHARS:
+ raise ReadingError("TextPositionSelector span is too long")
+ position_text = unit_text[position_selector.start : position_selector.end]
if quote_selector:
- if annotation.quote and quote_selector.exact != annotation.quote:
+ normalised_exact = _normalise_selector_text(quote_selector.exact)
+ if not normalised_exact:
+ raise ReadingError("TextQuoteSelector exact text is empty")
+ if annotation.quote and _normalise_selector_text(annotation.quote) != normalised_exact:
raise ReadingError("annotation quote does not match its TextQuoteSelector")
- if re.sub(r"\s+", " ", quote_selector.exact).strip() not in re.sub(
- r"\s+", " ", unit_text
- ):
- raise ReadingError("TextQuoteSelector does not occur in this reading unit")
- if quote_selector and not annotation.quote:
- annotation = dataclass_replace(annotation, quote=quote_selector.exact)
- for selector in annotation.selectors:
- if isinstance(selector, TextPositionSelector):
- if selector.end > len(unit_text):
- raise ReadingError("TextPositionSelector extends past this reading unit")
- if selector.end - selector.start > MAX_TEXT_SELECTOR_CHARS:
- raise ReadingError("TextPositionSelector span is too long")
+ if position_selector:
+ if _normalise_selector_text(position_text) != normalised_exact:
+ raise ReadingError("text quote and position selectors describe different text")
+ if not _quote_context_matches(
+ unit_text,
+ (position_selector.start, position_selector.end),
+ quote_selector,
+ ):
+ raise ReadingError("TextQuoteSelector context does not match this reading unit")
+ canonical_exact = position_text
+ else:
+ span = _find_quote_span(unit_text, quote_selector)
+ if span is None:
+ raise ReadingError("TextQuoteSelector does not occur in this reading unit")
+ canonical_exact = unit_text[slice(*span)]
+ canonical_quote = dataclass_replace(quote_selector, exact=canonical_exact)
+ annotation = dataclass_replace(
+ annotation,
+ quote=canonical_exact,
+ selectors=tuple(
+ canonical_quote if selector is quote_selector else selector
+ for selector in annotation.selectors
+ ),
+ )
+ elif position_selector:
+ if annotation.quote and _normalise_selector_text(
+ annotation.quote
+ ) != _normalise_selector_text(position_text):
+ raise ReadingError("annotation quote does not match its TextPositionSelector")
+ annotation = dataclass_replace(annotation, quote=position_text)
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 387b71ad1..35e10879c 100644
--- a/tests/reading/test_engine.py
+++ b/tests/reading/test_engine.py
@@ -434,6 +434,8 @@ def test_w3c_text_selectors_round_trip_and_can_supply_the_quote(
store: ReadingStore, pdf_path: Path
) -> None:
manifest = store.ingest(pdf_path)
+ unit_text = store.unit_text(manifest.material_id, 1)
+ start = unit_text.index("Introduction")
saved = store.save_annotation(
manifest.material_id,
@@ -441,8 +443,8 @@ def test_w3c_text_selectors_round_trip_and_can_supply_the_quote(
annotation_id="",
locator=1,
selectors=(
- TextQuoteSelector(exact="Introduction", suffix=" to attention"),
- TextPositionSelector(start=0, end=12),
+ TextQuoteSelector(exact="Introduction", suffix=" to sequence"),
+ TextPositionSelector(start=start, end=start + 12),
),
),
)
@@ -454,9 +456,9 @@ def test_w3c_text_selectors_round_trip_and_can_supply_the_quote(
{
"type": "TextQuoteSelector",
"exact": "Introduction",
- "suffix": " to attention",
+ "suffix": " to sequence",
},
- {"type": "TextPositionSelector", "start": 0, "end": 12},
+ {"type": "TextPositionSelector", "start": start, "end": start + 12},
]
@@ -508,7 +510,7 @@ def test_text_position_selector_cannot_extend_past_stored_unit(
)
-def test_legacy_selector_parser_trims_prefix_from_the_start() -> None:
+def test_legacy_selector_parser_keeps_prefix_tail_nearest_the_quote() -> None:
parsed = parse_text_selectors(
[
{
@@ -520,7 +522,47 @@ def test_legacy_selector_parser_trims_prefix_from_the_start() -> None:
)
assert isinstance(parsed[0], TextQuoteSelector)
- assert parsed[0].prefix == "a" * 128
+ assert parsed[0].prefix == "b" * 128
+
+
+def test_selector_whitespace_is_canonicalised_to_stored_unit(
+ store: ReadingStore, pdf_path: Path
+) -> None:
+ manifest = store.ingest(pdf_path)
+ unit_path = store.root / manifest.material_id / "units" / "0001.txt"
+ unit_path.write_text("Before Sequence\n\nmodels after", encoding="utf-8")
+
+ saved = store.save_annotation(
+ manifest.material_id,
+ Annotation(
+ annotation_id="",
+ locator=1,
+ quote="Sequence models",
+ selectors=(TextQuoteSelector(exact="Sequence models", prefix="Before"),),
+ ),
+ )
+
+ assert saved.quote == "Sequence\n\nmodels"
+ assert saved.selectors[0].to_dict()["exact"] == "Sequence\n\nmodels"
+
+
+def test_quote_and_position_selectors_must_identify_the_same_text(
+ store: ReadingStore, pdf_path: Path
+) -> None:
+ manifest = store.ingest(pdf_path)
+
+ with pytest.raises(ReadingError, match="different text"):
+ store.save_annotation(
+ manifest.material_id,
+ Annotation(
+ annotation_id="",
+ locator=1,
+ selectors=(
+ TextQuoteSelector(exact="Introduction"),
+ TextPositionSelector(start=0, end=7),
+ ),
+ ),
+ )
def test_saving_the_same_id_updates_in_place_and_keeps_created_at(
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index 188dd8ef5..57f2fd3d5 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -299,21 +299,23 @@ def test_annotation_round_trips_w3c_text_selectors(client: TestClient) -> None:
{
"type": "TextQuoteSelector",
"exact": "Sequence models",
- "suffix": " are",
+ "prefix": "Chapter one. ",
+ "suffix": " read",
},
- {"type": "TextPositionSelector", "start": 0, "end": 15},
+ {"type": "TextPositionSelector", "start": 13, "end": 28},
],
},
)
- assert created.status_code == 200
+ assert created.status_code == 200, created.text
assert created.json()["selectors"] == [
{
"type": "TextQuoteSelector",
"exact": "Sequence models",
- "suffix": " are",
+ "prefix": "Chapter one. ",
+ "suffix": " read",
},
- {"type": "TextPositionSelector", "start": 0, "end": 15},
+ {"type": "TextPositionSelector", "start": 13, "end": 28},
]