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: decode UTF-16 without BOM and repair .doc pieces split mid-surrogate (#16969)
DimitriChrysafisbb377fef6f69
diff --git a/studio/backend/core/rag/office_formats.py b/studio/backend/core/rag/office_formats.pyindex f866fa4933c..7f8bd1b3953 100644--- a/studio/backend/core/rag/office_formats.py+++ b/studio/backend/core/rag/office_formats.py@@ -1294,8 +1294,13 @@ def doc(path: str) -> list[Section]:chars.append(word[offset : offset + hi - lo].decode("cp1252", "replace"))else:offset = fc + 2 * (lo - start)- chars.append(word[offset : offset + 2 * (hi - lo)].decode("utf-16-le", "replace"))- return _word_text("".join(chars))+ raw = word[offset : offset + 2 * (hi - lo)]+ if len(raw) & 1:+ # Corrupt piece ending mid-character: one U+FFFD.+ raw = raw[:-1] + b"\xfd\xff"+ chars.append(raw.decode("utf-16-le", "surrogatepass"))+ text = "".join(chars).encode("utf-16-le", "surrogatepass").decode("utf-16-le", "replace")+ return _word_text(text)# Stories follow the main text in this order; headers and comments are left out, as for .docx.starts = [sum(ccps[:i]) for i in range(len(ccps))]diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.pyindex 97f8deecb9b..5d4acf4b576 100644--- a/studio/backend/core/rag/parsers.py+++ b/studio/backend/core/rag/parsers.py@@ -1718,6 +1718,7 @@ def _docx_mark_notes(document):_HIGH_BYTES = bytes(range(0x80, 0x100))_ASCII_LETTERS = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"_HIGH_RUN = re.compile(rb"[\x80-\xff]+")+_CONTROL_CHARS = re.compile(r"[\x00-\x08\x0e-\x1f\x7f-\x9f]")def _declared_charset(data: bytes) -> str | None:@@ -1737,6 +1738,27 @@ def _decode_text(data: bytes, *, html: bool = False) -> str:):if data.startswith(bom):return data.decode(codec, errors = "replace")+ # No BOM: NULs dominating one side of the byte pairs mean ASCII-heavy UTF-16.+ if len(data) >= 8:+ pairs = even_nulls = odd_nulls = 0+ for i in range(0, min(len(data), 1024) - 1, 2):+ if data[i : i + 2] == b"\0\0":+ break+ pairs += 1+ if data[i] == 0:+ even_nulls += 1+ elif data[i + 1] == 0:+ odd_nulls += 1+ codec = None+ if even_nulls >= 4 and odd_nulls * 10 <= even_nulls and 2 * even_nulls > pairs:+ codec = "utf-16-be"+ elif odd_nulls >= 4 and even_nulls * 10 <= odd_nulls and 2 * odd_nulls > pairs:+ codec = "utf-16-le"+ if codec is not None:+ decoded = data.decode(codec, errors = "replace")+ # Real text has no C0/C1 controls; NUL-shaped binaries fall through to the binary guard.+ if _CONTROL_CHARS.search(decoded) is None:+ return decodedtry:text = data.decode("utf-8")except UnicodeDecodeError:diff --git a/studio/backend/routes/data_recipe/seed.py b/studio/backend/routes/data_recipe/seed.pyindex f43cebe6845..8f9048658df 100644--- a/studio/backend/routes/data_recipe/seed.py+++ b/studio/backend/routes/data_recipe/seed.py@@ -1149,7 +1149,8 @@ def inspect_seed_dataset(def _extract_text_from_file(file_path: Path, ext: str) -> str:"""Extract text from an uploaded file by extension, to markdown where possible."""if ext in {".txt", ".md"}:- raw = file_path.read_text(encoding = "utf-8", errors = "ignore")+ from core.rag import parsers+ raw = "\n\n".join(page.text for page in parsers.parse(str(file_path)))elif ext == ".pdf":from core.rag import config, pdf_ocrraw = pdf_ocr.extract_text(str(file_path), config.OCR_SCANNED, config.OCR_MAX_PAGES)diff --git a/studio/backend/tests/test_data_recipe_seed.py b/studio/backend/tests/test_data_recipe_seed.pyindex 1871cc0f52c..06d12a9999e 100644--- a/studio/backend/tests/test_data_recipe_seed.py+++ b/studio/backend/tests/test_data_recipe_seed.py@@ -506,6 +506,15 @@ def test_text_extraction_falls_back_to_raw_without_the_plugin(monkeypatch, tmp_passert seed_route._extract_text_from_file(source, ".txt") == "a\n\n\n\nb"+def test_text_extraction_reads_a_utf16_file_without_a_byte_order_mark(monkeypatch, tmp_path):+ seed_route = _load_seed_route(monkeypatch, tmp_path)+ _without_plugin(monkeypatch, seed_route)+ source = tmp_path / "wide.txt"+ source.write_bytes("héllo wörld\n".encode("utf-16-le"))++ assert seed_route._extract_text_from_file(source, ".txt") == "héllo wörld\n"++def test_plugin_resolution_survives_a_reload_and_normalizes(monkeypatch, tmp_path):"""With the plugin installed the same call sites still go through it."""pytest.importorskip("data_designer_unstructured_seed")diff --git a/studio/backend/tests/test_rag_office_formats.py b/studio/backend/tests/test_rag_office_formats.pyindex 4e3b6976842..0c8283204c9 100644--- a/studio/backend/tests/test_rag_office_formats.py+++ b/studio/backend/tests/test_rag_office_formats.py@@ -981,6 +981,45 @@ def test_doc_reads_compressed_and_unicode_pieces_and_note_stories(tmp_path):)+def test_doc_repairs_a_surrogate_pair_split_across_pieces(tmp_path):+ word = bytearray(0x1800)+ struct.pack_into("<HH", word, 0, 0xA5EC, 0xC1)+ struct.pack_into("<H", word, 0x0A, 0x0200)+ struct.pack_into("<H", word, 32, 14) # csw+ struct.pack_into("<H", word, 62, 22) # cslw+ struct.pack_into("<i", word, 64 + 3 * 4, 4) # ccpText+ struct.pack_into("<H", word, 152, 93) # cbRgFcLcb+ word[0x1400:0x1404] = "A\ud83d".encode("utf-16-le", "surrogatepass")+ word[0x1410:0x1414] = "\ude00B".encode("utf-16-le", "surrogatepass")+ cps = [0, 2, 4]+ pcds = [0x1400, 0x1410]+ plc = struct.pack("<3I", *cps) + b"".join(struct.pack("<HIH", 0, fc, 0) for fc in pcds)+ clx = b"\x02" + struct.pack("<I", len(plc)) + plc+ struct.pack_into("<II", word, 154 + 33 * 8, 0, len(clx)) # fcClx, lcbClx+ path = tmp_path / "split.doc"+ path.write_bytes(compound_file({("WordDocument",): bytes(word), ("1Table",): clx}))+ assert _text(path) == "A\U0001f600B"+++def test_doc_leaves_one_replacement_char_when_a_piece_ends_mid_character(tmp_path):+ word = bytearray(0x1800)+ struct.pack_into("<HH", word, 0, 0xA5EC, 0xC1)+ struct.pack_into("<H", word, 0x0A, 0x0200)+ struct.pack_into("<H", word, 32, 14) # csw+ struct.pack_into("<H", word, 62, 22) # cslw+ struct.pack_into("<i", word, 64 + 3 * 4, 2) # ccpText+ struct.pack_into("<H", word, 152, 93) # cbRgFcLcb+ word[0x17FD:0x1800] = b"A\x00B"+ cps = [0, 2]+ pcds = [0x17FD]+ plc = struct.pack("<2I", *cps) + b"".join(struct.pack("<HIH", 0, fc, 0) for fc in pcds)+ clx = b"\x02" + struct.pack("<I", len(plc)) + plc+ struct.pack_into("<II", word, 154 + 33 * 8, 0, len(clx)) # fcClx, lcbClx+ path = tmp_path / "clipped.doc"+ path.write_bytes(compound_file({("WordDocument",): bytes(word), ("1Table",): clx}))+ assert _text(path) == "A\ufffd"++def test_xls_reads_errors_and_continued_formula_strings(tmp_path):long_text = "A" * 8000 + "Ж" * 300string = struct.pack("<HB", len(long_text), 0) + b"A" * 8000diff --git a/studio/backend/tests/test_rag_text_encoding.py b/studio/backend/tests/test_rag_text_encoding.pyindex ea241f5eef4..9887057859b 100644--- a/studio/backend/tests/test_rag_text_encoding.py+++ b/studio/backend/tests/test_rag_text_encoding.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport codecs+import pytest+from core.rag import parsersGREETING = "Sehr geehrte Frau Müller,\nviele Grüße aus Köln – 5 €.\n"@@ -53,6 +55,48 @@ 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_a_utf16_file_without_a_byte_order_mark_still_reads_as_text(tmp_path):+ for codec in ("utf-16-le", "utf-16-be"):+ assert _text(tmp_path, f"no_bom_{codec}.txt", GREETING.encode(codec)) == GREETING, codec+ assert _text(tmp_path, "tiny.txt", b"H\x00i\x00!\x00!\x00") == "Hi!!"+++def test_a_utf16_source_file_without_a_byte_order_mark_is_not_mistaken_for_binary(tmp_path):+ table = "name,score\nalpha,1\nbeta,2\n"+ assert _text(tmp_path, "scores.csv", table.encode("utf-16-le")) == table+++def test_utf16_detection_survives_an_astral_or_ideographic_character(tmp_path):+ text = "first line 😀 second line, more text follows here. 次\u3000の行\n"+ for codec in ("utf-16-le", "utf-16-be"):+ assert _text(tmp_path, f"astral_{codec}.txt", text.encode(codec)) == text+++def test_a_jpeg_header_is_not_read_as_utf16(tmp_path):+ jpeg = b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x48\x00\x48\x00\x00" + bytes(64)+ assert "JFIF" in _text(tmp_path, "photo.txt", jpeg)+++def test_a_binary_file_is_still_refused_under_a_source_extension(tmp_path):+ blob = bytes(range(256)) * 8+ path = tmp_path / "blob.csv"+ path.write_bytes(blob)+ with pytest.raises(ValueError, match = "binary"):+ parsers.parse(str(path))+++def test_a_nul_shaped_binary_is_still_refused_under_a_source_extension(tmp_path):+ for name, blob in (("readings.csv", b"\x01\x00" * 300), ("flags.csv", b"\x80\x00" * 300)):+ path = tmp_path / name+ path.write_bytes(blob)+ with pytest.raises(ValueError, match = "binary"):+ parsers.parse(str(path))+++def test_a_short_utf16_fragment_is_left_to_the_existing_heuristics(tmp_path):+ assert _text(tmp_path, "short.txt", b"H\x00i\x00") == "H\x00i\x00"++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>'