Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(docreader): recognize Unicode BOMs before legacy decoding (#4498)

fengyue-xve90db95d81161
diff --git a/docreader/tests/test_decode_bytes_bom.py b/docreader/tests/test_decode_bytes_bom.py
new file mode 100644
index 000000000..746726d6a
--- /dev/null
+++ b/docreader/tests/test_decode_bytes_bom.py
@@ -0,0 +1,36 @@
+"""Unicode upload signatures must be decoded before legacy encodings."""
+
+import codecs
+import unittest
+
+from docreader.utils.endecode import decode_bytes
+
+
+class DecodeBytesBOMTests(unittest.TestCase):
+ def test_unicode_signature_is_removed(self):
+ for encoding in ["utf-8-sig", "utf-16", "utf-32"]:
+ for text in ["# Heading\nHello", "# 中文\n| 名称 | 值 |"]:
+ with self.subTest(encoding=encoding, text=text):
+ self.assertEqual(decode_bytes(text.encode(encoding)), text)
+
+ def test_big_endian_signature(self):
+ text = "# 中文\nHello"
+ for bom, encoding in [
+ (codecs.BOM_UTF16_BE, "utf-16-be"),
+ (codecs.BOM_UTF32_BE, "utf-32-be"),
+ ]:
+ with self.subTest(encoding=encoding):
+ self.assertEqual(decode_bytes(bom + text.encode(encoding)), text)
+
+ def test_custom_encoding_order_is_respected(self):
+ data = "hello".encode("utf-8-sig")
+ self.assertEqual(decode_bytes(data, encodings=["latin-1"]), data.decode("latin-1"))
+
+ def test_unsigned_text_preserves_legacy_detection(self):
+ for encoding in ["utf-8", "gb18030"]:
+ with self.subTest(encoding=encoding):
+ text = "中文"
+ self.assertEqual(decode_bytes(text.encode(encoding)), text)
+
+ def test_incomplete_signature_uses_existing_fallback(self):
+ self.assertIsInstance(decode_bytes(codecs.BOM_UTF16_LE + b"x"), str)
diff --git a/docreader/utils/endecode.py b/docreader/utils/endecode.py
index d7f675a86..6d18da40d 100644
--- a/docreader/utils/endecode.py
+++ b/docreader/utils/endecode.py
@@ -9,9 +9,10 @@ with a focus on image and text data conversion:
"""
import base64
+import codecs
import io
import logging
-from typing import List, Union
+from typing import List, Optional, Union
import numpy as np
from PIL import Image
@@ -136,18 +137,13 @@ def encode_bytes(content: str) -> bytes:
def decode_bytes(
content: bytes,
- encodings: List[str] = [
- "utf-8",
- "gb18030",
- "gb2312",
- "gbk",
- "big5",
- "ascii",
- "latin-1",
- ],
+ encodings: Optional[List[str]] = None,
) -> str:
"""Decode bytes to string with automatic encoding detection.
+ With default encodings, a Unicode byte order mark is decoded first.
+ Explicit encoding lists retain their supplied priority.
+
This function attempts to decode bytes using multiple encoding formats
in order of priority. It's particularly useful for handling text files
with unknown or mixed encodings, especially for Chinese text.
@@ -181,6 +177,27 @@ def decode_bytes(
>>> # Decode with custom encodings
>>> text = decode_bytes(content, encodings=["utf-8", "gbk"])
"""
+ if encodings is None:
+ # UTF-32 LE starts with the UTF-16 LE signature: check it first.
+ for signatures, encoding in [
+ ((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE), "utf-32"),
+ ((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE), "utf-16"),
+ ((codecs.BOM_UTF8,), "utf-8-sig"),
+ ]:
+ if content.startswith(signatures):
+ try:
+ return content.decode(encoding)
+ except UnicodeDecodeError:
+ break
+ encodings = [
+ "utf-8",
+ "gb18030",
+ "gb2312",
+ "gbk",
+ "big5",
+ "ascii",
+ "latin-1",
+ ]
# Try decoding with each encoding format in order
for encoding in encodings:
try: