Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix(sanitize): fold Kangxi radicals to their ideographs in extracted text (#277)

yi1116f682c93f24e
diff --git a/book_to_skill/sanitize.py b/book_to_skill/sanitize.py
index f8643dd..32e03c2 100644
--- a/book_to_skill/sanitize.py
+++ b/book_to_skill/sanitize.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import unicodedata
+
# Invisible code points used to hide document-borne prompt injection. Grouped by
# attack shape so the reasoning behind each entry stays reviewable.
@@ -153,6 +155,55 @@ _ANNOTATION_CODEPOINTS = frozenset({
_MUSICAL_FORMAT_RANGE = (0x1D173, 0x1D17A)
+# 9. Kangxi radicals (U+2F00–U+2FDF). A PDF whose embedded font subset carries no
+# correct Unicode mapping emits a radical where a character belongs, so
+# "判断力" extracts as "判断⼒" and nothing looks wrong on the page. The run
+# still reports success, but from here on every grep, chapter-heading match and
+# topic index works on text that cannot be found (#274).
+#
+# Every code point in this block carries a Unicode compatibility
+# decomposition, so NFKC is the entire mapping — there is no table to keep in
+# sync with Unicode, and no per-radical judgement call to defend.
+#
+# The fold is scoped to this block deliberately. Applying NFKC to the whole
+# text would also rewrite full-width forms, ligatures, circled digits and CJK
+# compatibility ideographs: legitimate prose that sanitize.py must not touch
+# (see test_normalization_is_scoped_to_kangxi_radicals).
+#
+# CJK Radicals Supplement (U+2E80–U+2EF3) is the other half of this problem
+# and is deliberately *not* folded here. Unicode defines no decomposition for
+# that block, so its mapping is a curated table rather than a lookup — and
+# some entries must not be folded at all, since U+2EEB and friends are
+# ordinary Japanese kanji (⻫ is 匀, not a radical form of 二).
+_KANGXI_RADICAL_RANGE = (0x2F00, 0x2FDF)
+
+
+def _kangxi_radical_fold() -> dict[int, str]:
+ """Map each Kangxi radical that has a compatibility form to its ideograph."""
+ fold: dict[int, str] = {}
+ for codepoint in range(_KANGXI_RADICAL_RANGE[0], _KANGXI_RADICAL_RANGE[1] + 1):
+ radical = chr(codepoint)
+ ideograph = unicodedata.normalize("NFKC", radical)
+ if ideograph != radical:
+ fold[codepoint] = ideograph
+ return fold
+
+
+# Applied with str.translate, so it touches only the listed code points.
+_KANGXI_RADICAL_FOLD = str.maketrans(_kangxi_radical_fold())
+
+
+def fold_cjk_radicals(text: str) -> str:
+ """Replace Kangxi radicals with the ideographs they stand in for.
+
+ Exposed separately from :func:`sanitize_extracted_text` because this is a
+ legibility fix rather than a security strip: nothing is removed, so it does
+ not belong in the invisible-code-point count that
+ :func:`sanitize_extracted_text` reports.
+ """
+ return text.translate(_KANGXI_RADICAL_FOLD)
+
+
def is_invisible_codepoint(codepoint: int) -> bool:
"""Return True if the code point renders as nothing and should be stripped.
@@ -172,11 +223,16 @@ def is_invisible_codepoint(codepoint: int) -> bool:
def sanitize_extracted_text(text: str) -> tuple[str, int]:
- """Remove invisible code points used for document-borne prompt injection."""
+ """Remove invisible code points used for document-borne prompt injection.
+
+ Kangxi radicals are folded to their ideographs on the way through (see
+ :func:`fold_cjk_radicals`) because they are corrupted characters rather than
+ an attack, so they do not count toward the returned removal total.
+ """
kept: list[str] = []
removed = 0
- for character in text:
+ for character in fold_cjk_radicals(text):
if is_invisible_codepoint(ord(character)):
removed += 1
continue
diff --git a/docs/architecture.md b/docs/architecture.md
index 6e66f83..477bbb3 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -83,7 +83,7 @@ converter does not infer arbitrary `skills.load.extraDirs`.
| `book_to_skill/parsers/` | one module per format (`pdf`, `epub`, `docx`, `html`, `rtf`, `calibre`, `text`) |
| `book_to_skill/config.py` | supported extensions, output paths, dependency map |
| `book_to_skill/dependencies.py` | optional-dependency probing + `--check` |
-| `book_to_skill/sanitize.py` | strips zero-width / Unicode-tag-block characters from extracted text (see Security) |
+| `book_to_skill/sanitize.py` | strips zero-width / Unicode-tag-block characters from extracted text, and folds Kangxi radicals to their ideographs (see Security) |
| `tools/discovery_tax.py` | measures token cost vs context-dump / discovery loop |
| `tools/validate_skill.py` | checks a generated SKILL.md against host rules (`--lens claude\|copilot\|amp\|hermes\|openclaw`) |
| `tools/validate_skill.py` | checks a generated SKILL.md against host rules (`--lens claude\|copilot\|amp\|hermes\|opencode`) |
@@ -101,6 +101,15 @@ is layered:
every parser's output before metrics or `full_text.txt`, so invisible
document-borne instructions never reach the agent. Reports the removal count;
rejects a source with no visible content left.
+- **CJK radical folding** (`book_to_skill/sanitize.py`) — PDFs whose embedded
+ font subset carries no correct Unicode mapping emit a Kangxi radical
+ (`U+2F00–U+2FDF`) where a character belongs, so a Chinese book extracts
+ "判断⼒" for "判断力". Each radical in that block has a Unicode compatibility
+ decomposition, so the fold is NFKC applied to those code points only: the rest
+ of the text is passed through byte for byte. Nothing is removed, so it does
+ not count toward the security removal total. CJK Radicals Supplement
+ (`U+2E80–U+2EF3`) is deliberately not folded — Unicode defines no
+ decomposition for it, and some entries are ordinary kanji.
- **DOCX XXE / Billion-Laughs guard** (`parsers/docx.py`) — rejects any XML part
declaring a DTD or entities before parsing.
- **Subprocess argument-injection** — file paths are absolutised before reaching
diff --git a/tests/test_cjk_radical_normalization.py b/tests/test_cjk_radical_normalization.py
new file mode 100644
index 0000000..9af0f00
--- /dev/null
+++ b/tests/test_cjk_radical_normalization.py
@@ -0,0 +1,97 @@
+"""Kangxi radicals must be folded to the ideographs they stand in for (#274).
+
+A PDF whose embedded font subset has no correct Unicode mapping emits a radical
+where a character belongs, so a Chinese book extracts "判断⼒" instead of
+"判断力". Nothing looks wrong on the page and the run reports success, which is
+what makes this worth fixing at the extraction chokepoint: every later grep,
+chapter-heading match and topic index is built from the corrupted text.
+"""
+
+import sys
+import unicodedata
+from pathlib import Path
+
+import pytest
+
+ROOT_DIR = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT_DIR))
+
+from book_to_skill.sanitize import (
+ _KANGXI_RADICAL_RANGE,
+ fold_cjk_radicals,
+ sanitize_extracted_text,
+)
+
+# The shapes that actually show up in Chinese extractions: 一 (U+2F00), 人
+# (U+2F08), 自 (U+2F1B), 生 (U+2F25), 大 (U+2F27), 而 (U+2F3D).
+CORRUPTED = "纳⽡尔宝典 第⼀章 判断⼒ ⾃由 ⽣ ⼤ ⽽ ⼒"
+REPAIRED = "纳瓦尔宝典 第一章 判断力 自由 生 大 而 力"
+
+
+class TestKangxiRadicalsFolded:
+ def test_reported_chinese_passage_becomes_searchable(self):
+ assert fold_cjk_radicals(CORRUPTED) == REPAIRED
+
+ def test_fold_replaces_rather_than_removes(self):
+ # A radical and its ideograph are both one character, so a fold cannot
+ # change the length of the text — only what it says.
+ folded = fold_cjk_radicals(CORRUPTED)
+
+ assert len(folded) == len(CORRUPTED)
+
+ def test_every_folded_radical_maps_to_one_ideograph(self):
+ """No radical may expand to a sequence or to another radical."""
+ for codepoint in range(_KANGXI_RADICAL_RANGE[0], _KANGXI_RADICAL_RANGE[1] + 1):
+ radical = chr(codepoint)
+ folded = fold_cjk_radicals(radical)
+ if folded == radical: # unassigned code point, nothing to fold
+ continue
+ assert len(folded) == 1, f"U+{codepoint:04X} folded to {folded!r}"
+ assert _KANGXI_RADICAL_RANGE[0] > ord(folded) or ord(folded) > _KANGXI_RADICAL_RANGE[1], (
+ f"U+{codepoint:04X} folded to another radical"
+ )
+
+ def test_agrees_with_unicode_compatibility_decomposition(self):
+ """The table is NFKC, not a hand-written opinion."""
+ assert fold_cjk_radicals("⼀") == unicodedata.normalize("NFKC", "⼀") == "一"
+
+
+class TestNormalizationIsScoped:
+ """NFKC must not be applied to the whole text — it rewrites legitimate prose."""
+
+ @pytest.mark.parametrize(
+ "text",
+ [
+ "file first", # ligatures
+ "①②③", # circled digits
+ "㍿", # squared katakana
+ "中文", # already-normal ideographs
+ "ABC 123", # full-width forms
+ "Ⅳ", # Roman numeral four
+ "㊤", # parenthesized ideograph
+ ],
+ )
+ def test_prose_outside_the_block_is_byte_for_byte_preserved(self, text):
+ assert fold_cjk_radicals(text) == text
+
+
+class TestSanitizeExtractionPath:
+ def test_sanitize_folds_radicals_without_counting_them_as_removed(self):
+ sanitized, removed = sanitize_extracted_text(CORRUPTED)
+
+ assert sanitized == REPAIRED
+ # Radicals are a legibility fix, not a security strip, so they must not
+ # inflate the "[security] removed N" count the CLI reports.
+ assert removed == 0
+
+ def test_invisible_stripping_still_works_alongside_the_fold(self):
+ sanitized, removed = sanitize_extracted_text("第⼀章\u200b")
+
+ assert sanitized == "第一章"
+ assert removed == 1
+
+ def test_radicals_are_not_reported_as_invisible(self):
+ """is_invisible_codepoint drives the scanner; a radical must not drift in."""
+ from book_to_skill.sanitize import is_invisible_codepoint
+
+ assert is_invisible_codepoint(0x2F00) is False
\ No newline at end of file