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: keep formulas when the model reads a web page (#17544)
Nilaybb92c793e46d
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.pyindex fea88a1deb9..029f4e71ae9 100644--- a/studio/backend/core/inference/_html_to_md.py+++ b/studio/backend/core/inference/_html_to_md.py@@ -84,6 +84,36 @@ def _is_hidden_element(attr_dict: dict) -> bool:return bool(style) and _style_hides_element(style)+_MATH_INVISIBLE = {0x2061: " ", 0x2062: None, 0x2063: None, 0x2064: None}+_MATH_SPECIALS = re.compile(r"[{}%#&_$]")+_MATH_SCRIPTS = {"msup": "^", "msub": "_", "munder": "_"}+++def _mathml_tex(tag: str, parts: list[str]) -> str:+ if tag in ("annotation-xml", "mphantom"):+ return ""+ if tag == "mtext":+ text = "".join(parts)+ return f"\\text{{{text}}}" if text.strip() else " "+ if tag == "mfrac" and len(parts) == 2:+ return f"\\frac{{{parts[0]}}}{{{parts[1]}}}"+ if tag == "msqrt":+ return f"\\sqrt{{{''.join(parts)}}}"+ if tag == "mroot" and len(parts) == 2:+ return f"\\sqrt[{parts[1]}]{{{parts[0]}}}"+ if tag in _MATH_SCRIPTS and len(parts) == 2:+ return f"{parts[0]}{_MATH_SCRIPTS[tag]}{{{parts[1]}}}"+ if tag == "mover" and len(parts) == 2:+ return f"\\overset{{{parts[1]}}}{{{parts[0]}}}"+ if tag in ("msubsup", "munderover") and len(parts) == 3:+ return f"{parts[0]}_{{{parts[1]}}}^{{{parts[2]}}}"+ if tag == "mtr":+ return " & ".join(parts)+ if tag == "mtable":+ return " \\\\ ".join(parts)+ return "".join(parts)++def _span_attr(attr_dict: dict, name: str) -> int:try:value = int(attr_dict.get(name) or 1)@@ -849,6 +879,11 @@ class _MarkdownRenderer(HTMLParser):self._skip_html_at: list[int] = []self._skip_html_integration: list[bool] = []self._form_pointer: bool = False+ # one list per skipped element of the formula being read: the TeX of its children so far+ self._math: list[list[str]] | None = None+ self._math_tex: str = ""+ self._math_tex_at: int = -1+ self._math_block: bool = Falseself._scope_tags = scope_tagsself._scope_depth: int = 0@@ -1435,7 +1470,24 @@ class _MarkdownRenderer(HTMLParser):encoding = (attrs.get("encoding") or "").strip().lower()return tag == "annotation-xml" and encoding in {"text/html", "application/xhtml+xml"}+ def _close_math(self, index: int) -> None:+ for position in range(len(self._skip_tags) - 1, index - 1, -1):+ tex = _mathml_tex(self._skip_tags[position], self._math.pop())+ if position == self._math_tex_at:+ self._math_tex_at = -1+ if tex.strip():+ self._math_tex = tex+ elif position:+ self._math[-1].append(tex)+ else:+ tex = " ".join((self._math_tex or tex).translate(_MATH_INVISIBLE).split())+ self._math = None+ if tex:+ self._emit(f"\n\n$${tex}$$\n\n" if self._math_block else f"${tex}$")+def _truncate_skip_tags(self, index: int) -> None:+ if self._math is not None:+ self._close_math(index)for position, name in enumerate(self._skip_tags[index:], start = index):self._skip_at[name].pop()self._skip_ns_at[(self._skip_namespaces[position], name)].pop()@@ -1446,6 +1498,8 @@ class _MarkdownRenderer(HTMLParser):del self._skip_html_integration[index:]def _clear_skip_tags(self) -> None:+ if self._math is not None:+ self._close_math(0)self._skip_tags.clear()self._skip_at.clear()self._skip_ns_at.clear()@@ -1675,6 +1729,11 @@ class _MarkdownRenderer(HTMLParser):self._skip_html_integration.append(self._is_html_integration_point(tag, namespace, attr_dict))+ if self._math is not None:+ self._math.append([])+ encoding = (attr_dict.get("encoding") or "").strip().lower()+ if tag == "annotation" and encoding == "application/x-tex":+ self._math_tex_at = positionreturnif tag == "form" and self._form_pointer:@@ -1689,6 +1748,10 @@ class _MarkdownRenderer(HTMLParser):self._prepare_table_start(tag)if tag in _SKIP_TAGS and not (title_button and self._heading_marks):+ if tag == "math" and not self._text_suppressed() and not _is_hidden_element(attr_dict):+ self._math = [[]]+ self._math_tex = (attr_dict.get("alttext") or "").strip()+ self._math_block = (attr_dict.get("display") or "").strip().lower() == "block"self._skip_tags.append(tag)self._skip_at = {tag: [0]}namespace = self._html_start_namespace(tag)@@ -2024,6 +2087,15 @@ class _MarkdownRenderer(HTMLParser):if self._title_scan is not None:self._title_scan.data(data)if self._skip_tags or self._hidden_marks or self._text_suppressed():+ if self._math is None:+ return+ if len(self._skip_tags) - 1 == self._math_tex_at:+ self._math[-1].append(data)+ elif (+ self._skip_namespaces[-1] == "math"+ and self._skip_tags[-1] in _MATHML_TEXT_INTEGRATION_POINTS+ ):+ self._math[-1].append(_MATH_SPECIALS.sub(r"\\\g<0>", data))returnif self._in_pre:self._count_header_text(data)@@ -2065,6 +2137,11 @@ class _MarkdownRenderer(HTMLParser):def flush_pending(self) -> None:"""Flush open side-buffers into ``_out`` after close(), recovering truncated HTML."""+ if self._math is not None:+ # an annotation cut off mid-source must not override alttext or the MathML+ if self._math_tex_at >= 0:+ self._math[self._math_tex_at].clear()+ self._close_math(0)# Headers first: a frame emits into the enclosing link or cell, which must still be open.self._flush_header_frames()diff --git a/studio/backend/tests/test_html_to_md_fast_paths.py b/studio/backend/tests/test_html_to_md_fast_paths.pyindex 7ed090f5781..8985ad7edea 100644--- a/studio/backend/tests/test_html_to_md_fast_paths.py+++ b/studio/backend/tests/test_html_to_md_fast_paths.py@@ -75,9 +75,9 @@ CASES = {"<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 + "",+ "## Text\n\n$x$\n\nbreakout\n\n" + _PROSE + "",+ "## Text\n\n$x$\n\nbreakout\n\n" + _PROSE + "",+ "## Text\n\n$x$\n\nbreakout\n\n" + _PROSE + "",),"skipped_subtrees": ("<main><nav><h3><button>Nav q</button></h3></nav><h3><button>Real q</button></h3><div><p>"diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.pyindex 5f276a14b06..4792b5ca7fc 100644--- a/studio/backend/tests/test_web_fetch_extraction.py+++ b/studio/backend/tests/test_web_fetch_extraction.py@@ -448,7 +448,7 @@ def test_foreign_button_start_does_not_close_html_button(foreign, main_content):assert "Menu text" in out and "After" in out[email protected]("root, descendant", [("svg", "foreignObject"), ("math", "mi")])[email protected]("root, descendant", [("svg", "foreignObject"), ("math", "annotation-xml")])@pytest.mark.parametrize("main_content", [False, True])def test_foreign_root_end_closes_through_foreign_descendant(root, descendant, main_content):html = f"<{root}><{descendant}>Hidden</{root}><p>Real text</p>"@@ -3947,3 +3947,127 @@ def test_deeply_nested_tags_stay_linear():runs.append(time.perf_counter() - start)timings.append(min(runs))assert timings[1] < timings[0] * 12, timings+++_KATEX_HTML_COPY = (+ '<span class="katex-html" aria-hidden="true"><span class="base">'+ '<span class="mord mathnormal">y</span><span class="mrel">=</span>'+ '<span class="mord mathnormal">x</span><span class="mord mathnormal">A</span>'+ '<span class="mord mathnormal">T</span><span class="mbin">+</span>'+ '<span class="mord mathnormal">b</span></span></span>'+)+++ "markup, expected",+ [+ (+ 'incoming data: <span class="katex"><span class="katex-mathml"><math '+ 'xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>y</mi><mo>=</mo>'+ "<mi>x</mi><msup><mi>A</mi><mi>T</mi></msup><mo>+</mo><mi>b</mi></mrow>"+ '<annotation encoding="application/x-tex">y = xA^T + b</annotation></semantics>'+ f"</math></span>{_KATEX_HTML_COPY}</span>.",+ "incoming data: $y = xA^T + b$.",+ ),+ (+ 'keys of dimension <math class="ltx_Math" alttext="d_{k}" display="inline">'+ "<semantics><msub><mi>d</mi><mi>k</mi></msub>"+ '<annotation-xml encoding="MathML-Content"><apply><csymbol cd="ml">subscript'+ "</csymbol><ci>d</ci><ci>k</ci></apply></annotation-xml>"+ '<annotation encoding="application/x-tex">d_{k}</annotation>'+ '<annotation encoding="application/x-llamapun">ITALIC_d start_POSTSUBSCRIPT'+ "</annotation></semantics></math>, and values",+ "keys of dimension $d_{k}$, and values",+ ),+ (+ 'the form <math xmlns="http://www.w3.org/1998/Math/MathML"><mrow>\n<mstyle><mi>a'+ "</mi><msup><mi>x</mi><mrow><mn>2</mn></mrow></msup><mo>+</mo><mi>b</mi><mi>x</mi>"+ "<mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></mstyle>\n</mrow></math>, with",+ "the form $ax^{2}+bx+c=0$, with",+ ),+ (+ "roots <math><mi>x</mi><mo>=</mo><mfrac><mrow><mo>−</mo><mi>b</mi>"+ "<mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn>"+ "<mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></math>",+ "roots $x=\\frac{−b±\\sqrt{b^{2}−4ac}}{2a}$",+ ),+ (+ "sum <math><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><mn>1</mn></mrow>"+ "<mi>n</mi></munderover><msub><mi>x</mi><mi>i</mi></msub></math> and "+ "<math><mi>sin</mi><mo>⁡</mo><mi>x</mi></math>",+ "sum $∑_{i=1}^{n}x_{i}$ and $sin x$",+ ),+ (+ "<math><mtable><mtr><mtd><mi>a</mi></mtd><mtd><mi>b</mi></mtd></mtr>"+ "<mtr><mtd><mi>c</mi></mtd><mtd><mi>d</mi></mtd></mtr></mtable></math>",+ "$a & b \\\\ c & d$",+ ),+ (+ "set <math><mo>{</mo><mover><mi>x</mi><mo>¯</mo></mover><mo>></mo><mn>50</mn>"+ "<mi>%</mi><mo>}</mo><mtext> for all </mtext><mi>n</mi>"+ "<mphantom><mi>y</mi></mphantom></math>",+ "set $\\{\\overset{¯}{x}>50\\%\\}\\text{ for all }n$",+ ),+ ],+)+def test_formulas_reach_the_model_once(markup, expected):+ assert html_to_markdown(f"<p>{markup}</p>") == expected+++def test_display_formula_gets_its_own_paragraph():+ html = (+ '<p>We compute:</p><math alttext="E=mc^{2}" display="block"><mi>E</mi></math>'+ "<p>where c is the speed of light.</p>"+ )+ assert html_to_markdown(html) == (+ "We compute:\n\n$$E=mc^{2}$$\n\nwhere c is the speed of light."+ )+++ "html",+ [+ '<p>Shown</p><div hidden><math alttext="x"><mi>x</mi></math></div>',+ '<p>Shown</p><math style="display:none" alttext="x"><mi>x</mi></math>',+ '<p>Shown</p><nav><math alttext="x"><mi>x</mi></math></nav>',+ "<p>Shown</p><math><mi></mi></math>",+ ],+)+def test_hidden_or_empty_formulas_stay_out(html):+ assert html_to_markdown(html) == "Shown"+++def test_formula_counts_as_article_text():+ prose = "Attention weighs every key against the query. " * 6+ html = (+ f"<nav>Menu</nav><article><p>{prose}keys of dimension "+ '<math alttext="d_{k}"><mi>d</mi></math>.</p></article>'+ )+ out = html_to_markdown(html, main_content = True)+ assert out.count("$d_{k}$") == 1 and "Menu" not in out+++ "html",+ [+ '<p>Value <math alttext=" "><mi>x</mi></math> here.</p>',+ '<p>Value <math alttext="x"><semantics><mi>y</mi>'+ '<annotation encoding="application/x-tex"> </annotation></semantics></math> here.</p>',+ ],+)+def test_blank_tex_source_falls_back(html):+ assert html_to_markdown(html) == "Value $x$ here."++[email protected]("main_content", [False, True])+ "tail",+ [+ "<math><mi>x</mi><mo>+</mo><mi>y</mi>",+ '<math alttext="x+y"><semantics><mi>z</mi><annotation encoding="application/x-tex">x+',+ "<math><semantics><mi>x</mi><mo>+</mo><mi>y</mi>"+ '<annotation encoding="application/x-tex">x+',+ ],+)+def test_formula_cut_off_at_end_of_page_is_kept(tail, main_content):+ assert html_to_markdown(f"<p>Then {tail}", main_content = main_content) == "Then $x+y$"