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: score unclosed Markdown link destinations in linear time (#15811)
Daniel Han4eafe33d5aa5
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.pyindex 2f131b466a6..b6fac3731dc 100644--- a/studio/backend/core/inference/_html_to_md.py+++ b/studio/backend/core/inference/_html_to_md.py@@ -2342,11 +2342,13 @@ def _fence_for(raw: str) -> str:def _visible_len(line: str) -> int:"""Length of *line* without Markdown link destinations. A tracking URL is notprose: a card holding one [Read](/x?<300 bytes>) otherwise scored 339 visible- characters off 4 and displaced the article. Scanned, so no backtracking."""+ characters off 4 and displaced the article. Linear: once a destination fails to+ close, the rest are answered from one table instead of a rescan each."""if "[" not in line and "\\" not in line:return len(line)total, i, n = 0, 0, len(line)open_bracket = False+ closes = Nonewhile i < n:if line[i] == "\\":total += 2@@ -2356,15 +2358,22 @@ def _visible_len(line: str) -> int: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 closes is None:+ # 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:+ # Unclosed: later candidates would rescan this tail, so index it once.+ closes = _destination_ends(line)+ else:+ j = closes.get(i + 2, -1)+ depth = j < 0if depth:total += 1i += 1@@ -2377,6 +2386,34 @@ def _visible_len(line: str) -> int:return total+def _destination_ends(line: str) -> dict:+ """End of the destination scan from each reachable position, for scans that close. All scans+ step over the same positions, so a scan from p closes where the paren-depth prefix sum first+ drops below its value at p."""+ steps: list[int] = []+ sums: list[int] = []+ depth, k, n = 0, 0, len(line)+ while k < n:+ steps.append(k)+ sums.append(depth)+ char = line[k]+ if char == "\\":+ k += 2+ continue+ depth += (char == "(") - (char == ")")+ k += 1+ ends: dict = {}+ first_at: dict = {} # prefix sum -> earliest later step index+ sums.append(depth)+ for m in range(len(steps), -1, -1):+ if m < len(steps):+ after = first_at.get(sums[m] - 1)+ if after is not None:+ ends[steps[m]] = steps[after - 1] + 1+ first_at[sums[m]] = m+ return ends++# Scoped conversions shorter than this are rejected as main content, e.g. an empty article stub_MIN_MAIN_CONTENT_CHARS = 200# absent text = no such tag can tokenize, so that scope finds nothingdiff --git a/studio/backend/tests/test_html_to_md_visible_len_linear.py b/studio/backend/tests/test_html_to_md_visible_len_linear.pynew file mode 100644index 00000000000..0355c2d0d2f--- /dev/null+++ b/studio/backend/tests/test_html_to_md_visible_len_linear.py@@ -0,0 +1,89 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""_visible_len scores page text for main-content selection. A line full of link destinations+that never close used to rescan its tail once per candidate (quadratic in page text); it must+stay linear and count exactly what the rescanning scanner counted."""++from __future__ import annotations++import itertools+import random+import sys+from pathlib import Path++_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 _visible_len, html_to_markdown+++def _rescanning_visible_len(line: str) -> int:+ """The scanner before it indexed destinations: one forward scan per candidate."""+ if "[" not in line and "\\" not in line:+ return len(line)+ 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+ if open_bracket and line[i] == "]" and i + 1 < n and line[i + 1] == "(":+ 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:+ total += 1+ i += 1+ continue+ i = j+ open_bracket = False+ continue+ total += 1+ i += 1+ return total+++class _CountingStr(str):+ reads = 0++ def __getitem__(self, key):+ _CountingStr.reads += 1+ return str.__getitem__(self, key)+++def test_every_short_line_scores_as_the_rescanning_scanner_did():+ for length in range(8):+ for chars in itertools.product("[]()\\a", repeat = length):+ line = "".join(chars)+ assert _visible_len(line) == _rescanning_visible_len(line), line+++def test_random_link_soup_scores_as_the_rescanning_scanner_did():+ rng = random.Random(0)+ for _ in range(3000):+ alphabet = rng.choice(["[]()\\a", "[]((\\a", "[]())a", "[](a b", "[]()\\\\a"])+ line = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 400)))+ assert _visible_len(line) == _rescanning_visible_len(line), line+++def test_unclosed_destinations_are_read_a_bounded_number_of_times():+ line = _CountingStr("[a](" * 400)+ _CountingStr.reads = 0+ assert _visible_len(line) == _rescanning_visible_len(str(line))+ assert _CountingStr.reads < 10 * len(line)+++def test_a_page_of_unclosed_links_converts_as_before():+ html = "<html><body><p>" + " ".join(f"[x{i}](/y{i}" for i in range(300)) + "</p></body></html>"+ out = html_to_markdown(html, main_content = True)+ assert out.count("[x") == 300