Skip to content

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

fix(extractor): stop counting wrapped prose and code lines as chapters (#246)

Cheemibfed408b764a
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index 5eb0e78..3b1718f 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -117,6 +117,23 @@ _EXPLICIT_CHAPTER = re.compile(
# “Chapter 8 are relevant...”) is prose / a cross-reference, not a heading.
# The uppercase class is À-Þ so titles starting with Ü/Û (common in German, e.g. “Überblick”) are recognized.
_HEADING_TAIL = re.compile(r"^\s*$|^\s*[.:\-—–]|^\s+(?![a-z])")
+# A tail that opens with a sentence period — "Chapter 4. References are
+# indicated by the `&` symbol…", "Chapter 17.) We have seen…" — is prose wrapped
+# at the column limit, unless it reads like a title. Two shapes, measured on the
+# Rust Book sources (rust-lang/book, MIT OR Apache-2.0, 112 files) where the
+# numeric scan accepted 13 lines and every one of them was prose or code:
+# * a clause of 10-14 words ("Chapter 4. References are indicated by the `&`
+# symbol and borrow the value they"), and
+# * a bare "Chapter 6." ending a sentence that began on the line above.
+# The longest period-tail heading in this repository's fixtures and tests is 5
+# words ("Chapter 1. Introduction to Building AI"). (Issue #237)
+_PERIOD_TAIL = re.compile(r"^\s*\.[)\"'”’\]]*(\s|$)")
+_TAIL_WORD = re.compile(r"[^\s]*[0-9A-Za-z][^\s]*")
+_TITLE_TAIL_MAX_WORDS = 8
+# A line that ends a sentence / paragraph. When the line above does NOT end like
+# this, the next line continues it instead of starting a heading.
+_SENTENCE_END = re.compile(r"[.!?…:;\"'”’)\]]\s*$")
+
# Roman-numeral chapter heading: "I: Loomings", "II. The Carpet-Bag".
# Uppercase alone at line start is safe — no common English word is a valid
@@ -586,9 +603,34 @@ def _roman_to_int(s: str) -> int | None:
return total if _int_to_roman(total) == s else None
-def _match_chapter_number(line: str) -> int | None:
+def _is_prose_period_tail(tail: str, prev_line: str | None) -> bool:
+ """True when a period tail is a wrapped sentence, not a title.
+
+ The context decides first: a line that stands on its own (nothing above it,
+ or the line above ends a sentence) keeps its heading. When the paragraph
+ continues into the line, the tail must read like a title — a bare
+ "Chapter 6." and a clause of more than `_TITLE_TAIL_MAX_WORDS` words are the
+ sentence that wrapped. (Issue #237)
+ """
+ if not _PERIOD_TAIL.match(tail):
+ return False
+ if not prev_line or _SENTENCE_END.search(prev_line):
+ return False
+ words = _TAIL_WORD.findall(tail)
+ return not words or len(words) > _TITLE_TAIL_MAX_WORDS
+
+
+def _match_chapter_number(
+ line: str, prev_line: str | None = None, heading_marked: bool = False
+) -> 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).
+
+ `prev_line` is the line directly above (None when it is blank or inside a
+ fenced block); it is consulted only for a bare period tail. `heading_marked`
+ says the line carried an explicit "#"/"==" prefix before it was stripped —
+ an explicit heading is trusted as it stands, so "## Chapter 4. References
+ are indicated by the `&` symbol…" keeps counting. (Issue #237)
"""
# Normalize Kangxi-radical numerals (⼀⼆⼋⼗) to ideographs so Chinese
# ebooks that encode chapter numbers in the U+2F00 block are detected.
@@ -602,12 +644,20 @@ def _match_chapter_number(line: str) -> int | None:
#
# Require at least two spaces after the chapter number. This avoids
# treating ordinary numbered list items such as "1. Item" as chapters.
- plain = re.match(r"^([1-9]\d{0,2})\s{2,}\S", s)
- if plain:
+ #
+ # A unified-diff hunk line starts with exactly that shape
+ # ("1 + use crate::trpl::StreamExt;", "12 - use std::io::prelude::*;").
+ # Its first non-space character is the diff marker, which no chapter title
+ # starts with, so the marker decides. Fenced blocks are skipped by the
+ # caller; this covers code that arrives without fences. (Issue #237)
+ plain = re.match(r"^([1-9]\d{0,2})\s{2,}(\S)", s)
+ if plain and plain.group(2) not in "+-":
return int(plain.group(1))
m = _EXPLICIT_CHAPTER.match(s)
if m and _HEADING_TAIL.match(m.group("rest")):
+ if not heading_marked and _is_prose_period_tail(m.group("rest"), prev_line):
+ return None
if m.group(1):
return int(m.group(1))
return _roman_to_int(m.group("roman").upper())
@@ -661,9 +711,12 @@ def _match_chapter_number(line: str) -> int | None:
return None
-def _chapter_number(line: str) -> int | None:
+def _chapter_number(line: str, prev_line: str | None = None) -> int | None:
"""Return the chapter number if the line is a genuine chapter heading.
+ `prev_line` is the line directly above (None when it is blank or inside a
+ fenced block); see `_match_chapter_number` for how it is used.
+
Handles Arabic ("Chapter 5", "Capítulo 5: ..."), Roman-numeral
("I: Loomings", "## i. introduction", "II. The Carpet-Bag"),
Chinese ("第三章 …", "## 一 · …", "## 第一讲"), Thai ("บทที่ 3",
@@ -681,7 +734,7 @@ def _chapter_number(line: str) -> int | None:
optionally preceded by a Markdown/AsciiDoc heading marker
("## Chapter 1" is a chapter heading just like "Chapter 1").
"""
- match = _match_chapter_number(line)
+ match = _match_chapter_number(line, prev_line)
if match is not None:
return match
# Second pass: a Markdown/AsciiDoc heading prefix ("## Chapter 1",
@@ -690,10 +743,15 @@ def _chapter_number(line: str) -> int | None:
# 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)
+ #
+ # No previous line is passed and the line is marked as heading-marked: an
+ # explicit "#"/"==" prefix is a structural claim, so a period tail there
+ # ("## Chapter 6. Enums", "## Chapter 4. References are indicated by…") is
+ # trusted as written.
s = line.strip()
md = _MD_HEADING_PREFIX.match(s)
if md:
- return _match_chapter_number(s[md.end():])
+ return _match_chapter_number(s[md.end():], heading_marked=True)
return None
@@ -704,16 +762,34 @@ def detect_structure(text: str) -> dict:
from explicit "Chapter N"/"Capítulo N" headings, rejecting prose
cross-references and numbered list items. Counting distinct numbers means a
ToC entry and its body heading are not double-counted.
+
+ Lines inside closed code fences are skipped, the same guard
+ `_structural_chapter_count()` uses: a sample holding a diff
+ ("1 + use crate::trpl::StreamExt;") otherwise matched the numeric scan and
+ the count built from code lines won over the structural count. A period
+ tail is judged against the line above it so a wrapped cross-reference
+ ("...as we cover in / Chapter 6. Closures create types...") is not counted
+ while a heading on its own line still is. (Issue #237)
"""
lines = text.splitlines()
+ fenced = _closed_fence_line_numbers(lines)
headings = []
numbers = set()
- for line in lines:
- num = _chapter_number(line)
+ prev = "" # previous non-blank line; cleared by blanks and fences
+ for index, line in enumerate(lines):
+ if index in fenced:
+ prev = ""
+ continue
+ s = line.strip()
+ if not s:
+ prev = ""
+ continue
+ num = _chapter_number(line, prev)
if num is not None:
numbers.add(num)
- headings.append(line.strip())
+ headings.append(s)
+ prev = s
numeric_count = len(numbers)
# Fall back to structural (Markdown/AsciiDoc) headings only when no numeric
# "Chapter N" headings were found, so books with real chapters are unaffected.
diff --git a/tests/test_chapter_numeric_false_positives.py b/tests/test_chapter_numeric_false_positives.py
new file mode 100644
index 0000000..3b05539
--- /dev/null
+++ b/tests/test_chapter_numeric_false_positives.py
@@ -0,0 +1,154 @@
+"""Prose and code lines must not turn into chapters in the numeric scan.
+
+`detect_structure()` counts distinct numbers from explicit "Chapter N" headings,
+and that count wins over the structural (Markdown) count as soon as two numbers
+match. Two shapes of ordinary input produced numbers that were not headings
+(issue #237):
+
+* a sentence wrapped at the column limit, where the continuation line starts
+ with a cross-reference —
+ ``...as we cover in\\nChapter 6. Closures create types that only the compiler...``
+ — and the capital letter after the period defeats the lowercase-only prose
+ guard in ``_HEADING_TAIL``;
+* a code sample holding a unified diff, where ``1 + use crate::trpl::StreamExt;``
+ satisfies the plain numbered-heading pattern.
+
+The tail of a heading is judged from the line above it: a period tail is prose
+when the paragraph continues into it and the tail reads as a sentence rather
+than a title. A line that stands on its own keeps its heading, including a bare
+"Chapter 6.".
+"""
+
+import sys
+from pathlib import Path
+
+ROOT_DIR = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT_DIR))
+
+from book_to_skill.utils import _chapter_number, detect_structure
+
+CHAPTER_BODY = "prose carrying the section's actual content. " * 40
+
+# A sentence wrapped at the column limit: the continuation line opens with the
+# cross-reference and the previous line does not end a sentence.
+WRAP_PREV = "The borrow checker rules are explained in more detail as we cover in"
+WRAP_LINE = "Chapter 4. References are indicated by the & symbol and borrow the value they"
+
+FENCED_DIFF = "```diff\n1 + use crate::trpl::StreamExt;\n2 - use std::io::prelude::*;\n```\n"
+
+
+class TestWrappedProseIsNotAChapter:
+ def test_capitalized_continuation_line_is_not_a_heading(self):
+ assert _chapter_number(WRAP_LINE, prev_line=WRAP_PREV) is None
+
+ def test_parenthetical_continuation_line_is_not_a_heading(self):
+ line = "Chapter 17.) We have seen a solution to this problem a few times now: We can"
+ assert _chapter_number(line, prev_line=WRAP_PREV) is None
+
+ def test_standalone_period_heading_is_kept(self):
+ # "Chapter 6." on a line of its own carries no context that makes it
+ # prose, so it stays a heading (see the maintainer note on #237).
+ assert _chapter_number("Chapter 6.") == 6
+
+ def test_bare_tail_inside_a_wrapped_sentence_is_not_a_heading(self):
+ # "... that we discussed in / Chapter 6." is one sentence (Rust Book,
+ # ch09-02).
+ assert _chapter_number("Chapter 6.", prev_line="`Result` using a basic tool, the `match` expression that we discussed in") is None
+
+ def test_title_sized_tail_after_an_unfinished_line_is_kept(self):
+ # The plain-text fixture layout: heading lines separated by a body line
+ # that is not a sentence.
+ assert _chapter_number("Chapter 2. Understanding Models", prev_line="body") == 2
+
+ def test_long_tail_on_a_marked_heading_is_trusted(self):
+ assert (
+ _chapter_number(
+ "## Chapter 4. References are indicated by the `&` symbol and borrow the value they"
+ )
+ == 4
+ )
+
+ def test_long_tail_on_a_standalone_line_is_kept(self):
+ # Conservative on purpose: without the enclosing paragraph there is no
+ # evidence that a sentence wrapped, so the line keeps its heading — the
+ # shape a PDF extractor produces once it has lost the wrap.
+ assert (
+ _chapter_number(
+ "Chapter 13. Closures and iterators create types that only the compiler knows or"
+ )
+ == 13
+ )
+
+ def test_heading_after_a_finished_sentence_is_kept(self):
+ assert _chapter_number("Chapter 6. Enums", prev_line="Section one ends here.") == 6
+
+ def test_colon_tail_after_prose_is_kept(self):
+ # A colon introduces a title, not a sentence: "see Chapter 6: Enums".
+ assert _chapter_number("Chapter 6: Enums", prev_line=WRAP_PREV) == 6
+
+ def test_heading_controls_are_retained(self):
+ kept = (
+ "Chapter 6",
+ "# Chapter 6",
+ "## Chapter 6: Enums",
+ "Chapter 1. Intro",
+ "Capítulo 5",
+ "Unit 1 — How to Write an Introduction",
+ "## i. introduction",
+ )
+ for line in kept:
+ assert _chapter_number(line) is not None, line
+
+
+class TestCodeLinesAreNotChapters:
+ def test_bare_diff_lines_are_not_chapters(self):
+ assert _chapter_number("1 + use crate::trpl::StreamExt;") is None
+ assert _chapter_number("12 - use std::io::prelude::*;") is None
+
+ def test_plain_numbered_heading_is_kept(self):
+ assert _chapter_number("1 Introduction") == 1
+
+ def test_fenced_diff_does_not_count(self):
+ text = (
+ "## Real One\n" + CHAPTER_BODY + "\n\n"
+ + FENCED_DIFF + "\n"
+ + "## Real Two\n" + CHAPTER_BODY + "\n"
+ )
+
+ result = detect_structure(text)
+
+ assert result["chapters_method"] == "structural"
+ assert result["chapters_detected"] == 2
+ assert result["chapter_headings_sample"] == []
+
+ def test_prose_and_code_do_not_steal_the_numeric_branch(self):
+ text = (
+ WRAP_PREV + "\n" + WRAP_LINE + "\npoint at.\n\n"
+ + FENCED_DIFF + "\n"
+ + "## Real One\n" + CHAPTER_BODY + "\n\n"
+ + "## Real Two\n" + CHAPTER_BODY + "\n\n"
+ + "## Real Three\n" + CHAPTER_BODY + "\n"
+ )
+
+ result = detect_structure(text)
+
+ assert result["chapters_method"] == "structural"
+ assert result["chapters_detected"] == 3
+ assert result["chapter_headings_sample"] == []
+
+
+class TestRealNumericBooksAreUnaffected:
+ def test_chapter_headings_still_count(self):
+ text = "\n\n".join(
+ f"Chapter {n}: Title {n}\n{CHAPTER_BODY}" for n in (1, 2, 3)
+ )
+
+ result = detect_structure(text)
+
+ assert result["chapters_method"] == "numeric"
+ assert result["chapters_detected"] == 3
+ assert result["chapter_headings_sample"] == [
+ "Chapter 1: Title 1",
+ "Chapter 2: Title 2",
+ "Chapter 3: Title 3",
+ ]