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 text, Markdown and HTML uploads in the encoding they were written in (#11896)

Lukas255217292bfb
diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.py
index 7114aebbcba..09bd478db80 100644
--- a/studio/backend/core/rag/parsers.py
+++ b/studio/backend/core/rag/parsers.py
@@ -594,6 +594,44 @@ def _docx(path: str) -> list[Page]:
return [_page("\n".join(lines), None)]
+def _declared_charset(data: bytes) -> str | None:
+ # Lazy: tools is heavy, and only HTML that is not UTF-8 gets here.
+ from ..inference.tools import _META_CHARSET_SCAN_BYTES, _sniff_meta_charset
+ return _sniff_meta_charset(data[:_META_CHARSET_SCAN_BYTES], "text/html")
+
+
+def _decode_text(data: bytes, *, html: bool = False) -> str:
+ # Check UTF-32 before its overlapping UTF-16 prefix.
+ for bom, codec in (
+ (codecs.BOM_UTF32_LE, "utf-32"),
+ (codecs.BOM_UTF32_BE, "utf-32"),
+ (codecs.BOM_UTF16_LE, "utf-16"),
+ (codecs.BOM_UTF16_BE, "utf-16"),
+ (codecs.BOM_UTF8, "utf-8-sig"),
+ ):
+ if data.startswith(bom):
+ return data.decode(codec, errors = "replace")
+ try:
+ text = data.decode("utf-8")
+ except UnicodeDecodeError:
+ pass
+ else:
+ # ISO-2022-JP is 7-bit, so it always passes as UTF-8; its escapes give it away.
+ if html and "\x1b$" in text and _declared_charset(data) == "iso2022_jp":
+ return data.decode("iso2022_jp", errors = "replace")
+ return text
+ declared = _declared_charset(data) if html else None
+ # WHATWG reads UTF-16 labels as UTF-8, which these bytes already failed.
+ if declared and declared != "utf-8":
+ return data.decode(declared, errors = "replace")
+ text = data.decode("utf-8", errors = "replace")
+ # Ties stay UTF-8 (truncated file); cp1252 can form a stray valid sequence ("à\xa0»").
+ non_ascii = len(text) - len(text.encode("ascii", "ignore"))
+ if non_ascii >= 2 * text.count("\ufffd"):
+ return text
+ return data.decode("cp1252", errors = "replace")
+
+
def parse(path: str, *, want_images: bool = False):
"""Parse a file into pages by extension. Returns ``list[Page]``, or
``(list[Page], list[ParsedImage])`` when ``want_images=True`` (only PDFs yield
@@ -609,22 +647,12 @@ def parse(path: str, *, want_images: bool = False):
return (pages, []) if want_images else pages
if ext in (".html", ".htm", ".txt", ".md", ".markdown"):
- # Honor Unicode BOMs; check UTF-32 before its overlapping UTF-16 prefix.
+ is_html = ext in (".html", ".htm")
with open(path, "rb") as f:
- prefix = f.read(4)
- encoding = "utf-8-sig"
- for bom, codec in (
- (codecs.BOM_UTF32_LE, "utf-32"),
- (codecs.BOM_UTF32_BE, "utf-32"),
- (codecs.BOM_UTF16_LE, "utf-16"),
- (codecs.BOM_UTF16_BE, "utf-16"),
- ):
- if prefix.startswith(bom):
- encoding = codec
- break
- with open(path, encoding = encoding, errors = "replace") as f:
- raw = f.read()
- pages = _html(raw) if ext in (".html", ".htm") else [_page(raw, None)]
+ raw = _decode_text(f.read(), html = is_html)
+ # Universal newlines, as text-mode open() gave: the chunker splits on "\n\n".
+ raw = raw.replace("\r\n", "\n").replace("\r", "\n")
+ pages = _html(raw) if is_html else [_page(raw, None)]
return (pages, []) if want_images else pages
raise ValueError(f"unsupported file type: {ext}")
diff --git a/studio/backend/tests/test_rag_text_encoding.py b/studio/backend/tests/test_rag_text_encoding.py
new file mode 100644
index 00000000000..79c978f9d4d
--- /dev/null
+++ b/studio/backend/tests/test_rag_text_encoding.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import codecs
+
+from core.rag import parsers
+
+GREETING = "Sehr geehrte Frau Müller,\nviele Grüße aus Köln – 5 €.\n"
+
+
+def _text(tmp_path, name: str, data: bytes) -> str:
+ path = tmp_path / name
+ path.write_bytes(data)
+ return "\n".join(page.text for page in parsers.parse(str(path)))
+
+
+def test_a_windows_1252_text_file_keeps_its_accented_letters(tmp_path):
+ assert _text(tmp_path, "letter.txt", GREETING.encode("cp1252")) == GREETING
+
+
+def test_a_latin_1_markdown_file_keeps_its_accented_letters(tmp_path):
+ markdown = "# Überblick\nCafé und Crème brûlée\n"
+ assert _text(tmp_path, "notes.md", markdown.encode("latin-1")) == markdown
+
+
+def test_utf8_is_read_as_before(tmp_path):
+ assert _text(tmp_path, "plain.txt", GREETING.encode("utf-8")) == GREETING
+ assert _text(tmp_path, "bom.txt", GREETING.encode("utf-8-sig")) == GREETING
+
+
+def test_a_damaged_byte_in_utf8_costs_only_that_byte(tmp_path):
+ data = GREETING.encode("utf-8") + b"\xff"
+ assert _text(tmp_path, "damaged.txt", data) == GREETING + "�"
+
+
+def test_a_short_utf8_file_with_a_truncated_character_stays_utf8(tmp_path):
+ assert _text(tmp_path, "cut.txt", b"caf\xc3\xa9\xc3") == "caf\u00e9\ufffd"
+ page = b"<meta charset=utf-8><p>caf\xc3\xa9\xff</p>"
+ assert _text(tmp_path, "cut.html", page) == "caf\u00e9\ufffd"
+
+
+def test_a_utf8_byte_order_mark_wins_over_a_damaged_byte_and_a_declared_charset(tmp_path):
+ assert _text(tmp_path, "bom.txt", b"\xef\xbb\xbfhello\xff") == "hello\ufffd"
+ page = '<meta charset="shift_jis"><p>café \xff</p>'.encode("utf-8").replace(
+ b"\xc3\xbf", b"\xff"
+ )
+ assert _text(tmp_path, "bom.html", codecs.BOM_UTF8 + page) == "café \ufffd"
+
+
+def test_a_utf16_file_is_read_by_its_byte_order_mark(tmp_path):
+ assert _text(tmp_path, "wide.txt", GREETING.encode("utf-16")) == GREETING
+
+
+def test_an_html_page_is_read_in_the_charset_it_declares(tmp_path):
+ for charset, text in (("shift_jis", "日本語のページ"), ("gbk", "中文网页")):
+ page = f'<html><head><meta charset="{charset}"></head><body><p>{text}</p></body></html>'
+ assert _text(tmp_path, f"{charset}.html", page.encode(charset)) == text
+
+
+def test_a_declared_iso_2022_jp_page_is_not_read_as_its_escape_sequences(tmp_path):
+ page = (
+ '<html><head><meta charset="iso-2022-jp"></head><body><p>日本語のページ</p></body></html>'
+ )
+ assert _text(tmp_path, "jis.html", page.encode("iso2022_jp")) == "日本語のページ"
+
+
+def test_an_http_equiv_content_type_declares_the_charset_too(tmp_path):
+ page = (
+ '<html><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">'
+ "</head><body><p>Dobrý den, Łódź</p></body></html>"
+ )
+ assert _text(tmp_path, "latin2.html", page.encode("iso-8859-2")) == "Dobrý den, Łódź"
+
+
+def test_an_undeclared_windows_1252_page_keeps_its_accented_letters(tmp_path):
+ page = "<html><body><p>Grüße aus Köln</p></body></html>"
+ assert _text(tmp_path, "page.html", page.encode("cp1252")) == "Grüße aus Köln"
+
+
+def test_a_declared_charset_that_cannot_have_written_the_page_is_ignored(tmp_path):
+ for charset in ("no-such-charset", "utf-16", "punycode", "idna"):
+ page = f'<html><head><meta charset="{charset}"></head><body><p>Grüße</p></body></html>'
+ assert _text(tmp_path, "odd.html", page.encode("cp1252")) == "Grüße", charset
+
+
+def test_crlf_and_cr_line_endings_become_newlines(tmp_path):
+ windows = "Para one.\r\nStill one.\r\n\r\nPara two.\r\n"
+ expected = "Para one.\nStill one.\n\nPara two.\n"
+ assert _text(tmp_path, "crlf.txt", windows.encode("utf-8")) == expected
+ assert _text(tmp_path, "crlf_ansi.txt", windows.encode("cp1252")) == expected
+ assert _text(tmp_path, "crlf_wide.txt", windows.encode("utf-16")) == expected
+ assert _text(tmp_path, "cr.md", b"a\rb\r") == "a\nb\n"
+
+
+def test_a_stray_valid_utf8_sequence_does_not_keep_a_windows_1252_file_as_utf8(tmp_path):
+ # Word puts a no-break space before "»" in French; "à\xa0»" is also valid UTF-8.
+ french = "Il a dit «\xa0voilà\xa0» à l'été, café, crème.\n"
+ assert _text(tmp_path, "fr.txt", french.encode("cp1252")) == french
+
+
+def test_a_declared_charset_decodes_as_its_browser_superset(tmp_path):
+ for charset, codec, text in (
+ ("iso-8859-1", "cp1252", "“smart” quotes cost €5"),
+ ("shift_jis", "cp932", "① 髙橋"),
+ ("gb2312", "gbk", "镕"),
+ ):
+ page = f'<html><head><meta charset="{charset}"></head><body><p>{text}</p></body></html>'
+ assert _text(tmp_path, f"{charset}.html", page.encode(codec)) == text, charset