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
feat(extractor): detect setext/RST underline headings (#51)
Shubham Srivastavada474c0707dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e21e86..5573ed5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0table-of-contents languages added previously.- Heading-title detection now accepts titles starting with `Ü`/`Û`/`Ý`/`Þ`(e.g. German "Überblick"), which the previous `À–Ú` range excluded.+- Structure detection now recognizes setext / reStructuredText underline+ headings (a title line over a row of `=` or `-`), so `.rst` and setext-style+ Markdown sources are no longer detected as zero-chapter.+- All-punctuation ATX "titles" (e.g. a `===== =====` simple-table border) are+ no longer miscounted as chapters.### Security- **CI security scanning** — added CodeQL (Python, security-and-quality + weeklydiff --git a/scripts/extractor/utils.py b/scripts/extractor/utils.pyindex df31886..12dbff0 100644--- a/scripts/extractor/utils.py+++ b/scripts/extractor/utils.py@@ -113,40 +113,63 @@ _TOC_PATTERN = re.compile(# reStructuredText underline "=====" (no space) — the latter is intentionally# ignored (RST underline headings are out of scope)._ATX_HEADING = re.compile(r"^(#{1,6}|={1,6})\s+(.+?)\s*#*$")+# Setext/RST underline: a full line of "=" (level 1) or "-" (level 2), length+# >= 2. Marks the line directly above it as a heading title.+_SETEXT_UNDERLINE = re.compile(r"^(={2,}|-{2,})$")def _structural_chapter_count(text: str) -> int:- """Count chapter-like ATX headings in Markdown/AsciiDoc sources.-- Groups distinct (case-normalized) heading titles by depth and returns the- count at the shallowest depth with >= 2 distinct headings — this selects the- real chapter level in the common "# Book Title / ## Chapter" layout where the- top level appears once. Headings inside fenced code blocks are skipped so a- "# comment" in a code sample is not mistaken for a chapter. Headings whose- title starts with an ASCII digit (e.g. "## 5 Setup") are excluded — they- are numeric-list-style, not chapters.+ """Count chapter-like structural headings in Markdown/AsciiDoc/RST sources.++ Recognizes ATX headings ("# Title", "== Section") and setext/RST underline+ headings (a title line directly above a row of "=" or "-"). Groups distinct+ (case-normalized) titles by depth and returns the count at the shallowest+ depth with >= 2 distinct titles — this selects the real chapter level in the+ common "# Book Title / ## Chapter" layout where the top level appears once.++ Guards against false positives: headings inside fenced code blocks are+ skipped; an ATX title starting with a bare digit ("## 5 Setup") or made only+ of punctuation ("=====" table borders) is rejected; a setext underline counts+ only when it sits directly under a non-blank title line at least as long as+ the underline (so thematic breaks, table borders, and front-matter "---" do+ not match)."""levels: dict[int, set[str]] = {}in_fence = False+ prev = "" # previous non-fence line (stripped); a setext title candidatefor line in text.splitlines():s = line.strip()if s.startswith("```") or s.startswith("~~~"):in_fence = not in_fence+ prev = ""continueif in_fence:+ prev = ""continue- m = _ATX_HEADING.match(s)- if not m:- continue- title = m.group(2).strip().lower()- if not title:+ # Setext/RST underline: "=" (level 1) or "-" (level 2) directly under a+ # title line at least as long as the underline.+ if (+ _SETEXT_UNDERLINE.match(s)+ and prev+ and not _SETEXT_UNDERLINE.match(prev)+ and len(s) >= len(prev)+ ):+ depth = 1 if s[0] == "=" else 2+ levels.setdefault(depth, set()).add(prev.lower())+ prev = ""continue- # Skip headings whose title starts with a bare ASCII digit ("## 5 Setup").- # These are numeric list-item style headings, not chapter headings; they- # were intentionally excluded from numeric detection and must stay excluded.- if title[0].isdigit():+ # 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)+ # An ATX heading line is not a setext title for the next line.+ prev = ""continue- levels.setdefault(len(m.group(1)), set()).add(title)+ prev = sif not levels:return 0for depth in sorted(levels):diff --git a/tests/test_extractor.py b/tests/test_extractor.pyindex e5ff7b8..3fda846 100644--- a/tests/test_extractor.py+++ b/tests/test_extractor.py@@ -757,6 +757,57 @@ class TestDetectStructure:text = "I: Überblick\nbody\nII: Anfang\nbody\n"assert detect_structure(text)["chapters_detected"] == 2+ def test_setext_rst_equals_three_sections(self):+ text = ("Introduction\n============\nbody\n\n"+ "Getting Started\n===============\nbody\n\n"+ "Advanced\n========\nbody\n")+ assert detect_structure(text)["chapters_detected"] == 3++ def test_setext_rst_dash_two_sections(self):+ text = "Methods\n-------\nbody\n\nResults\n-------\nbody\n"+ assert detect_structure(text)["chapters_detected"] == 2++ def test_setext_markdown_h1(self):+ text = "First\n=====\ntext\n\nSecond\n======\ntext\n"+ assert detect_structure(text)["chapters_detected"] == 2++ def test_setext_equals_top_level_wins_over_dash(self):+ # "=" (level 1) is shallower than "-" (level 2); the two "=" titles win.+ text = "Chap One\n========\nSec a\n-----\nSec b\n-----\nChap Two\n========\n"+ assert detect_structure(text)["chapters_detected"] == 2++ def test_setext_thematic_break_under_paragraph_not_heading(self):+ text = "This is a normal paragraph of body text.\n---\nmore text follows here too.\n"+ assert detect_structure(text)["chapters_detected"] == 0++ def test_setext_horizontal_rule_with_blank_above_not_heading(self):+ text = "text here\n\n---\n\nmore\n\n***\n"+ assert detect_structure(text)["chapters_detected"] == 0++ def test_setext_simple_table_border_not_heading(self):+ text = "Name Value\n===== =====\nfoo 1\nbar 2\n"+ assert detect_structure(text)["chapters_detected"] == 0++ def test_setext_yaml_front_matter_not_heading(self):+ text = "---\ntitle: foo\nauthor: bar\n---\nbody text here\n"+ assert detect_structure(text)["chapters_detected"] == 0++ def test_setext_inside_code_fence_ignored(self):+ text = "```\nTitle\n=====\nAnother\n=======\n```\n"+ assert detect_structure(text)["chapters_detected"] == 0++ def test_atx_all_punctuation_title_not_heading(self):+ # "===== =====" matches the ATX regex (group 2 = "====="), but the \w guard+ # rejects it: an all-punctuation title is not a real heading.+ text = "intro line\n===== =====\nbody\n"+ assert detect_structure(text)["chapters_detected"] == 0++ def test_atx_heading_followed_by_underline_not_double_counted(self):+ # A malformed mix (ATX heading then a "=" underline) must not count the+ # same heading twice (once as ATX, once as setext).+ text = "# Hi\n====\n# Bye\n=====\n"+ assert detect_structure(text)["chapters_detected"] == 2+class TestTextExtraction:"""Tests for plain-text file extraction."""