~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(loaders): read JSON and YAML uploads in the encoding they were written in (#7731)
Lukas9183f432987a
diff --git a/changelog.d/7731.bugfix.md b/changelog.d/7731.bugfix.mdnew file mode 100644index 0000000000..8b57b26442--- /dev/null+++ b/changelog.d/7731.bugfix.md@@ -0,0 +1,6 @@+JSON and YAML uploads are read in the encoding they were written in, as text and CSV uploads+already are: a UTF-8 byte-order mark no longer turns a JSON file into raw text, and UTF-16 or+Windows-1252 files are no longer refused with a decoding error. A file in another legacy+encoding that Windows-1252 can decode, KOI8-R for one, is now read as Windows-1252 text instead+of being refused, while a file with bytes Windows-1252 leaves undefined, as most Shift_JIS text+has, is still refused. That is the trade-off text uploads already make.diff --git a/src/local_deep_research/document_loaders/json_loader.py b/src/local_deep_research/document_loaders/json_loader.pyindex 68e2afea18..ac285d86a0 100644--- a/src/local_deep_research/document_loaders/json_loader.py+++ b/src/local_deep_research/document_loaders/json_loader.py@@ -13,6 +13,8 @@ from langchain_core.document_loaders import BaseLoaderfrom langchain_core.documents import Documentfrom loguru import logger+from .text_encoding import _file_encoding+def extract_strings_from_json(data: Any, path: str = ""@@ -50,7 +52,7 @@ class SimpleJSONLoader(BaseLoader):def __init__(self,file_path: str | Path,- encoding: str = "utf-8",+ encoding: str | None = None,include_paths: bool = True,):"""@@ -58,7 +60,7 @@ class SimpleJSONLoader(BaseLoader):Args:file_path: Path to the JSON file- encoding: File encoding (default: utf-8)+ encoding: File encoding (default: detected, as for text uploads)include_paths: If True, include JSON paths with values (default: True)"""self.file_path = Path(file_path)@@ -73,7 +75,12 @@ class SimpleJSONLoader(BaseLoader):Document objects containing the extracted text"""try:- with open(self.file_path, encoding=self.encoding) as f:+ # Detected like a text upload's: a byte-order mark is dropped, and UTF-16+ # from PowerShell or Windows-1252 from Notepad reads as text+ encoding = self.encoding or _file_encoding(self.file_path)+ # Recorded as for text uploads, when it was detected+ detected = {} if self.encoding else {"detected_encoding": encoding}+ with open(self.file_path, encoding=encoding) as f:content = f.read()try:@@ -86,6 +93,7 @@ class SimpleJSONLoader(BaseLoader):metadata={"source": str(self.file_path),"parse_error": True,+ **detected,},)return@@ -110,6 +118,7 @@ class SimpleJSONLoader(BaseLoader):"source": str(self.file_path),"file_type": "json","string_count": len(string_pairs),+ **detected,},)diff --git a/src/local_deep_research/document_loaders/text_encoding.py b/src/local_deep_research/document_loaders/text_encoding.pyindex 50f3faea4f..f614181e15 100644--- a/src/local_deep_research/document_loaders/text_encoding.py+++ b/src/local_deep_research/document_loaders/text_encoding.py@@ -14,9 +14,9 @@ and Windows-1252, the Western-European legacy encoding Notepad and Excel write.A file in any other legacy encoding has one of two outcomes:- it is refused, when its bytes include one Windows-1252 leaves undefined or- decode into control characters (cp866, for one);+ decode into control characters (cp866, and most Shift_JIS text);- otherwise it is read as Windows-1252 and stored as mojibake (KOI8-R,- Shift_JIS, GB18030, EUC-KR and EUC-JP text all decode this way).+ GB18030, EUC-KR and EUC-JP text all decode this way).The encoding each file was read in is recorded on its documents as``detected_encoding``, for callers that keep the documents. The upload pathdiff --git a/src/local_deep_research/document_loaders/yaml_loader.py b/src/local_deep_research/document_loaders/yaml_loader.pyindex c874a94f31..71a66539de 100644--- a/src/local_deep_research/document_loaders/yaml_loader.py+++ b/src/local_deep_research/document_loaders/yaml_loader.py@@ -13,6 +13,8 @@ from langchain_core.document_loaders import BaseLoaderfrom langchain_core.documents import Documentfrom loguru import logger+from .text_encoding import _file_encoding+class YAMLLoader(BaseLoader):"""@@ -22,13 +24,13 @@ class YAMLLoader(BaseLoader):and semantic search. Complex structures are preserved in their YAML format."""- def __init__(self, file_path: str | Path, encoding: str = "utf-8"):+ def __init__(self, file_path: str | Path, encoding: str | None = None):"""Initialize the YAML loader.Args:file_path: Path to the YAML file- encoding: File encoding (default: utf-8)+ encoding: File encoding (default: detected, as for text uploads)"""self.file_path = Path(file_path)self.encoding = encoding@@ -41,7 +43,12 @@ class YAMLLoader(BaseLoader):Document objects containing the YAML content as text"""try:- with open(self.file_path, encoding=self.encoding) as f:+ # Detected like a text upload's: a byte-order mark is dropped, and UTF-16+ # from PowerShell or Windows-1252 from Notepad reads as text+ encoding = self.encoding or _file_encoding(self.file_path)+ # Recorded as for text uploads, when it was detected+ detected = {} if self.encoding else {"detected_encoding": encoding}+ with open(self.file_path, encoding=encoding) as f:content = f.read()# Parse YAML to validate and normalize@@ -55,6 +62,7 @@ class YAMLLoader(BaseLoader):metadata={"source": str(self.file_path),"parse_error": True,+ **detected,},)return@@ -78,6 +86,7 @@ class YAMLLoader(BaseLoader):metadata={"source": str(self.file_path),"file_type": "yaml",+ **detected,},)diff --git a/tests/document_loaders/test_json_loader_behavior.py b/tests/document_loaders/test_json_loader_behavior.pyindex cab3d70e73..7c68e3e540 100644--- a/tests/document_loaders/test_json_loader_behavior.py+++ b/tests/document_loaders/test_json_loader_behavior.py@@ -182,14 +182,14 @@ class TestSimpleJSONLoaderInit:loader = SimpleJSONLoader(Path("/path/to/file.json"))assert loader.file_path == Path("/path/to/file.json")- def test_default_encoding_is_utf8(self):- """Default encoding is utf-8."""+ def test_default_encoding_is_detected(self):+ """Without an encoding the file's own is detected, as for text uploads."""from local_deep_research.document_loaders.json_loader import (SimpleJSONLoader,)loader = SimpleJSONLoader("/path/to/file.json")- assert loader.encoding == "utf-8"+ assert loader.encoding is Nonedef test_accepts_custom_encoding(self):"""Accepts custom encoding."""diff --git a/tests/document_loaders/test_loader_hostile_input.py b/tests/document_loaders/test_loader_hostile_input.pyindex 03d5412172..60190eff98 100644--- a/tests/document_loaders/test_loader_hostile_input.py+++ b/tests/document_loaders/test_loader_hostile_input.py@@ -310,13 +310,11 @@ class TestStructuredTextParseFailuresAreSoftFailures:assert "parse_error" not in documents[0].metadata@pytest.mark.parametrize("extension", [".json", ".yaml", ".yml"])- def test_undecodable_bytes_raise_unicode_error_and_are_handled(- self, extension- ):- # The loaders open() with encoding="utf-8" and no errors= handler,- # so invalid UTF-8 raises before any parsing happens.+ def test_undecodable_bytes_are_refused_and_handled(self, extension):+ # The loaders detect the encoding the way text uploads do, so bytes that+ # decode into no text are refused before any parsing happens.undecodable = b"\xff\xfe\x00\x01not utf-8"- with pytest.raises(UnicodeDecodeError):+ with pytest.raises(ValueError, match="no recognized text encoding"):load_from_bytes(undecodable, extension, f"bad{extension}")assert (extract_text_from_bytes(undecodable, extension, f"bad{extension}")diff --git a/tests/document_loaders/test_text_encoding.py b/tests/document_loaders/test_text_encoding.pyindex 554758f033..306cb1d105 100644--- a/tests/document_loaders/test_text_encoding.py+++ b/tests/document_loaders/test_text_encoding.py@@ -154,3 +154,50 @@ class TestCsvUploads:assert [d.page_content for d in _load(path)][0] == ("Name: Müller\nStadt: Köln")+++class TestStructuredUploads:+ """JSON and YAML uploads are decoded the way text uploads are."""++ @pytest.mark.parametrize("suffix", [".json", ".yaml"])+ @pytest.mark.parametrize("encoding", ["utf-8-sig", "utf-16", "cp1252"])+ def test_a_json_or_yaml_file_is_read_in_its_encoding(+ self, tmp_path, suffix, encoding+ ):+ # Notepad saves UTF-8 with a byte-order mark or as Windows-1252, and+ # PowerShell's Out-File writes UTF-16+ path = tmp_path / f"data{suffix}"+ path.write_bytes('{"city": "Köln", "note": "Groß"}'.encode(encoding))++ [document] = _load(path)++ assert "Köln" in document.page_content+ assert "Groß" in document.page_content+ assert not document.metadata.get("parse_error")++ @pytest.mark.parametrize("suffix", [".json", ".yaml"])+ @pytest.mark.parametrize(+ "encoding,detected",+ [("utf-8", "utf-8-sig"), ("cp1252", "cp1252"), ("utf-16", "utf-16")],+ )+ def test_the_encoding_read_is_recorded_on_the_document(+ self, tmp_path, suffix, encoding, detected+ ):+ path = tmp_path / f"data{suffix}"+ path.write_bytes('{"city": "Köln"}'.encode(encoding))++ assert [d.metadata["detected_encoding"] for d in _load(path)] == [+ detected+ ]++ @pytest.mark.parametrize("suffix", [".json", ".yaml"])+ def test_a_file_that_does_not_parse_records_the_encoding_too(+ self, tmp_path, suffix+ ):+ path = tmp_path / f"broken{suffix}"+ path.write_bytes('{"city": "Köln", "note": [}'.encode("cp1252"))++ [document] = _load(path)++ assert document.metadata["parse_error"] is True+ assert document.metadata["detected_encoding"] == "cp1252"diff --git a/tests/document_loaders/test_yaml_loader_behavior.py b/tests/document_loaders/test_yaml_loader_behavior.pyindex d19f1580b4..e9c8595e9c 100644--- a/tests/document_loaders/test_yaml_loader_behavior.py+++ b/tests/document_loaders/test_yaml_loader_behavior.py@@ -27,12 +27,12 @@ class TestYAMLLoaderInit:loader = YAMLLoader(Path("/path/to/file.yaml"))assert loader.file_path == Path("/path/to/file.yaml")- def test_default_encoding_is_utf8(self):- """Default encoding is utf-8."""+ def test_default_encoding_is_detected(self):+ """Without an encoding the file's own is detected, as for text uploads."""from local_deep_research.document_loaders.yaml_loader import YAMLLoaderloader = YAMLLoader("/path/to/file.yaml")- assert loader.encoding == "utf-8"+ assert loader.encoding is Nonedef test_accepts_custom_encoding(self):"""Accepts custom encoding."""