Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: Drop <header> from fetched page main content (#7509)
Nilay470fd30901a1
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.pyindex 92471b98661..5f207176e6b 100644--- a/studio/backend/core/inference/_html_to_md.py+++ b/studio/backend/core/inference/_html_to_md.py@@ -99,6 +99,16 @@ def _is_hidden_element(attr_dict: dict) -> bool:return _style_hides_element(attr_dict.get("style") or "")+def _is_aria_heading(attr_dict: dict) -> bool:+ """True for ``role="heading"``, which titles a page just as ``h1``-``h6`` does.++ ``role`` is a token list authors use for fallbacks (``role="future-role+ heading"``), so any token counts. WAI-ARIA takes the first token naming a+ real role, which would need the whole role table; matching anywhere is the+ safe direction, since keeping a stray title beats dropping a real one."""+ return "heading" in (attr_dict.get("role") or "").lower().split()++# HTML5 optional end tags: a listed start tag implicitly closes an open element# of the key type (as browsers do), else an unclosed ``<p hidden>``/``<li hidden>``# swallows every following sibling. Keys: closable elements; values: closers.@@ -184,6 +194,89 @@ _BLOCK_TAGS = frozenset(_HEADING_TAGS = frozenset({"h1", "h2", "h3", "h4", "h5", "h6"})_INLINE_EMPHASIS = {"strong": "**", "b": "**", "em": "*", "i": "*"}+# Measured density: 0.94-1.00 for link lists, 0.13-0.90 for content headers.+_HEADER_LINK_DENSITY = 0.93+# Below this the ratio is noise: link lists start at 182 chars, link-dense headers stop at 93.+_HEADER_MIN_CHARS = 150+# Short labels hide huge hrefs, so size the render too: content peaks at 363, link lists at 1609+.+_HEADER_MAX_RENDERED_CHARS = 800++# Pages nest headers one or two deep; past this, closing a frame cannot copy an unbounded chain.+_MAX_HEADER_NESTING = 8+++class _HeaderFrame:+ """Buffered ``<header>`` output plus the link tally used to judge it.++ Buffering (like ``_bq_stack``) defers the decision to ``</header>``, once the+ whole subtree is known. A header no end tag closes is emitted unchanged."""++ __slots__ = (+ "depth",+ "parts",+ "heading_parts",+ "text_chars",+ "link_chars",+ "stripped",+ "rendered_chars",+ "heading_chars",+ "outer_list_depth",+ "outer_link_seq",+ "outer_cell_seq",+ "outer_in_pre",+ "outer_in_code",+ "outer_bq_depth",+ )++ def __init__(+ self,+ depth: int,+ link_seq: int,+ cell_seq: int,+ in_pre: bool,+ in_code: int,+ bq_depth: int,+ list_depth: int,+ ):+ self.depth = depth+ self.parts: list[str] = []+ # Teed, so a heading routed through a nested buffer survives.+ self.heading_parts: list[str] = []+ self.stripped: bool = False # set by render()+ # Tallied on emit; re-cleaning each parent's buffer would be quadratic.+ self.rendered_chars: int = 0+ self.heading_chars: int = 0+ # Buffers open now enclose the frame, later ones nest. Link/cell sequence numbers, not+ # flags: an inner one replaces the outer in the renderer's single slot.+ self.outer_list_depth = list_depth+ self.outer_link_seq = link_seq+ self.outer_cell_seq = cell_seq+ self.outer_in_pre = in_pre+ self.outer_in_code = in_code+ self.outer_bq_depth = bq_depth+ # Both exclude heading text: it is kept anyway, so it must not vote on dropping the rest.+ self.text_chars: int = 0+ self.link_chars: int = 0++ def render(self, closed_by_own_tag: bool) -> str:+ """The buffer, or only its headings when the header is link furniture.++ Without a matching ``</header>`` the header may have adopted the page+ body, so keep it whole."""+ self.stripped = False+ if not closed_by_own_tag:+ return "".join(self.parts)+ headings = "".join(self.heading_parts)+ # Droppable chars only; headings survive, and blank structure _cleanup collapses must not+ # inflate a tiny header.+ droppable = self.rendered_chars - self.heading_chars+ big_enough = self.text_chars >= _HEADER_MIN_CHARS or droppable >= _HEADER_MAX_RENDERED_CHARS+ if big_enough and self.link_chars >= _HEADER_LINK_DENSITY * self.text_chars:+ self.stripped = True+ # The closing tag's blank line lands after the heading mark pops, so terminate it here.+ return headings + "\n\n" if headings.strip() else headings+ return "".join(self.parts)+class _MarkdownRenderer(HTMLParser):"""HTMLParser subclass that emits Markdown tokens into a list.@@ -193,7 +286,11 @@ class _MarkdownRenderer(HTMLParser):how the readability-style main-content pass drops page furniture."""- def __init__(self, scope_tags: frozenset[str] | None = None):+ def __init__(+ self,+ scope_tags: frozenset[str] | None = None,+ strip_header: bool = False,+ ):super().__init__(convert_charrefs = False)self._out: list[str] = []self._skip_depth: int = 0@@ -202,21 +299,43 @@ class _MarkdownRenderer(HTMLParser):self._scope_tags = scope_tagsself._scope_depth: int = 0- # Output boundaries per top-level scope element, so a caller can size each- # candidate alone and a swarm of tiny sibling cards can't clear the threshold.+ # One boundary per top-level scope element, so a swarm of tiny cards cannot clear the gate.self.scope_segments: list[str] = []self._scope_seg_start: int | None = None- # Hidden-subtree tracking: stack of open non-void tags plus the indices- # where a hidden element started. End tags pop to the matching tag, so- # an omitted </p>/<li> close cannot leave the renderer stuck hidden.+ # Open non-void tags plus hidden-start indices, so an omitted </p>/</li> cannot leave the+ # renderer stuck hidden.self._open_tags: list[str] = []+ # Open tags that can be closed implicitly; zero lets _close_implicit skip the scan.+ self._closable_open: int = 0self._hidden_marks: list[int] = []+ # Open <header> buffers, innermost last. Empty unless strip_header.+ self._strip_header = strip_header+ self._header_stack: list[_HeaderFrame] = []+ # Furniture chars removed, so a candidate is sized as the page wrote it.+ self._dropped_chars: int = 0+ self._seg_dropped_start: int = 0+ self.scope_dropped: list[int] = []+ # Heading text per segment: role="heading", hgroup and linked h1 render as prose, so ATX+ # reparsing alone cannot keep them out of the gate.+ self._seg_heading_texts: list[str] = []+ self.scope_heading_prose: list[int] = []+ # Open-tag indices of headings, unwound with _hidden_marks.+ self._heading_marks: list[int] = []+# Link stateself._link_href: str | None = Noneself._link_text_parts: list[str] = []self._in_link: bool = False+ self._link_seq: int = 0+ # A link wrapping a heading emits after the mark pops, so the tee is told to treat it so.+ self._link_had_heading: bool = False+ self._link_heading_parts: list[str] = []+ self._emit_as_heading: bool = False+ self._replaying: bool = False+ # Credited only at </a>: an <a> left open adopts body prose, which is not furniture.+ self._link_header_chars: int = 0# List stateself._list_stack: list[str] = [] # "ul" or "ol"@@ -227,6 +346,7 @@ class _MarkdownRenderer(HTMLParser):self._current_row: list[str] = []self._cell_parts: list[str] = []self._in_cell: bool = False+ self._cell_seq: int = 0self._header_row_done: bool = Falseself._row_has_th: bool = Falseself._is_first_row: bool = False@@ -234,15 +354,57 @@ class _MarkdownRenderer(HTMLParser):# Pre/code stateself._in_pre: bool = Falseself._pre_parts: list[str] = []- self._in_inline_code: bool = False+ # Depth, not a flag: nested <code> opens two spans and each </code> owes a backtick.+ self._inline_code_depth: int = 0# Blockquote state: stack of buffers so nested blockquotes get the right ">" depth.self._bq_stack: list[list[str]] = []# ------------------------------------------------------------------+ def _nested_buffer_open(self, frame: _HeaderFrame) -> bool:+ """True when a side buffer opened *inside* *frame* still holds content.++ Such a buffer emits into the frame when it closes; an enclosing one+ (already open at ``<header>``) must not capture it."""+ # Only the buffer _emit would pick matters, in its order; OR-ing them calls an enclosing+ # one nested.+ if self._in_link:+ return self._link_seq != frame.outer_link_seq+ if self._in_cell:+ return self._cell_seq != frame.outer_cell_seq+ if self._in_pre:+ return not frame.outer_in_pre+ return len(self._bq_stack) > frame.outer_bq_depth+def _emit(self, text: str) -> None:+ frame = self._header_stack[-1] if self._header_stack else None+ # Tee wherever the text routes, so a heading in a nested buffer is captured. A link opened+ # inside the frame delivers twice, so tee only the formatted form; an enclosing link, once.+ in_nested_link = (+ self._in_link and self._link_seq != frame.outer_link_seq if frame else False+ )+ # Replays never tee: the text was teed on the way in. _finish_link re-arms the tee itself.+ as_heading = (+ self._heading_marks and not in_nested_link and not self._replaying+ ) or self._emit_as_heading+ if frame is not None and as_heading:+ frame.heading_parts.append(text)+ frame.heading_chars += len(text.strip())+ # For the eligibility gate, frame or not. Link text waits for _finish_link to count once.+ if not self._replaying and (+ (self._heading_marks and not self._in_link) or self._emit_as_heading+ ):+ self._seg_heading_texts.append(text)+ nested_open = self._nested_buffer_open(frame) if frame is not None else False+ # Tally once, on the emit reaching the frame; counting again on flush doubled it.+ if frame is not None and not nested_open:+ frame.rendered_chars += len(text.strip())+ frame.parts.append(text)+ returnif self._in_link:self._link_text_parts.append(text)+ if self._heading_marks:+ self._link_heading_parts.append(text)elif self._in_cell:self._cell_parts.append(text)elif self._in_pre:@@ -253,6 +415,36 @@ class _MarkdownRenderer(HTMLParser):self._out.append(text)# ------------------------------------------------------------------+ def _seg_heading_prose(self) -> int:+ """Heading characters in this segment that the gate would otherwise read as+ body prose. ATX headings carry their own ``#`` here and so score zero."""+ return _visible_chars("".join(self._seg_heading_texts))++ def _drain_pre(self) -> None:+ """Emit the open ``<pre>`` and empty it, so a late ``</pre>`` cannot replay+ it outside a stripped header and push the article past the fetch cap."""+ raw = "".join(self._pre_parts)+ self._in_pre = False+ self._pre_parts = []+ fence = _fence_for(raw)+ self._emit_replay(f"\n\n{fence}\n{raw}\n{fence}\n\n")++ def _drain_blockquote(self) -> None:+ """Pop the innermost quote and emit it prefixed. Not used by ``flush_pending``,+ which re-nests into the parent stack instead of emitting."""+ prefixed = self._prefix_blockquote("".join(self._bq_stack.pop()))+ if prefixed:+ self._emit_replay("\n\n" + prefixed + "\n\n")++ def _emit_replay(self, text: str) -> None:+ """Emit a flushed buffer's own output, which must not be teed as a heading+ a second time (the raw text was teed when it entered the buffer)."""+ was, self._replaying = self._replaying, True+ try:+ self._emit(text)+ finally:+ self._replaying = was+def _prefix_blockquote(self, content: str) -> str:"""Prefix every line of *content* with ``> ``."""# Strip trailing whitespace, then collapse blank lines.@@ -283,7 +475,7 @@ class _MarkdownRenderer(HTMLParser):if not self._current_row:returnline = "| " + " | ".join(self._current_row) + " |"- self._emit(line + "\n")+ self._emit_replay(line + "\n")if not self._header_row_done and (self._row_has_th or self._is_first_row):sep = "| " + " | ".join("---" for _ in self._current_row) + " |"self._emit(sep + "\n")@@ -295,17 +487,40 @@ class _MarkdownRenderer(HTMLParser):# Link text helper: normalize whitespace so block content in <a> stays single-line.def _finish_link(self) -> None:text = re.sub(r"\s+", " ", "".join(self._link_text_parts)).strip()+ heading_text = re.sub(r"\s+", " ", "".join(self._link_heading_parts)).strip()href = self._link_href or ""self._in_link = False+ self._link_text_parts = []+ self._link_heading_parts = []+ # An anchor wrapping a heading AND other content tees the title alone, else the nav rides.+ partial = bool(heading_text) and heading_text != text+ self._emit_as_heading = self._link_had_heading and not partial+ self._link_had_heading = False+ # Recovery paths reach here without </a>, so drop the uncredited tally.+ self._link_header_chars = 0if href and text:self._emit(f"[{text}]({href})")elif text:self._emit(text)+ self._emit_as_heading = False+ if partial and self._header_stack:+ frame = self._header_stack[-1]+ frame.heading_parts.append(heading_text + "\n\n")+ frame.heading_chars += len(heading_text)+ # Preserved by hand, so tell the gate too or a title-only card reads as body prose.+ self._seg_heading_texts.append(heading_text)# ------------------------------------------------------------------# Tag handlers# ------------------------------------------------------------------# Structural bookkeeping shared by every start tag (skip/hidden/scope).+ def _truncate_open_tags(self, index: int) -> None:+ """Drop the open-tag stack above *index*, keeping the closable count."""+ for name in self._open_tags[index:]:+ if name in _IMPLICIT_CLOSERS:+ self._closable_open -= 1+ del self._open_tags[index:]+def _close_implicit(self, tag: str) -> None:"""HTML5 optional-end-tag recovery for a start tag about to open.@@ -314,6 +529,8 @@ class _MarkdownRenderer(HTMLParser):``<span>``. Stops at a ``_CLOSE_BARRIERS`` container so recovery never crossesa nested list/table/dl and leaks the outer item's hidden content. Runs evenfor skipped ``<nav>``/``<footer>``, which also close ``<p>``."""+ if not self._closable_open:+ returnbarriers = _CLOSE_BARRIERS.get(tag, ())while True:close_at = None@@ -327,9 +544,84 @@ class _MarkdownRenderer(HTMLParser):breakif close_at is None:break- del self._open_tags[close_at:]+ self._truncate_open_tags(close_at)while self._hidden_marks and self._hidden_marks[-1] >= close_at:self._hidden_marks.pop()+ while self._heading_marks and self._heading_marks[-1] >= close_at:+ self._heading_marks.pop()+ self._close_header_frames(close_at)++ def _close_header_frames(+ self,+ depth: int,+ own_tag: bool = False,+ ) -> None:+ """Judge and emit every buffered header at or below *depth*. Only the+ innermost frame can be the one its own ``</header>`` closed."""+ closed_by_own_tag = own_tag+ while self._header_stack and self._header_stack[-1].depth >= depth:+ self._finalize_nested_buffers(self._header_stack[-1])+ frame = self._header_stack.pop()+ if self._header_stack:+ # Roll the tally outward so an enclosing header is judged whole.+ self._header_stack[-1].text_chars += frame.text_chars+ self._header_stack[-1].link_chars += frame.link_chars+ self._header_stack[-1].heading_parts.extend(frame.heading_parts)+ self._header_stack[-1].heading_chars += frame.heading_chars+ out = frame.render(closed_by_own_tag)+ if frame.stripped:+ self._dropped_chars += max(0, frame.rendered_chars - frame.heading_chars)+ self._emit(out)+ closed_by_own_tag = False++ def _finalize_nested_buffers(self, frame: _HeaderFrame) -> None:+ """Close side buffers opened inside *frame* whose end tags the page omitted.++ Their content is the header's, so it has to land in the frame before the+ strip is judged; otherwise it is emitted afterwards and escapes."""+ if self._in_link and self._link_seq != frame.outer_link_seq:+ # The header boundary proves this anchor did not adopt the body: its text is furniture.+ frame.link_chars += self._link_header_chars+ self._finish_link()+ # Code opened OUTSIDE the header is the page's; closing it here leaves </code> unpaired.+ while self._inline_code_depth > frame.outer_in_code:+ self._inline_code_depth -= 1+ self._emit("`")+ # Before the cell: _finish_row emits, and an open <pre> would swallow the row as CODE| |.+ if self._in_pre and not frame.outer_in_pre:+ self._drain_pre()+ if self._in_cell and self._cell_seq != frame.outer_cell_seq:+ self._finish_cell()+ self._finish_row()+ while len(self._bq_stack) > frame.outer_bq_depth:+ self._drain_blockquote()+ # A list left open in the header would indent the body's lists under phantom nesting.+ while len(self._list_stack) > frame.outer_list_depth:+ if self._list_stack.pop() == "ol" and self._ol_counter:+ self._ol_counter.pop()++ def _flush_header_frames(self) -> None:+ """Emit every open header unchanged, abandoning the strip."""+ while self._header_stack:+ self._finalize_nested_buffers(self._header_stack[-1])+ self._emit("".join(self._header_stack.pop().parts))++ def _count_header_text(self, text: str) -> None:+ """Tally visible text for the innermost header's link density. Heading text+ is skipped so a long linked heading cannot condemn the byline beside it."""+ if not self._header_stack or self._heading_marks:+ return+ frame = self._header_stack[-1]+ chars = len(text.strip())+ frame.text_chars += chars+ # An anchor with no usable href renders as prose, not as a link.+ if not (self._in_link and self._link_href):+ return+ if self._link_seq == frame.outer_link_seq:+ # An enclosing anchor closes after the header, too late to credit.+ frame.link_chars += chars+ else:+ self._link_header_chars += charsdef _enter_tag(self, tag: str, attr_dict: dict) -> bool:"""Track open/hidden/scope state; return True when the tag's content@@ -337,14 +629,41 @@ class _MarkdownRenderer(HTMLParser):first so recovery also fires for skipped tags."""if tag not in _VOID_TAGS:self._open_tags.append(tag)+ if tag in _IMPLICIT_CLOSERS:+ self._closable_open += 1if _is_hidden_element(attr_dict):self._hidden_marks.append(len(self._open_tags) - 1)+ if tag in _HEADING_TAGS or tag == "hgroup" or _is_aria_heading(attr_dict):+ self._heading_marks.append(len(self._open_tags) - 1)+ if self._in_link:+ self._link_had_heading = True+ if (+ self._strip_header+ and tag == "header"+ and not self._hidden_marks+ and len(self._header_stack) < _MAX_HEADER_NESTING+ ):+ self._header_stack.append(+ _HeaderFrame(+ len(self._open_tags) - 1,+ self._link_seq if self._in_link else -1,+ self._cell_seq if self._in_cell else -1,+ self._in_pre,+ self._inline_code_depth,+ len(self._bq_stack),+ len(self._list_stack),+ )+ )elif _is_hidden_element(attr_dict):# Void elements never join the stack, so suppress a hidden one inline.return Falseif self._scope_tags is not None and tag in self._scope_tags:+ # A scope element inside a header would strand its output in the buffer.+ self._flush_header_frames()if self._scope_depth == 0:self._scope_seg_start = len(self._out)+ self._seg_dropped_start = self._dropped_chars+ self._seg_heading_texts = []self._scope_depth += 1if self._hidden_marks:return False@@ -355,21 +674,33 @@ class _MarkdownRenderer(HTMLParser):def _exit_tag(self, tag: str) -> bool:"""Pop to the matching open tag; return True when the end tag shouldbe rendered (False = it closed inside a hidden / out-of-scope region)."""+ # Recover an <a> left open before the segment is recorded, or its text is stranded.+ if self._in_link and self._scope_tags is not None and tag in self._scope_tags:+ self._finish_link()suppressed = bool(self._hidden_marks) or (self._scope_tags is not None and self._scope_depth == 0)+ # An element that IS the heading emits when its buffer closes, after the mark pops; flush+ # it here while the tee still recognises it.+ if self._in_link and tag == "a" and self._heading_marks:+ self._finish_link()if tag not in _VOID_TAGS:# Pop to the innermost matching open tag (recovers omitted closes).for i in range(len(self._open_tags) - 1, -1, -1):if self._open_tags[i] == tag:- del self._open_tags[i:]+ self._truncate_open_tags(i)while self._hidden_marks and self._hidden_marks[-1] >= i:self._hidden_marks.pop()+ while self._heading_marks and self._heading_marks[-1] >= i:+ self._heading_marks.pop()+ self._close_header_frames(i, own_tag = tag == "header")breakif self._scope_tags is not None and tag in self._scope_tags and self._scope_depth > 0:self._scope_depth -= 1if self._scope_depth == 0 and self._scope_seg_start is not None:self.scope_segments.append("".join(self._out[self._scope_seg_start :]))+ self.scope_dropped.append(self._dropped_chars - self._seg_dropped_start)+ self.scope_heading_prose.append(self._seg_heading_prose())self._scope_seg_start = Nonereturn not suppressed@@ -402,7 +733,10 @@ class _MarkdownRenderer(HTMLParser):elif tag == "a":self._link_href = attr_dict.get("href")self._link_text_parts = []+ self._link_heading_parts = []self._in_link = True+ self._link_seq += 1+ self._link_header_chars = 0elif tag in _INLINE_EMPHASIS:self._emit(_INLINE_EMPHASIS[tag])@@ -450,7 +784,7 @@ class _MarkdownRenderer(HTMLParser):self._in_pre = Trueelif tag == "code" and not self._in_pre:- self._in_inline_code = True+ self._inline_code_depth += 1self._emit("`")elif tag == "table":@@ -468,6 +802,7 @@ class _MarkdownRenderer(HTMLParser):self._finish_cell() # handles omitted </td>/</th>self._cell_parts = []self._in_cell = True+ self._cell_seq += 1if tag == "th":self._row_has_th = True@@ -491,6 +826,8 @@ class _MarkdownRenderer(HTMLParser):self._emit("\n\n")elif tag == "a":+ if self._header_stack:+ self._header_stack[-1].link_chars += self._link_header_charsself._finish_link()elif tag in _INLINE_EMPHASIS:@@ -501,10 +838,7 @@ class _MarkdownRenderer(HTMLParser):elif tag == "blockquote":if self._bq_stack:- content = "".join(self._bq_stack.pop())- prefixed = self._prefix_blockquote(content)- if prefixed:- self._emit("\n\n" + prefixed + "\n\n")+ self._drain_blockquote()elif tag == "ul":if self._list_stack and self._list_stack[-1] == "ul":@@ -518,14 +852,12 @@ class _MarkdownRenderer(HTMLParser):self._ol_counter.pop()self._emit("\n")- elif tag == "pre":- raw = "".join(self._pre_parts)- self._in_pre = False- block = "```\n" + raw + "\n```"- self._emit("\n\n" + block + "\n\n")+ elif tag == "pre" and self._in_pre:+ self._drain_pre()- elif tag == "code" and not self._in_pre:- self._in_inline_code = False+ # Already closed means a frame recovered it; a second backtick codes the rest of the page.+ elif tag == "code" and not self._in_pre and self._inline_code_depth:+ self._inline_code_depth -= 1self._emit("`")elif tag in ("th", "td"):@@ -554,14 +886,19 @@ class _MarkdownRenderer(HTMLParser):if self._text_suppressed():returnif self._in_pre:+ self._count_header_text(data)self._pre_parts.append(data)return# Preserve literal whitespace inside inline <code> spans.- if self._in_inline_code:+ if self._inline_code_depth:+ self._count_header_text(data)self._emit(data)return# Collapse all whitespace (including newlines) per HTML rules.text = re.sub(r"\s+", " ", data)+ # Sized after collapsing, as the reader sees it: raw spaces in a link cleared the floor at+ # ~100% density and dropped the byline.+ self._count_header_text(text)# Suppress whitespace-only nodes between table elements (source indentation).if self._in_table and not self._in_cell and not text.strip():return@@ -570,32 +907,37 @@ class _MarkdownRenderer(HTMLParser):def handle_entityref(self, name: str) -> None:if self._text_suppressed():return- self._emit(html.unescape(f"&{name};"))+ text = html.unescape(f"&{name};")+ self._count_header_text(text)+ self._emit(text)def handle_charref(self, name: str) -> None:if self._text_suppressed():return- self._emit(html.unescape(f"&#{name};"))+ text = html.unescape(f"&#{name};")+ self._count_header_text(text)+ self._emit(text)# Flush pending buffers (handles truncated HTML from capped fetches)def flush_pending(self) -> None:"""Flush open side-buffers into ``_out`` after close(), recovering truncated HTML."""+ # Headers first: a frame finalizes its inner buffers, then emits into the enclosing link or+ # cell, which must still be open here; it is finalized below.+ self._flush_header_frames()+# Flush innermost buffers first so their content propagates outward.if self._in_link:self._finish_link()- if self._in_inline_code:- self._in_inline_code = False+ while self._inline_code_depth:+ self._inline_code_depth -= 1self._emit("`")self._finish_cell()self._finish_row()if self._in_pre:- raw = "".join(self._pre_parts)- self._in_pre = False- block = "```\n" + raw + "\n```"- self._emit("\n\n" + block + "\n\n")+ self._drain_pre()# Flatten any open blockquote buffers (innermost first).while self._bq_stack:@@ -613,6 +955,8 @@ class _MarkdownRenderer(HTMLParser):# here (after the side-buffers) so a truncated main-content page is scored.if self._scope_seg_start is not None:self.scope_segments.append("".join(self._out[self._scope_seg_start :]))+ self.scope_dropped.append(self._dropped_chars - self._seg_dropped_start)+ self.scope_heading_prose.append(self._seg_heading_prose())self._scope_seg_start = Noneself._scope_depth = 0@@ -622,18 +966,19 @@ def _cleanup(text: str) -> str:"""Normalize whitespace and blank lines, preserving fenced code blocks verbatim."""lines = text.split("\n")out: list[str] = []- in_fence = False+ fence = 0blank_run = 0for line in lines:stripped = line.rstrip(" \t")- if stripped.startswith("```"):- in_fence = not in_fence+ moved = _fence_state(stripped, fence)+ if moved != fence:+ fence = movedblank_run = 0out.append(stripped)continue- if in_fence:+ if fence:out.append(line)continue@@ -695,53 +1040,144 @@ def _line_is_boilerplate(line: str) -> bool:return bool(segments) and all(segment in _BOILERPLATE_NORMALIZED for segment in segments)+def _fence_state(line: str, fence: int) -> int:+ """Fence width after *line*, 0 outside a block. Every pass over rendered text+ must agree with ``_fence_for``: a block opened with a longer fence is closed+ only by a run at least as long, so a literal ``` inside it is content."""+ stripped = line.strip()+ if len(stripped) < 3 or stripped.count("`") != len(stripped):+ return fence+ if not fence:+ return len(stripped)+ return 0 if len(stripped) >= fence else fence++def _strip_boilerplate_lines(text: str) -> str:"""Drop short lines that consist entirely of known page-furniture phrases.Fenced code blocks are preserved verbatim: boilerplate never rendersinside ``<pre>``, while READMEs legitimately quote error strings."""out: list[str] = []- in_fence = False+ fence = 0for line in text.split("\n"):- if line.lstrip().startswith("```"):- in_fence = not in_fence+ moved = _fence_state(line, fence)+ if moved != fence:+ fence = movedout.append(line)continue- if not in_fence and len(line) <= _BOILERPLATE_MAX_LINE_CHARS and _line_is_boilerplate(line):+ if not fence and len(line) <= _BOILERPLATE_MAX_LINE_CHARS and _line_is_boilerplate(line):continueout.append(line)# Collapse blank runs the dropped lines may have left behind.return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip()-def _render(source_html: str, scope_tags: frozenset[str] | None) -> str:- renderer = _MarkdownRenderer(scope_tags = scope_tags)+def _new_renderer(+ source_html: str, scope_tags: frozenset[str] | None, strip_header: bool+) -> _MarkdownRenderer:+ renderer = _MarkdownRenderer(scope_tags = scope_tags, strip_header = strip_header)renderer.feed(source_html)renderer.close()renderer.flush_pending()- raw = "".join(renderer._out)- return _cleanup(raw)+ return renderer+++def _render(+ source_html: str,+ scope_tags: frozenset[str] | None,+ strip_header: bool = False,+) -> str:+ return _cleanup("".join(_new_renderer(source_html, scope_tags, strip_header)._out))def _select_main_scope_render(source_html: str, tag: str) -> tuple[int, str]:"""Length and boilerplate-stripped render of the largest single ``<tag>``subtree. Sizing candidates one at a time stops many tiny sibling cards fromclearing the threshold together, and returning that one subtree keeps- unrelated siblings (related cards, comment threads) out of the output."""- renderer = _MarkdownRenderer(scope_tags = frozenset({tag}))- renderer.feed(source_html)- renderer.close()- renderer.flush_pending()+ unrelated siblings (related cards, comment threads) out of the output.++ A candidate earns its place on the prose it RETAINED, then gets its dropped+ header furniture added back to rank against siblings. Furniture must not buy+ eligibility: a card whose header was the only bulk would otherwise clear the+ gate on deleted bytes and suppress the ``<main>`` holding the real page.++ Nor may it dominate: the credit is capped at the retained render, so removed+ furniture can never be the majority of a score. Uncapped, a teaser with a+ 1000 link header outranked a sibling holding five times its real text."""+ renderer = _new_renderer(source_html, frozenset({tag}), strip_header = True)+ dropped = renderer.scope_dropped+ heading_prose = renderer.scope_heading_prosebest_len = 0best_render = ""- for seg in renderer.scope_segments:+ for i, seg in enumerate(renderer.scope_segments):rendered = _strip_boilerplate_lines(_cleanup(seg))- if len(rendered) > best_len:- best_len = len(rendered)+ prose = _visible_chars(rendered) - heading_prose[i]+ if prose < _MIN_MAIN_CONTENT_CHARS:+ continue+ size = len(rendered) + min(dropped[i], len(rendered))+ if size > best_len:+ best_len = sizebest_render = renderedreturn best_len, best_render+def _visible_chars(text: str) -> int:+ """Visible characters in *text*, ignoring blank lines and link destinations.++ Headings are NOT discounted here. The renderer already tallies what it marked+ as a heading (``_seg_heading_prose``), which sees ``role="heading"``, hgroup+ and a linked ``h1``; re-deriving that from ATX syntax could not, and running+ both meant two answers to one question."""+ return sum(_visible_len(line) for line in text.split("\n") if line.strip())+++def _fence_for(raw: str) -> str:+ """Fence long enough to survive backticks in *raw*, as CommonMark requires:+ a literal ``` line inside the block would otherwise close it early."""+ longest = run = 0+ for char in raw:+ run = run + 1 if char == "`" else 0+ longest = max(longest, run)+ return "`" * max(3, longest + 1)+++def _visible_len(line: str) -> int:+ """Length of *line* without Markdown link destinations. A tracking URL is not+ prose: a card holding one [Read](/x?<300 bytes>) otherwise scored 339 visible+ characters off 4 and displaced the article. Scanned, so no backtracking."""+ total, i, n = 0, 0, len(line)+ open_bracket = False+ while i < n:+ if line[i] == "\\":+ total += 2+ i += 2+ continue+ if line[i] == "[":+ open_bracket = True+ # With no opening bracket, "](" is literal and the parens after it are prose.+ if open_bracket and line[i] == "]" and i + 1 < n and line[i + 1] == "(":+ # Destinations may hold balanced or escaped parens, so the first ) does not end them.+ j, depth = i + 2, 1+ while j < n and depth:+ char = line[j]+ if char == "\\":+ j += 2+ continue+ depth += (char == "(") - (char == ")")+ j += 1+ if depth:+ # Never balances, so it is not a link; the bytes show as text, so count them.+ total += 1+ i += 1+ continue+ i = j+ open_bracket = False+ continue+ total += 1+ i += 1+ return total++# A scoped conversion below this size is judged not to be the page's main# content (e.g. an empty <article> stub) and the next candidate is tried._MIN_MAIN_CONTENT_CHARS = 200@@ -756,17 +1192,16 @@ def html_to_markdown(source_html: str, *, main_content: bool = False) -> str:``main_content=True`` applies a readability-style heuristic for pagefetches: prefer the ``<article>`` subtree (GitHub renders READMEs there),- then ``<main>``, falling back to the whole document, and strip known- boilerplate fragments from the result.+ then ``<main>``, falling back to the whole document, reduce a link-only+ ``<header>`` to the heading it carries, and strip known boilerplate+ fragments from the result."""- # Normalize line endings before parsing.source_html = source_html.replace("\r\n", "\n").replace("\r", "\n")if main_content:for scope_tag in ("article", "main"):- # Render only the chosen subtree so sibling <article>/<main>- # elements do not leak in once the largest passes the size gate.+ # Render only the chosen subtree so sibling <article>/<main> elements do not leak in.length, rendered = _select_main_scope_render(source_html, scope_tag)if length >= _MIN_MAIN_CONTENT_CHARS:return rendered- return _strip_boilerplate_lines(_render(source_html, None))+ return _strip_boilerplate_lines(_render(source_html, None, strip_header = True))return _render(source_html, None)diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.pyindex 0f749d2fd8e..0d3d2af1aee 100644--- a/studio/backend/tests/test_web_fetch_extraction.py+++ b/studio/backend/tests/test_web_fetch_extraction.py@@ -21,7 +21,7 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)-from core.inference._html_to_md import html_to_markdown+from core.inference._html_to_md import _is_aria_heading, html_to_markdownfrom core.inference.tools import (_fetch_page_text,_fetch_url_raw,@@ -163,9 +163,7 @@ def test_inline_style_display_none_important_is_dropped():def test_inline_style_display_none_among_other_declarations():- html = (- "<body><p>keep</p>" '<div style="color: red; display : none ; margin:0">gone</div></body>'- )+ html = '<body><p>keep</p><div style="color: red; display : none ; margin:0">gone</div></body>'out = html_to_markdown(html)assert "keep" in outassert "gone" not in out@@ -216,8 +214,7 @@ def test_hidden_paragraph_omitted_close_does_not_swallow_siblings():# HTML5 optional end tags: a sibling <p> start tag implicitly closes an open# <p hidden>, so the hidden region ends there instead of swallowing siblings.html = (- "<body><div><p hidden>secret"- "<p>visible one</p><p>visible two</p></div><p>after</p></body>"+ "<body><div><p hidden>secret<p>visible one</p><p>visible two</p></div><p>after</p></body>")out = html_to_markdown(html)assert "secret" not in out@@ -1269,3 +1266,858 @@ def test_looks_like_html_document_only_matches_real_documents():"<dl><dt>x</dt></dl>",):assert not _looks_like_html_document(frag), frag+++# <header> inside the selected scope (Wikipedia's Vector 2022 skin)+def _interlanguage_list(count: int) -> str:+ return "".join(+ f'<li class="interlanguage-link">'+ f'<a href="https://x{i}.wikipedia.org/wiki/K">Lang{i}</a></li>'+ for i in range(count)+ )+++def test_in_main_header_language_list_does_not_displace_article():+ body = (+ "<main><header><h1>Cat</h1><div id='p-lang-btn'><ul>%s</ul></div></header>"+ "<div id='mw-content-text'><p>%s</p></div></main>"+ ) % (_interlanguage_list(300), "The cat (Felis catus) is a small mammal. " * 30)+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Felis catus" in out+ assert "Lang0" not in out+ assert "x0.wikipedia.org" not in out+ assert "# Cat" in out+ assert out.index("Felis catus") < 200+++def test_header_title_kept_when_article_is_shorter_than_its_language_list():+ body = ("<main><header><h1>Stub</h1><ul>%s</ul></header><p>%s</p></main>") % (+ _interlanguage_list(300),+ "Short article body. " * 15,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Short article body." in out+ assert "Lang0" not in out+ assert "# Stub" in out+++def test_link_only_article_header_reduces_to_its_heading():+ body = ("<article><header><h1>Post title</h1><ul>%s</ul></header><p>%s</p></article>") % (+ _interlanguage_list(300),+ "Real article content. " * 40,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "# Post title" in out+ assert "Real article content." in out+ assert "Lang0" not in out+++def test_article_header_byline_and_date_are_kept():+ # Standard semantic blog markup: only near-pure link lists are furniture.+ body = (+ "<article><header><h1>Why Rust</h1><p>By Jane Doe</p>"+ "<time>2026-07-12</time><p>A summary of what this essay argues.</p></header>"+ "<p>%s</p></article>"+ ) % ("Real article content. " * 40)+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "# Why Rust" in out+ assert "By Jane Doe" in out+ assert "2026-07-12" in out+ assert "A summary of what this essay argues." in out+++def test_small_link_header_is_left_alone():+ # Under the size floor there is nothing large enough to displace an article.+ body = (+ "<article><header><h1>Post title</h1>"+ "<a href='/subscribe'>Subscribe now</a></header><p>%s</p></article>"+ ) % ("Real article content. " * 40)+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Subscribe now" in out+ assert "Real article content." in out+++def test_unclosed_header_does_not_swallow_the_body():+ # Browsers adopt the rest of the subtree into an unclosed <header>.+ body = "<main><header><h1>Title</h1><p>%s</p></main>" % ("Article body text. " * 40)+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Article body text." in out+ assert "Title" in out+++def test_unclosed_header_with_many_headings_keeps_body():+ # Headings survive, so a heading-rich page clears the size gate alone.+ sections = "".join(f"<h2>Section {i}</h2><p>{'Body prose here. ' * 10}</p>" for i in range(12))+ body = f"<main><header><h1>T</h1>{sections}</main>"+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Body prose here." in out+ assert "Section 0" in out+++def test_header_strip_applies_without_article_or_main():+ body = ("<header><h1>Site name</h1><ul>%s</ul></header><p>%s</p>") % (+ _interlanguage_list(300),+ "Page prose without a main landmark. " * 20,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Page prose without a main landmark." in out+ assert "# Site name" in out+ assert "Lang0" not in out+++def test_header_kept_in_unscoped_conversion():+ body = "<header><h1>Site</h1><a href='/x'>Nav link</a></header><p>Text.</p>"+ out = html_to_markdown(f"<body>{body}</body>")+ assert "Nav link" in out+ assert "Text." in out+++def test_unclosed_header_in_truncated_scope_keeps_body():+ # A capped fetch ends before </main>: the flushed segment must still carry its dropped prose.+ sections = "".join(+ f"<h2>Section {i} of the article</h2><p>{'Body prose here. ' * 10}</p>" for i in range(12)+ )+ out = html_to_markdown(+ f"<body><main><header><h1>T</h1>{sections}",+ main_content = True,+ )+ assert "Body prose here." in out+ assert "Section 0 of the article" in out+++def test_sibling_card_does_not_beat_an_article_with_a_swallowed_body():+ real = "<article><header><h1>Real</h1><p>%s</p></article>" % ("Real article body. " * 40)+ card = "<article><p>%s</p></article>" % ("Related card teaser. " * 12)+ out = html_to_markdown(f"<body>{real}{card}</body>", main_content = True)+ assert "Real article body." in out+ assert "Related card teaser." not in out+++def test_text_heavy_header_is_kept_even_when_longer_than_the_body():+ # python.org keeps its hero carousel here, so size alone cannot condemn it.+ body = "<main><header><h1>Title</h1><p>%s</p></header><p>%s</p></main>" % (+ "Introductory hero text. " * 30,+ "The real body prose. " * 20,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "The real body prose." in out+ assert "Introductory hero text." in out+ assert "# Title" in out+++def test_unclosed_link_in_unclosed_header_keeps_the_body():+ # The <a> adopts the body, so its text is not link furniture.+ body = "<main><header><h1>Title</h1><a href='/'>Home<p>%s</p>" % ("Article body text. " * 40)+ out = html_to_markdown(f"<body>{body}", main_content = True)+ assert "Article body text." in out+ assert "# Title" in out+++def test_unclosed_link_does_not_hand_the_scope_to_a_sibling_card():+ real = "<article><header><h1>Real</h1><a href='/'>Home<p>%s</p></article>" % ("REAL " * 60)+ card = "<article><p>%s</p></article>" % ("CARD " * 30)+ out = html_to_markdown(f"<body>{real}{card}</body>", main_content = True)+ assert "REAL" in out+ assert "CARD" not in out+++def test_entity_encoded_body_is_not_lost_to_an_unclosed_header():+ out = html_to_markdown(+ "<body><main><header><h1>T</h1><p>%s</p>" % ("α" * 400),+ main_content = True,+ )+ assert out.count("α") == 400+++def test_header_closed_by_an_ancestor_is_kept_whole():+ # Without a matching </header> the header may have adopted the body, so keep all.+ body = "<div><header><h1>Site</h1><ul>%s</ul></div><p>%s</p>" % (+ _interlanguage_list(300),+ "The real body prose. " * 20,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "The real body prose." in out+ assert "# Site" in out+ assert "Lang0" in out+++def test_unclosed_header_does_not_strip_a_short_article_it_adopted():+ body = "<main><header><h1>T</h1><ul>%s</ul><p>%s</p></main>" % (+ _interlanguage_list(300),+ "Short real article. " * 4,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Short real article." in out+++def test_heading_inside_a_nested_buffer_is_kept_and_the_links_still_go():+ # Teeing keeps the title without forcing the language list back in.+ body = (+ "<main><header><blockquote><h1>Page Title</h1></blockquote><ul>%s</ul></header><p>%s</p></main>"+ % (+ _interlanguage_list(400),+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Page Title" in out+ assert "Lang0" not in out+ assert out.index("Article body.") < 16000+++def test_long_hrefs_count_toward_the_header_size_floor():+ # Short labels, huge destinations: the rendered links are what displace it.+ nav = "".join('<a href="https://e.com/p?%s=%d">L%d</a>' % ("q" * 1000, i, i) for i in range(30))+ body = "<main><header>%s</header><p>%s</p></main>" % (nav, "Article body. " * 30)+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "L0" not in out+ assert out.index("Article body.") < 16000+++def test_linked_heading_does_not_condemn_the_byline_beside_it():+ body = (+ "<article><header><h1><a href='/p'>%s</a></h1><p>By Jane Doe, July 2026</p></header><p>%s</p></article>"+ % (+ "A Very Long Linked Headline About Assorted Things In The World Today " * 5,+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "By Jane Doe" in out+ assert "Very Long Linked" in out+++def test_anchor_without_href_is_prose_not_link_furniture():+ body = (+ "<article><header><h1>T</h1><a name='intro'>%s</a><p>Byline</p></header><p>%s</p></article>"+ % (+ "Introductory prose that renders as plain text. " * 8,+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Introductory prose" in out+ assert "Byline" in out+++def test_linked_heading_is_not_emitted_twice():+ body = (+ "<main><header><h1><a href='/post'>Title</a></h1><ul>%s</ul></header><p>%s</p></main>"+ % (+ _interlanguage_list(300),+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "# [Title](/post)" in out+ assert out.count("Title") == 1+++def test_article_still_beats_a_bigger_card_after_its_header_goes():+ # Dropped furniture is added back when ranking siblings, so a stripped header still wins.+ real = "<article><header><h1>Real</h1><ul>%s</ul></header><p>%s</p></article>" % (+ _interlanguage_list(300),+ "Short real body. " * 14,+ )+ card = "<article><p>%s</p></article>" % ("Related card teaser text here. " * 12)+ out = html_to_markdown(f"<body>{real}{card}</body>", main_content = True)+ assert "Short real body." in out+ assert "Related card teaser" not in out+++def test_furniture_only_card_does_not_suppress_the_main_it_sits_in():+ # Furniture ranks, never makes eligible: a nav-only header returned a 225 char astro.build card.+ card = "<article><header>%s</header><p>%s</p></article>" % (+ "".join('<a href="/l%d">Language %d</a>' % (i, i) for i in range(120)),+ "Short teaser about the related thing, read more.",+ )+ body = "<p>%s</p>" % ("The real article body the reader wants. " * 40)+ out = html_to_markdown(f"<body><main>{body}{card}</main></body>", main_content = True)+ assert "The real article body the reader wants." in out+ assert "Language 7" not in out+++def test_a_long_heading_href_does_not_condemn_the_rest_of_the_header():+ # The heading is kept anyway, so its size must not clear the floor for the metadata beside it.+ body = (+ "<article><header><h1><a href='/p?%s'>Title</a></h1>"+ "<a href='/author/jane'>Jane</a></header><p>%s</p></article>"+ % ("q" * 900, "Article body. " * 30)+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Title" in out+ assert "Jane" in out+++def test_a_preserved_heading_is_terminated():+ # The closing tag's blank line lands after the heading mark pops, so render must supply it.+ body = "<main><header><h1>Title</h1><ul>%s</ul></header>Article body text here.</main>" % (+ _interlanguage_list(300)+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "# TitleArticle" not in out+ assert out.startswith("# Title")+ assert "Article body text here." in out+++def test_scope_holding_only_furniture_does_not_win_or_blank_the_page():+ # Removed furniture must not make an empty candidate eligible, or the fetch returns nothing.+ body = "<main><header><ul>%s</ul></header></main><p>%s</p>" % (+ _interlanguage_list(300),+ "Real page body prose. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Real page body prose." in out+++def test_header_inside_an_enclosing_link_renders_once():+ body = "<main><a href='/x'><header><h1>T</h1></header></a><p>%s</p></main>" % (+ "Article body. " * 30+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert out.count("[# T](/x)") == 1+++def test_table_nested_in_a_header_inside_a_cell_keeps_its_columns():+ html = "<table><tr><td><header><table><tr><td>x</td></tr></table></header></td></tr></table>"+ assert html_to_markdown(f"<body>{html}</body>", main_content = True) == html_to_markdown(+ f"<body>{html}</body>"+ )+++def test_truncated_header_and_blockquote_keep_source_order():+ out = html_to_markdown("<body><main><header><h1>Title</h1><blockquote>Quote", main_content = True)+ assert out.index("Title") < out.index("Quote")+++# Headers interact with every buffer, so enumerate the grid: that is where the one-off bugs live.+_GRID_HEADINGS = {+ "h1": "<h1>Page Title</h1>",+ "aria": "<div role='heading'>Page Title</div>",+ "in_quote": "<blockquote><h1>Page Title</h1></blockquote>",+ "is_link": "<a role='heading' href='/t'>Page Title</a>",+ "none": "",+}+_GRID_WRAPPERS = {+ "bare": ("", ""),+ "quote": ("<blockquote>", "</blockquote>"),+ "cell": ("<table><tr><td>", "</td></tr></table>"),+ "link": ("<a href='/x'>", "</a>"),+ "item": ("<ul><li>", "</li></ul>"),+ "pre": ("<pre>", "</pre>"),+}+_GRID_NESTED = {+ "bare": ("", ""),+ "quote": ("<blockquote>", "</blockquote>"),+ "cell": ("<table><tr><td>", "</td></tr></table>"),+ "pre": ("<pre>", "</pre>"),+}+_GRID_BODY = "Article body sentence. " * 30++[email protected]("heading", sorted(_GRID_HEADINGS))[email protected]("wrapper", sorted(_GRID_WRAPPERS))[email protected]("nested", sorted(_GRID_NESTED))[email protected]("inner", ("link_dense", "content"))[email protected]("close_header", (True, False))[email protected]("close_nested", (True, False))+def test_header_survives_every_buffer_combination(+ heading, wrapper, nested, inner, close_header, close_nested+):+ open_wrap, close_wrap = _GRID_WRAPPERS[wrapper]+ open_nest, close_nest = _GRID_NESTED[nested]+ payload = (+ f"<ul>{_interlanguage_list(300)}</ul>"+ if inner == "link_dense"+ else "<p>By Jane Doe, 12 July 2026</p><p>A summary of the argument.</p>"+ )+ header = (+ f"<header>{_GRID_HEADINGS[heading]}{open_nest}{payload}"+ f"{close_nest if close_nested else ''}{'</header>' if close_header else ''}"+ )+ html = (+ f"<body><main>{open_wrap}{header}{close_wrap if close_header else ''}"+ f"<p>{_GRID_BODY}</p></main></body>"+ )+ out = html_to_markdown(html, main_content = True)+ # These hold for every shape, however malformed.+ assert "Article body sentence." in out, "body lost"+ assert out.strip(), "empty output"+ assert out.index("Article body sentence.") < 16000, "body pushed past the fetch cap"+ # The title holds only for closed markup with no <pre>: there a heading is verbatim text, and+ # unclosed shapes get best-effort recovery predating this pass.+ well_formed = close_header and close_nested and "pre" not in (wrapper, nested)+ if _GRID_HEADINGS[heading] and well_formed:+ assert out.count("Page Title") == 1, "title duplicated or lost"+++def test_a_stub_cannot_outrank_a_real_article_on_removed_navigation():+ # A long title alone is not substantive retained content.+ stub = "<article><header><h1>%s</h1><ul>%s</ul></header></article>" % (+ "A Long Title That Exceeds Fifty Characters Easily Here",+ _interlanguage_list(300),+ )+ real = "<article><p>%s</p></article>" % ("Genuine full article body text. " * 20)+ out = html_to_markdown(f"<body>{stub}{real}</body>", main_content = True)+ assert "Genuine full article body" in out+++def test_unclosed_link_in_a_closed_header_counts_as_furniture():+ # The </header> proves the anchor did not adopt the body.+ body = "<main><header><h1>T</h1><a href='/nav'>%s</header><p>%s</p></main>" % (+ "Navigation label text. " * 20,+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Navigation label text." not in out+ assert "Article body." in out+++def test_enclosing_anchor_text_counts_toward_header_density():+ body = "<main><a href='/nav'><header>%s</header></a><p>%s</p></main>" % (+ "".join(f"<span>Nav label {i}</span>" for i in range(40)),+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Nav label 0" not in out+ assert "Article body." in out+++def test_truncated_header_flushes_into_its_enclosing_buffer():+ # The header is inside the link/cell, so its text belongs there, in order.+ assert html_to_markdown(+ "<body><main><a href='/x'>before<header><h1>Title", main_content = True+ ).startswith("[before")+ assert html_to_markdown(+ "<body><main><table><tr><td><header><h1>Title", main_content = True+ ).startswith("|")+++def test_empty_blocks_do_not_inflate_the_header_size():+ # _cleanup collapses them, so the size threshold must see the cleaned form.+ body = (+ "<article><header><h1>%s</h1>%s<a href='/x'>L</a></header></article>"+ "<article><p>%s</p></article>"+ % (+ "A Fairly Long Heading Title Here" * 2,+ "<div></div>" * 500,+ "Genuine full article body text. " * 20,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Genuine full article body" in out+++def test_blockquoted_heading_is_not_counted_as_retained_prose():+ stub = "<article><blockquote><header><h1>%s</h1><ul>%s</ul></header></blockquote></article>" % (+ "A Long Title That Exceeds Fifty Characters Easily Here",+ _interlanguage_list(300),+ )+ real = "<article><p>%s</p></article>" % ("Genuine full article body text. " * 20)+ out = html_to_markdown(f"<body>{stub}{real}</body>", main_content = True)+ assert "Genuine full article body" in out+++def test_list_left_open_in_a_header_does_not_indent_the_body():+ body = "<main><header><h1>T</h1><ul>%s</header><ul><li>Body item one</li></ul></main>" % (+ _interlanguage_list(300)+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ item = next(line for line in out.split("\n") if "Body item one" in line)+ assert item.startswith("*"), item+++def test_deeply_nested_headers_do_not_blow_up_quadratically():+ # Header sizing must not rescan each parent's cumulative buffer.+ chunk = "<p>%s</p>" % ("filler text here. " * 100)++ def build(depth):+ return (+ "<body><main>"+ + "".join(f"<header>{chunk}" for _ in range(depth))+ + "</header>" * depth+ + "<p>body</p></main></body>"+ )++ import time++ timings = []+ for depth in (20, 80):+ html = build(depth)+ start = time.perf_counter()+ html_to_markdown(html, main_content = True)+ timings.append(time.perf_counter() - start)+ # Four times the depth and payload, nowhere near quadratic cost.+ assert timings[1] < timings[0] * 12, timings+++def test_linked_heading_text_is_counted_once_for_the_size_floor():+ body = (+ "<article><header><h1><a href='/p'>%s</a></h1>"+ "<a href='/author'>Jane</a></header><p>%s</p></article>"+ % ("Headline word " * 60, "Article body. " * 30)+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Jane" in out+++def test_fenced_code_counts_as_retained_content():+ # A leading # inside a fence is a comment, not a heading; scoring it as one loses this article.+ code = "<pre>%s</pre>" % "\n".join("# comment line %d" % i for i in range(16))+ article = "<article><header><h1>T</h1><ul>%s</ul></header>%s</article>" % (+ _interlanguage_list(300),+ code,+ )+ sibling = "<article><p>%s</p></article>" % ("Sibling teaser text here. " * 12)+ out = html_to_markdown(f"<body>{article}{sibling}</body>", main_content = True)+ assert "comment line 1" in out+ assert "Sibling teaser" not in out+++_FENCE = "`" * 3+++def test_dropped_furniture_cannot_dominate_sibling_ranking():+ # Credit must not decide the match: a teaser with a 1000 link header outranked five times its+ # own real text.+ teaser = "<article><header>%s</header><p>%s</p></article>" % (+ "".join('<a href="/l%d">Lang%d</a>' % (i, i) for i in range(1000)),+ "Teaser words here. " * 20,+ )+ real = "<article><p>%s</p></article>" % ("The genuine article body text goes here. " * 55)+ out = html_to_markdown(f"<body>{teaser}{real}</body>", main_content = True)+ assert "The genuine article body text goes here." in out+ assert "Teaser words here." not in out+++def test_literal_bracket_paren_is_prose_not_a_destination():+ # No [ opened it, so "](" is literal and the parens hold prose; skipping them scored 192 of 295.+ article = "<article><p>%s](%s) %s</p></article>" % (+ "Real article prose that the reader wants to see. " * 3,+ "y" * 100,+ "Tail prose to finish the paragraph off here.",+ )+ sibling = "<article><p>%s</p></article>" % ("Unrelated sibling teaser words. " * 8)+ out = html_to_markdown(f"<body>{article}{sibling}</body>", main_content = True)+ assert "Real article prose that the reader wants to see." in out+ assert "Unrelated sibling teaser" not in out+++def test_hand_preserved_heading_reaches_the_eligibility_tally():+ # The partial branch writes the title straight into heading_parts, so the gate needs telling+ # too or a title-only card reads as body prose.+ card = (+ '<article><header><a href="/h"><div role="heading">%s</div>%s</a><ul>%s</ul></header></article>'+ % (+ "Card Title Words " * 14,+ "nav text " * 40,+ _interlanguage_list(300),+ )+ )+ real = "<p>%s</p>" % ("The real page body text here. " * 30)+ out = html_to_markdown(f"<body><main>{real}{card}</main></body>", main_content = True)+ assert "The real page body text here." in out+++def test_pre_inside_a_table_cell_is_drained_before_the_row():+ # The row is emitted, so an open <pre> swallowed it into a fence as CODEMARKER| |.+ body = "<main><header><h1>T</h1><table><tr><td><pre>CODEMARKER</header><p>%s</p></main>" % (+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "CODEMARKER|" not in out+ assert "Article body." in out+++def test_post_processing_respects_the_widened_fence():+ # Both passes toggled on any ``` line, so the literal one closed the block and its code was+ # cleaned and de-boilerplated.+ code = "<pre>%s\nskip to content\n\nreal code line \nmore code</pre>" % _FENCE+ body = "<article>%s<p>%s</p></article>" % (code, "Body text here. " * 20)+ out = html_to_markdown(f"<body><main>{body}</main></body>", main_content = True)+ assert "skip to content" in out+ assert "skip to content\n\nreal code line" in out+ assert "real code line " in out+++def test_unbalanced_destination_keeps_scoring_the_rest_of_the_line():+ # /docs/(draft never balances, so it is not a link; the scan must keep the prose on that line.+ article = '<article><p><a href="/docs/(draft">Doc</a> %s</p></article>' % (+ "Substantial article prose continues here. " * 6,+ )+ sibling = "<article><p>%s</p></article>" % ("Sibling teaser text. " * 12)+ out = html_to_markdown(f"<body>{article}{sibling}</body>", main_content = True)+ assert "Substantial article prose continues here." in out+ assert "Sibling teaser" not in out+++def test_structural_headings_do_not_satisfy_the_eligibility_gate():+ # role="heading" renders as prose, so ATX reparsing missed it and a header-only card cleared+ # the gate on its title plus dropped-list credit.+ card = '<article><header><div role="heading">%s</div><ul>%s</ul></header></article>' % (+ "Card Title Words " * 14,+ _interlanguage_list(300),+ )+ real = "<article><p>%s</p></article>" % ("The real article body text here. " * 20)+ out = html_to_markdown(f"<body>{real}{card}</body>", main_content = True)+ assert "The real article body text here." in out+ assert "Card Title Words" not in out+++def test_anchor_wrapping_a_heading_preserves_only_the_heading():+ # <a><h1>Title</h1>...nav...</a> carries a title; teeing the whole anchor returned 14k of nav.+ bulk = " ".join("NavWord%04d" % i for i in range(1200))+ body = (+ '<main><header><a href="/home"><h1>Title</h1>%s</a><ul>%s</ul></header><p>%s</p></main>'+ % (+ bulk,+ _interlanguage_list(300),+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Title" in out+ assert "NavWord0000" not in out+ assert out.index("Article body.") < 16000+++def test_link_destination_scan_balances_parentheses():+ # A destination may hold parens, so stopping at the first ) scored the rest of the URL as prose.+ query = "utm_source=x&" * 25+ card = '<article><header>%s</header><p><a href="/card(foo)?%s">Read</a></p></article>' % (+ "".join('<a href="/l%d">Lang%d</a>' % (i, i) for i in range(120)),+ query,+ )+ real = "<article><p>%s</p></article>" % ("The genuine article body text here. " * 20)+ out = html_to_markdown(f"<body>{real}{card}</body>", main_content = True)+ assert "The genuine article body text here." in out+ assert "/card(foo)?" not in out+++def test_literal_fence_inside_pre_does_not_end_the_code_region():+ # A ``` line in the source is content; ending the fence there made the rest read as headings.+ code = "<pre>%s\n%s</pre>" % (+ _FENCE,+ "\n".join("# code line %d" % i for i in range(20)),+ )+ article = "<article><header><h1>T</h1><ul>%s</ul></header>%s</article>" % (+ _interlanguage_list(300),+ code,+ )+ sibling = "<article><p>%s</p></article>" % ("Sibling teaser text here. " * 12)+ out = html_to_markdown(f"<body>{article}{sibling}</body>", main_content = True)+ assert "code line 1" in out+ assert "Sibling teaser" not in out+++def test_heading_through_a_nested_buffer_is_emitted_once():+ # The title was teed entering the blockquote and again on flush, so it was kept twice.+ body = (+ '<main><header><div role="heading"><blockquote>UniqueTitle</blockquote></div><ul>%s</ul></header><p>%s</p></main>'+ % (+ _interlanguage_list(300),+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert out.count("UniqueTitle") == 1+++def test_late_code_end_tag_after_a_recovered_header_is_a_no_op():+ # </code> arrives after </header>; the frame already closed the span, so a second emit is odd.+ body = "<main><header><h1>T</h1><code>navcode<ul>%s</ul></header><p>%s</p></code></main>" % (+ _interlanguage_list(300),+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert out.count("`") % 2 == 0+ assert "Article body." in out+++def test_header_text_is_sized_after_whitespace_collapses():+ # The run collapses to one space, so counting it raw pushed a short byline over the floor.+ byline = '<a href="/a">Jane%sDoe</a><time>July 2026</time>' % (" " * 300)+ body = "<main><header><h1>T</h1>%s</header><p>%s</p></main>" % (+ byline,+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Jane Doe" in out+ assert "July 2026" in out+++def test_link_destinations_do_not_count_as_retained_prose():+ # A tracking URL is not prose: this card shows 4 visible chars but its destination scored 339.+ query = "utm_source=x&" * 25+ card = '<article><header>%s</header><p><a href="/card?%s">Read</a></p></article>' % (+ "".join('<a href="/l%d">Lang%d</a>' % (i, i) for i in range(120)),+ query,+ )+ real = "<article><p>%s</p></article>" % ("The genuine article body text here. " * 20)+ out = html_to_markdown(f"<body>{real}{card}</body>", main_content = True)+ assert "The genuine article body text here." in out+ assert "/card?" not in out+++def test_late_end_tag_cannot_replay_a_recovered_pre_block():+ # </header> arrives while <pre> is open, so the frame drains it; the later </pre> replayed it.+ body = "<main><header><h1>T</h1><ul>%s</ul><pre>%s</header><p>%s</p></pre></main>" % (+ _interlanguage_list(300),+ "NAVJUNK_MARKER\n" * 3,+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "NAVJUNK_MARKER" not in out+ assert out.index("Article body.") < 16000+++def test_aria_heading_accepts_a_fallback_role_token_list():+ # role is a token list authors use for fallbacks, so an exact match dropped the title.+ assert _is_aria_heading({"role": "heading"})+ assert _is_aria_heading({"role": "future-role heading"})+ assert _is_aria_heading({"role": "HEADING"})+ assert not _is_aria_heading({"role": "banner"})+ assert not _is_aria_heading({})+ body = (+ '<main><header><div role="future-role heading">Page Title</div><ul>%s</ul></header><p>%s</p></main>'+ % (+ _interlanguage_list(300),+ "Article body. " * 30,+ )+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Page Title" in out+ assert "Lang0" not in out+++ ("heading_markup", "marker"),+ [+ ("<h1>Page Title</h1>", "Page Title"),+ ("<table><tr><td><h1>Page Title</h1></td></tr></table>", "Page Title"),+ ("<div role='heading' aria-level='1'>Page Title</div>", "Page Title"),+ ("<a role='heading' href='/title'>Page Title</a>", "Page Title"),+ ("<a href='/post'><h1>Page Title</h1></a>", "Page Title"),+ ("<hgroup><h1>Title</h1><p>Subtitle here</p></hgroup>", "Subtitle here"),+ ],+)+def test_heading_survives_a_stripped_header(heading_markup, marker):+ # However the title is expressed, reducing a link-only header keeps it and nothing else.+ body = "<main><header>%s<ul>%s</ul></header><p>%s</p></main>" % (+ heading_markup,+ _interlanguage_list(300),+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert marker in out+ assert "Lang0" not in out+ assert "Article body." in out+++ "body_markup",+ [+ # The blockquote encloses the header, so its content belongs to the frame.+ "<main><blockquote><header><h1>T</h1><ul>{links}</ul></header></blockquote><p>{body}</p></main>",+ # </blockquote> omitted: the frame must claim the content before judging.+ "<main><header><h1>T</h1><blockquote><ul>{links}</ul></header><p>{body}</p></main>",+ # </td> omitted, same requirement through the cell buffer.+ "<main><header><h1>T</h1><table><tr><td><ul>{links}</ul></header><p>{body}</p></main>",+ ],+)+def test_link_list_is_stripped_through_a_nested_buffer(body_markup):+ body = body_markup.format(links = _interlanguage_list(300), body = "Article body. " * 30)+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert "Lang0" not in out+ assert out.index("Article body.") < 16000+++def test_hash_prefixed_prose_still_wins_its_scope():+ # Every line opens with a hash, so treating those as headings left the scope looking empty.+ lines = "".join("<p>#include <header_%02d.h></p>" % i for i in range(14))+ article = "<article><header><h1>T</h1><ul>%s</ul></header>%s</article>" % (+ _interlanguage_list(300),+ lines,+ )+ sibling = "<article><p>%s</p></article>" % ("Sibling teaser text here. " * 12)+ out = html_to_markdown(f"<body>{article}{sibling}</body>", main_content = True)+ assert "#include" in out+ assert "Sibling teaser" not in out+++def test_header_size_is_independent_of_the_buffer_it_renders_through():+ # Text counted entering a nested buffer AND on flush doubled it, so links stripped once quoted.+ links = "".join(+ '<a href="/very/long/section/path/number/%03d/index">L%03d</a>' % (i, i) for i in range(14)+ )+ wrapped = {+ "bare": links,+ "blockquote": f"<blockquote>{links}</blockquote>",+ "cell": f"<table><tr><td>{links}</td></tr></table>",+ }+ kept = set()+ for inner in wrapped.values():+ body = "<main><header><h1>T</h1>%s</header><p>%s</p></main>" % (+ inner,+ "Article body. " * 30,+ )+ kept.add("L000" in html_to_markdown(f"<body>{body}</body>", main_content = True))+ assert len(kept) == 1+++def test_nested_inline_code_closes_every_span_it_opened():+ # Two <code> elements owe two backticks; as a flag the first </code> answered for both.+ body = "<main><article><p><code><code>x</code></code></p><p>%s</p></article></main>" % (+ "Body text here. " * 20,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert out.count("`") % 2 == 0+ assert "``x``" in out+++def test_header_inside_open_inline_code_leaves_delimiters_paired():+ # The <code> opened outside the header, so closing it in the frame left </code> unpaired.+ body = "<main><code>head<header><h1>T</h1></header>tail</code><p>%s</p></main>" % (+ "Article body. " * 30,+ )+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)+ assert out.count("`") % 2 == 0+ assert "`head`" not in out+ assert "Article body." in out+++def test_nested_blockquote_prose_does_not_backtrack():+ # Heading detection must scan linearly: a regex backtracks exponentially on "> > > ... prose".+ import time++ html = (+ "<body><main>"+ + "<blockquote>" * 40+ + "<p>prose text here</p>"+ + "</blockquote>" * 40+ + "</main></body>"+ )+ start = time.perf_counter()+ html_to_markdown(html, main_content = True)+ assert time.perf_counter() - start < 1.0+++def test_deeply_nested_tags_stay_linear():+ # _close_implicit must not rescan the whole open-tag stack per start tag.+ import time++ def build(count):+ return (+ "<body><main>"+ + "<header><h1>T</h1>" * count+ + "</header>" * count+ + "<p>body</p></main></body>"+ )++ timings = []+ for count in (1000, 4000):+ start = time.perf_counter()+ html_to_markdown(build(count), main_content = True)+ timings.append(time.perf_counter() - start)+ # Four times the tags, well under sixteen times the work.+ assert timings[1] < timings[0] * 12, timings