Skip to content

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

fix(extractor): detect Markdown-prefixed chapter headings (#91) (#92)

Stamina9b4b373351d0b
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index ca090a1..0534656 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -100,6 +100,11 @@ _ROMAN_HEAD = re.compile(r"^\s*([IVXLCDM]+)\s*[:.]\s+[A-ZÀ-Þ0-9\"“(]")
_LC_MD_ROMAN = re.compile(r"^\s*#{1,6}\s+([ivxlcdm]+)\s*[:.]\s+[A-Za-zÀ-Þ\"“(]")
_ROMAN_VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
+# Optional Markdown / AsciiDoc heading prefix ("## Chapter 1", "== Section").
+# Stripped in _chapter_number() as a second pass so the CJK/Thai/Korean
+# matchers (which already tolerate the prefix inline) are untouched. (Issue #91)
+_MD_HEADING_PREFIX = re.compile(r"^(#{1,6}|={1,6})\s+")
+
# Chinese chapter headings. Two common styles:
# 1. explicit "第N章" / "第 3 回" / "第十二节" / "第一讲" — 第 + numeral + a
# chapter classifier (章回卷节篇讲);
@@ -282,15 +287,9 @@ def _roman_to_int(s: str) -> int | None:
return total if _int_to_roman(total) == s else None
-def _chapter_number(line: str) -> int | None:
- """Return the chapter number if the line is a genuine chapter heading.
-
- Handles Arabic ("Chapter 5", "Capítulo 5: ..."), Roman-numeral
- ("I: Loomings", "## i. introduction", "II. The Carpet-Bag"),
- Chinese ("第三章 …", "## 一 · …", "## 第一讲"), Thai ("บทที่ 3",
- "## บทที่ ๑"), and Korean ("제1장 총칙", "## 제4장 근로시간과 휴식")
- heading styles.
- """
+def _match_chapter_number(line: str) -> int | None:
+ """Return the chapter number if the line is a genuine chapter heading,
+ with no Markdown/AsciiDoc heading prefix (the caller strips it first)."""
s = line.strip()
if len(s) > 80:
return None
@@ -314,6 +313,32 @@ def _chapter_number(line: str) -> int | None:
return None
+def _chapter_number(line: str) -> int | None:
+ """Return the chapter number if the line is a genuine chapter heading.
+
+ Handles Arabic ("Chapter 5", "Capítulo 5: ..."), Roman-numeral
+ ("I: Loomings", "## i. introduction", "II. The Carpet-Bag"),
+ Chinese ("第三章 …", "## 一 · …", "## 第一讲"), Thai ("บทที่ 3",
+ "## บทที่ ๑"), and Korean ("제1장 총칙", "## 제4장 근로시간과 휴식")
+ heading styles — each optionally preceded by a Markdown/AsciiDoc heading
+ marker ("## Chapter 1" is a chapter heading just like "Chapter 1").
+ """
+ match = _match_chapter_number(line)
+ if match is not None:
+ return match
+ # Second pass: a Markdown/AsciiDoc heading prefix ("## Chapter 1",
+ # "== Section") hides the heading from the matchers above — the CJK
+ # matchers tolerate the prefix inline but the Latin/Thai/Korean ones anchor
+ # on the line start. Strip the prefix and retry so --mode technical
+ # (Docling emits headings as Markdown) detects the same chapters as
+ # plain-text extraction. (Issue #91)
+ s = line.strip()
+ md = _MD_HEADING_PREFIX.match(s)
+ if md:
+ return _match_chapter_number(s[md.end():])
+ return None
+
+
def detect_structure(text: str) -> dict:
"""Detect chapter count and table of contents presence.
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 5a1996a..8b27c65 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -947,6 +947,69 @@ class TestDetectStructure:
assert detect_structure(text)["chapters_detected"] == 2
+class TestMarkdownPrefixedLatinChapters:
+ """Issue #91 — _chapter_number() must see chapter headings behind a
+ Markdown/AsciiDoc prefix ("## Chapter 1"). Previously the Latin/Thai/Korean
+ matchers anchored on the line start, so --mode technical books (Docling
+ emits headings as Markdown) fell through to the structural fallback and
+ inflated chapters_detected."""
+
+ def test_md_prefixed_latin_chapter_word(self):
+ from book_to_skill.utils import _chapter_number
+
+ assert _chapter_number("## Chapter 1") == 1
+ assert _chapter_number("## CHAPTER 5") == 5
+ assert _chapter_number("## Chapter 1 Interaction Design") == 1
+ assert _chapter_number("## Capítulo 5") == 5
+ assert _chapter_number("## Chapitre 2") == 2
+ assert _chapter_number("## Kapitel 3") == 3
+
+ def test_asciidoc_prefixed_chapter_word(self):
+ from book_to_skill.utils import _chapter_number
+
+ assert _chapter_number("== Chapter 1") == 1
+ assert _chapter_number("=== Chapter 2") == 2
+
+ def test_md_prefixed_roman_numeral(self):
+ from book_to_skill.utils import _chapter_number
+
+ assert _chapter_number("## I. Loomings") == 1
+ assert _chapter_number("## III: The Spouter-Inn") == 3
+
+ def test_issue91_repro_matches_plain_text_count(self):
+ # The exact reproduction from #91: 35 real chapters plus 35 subsection
+ # headings. With the fix, the numeric path wins and the structural
+ # fallback no longer inflates the count to 36.
+ md = "\n".join(f"## Chapter {i}\n## Some Section\nbody\n" for i in range(1, 36))
+ plain = "\n".join(f"Chapter {i}\nbody\n" for i in range(1, 36))
+ assert detect_structure(md)["chapters_detected"] == 35
+ assert detect_structure(plain)["chapters_detected"] == 35
+ # The numeric path also fills the heading sample — an empty sample is a
+ # reliable tell that the structural fallback was used instead.
+ sample = detect_structure(md)["chapter_headings_sample"]
+ assert sample and sample[0] == "## Chapter 1"
+
+ def test_md_prefixed_lowercase_roman_still_works(self):
+ # "## i. introduction" is trusted as a heading (markdown context);
+ # unchanged from before the fix.
+ text = "## i. introduction\nbody\n## ii. methods\nbody\n## iii. results\nbody\n"
+ assert detect_structure(text)["chapters_detected"] == 3
+
+ def test_md_prefixed_non_chapter_headings_still_rejected(self):
+ from book_to_skill.utils import _chapter_number
+
+ assert _chapter_number("## Some Section") is None
+ assert _chapter_number("## 5 Setup") is None
+ assert _chapter_number("## Acknowledgment") is None
+ assert _chapter_number("## 2025 Goals") is None
+
+ def test_md_prefixed_cjk_unchanged(self):
+ # CJK matchers already tolerated the prefix inline; behavior is
+ # byte-for-byte unchanged.
+ assert detect_structure("## 第一讲\n正文\n## 第二讲\n正文\n")["chapters_detected"] == 2
+ assert detect_structure("## 一 · 缘起\n正文\n## 二 · 主体\n正文\n")["chapters_detected"] == 2
+
+
class TestTextExtraction:
"""Tests for plain-text file extraction."""