Skip to content

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

fix(rtf): decode hex-escaped text (#242)

Stamina903891b1ab3ee
diff --git a/book_to_skill/parsers/rtf.py b/book_to_skill/parsers/rtf.py
index c64215d..5d67725 100644
--- a/book_to_skill/parsers/rtf.py
+++ b/book_to_skill/parsers/rtf.py
@@ -1,3 +1,4 @@
+import codecs
import html
import re
import sys
@@ -10,6 +11,8 @@ from book_to_skill.exceptions import ExtractionError
# or a literal "?". Assumes the default \uc1 (one fallback char); \ucN directives
# and multi-char/group fallbacks are not parsed (best-effort fallback only).
_RTF_UNICODE = re.compile(r"\\u(-?\d+)[ ]?(?:\\'[0-9a-fA-F]{2}|\?)?")
+_RTF_HEX_RUN = re.compile(r"(?:\\'[0-9a-fA-F]{2})+")
+_RTF_ANSI_CODEPAGE = re.compile(r"\\ansicpg(\d+)")
def _rtf_unicode_repl(match: re.Match) -> str:
@@ -19,6 +22,25 @@ def _rtf_unicode_repl(match: re.Match) -> str:
return chr(cp)
+def _rtf_ansi_encoding(raw: str) -> str:
+ """Return the declared ANSI code page, defaulting to Windows-1252."""
+ match = _RTF_ANSI_CODEPAGE.search(raw)
+ encoding = f"cp{match.group(1)}" if match else "cp1252"
+ try:
+ codecs.lookup(encoding)
+ except LookupError:
+ return "cp1252"
+ return encoding
+
+
+def _decode_hex_run(match: re.Match, encoding: str) -> str:
+ payload = bytes(
+ int(value, 16)
+ for value in re.findall(r"[0-9a-fA-F]{2}", match.group(0))
+ )
+ return payload.decode(encoding, errors="replace")
+
+
# RTF groups whose contents are metadata or formatting tables rather than
# document text. Stripping only the control words inside them (what the cleanup
# below does) leaves the residue behind: font and style *names*, the generator
@@ -109,8 +131,14 @@ def strip_rtf_fallback(raw: str) -> str:
# the control-word cleanup that would otherwise strip the markup and leave
# the names behind as if they were prose.
raw = _strip_destination_groups(raw)
+ ansi_encoding = _rtf_ansi_encoding(raw)
raw = _RTF_UNICODE.sub(_rtf_unicode_repl, raw) # decode \uN escapes first
- raw = re.sub(r"\\'[0-9a-fA-F]{2}", " ", raw)
+ # A hex byte immediately following \uN is its compatibility fallback and
+ # was consumed by _RTF_UNICODE above. Any remaining \'hh escapes are actual
+ # document text. Decode adjacent bytes as a run so multibyte code pages work.
+ raw = _RTF_HEX_RUN.sub(
+ lambda match: _decode_hex_run(match, ansi_encoding), raw
+ )
raw = re.sub(r"\\par[d]?", "\n", raw)
raw = re.sub(r"\\tab", "\t", raw)
# Park the three escaped literals ("\\", "\{", "\}") on placeholders before
diff --git a/tests/test_rtf_destination_groups.py b/tests/test_rtf_destination_groups.py
index 179daac..f0e2f2d 100644
--- a/tests/test_rtf_destination_groups.py
+++ b/tests/test_rtf_destination_groups.py
@@ -136,6 +136,24 @@ class TestExistingBehaviourPreserved:
assert "\t" in out
+class TestHexEscapedText:
+ """Standalone RTF hex bytes are text, not Unicode fallback bytes."""
+
+ def test_default_ansi_hex_escape_decodes_cp1252(self):
+ out = strip_rtf_fallback(r"{\rtf1\ansi caf\'e9 and \'93quoted\'94.}")
+ assert out == "café and “quoted”."
+
+ def test_declared_code_page_decodes_consecutive_bytes(self):
+ escaped = "".join(f"\\'{byte:02x}" for byte in "Привет".encode("cp1251"))
+ out = strip_rtf_fallback(r"{\rtf1\ansi\ansicpg1251 " + escaped + "}")
+ assert out == "Привет"
+
+ def test_declared_multibyte_code_page_decodes_each_run_together(self):
+ escaped = "".join(f"\\'{byte:02x}" for byte in "日本".encode("cp932"))
+ out = strip_rtf_fallback(r"{\rtf1\ansi\ansicpg932 " + escaped + "}")
+ assert out == "日本"
+
+
class TestMalformedInputIsNotTruncated:
def test_unterminated_skipped_group_falls_back(self):
"""Losing the whole body would be worse than leaking table residue."""