Skip to content

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

fix(extractor): make chapter detection robust (no false positives, full scan) (#26)

Virgilio Junior4d8a7738ab47
diff --git a/scripts/extractor/utils.py b/scripts/extractor/utils.py
index 2a076fd..7cfd7c7 100644
--- a/scripts/extractor/utils.py
+++ b/scripts/extractor/utils.py
@@ -48,16 +48,49 @@ def estimate_tokens(text: str) -> int:
return int(len(text.split()) / WORDS_PER_TOKEN)
+# Explicit chapter heading: "Chapter 5", "Capítulo 5: ...", "Chapter 1. Intro".
+# Captures the number (bounded to 1..99 — drops years like "2025.") and whatever
+# follows it on the line, so we can reject prose.
+_EXPLICIT_CHAPTER = re.compile(
+ r"^\s*(?:chapter|cap[ií]tulo|ch\.?)\s*(\d{1,2})\b(?P<rest>.*)$", re.IGNORECASE
+)
+# A heading's number is followed by end-of-line, punctuation (". : - —"), or a
+# Capitalized title word. A lowercase continuation ("Chapter 6 explores...",
+# "Chapter 8 are relevant...") is prose / a cross-reference, not a heading.
+_HEADING_TAIL = re.compile(r"^\s*$|^\s*[.:\-—–]|^\s+[A-ZÀ-Ú0-9\"“(]")
+
+
+def _chapter_number(line: str) -> int | None:
+ """Return the chapter number if the line is a genuine chapter heading."""
+ s = line.strip()
+ if len(s) > 80:
+ return None
+ m = _EXPLICIT_CHAPTER.match(s)
+ if not m:
+ return None
+ if not _HEADING_TAIL.match(m.group("rest")):
+ return None
+ return int(m.group(1))
+
+
def detect_structure(text: str) -> dict:
- """Detect chapter count and table of contents presence."""
- lines = text[:50000].splitlines()
+ """Detect chapter count and table of contents presence.
- # Look for chapter headings
- chapter_pattern = re.compile(
- r"^\s*(chapter\s+\d+|CHAPTER\s+\d+|ch\.\s*\d+|\d+\.\s+[A-Z])",
- re.IGNORECASE
- )
- chapters_found = [line.strip() for line in lines if chapter_pattern.match(line)]
+ Scans the whole text (not just the head) and counts DISTINCT chapter numbers
+ 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 = text.splitlines()
+
+ headings = []
+ numbers = set()
+ for line in lines:
+ num = _chapter_number(line)
+ if num is not None:
+ numbers.add(num)
+ headings.append(line.strip())
+ chapters_detected = len(numbers)
# Look for ToC indicators in the first ~30k chars
toc_pattern = re.compile(
@@ -67,8 +100,8 @@ def detect_structure(text: str) -> dict:
has_toc = bool(toc_pattern.search(text[:30000]))
return {
- "chapters_detected": len(chapters_found),
- "chapter_headings_sample": chapters_found[:10],
+ "chapters_detected": chapters_detected,
+ "chapter_headings_sample": headings[:10],
"has_toc": has_toc,
}
diff --git a/tests/test_extractor.py b/tests/test_extractor.py
index 4a95feb..7fb4edd 100644
--- a/tests/test_extractor.py
+++ b/tests/test_extractor.py
@@ -552,6 +552,44 @@ class TestDetectStructure:
result = detect_structure(text)
assert result["has_toc"] is False
+ def test_numbered_list_items_are_not_chapters(self):
+ # The AI-Engineering failure: numbered list items were counted as chapters.
+ text = (
+ "1. Compared to characters, tokens allow the model to break words into\n"
+ "2. Because there are fewer unique tokens than unique words, this reduces\n"
+ "3. Tokens also help the model process unknown words, for instance a word\n"
+ )
+ assert detect_structure(text)["chapters_detected"] == 0
+
+ def test_inline_cross_references_are_not_chapters(self):
+ text = (
+ "Chapter 6 explores why context is important for a model to perform.\n"
+ "As discussed, Chapter 8 are relevant beyond finetuning in this case.\n"
+ )
+ assert detect_structure(text)["chapters_detected"] == 0
+
+ def test_years_are_not_chapters(self):
+ text = "2025. AI is often mentioned as a competitive advantage these days.\n"
+ assert detect_structure(text)["chapters_detected"] == 0
+
+ def test_real_headings_with_titles_count(self):
+ text = "Chapter 1. Introduction to Building AI\nbody\nChapter 2. Understanding Models\nbody\n"
+ assert detect_structure(text)["chapters_detected"] == 2
+
+ def test_portuguese_capitulo(self):
+ text = "Capítulo 1\nalgum texto\nCapítulo 2\nmais texto\n"
+ assert detect_structure(text)["chapters_detected"] == 2
+
+ def test_distinct_numbering_dedups_toc_and_body(self):
+ # A ToC heading and the body heading for the same chapter count once.
+ text = "Capítulo 1: Alicerces\n...\nCapítulo 1\nbody of chapter one\n"
+ assert detect_structure(text)["chapters_detected"] == 1
+
+ def test_scans_full_text_not_just_head(self):
+ # A chapter heading far past the old 50k-char window must still be found.
+ text = "Capítulo 1\n" + ("filler word " * 6000) + "\nCapítulo 2\n"
+ assert detect_structure(text)["chapters_detected"] == 2
+
class TestTextExtraction:
"""Tests for plain-text file extraction."""