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.

Studio: read web pages in the encoding the page itself declares (#11598)

Nilay06c766350e03
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 60f01119073..9609f61cb2d 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -13839,6 +13839,94 @@ _UNICODE_BOM_CODECS = (
_MIN_SINGLE_BYTE_ASCII_RATIO = 3 / 4
_ASCII_TEXT_BYTES = frozenset((*range(0x20, 0x7F), 0x09, 0x0A, 0x0D, 0x1B))
+_META_CHARSET_SCAN_BYTES = 2048
+# A comment or whole tag, quoted attribute values included, so markup inside them is never read as <meta>. As in the
+# browser prescan, an unterminated tag ends the scan.
+_HTML_TAG_RE = re.compile(
+ rb"<!--.*?(?:-->|\Z)|<([a-z][^\s/>]*)((?:[\s/](?:[^>\"']|\"[^\"]*\"|'[^']*')*)?)>|<[!/?][^>]*>|<[a-z!/?].*",
+ re.IGNORECASE | re.DOTALL,
+)
+_META_ATTR_RE = re.compile(rb"([^\s\"'/=>]+)(?:\s*=\s*(?:\"([^\"]*)\"|'([^']*)'|([^\s>]*)))?")
+_META_CONTENT_CHARSET_RE = re.compile(rb"charset\s*=\s*[\"']?\s*([^\s\"';]+)", re.IGNORECASE)
+_XML_ENCODING_RE = re.compile(rb"\s*<\?xml\b[^>]*?encoding\s*=\s*[\"']([\w.:-]+)", re.IGNORECASE)
+# WHATWG Encoding labels by the Python codec that matches the browser decoder. A meta declaration
+# of UTF-16 or x-user-defined means UTF-8 or windows-1252; "replacement" labels are left out.
+_WHATWG_CHARSET_LABELS = {
+ "utf-8": (
+ "unicode-1-1-utf-8 unicode11utf8 unicode20utf8 utf-8 utf8 x-unicode20utf8 unicodefffe "
+ "utf-16be csunicode iso-10646-ucs-2 ucs-2 unicode unicodefeff utf-16 utf-16le"
+ ),
+ "cp866": "866 cp866 csibm866 ibm866",
+ "iso8859-2": (
+ "csisolatin2 iso-8859-2 iso-ir-101 iso8859-2 iso88592 iso_8859-2 iso_8859-2:1987 l2 "
+ "latin2"
+ ),
+ "iso8859-3": (
+ "csisolatin3 iso-8859-3 iso-ir-109 iso8859-3 iso88593 iso_8859-3 iso_8859-3:1988 l3 "
+ "latin3"
+ ),
+ "iso8859-4": (
+ "csisolatin4 iso-8859-4 iso-ir-110 iso8859-4 iso88594 iso_8859-4 iso_8859-4:1988 l4 "
+ "latin4"
+ ),
+ "iso8859-5": (
+ "csisolatincyrillic cyrillic iso-8859-5 iso-ir-144 iso8859-5 iso88595 iso_8859-5 "
+ "iso_8859-5:1988"
+ ),
+ "iso8859-6": (
+ "arabic asmo-708 csiso88596e csiso88596i csisolatinarabic ecma-114 iso-8859-6 "
+ "iso-8859-6-e iso-8859-6-i iso-ir-127 iso8859-6 iso88596 iso_8859-6 iso_8859-6:1987"
+ ),
+ "iso8859-7": (
+ "csisolatingreek ecma-118 elot_928 greek greek8 iso-8859-7 iso-ir-126 iso8859-7 iso88597 "
+ "iso_8859-7 iso_8859-7:1987 sun_eu_greek"
+ ),
+ "iso8859-8": (
+ "csiso88598e csisolatinhebrew hebrew iso-8859-8 iso-8859-8-e iso-ir-138 iso8859-8 "
+ "iso88598 iso_8859-8 iso_8859-8:1988 visual csiso88598i iso-8859-8-i logical"
+ ),
+ "iso8859-10": "csisolatin6 iso-8859-10 iso-ir-157 iso8859-10 iso885910 l6 latin6",
+ "iso8859-13": "iso-8859-13 iso8859-13 iso885913",
+ "iso8859-14": "iso-8859-14 iso8859-14 iso885914",
+ "iso8859-15": "csisolatin9 iso-8859-15 iso8859-15 iso885915 iso_8859-15 l9",
+ "iso8859-16": "iso-8859-16",
+ "koi8-r": "cskoi8r koi koi8 koi8-r koi8_r",
+ "koi8-u": "koi8-ru koi8-u",
+ "mac-roman": "csmacintosh mac macintosh x-mac-roman",
+ "cp874": "dos-874 iso-8859-11 iso8859-11 iso885911 tis-620 windows-874",
+ "cp1250": "cp1250 windows-1250 x-cp1250",
+ "cp1251": "cp1251 windows-1251 x-cp1251",
+ "cp1252": (
+ "ansi_x3.4-1968 ascii cp1252 cp819 csisolatin1 ibm819 iso-8859-1 iso-ir-100 iso8859-1 "
+ "iso88591 iso_8859-1 iso_8859-1:1987 l1 latin1 us-ascii windows-1252 x-cp1252 "
+ "x-user-defined"
+ ),
+ "cp1253": "cp1253 windows-1253 x-cp1253",
+ "cp1254": (
+ "cp1254 csisolatin5 iso-8859-9 iso-ir-148 iso8859-9 iso88599 iso_8859-9 iso_8859-9:1989 "
+ "l5 latin5 windows-1254 x-cp1254"
+ ),
+ "cp1255": "cp1255 windows-1255 x-cp1255",
+ "cp1256": "cp1256 windows-1256 x-cp1256",
+ "cp1257": "cp1257 windows-1257 x-cp1257",
+ "cp1258": "cp1258 windows-1258 x-cp1258",
+ "mac-cyrillic": "x-mac-cyrillic x-mac-ukrainian",
+ "gb18030": (
+ "chinese csgb2312 csiso58gb231280 gb2312 gb_2312 gb_2312-80 gbk iso-ir-58 x-gbk gb18030"
+ ),
+ "big5hkscs": "big5 big5-hkscs cn-big5 csbig5 x-x-big5",
+ "euc_jp": "cseucpkdfmtjapanese euc-jp x-euc-jp",
+ "iso2022_jp": "csiso2022jp iso-2022-jp",
+ "cp932": "csshiftjis ms932 ms_kanji shift-jis shift_jis sjis windows-31j x-sjis",
+ "cp949": (
+ "cseuckr csksc56011987 euc-kr iso-ir-149 korean ks_c_5601-1987 ks_c_5601-1989 ksc5601 "
+ "ksc_5601 windows-949"
+ ),
+}
+_WHATWG_CHARSET_CODECS = {
+ label: codec for codec, labels in _WHATWG_CHARSET_LABELS.items() for label in labels.split()
+}
+
def _looks_binary(text: str) -> bool:
"""Whether control or undecodable characters exceed the binary threshold."""
@@ -13873,6 +13961,39 @@ def _has_single_byte_text_evidence(data: bytes) -> bool:
return ascii_text_bytes / len(data) >= _MIN_SINGLE_BYTE_ASCII_RATIO
+def _whatwg_codec(label: bytes) -> str | None:
+ return _WHATWG_CHARSET_CODECS.get(label.strip(b"\t\n\f\r ").decode("latin-1").lower())
+
+
+def _sniff_meta_charset(head: bytes, content_type: str) -> str | None:
+ # Browsers prescan <meta> only in HTML (first usable one wins, XML prolog as fallback) and read
+ # only the prolog in XML. A headerless body is XML if it opens with a prolog, HTML if it looks it.
+ prolog = _XML_ENCODING_RE.match(head)
+ if content_type:
+ is_html = content_type == "text/html"
+ is_xml = content_type in ("text/xml", "application/xml") or content_type.endswith("+xml")
+ else:
+ is_xml = prolog is not None
+ is_html = not is_xml and _looks_like_html(head.decode("latin-1"))
+ if is_html:
+ for tag in _HTML_TAG_RE.finditer(head):
+ if (tag.group(1) or b"").lower() != b"meta":
+ continue
+ attrs = {}
+ for name, *values in _META_ATTR_RE.findall(tag.group(2)):
+ attrs.setdefault(name.lower(), b"".join(values))
+ label = attrs.get(b"charset")
+ if label is None and attrs.get(b"http-equiv", b"").strip().lower() == b"content-type":
+ match = _META_CONTENT_CHARSET_RE.search(attrs.get(b"content", b""))
+ label = match and match.group(1)
+ codec = label and _whatwg_codec(label)
+ if codec:
+ return codec
+ elif not is_xml:
+ return None
+ return prolog and _whatwg_codec(prolog.group(1))
+
+
def _extract_pdf_text(data: bytes) -> str:
"""Extract page-delimited text with the same parser used by RAG ingestion."""
from ..rag.parsers import parse_pdf_bytes
@@ -14617,14 +14738,19 @@ def _fetch_url_raw(
(codec for bom, codec in _UNICODE_BOM_CODECS if raw_bytes.startswith(bom)),
None,
)
+ fallback_codec = (
+ bom_codec
+ or _sniff_meta_charset(raw_bytes[:_META_CHARSET_SCAN_BYTES], content_type)
+ or "utf-8"
+ )
try:
- raw_html = raw_bytes.decode(declared or bom_codec or "utf-8", errors = "replace")
+ raw_html = raw_bytes.decode(declared or fallback_codec, errors = "replace")
except (LookupError, ValueError):
# Survives lookup, fails the decode: base64/hex/zlib are not text codecs, "undefined" always raises, idna
# rejects replace. The fallback cannot raise.
declared = None
declared_codec = None
- raw_html = raw_bytes.decode(bom_codec or "utf-8", errors = "replace")
+ raw_html = raw_bytes.decode(fallback_codec, errors = "replace")
# Catch mislabeled or unlabeled binary, including valid UTF-8 controls.
if _looks_binary(raw_html):
diff --git a/studio/backend/tests/test_web_fetch_binary_guard.py b/studio/backend/tests/test_web_fetch_binary_guard.py
index 4a5786dd6fe..3396252e094 100644
--- a/studio/backend/tests/test_web_fetch_binary_guard.py
+++ b/studio/backend/tests/test_web_fetch_binary_guard.py
@@ -1,12 +1,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Regression tests for binary bodies poisoning web_search model context (#7084)."""
+"""Regression tests for web fetch decoding: binary bodies poisoning model context (#7084) and page charsets."""
from __future__ import annotations
import codecs
import sys
+import time
from email.message import Message
from pathlib import Path
@@ -430,3 +431,220 @@ def test_text_with_a_few_stray_replacement_chars_kept(monkeypatch):
out = _fetch_with(monkeypatch, body, "text/html")
assert "Real article text." in out
assert "binary content" not in out
+
+
+_JAPANESE = "価格.com は日本最大級の購買支援サイトです。製品の価格比較とクチコミ。"
+
+
+def _html_page(head: str, text: str) -> str:
+ return (
+ f"<!doctype html><html><head>{head}<title>t</title></head><body><p>{text}</p></body></html>"
+ )
+
+
+ "head",
+ [
+ '<meta charset="Shift_JIS">',
+ "<meta charset=shift_jis>",
+ '<meta charset="x-sjis">',
+ '<meta charset="windows-31j">',
+ '<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">',
+ '<meta content="text/html; charset=shift_jis" http-equiv="content-type">',
+ '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=Shift_JIS">',
+ "<meta http-equiv=content-type content=\"text/html; charset='shift_jis'\">",
+ ],
+)
+def test_meta_charset_read_when_header_names_none(monkeypatch, head):
+ body = _html_page(head, _JAPANESE * 40).encode("cp932")
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert _JAPANESE in out
+ assert "�" not in out
+ assert "binary content" not in out
+
+
[email protected]("content_type", ["text/html", "application/xhtml+xml", "text/xml"])
+def test_xml_prolog_encoding_read_when_header_names_none(monkeypatch, content_type):
+ body = ('<?xml version="1.0" encoding="EUC-JP"?>\n' + _html_page("", _JAPANESE * 40)).encode(
+ "euc_jp"
+ )
+ out = _fetch_with(monkeypatch, body, content_type)
+ assert _JAPANESE in out
+ assert "�" not in out
+
+
+ "label,encoding,text",
+ [
+ ("gb2312", "gbk", "镕 GBK-only MARKERWORD"),
+ ("latin1", "cp1252", "“quoted” MARKERWORD"),
+ ("iso-8859-1", "cp1252", "“quoted” MARKERWORD"),
+ ("windows-1251", "cp1251", "Привет MARKERWORD"),
+ ("euc-jp", "euc_jp", _JAPANESE),
+ ("euc-kr", "cp949", "작성자: 김똠, 댓글: 햏햏 뷁 MARKERWORD"),
+ ("ks_c_5601-1987", "cp949", "작성자: 김똠, 댓글: 햏햏 뷁 MARKERWORD"),
+ ("big5", "big5hkscs", "台灣裏面恒春 碁盤 MARKERWORD"),
+ ("tis-620", "cp874", "ภาษาไทย “คำพูด” … MARKERWORD"),
+ ("iso-8859-9", "cp1254", "Türkiye’nin “Ankara”dır… MARKERWORD"),
+ ],
+)
+def test_meta_charset_labels_decode_with_whatwg_codecs(monkeypatch, label, encoding, text):
+ body = _html_page(f'<meta charset="{label}">', text * 40).encode(encoding)
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert text in out
+ assert "�" not in out
+
+
+def test_header_charset_wins_over_contradicting_meta(monkeypatch):
+ body = _html_page('<meta charset="Shift_JIS">', _JAPANESE * 40).encode("utf-8")
+ out = _fetch_with(monkeypatch, body, "text/html; charset=utf-8")
+ assert _JAPANESE in out
+ assert "�" not in out
+
+
+def test_bom_wins_over_contradicting_meta(monkeypatch):
+ body = codecs.BOM_UTF8 + _html_page('<meta charset="Shift_JIS">', _JAPANESE * 40).encode()
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert _JAPANESE in out
+ assert "�" not in out
+
+
+ "label",
+ [
+ "x-mac-fantasy",
+ "utf8mb4",
+ "base64",
+ "rot13",
+ "idna",
+ "undefined",
+ "utf-7",
+ "utf-32",
+ "punycode",
+ ],
+)
+def test_unknown_meta_charset_falls_back_to_utf8_without_raising(monkeypatch, label):
+ body = _html_page(f'<meta charset="{label}">', "MARKERWORD über " * 40).encode("utf-8")
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert "MARKERWORD über" in out
+ assert "Failed to fetch URL" not in out
+
+
[email protected]("meta", ['<meta charset="utf-8">', '<meta charset="utf-16">'])
+def test_meta_charset_keeps_cp1252_rescue_for_mislabeled_page(monkeypatch, meta):
+ text = "¿Qué pasó? Canción, corazón, niño, España, José, señor. "
+ body = _html_page(meta, text * 30).encode("cp1252")
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert text.strip() in out
+ assert "binary content" not in out
+
+
+def test_commented_out_meta_charset_is_ignored(monkeypatch):
+ text = "Ünïcödé “smart” 日本語 MARKERWORD "
+ head = '<!--[if IE]><meta charset="iso-8859-1"><![endif]--><meta charset="utf-8">'
+ body = _html_page(head, text * 20).encode("utf-8")
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert text.strip() in out
+ assert "Ã" not in out
+
+
[email protected]("header_label", ["x-bogus-label", "base64"])
+def test_meta_charset_used_when_header_charset_unusable(monkeypatch, header_label):
+ body = _html_page('<meta charset="Shift_JIS">', _JAPANESE * 40).encode("cp932")
+ out = _fetch_with(monkeypatch, body, f"text/html; charset={header_label}")
+ assert _JAPANESE in out
+ assert "�" not in out
+
+
+def test_unusable_meta_charset_does_not_stop_the_scan(monkeypatch):
+ head = '<meta charset="bogus"><meta charset="Shift_JIS">'
+ body = _html_page(head, _JAPANESE * 40).encode("cp932")
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert _JAPANESE in out
+ assert "�" not in out
+
+
+ "head",
+ [
+ '<meta name="description" content="docs about charset=shift_jis">',
+ '<meta http-equiv="refresh" content="0; url=/next?charset=shift_jis">',
+ '<meta name="Content-Type" content="text/html; charset=shift_jis">',
+ '<meta name="x" content="<meta charset=shift_jis>">',
+ "<script data-x='<meta charset=\"shift_jis\">'></script>",
+ '<meta charset="shift<!-- x -->_jis">',
+ '<meta-info charset="shift_jis"><metadata charset="shift_jis">',
+ ],
+)
+def test_charset_text_outside_a_declaration_is_ignored(monkeypatch, head):
+ text = "Ünïcödé “smart” 日本語 MARKERWORD "
+ body = _html_page(head, text * 20).encode("utf-8")
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert text.strip() in out
+ assert "�" not in out
+
+
+def test_meta_charset_wins_over_xml_prolog(monkeypatch):
+ text = "Café crème brûlée — MARKERWORD "
+ head = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'
+ body = ('<?xml version="1.0" encoding="iso-8859-1"?>\n' + _html_page(head, text * 20)).encode()
+ out = _fetch_with(monkeypatch, body, "text/html")
+ assert text.strip() in out
+ assert "Ã" not in out
+
+
+ "head",
+ [
+ b"<a" * 1024,
+ b'<html><head><script data-x="' + b"<a" * 1024,
+ b"<html><head><script>" + b"x<y;" * 512,
+ b'<html><head><script data-x=\'<meta charset="shift_jis">' + b"x" * 2048,
+ ],
+)
+def test_meta_prescan_stops_at_an_unterminated_tag(head):
+ start = time.perf_counter()
+ assert tools._sniff_meta_charset(head[: tools._META_CHARSET_SCAN_BYTES], "text/html") is None
+ assert time.perf_counter() - start < 1
+
+
+def test_whatwg_charset_table_only_names_text_codecs():
+ for label, codec in tools._WHATWG_CHARSET_CODECS.items():
+ assert label == label.lower()
+ assert codecs.lookup(codec)._is_text_encoding, label
+ assert b"a\xff".decode(codec, "replace")
+
+
+ "content_type", ["text/plain", "application/json", "application/xml", "text/css"]
+)
+def test_meta_charset_in_non_html_body_is_ignored(monkeypatch, content_type):
+ text = "日本語のテキスト。価格比較とクチコミ。MARKERWORD "
+ body = ('<p>Example:</p> <meta charset="shift_jis"/> ' + text * 40).encode("utf-8")
+ out = _fetch_with(monkeypatch, body, content_type)
+ assert text.strip() in out
+ assert "�" not in out
+
+
+def test_meta_charset_read_when_content_type_missing(monkeypatch):
+ body = _html_page('<meta charset="Shift_JIS">', _JAPANESE * 40).encode("cp932")
+ out = _fetch_with(monkeypatch, body, None)
+ assert _JAPANESE in out
+ assert "�" not in out
+
+
+def test_meta_charset_in_headerless_non_html_body_is_ignored(monkeypatch):
+ text = "日本語のテキスト。価格比較とクチコミ。MARKERWORD "
+ body = ('# Encoding\n\nUse `<meta charset="shift_jis">` on old pages.\n\n' + text * 40).encode()
+ out = _fetch_with(monkeypatch, body, None)
+ assert text.strip() in out
+ assert "�" not in out
+
+
+def test_xml_prolog_encoding_read_when_content_type_missing(monkeypatch):
+ body = (
+ '<?xml version="1.0" encoding="Shift_JIS"?>\n<doc><p>' + _JAPANESE * 40 + "</p></doc>"
+ ).encode("cp932")
+ out = _fetch_with(monkeypatch, body, None)
+ assert _JAPANESE in out
+ assert "�" not in out