Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.
Python agent-skillsai-agentsbook-to-skillcontext-engineeringdocument-processingedtechknowledge-baseknowledge-managementllmpdf-to-markdownragself-studystudy-tools
fix(text): decode UTF-16/UTF-32 files by BOM in read_text_file (#65)
Shubham Srivastava26a0b5c96161
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bd4f4ab..003c658 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -35,6 +35,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`PyPDF2` is end-of-life and no longer receives security fixes (#54).### Fixed+- Text files (`.txt`, `.md`, `.rst`, `.adoc`, `.html`, `.rtf`) saved as UTF-16 or+ UTF-32 (e.g. Windows Notepad "Unicode" or PowerShell output) are now decoded by+ their byte-order mark instead of being read as `cp1252`/`latin-1` mojibake.- The dependency-free RTF fallback (used when `striprtf` is not installed) nowdecodes `\uN` unicode escapes — smart quotes, dashes, accented letters — insteadof dropping them and leaving only the ASCII fallback character.diff --git a/book_to_skill/parsers/text.py b/book_to_skill/parsers/text.pyindex cfe74a1..4055c5a 100644--- a/book_to_skill/parsers/text.py+++ b/book_to_skill/parsers/text.py@@ -2,14 +2,37 @@ from __future__ import annotationsimport sysfrom pathlib import Path+# Byte-order marks, longest first: the UTF-32 LE BOM ("ff fe 00 00") starts with+# the UTF-16 LE BOM ("ff fe"), so UTF-32 must be checked before UTF-16.+_BOMS = (+ (b"\xef\xbb\xbf", "utf-8-sig"),+ (b"\xff\xfe\x00\x00", "utf-32"),+ (b"\x00\x00\xfe\xff", "utf-32"),+ (b"\xff\xfe", "utf-16"),+ (b"\xfe\xff", "utf-16"),+)+def read_text_file(path: str) -> str | None:- for encoding in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):+ try:+ data = Path(path).read_bytes()+ except Exception as e:+ print(f" [warn] read_text_file failed: {type(e).__name__}: {e}", file=sys.stderr)+ return None++ # Decode by BOM when present (the utf-16/utf-32 codecs strip the BOM and+ # auto-select byte order).+ for bom, encoding in _BOMS:+ if data.startswith(bom):+ try:+ return data.decode(encoding)+ except (UnicodeDecodeError, LookupError):+ break++ # No (usable) BOM: fall back to the prior chain for BOM-less files.+ for encoding in ("utf-8", "cp1252", "latin-1"):try:- return Path(path).read_text(encoding=encoding)+ return data.decode(encoding)except UnicodeDecodeError:continue- except Exception as e:- print(f" [warn] read_text_file failed: {type(e).__name__}: {e}", file=sys.stderr)- return Nonereturn Nonediff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.pyindex e42b665..f687997 100644--- a/tests/test_book_to_skill.py+++ b/tests/test_book_to_skill.py@@ -34,6 +34,7 @@ from book_to_skill.utils import (main,)from book_to_skill.config import SUPPORTED_EXTENSIONS+from book_to_skill.parsers.text import read_text_filefrom book_to_skill.parsers.docx import extract_docx_with_zipfilefrom book_to_skill.parsers.rtf import strip_rtf_fallbackfrom book_to_skill.parsers.epub import extract_with_zipfile@@ -1236,3 +1237,50 @@ class TestEpubSpineOrder:zf.writestr("b.xhtml", self._doc("BBB"))out = extract_with_zipfile(str(p))assert "AAA" in out and "BBB" in out+++class TestTextEncodingDetection:+ """read_text_file decodes UTF-16/UTF-32 by BOM, with a BOM-less fallback."""++ SAMPLE = "Café — naïve résumé\nSecond line"++ def _write(self, tmp_path, raw_bytes):+ p = tmp_path / "sample.txt"+ p.write_bytes(raw_bytes)+ return str(p)++ def test_utf16_le_bom(self, tmp_path):+ raw = b"\xff\xfe" + self.SAMPLE.encode("utf-16-le")+ assert read_text_file(self._write(tmp_path, raw)) == self.SAMPLE++ def test_utf16_be_bom(self, tmp_path):+ raw = b"\xfe\xff" + self.SAMPLE.encode("utf-16-be")+ assert read_text_file(self._write(tmp_path, raw)) == self.SAMPLE++ def test_utf32_le_bom(self, tmp_path):+ raw = b"\xff\xfe\x00\x00" + self.SAMPLE.encode("utf-32-le")+ assert read_text_file(self._write(tmp_path, raw)) == self.SAMPLE++ def test_utf8_bom(self, tmp_path):+ raw = b"\xef\xbb\xbf" + self.SAMPLE.encode("utf-8")+ assert read_text_file(self._write(tmp_path, raw)) == self.SAMPLE++ def test_utf8_no_bom(self, tmp_path):+ raw = self.SAMPLE.encode("utf-8")+ assert read_text_file(self._write(tmp_path, raw)) == self.SAMPLE++ def test_cp1252_no_bom(self, tmp_path):+ # 0xE9 (é) is valid cp1252 but not a valid standalone utf-8 byte.+ raw = "café".encode("cp1252")+ assert read_text_file(self._write(tmp_path, raw)) == "café"++ def test_ascii_no_bom(self, tmp_path):+ assert read_text_file(self._write(tmp_path, b"hello world")) == "hello world"++ def test_utf32_be_bom(self, tmp_path):+ raw = b"\x00\x00\xfe\xff" + self.SAMPLE.encode("utf-32-be")+ assert read_text_file(self._write(tmp_path, raw)) == self.SAMPLE++ def test_empty_file_returns_empty_string(self, tmp_path):+ # An empty file decodes to "" (not None, which is reserved for read errors).+ assert read_text_file(self._write(tmp_path, b"")) == ""