Skip to content

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

feat(reading): render safe versioned web snapshots

Bingxi Zhao (Frank)3f3bf0b84112
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index 9430f99c5..5dc838793 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -135,6 +135,10 @@ class MaterialInfo(BaseModel):
has_raw_view: bool = False
render_mode: Literal["text", "pdf", "epub", "video", "audio"] = "text"
extractor: str = ""
+ content_format: Literal["plain_text", "web_markdown"] = "plain_text"
+ source_type: str = "upload"
+ source_url: str = ""
+ revision: int = 1
annotation_count: int = 0
@@ -977,6 +981,40 @@ async def get_unit(material_id: str, locator: int) -> UnitText:
raise _http_error(exc) from exc
[email protected]("/materials/{material_id}/revisions")
+async def list_material_revisions(material_id: str) -> list[dict[str, Any]]:
+ """Prior immutable snapshots retained when a URL is cleaned/refetched."""
+ store = _store()
+ try:
+ return [row.to_dict() for row in store.revisions(material_id)]
+ except Exception as exc:
+ raise _http_error(exc) from exc
+
+
+ "/materials/{material_id}/revisions/{revision}/units/{locator}",
+ response_model=UnitText,
+)
+async def get_revision_unit(
+ material_id: str, revision: int, locator: int
+) -> UnitText:
+ store = _store()
+ try:
+ manifest = next(
+ (row for row in store.revisions(material_id) if row.revision == revision),
+ None,
+ )
+ if manifest is None:
+ raise MaterialNotFound(f"revision {revision} not found")
+ return UnitText(
+ locator=locator,
+ unit=manifest.unit,
+ text=store.revision_unit_text(material_id, revision, locator),
+ )
+ except Exception as exc:
+ raise _http_error(exc) from exc
+
+
@router.get("/materials/{material_id}/raw")
async def get_raw(material_id: str) -> FileResponse:
"""The original bytes, for the faithful viewer. Serves Range requests."""
@@ -999,6 +1037,34 @@ async def get_raw(material_id: str) -> FileResponse:
)
[email protected]("/materials/{material_id}/assets/{asset_name}")
+async def get_snapshot_asset(material_id: str, asset_name: str) -> FileResponse:
+ """Serve one authenticated, MIME-sniffed image captured with a web page."""
+ from deeptutor.services.web_source.snapshot_assets import snapshot_asset_mime
+
+ store = _store()
+ try:
+ path = store.asset_path(material_id, asset_name)
+ except Exception as exc:
+ raise _http_error(exc) from exc
+ if path is None:
+ raise HTTPException(status_code=404, detail="Snapshot image not found.")
+ data = path.read_bytes()
+ mime = snapshot_asset_mime(data)
+ if mime is None:
+ raise HTTPException(status_code=404, detail="Snapshot image is invalid.")
+ return FileResponse(
+ path,
+ media_type=mime,
+ filename=path.name,
+ content_disposition_type="inline",
+ headers={
+ "Cache-Control": "private, max-age=31536000, immutable",
+ "X-Content-Type-Options": "nosniff",
+ },
+ )
+
+
@router.get("/materials/{material_id}/annotations", response_model=list[AnnotationInfo])
async def list_annotations(material_id: str) -> list[AnnotationInfo]:
store = _store()
diff --git a/deeptutor/reading/ingestion.py b/deeptutor/reading/ingestion.py
index 3728a6f78..6e298af61 100644
--- a/deeptutor/reading/ingestion.py
+++ b/deeptutor/reading/ingestion.py
@@ -30,6 +30,11 @@ from deeptutor.reading.catalog_store import ReadingCatalogStore
from deeptutor.reading.extract import split_markdown_by_headings
from deeptutor.reading.models import OutlineEntry, ReadingError, UnitReference
from deeptutor.reading.store import ReadingStore, content_hash
+from deeptutor.services.web_source.markdown import strip_leading_snapshot_provenance
+from deeptutor.services.web_source.snapshot_assets import (
+ ImageFetcher,
+ localize_snapshot_images,
+)
from deeptutor.tools.web_fetch import FetchOutcome, fetch_url_as_markdown
logger = logging.getLogger(__name__)
@@ -125,6 +130,7 @@ class ReadingIngestionService:
bilibili_loader: BilibiliLoader | None = None,
media_chunker: MediaChunker | None = None,
transcriber: Transcriber | None = None,
+ image_fetcher: ImageFetcher | None = None,
) -> None:
self.catalog = catalog or ReadingCatalogStore()
self.reading_store = reading_store or ReadingStore(self.catalog.root)
@@ -132,6 +138,7 @@ class ReadingIngestionService:
self._youtube_loader = youtube_loader or _load_youtube_captions
self._bilibili_loader = bilibili_loader or _load_bilibili_media
self._media_chunker = media_chunker or _chunk_media_audio
+ self._image_fetcher = image_fetcher
if transcriber is None:
from deeptutor.services.voice import transcribe_audio
@@ -208,7 +215,14 @@ class ReadingIngestionService:
outcome = await self._web_fetcher(record.source_url, max_chars=500_000)
if not outcome.ok:
raise ReadingError(outcome.error or "web source could not be fetched")
- units, outline = split_markdown_by_headings(outcome.markdown)
+ source_url = outcome.url or record.source_url
+ markdown = strip_leading_snapshot_provenance(outcome.markdown)
+ markdown, assets = await localize_snapshot_images(
+ markdown,
+ record.material_id,
+ fetcher=self._image_fetcher,
+ )
+ units, outline = split_markdown_by_headings(markdown)
if not units:
raise ReadingError("web source contained no readable article text")
self.reading_store.ingest_units(
@@ -219,6 +233,10 @@ class ReadingIngestionService:
title=outcome.title or record.title,
mime="text/markdown",
extractor="safe-web-fetch",
+ content_format="web_markdown",
+ source_type="url_snapshot",
+ source_url=source_url,
+ assets=assets,
# An empty outline means the page had only its synthetic title (or
# no headings), so ReadingStore deliberately retains its existing
# first-line fallback for unstructured web content.
@@ -230,7 +248,7 @@ class ReadingIngestionService:
filename=f"{record.material_id}.md",
title=outcome.title or record.title,
source_kind=SourceKind.WEB,
- source_url=outcome.url or record.source_url,
+ source_url=source_url,
mime="text/markdown",
render_mode="text",
status=IngestionStatus.READY,
diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.py
index 4ae7099c2..654d1852e 100644
--- a/deeptutor/reading/models.py
+++ b/deeptutor/reading/models.py
@@ -23,6 +23,7 @@ from typing import Any, Literal
# model and the UI ("page 12" vs "chapter 3"); the addressing is identical.
UnitKind = Literal["page", "chapter", "slide", "section", "segment"]
RenderMode = Literal["text", "pdf", "epub", "video", "audio"]
+ContentFormat = Literal["plain_text", "web_markdown"]
AnnotationKind = Literal["highlight", "underline", "note"]
TextSelectorType = Literal["TextQuoteSelector", "TextPositionSelector"]
@@ -206,6 +207,12 @@ class MaterialManifest:
# Selects the faithful renderer without overloading ``has_raw_view``.
# The legacy boolean remains PDF-only until every client understands EPUB.
render_mode: RenderMode = "text"
+ # Uploaded Markdown remains literal source text; only captured web pages
+ # opt into structured rendering.
+ content_format: ContentFormat = "plain_text"
+ source_type: str = "upload"
+ source_url: str = ""
+ revision: int = 1
def to_dict(self) -> dict[str, Any]:
return {
@@ -222,6 +229,10 @@ class MaterialManifest:
"created_at": self.created_at,
"has_raw_view": self.has_raw_view,
"render_mode": self.render_mode,
+ "content_format": self.content_format,
+ "source_type": self.source_type,
+ "source_url": self.source_url,
+ "revision": self.revision,
}
@classmethod
@@ -230,6 +241,9 @@ class MaterialManifest:
render_mode = str(data.get("render_mode") or "")
if render_mode not in ("text", "pdf", "epub", "video", "audio"):
render_mode = "pdf" if data.get("has_raw_view") else "text"
+ content_format = str(data.get("content_format") or "")
+ if content_format not in ("plain_text", "web_markdown"):
+ content_format = "plain_text"
return cls(
material_id=str(data.get("material_id") or ""),
filename=str(data.get("filename") or ""),
@@ -244,6 +258,10 @@ class MaterialManifest:
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]
+ content_format=content_format, # type: ignore[arg-type]
+ source_type=str(data.get("source_type") or "upload"),
+ source_url=str(data.get("source_url") or ""),
+ revision=max(1, int(data.get("revision") or 1)),
)
@@ -416,6 +434,7 @@ __all__ = [
"DEFAULT_ANNOTATION_COLOR",
"Annotation",
"AnnotationKind",
+ "ContentFormat",
"MaterialManifest",
"MaterialNotFound",
"OutlineEntry",
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index 3eff69c03..252d93f45 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -38,7 +38,7 @@ import shutil
import sqlite3
import threading
import time
-from typing import Any, Iterator, Sequence
+from typing import Any, Iterator, Literal, Mapping, Sequence
import uuid
from deeptutor.reading.extract import extract_material, synthesise_outline
@@ -68,6 +68,8 @@ POSITIONS_DIR = "positions"
UNIT_REFS_NAME = "unit_refs.json"
UNITS_DIR = "units"
RAW_DIR = "raw"
+ASSETS_DIR = "assets"
+REVISIONS_DIR = "revisions"
# Both content hashes and separately minted catalog ids are path-safe. Content
# directories themselves remain hashes only.
@@ -368,6 +370,10 @@ class ReadingStore:
raw_data: bytes | None = None,
outline: Sequence[OutlineEntry] | None = None,
unit_refs: Sequence[UnitReference] = (),
+ content_format: Literal["plain_text", "web_markdown"] = "plain_text",
+ source_type: str = "upload",
+ source_url: str = "",
+ assets: Mapping[str, bytes] | None = None,
) -> MaterialManifest:
"""Install trusted, already-extracted units (web pages and transcripts).
@@ -385,6 +391,8 @@ class ReadingStore:
raise ReadingError(f"unsupported reading unit: {unit}")
if render_mode not in {"text", "pdf", "epub", "video", "audio"}:
raise ReadingError(f"unsupported render mode: {render_mode}")
+ if content_format not in {"plain_text", "web_markdown"}:
+ raise ReadingError(f"unsupported content format: {content_format}")
remote_video = render_mode == "video" and extractor.startswith(("youtube-", "bilibili-"))
if render_mode != "text" and not raw_data and not remote_video:
raise ReadingError(f"{render_mode} materials require playable source bytes")
@@ -399,6 +407,13 @@ class ReadingStore:
for index, text in enumerate(clean_units, start=1):
self._unit_file(stage_dir, index).write_text(text, encoding="utf-8")
+ if assets:
+ assets_dir = stage_dir / ASSETS_DIR
+ assets_dir.mkdir(parents=True, exist_ok=True)
+ for name, data in assets.items():
+ safe_name = _safe_filename(str(name), fallback="asset")
+ (assets_dir / safe_name).write_bytes(bytes(data))
+
if raw_data is not None:
raw_dir = stage_dir / RAW_DIR
raw_dir.mkdir(parents=True, exist_ok=True)
@@ -427,11 +442,34 @@ class ReadingStore:
created_at=existing.created_at if existing else time.time(),
has_raw_view=render_mode == "pdf",
render_mode=render_mode, # type: ignore[arg-type]
+ content_format=content_format,
+ source_type=source_type,
+ source_url=source_url,
+ revision=(existing.revision + 1 if existing else 1),
)
_atomic_write(
stage_dir / MANIFEST_NAME,
json.dumps(manifest.to_dict(), ensure_ascii=False, indent=2),
)
+ if existing is not None and material_dir.is_dir():
+ previous_revisions = material_dir / REVISIONS_DIR
+ if previous_revisions.is_dir():
+ shutil.copytree(
+ previous_revisions,
+ stage_dir / REVISIONS_DIR,
+ dirs_exist_ok=True,
+ )
+ revision_dir = stage_dir / REVISIONS_DIR / f"{existing.revision:06d}"
+ if not revision_dir.exists():
+ revision_dir.mkdir(parents=True, exist_ok=True)
+ for filename in (MANIFEST_NAME, OUTLINE_NAME, UNIT_REFS_NAME):
+ source = material_dir / filename
+ if source.is_file():
+ shutil.copy2(source, revision_dir / filename)
+ for dirname in (UNITS_DIR, ASSETS_DIR):
+ source_dir = material_dir / dirname
+ if source_dir.is_dir():
+ shutil.copytree(source_dir, revision_dir / dirname)
for state_name in (ANNOTATIONS_NAME, POSITION_NAME):
source_state = material_dir / state_name
if source_state.is_file():
@@ -458,6 +496,40 @@ class ReadingStore:
shutil.rmtree(backup_dir, ignore_errors=True)
return self.manifest(material_id)
+ def revisions(self, material_id: str) -> list[MaterialManifest]:
+ """List immutable prior manifests, oldest first."""
+ self.manifest(material_id)
+ root = self._dir(material_id) / REVISIONS_DIR
+ if not root.is_dir():
+ return []
+ rows: list[MaterialManifest] = []
+ for child in sorted(root.iterdir()):
+ if not child.is_dir() or not re.fullmatch(r"\d{6}", child.name):
+ continue
+ data = _read_json(child / MANIFEST_NAME)
+ if isinstance(data, dict):
+ rows.append(MaterialManifest.from_dict(data))
+ return rows
+
+ def revision_unit_text(self, material_id: str, revision: int, locator: int) -> str:
+ """Read a unit from a preserved prior web-snapshot revision."""
+ self.manifest(material_id)
+ if revision < 1 or locator < 1:
+ raise ReadingError("revision and locator must be positive")
+ revision_dir = self._dir(material_id) / REVISIONS_DIR / f"{revision:06d}"
+ data = _read_json(revision_dir / MANIFEST_NAME)
+ if not isinstance(data, dict):
+ raise MaterialNotFound(f"revision {revision} not found")
+ manifest = MaterialManifest.from_dict(data)
+ if locator > manifest.unit_count:
+ raise ReadingError(
+ f"{manifest.unit} {locator} is out of range for revision {revision}."
+ )
+ path = self._unit_file(revision_dir, locator)
+ if not path.is_file():
+ raise MaterialNotFound(f"revision {revision} unit {locator} not found")
+ return path.read_text(encoding="utf-8")
+
def _is_complete(self, material_id: str, manifest: MaterialManifest) -> bool:
"""Whether a previously ingested material is still fully on disk."""
material_dir = self._dir(material_id)
@@ -665,6 +737,15 @@ class ReadingStore:
return candidate
return None
+ def asset_path(self, material_id: str, asset_name: str) -> Path | None:
+ """Resolve one generated snapshot raster without permitting traversal."""
+ self.manifest(material_id)
+ name = str(asset_name or "").strip().lower()
+ if not re.fullmatch(r"[0-9a-f]{20}\.(?:png|jpg|gif|webp)", name):
+ return None
+ path = self._dir(material_id) / ASSETS_DIR / name
+ return path if path.is_file() else None
+
@contextmanager
def staged_delete(self, material_id: str) -> Iterator[bool]:
"""Stage a recoverable material deletion around catalog cleanup.
diff --git a/deeptutor/services/web_source/crawler.py b/deeptutor/services/web_source/crawler.py
index 7da62c241..e363c32c9 100644
--- a/deeptutor/services/web_source/crawler.py
+++ b/deeptutor/services/web_source/crawler.py
@@ -26,6 +26,8 @@ from urllib.parse import quote, unquote, urldefrag, urljoin, urlparse
import httpx
+from deeptutor.services.web_source.markdown import strip_leading_snapshot_provenance
+
# Reuse the SSRF guard and HTML extraction from web_fetch
from deeptutor.tools.web_fetch import (
DEFAULT_MAX_CHARS,
@@ -299,7 +301,7 @@ async def _process_page(
)
try:
- title, body = extract_article_markdown(html)
+ title, body = extract_article_markdown(html, base_url=final_url or url)
except Exception:
title, body = _extract_readable(html)
content_hash = hashlib.sha256(body.encode("utf-8")).hexdigest()
@@ -355,8 +357,8 @@ async def crawl_docs_site(
except (TypeError, ValueError):
result.errors.append("Crawl depth and page count must be integers")
return result
- if not 1 <= max_depth <= MAX_CRAWL_DEPTH:
- result.errors.append(f"Crawl depth must be between 1 and {MAX_CRAWL_DEPTH}")
+ if not 0 <= max_depth <= MAX_CRAWL_DEPTH:
+ result.errors.append(f"Crawl depth must be between 0 and {MAX_CRAWL_DEPTH}")
return result
if not 1 <= max_pages <= MAX_CRAWL_PAGES:
result.errors.append(f"Crawl page count must be between 1 and {MAX_CRAWL_PAGES}")
@@ -609,8 +611,7 @@ async def crawl_and_diff(
changed_paths: list[str] = []
for fname in added + updated:
content = page_contents.get(fname, "")
- page_url = page_urls.get(fname, "")
- full_content = f"<!-- source: {page_url} -->\n\n{content}"
+ full_content = strip_leading_snapshot_provenance(content)
dest = _contained_path(raw_dir, fname)
if dest is None:
return CrawlDiff(ok=False, error=f"Unsafe page filename: {fname}", url=url)
diff --git a/deeptutor/services/web_source/html_extractor.py b/deeptutor/services/web_source/html_extractor.py
index 70e41f00d..89b00fc2a 100644
--- a/deeptutor/services/web_source/html_extractor.py
+++ b/deeptutor/services/web_source/html_extractor.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import html as _html
import logging
import re
+from urllib.parse import urljoin, urlparse
logger = logging.getLogger(__name__)
@@ -316,7 +317,7 @@ def _remove_element(el) -> None:
parent.remove(el)
-def extract_article_markdown(raw_html: str) -> tuple[str, str]:
+def extract_article_markdown(raw_html: str, base_url: str = "") -> tuple[str, str]:
"""Extract ``(title, markdown)`` from a doc-site HTML page.
Falls back to full-body text if no article container is found, but
@@ -366,7 +367,7 @@ def extract_article_markdown(raw_html: str) -> tuple[str, str]:
_remove_element(el)
# Convert to markdown
- md = _element_to_markdown(content_el)
+ md = _element_to_markdown(content_el, base_url=base_url)
md = _clean_markdown(md)
if not title:
@@ -416,7 +417,7 @@ def _pre_to_text(el) -> str:
return "".join(parts)
-def _element_to_markdown(el) -> str:
+def _element_to_markdown(el, base_url: str = "") -> str:
"""Recursively convert an lxml element to markdown text.
Correctly preserves inter-element whitespace by including both
@@ -445,7 +446,7 @@ def _element_to_markdown(el) -> str:
parts.append(child.tail)
continue
- text = _element_to_markdown(child)
+ text = _element_to_markdown(child, base_url=base_url)
if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
level = int(tag[1])
@@ -474,7 +475,7 @@ def _element_to_markdown(el) -> str:
else:
parts.append(text)
elif tag in ("ul", "ol"):
- items = _list_to_markdown(child, ordered=(tag == "ol"))
+ items = _list_to_markdown(child, ordered=(tag == "ol"), base_url=base_url)
parts.append(f"\n\n{items}\n\n")
elif tag == "blockquote":
quoted = "\n".join(f"> {line}" for line in text.strip().split("\n"))
@@ -491,6 +492,7 @@ def _element_to_markdown(el) -> str:
href = child.get("href", "")
link_text = child.text_content().strip()
if href and link_text and not href.startswith("#"):
+ href = _normalise_captured_url(href, base_url)
parts.append(f"[{link_text}]({href})")
elif link_text:
parts.append(link_text)
@@ -506,6 +508,7 @@ def _element_to_markdown(el) -> str:
alt = child.get("alt", "")
src = child.get("src", "")
if src:
+ src = _normalise_captured_url(src, base_url)
parts.append(f"![{alt}]({src})")
elif tag in ("div", "section", "span", "article", "main"):
parts.append(text)
@@ -522,7 +525,17 @@ def _element_to_markdown(el) -> str:
return "".join(parts)
-def _list_to_markdown(el, ordered: bool = False) -> str:
+def _normalise_captured_url(value: str, base_url: str) -> str:
+ candidate = str(value or "").strip()
+ if not candidate or candidate.startswith("#") or not base_url:
+ return candidate
+ parsed = urlparse(candidate)
+ if parsed.scheme and parsed.scheme.lower() not in {"http", "https"}:
+ return candidate
+ return urljoin(base_url, candidate)
+
+
+def _list_to_markdown(el, ordered: bool = False, base_url: str = "") -> str:
"""Convert a <ul> or <ol> element to markdown."""
lines: list[str] = []
idx = 0
@@ -530,7 +543,7 @@ def _list_to_markdown(el, ordered: bool = False) -> str:
if _tag_name(child) == "li":
idx += 1
prefix = f"{idx}. " if ordered else "- "
- text = _element_to_markdown(child).strip()
+ text = _element_to_markdown(child, base_url=base_url).strip()
# Handle nested lists
text = text.replace("\n", "\n ")
lines.append(f"{prefix}{text}")
diff --git a/deeptutor/services/web_source/markdown.py b/deeptutor/services/web_source/markdown.py
new file mode 100644
index 000000000..a32dae093
--- /dev/null
+++ b/deeptutor/services/web_source/markdown.py
@@ -0,0 +1,28 @@
+"""Markdown cleanup shared by web-source persistence and reading ingestion."""
+
+from __future__ import annotations
+
+import re
+
+_LEADING_SOURCE_COMMENT = re.compile(
+ r"^<!--\s*source:\s*https?://[^>\r\n]+?-->\s*$",
+ re.IGNORECASE,
+)
+
+
+def strip_leading_snapshot_provenance(markdown: str) -> str:
+ """Remove only crawler provenance comments from a snapshot's preamble."""
+ lines = markdown.splitlines(keepends=True)
+ index = 0
+ while index < len(lines):
+ stripped = lines[index].strip()
+ if not stripped:
+ index += 1
+ continue
+ if not _LEADING_SOURCE_COMMENT.fullmatch(stripped):
+ break
+ index += 1
+ return "".join(lines[index:]).lstrip("\r\n")
+
+
+__all__ = ["strip_leading_snapshot_provenance"]
diff --git a/deeptutor/services/web_source/snapshot_assets.py b/deeptutor/services/web_source/snapshot_assets.py
new file mode 100644
index 000000000..fc431b228
--- /dev/null
+++ b/deeptutor/services/web_source/snapshot_assets.py
@@ -0,0 +1,171 @@
+"""Safe, local image assets for captured web Markdown."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+import hashlib
+import logging
+import re
+from typing import Any
+from urllib.parse import urljoin, urlsplit
+
+import httpx
+
+from deeptutor.tools.web_fetch import (
+ ALLOWED_SCHEMES,
+ DEFAULT_TIMEOUT_S,
+ DEFAULT_USER_AGENT,
+ MAX_REDIRECTS,
+ _is_disallowed_host,
+)
+
+logger = logging.getLogger(__name__)
+
+MAX_SNAPSHOT_IMAGES = 24
+MAX_SNAPSHOT_IMAGE_BYTES = 8 * 1024 * 1024
+_IMAGE = re.compile(
+ r"!\[([^\]]*)\]\(\s*(https?://[^\s)]+)(?:\s+[\"'][^)]*[\"'])?\s*\)",
+ re.IGNORECASE,
+)
+
+
+@dataclass(frozen=True, slots=True)
+class SnapshotAsset:
+ data: bytes
+ mime: str
+ extension: str
+
+
+ImageFetcher = Callable[[str], Awaitable[SnapshotAsset | None]]
+
+
+async def localize_snapshot_images(
+ markdown: str,
+ material_id: str,
+ *,
+ fetcher: ImageFetcher | None = None,
+) -> tuple[str, dict[str, bytes]]:
+ """Cache bounded raster images and replace hotlinks with local API URLs."""
+ matches = list(_IMAGE.finditer(markdown))
+ urls = list(dict.fromkeys(match.group(2) for match in matches))[:MAX_SNAPSHOT_IMAGES]
+ if not urls:
+ return markdown, {}
+
+ resolved_fetcher = fetcher or fetch_snapshot_image
+ semaphore = asyncio.Semaphore(4)
+
+ async def load(url: str) -> tuple[str, SnapshotAsset | None]:
+ try:
+ async with semaphore:
+ return url, await resolved_fetcher(url)
+ except Exception:
+ logger.info("Snapshot image could not be localized: %s", url, exc_info=True)
+ return url, None
+
+ fetched = dict(await asyncio.gather(*(load(url) for url in urls)))
+ assets: dict[str, bytes] = {}
+ replacements: dict[str, str | None] = {}
+ for url, asset in fetched.items():
+ if asset is None:
+ replacements[url] = None
+ continue
+ digest = hashlib.sha256(url.encode("utf-8") + asset.data).hexdigest()[:20]
+ name = f"{digest}.{asset.extension}"
+ assets[name] = asset.data
+ replacements[url] = f"/api/v1/reading/materials/{material_id}/assets/{name}"
+
+ def replace(match: re.Match[str]) -> str:
+ alt, url = match.group(1), match.group(2)
+ local = replacements.get(url)
+ if local:
+ return f"![{alt}]({local})"
+ label = alt.strip() or "image"
+ return f"*Image unavailable: {label}*"
+
+ return _IMAGE.sub(replace, markdown), assets
+
+
+async def fetch_snapshot_image(
+ url: str,
+ *,
+ timeout_s: float = DEFAULT_TIMEOUT_S,
+ client_factory: Any = None,
+ host_validator: Any = None,
+) -> SnapshotAsset | None:
+ """Fetch one public raster image with redirect, MIME, and size guards."""
+ current_url = str(url or "").strip()
+ validator = host_validator or _is_disallowed_host
+ factory = client_factory or _default_client_factory
+ try:
+ async with factory(timeout=timeout_s) as client:
+ for hop in range(MAX_REDIRECTS + 1):
+ parsed = urlsplit(current_url)
+ host = (parsed.hostname or "").strip()
+ if parsed.scheme.lower() not in ALLOWED_SCHEMES or not host:
+ return None
+ if validator(host):
+ return None
+ async with client.stream(
+ "GET",
+ current_url,
+ headers={
+ "User-Agent": DEFAULT_USER_AGENT,
+ "Accept": "image/png,image/jpeg,image/gif,image/webp;q=0.9",
+ },
+ follow_redirects=False,
+ ) as response:
+ location = response.headers.get("location", "")
+ if response.status_code in {301, 302, 303, 307, 308} and location:
+ if hop >= MAX_REDIRECTS:
+ return None
+ current_url = urljoin(current_url, location)
+ continue
+ if response.status_code >= 400:
+ return None
+ data = await _bounded_image_read(response)
+ return _sniff_raster(data)
+ except httpx.HTTPError:
+ return None
+ return None
+
+
+def _default_client_factory(*, timeout: float) -> httpx.AsyncClient:
+ return httpx.AsyncClient(timeout=timeout, max_redirects=MAX_REDIRECTS)
+
+
+async def _bounded_image_read(response: httpx.Response) -> bytes:
+ data = bytearray()
+ async for chunk in response.aiter_bytes():
+ data.extend(chunk)
+ if len(data) > MAX_SNAPSHOT_IMAGE_BYTES:
+ return b""
+ return bytes(data)
+
+
+def _sniff_raster(data: bytes) -> SnapshotAsset | None:
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return SnapshotAsset(data, "image/png", "png")
+ if data.startswith(b"\xff\xd8\xff"):
+ return SnapshotAsset(data, "image/jpeg", "jpg")
+ if data.startswith((b"GIF87a", b"GIF89a")):
+ return SnapshotAsset(data, "image/gif", "gif")
+ if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return SnapshotAsset(data, "image/webp", "webp")
+ return None
+
+
+def snapshot_asset_mime(data: bytes) -> str | None:
+ asset = _sniff_raster(data)
+ return asset.mime if asset else None
+
+
+__all__ = [
+ "MAX_SNAPSHOT_IMAGE_BYTES",
+ "MAX_SNAPSHOT_IMAGES",
+ "SnapshotAsset",
+ "fetch_snapshot_image",
+ "localize_snapshot_images",
+ "snapshot_asset_mime",
+]
diff --git a/deeptutor/tools/web_fetch.py b/deeptutor/tools/web_fetch.py
index 71a65b2b0..19d649938 100644
--- a/deeptutor/tools/web_fetch.py
+++ b/deeptutor/tools/web_fetch.py
@@ -153,7 +153,7 @@ async def fetch_url_as_markdown(
except Exception as exc: # pragma: no cover — defensive
return FetchOutcome(ok=False, error=f"Unexpected fetch failure: {exc}")
- title, body = _extract_readable(raw)
+ title, body = _extract_readable(raw, base_url=final_url)
truncated = False
if len(body) > max_chars:
body = body[:max_chars].rstrip() + "\n…[truncated]"
@@ -245,7 +245,7 @@ async def _bounded_read(response: httpx.Response, limit: int) -> str:
return buf.decode("utf-8", errors="replace")
-def _extract_readable(html_or_text: str) -> tuple[str, str]:
+def _extract_readable(html_or_text: str, base_url: str = "") -> tuple[str, str]:
"""Return ``(title, body_text)`` extracted from an HTML string.
For non-HTML payloads (plain text, JSON dumps) just normalises
@@ -263,7 +263,7 @@ def _extract_readable(html_or_text: str) -> tuple[str, str]:
extract_article_markdown,
)
- return extract_article_markdown(html_or_text)
+ return extract_article_markdown(html_or_text, base_url=base_url)
except Exception:
logger.debug("structured HTML extraction failed; using text fallback", exc_info=True)
title_match = _TITLE_RE.search(html_or_text)
diff --git a/tests/reading/test_ingestion.py b/tests/reading/test_ingestion.py
index 1478b0fd3..68f6504da 100644
--- a/tests/reading/test_ingestion.py
+++ b/tests/reading/test_ingestion.py
@@ -25,6 +25,7 @@ from deeptutor.reading.ingestion import (
)
from deeptutor.reading.models import ReadingError
from deeptutor.reading.store import ReadingStore
+from deeptutor.services.web_source.snapshot_assets import SnapshotAsset
from deeptutor.tools.web_fetch import FetchOutcome, _extract_readable
_ARTICLE_FIXTURE = Path(__file__).parents[1] / "fixtures" / "web" / "vector_article.html"
@@ -61,6 +62,58 @@ async def test_web_import_uses_safe_fetch_result_and_builds_sections(stores) ->
assert reading.outline(ready.material_id)[0].synthesised is True
+async def test_web_import_is_rich_localizes_images_and_preserves_old_revision(stores) -> None:
+ reading, catalog = stores
+ url = "https://example.com/article"
+
+ async def fetcher(_url: str, **_kwargs):
+ return FetchOutcome(
+ ok=True,
+ url="https://example.com/final/article",
+ title="Snapshot",
+ markdown=(
+ "<!-- source: https://example.com/legacy -->\n"
+ "# Snapshot\n\n![Diagram](https://cdn.example.com/diagram.png)"
+ ),
+ )
+
+ async def image_fetcher(_url: str):
+ return SnapshotAsset(b"\x89PNG\r\n\x1a\nimage", "image/png", "png")
+
+ service = ReadingIngestionService(
+ reading,
+ catalog,
+ web_fetcher=fetcher,
+ image_fetcher=image_fetcher,
+ )
+ queued = service.queue_url(url)
+ reading.ingest_units(
+ queued.material_id,
+ filename=f"{queued.material_id}.md",
+ units=["<!-- source: https://example.com/old -->\n# Old snapshot"],
+ source_type="url_snapshot",
+ source_url=url,
+ )
+
+ ready = await service.process_url(queued.material_id)
+ manifest = reading.manifest(ready.material_id)
+ current = reading.unit_text(ready.material_id, 1)
+
+ assert manifest.content_format == "web_markdown"
+ assert manifest.source_url == "https://example.com/final/article"
+ assert manifest.revision == 2
+ assert "<!-- source:" not in current
+ assert "/api/v1/reading/materials/" in current
+ assert reading.asset_path(
+ ready.material_id,
+ next((reading._dir(ready.material_id) / "assets").iterdir()).name,
+ ) is not None
+ revisions = reading.revisions(ready.material_id)
+ assert [row.revision for row in revisions] == [1]
+ assert "# Old snapshot" in reading.revision_unit_text(ready.material_id, 1, 1)
+
+
@pytest.mark.asyncio
async def test_web_article_fixture_builds_heading_derived_outline(stores) -> None:
reading, catalog = stores
diff --git a/tests/reading/test_router.py b/tests/reading/test_router.py
index c35c6f634..4785d87de 100644
--- a/tests/reading/test_router.py
+++ b/tests/reading/test_router.py
@@ -158,6 +158,31 @@ def test_get_material_400s_for_a_traversal_attempt(client: TestClient) -> None:
assert response.status_code in (400, 404)
+def test_snapshot_assets_are_served_with_sniffed_private_headers(client: TestClient) -> None:
+ store = ReadingStore()
+ material_id = "0123456789abcdef"
+ name = "a" * 20 + ".png"
+ store.ingest_units(
+ material_id,
+ filename="snapshot.md",
+ units=["# Snapshot"],
+ content_format="web_markdown",
+ source_type="url_snapshot",
+ source_url="https://example.com",
+ assets={name: b"\x89PNG\r\n\x1a\nasset"},
+ )
+
+ response = client.get(f"/api/v1/reading/materials/{material_id}/assets/{name}")
+
+ assert response.status_code == 200
+ assert response.headers["content-type"] == "image/png"
+ assert response.headers["x-content-type-options"] == "nosniff"
+ assert response.headers["cache-control"].startswith("private")
+ assert client.get(
+ f"/api/v1/reading/materials/{material_id}/assets/not-an-image.svg"
+ ).status_code == 404
+
+
def test_delete_material_is_idempotent_then_404s(client: TestClient) -> None:
material = _upload(client)
material_id = material["material_id"]
diff --git a/tests/services/web_source/test_markdown.py b/tests/services/web_source/test_markdown.py
new file mode 100644
index 000000000..5a703a95e
--- /dev/null
+++ b/tests/services/web_source/test_markdown.py
@@ -0,0 +1,59 @@
+"""Tests for web snapshot cleanup, URL normalization, and local assets."""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.services.web_source.html_extractor import extract_article_markdown
+from deeptutor.services.web_source.markdown import strip_leading_snapshot_provenance
+from deeptutor.services.web_source.snapshot_assets import (
+ SnapshotAsset,
+ localize_snapshot_images,
+)
+
+
+def test_strips_only_leading_source_comments() -> None:
+ markdown = (
+ "\n<!-- source: https://docs.example.com/page -->\n"
+ "<!-- source: https://docs.example.com/canonical -->\n# Documentation\n"
+ )
+ assert strip_leading_snapshot_provenance(markdown) == "# Documentation\n"
+
+ body_comment = (
+ "# Documentation\n\n<!-- source: https://docs.example.com/body -->\n\n"
+ "```html\n<!-- source: https://docs.example.com/code -->\n```\n"
+ )
+ assert strip_leading_snapshot_provenance(body_comment) == body_comment
+
+
+def test_html_extractor_resolves_relative_links_and_images() -> None:
+ _, markdown = extract_article_markdown(
+ "<html><body><article><a href='../next'>Next</a>"
+ "<img src='../images/diagram.png' alt='Diagram'></article></body></html>",
+ base_url="https://docs.example.com/guide/start/",
+ )
+
+ assert "[Next](https://docs.example.com/guide/next)" in markdown
+ assert "![Diagram](https://docs.example.com/guide/images/diagram.png)" in markdown
+
+
+async def test_localizes_safe_images_and_never_leaves_failed_hotlinks() -> None:
+ png = b"\x89PNG\r\n\x1a\n" + b"safe"
+
+ async def fetcher(url: str):
+ if url.endswith("ok.png"):
+ return SnapshotAsset(png, "image/png", "png")
+ return None
+
+ markdown, assets = await localize_snapshot_images(
+ "![Diagram](https://cdn.example.com/ok.png)\n"
+ "![Tracker](https://cdn.example.com/bad.svg)",
+ "0123456789abcdef",
+ fetcher=fetcher,
+ )
+
+ assert "https://cdn.example.com" not in markdown
+ assert "/api/v1/reading/materials/0123456789abcdef/assets/" in markdown
+ assert "Image unavailable: Tracker" in markdown
+ assert list(assets.values()) == [png]
diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsx
index 25dfe62ed..22acfa46b 100644
--- a/web/components/common/MarkdownRenderer.tsx
+++ b/web/components/common/MarkdownRenderer.tsx
@@ -14,6 +14,7 @@ export interface MarkdownRendererProps {
enableMath?: boolean;
enableCode?: boolean;
enableMermaid?: boolean;
+ enableImages?: boolean;
allowHtml?: boolean;
/**
* When true, top-level block elements receive a `data-source-line` attribute
@@ -68,6 +69,7 @@ export default function MarkdownRenderer({
enableMath,
enableCode,
enableMermaid,
+ enableImages,
allowHtml,
trackSourceLines,
}: MarkdownRendererProps) {
@@ -106,6 +108,7 @@ export default function MarkdownRenderer({
enableMath={resolvedEnableMath}
enableCode={resolvedEnableCode}
enableMermaid={resolvedEnableMermaid}
+ enableImages={enableImages}
allowHtml={resolvedAllowHtml}
trackSourceLines={trackSourceLines}
/>
diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsx
index d3542047c..695e7481d 100644
--- a/web/components/common/RichMarkdownRenderer.tsx
+++ b/web/components/common/RichMarkdownRenderer.tsx
@@ -158,6 +158,7 @@ export default function RichMarkdownRenderer({
enableMath = false,
enableCode = false,
enableMermaid = false,
+ enableImages = true,
allowHtml = false,
trackSourceLines = false,
}: MarkdownRendererProps) {
@@ -648,16 +649,17 @@ export default function RichMarkdownRenderer({
</a>
);
},
- img: ({ node, src, alt, ...props }: any) => (
- <img
- src={src}
- alt={alt || ""}
- loading="lazy"
- className={`${gap} inline-block max-w-full rounded-lg border border-[var(--border)]`}
- {...lineAttr(node)}
- {...props}
- />
- ),
+ img: ({ node, src, alt, ...props }: any) =>
+ enableImages ? (
+ <img
+ src={src}
+ alt={alt || ""}
+ loading="lazy"
+ className={`${gap} inline-block max-w-full rounded-lg border border-[var(--border)]`}
+ {...lineAttr(node)}
+ {...props}
+ />
+ ) : null,
blockquote: ({ node, ...props }: any) => (
<blockquote
className={`${gap} border-l-[3px] border-[var(--muted-foreground)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}
@@ -711,7 +713,14 @@ export default function RichMarkdownRenderer({
const components = useMemo(
() => (isTrace ? traceComponents : normalComponents),
// eslint-disable-next-line react-hooks/exhaustive-deps -- components only change with variant/feature flags
- [isTrace, variant, enableMermaid, enableCode, trackSourceLines],
+ [
+ isTrace,
+ variant,
+ enableMermaid,
+ enableCode,
+ enableImages,
+ trackSourceLines,
+ ],
);
const rootClasses = isTrace
diff --git a/web/components/reading/ReaderPane.tsx b/web/components/reading/ReaderPane.tsx
index 0ddd7c384..aadb76fe3 100644
--- a/web/components/reading/ReaderPane.tsx
+++ b/web/components/reading/ReaderPane.tsx
@@ -488,6 +488,7 @@ export function ReaderPane({
materialId={material.material_id}
unit={material.unit}
unitCount={material.unit_count}
+ contentFormat={material.content_format}
annotations={annotations}
jump={jump}
highlightedAnnotationId={activeAnnotationId}
diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsx
index e76809bc0..8731000bd 100644
--- a/web/components/reading/TextUnitView.tsx
+++ b/web/components/reading/TextUnitView.tsx
@@ -20,6 +20,7 @@ import {
SunMoon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
+import RichMarkdownRenderer from "@/components/common/RichMarkdownRenderer";
import type { AnnotationItem, UnitKind } from "@/lib/reading-api";
import { getUnitText } from "@/lib/reading-api";
import {
@@ -60,6 +61,7 @@ export interface TextUnitViewProps {
materialId: string;
unit: UnitKind;
unitCount: number;
+ contentFormat?: "plain_text" | "web_markdown";
annotations: AnnotationItem[];
jump: JumpRequest | null;
highlightedAnnotationId?: string | null;
@@ -84,6 +86,7 @@ export function TextUnitView({
materialId,
unit,
unitCount,
+ contentFormat = "plain_text",
annotations,
jump,
highlightedAnnotationId,
@@ -116,6 +119,7 @@ export function TextUnitView({
const [lineWidth, setLineWidth] = useState(DEFAULT_LINE_WIDTH);
const [serif, setSerif] = useState(true);
const [readerTheme, setReaderTheme] = useState<ReaderTheme>("auto");
+ const isWebMarkdown = contentFormat === "web_markdown";
useEffect(() => {
try {
@@ -331,6 +335,20 @@ export function TextUnitView({
[locator, text],
);
+ useEffect(() => {
+ if (!isWebMarkdown) return;
+ const article = articleRef.current;
+ if (!article || loading || error) return;
+ article
+ .querySelectorAll<HTMLElement>("h1,h2,h3,h4,h5,h6")
+ .forEach((element, index) => {
+ const heading = pageHeadings[index];
+ if (!heading) return;
+ element.id = heading.id;
+ element.dataset.readerHeadingId = heading.id;
+ });
+ }, [error, isWebMarkdown, loading, pageHeadings]);
+
useEffect(() => {
headingsChangeRef.current?.(pageHeadings);
return () => headingsChangeRef.current?.([]);
@@ -543,7 +561,9 @@ export function TextUnitView({
) : (
<article
ref={articleRef}
- className={`mx-auto whitespace-pre-wrap leading-[1.75] selection:bg-[var(--primary)]/20 ${
+ className={`mx-auto leading-[1.75] selection:bg-[var(--primary)]/20 ${
+ isWebMarkdown ? "" : "whitespace-pre-wrap "
+ }${
serif ? "font-serif" : "font-sans"
}`}
style={{
@@ -556,6 +576,16 @@ export function TextUnitView({
<span className="text-[var(--muted-foreground)]">
{t("This section has no extractable text.")}
</span>
+ ) : isWebMarkdown ? (
+ <RichMarkdownRenderer
+ content={text}
+ allowHtml={false}
+ enableMath
+ enableCode
+ enableMermaid={false}
+ enableImages
+ variant="prose"
+ />
) : (
<TextWithHeadings text={text} headings={pageHeadings} />
)}
diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.ts
index 9857de452..9118d0445 100644
--- a/web/lib/reading-api.ts
+++ b/web/lib/reading-api.ts
@@ -12,6 +12,7 @@ export type UnitKind = "page" | "chapter" | "slide" | "section" | "segment";
export type AnnotationKind = "highlight" | "underline" | "note";
export type ExportFormat = "auto" | "pdf" | "markdown";
export type RenderMode = "text" | "pdf" | "epub" | "video" | "audio";
+export type ContentFormat = "plain_text" | "web_markdown";
/** Palette offered by the annotation toolbar; mirrored server-side. */
export const ANNOTATION_COLORS = [
@@ -52,6 +53,10 @@ export interface MaterialInfo {
has_raw_view: boolean;
render_mode: RenderMode;
extractor: string;
+ content_format?: ContentFormat;
+ source_type?: string;
+ source_url?: string;
+ revision?: number;
annotation_count: number;
}
diff --git a/web/tests/reading-web-markdown.test.ts b/web/tests/reading-web-markdown.test.ts
new file mode 100644
index 000000000..65acde9d9
--- /dev/null
+++ b/web/tests/reading-web-markdown.test.ts
@@ -0,0 +1,22 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import path from "node:path";
+
+test("only captured web snapshots use the safe rich Markdown renderer", () => {
+ const reader = fs.readFileSync(
+ path.join(process.cwd(), "components/reading/TextUnitView.tsx"),
+ "utf8",
+ );
+ const pane = fs.readFileSync(
+ path.join(process.cwd(), "components/reading/ReaderPane.tsx"),
+ "utf8",
+ );
+
+ assert.match(reader, /contentFormat === "web_markdown"/);
+ assert.match(reader, /<RichMarkdownRenderer/);
+ assert.match(reader, /allowHtml=\{false\}/);
+ assert.match(reader, /enableImages/);
+ assert.match(reader, /whitespace-pre-wrap/);
+ assert.match(pane, /contentFormat=\{material\.content_format\}/);
+});