~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 .txt, .csv and .tsv uploads in the encoding they were written in (#6830)
Lukase04b0af81802
diff --git a/changelog.d/6830.bugfix.md b/changelog.d/6830.bugfix.mdnew file mode 100644index 0000000000..4173a6f01a--- /dev/null+++ b/changelog.d/6830.bugfix.md@@ -0,0 +1 @@+Text, CSV and TSV uploads that are not UTF-8 are read again instead of being refused: Windows-1252 ("ANSI") files, as Notepad and Excel write them on Western-European Windows, and UTF-16 or UTF-32 files with a byte-order mark. A UTF-8 byte-order mark no longer ends up in the text or in the first CSV column name. Files in other legacy encodings (Cyrillic, Chinese, Japanese, Korean) are still either refused or read as Windows-1252; the encoding a file was read in is recorded on each of its documents as `detected_encoding`.diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.pyindex 32606f36fd..7446a84029 100644--- a/src/local_deep_research/document_loaders/bytes_loader.py+++ b/src/local_deep_research/document_loaders/bytes_loader.py@@ -143,7 +143,10 @@ def extract_text_from_bytes()return Noneexcept ValueError:- logger.warning("Unsupported format")+ logger.warning(+ f"No text extracted from {filename}: unsupported format or "+ "unrecognized text encoding"+ )return Noneexcept Exception:logger.exception(f"Error extracting text from {filename}")diff --git a/src/local_deep_research/document_loaders/loader_registry.py b/src/local_deep_research/document_loaders/loader_registry.pyindex e041b83fd6..3bd844039e 100644--- a/src/local_deep_research/document_loaders/loader_registry.py+++ b/src/local_deep_research/document_loaders/loader_registry.py@@ -11,12 +11,10 @@ from pathlib import Pathfrom typing import Optionalfrom langchain_community.document_loaders import (- CSVLoader,EverNoteLoader,MHTMLLoader,NotebookLoader,PyPDFLoader,- TextLoader,TomlLoader,UnstructuredEmailLoader,UnstructuredExcelLoader,@@ -85,6 +83,7 @@ except ImportError:# Import our custom loadersfrom .json_loader import SimpleJSONLoader+from .text_encoding import EncodingAwareCSVLoader, EncodingAwareTextLoaderfrom .xls_loader import XLSLoaderfrom .yaml_loader import YAMLLoader@@ -149,10 +148,10 @@ LOADER_REGISTRY: dict = {"loader_class": PyPDFLoader,"loader_kwargs": {},},- # Plain text+ # Plain text, read in the encoding it was written in".txt": {- "loader_class": TextLoader,- "loader_kwargs": {"encoding": "utf-8", "autodetect_encoding": True},+ "loader_class": EncodingAwareTextLoader,+ "loader_kwargs": {},},# Markdown".md": {@@ -165,7 +164,7 @@ LOADER_REGISTRY: dict = {},# CSV (Word/Excel are registered below, gated on their runtime deps)".csv": {- "loader_class": CSVLoader,+ "loader_class": EncodingAwareCSVLoader,"loader_kwargs": {},},# HTML@@ -266,9 +265,9 @@ LOADER_REGISTRY[".eml"] = {"loader_kwargs": {},}-# TSV (Tab-Separated Values) - use CSVLoader with tab delimiter+# TSV (Tab-Separated Values) - the CSV loader with a tab delimiterLOADER_REGISTRY[".tsv"] = {- "loader_class": CSVLoader,+ "loader_class": EncodingAwareCSVLoader,"loader_kwargs": {"csv_args": {"delimiter": "\t"}},}diff --git a/src/local_deep_research/document_loaders/text_encoding.py b/src/local_deep_research/document_loaders/text_encoding.pynew file mode 100644index 0000000000..b09640f7f2--- /dev/null+++ b/src/local_deep_research/document_loaders/text_encoding.py@@ -0,0 +1,109 @@+"""+Read text uploads in the encoding they were written in.++LangChain's ``autodetect_encoding`` passes every candidate that+``chardet.detect_all`` returns to ``FileEncoding(**candidate)``. chardet 7+adds a ``mime_type`` key to each candidate, so detection raises ``TypeError``+and every ``.txt`` file that is not UTF-8 is refused, readable or not. With an+older chardet, the same detection decodes binary bytes into text. Which of the+two happened depended on the installed chardet (#6532).++These loaders decide the encoding themselves, the same way everywhere. The+scope is deliberately narrow: UTF-8, UTF-16 and UTF-32 with a byte-order mark,+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);+- 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).++The encoding each file was read in is recorded on its documents as+``detected_encoding``, for callers that keep the documents. The upload path+joins their text in ``extract_text_from_bytes`` and does not keep it yet+(#6836).+"""++import re+from collections.abc import Iterator+from pathlib import Path++from langchain_community.document_loaders import CSVLoader, TextLoader+from langchain_core.documents import Document++# Characters that legacy text does not contain: NUL and the C0 controls other+# than tab, line feed, vertical tab, form feed, carriage return, the DOS+# end-of-file mark (SUB) and escape.+_NOT_TEXT = re.compile(r"[\x00-\x08\x0e-\x19\x1c-\x1f]")+++def _fallback_encodings(raw: bytes) -> list[str]:+ # UTF-32's little-endian mark begins with UTF-16's.+ if raw.startswith((b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff")):+ return ["utf-32", "cp1252"]+ if raw.startswith((b"\xff\xfe", b"\xfe\xff")):+ return ["utf-16", "cp1252"]+ # What Notepad and Excel write on Western-European Windows ("ANSI").+ return ["cp1252"]+++def detect_text_encoding(raw: bytes) -> str | None:+ """+ Return the encoding that decodes ``raw`` into text, or None.++ Bytes that are UTF-8, with or without a byte-order mark, are read as+ UTF-8, as before. Other bytes are read as UTF-16 or UTF-32 when they start+ with its byte-order mark, and otherwise as Windows-1252, but only when the+ result is text: bytes that decode into control characters are refused.+ """+ try:+ raw.decode("utf-8-sig")+ return "utf-8-sig"+ except UnicodeDecodeError:+ pass+ for encoding in _fallback_encodings(raw):+ try:+ text = raw.decode(encoding)+ except UnicodeDecodeError:+ continue+ if not _NOT_TEXT.search(text):+ return encoding+ return None+++def _file_encoding(file_path: str | Path) -> str:+ encoding = detect_text_encoding(Path(file_path).read_bytes())+ if encoding is None:+ raise ValueError(+ f"{Path(file_path).name}: no recognized text encoding (tried "+ "UTF-8, UTF-16 or UTF-32 with a byte-order mark, and "+ "Windows-1252)"+ )+ return encoding+++def _with_encoding(+ documents: Iterator[Document], encoding: str+) -> Iterator[Document]:+ for document in documents:+ document.metadata["detected_encoding"] = encoding+ yield document+++class EncodingAwareTextLoader(TextLoader):+ """A ``TextLoader`` that reads a file in the encoding it was written in."""++ def lazy_load(self) -> Iterator[Document]:+ self.encoding = _file_encoding(self.file_path)+ yield from _with_encoding(super().lazy_load(), self.encoding)+++class EncodingAwareCSVLoader(CSVLoader):+ """A ``CSVLoader`` that reads a file in the encoding it was written in.++ A byte-order mark is dropped rather than read into the first column name.+ """++ def lazy_load(self) -> Iterator[Document]:+ self.encoding = _file_encoding(self.file_path)+ yield from _with_encoding(super().lazy_load(), self.encoding)diff --git a/tests/document_loaders/test_loader_registry_behavior.py b/tests/document_loaders/test_loader_registry_behavior.pyindex 44c67d16a2..5c8b81aafa 100644--- a/tests/document_loaders/test_loader_registry_behavior.py+++ b/tests/document_loaders/test_loader_registry_behavior.py@@ -316,16 +316,19 @@ class TestGetLoaderClassForExtension:assert result is not Noneassert result[0] == YAMLLoader- def test_txt_has_encoding_kwargs(self):- """TXT loader has encoding kwargs."""+ def test_txt_loader_chooses_the_encoding_itself(self):+ """TXT loader detects the encoding, so the registry passes none."""from local_deep_research.document_loaders.loader_registry import (get_loader_class_for_extension,)+ from local_deep_research.document_loaders.text_encoding import (+ EncodingAwareTextLoader,+ )result = get_loader_class_for_extension(".txt")assert result is not None- kwargs = result[1]- assert "encoding" in kwargs+ assert result[0] is EncodingAwareTextLoader+ assert result[1] == {}class TestLoaderRegistry:diff --git a/tests/document_loaders/test_loader_registry_coverage.py b/tests/document_loaders/test_loader_registry_coverage.pyindex 95eb906e50..7399bf765f 100644--- a/tests/document_loaders/test_loader_registry_coverage.py+++ b/tests/document_loaders/test_loader_registry_coverage.py@@ -59,11 +59,11 @@ class TestRegistrySpecificLoaderClasses:"ext, expected_class_name",[(".pdf", "PyPDFLoader"),- (".txt", "TextLoader"),+ (".txt", "EncodingAwareTextLoader"),(".md", "UnstructuredMarkdownLoader"),(".markdown", "UnstructuredMarkdownLoader"),(".docx", "UnstructuredWordDocumentLoader"),- (".csv", "CSVLoader"),+ (".csv", "EncodingAwareCSVLoader"),(".xlsx", "UnstructuredExcelLoader"),(".xls", "XLSLoader"),(".html", "UnstructuredHTMLLoader"),@@ -71,7 +71,7 @@ class TestRegistrySpecificLoaderClasses:(".pptx", "UnstructuredPowerPointLoader"),(".xml", "UnstructuredXMLLoader"),(".eml", "UnstructuredEmailLoader"),- (".tsv", "CSVLoader"),+ (".tsv", "EncodingAwareCSVLoader"),(".json", "SimpleJSONLoader"),(".yaml", "YAMLLoader"),(".yml", "YAMLLoader"),@@ -91,9 +91,9 @@ class TestRegistrySpecificKwargs:"""Test that specific extensions carry the expected kwargs."""def test_txt_encoding_kwargs(self):+ # The loader detects the encoding itself; see text_encoding.py.entry = LOADER_REGISTRY[".txt"]- assert entry["loader_kwargs"]["encoding"] == "utf-8"- assert entry["loader_kwargs"]["autodetect_encoding"] is True+ assert entry["loader_kwargs"] == {}def test_tsv_delimiter_kwargs(self):entry = LOADER_REGISTRY[".tsv"]diff --git a/tests/document_loaders/test_loader_registry_deep_coverage.py b/tests/document_loaders/test_loader_registry_deep_coverage.pyindex 0afdac9579..083f3eebc2 100644--- a/tests/document_loaders/test_loader_registry_deep_coverage.py+++ b/tests/document_loaders/test_loader_registry_deep_coverage.py@@ -34,7 +34,7 @@ class TestGetLoaderClassForExtensionNoDot:result = get_loader_class_for_extension("txt")assert result is not Noneloader_class, kwargs = result- assert loader_class.__name__ == "TextLoader"+ assert loader_class.__name__ == "EncodingAwareTextLoader"def test_pdf_without_dot_resolves(self):from local_deep_research.document_loaders.loader_registry import (diff --git a/tests/document_loaders/test_loader_registry_edge_cases.py b/tests/document_loaders/test_loader_registry_edge_cases.pyindex 3f288d0d15..37c8eb1093 100644--- a/tests/document_loaders/test_loader_registry_edge_cases.py+++ b/tests/document_loaders/test_loader_registry_edge_cases.py@@ -94,15 +94,18 @@ class TestSpecialLoaderKwargs:entry = LOADER_REGISTRY[".tsv"]assert entry["loader_kwargs"]["csv_args"]["delimiter"] == "\t"- def test_txt_has_autodetect_encoding(self):- """TXT entry specifies autodetect_encoding=True."""+ def test_txt_does_not_use_langchain_autodetect_encoding(self):+ """TXT entry leaves the encoding to its loader, not autodetect_encoding.++ LangChain's autodetect raises TypeError with chardet 7 (#6532).+ """from local_deep_research.document_loaders.loader_registry import (LOADER_REGISTRY,)kwargs = LOADER_REGISTRY[".txt"]["loader_kwargs"]- assert kwargs["autodetect_encoding"] is True- assert kwargs["encoding"] == "utf-8"+ assert "autodetect_encoding" not in kwargs+ assert "encoding" not in kwargsdef test_notebook_include_outputs(self):"""Notebook entry has include_outputs=True and remove_newline=True."""diff --git a/tests/document_loaders/test_text_encoding.py b/tests/document_loaders/test_text_encoding.pynew file mode 100644index 0000000000..554758f033--- /dev/null+++ b/tests/document_loaders/test_text_encoding.py@@ -0,0 +1,156 @@+"""+Tests for reading text uploads in the encoding they were written in (#6532).+"""++import pytest++from local_deep_research.document_loaders.loader_registry import (+ get_loader_for_path,+)+from local_deep_research.document_loaders.text_encoding import (+ detect_text_encoding,+)++GREETING = "Sehr geehrte Frau Müller,\nviele Grüße aus Köln.\n"+ROWS = "Name,Stadt\nMüller,Köln\nGroß,Düsseldorf\n"+# The bytes pinned by test_binary_bytes_under_a_txt_name_are_refused.+BINARY = b"\x00\x01\x02\xff\xfe binary \x80"+++class TestDetectTextEncoding:+ def test_utf8_is_read_as_utf8_with_or_without_a_byte_order_mark(self):+ assert detect_text_encoding(GREETING.encode("utf-8")) == "utf-8-sig"+ assert detect_text_encoding(GREETING.encode("utf-8-sig")) == "utf-8-sig"++ def test_utf8_is_read_as_before_even_with_control_characters(self):+ assert detect_text_encoding(b"\x1b[31mred\x1b[0m \x00") == "utf-8-sig"++ def test_utf16_and_utf32_are_recognized_by_their_byte_order_mark(self):+ assert detect_text_encoding(GREETING.encode("utf-16")) == "utf-16"+ assert detect_text_encoding(GREETING.encode("utf-16-be")) is None+ assert detect_text_encoding(GREETING.encode("utf-32")) == "utf-32"++ def test_big_endian_byte_order_marks_are_recognized(self):+ # Notepad's "Unicode big endian" writes the UTF-16 one.+ text = "Grüße"+ assert (+ detect_text_encoding(b"\xfe\xff" + text.encode("utf-16-be"))+ == "utf-16"+ )+ assert (+ detect_text_encoding(b"\x00\x00\xfe\xff" + text.encode("utf-32-be"))+ == "utf-32"+ )++ def test_a_mark_that_does_not_decode_falls_back_to_windows_1252(self):+ # Three bytes after a UTF-16 mark cannot be UTF-16, so the mark is+ # read as the two Windows-1252 characters it also is: "ÿþabc".+ assert detect_text_encoding(b"\xff\xfeabc") == "cp1252"++ def test_windows_1252_text_is_read_as_windows_1252(self):+ assert detect_text_encoding(GREETING.encode("cp1252")) == "cp1252"+ assert detect_text_encoding("Preis: 5 €\r\n\x1a".encode("cp1252")) == (+ "cp1252"+ )+ assert detect_text_encoding("\x1b[1mGrüße\x1b[0m".encode("cp1252")) == (+ "cp1252"+ )++ def test_bytes_that_are_not_text_have_no_encoding(self):+ assert detect_text_encoding(BINARY) is None+ # 0x81 is one of the five bytes Windows-1252 leaves undefined.+ assert detect_text_encoding(b"hello \x81 world") is None+ assert (+ detect_text_encoding(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") is None+ )+++def _load(path):+ loader = get_loader_for_path(path)+ assert loader is not None+ return loader.load()+++class TestTextUploads:+ def test_a_windows_1252_text_file_is_read(self, tmp_path):+ path = tmp_path / "letter.txt"+ path.write_bytes(GREETING.encode("cp1252"))++ assert [d.page_content for d in _load(path)] == [GREETING]++ def test_a_utf16_text_file_is_read(self, tmp_path):+ path = tmp_path / "notes.txt"+ path.write_bytes(GREETING.encode("utf-16"))++ assert [d.page_content for d in _load(path)] == [GREETING]++ def test_a_utf8_byte_order_mark_is_not_part_of_the_text(self, tmp_path):+ path = tmp_path / "notes.txt"+ path.write_bytes(GREETING.encode("utf-8-sig"))++ assert [d.page_content for d in _load(path)] == [GREETING]++ def test_binary_bytes_under_a_txt_name_are_refused(self, tmp_path):+ path = tmp_path / "bin.txt"+ path.write_bytes(BINARY)++ with pytest.raises(ValueError, match="no recognized text encoding"):+ _load(path)++ @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, encoding, detected+ ):+ path = tmp_path / "notes.txt"+ path.write_bytes(GREETING.encode(encoding))++ assert [d.metadata["detected_encoding"] for d in _load(path)] == [+ detected+ ]+++class TestCsvUploads:+ @pytest.mark.parametrize(+ "encoding", ["utf-8", "utf-8-sig", "cp1252", "utf-16"]+ )+ def test_rows_are_read_in_the_encoding_of_the_file(+ self, tmp_path, encoding+ ):+ path = tmp_path / "people.csv"+ path.write_bytes(ROWS.encode(encoding))++ assert [d.page_content for d in _load(path)] == [+ "Name: Müller\nStadt: Köln",+ "Name: Groß\nStadt: Düsseldorf",+ ]++ @pytest.mark.parametrize(+ "encoding,detected",+ [+ ("utf-8", "utf-8-sig"),+ ("utf-8-sig", "utf-8-sig"),+ ("cp1252", "cp1252"),+ ("utf-16", "utf-16"),+ ],+ )+ def test_every_row_records_the_encoding_read(+ self, tmp_path, encoding, detected+ ):+ path = tmp_path / "people.csv"+ path.write_bytes(ROWS.encode(encoding))++ assert [d.metadata["detected_encoding"] for d in _load(path)] == [+ detected,+ detected,+ ]++ def test_a_windows_1252_tsv_file_is_read(self, tmp_path):+ path = tmp_path / "people.tsv"+ path.write_bytes(ROWS.replace(",", "\t").encode("cp1252"))++ assert [d.page_content for d in _load(path)][0] == (+ "Name: Müller\nStadt: Köln"+ )diff --git a/tests/research_library/test_library_pipeline_contracts.py b/tests/research_library/test_library_pipeline_contracts.pyindex 8fda7f4fd6..ce10b59219 100644--- a/tests/research_library/test_library_pipeline_contracts.py+++ b/tests/research_library/test_library_pipeline_contracts.py@@ -425,6 +425,51 @@ class TestFormatHandling:assert "Could not extract text" in resp.json()["errors"][0]["error"]assert _doc_ids(upload_client, formats_collection) == before+ def test_windows_1252_text_under_a_txt_name_is_stored_as_written(+ self, upload_client, formats_collection+ ):+ """Legacy "ANSI" text is read, where the bytes above are refused.++ With chardet 7, LangChain's ``autodetect_encoding`` raised+ ``TypeError`` for every .txt that was not UTF-8, so this upload was+ refused as well (#6532).+ """+ text = "Grüße aus Köln, 5 €"++ resp = _upload(+ upload_client,+ formats_collection,+ "ansi.txt",+ text.encode("cp1252"),+ "text/plain",+ )+ doc_id = _uploaded_id(resp)+ stored = _text_of(upload_client, doc_id).json()["text_content"]+ assert stored == text++ @pytest.mark.parametrize("encoding", ["utf-8-sig", "cp1252", "utf-16"])+ def test_a_csv_upload_is_stored_in_the_encoding_it_was_written_in(+ self, upload_client, formats_collection, encoding+ ):+ """Excel's "CSV UTF-8" (with a BOM), its "ANSI" CSV, and UTF-16.++ Before #6532 was fixed, the Windows-1252 and UTF-16 files were+ refused, and the UTF-8 byte-order mark was stored as part of the+ first column name.+ """+ rows = "Name,Stadt\nMüller,Köln\n"++ resp = _upload(+ upload_client,+ formats_collection,+ f"people-{encoding}.csv",+ rows.encode(encoding),+ "text/csv",+ )+ doc_id = _uploaded_id(resp)+ stored = _text_of(upload_client, doc_id).json()["text_content"]+ assert stored == "Name: Müller\nStadt: Köln"+def test_extension_wins_over_content_in_both_directions(self, upload_client, formats_collection):