diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py index 25b27bd11..cde1e1834 100644 --- a/deeptutor/reading/models.py +++ b/deeptutor/reading/models.py @@ -27,6 +27,9 @@ ContentFormat = Literal["plain_text", "web_markdown"] AnnotationKind = Literal["highlight", "underline", "note", "citation"] TextSelectorType = Literal["TextQuoteSelector", "TextPositionSelector"] + +AnnotationResolution = Literal["resolved", "unresolved", "ambiguous"] + MAX_TEXT_SELECTOR_CHARS = 2000 # Palette offered by the reader toolbar. Kept server-side too so an annotation @@ -357,6 +360,12 @@ class Annotation: # Portable W3C selectors for reflowing text. Existing annotations omit # them and continue to resolve through ``quote`` and/or ``rects``. selectors: tuple[TextSelector, ...] = () + # Selector validity against the current content revision. Legacy rows + # predate this field and default to ``resolved`` so they are not hidden + # from readers who already had them visible. Revision migration flips + # rows to ``unresolved`` or ``ambiguous`` when the stored quote no longer + # identifies exactly one passage in the new unit text. + resolution: AnnotationResolution = "resolved" author: str = "user" created_at: float = field(default_factory=time.time) updated_at: float = field(default_factory=time.time) @@ -376,6 +385,7 @@ class Annotation: "rects": [r.to_list() for r in self.rects], "source_anchor": self.source_anchor, "selectors": [selector.to_dict() for selector in self.selectors], + "resolution": self.resolution, "author": self.author, "created_at": self.created_at, "updated_at": self.updated_at, @@ -401,6 +411,11 @@ class Annotation: rects=rects, source_anchor=str(data.get("source_anchor") or ""), selectors=parse_text_selectors(data.get("selectors")), + resolution=( + data["resolution"] + if data.get("resolution") in ("resolved", "unresolved", "ambiguous") + else "resolved" + ), 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), @@ -482,6 +497,7 @@ __all__ = [ "DEFAULT_ANNOTATION_COLOR", "Annotation", "AnnotationKind", + "AnnotationResolution", "ContentFormat", "MaterialManifest", "MaterialNotFound", diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py index d9c142464..fa7f64691 100644 --- a/deeptutor/reading/store.py +++ b/deeptutor/reading/store.py @@ -121,6 +121,24 @@ def _quote_context_matches( ) +def _find_all_quote_spans(text: str, selector: TextQuoteSelector) -> list[tuple[int, int]]: + """All spans matching the quote, preferring context-filtered matches. + + When the quote occurs multiple times but only once carries the stored + prefix/suffix context, only the contextual hit is returned — the other + occurrences are coincidence. When context eliminates everything (the + surrounding text shifted), the raw occurrences are returned so the caller + can still distinguish a unique reflow from true ambiguity. + """ + words = re.findall(r"\S+", selector.exact) + if not words: + return [] + pattern = re.compile(r"\s+".join(re.escape(word) for word in words)) + all_spans = [match.span() for match in pattern.finditer(text)] + contextual = [span for span in all_spans if _quote_context_matches(text, span, selector)] + return contextual if contextual else all_spans + + def _read_json(path: Path) -> Any: try: return json.loads(path.read_text(encoding="utf-8")) @@ -485,6 +503,11 @@ class ReadingStore: source_dir = material_dir / dirname if source_dir.is_dir(): shutil.copytree(source_dir, revision_dir / dirname) + # Preserve the pre-migration annotations alongside the + # old revision so the previous state survives for audit. + annotations_state = material_dir / ANNOTATIONS_DIR + if annotations_state.is_dir(): + shutil.copytree(annotations_state, revision_dir / ANNOTATIONS_DIR) for state_name in (ANNOTATIONS_NAME, POSITION_NAME): source_state = material_dir / state_name if source_state.is_file(): @@ -497,6 +520,11 @@ class ReadingStore: stage_dir / state_dir, dirs_exist_ok=True, ) + # Re-anchor selectors against the new revision's text while the + # material directory is still staged. A failure here leaves the + # original annotations untouched and the swap still proceeds. + if existing is not None: + self._reanchor_annotations(stage_dir, manifest.revision) try: if material_dir.exists(): os.replace(material_dir, backup_dir) @@ -847,6 +875,97 @@ class ReadingStore: ] return sorted(parsed, key=lambda a: (a.locator, a.created_at)) + def _reanchor_annotations( + self, + stage_dir: Path, + new_revision: int, + ) -> None: + """Re-anchor selectors after a revision upgrade. + + Called while the new material directory is still staged, before the + atomic swap. Reads the annotations that were just copied forward and + re-resolves each quote against the new unit texts. Reliable matches + are migrated (locator, selectors, and revision bumped); ambiguous or + vanished quotes keep their original locator and revision but are + marked so the reader can show an explicit review state instead of + painting the wrong passage. + """ + annotation_files = list((stage_dir / ANNOTATIONS_DIR).glob("*.json")) + if not annotation_files: + return + annotations_path = annotation_files[0] + rows_data = _read_json(annotations_path) + if not isinstance(rows_data, list) or not rows_data: + return + rows = [ + Annotation.from_dict(row) + for row in rows_data + if isinstance(row, dict) and row.get("annotation_id") + ] + if not rows: + return + + new_unit_texts: dict[int, str] = {} + units_dir = stage_dir / UNITS_DIR + if units_dir.is_dir(): + for unit_file in sorted(units_dir.iterdir()): + if unit_file.suffix == ".txt": + locator = int(unit_file.stem) + new_unit_texts[locator] = unit_file.read_text(encoding="utf-8") + + changed = False + migrated: list[Annotation] = [] + for row in rows: + quote_selectors = [s for s in row.selectors if isinstance(s, TextQuoteSelector)] + if not quote_selectors: + migrated.append(row) + continue + quote_selector = quote_selectors[0] + matches: list[tuple[int, tuple[int, int]]] = [] + for locator, text in sorted(new_unit_texts.items()): + for span in _find_all_quote_spans(text, quote_selector): + matches.append((locator, span)) + if len(matches) == 1: + locator, (start, end) = matches[0] + unit_text = new_unit_texts[locator] + canonical_exact = unit_text[start:end] + new_quote = dataclass_replace(quote_selector, exact=canonical_exact) + new_selectors = [] + for s in row.selectors: + if s is quote_selector: + new_selectors.append(new_quote) + elif isinstance(s, TextPositionSelector): + new_selectors.append(TextPositionSelector(start=start, end=end)) + else: + new_selectors.append(s) + migrated.append( + dataclass_replace( + row, + locator=locator, + quote=canonical_exact, + selectors=tuple(new_selectors), + material_revision=new_revision, + resolution="resolved", + ) + ) + changed = True + elif len(matches) > 1: + migrated.append(dataclass_replace(row, resolution="ambiguous")) + changed = True + else: + migrated.append(dataclass_replace(row, resolution="unresolved")) + changed = True + + if changed: + _atomic_write( + annotations_path, + json.dumps( + [row.to_dict() for row in migrated], + ensure_ascii=False, + indent=2, + ), + ) + def _write_annotations(self, material_id: str, rows: Sequence[Annotation]) -> None: _atomic_write( self._state_path(material_id, ANNOTATIONS_DIR), diff --git a/tests/reading/test_ingestion.py b/tests/reading/test_ingestion.py index 992702422..4119b8d0a 100644 --- a/tests/reading/test_ingestion.py +++ b/tests/reading/test_ingestion.py @@ -24,7 +24,12 @@ from deeptutor.reading.ingestion import ( parse_bilibili_url, parse_youtube_url, ) -from deeptutor.reading.models import ReadingError +from deeptutor.reading.models import ( + Annotation, + ReadingError, + TextPositionSelector, + TextQuoteSelector, +) from deeptutor.reading.store import ReadingStore from deeptutor.services.web_source.snapshot_assets import SnapshotAsset from deeptutor.tools.web_fetch import FetchOutcome, _extract_readable @@ -118,6 +123,156 @@ async def test_web_import_is_rich_localizes_images_and_preserves_old_revision(st assert "# Old snapshot" in reading.revision_unit_text(ready.material_id, 1, 1) +def test_revision_migration_reanchors_reliable_quote(stores) -> None: + reading, _catalog = stores + material_id = "abcdef0123456789" + + reading.ingest_units( + material_id, + filename="article.md", + units=["# First section\n\nThe quick brown fox jumps over the lazy dog."], + source_type="url_snapshot", + ) + annotation = reading.save_annotation( + material_id, + Annotation( + annotation_id="test001", + locator=1, + quote="quick brown fox", + selectors=( + TextQuoteSelector( + exact="quick brown fox", + prefix="The ", + suffix=" jumps", + ), + TextPositionSelector(start=21, end=36), + ), + ), + ) + assert annotation.material_revision == 1 + + reading.ingest_units( + material_id, + filename="article-v2.md", + units=["# Revised\n\nIntro. The quick brown fox jumps over the lazy dog. End."], + source_type="url_snapshot", + ) + stored = reading.annotations(material_id) + assert len(stored) == 1 + migrated = stored[0] + assert migrated.resolution == "resolved" + assert migrated.material_revision == 2 + assert "quick brown fox" in migrated.quote + quote_selector = next(s for s in migrated.selectors if isinstance(s, TextQuoteSelector)) + position_selector = next(s for s in migrated.selectors if isinstance(s, TextPositionSelector)) + unit_text = reading.unit_text(material_id, migrated.locator) + assert unit_text[position_selector.start : position_selector.end] == quote_selector.exact + + +def test_revision_migration_marks_gone_quote_unresolved(stores) -> None: + reading, _catalog = stores + material_id = "abcdef0123456789" + + reading.ingest_units( + material_id, + filename="article.md", + units=["# Section\n\nThe unique phrase is here."], + source_type="url_snapshot", + ) + reading.save_annotation( + material_id, + Annotation( + annotation_id="test002", + locator=1, + quote="unique phrase", + selectors=(TextQuoteSelector(exact="unique phrase", prefix="The ", suffix=" is"),), + ), + ) + + reading.ingest_units( + material_id, + filename="article-v2.md", + units=["# Rewritten\n\nEntirely different content."], + source_type="url_snapshot", + ) + stored = reading.annotations(material_id) + assert len(stored) == 1 + assert stored[0].resolution == "unresolved" + assert stored[0].material_revision == 1 # kept pinned to old revision + assert stored[0].quote == "unique phrase" + + +def test_revision_migration_marks_repeated_quote_ambiguous(stores) -> None: + reading, _catalog = stores + material_id = "abcdef0123456789" + + reading.ingest_units( + material_id, + filename="article.md", + units=["# Section\n\nA key claim with unique context."], + source_type="url_snapshot", + ) + reading.save_annotation( + material_id, + Annotation( + annotation_id="test003", + locator=1, + quote="key claim", + selectors=(TextQuoteSelector(exact="key claim", prefix="A ", suffix=" with"),), + ), + ) + + reading.ingest_units( + material_id, + filename="article-v2.md", + units=["# Duplicated\n\nA key claim here.\n\nAnother key claim there."], + source_type="url_snapshot", + ) + stored = reading.annotations(material_id) + assert len(stored) == 1 + assert stored[0].resolution == "ambiguous" + assert stored[0].material_revision == 1 + + +def test_revision_migration_preserves_old_annotations_for_audit(stores) -> None: + reading, _catalog = stores + material_id = "abcdef0123456789" + + reading.ingest_units( + material_id, + filename="article.md", + units=["# Section\n\nThe original phrase."], + source_type="url_snapshot", + ) + reading.save_annotation( + material_id, + Annotation( + annotation_id="test004", + locator=1, + quote="original phrase", + selectors=(TextQuoteSelector(exact="original phrase"),), + ), + ) + + reading.ingest_units( + material_id, + filename="article-v2.md", + units=["# Changed\n\nA new phrase entirely."], + source_type="url_snapshot", + ) + + revision_dir = reading._dir(material_id) / "revisions" / "000001" + assert revision_dir.is_dir() + saved_annotations = revision_dir / "annotations" / f"{material_id}.json" + assert saved_annotations.is_file() + import json + + saved_rows = json.loads(saved_annotations.read_text(encoding="utf-8")) + assert len(saved_rows) == 1 + assert saved_rows[0]["quote"] == "original phrase" + assert saved_rows[0]["resolution"] == "resolved" + + @pytest.mark.asyncio async def test_web_article_fixture_builds_heading_derived_outline(stores) -> None: reading, catalog = stores diff --git a/web/components/reading/AnnotationList.tsx b/web/components/reading/AnnotationList.tsx index e00e9d232..7bb4f1eba 100644 --- a/web/components/reading/AnnotationList.tsx +++ b/web/components/reading/AnnotationList.tsx @@ -1,7 +1,14 @@ "use client"; import { useMemo, useState } from "react"; -import { Bookmark, Bot, Highlighter, Sparkles, Trash2 } from "lucide-react"; +import { + AlertCircle, + Bookmark, + Bot, + Highlighter, + Sparkles, + Trash2, +} from "lucide-react"; import { useTranslation } from "react-i18next"; import { ANNOTATION_SWATCH, @@ -157,6 +164,18 @@ export function AnnotationList({ {t("Citation")} )} + {annotation.resolution === "unresolved" && ( + + + {t("Not found")} + + )} + {annotation.resolution === "ambiguous" && ( + + + {t("Ambiguous")} + + )}