"""Extract readable, unpaginated Markdown from an already fetched HTML page.""" import re from collections.abc import Callable, Iterator from dataclasses import dataclass from urllib.parse import quote, urldefrag, urljoin, urlsplit from uuid import uuid4 import soupsieve from bs4 import BeautifulSoup, Comment, NavigableString, Tag from markdownify import MarkdownConverter _HEADING_LEVELS = {f"h{level}": level for level in range(1, 7)} _ALWAYS_HIDDEN = frozenset( { "head", "title", "script", "style", "template", "noscript", "svg", "canvas", "iframe", "object", "embed", "link", "meta", } ) _CHROME = frozenset({"nav", "aside", "footer", "form"}) _CHROME_ROLES = frozenset({"navigation", "banner", "contentinfo", "complementary", "search"}) _PRE_FENCE = re.compile(r"`+") _CODE_LANGUAGE = re.compile(r"(?:language|lang)-([a-zA-Z0-9_+#.-]{1,32})\Z") _LABEL_SPECIAL = re.compile(r"([\\`*_<>\[\]&])") _OUTLINE_ID = re.compile(r"@[0-9]+\Z") _MAX_DEPTH = 96 _MAX_MARKDOWN = 8 * 1024 * 1024 _MAX_RENDER_WORK = 32 * 1024 * 1024 _URL_SAFE = ":/?#[]@!$&'*+,;=%~.-_" @dataclass(frozen=True, slots=True) class _Heading: tag: Tag number: int level: int label: str @property def reference(self) -> str: return f"@{self.number}" def _attr(tag: Tag, name: str) -> str: value = tag.get(name) return value if isinstance(value, str) else "" def _ignored(tag: Tag, drop_chrome: bool) -> bool: name = tag.name if name in _ALWAYS_HIDDEN or tag.has_attr("hidden") or _attr(tag, "aria-hidden").lower() == "true": return True if name == "a" and _attr(tag, "href").startswith("#"): classes = tag.get("class", ()) if "headerlink" in classes or "heading-anchor" in classes: return True if not drop_chrome: return False return ( name in _CHROME or _attr(tag, "role") in _CHROME_ROLES or (name == "header" and tag.parent is not None and tag.parent.name in {"body", "html", "[document]"}) ) def _walk(root: Tag, drop_chrome: bool, stop_at: set[int] | None = None) -> Iterator[Tag | NavigableString]: stack: list[Iterator[Tag | NavigableString]] = [iter((root,))] while stack: node = next(stack[-1], None) if node is None: stack.pop() continue if isinstance(node, Tag): if _ignored(node, drop_chrome): continue if len(stack) > _MAX_DEPTH: raise ValueError("HTML is nested too deeply to render safely.") yield node if stop_at is None or id(node) not in stop_at: stack.append(iter(node.children)) elif type(node) is NavigableString: yield node def _reader_root(document: BeautifulSoup) -> Tag: body = document.body if body is None: body = document article = None for node in _walk(body, True): if not isinstance(node, Tag): continue if node.name == "main" or _attr(node, "role") == "main": return node if article is None and node.name == "article": article = node return article if article is not None else body def _label(tag: Tag) -> str: parts: list[str] = [] for node in _walk(tag, True): if isinstance(node, NavigableString): parts.append(str(node)) elif node.name == "br": parts.append(" ") elif node.name == "img": parts.append(_attr(node, "alt")) return " ".join("".join(parts).split()) def _headings(root: Tag) -> Iterator[_Heading]: number = 0 label_size = 0 for node in _walk(root, True): if isinstance(node, Tag) and (level := _HEADING_LEVELS.get(node.name)): label = _label(node) if not label: continue label_size += len(label) if label_size > _MAX_MARKDOWN: raise ValueError("HTML heading text exceeds the rendering limit.") number += 1 yield _Heading(node, number, level, label) def _section_heading(headings: list[_Heading], value: str) -> _Heading: if _OUTLINE_ID.fullmatch(value): for heading in headings: if heading.reference == value: return heading else: matches = [heading for heading in headings if heading.label == value] if len(matches) == 1: return matches[0] if matches: references = ", ".join(heading.reference for heading in matches[:8]) if len(matches) > 8: references += ", ..." raise ValueError(f"Heading text is ambiguous; use an outline ID ({references}).") raise ValueError(f"No heading matches {value!r}; use outline to see available headings.") def _anchor(tag: Tag) -> str: if anchor := _attr(tag, "id"): return anchor for child in tag.find_all("a"): if anchor := _attr(child, "id") or _attr(child, "name"): return anchor previous = tag.previous_sibling while isinstance(previous, Comment) or (isinstance(previous, NavigableString) and not previous.strip()): previous = previous.previous_sibling if isinstance(previous, Tag) and previous.name == "a": return _attr(previous, "id") or _attr(previous, "name") if previous is None and tag.parent is not None and tag.parent.name in {"section", "article", "div"}: return _attr(tag.parent, "id") return "" def _outline(headings: list[_Heading], url: str) -> str: if not headings: return "No headings found." page = quote(urldefrag(url).url, safe=_URL_SAFE) lines: list[str] = [] size = 0 for heading in headings: label = _LABEL_SPECIAL.sub(r"\\\1", heading.label) if anchor := _anchor(heading.tag): destination = f"{page}#{quote(anchor, safe='')}" label = f"[{label}]({destination})" line = f"- `{heading.reference}` H{heading.level} {label}" size += len(line) + 1 if size > _MAX_MARKDOWN: raise ValueError("HTML outline exceeds the Markdown rendering limit.") lines.append(line) return "\n".join(lines) def _absolute_link(base: str, target: str, *, web_only: bool = False) -> str: target = target.strip() if not target: return "" try: resolved = urljoin(base, target) parsed = urlsplit(resolved) except ValueError: return "" if parsed.scheme in {"http", "https"} and parsed.hostname: return quote(resolved, safe=_URL_SAFE) if not web_only and parsed.scheme in {"mailto", "tel"}: return quote(resolved, safe=_URL_SAFE) return "" def _bounded_start(tag: Tag) -> int: value = _attr(tag, "start") digits = value.removeprefix("-") return int(value) if len(digits) <= 9 and digits.isascii() and digits.isdecimal() else 1 def _colspan(tag: Tag) -> int: value = _attr(tag, "colspan") if len(value) <= 4 and value.isascii() and value.isdecimal(): return max(1, min(1000, int(value))) return 1 class _Converter(MarkdownConverter): def __init__( self, base: str, *, drop_chrome: bool, start: Tag | None = None, stop: Tag | None = None, markers: dict[int, str] | None = None, ) -> None: # Collapse insignificant source newlines without wrapping rendered lines. super().__init__(heading_style="ATX", wrap=True, wrap_width=None, escape_misc=True) self.base = base self.drop_chrome = drop_chrome self.start = start self.stop = stop self.leading_ancestors = {id(parent) for parent in start.parents} if start is not None else set() self.active = start is None self.markers = markers or {} self.depth = 0 self.work = 0 self.ordered_counts: dict[int, int] = {} self.tables: set[int] = set() def _charge(self, text: str) -> str: self.work += len(text) if len(text) > _MAX_MARKDOWN or self.work > _MAX_RENDER_WORK: raise ValueError("HTML exceeds the Markdown rendering limit.") return text def process_tag(self, node: Tag, parent_tags: set[str] | None = None) -> str: if self.depth >= _MAX_DEPTH: raise ValueError("HTML is nested too deeply to render safely.") if _ignored(node, self.drop_chrome): return "" if node is self.stop: self.active = False return "" if node is self.start: self.active = True if not self.active and id(node) not in self.leading_ancestors: return "" self.depth += 1 try: return self._charge(super().process_tag(node, parent_tags)) finally: self.depth -= 1 def process_text(self, el: NavigableString, parent_tags: set[str] | None = None) -> str: return self._charge(super().process_text(el, parent_tags)) if self.active else "" def get_conv_fn(self, tag_name: str) -> Callable[[Tag, str, set[str]], str] | None: # Unknown tags named h123... are not HTML headings. if tag_name.startswith("h") and tag_name[1:2].isdigit() and tag_name not in _HEADING_LEVELS: return None return super().get_conv_fn(tag_name) def convert_hN(self, n: int, el: Tag, text: str, parent_tags: set[str]) -> str: return super().convert_hN(n, el, self.markers.get(id(el), "") + text, parent_tags) def convert_a(self, el: Tag, text: str, parent_tags: set[str]) -> str: el["href"] = _absolute_link(self.base, _attr(el, "href")) return super().convert_a(el, text, parent_tags) def convert_video(self, el: Tag, text: str, parent_tags: set[str]) -> str: source = el.find("source", src=True) target = _attr(el, "src") or (_attr(source, "src") if isinstance(source, Tag) else "") destination = _absolute_link(self.base, target, web_only=True) if not destination: return text el["src"] = destination el["poster"] = _absolute_link(self.base, _attr(el, "poster"), web_only=True) return super().convert_video(el, text, parent_tags) def convert_img(self, el: Tag, text: str, parent_tags: set[str]) -> str: destination = _absolute_link(self.base, _attr(el, "src"), web_only=True) el["alt"] = _LABEL_SPECIAL.sub(r"\\\1", _attr(el, "alt")) if not destination: return _attr(el, "alt") el["src"] = destination return super().convert_img(el, text, parent_tags) def convert_pre(self, el: Tag, text: str, parent_tags: set[str]) -> str: if not text: return "" text = text.removeprefix("\n").removesuffix("\n") fence = "`" * max(3, 1 + max((len(run[0]) for run in _PRE_FENCE.finditer(text)), default=0)) code = el.find("code", recursive=False) language = "" for token in (code if code is not None else el).get("class", ()): if match := _CODE_LANGUAGE.fullmatch(token): language = match[1] break return f"\n\n{fence}{language}\n{text}\n{fence}\n\n" def convert_li(self, el: Tag, text: str, parent_tags: set[str]) -> str: parent = el.parent if parent is None or parent.name != "ol": return super().convert_li(el, text, parent_tags) text = text.strip() if not text: return "" key = id(parent) index = self.ordered_counts.get(key) if index is None: index = _bounded_start(parent) self.ordered_counts[key] = index + 1 bullet = f"{index}. " indent = " " * len(bullet) first, *rest = text.split("\n") return f"{bullet}{first}\n" + "".join(f"{indent}{line}\n" if line else "\n" for line in rest) def convert_td(self, el: Tag, text: str, parent_tags: set[str]) -> str: return " " + text.strip().replace("\n", " ") + " |" * _colspan(el) convert_th = convert_td def convert_tr(self, el: Tag, text: str, parent_tags: set[str]) -> str: if not text.strip(): return "" table = el.find_parent("table") key = id(table) if table is not None else id(el) row = f"| {text.strip()}\n" if key not in self.tables: self.tables.add(key) columns = sum(_colspan(cell) for cell in el.find_all(["th", "td"], recursive=False)) if columns: row += "|" + " --- |" * columns + "\n" return row def convert_main(self, el: Tag, text: str, parent_tags: set[str]) -> str: return self.convert_div(el, text, parent_tags) def _find(markdown: str, marker: str, headings: list[_Heading], query: str, context: int) -> str: needle = query.casefold() pattern = re.compile(re.escape(marker) + r"([1-9][0-9]*):") lines = markdown.split("\n") locations: list[tuple[int, int]] = [(0, 0)] for index, line in enumerate(lines): if marker not in line: continue matches = list(pattern.finditer(line)) if not matches: continue location = (index, int(matches[-1][1])) if locations[-1][0] == index: locations[-1] = location else: locations.append(location) lines[index] = pattern.sub("", line) locations.append((len(lines), 0)) output: list[str] = [] for (start, number), (stop, _) in zip(locations, locations[1:], strict=False): visible = [index for index in range(start, stop) if lines[index].strip()] windows: list[tuple[int, int]] = [] for position, index in enumerate(visible): line = lines[index].casefold() if needle not in line and needle not in re.sub(r"\\([!-/:-@\[-`{-~])", r"\1", line): continue left = max(0, position - context) right = min(len(visible), position + context + 1) if windows and left <= windows[-1][1]: windows[-1] = (windows[-1][0], right) else: windows.append((left, right)) if not windows: continue if number: heading = headings[number - 1] label = _LABEL_SPECIAL.sub(r"\\\1", heading.label) output.append(f"**{heading.reference} {label}**") else: output.append("**Before first heading**") output.append( "\n\n...\n\n".join("\n".join(lines[visible[left] : visible[right - 1] + 1]) for left, right in windows) ) if sum(len(part) + 2 for part in output) > _MAX_MARKDOWN: raise ValueError("Find results exceed the Markdown rendering limit.") return "\n\n".join(output) if output else f"No matches found for {query!r}." def _select(document: BeautifulSoup, value: str) -> list[Tag]: if len(value) > 1024: raise ValueError("CSS selector exceeds 1024 characters.") try: matches = {id(tag) for tag in document.select(value)} except soupsieve.SelectorSyntaxError as exc: raise ValueError(f"Invalid CSS selector: {exc}") from exc except RecursionError as exc: raise ValueError("CSS selector is too complex for this document.") from exc selected = [ node for node in _walk(document, False, stop_at=matches) if isinstance(node, Tag) and id(node) in matches ] if not selected: raise ValueError(f"CSS selector matched no visible elements: {value!r}.") return selected def render_html( body: bytes, url: str, charset: str | None, mode: str, value: str | None, context_lines: int, ) -> tuple[str, str]: """Return the page title and full view. Find searches literal rendered Markdown lines.""" if mode not in {"outline", "text", "section", "find", "css"}: raise ValueError(f"Unsupported HTML view: {mode!r}.") query = value.strip() if value is not None else "" if mode in {"section", "find", "css"} and not query: raise ValueError(f"The {mode} view requires a non-empty value.") if mode == "find" and context_lines < 0: raise ValueError("Find context_lines must be non-negative.") document = BeautifulSoup(body, "html.parser", from_encoding=charset) root = _reader_root(document) title_tag = document.title title = " ".join(title_tag.get_text().split()) if title_tag is not None else "" headings = list(_headings(root)) if mode in {"outline", "section", "find"} else None if not title: first_heading = headings[0] if headings else next(_headings(root), None) title = first_heading.label if first_heading is not None else url if mode == "outline" and headings is not None: return title, _outline(headings, url) base_tag = document.find("base", href=True) base = _absolute_link(url, _attr(base_tag, "href"), web_only=True) if isinstance(base_tag, Tag) else "" base = base or url if mode == "css": selected = _select(document, query) converter = _Converter(base, drop_chrome=False) blocks: list[str] = [] size = 0 for tag in selected: block = converter.convert_soup(tag).strip("\n") if not block: continue size += len(block) + 2 if size > _MAX_MARKDOWN: raise ValueError("CSS selection exceeds the Markdown rendering limit.") blocks.append(block) return title, "\n\n".join(blocks) if mode == "section" and headings is not None: start = _section_heading(headings, query) stop = next((heading.tag for heading in headings[start.number :] if heading.level <= start.level), None) converter = _Converter(base, drop_chrome=True, start=start.tag, stop=stop) elif mode == "find" and headings is not None: marker = f"fetchmcp{uuid4().hex}:" markers = {id(heading.tag): f"{marker}{heading.number}:" for heading in headings} converter = _Converter(base, drop_chrome=True, markers=markers) markdown = converter.convert_soup(root).strip("\n") return title, _find(markdown, marker, headings, query, context_lines) else: converter = _Converter(base, drop_chrome=True) return title, converter.convert_soup(root).strip("\n")