From ea517d2c59a65b2dbdc88e8a9bdbbd20003a2208 Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Sun, 15 Nov 2026 00:50:30 +0800 Subject: [PATCH] fix(import): use locale hints for ambiguous legacy text encodings Local dev repairs for #2132, #2133. Turkish UI prefers Windows-1254 after UTF-8; strict explicit encoding is available for mixed legacy collections. Tested both upload bytes and file reads, short Turkish strings, GBK, GB18030 and Windows-1252. Encoding and memory suite: 398 passed. --- deeptutor/utils/file_types.py | 55 ++++++++++++++--------- docs-for-dev/AGENT_SETUP.md | 13 ++++++ tests/utils/test_text_decoding.py | 74 +++++++++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 20 deletions(-) create mode 100644 tests/utils/test_text_decoding.py diff --git a/deeptutor/utils/file_types.py b/deeptutor/utils/file_types.py index 393b12c01..09ae47a21 100644 --- a/deeptutor/utils/file_types.py +++ b/deeptutor/utils/file_types.py @@ -275,38 +275,53 @@ class FileTypeRouter: "gbk", "gb2312", "gb18030", - "latin-1", "cp1252", + "latin-1", ) @classmethod - def decode_bytes(cls, data: bytes) -> str: - """Decode raw bytes using the same fallback chain as read_text_file. + def decode_bytes( + cls, data: bytes, *, encoding: str | None = None, language_hint: str | None = None + ) -> str: + """Decode uploaded text, using an explicit encoding or the user's locale. - Used by the chat-attachment extractor so path-based and bytes-based - callers share one source of truth for supported encodings. + Short cp1254 strings can be valid GBK (#2132, #2133); bytes alone cannot + disambiguate them. UTF-8 always wins by default. Turkish UI users then + prefer their Windows ANSI encoding; other users retain Chinese fallback + order. An explicit encoding is strict and never silently substituted. """ - for encoding in cls.TEXT_DECODING_CANDIDATES: + if encoding is not None: + return data.decode(encoding) + try: + return data.decode("utf-8") + except UnicodeDecodeError: + pass + if language_hint is None: + from deeptutor.services.settings.interface_settings import get_ui_language + + language_hint = get_ui_language() + candidates = cls.TEXT_DECODING_CANDIDATES[2:] + if language_hint.lower().replace("_", "-").split("-")[0] == "tr": + candidates = ("cp1254", *candidates) + for candidate in candidates: try: - return data.decode(encoding) + return data.decode(candidate) except UnicodeDecodeError: continue return data.decode("utf-8", errors="replace") @classmethod - async def read_text_file(cls, file_path: str) -> str: - """Read a text file with automatic encoding detection.""" - for encoding in cls.TEXT_DECODING_CANDIDATES: - try: - with open(file_path, "r", encoding=encoding) as f: - text = f.read() - break - except UnicodeDecodeError: - continue - - else: - with open(file_path, "rb") as f: - text = f.read().decode("utf-8", errors="replace") + async def read_text_file( + cls, file_path: str, *, encoding: str | None = None, language_hint: str | None = None + ) -> str: + """Read text with the same decoding policy as in-memory uploads.""" + text = ( + cls.decode_bytes( + Path(file_path).read_bytes(), encoding=encoding, language_hint=language_hint + ) + .replace("\r\n", "\n") + .replace("\r", "\n") + ) if Path(file_path).suffix.lower() == ".bib": from deeptutor.utils.bibtex_converter import bibtex_to_markdown diff --git a/docs-for-dev/AGENT_SETUP.md b/docs-for-dev/AGENT_SETUP.md index dfa764bdb..22fbe814b 100644 --- a/docs-for-dev/AGENT_SETUP.md +++ b/docs-for-dev/AGENT_SETUP.md @@ -305,3 +305,16 @@ based on evidence; there is no need to run every command for every problem. - [deeptutor_cli/setup_config.py](../deeptutor_cli/setup_config.py) - [deeptutor_cli/doctor.py](../deeptutor_cli/doctor.py) - [tests/cli/test_agent_setup.py](../tests/cli/test_agent_setup.py) + + +### Legacy text encodings + +Prefer UTF-8 for knowledge-base text and chat attachments. For legacy Windows +ANSI files, the importer uses the account's interface language: Turkish prefers +Windows-1254 after UTF-8; other locales preserve the GBK/GB18030 fallback and use +Windows-1252 before Latin-1. This fixes Turkish text such as `Çiçek` whose bytes +are also valid Chinese text. The bytes alone cannot distinguish those encodings. +For mixed-language legacy collections, convert files to UTF-8 before uploading; +Python callers may pass a strict `encoding="cp1254"` or `encoding="gbk"` to +`FileTypeRouter.decode_bytes` / `read_text_file`. No decoding step rewrites the +original uploaded file. diff --git a/tests/utils/test_text_decoding.py b/tests/utils/test_text_decoding.py new file mode 100644 index 000000000..0ffb60159 --- /dev/null +++ b/tests/utils/test_text_decoding.py @@ -0,0 +1,74 @@ +"""Legacy single-byte encodings decode to the text the author wrote.""" + +from __future__ import annotations + +import asyncio + +import pytest + +from deeptutor.utils.file_types import FileTypeRouter + +TURKISH_PARAGRAPH = ( + "Öğrenciler sınav haftasında kütüphanede çalışıyor. Şirketin İstanbul'daki " + "eğitim merkezi, ağaç gölgesinde ders işlemeyi seviyor. Ilık bir sabahta " + "öğretmen, sorulara cevap verirken öğrencilerin dikkatini çekti. " +) + +CHINESE = "这是一个中文测试文件,用于检查编码识别是否正确。用Python编程很有趣。" + + +@pytest.mark.parametrize("repeat", [1, 2, 4]) +def test_windows_1254_turkish_keeps_its_letters(repeat: int) -> None: + text = TURKISH_PARAGRAPH * repeat + assert FileTypeRouter.decode_bytes(text.encode("cp1254"), language_hint="tr-TR") == text + + +@pytest.mark.parametrize("text", ["Çiçek", "İyi günler"]) +def test_short_windows_1254_turkish(text: str) -> None: + assert FileTypeRouter.decode_bytes(text.encode("cp1254"), language_hint="tr-TR") == text + + +@pytest.mark.parametrize("encoding", ["gbk", "gb18030"]) +def test_chinese_encodings_are_unchanged(encoding: str) -> None: + assert FileTypeRouter.decode_bytes(CHINESE.encode(encoding)) == CHINESE + + +@pytest.mark.parametrize( + "text", + [ + "Les élèves révisent à la bibliothèque, « c’est l’été ».", + "Die Schüler lernen für die Prüfung – „schön“ und groß.", + ], +) +def test_windows_1252_text_and_smart_quotes(text: str) -> None: + assert FileTypeRouter.decode_bytes(text.encode("cp1252")) == text + + +def test_utf8_with_bom() -> None: + assert FileTypeRouter.decode_bytes("Çalışma notu".encode("utf-8")) == "Çalışma notu" + + +def test_read_text_file_uses_the_same_chain(tmp_path) -> None: + path = tmp_path / "notes.txt" + path.write_bytes((TURKISH_PARAGRAPH * 2).encode("cp1254")) + assert ( + asyncio.run(FileTypeRouter.read_text_file(str(path), language_hint="tr")) + == TURKISH_PARAGRAPH * 2 + ) + + +def test_upload_extractor_uses_account_locale_without_affecting_utf8(monkeypatch): + from deeptutor.services.settings import interface_settings + from deeptutor.utils.document_extractor import extract_text_from_bytes + + monkeypatch.setattr(interface_settings, "get_ui_language", lambda: "tr") + assert extract_text_from_bytes("flower.txt", "Çiçek".encode("cp1254")) == "Çiçek" + assert extract_text_from_bytes("notes.txt", CHINESE.encode("utf-8")) == CHINESE + assert FileTypeRouter.decode_bytes(CHINESE.encode("gbk"), encoding="gbk") == CHINESE + + +def test_explicit_encoding_is_strict_and_keeps_other_latin_alphabets(): + icelandic = "Það er góð hugmynd" + assert FileTypeRouter.decode_bytes(icelandic.encode("cp1252"), encoding="cp1252") == icelandic + with pytest.raises(UnicodeDecodeError): + FileTypeRouter.decode_bytes(b"\xff", encoding="utf-8")