Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.
Python agent-skillsai-agentsbook-to-skillcontext-engineeringdocument-processingedtechknowledge-baseknowledge-managementllmpdf-to-markdownragself-studystudy-tools
fix(extractor): count numbered headings as chapters when they carry a chapter's weight (#149)
Virgilio Juniorb7e3a81ad604
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.pyindex a04adda..2f9f51f 100644--- a/book_to_skill/utils.py+++ b/book_to_skill/utils.py@@ -4,6 +4,7 @@ import globimport jsonimport osimport re+import statisticsimport sysimport shutilimport zipfile@@ -228,6 +229,40 @@ def _closed_fence_line_numbers(lines: list[str]) -> set[int]:return inside+# A numbered heading is a chapter when the numbering is systematic AND the+# sections carry a chapter's worth of text. Both are required, because neither+# separates the two shapes alone: a three-step tutorial is also systematic and+# also ascends from 1, while a single long section is not a numbering scheme.+# Measured medians of body text per section: tutorial steps ~20 chars, doc+# sections ~500, paper sections ~2,000, real book chapters ~5,000. The floor+# sits an order of magnitude below the smallest real chapter seen and an order+# above the largest tutorial step.+_MIN_NUMBERED_TITLES = 3+_MIN_NUMBERED_BODY_CHARS = 200+++def _numbered_titles_are_structural(+ entries: list[tuple[str, int]], heading_lines: list[int], lines: list[str]+) -> bool:+ """Decide whether digit-led titles at one depth are chapters or list items.++ Deliberately not based on the numbers themselves. An ascending run starting+ at 1 describes "Step 1 / Step 2 / Step 3" as accurately as it describes a+ paper's sections, and requiring the run to be unbroken would throw away a+ whole book when extraction drops one heading, a chapter list that starts at+ 0, or a multi-source corpus where the numbering restarts.+ """+ if len(entries) < _MIN_NUMBERED_TITLES:+ return False+ ordered = sorted(heading_lines)+ bodies = []+ for _, index in entries:+ after = [ln for ln in ordered if ln > index]+ end = after[0] if after else len(lines)+ bodies.append(sum(len(ln) for ln in lines[index + 1:end]))+ return statistics.median(bodies) >= _MIN_NUMBERED_BODY_CHARS++def _structural_chapter_count(text: str) -> int:"""Count chapter-like structural headings in Markdown/AsciiDoc/RST sources.@@ -244,8 +279,13 @@ def _structural_chapter_count(text: str) -> int:the underline (so thematic breaks, table borders, and front-matter "---" donot match)."""- levels: dict[int, set[str]] = {}lines = text.splitlines()+ levels: dict[int, set[str]] = {}+ # Digit-led titles are held back and judged per depth at the end (see+ # _numbered_titles_are_structural): "## 1. Introduction" and "## 5 Setup"+ # are the same string shape, so the line alone cannot decide.+ numbered: dict[int, list[tuple[str, int]]] = {}+ heading_lines: list[int] = []fenced = _closed_fence_line_numbers(lines)prev = "" # previous non-fence line (stripped); a setext title candidatefor index, line in enumerate(lines):@@ -263,20 +303,28 @@ def _structural_chapter_count(text: str) -> int:):depth = 1 if s[0] == "=" else 2levels.setdefault(depth, set()).add(prev.lower())+ heading_lines.append(index)prev = ""continue# ATX heading ("# Title", "== Section").m = _ATX_HEADING.match(s)if m:title = m.group(2).strip().lower()- # Reject empty, bare-digit-led ("## 5 Setup"), and all-punctuation- # ("=====" table-border) titles — none are real chapter headings.- if title and not title[0].isdigit() and re.search(r"\w", title):- levels.setdefault(len(m.group(1)), set()).add(title)+ depth = len(m.group(1))+ # Reject empty and all-punctuation ("=====" table-border) titles.+ if title and re.search(r"\w", title):+ heading_lines.append(index)+ if title[0].isdigit():+ numbered.setdefault(depth, []).append((title, index))+ else:+ levels.setdefault(depth, set()).add(title)# An ATX heading line is not a setext title for the next line.prev = ""continueprev = s+ for depth, entries in numbered.items():+ if _numbered_titles_are_structural(entries, heading_lines, lines):+ levels.setdefault(depth, set()).update(title for title, _ in entries)if not levels:return 0for depth in sorted(levels):diff --git a/tests/test_numbered_headings.py b/tests/test_numbered_headings.pynew file mode 100644index 0000000..3953add--- /dev/null+++ b/tests/test_numbered_headings.py@@ -0,0 +1,115 @@+"""Numbered headings are chapters when the numbering is systematic AND the+sections carry a chapter's worth of text.++`## 1. Introduction` (a paper's section) and `## 5 Setup` (a tutorial step) are+the same string shape, so the heading line alone cannot decide. The old guard+rejected every digit-led title, which dropped the entire structure of numbered+documents — the format `--mode technical` exists to serve.++The discriminator deliberately ignores the numbers themselves: an ascending run+starting at 1 describes "Step 1 / Step 2 / Step 3" exactly as well as it+describes a paper, and requiring an unbroken run would discard a book whose+extraction lost one heading, a chapter list starting at 0, or a multi-source+corpus where numbering restarts.+"""++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 _structural_chapter_count++CHAPTER_BODY = "prose carrying the section's actual content. " * 40 # ~1.8k chars+STEP_BODY = "run the command below." # ~22 chars+++def document(headings, body):+ return "# The Document\n\n" + "\n\n".join(f"{h}\n{body}" for h in headings)+++class TestNumberedSectionsAreCounted:+ """Every arabic form, not just the one with a dot."""++ def test_dot(self):+ doc = document(["## 1. Intro", "## 2. Method", "## 3. Results"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3++ def test_bare_space(self):+ doc = document(["## 1 Intro", "## 2 Method", "## 3 Results"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3++ def test_parenthesis(self):+ doc = document(["## 1) Intro", "## 2) Method", "## 3) Results"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3++ def test_decimal(self):+ doc = document(["## 1.1 Intro", "## 1.2 Method", "## 1.3 Results"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3+++class TestNumberingIrregularitiesSurvive:+ """The count must not depend on the sequence being clean."""++ def test_numbering_starting_at_zero(self):+ """"Chapter 0: Prologue" is common; so is zero-indexing in CS books."""+ doc = document(["## 0. Prologue", "## 1. One", "## 2. Two"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3++ def test_gap_from_a_heading_lost_in_extraction(self):+ """A dropped heading must cost one chapter, not the whole document."""+ doc = document(+ ["## 1. One", "## 2. Two", "## 5. Five", "## 6. Six"], CHAPTER_BODY+ )+ assert _structural_chapter_count(doc) == 4++ def test_numbering_restarting_mid_corpus(self):+ """full_text.txt concatenates sources; numbering restarts at 1."""+ doc = document(+ ["## 1. A One", "## 2. A Two", "## 1. B One", "## 2. B Two"], CHAPTER_BODY+ )+ assert _structural_chapter_count(doc) == 4+++class TestTutorialStepsStillRejected:+ """The guard this replaces existed for a reason. It must keep working."""++ def test_three_numbered_steps_are_not_chapters(self):+ """Systematic and ascending from 1 — and still a tutorial.++ This is the case that makes sequence-based detection useless: the shape+ of the numbering is identical to a paper's. Only the weight differs.+ """+ doc = document(["## 1 Install", "## 2 Configure", "## 3 Run"], STEP_BODY)+ assert _structural_chapter_count(doc) == 1 # only "# The Document"++ def test_isolated_numbered_heading(self):+ doc = document(["## 5 Setup"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 1++ def test_two_numbered_headings_are_not_a_scheme(self):+ """Below the floor of three, numbering is incidental."""+ doc = document(["## 1 Install", "## 2 Configure"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 1+++class TestExistingBehaviourPreserved:+ def test_unnumbered_headings_unchanged(self):+ doc = document(["## Intro", "## Method", "## Results"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3++ def test_roman_numerals_unchanged(self):+ doc = document(["## I. Intro", "## II. Method", "## III. Results"], CHAPTER_BODY)+ assert _structural_chapter_count(doc) == 3++ def test_headings_inside_a_closed_fence_still_ignored(self):+ doc = (+ "# The Document\n\n## Alpha\ntext\n\n"+ "```\n## 1. Not a section\n## 2. Also not\n## 3. Nor this\n```\n\n"+ "## Beta\ntext\n"+ )+ assert _structural_chapter_count(doc) == 2++ def test_document_with_no_headings(self):+ assert _structural_chapter_count("just prose\nmore prose\n") == 0