Skip to content

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

fix: CJK-aware token estimate (rescued from #70) (#103)

Virgilio Junior2bda18333eac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7b0c91..72ac9bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- **CJK-aware token estimate** — `estimate_tokens` now counts CJK codepoints
+ directly (against `CJK_CHARS_PER_TOKEN`) instead of whitespace-delimited words,
+ fixing a ~1000× undercount for space-less Chinese/Japanese books in the cost
+ pre-flight. Latin behavior is unchanged and the estimate stays deterministic
+ and dependency-free (rescued from #70).
+
### Removed
- **Stale tracked bytecode** — `scripts/__pycache__/extract.cpython-313.pyc` was committed
alongside the EPUB-support change and has been tracked ever since, despite `.gitignore`
diff --git a/book_to_skill/config.py b/book_to_skill/config.py
index 0d4a9fc..ef20237 100644
--- a/book_to_skill/config.py
+++ b/book_to_skill/config.py
@@ -11,7 +11,11 @@ OUTPUT_DIR = Path(
OUTPUT_TEXT = OUTPUT_DIR / "full_text.txt"
OUTPUT_META = OUTPUT_DIR / "metadata.json"
-WORDS_PER_TOKEN = 0.75 # approximate
+WORDS_PER_TOKEN = 0.75 # approximate (Latin / whitespace-delimited text)
+# CJK scripts carry little or no whitespace, so word-splitting under-counts them
+# by orders of magnitude. Count CJK codepoints directly against this
+# chars-per-token ratio instead (see estimate_tokens in utils.py).
+CJK_CHARS_PER_TOKEN = 1.5 # approximate for cl100k-style tokenizers
TEXT_EXTENSIONS = {".txt", ".text", ".md", ".markdown", ".rst", ".adoc", ".asciidoc"}
HTML_EXTENSIONS = {".html", ".htm", ".xhtml"}
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index 95108c7..5d3724a 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -16,6 +16,7 @@ from book_to_skill.config import (
OUTPUT_TEXT,
OUTPUT_META,
WORDS_PER_TOKEN,
+ CJK_CHARS_PER_TOKEN,
SUPPORTED_EXTENSIONS,
TEXT_EXTENSIONS,
HTML_EXTENSIONS,
@@ -47,8 +48,32 @@ from book_to_skill.parsers.epub import (
from book_to_skill.sanitize import sanitize_extracted_text
+# CJK codepoints: ideographs + extensions, kana, hangul, CJK punctuation, and
+# fullwidth forms. These are not whitespace-delimited, so counting "words" on a
+# Chinese/Japanese book collapses it to a handful of tokens; count them directly.
+_CJK_RE = re.compile(
+ r"[ -〿぀-ヿ㐀-䶿一-鿿"
+ r"가-힣豈-﫿＀-￯]"
+)
+
+
def estimate_tokens(text: str) -> int:
- return int(len(text.split()) / WORDS_PER_TOKEN)
+ """Estimate the token count of ``text`` with a deterministic heuristic.
+
+ Latin / whitespace-delimited text is counted by words (``words /
+ WORDS_PER_TOKEN`` — the project's long-standing ratio). CJK characters are
+ counted directly against ``CJK_CHARS_PER_TOKEN`` because they carry little
+ or no whitespace; without this a space-less Chinese/Japanese book estimates
+ at a few tokens and the cost pre-flight under-reports by ~1000x. Kept
+ dependency-free on purpose so the same book always yields the same number.
+ """
+ if not text:
+ return 0
+ cjk = len(_CJK_RE.findall(text))
+ if not cjk:
+ return int(len(text.split()) / WORDS_PER_TOKEN)
+ latin_words = len(_CJK_RE.sub(" ", text).split())
+ return int(latin_words / WORDS_PER_TOKEN + cjk / CJK_CHARS_PER_TOKEN)
# Explicit chapter heading: "Chapter 5", "Capítulo 5: ...", "Chapter 1. Intro".
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 0482a66..2d4f3f2 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -1570,3 +1570,26 @@ class TestParseArgumentsUnknownFlags:
parse_arguments(["extract.py", "book.pdf", "notes.txt"])
captured = capsys.readouterr()
assert captured.err == ""
+
+
+# ═══════════════════════════════════════════════════════════════════════════
+# CJK-aware token estimate (rescued from #70)
+# ═══════════════════════════════════════════════════════════════════════════
+
+class TestCjkTokenEstimate:
+ """estimate_tokens counts CJK codepoints directly, not whitespace words."""
+
+ def test_latin_estimate_unchanged(self):
+ # The project's long-standing pinned ratio: 100 words -> 133 tokens.
+ assert estimate_tokens(" ".join(["word"] * 100)) == 133
+
+ def test_cjk_is_not_undercounted(self):
+ # 1500 space-less Chinese chars must estimate ~1000 tokens, not ~1.
+ assert estimate_tokens("中" * 1500) == 1000
+
+ def test_mixed_latin_and_cjk(self):
+ # Latin words + CJK chars are both counted.
+ assert estimate_tokens("hello 世界 " * 100) > 100
+
+ def test_empty_is_zero(self):
+ assert estimate_tokens("") == 0