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: cheaper per-token work in web page Markdown extraction (#16286)
Daniel Handc75b66c9fe8
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.pyindex 621db3f6296..f768e7b09e4 100644--- a/studio/backend/core/inference/_html_to_md.py+++ b/studio/backend/core/inference/_html_to_md.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport htmlimport itertools+import operatorimport reimport secretsimport unicodedata@@ -77,9 +78,11 @@ def _is_hidden_element(attr_dict: dict) -> bool:"""Any present hidden attribute counts, even hidden=false, since presence means not rendered; aria-hidden=true and inline hiding styles count too"""if "hidden" in attr_dict:return True- if (attr_dict.get("aria-hidden") or "").strip().lower() == "true":+ aria_hidden = attr_dict.get("aria-hidden")+ if aria_hidden and aria_hidden.strip().lower() == "true":return True- return _style_hides_element(attr_dict.get("style") or "")+ style = attr_dict.get("style")+ return bool(style) and _style_hides_element(style)def _span_attr(attr_dict: dict, name: str) -> int:@@ -92,7 +95,8 @@ def _span_attr(attr_dict: dict, name: str) -> int:def _is_aria_heading(attr_dict: dict) -> bool:"""Any role token counts: WAI-ARIA's first-token rule needs the full role table, so match loosely."""- return "heading" in (attr_dict.get("role") or "").lower().split()+ role = attr_dict.get("role")+ return bool(role) and "heading" in role.lower().split()# HTML5 optional end tags: a listed start tag implicitly closes an open element of the key type, else an unclosed p hidden swallows later siblings@@ -150,6 +154,19 @@ _IMPLICIT_CLOSERS: dict = {"option": frozenset({"option", "optgroup"}),"optgroup": frozenset({"optgroup"}),}+# a start tag outside every closer set can close nothing, so implicit-close recovery skips its scan+_ANY_IMPLICIT_CLOSER = frozenset().union(*_IMPLICIT_CLOSERS.values())+++def _innermost_index(stack: list, tag: str) -> int:+ """Index of the last ``tag`` in ``stack``, else -1; searches backward from the top without copying."""+ last = len(stack) - 1+ if last >= 0 and stack[last] == tag:+ return last+ try:+ return last - operator.indexOf(reversed(stack), tag)+ except ValueError:+ return -1# A nested container makes an inner item a descendant, so recovery must stop there.@@ -335,6 +352,7 @@ _MIN_SCOPE_SPAN_CHARS = 256_INLINE_EMPHASIS = {"strong": "**", "b": "**", "em": "*", "i": "*"}_BLANK_LINE_RUN = re.compile(r"\n\n\n+")+_WHITESPACE_RUN = re.compile(r"\s+")# 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})+")@@ -661,22 +679,34 @@ class _TitleButtonScan:# per open heading: [open-tag index, candidate position or None, candidate has text, _text_seq at open]self._headings: list[list] = []- def starttag(self, tag: str, attrs: list[tuple[str, str | None]], pos: tuple[int, int]) -> None:- attr_dict = dict(attrs)- self._prepare_foreign_html_start(tag, attr_dict)- self._close_implicit(tag)+ def starttag(+ self, tag: str, attr_dict: dict, pos: tuple[int, int], hidden: bool, aria_heading: bool+ ) -> None:+ """``hidden`` / ``aria_heading`` are the renderer's ``_is_hidden_element`` / ``_is_aria_heading`` results."""+ namespaces = self._namespaces+ if namespaces and namespaces[-1] != "html":+ self._prepare_foreign_html_start(tag, attr_dict)+ if self._closable_open and tag in _ANY_IMPLICIT_CLOSER:+ self._close_implicit(tag)if tag in _VOID_TAGS:return- namespace = self._next_namespace(tag)+ # _next_namespace's HTML-parent branch, inlined; an HTML element is never an integration point+ if not namespaces or namespaces[-1] == "html":+ namespace = "svg" if tag == "svg" else "math" if tag == "math" else "html"+ else:+ namespace = self._next_namespace(tag)+ integration = namespace != "html" and self._is_html_integration_point(+ tag, namespace, attr_dict+ )self._open.append(tag)- self._namespaces.append(namespace)- self._html_integration.append(self._is_html_integration_point(tag, namespace, attr_dict))+ namespaces.append(namespace)+ self._html_integration.append(integration)if tag in _IMPLICIT_CLOSERS:self._closable_open += 1index = len(self._open) - 1- if _is_hidden_element(attr_dict) or (tag in _SKIP_TAGS and tag != "button"):+ if hidden or (tag in _SKIP_TAGS and tag != "button"):self._muted.append(index)- if tag in _HEADING_TAGS or _is_aria_heading(attr_dict):+ if tag in _HEADING_TAGS or aria_heading:self._headings.append([index, None, False, self._text_seq])elif tag == "button" and self._button_at is None:self._button_at = index@@ -686,10 +716,9 @@ class _TitleButtonScan:self._button_frame = framedef endtag(self, tag: str) -> None:- for i in range(len(self._open) - 1, -1, -1):- if self._open[i] == tag:- self._pop_to(i)- return+ i = _innermost_index(self._open, tag)+ if i >= 0:+ self._pop_to(i)def data(self, data: str) -> None:if self._muted or not data.strip():@@ -763,8 +792,10 @@ class _TitleButtonScan:self._button_frame = Nonewhile self._muted and self._muted[-1] >= i:self._muted.pop()- self._close_headings(i)- self._closable_open -= sum(1 for name in self._open[i:] if name in _IMPLICIT_CLOSERS)+ if self._headings and self._headings[-1][0] >= i:+ self._close_headings(i)+ if self._closable_open:+ self._closable_open -= sum(1 for name in self._open[i:] if name in _IMPLICIT_CLOSERS)del self._open[i:]del self._namespaces[i:]del self._html_integration[i:]@@ -911,6 +942,10 @@ class _MarkdownRenderer(HTMLParser):if text:self._li_marker_pending = Falseframe = self._header_stack[-1] if self._header_stack else None+ # outside header frames and headings no tee or tally below applies: only the routing does+ if frame is None and not self._heading_marks and not self._emit_as_heading:+ self._emit_target().append(text)+ return# Tee wherever text routes; a link inside the frame arrives twice, so tee only its formatted formin_nested_link = (self._in_link and self._link_seq != frame.outer_link_seq if frame else False@@ -919,7 +954,12 @@ class _MarkdownRenderer(HTMLParser):as_heading = (self._heading_marks and not in_nested_link and not self._replaying) or self._emit_as_heading- measured = self._site_links.clean(text) if self._site_links is not None else text+ # clean() is pure and only a header frame reads measured+ measured = (+ self._site_links.clean(text)+ if frame is not None and self._site_links is not None+ else text+ )if frame is not None and as_heading:frame.heading_parts.append(text)frame.heading_chars += len(measured.strip())@@ -1261,7 +1301,7 @@ class _MarkdownRenderer(HTMLParser):def _close_implicit(self, tag: str) -> None:"""Recovery stops at _CLOSE_BARRIERS containers so an outer item hidden content cannot leak; runs even for skipped nav and footer, which also close p"""- if not self._closable_open:+ if not self._closable_open or tag not in _ANY_IMPLICIT_CLOSER:returnbarriers = _IMPLICIT_CLOSE_BARRIERS.get(tag, frozenset())while True:@@ -1407,17 +1447,29 @@ class _MarkdownRenderer(HTMLParser):self._skip_html_at.clear()self._skip_html_integration.clear()- def _enter_tag(self, tag: str, attr_dict: dict) -> bool:- """track tag state; run ``_close_implicit`` first so skipped tags trigger recovery."""+ def _enter_tag(+ self,+ tag: str,+ attr_dict: dict,+ hidden: bool | None = None,+ aria_heading: bool | None = None,+ ) -> bool:+ """track tag state; run ``_close_implicit`` first so skipped tags trigger recovery; None checks are computed here."""+ if hidden is None:+ hidden = _is_hidden_element(attr_dict)if tag not in _VOID_TAGS:if tag in _INDEXED_OPEN_TAGS:self._open_at.setdefault(tag, []).append(len(self._open_tags))self._open_tags.append(tag)if tag in _IMPLICIT_CLOSERS:self._closable_open += 1- if _is_hidden_element(attr_dict):+ if hidden:self._hidden_marks.append(len(self._open_tags) - 1)- if tag in _HEADING_TAGS or tag == "hgroup" or _is_aria_heading(attr_dict):+ if (+ tag in _HEADING_TAGS+ or tag == "hgroup"+ or (_is_aria_heading(attr_dict) if aria_heading is None else aria_heading)+ ):self._heading_marks.append(len(self._open_tags) - 1)if self._in_link:self._link_had_heading = True@@ -1439,7 +1491,7 @@ class _MarkdownRenderer(HTMLParser):self._table_depth(),))- elif _is_hidden_element(attr_dict):+ elif hidden:return Falseif self._scope_tags is not None and tag in self._scope_tags:self._flush_header_frames()@@ -1470,16 +1522,16 @@ class _MarkdownRenderer(HTMLParser):# Flush the heading here while the tee still recognises it; it emits only after its mark popsif self._in_link and tag == "a" and self._heading_marks:self._finish_link()- if tag not in _VOID_TAGS:- for i in range(len(self._open_tags) - 1, -1, -1):- if self._open_tags[i] == tag:- 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")- break+ i = -1 if tag in _VOID_TAGS else _innermost_index(self._open_tags, tag)+ if i >= 0:+ 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()+ # _close_header_frames' own loop test+ if self._header_stack and self._header_stack[-1].depth >= i:+ self._close_header_frames(i, own_tag = tag == "header")if 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:@@ -1569,10 +1621,15 @@ class _MarkdownRenderer(HTMLParser):def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:if self._record is not None:- self._record.append((0, (tag, tuple(attrs), *self.getpos())))+ # HTMLParser builds a fresh attrs list per tag and nothing here mutates it, so it is kept uncopied+ self._record.append((0, (tag, attrs, self.lineno, self.offset)))tag = tag.lower()+ attr_dict = dict(attrs)+ hidden = aria_heading = Noneif self._title_scan is not None:- self._title_scan.starttag(tag, attrs, self.getpos())+ hidden = bool(attr_dict) and _is_hidden_element(attr_dict)+ aria_heading = bool(attr_dict) and _is_aria_heading(attr_dict)+ self._title_scan.starttag(tag, attr_dict, self.getpos(), hidden, aria_heading)title_button = (tag == "button" and bool(self.title_buttons) and self.getpos() in self.title_buttons)@@ -1580,7 +1637,9 @@ class _MarkdownRenderer(HTMLParser):button = self._last_skip_position("button", "html")if button >= 0 and self._skip_target_in_scope(tag, button):self._truncate_skip_tags(button)- self._prepare_foreign_html_start(tag, attrs)+ # each _prepare_* / _close_implicit call below is guarded by that helper's own early-return test+ if self._skip_tags and self._skip_namespaces[-1] != "html":+ self._prepare_foreign_html_start(tag, attrs)if tag in _TABLE_ONLY_START_TAGS and not self._in_table:returnif tag == "table" and self._prepare_sibling_table_start():@@ -1594,7 +1653,6 @@ class _MarkdownRenderer(HTMLParser):if self._skip_tags:if tag not in _VOID_TAGS:- attr_dict = dict(attrs)namespace = self._skipped_tag_namespace(tag)template = self._last_skip_position("template", "html")if tag == "form" and namespace == "html" and template < 0:@@ -1617,9 +1675,12 @@ class _MarkdownRenderer(HTMLParser):return# close optional tags before skipping so skipped <nav>/<footer> releases an open <p> marker- self._close_implicit(tag)- self._prepare_heading_start(tag)- self._prepare_table_start(tag)+ if self._closable_open and tag in _ANY_IMPLICIT_CLOSER:+ self._close_implicit(tag)+ if tag in _HEADING_TAGS:+ self._prepare_heading_start(tag)+ if self._in_table:+ self._prepare_table_start(tag)if tag in _SKIP_TAGS and not (title_button and self._heading_marks):self._skip_tags.append(tag)@@ -1629,14 +1690,13 @@ class _MarkdownRenderer(HTMLParser):self._skip_namespaces = [namespace]self._skip_html_at = [0] if namespace == "html" else []self._skip_html_integration = [- self._is_html_integration_point(tag, namespace, dict(attrs))+ self._is_html_integration_point(tag, namespace, attr_dict)]return- attr_dict = dict(attrs)if tag == "form":self._form_pointer = True- if not self._enter_tag(tag, attr_dict):+ if not self._enter_tag(tag, attr_dict, hidden, aria_heading):returnif tag in _HEADING_TAGS:@@ -1957,7 +2017,7 @@ class _MarkdownRenderer(HTMLParser):self._record.append((2, data))if self._title_scan is not None:self._title_scan.data(data)- if self._text_suppressed():+ if self._skip_tags or self._hidden_marks or self._text_suppressed():returnif self._in_pre:self._count_header_text(data)@@ -1969,7 +2029,7 @@ class _MarkdownRenderer(HTMLParser):self._emit(data)return# Collapse all whitespace (including newlines) per HTML rules.- text = re.sub(r"\s+", " ", data)+ text = _WHITESPACE_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).diff --git a/studio/backend/tests/test_html_to_md_fast_paths.py b/studio/backend/tests/test_html_to_md_fast_paths.pynew file mode 100644index 00000000000..7ed090f5781--- /dev/null+++ b/studio/backend/tests/test_html_to_md_fast_paths.py@@ -0,0 +1,186 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Fast paths in html_to_markdown's renderer and title-button scan (shared attribute checks, guarded+helper calls, C-speed open-tag lookups) must render exactly what the plain per-token code did.+Expected strings were produced by the converter before those fast paths."""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++import core.inference._html_to_md as h2m+from core.inference._html_to_md import SiteLinks, html_to_markdown++_PROSE = " ".join(+ f"Sentence {i} of the body text, long enough to count as prose." for i in range(6)+)++# name: (html, main_content Markdown with site links, its stripped form, whole-page Markdown)+CASES = {+ "aria_heading_title_button": (+ "<main><div role='presentation Heading'><button>Is it fast?</button></div><p>"+ + _PROSE+ + "</p><h3 aria-hidden=' TRUE '><button>Hidden</button></h3><h4><button>Kept title</button></h4><p>"+ + _PROSE+ + "</p></main>",+ "Is it fast?\n\n" + _PROSE + "\n\n#### Kept title\n\n" + _PROSE + "",+ "Is it fast?\n\n" + _PROSE + "\n\n#### Kept title\n\n" + _PROSE + "",+ "Is it fast?\n\n" + _PROSE + "\n\n#### Kept title\n\n" + _PROSE + "",+ ),+ "hidden_variants": (+ "<main><p hidden=false>gone</p><p style='color:red'>shown red</p><p style='display : none'>gone too</p><p aria-hidden='false'>shown</p><img hidden src=x><p>"+ + _PROSE+ + "</p></main>",+ "shown red\n\nshown\n\n" + _PROSE + "",+ "shown red\n\nshown\n\n" + _PROSE + "",+ "shown red\n\nshown\n\n" + _PROSE + "",+ ),+ "implicit_closers": (+ "<main><p>one<div>two</div><ul><li>a<li>b<ul><li>c</ul><li>d</ul><table><tr><td>x<td>y<tr><th>z</table><dl><dt>t<dd>u<dt>v</dl><p>"+ + _PROSE+ + "</main>",+ "one\n\ntwo\n\n* a\n* b\n\n * c\n\n* d\n\n| x | y |\n| --- | --- |\n| z |\n\nt\n\nu\n\nv\n\n"+ + _PROSE+ + "",+ "one\n\ntwo\n\n* a\n* b\n\n * c\n\n* d\n\n| x | y |\n| --- | --- |\n| z |\n\nt\n\nu\n\nv\n\n"+ + _PROSE+ + "",+ "one\n\ntwo\n\n* a\n* b\n\n * c\n\n* d\n\n| x | y |\n| --- | --- |\n| z |\n\nt\n\nu\n\nv\n\n"+ + _PROSE+ + "",+ ),+ "header_frames": (+ "<main><header><a href='/home'>Home</a> <a href='/about'>About</a><h1>Big <a href='/t'>title</a></h1></header><p>"+ + _PROSE+ + " <a href='/more'>more</a></p><header><p>Byline by someone with a longer line of text</p></header></main>",+ "[Home](/home) [About](/about)\n\n# Big [title](/t)\n\n"+ + _PROSE+ + " [more](/more)\n\nByline by someone with a longer line of text",+ "Home About\n\n# Big title\n\n"+ + _PROSE+ + " more\n\nByline by someone with a longer line of text",+ "[Home](/home) [About](/about)\n\n# Big [title](/t)\n\n"+ + _PROSE+ + " [more](/more)\n\nByline by someone with a longer line of text",+ ),+ "foreign_content": (+ "<main><h2><svg><title>icon</title><foreignObject><button>in svg</button></foreignObject></svg>Text</h2><math><mi>x</mi><annotation-xml encoding='text/html'><p>html in math</p></annotation-xml></math><svg><p>breakout</p></svg><p>"+ + _PROSE+ + "</p></main>",+ "## Text\n\nbreakout\n\n" + _PROSE + "",+ "## Text\n\nbreakout\n\n" + _PROSE + "",+ "## Text\n\nbreakout\n\n" + _PROSE + "",+ ),+ "skipped_subtrees": (+ "<main><nav><h3><button>Nav q</button></h3></nav><h3><button>Real q</button></h3><div><p>"+ + _PROSE+ + "</p></div><footer><p>foot</p></footer><script>var a='</h3>';</script></main>",+ "### Real q\n\n" + _PROSE + "",+ "### Real q\n\n" + _PROSE + "",+ "### Real q\n\n" + _PROSE + "",+ ),+}++[email protected]("name", sorted(CASES))+def test_output_matches_pre_fast_path_render(name):+ html, main_md, stripped, full_md = CASES[name]+ h2m._TITLE_BUTTON_CACHE.clear()+ site_links = SiteLinks("https://example.com/page")+ rendered = html_to_markdown(html, main_content = True, site_links = site_links)+ assert rendered == main_md+ assert site_links.strip(rendered) == stripped+ assert html_to_markdown(html) == full_md+++def test_title_buttons_found_through_shared_attribute_checks():+ html = CASES["aria_heading_title_button"][0]+ h2m._TITLE_BUTTON_CACHE.clear()+ html_to_markdown(html, main_content = True)+ (keep,) = h2m._TITLE_BUTTON_CACHE.values()+ # role="presentation Heading" and the plain h4 keep their buttons; the aria-hidden h3 does not+ assert len(keep) == 2+++def _old_is_hidden(attr_dict):+ if "hidden" in attr_dict:+ return True+ if (attr_dict.get("aria-hidden") or "").strip().lower() == "true":+ return True+ return h2m._style_hides_element(attr_dict.get("style") or "")+++def _old_is_aria_heading(attr_dict):+ return "heading" in (attr_dict.get("role") or "").lower().split()+++_ATTR_VALUES = [+ None,+ "",+ " ",+ "true",+ " TRUE ",+ "false",+ "heading",+ "Heading tab",+ "display:none",+ "visibility: hidden !important",+ "color: red",+ "none",+]++[email protected]("name", ["hidden", "aria-hidden", "style", "role", "class"])+def test_attribute_checks_match_previous_formulas(name):+ for value in _ATTR_VALUES:+ for attr_dict in ({}, {name: value}, {name: value, "style": "display:none"}):+ assert h2m._is_hidden_element(attr_dict) is _old_is_hidden(attr_dict)+ assert h2m._is_aria_heading(attr_dict) is _old_is_aria_heading(attr_dict)+++def test_any_implicit_closer_is_the_union_of_closer_sets():+ union = set()+ for closers in h2m._IMPLICIT_CLOSERS.values():+ union |= closers+ assert h2m._ANY_IMPLICIT_CLOSER == union+ # inline elements never close anything, so they skip the recovery scan+ assert not {"span", "a", "img", "b", "svg"} & h2m._ANY_IMPLICIT_CLOSER+++class _NoSliceList(list):+ reads = 0++ def __getitem__(self, key):+ assert not isinstance(key, slice), "the open-tag lookup must not copy the stack"+ _NoSliceList.reads += 1+ return super().__getitem__(key)+++def test_innermost_index_matches_reverse_scan_without_copying():+ stack = _NoSliceList(["html", "body", "div", "p", "div", "span"])+ for tag in ("span", "div", "p", "html", "table"):+ expected = max((i for i, name in enumerate(stack) if name == tag), default = -1)+ assert h2m._innermost_index(stack, tag) == expected+ assert h2m._innermost_index(_NoSliceList(), "div") == -1+ # closing the innermost element reads one slot however deep the stack is+ deep = _NoSliceList(["div"] * 50_000)+ _NoSliceList.reads = 0+ assert h2m._innermost_index(deep, "div") == 49_999+ assert _NoSliceList.reads == 1+++def test_deeply_nested_page_still_renders():+ depth = 5_000+ page = "<div><span>" * depth + "deep text" + "</span></div>" * depth+ assert html_to_markdown(page, main_content = True) == "deep text"+ # each </section> closes one slot below the top of a deep stack+ misnested = "<div>" * depth + "<section><span>t</section>" * 3 + "</div>" * depth+ assert html_to_markdown(misnested, main_content = True) == "t\n\nt\n\nt"