Skip to content

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.

[CS146S Stanford] Studio web fetch: a bare & stays as written, and escaped code stays in its code block (#17200)

Mrityunjay Kumar025f8bb1d54b
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.py
index dac2fa35a22..57fd900d772 100644
--- a/studio/backend/core/inference/_html_to_md.py
+++ b/studio/backend/core/inference/_html_to_md.py
@@ -5,7 +5,6 @@
from __future__ import annotations
-import html
import itertools
import operator
import re
@@ -353,6 +352,11 @@ _INLINE_EMPHASIS = {"strong": "**", "b": "**", "em": "*", "i": "*"}
_BLANK_LINE_RUN = re.compile(r"\n\n\n+")
_WHITESPACE_RUN = re.compile(r"\s+")
+# browsers collapse only ASCII whitespace, so text indented with   or   keeps its indent
+_COLLAPSIBLE_RUN = re.compile(r"[ \t\n\r\f]+")
+# a space run holding a kept Unicode space; the lookbehind starts it only at a run's first char, keeping it linear
+_KEPT_SPACE_RUN = re.compile(r"(?<![^\S\n])[ \t\r\f\v]*[^\S \t\n\r\f\v][^\S\n]*")
+_KEPT_SPACE = re.compile(r"[^\S \t\n\r\f\v]")
# citation lists after words use commas or en dashes; hyphens, minuses, and thousands stay exponents
_CITATION_LIST = re.compile(r"\d+(?:\s*[–,]\s*\d+)+")
_THOUSANDS = re.compile(r"\d{1,3}(?:,\d{3})+")
@@ -829,7 +833,8 @@ class _MarkdownRenderer(HTMLParser):
site_links: SiteLinks | None = None,
page_span_limit: int | None = None,
):
- super().__init__(convert_charrefs = False)
+ # charrefs must decode inside their text run: decoded apart, they left <pre> and gained a stray ';' (#17199)
+ super().__init__(convert_charrefs = True)
self._record: list | None = None
# parser positions of buttons that carry their heading title, found by _TitleButtonScan
self.title_buttons: frozenset[tuple[int, int]] = frozenset()
@@ -960,6 +965,8 @@ class _MarkdownRenderer(HTMLParser):
if frame is not None and self._site_links is not None
else text
)
+ if frame is not None:
+ measured = _fold_kept_spaces(measured)
if frame is not None and as_heading:
frame.heading_parts.append(text)
frame.heading_chars += len(measured.strip())
@@ -1384,6 +1391,8 @@ class _MarkdownRenderer(HTMLParser):
if not self._header_stack or self._heading_marks:
return
frame = self._header_stack[-1]
+ if not text.isascii():
+ text = _WHITESPACE_RUN.sub(" ", text)
chars = len(text.strip())
frame.text_chars += chars
# anchors without usable hrefs render as prose
@@ -2025,40 +2034,23 @@ class _MarkdownRenderer(HTMLParser):
self._count_header_text(data)
self._emit(data)
return
- # Collapse all whitespace (including newlines) per HTML rules.
- text = _WHITESPACE_RUN.sub(" ", data)
+ # Collapse ASCII whitespace (including newlines) per HTML rules.
+ text = _COLLAPSIBLE_RUN.sub(" ", data)
# Count after collapsing: raw spaces in a link inflated it past the floor.
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():
+ # Drop whitespace-only nodes between table elements, except a caption's &nbsp; (Javadoc tab separators).
+ if (
+ self._in_table
+ and not self._in_cell
+ and not text.strip()
+ and not (self._open_at.get("caption") and not text.isascii())
+ ):
return
# Source indentation between <li> and its first block must not end the marker line.
if self._li_marker_pending and not text.strip():
return
self._emit(text)
- def handle_entityref(self, name: str) -> None:
- if self._record is not None:
- self._record.append((3, name))
- text = html.unescape(f"&{name};")
- if self._title_scan is not None:
- self._title_scan.data(text)
- if self._text_suppressed():
- return
- self._count_header_text(text)
- self._emit(text)
-
- def handle_charref(self, name: str) -> None:
- if self._record is not None:
- self._record.append((4, name))
- text = html.unescape(f"&#{name};")
- if self._title_scan is not None:
- self._title_scan.data(text)
- if self._text_suppressed():
- return
- self._count_header_text(text)
- self._emit(text)
-
def replay(self, events: list) -> None:
"""Re-run recorded handler calls in order, restoring ``getpos()`` at each start tag."""
start, end, data = self.handle_starttag, self.handle_endtag, self.handle_data
@@ -2068,12 +2060,8 @@ class _MarkdownRenderer(HTMLParser):
elif kind == 0:
tag, attrs, self.lineno, self.offset = arg
start(tag, list(attrs))
- elif kind == 1:
- end(arg)
- elif kind == 3:
- self.handle_entityref(arg)
else:
- self.handle_charref(arg)
+ end(arg)
def flush_pending(self) -> None:
"""Flush open side-buffers into ``_out`` after close(), recovering truncated HTML."""
@@ -2219,8 +2207,8 @@ def _strip_boilerplate_lines(text: str, site_links: SiteLinks | None = None) ->
class _TokenLog:
"""Handler calls of one document, recorded by the first fed pass and replayed by later ones.
- Sound only while the renderer overrides just these five handlers and reads parser state only
- via ``getpos()`` in ``handle_starttag``."""
+ Sound only while the renderer overrides just ``handle_starttag``, ``handle_endtag`` and
+ ``handle_data`` and reads parser state only via ``getpos()`` in ``handle_starttag``."""
__slots__ = ("events", "armed")
@@ -2332,6 +2320,7 @@ def _select_main_scope_render(
)
if site_links is not None:
scored = site_links.clean(scored)
+ scored = _fold_kept_spaces(scored)
visible = _visible_chars(scored)
prose = visible - scoring.scope_heading_prose[i]
if prose < _MIN_MAIN_CONTENT_CHARS:
@@ -2379,8 +2368,17 @@ def _render_main_document(
return _visible_chars(scored), rendered
+def _fold_kept_spaces(text: str) -> str:
+ """Scoring view of *text*: a space run holding U+00A0 or another kept Unicode space is layout
+ padding, so it counts as one space, while pure ASCII runs (code indentation) stay as rendered."""
+ if text.isascii() or not _KEPT_SPACE.search(text):
+ return text
+ return _KEPT_SPACE_RUN.sub(" ", text)
+
+
def _visible_chars(text: str) -> int:
"""count visible nonblank characters without link targets; callers subtract tracked heading prose."""
+ text = _fold_kept_spaces(text)
return sum(_visible_len(line) for line in text.split("\n") if line.strip())
@@ -2471,6 +2469,16 @@ _ARTICLE_START = re.compile(r"<article", re.IGNORECASE)
_MAIN_START = re.compile(r"<main", re.IGNORECASE)
# absent text = no generated span cells, so a pass needs no span-free scoring re-render
_SPAN_ATTR = re.compile(r"(?:col|row)span", re.IGNORECASE)
+# html.unescape raises once a decimal reference has more digits, leading zeros included, than
+# int()'s limit, which Python never sets below 640
+_LONG_DECIMAL_REF = re.compile(r"&#([0-9]{641,})")
+
+
+def _short_decimal_ref(match: re.Match[str]) -> str:
+ """The reference without its leading zeros, or &#65533 (U+FFFD, what html.unescape gives past
+ U+10FFFF) when 8 or more digits remain."""
+ digits = match.group(1).lstrip("0") or "0"
+ return "&#" + (digits if len(digits) < 8 else "65533")
def html_to_markdown(
@@ -2482,6 +2490,7 @@ def html_to_markdown(
) -> str:
"""convert HTML to Markdown; main_content prefers a dominant article or main subtree, site_links records same-site links without changing output, and max_span_chars limits generated table cells."""
source_html = source_html.replace("\r\n", "\n").replace("\r", "\n")
+ source_html = _LONG_DECIMAL_REF.sub(_short_decimal_ref, source_html)
span_limit = 2 * len(source_html)
if max_span_chars is not None:
span_limit = min(span_limit, max_span_chars)
diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.py
index 4c351075025..5f276a14b06 100644
--- a/studio/backend/tests/test_web_fetch_extraction.py
+++ b/studio/backend/tests/test_web_fetch_extraction.py
@@ -1525,6 +1525,178 @@ def test_fetched_page_keeps_exponents_beside_footnotes(monkeypatch):
assert "1.898×10^27 kg[[12]](#cite_note-12) and a surface area of 6.1419×10^10 km^2." in out
+ "markup, expected",
+ [
+ ("<p>R&D and Q&A at AT&T.</p>", "R&D and Q&A at AT&T."),
+ # &format is no reference and &lang is one only with its ";", so both stay as written
+ (
+ "<p>See https://example.com/v1?key=abc&format=json&lang=en for details.</p>",
+ "See https://example.com/v1?key=abc&format=json&lang=en for details.",
+ ),
+ (
+ "<pre>curl 'https://example.com/v1?api=1&map_action=map&b=2'</pre>",
+ "```\ncurl 'https://example.com/v1?api=1&map_action=map&b=2'\n```",
+ ),
+ ],
+)
[email protected]("main_content", [False, True])
+def test_a_bare_ampersand_stays_as_written(markup, expected, main_content):
+ assert html_to_markdown(markup, main_content = main_content) == expected
+
+
+ "markup, expected",
+ [
+ # a decimal reference may drop its ";", even before a letter a-f
+ (
+ "<p>&#169Copyright 2026</p><h2>Next</h2><p>More &amp; text.</p>",
+ "©Copyright 2026\n\n## Next\n\nMore & text.",
+ ),
+ # "&#" without digits is text, with or without a ";" later in the page
+ (
+ "<p>Use &# here</p><h2>Next</h2><p>More text.</p>",
+ "Use &# here\n\n## Next\n\nMore text.",
+ ),
+ (
+ "<p>C&#; and C&#x; typos</p><h2>Next</h2><p>More text.</p>",
+ "C&#; and C&#x; typos\n\n## Next\n\nMore text.",
+ ),
+ ],
+)
[email protected]("main_content", [False, True])
+def test_a_malformed_numeric_reference_keeps_the_rest_of_the_page(markup, expected, main_content):
+ assert html_to_markdown(markup, main_content = main_content) == expected
+
+
[email protected]("main_content", [False, True])
+def test_references_decode_as_a_browser_shows_them(main_content):
+ # legacy names such as &amp and &not decode without their ";" in text
+ html = "<p>&lt;b&gt; &amp; &copy; &#65;&#x42; &amp x &notit; &foo;</p>"
+ assert html_to_markdown(html, main_content = main_content) == "<b> & © AB & x ¬it; &foo;"
+
+
+ "markup, expected",
+ [
+ # &nbsp; and a literal U+00A0 are both kept, as a browser keeps them
+ ("<p>10&nbsp;GB and 10\xa0GB</p>", "10\xa0GB and 10\xa0GB"),
+ ("<div>for x in y:<br>&nbsp;&nbsp;print(x)</div>", "for x in y:\n\xa0\xa0print(x)"),
+ ("<div>if x:<br>&emsp;&emsp;print(x)</div>", "if x:\n\u2003\u2003print(x)"),
+ ],
+)
[email protected]("main_content", [False, True])
+def test_no_break_spaces_are_kept(markup, expected, main_content):
+ assert html_to_markdown(markup, main_content = main_content) == expected
+
+
[email protected]("tag", ["span", "code", "pre"])
[email protected]("nbsp", ["&nbsp;", "\xa0", "&nbsp; "])
+def test_kept_no_break_spaces_do_not_dilute_a_link_header(nbsp, tag):
+ links = "".join(f'<a href="/s{i}">Section {i}</a> ' for i in range(20))
+ prose = "Article prose. " * 20
+ html = (
+ f"<article><header>{links}<{tag}>Menu{nbsp * 10}x</{tag}></header><p>{prose}</p></article>"
+ )
+ assert html_to_markdown(html, main_content = True) == prose.strip()
+
+
[email protected]("sep", ["&nbsp;", "&emsp;"])
[email protected]("main_content", [False, True])
+def test_a_caption_keeps_the_no_break_spaces_between_its_tabs(main_content, sep):
+ # Javadoc 8 method summary: the caption's tabs are separated only by &nbsp;
+ html = (
+ f'<table><caption><span>All Methods</span><span class="tabEnd">{sep}</span>'
+ f'<span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">{sep}</span>'
+ "</caption><tr><th>Modifier</th><th>Method</th></tr><tr><td>a</td><td>b</td></tr></table>"
+ )
+ out = html_to_markdown(html, main_content = main_content)
+ kept = {"&nbsp;": "\xa0", "&emsp;": "\u2003"}[sep]
+ assert out.startswith(
+ f"All Methods{kept}[Static Methods](javascript:show(1);){kept}| Modifier |"
+ )
+
+
[email protected]("nbsp", ["&nbsp;", "\xa0", "&nbsp; ", "&emsp;"])
+def test_no_break_space_padding_does_not_make_a_stub_the_main_content(nbsp):
+ body = "Body prose that the page is about. " * 20
+ html = f"<main><article><p>a{nbsp * 220}b</p></article><p>{body}</p></main>"
+ assert body.strip() in html_to_markdown(html, main_content = True)
+
+
+def test_no_break_space_padding_in_a_stripped_header_does_not_outrank_a_longer_article():
+ links = "".join(f'<a href="/s{i}">Section {i}</a> ' for i in range(20))
+ body = "Actual article body. " * 48
+ html = (
+ f'<article><header>{links}<span>Menu{"&nbsp;" * 200}x</span></header>'
+ f"<p>{'Teaser prose. ' * 40}</p></article><article><p>{body}</p></article>"
+ )
+ assert body.strip() in html_to_markdown(html, main_content = True)
+
+
+def test_no_break_space_padding_does_not_make_a_byline_header_navigation():
+ title = (
+ "Practical techniques for building reliable Python applications "
+ "and deploying them with confidence in production"
+ )
+ html = (
+ f'<article><header><a href="/read?token={"x" * 650}">{title}</a>'
+ f'<p>by{"&nbsp;" * 20}Ann</p></header>'
+ f'<p>{"This is the main article body. " * 30}</p></article>'
+ )
+ assert title in html_to_markdown(html, main_content = True)
+
+
+def test_no_break_space_padding_does_not_outrank_a_longer_article():
+ teaser = "Teaser " + "&nbsp;" * 3000 + " ".join(["teaser words"] * 20)
+ body = "Body prose that the page is about. " * 60
+ html = f"<article><p>{teaser}</p></article><article><p>{body}</p></article>"
+ assert body.strip() in html_to_markdown(html, main_content = True)
+
+
[email protected]("main_content", [False, True])
+def test_a_decimal_reference_past_the_int_digit_limit_still_renders(main_content):
+ ones, zeros = "1" * 5000, "0" * 5000
+ html = (
+ f'<p><a href="/x?q=&#{ones};">[&#{zeros}65;] [&#{ones};] [&#{ones}a]</a></p>'
+ f"<p>[&#{ones}"
+ )
+ out = html_to_markdown(html, main_content = main_content)
+ assert out == "[[A] [\ufffd] [\ufffda]](/x?q=\ufffd)\n\n[\ufffd"
+
+
+ "markup, expected",
+ [
+ # Pygments 2.21 HtmlFormatter(linenos="table"): each <pre> sits in a table cell.
+ (
+ '<div class="highlight"><table class="highlighttable"><tr><td class="linenos">'
+ '<div class="linenodiv"><pre><span class="normal">1</span>\n'
+ '<span class="normal">2</span></pre></div></td><td class="code"><div><pre><span></span>'
+ '<span class="k">if</span> <span class="n">a</span> <span class="o">&lt;</span> '
+ '<span class="n">b</span> <span class="ow">and</span> <span class="n">c</span> '
+ '<span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>\n'
+ ' <span class="nb">print</span><span class="p">(</span>'
+ '<span class="s2">"a &amp; b"</span><span class="p">)</span>\n'
+ "</pre></div></td></tr></table></div>\n",
+ '| ``` 1 2 ``` | ``` if a < b and c > 0: print("a & b") ``` |\n| --- | --- |',
+ ),
+ # an RFC section link inside a <pre> keeps its &nbsp;
+ (
+ '<pre>in <a href="./rfc5741#section-2">Section&nbsp;2 of RFC 5741</a>.</pre>',
+ "```\nin Section\xa02 of RFC 5741.\n```",
+ ),
+ (
+ '<pre>fn new() -&gt; <a href="/std/vec">Vec&lt;T&gt;</a></pre>',
+ "```\nfn new() -> Vec<T>\n```",
+ ),
+ ],
+)
[email protected]("main_content", [False, True])
+def test_escaped_code_stays_inside_its_code_block(markup, expected, main_content):
+ assert html_to_markdown(markup, main_content = main_content) == expected
+
+
def test_page_cut_by_the_room_left_drops_its_site_link_urls(monkeypatch):
from core.inference import tools