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): use trafilatura for real boilerplate detection in HTML (#142)
Chris Brownb8ad0d0bf386
diff --git a/book_to_skill/config.py b/book_to_skill/config.pyindex ef20237..18ca0ce 100644--- a/book_to_skill/config.py+++ b/book_to_skill/config.py@@ -35,6 +35,7 @@ PYTHON_DEPENDENCIES = {"bs4": "beautifulsoup4","docx": "python-docx","striprtf": "striprtf",+ "trafilatura": "trafilatura",}diff --git a/book_to_skill/dependencies.py b/book_to_skill/dependencies.pyindex 6bef17f..a4c9bd4 100644--- a/book_to_skill/dependencies.py+++ b/book_to_skill/dependencies.py@@ -45,10 +45,10 @@ DEPENDENCY_GROUPS = [},{"label": "HTML",- "modules": ["bs4"],+ "modules": ["trafilatura", "bs4"],"any_of_modules": True,"system": [],- "note": "falls back to the stdlib html.parser if missing",+ "note": "trafilatura does real boilerplate detection; falls back to bs4, then the stdlib html.parser, if missing",},{"label": "RTF",diff --git a/book_to_skill/parsers/html.py b/book_to_skill/parsers/html.pyindex 1f391d5..a4d397a 100644--- a/book_to_skill/parsers/html.py+++ b/book_to_skill/parsers/html.py@@ -86,15 +86,52 @@ class _HTMLTextExtractor(html.parser.HTMLParser):def extract_html_content(raw_html: str) -> str:+ # Prints mirror extract_docx()'s "Trying X..." style so a run+ # says which of the three extractors actually answered, instead of+ # silently returning one of two materially different documents (the+ # trafilatura result strips page chrome the bs4/stdlib paths don't).+ print("Trying trafilatura...", end=" ", flush=True)+ try:+ import trafilatura+ except ImportError:+ trafilatura = None++ if trafilatura is not None:+ # trafilatura does real main-content/boilerplate detection (nav, footer,+ # ads, cookie banners) -- neither the bs4 path below nor the stdlib+ # fallback attempt this, they only strip script/style/head. Falls+ # through to bs4 on a missing dependency, a page trafilatura can't+ # confidently extract from (e.g. very short pages -- returns None or+ # whitespace, not always an exception), and on any parse failure+ # (e.g. malformed HTML raising inside trafilatura itself), rather than+ # propagating an exception or returning a silently empty result.+ try:+ extracted = trafilatura.extract(+ raw_html, include_tables=True, include_formatting=False+ )+ except Exception:+ extracted = None+ if extracted and extracted.strip():+ print("OK")+ return extracted+ print("no confident extraction, falling back")+ else:+ print("not available")++ print("Trying BeautifulSoup (bs4)...", end=" ", flush=True)try:from bs4 import BeautifulSoupsoup = BeautifulSoup(raw_html, "html.parser")for element in soup(["script", "style", "head"]):element.decompose()+ print("OK")return soup.get_text(separator="\n")except ImportError:+ print("not available")+ print("Trying stdlib HTML parser...", end=" ", flush=True)parser = _HTMLTextExtractor()parser.feed(raw_html)+ print("OK")return parser.get_text()diff --git a/docs/install.md b/docs/install.mdindex 781cb26..a3167bc 100644--- a/docs/install.md+++ b/docs/install.md@@ -78,6 +78,12 @@ book-to-skill ~/path/to/book.pdf --mode text # or: python -m book_to_skill ...book-to-skill --check # report which extractors are installed```+> **`[html]` is heavier than the others.** It pulls in `trafilatura`, which brings a full+> HTML-processing stack (lxml, a date parser, a timezone database, a URL classifier — 17+> packages total) to do real main-content/boilerplate detection instead of just stripping+> `<script>`/`<style>`. Worth knowing before installing on a constrained machine — the+> `bs4` fallback (no `[html]` extra needed) still works, just without boilerplate removal.+---diff --git a/pyproject.toml b/pyproject.tomlindex 4aacdd1..8fac3e9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -14,12 +14,14 @@ license = { text = "MIT" }book-to-skill = "book_to_skill.cli:main"[project.optional-dependencies]+html = ["trafilatura"]epub = ["ebooklib", "beautifulsoup4"]pdf = ["pypdf", "pdfminer.six"]docx = ["python-docx"]rtf = ["striprtf"]technical = ["docling"]all = [+ "trafilatura","ebooklib","beautifulsoup4","pypdf",diff --git a/tests/test_html_boilerplate_extraction.py b/tests/test_html_boilerplate_extraction.pynew file mode 100644index 0000000..1bfcd95--- /dev/null+++ b/tests/test_html_boilerplate_extraction.py@@ -0,0 +1,64 @@+"""extract_html_content() only stripped <script>/<style>/<head> on both the+bs4 and stdlib-fallback paths -- neither does real main-content vs. page-chrome+detection. Verified against 61 real pages scraped from personalmba.com (two+full chapters): a repeated footer block (ad + author bio + copyright notice)+appeared 183 times in the combined extracted text.++trafilatura is purpose-built for "find the article, discard the chrome" and is+now the primary path. This suite covers the fallback contract deterministically+(mocked import/return/exception states) rather than trafilatura's own+boilerplate-detection heuristics, which need realistic page-scale content to+exercise meaningfully and would be flaky against a tiny synthetic fixture --+that behavior is verified against the real 61-page corpus instead (see the PR+description for the before/after numbers).+"""++import sys+from pathlib import Path+from unittest.mock import patch++import pytest++ROOT_DIR = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT_DIR))++from book_to_skill.parsers.html import extract_html_content++SAMPLE_HTML = "<html><body><h1>Chapter 1</h1><p>Real content here.</p></body></html>"+++class TestTrafilaturaPrimaryPath:+ def test_uses_trafilatura_result_when_available(self):+ pytest.importorskip("trafilatura")+ with patch("trafilatura.extract", return_value="Chapter 1\nReal content here."):+ result = extract_html_content(SAMPLE_HTML)+ assert result == "Chapter 1\nReal content here."++ def test_falls_back_to_bs4_when_trafilatura_returns_none(self):+ pytest.importorskip("trafilatura")+ with patch("trafilatura.extract", return_value=None):+ result = extract_html_content(SAMPLE_HTML)+ assert "Real content here." in result++ def test_falls_back_to_bs4_when_trafilatura_returns_whitespace_only(self):+ # A near-empty/low-confidence result is still truthy -- must not be+ # returned as-is, or a page trafilatura can't confidently parse+ # silently produces an empty skill instead of falling through.+ pytest.importorskip("trafilatura")+ with patch("trafilatura.extract", return_value=" \n "):+ result = extract_html_content(SAMPLE_HTML)+ assert "Real content here." in result++ def test_falls_back_to_bs4_when_trafilatura_raises(self):+ # A parse-time exception (e.g. malformed HTML) must not propagate --+ # the whole point of this function is graceful degradation through+ # bs4 -> stdlib, not a hard failure on the best-effort first attempt.+ pytest.importorskip("trafilatura")+ with patch("trafilatura.extract", side_effect=ValueError("simulated parse failure")):+ result = extract_html_content(SAMPLE_HTML)+ assert "Real content here." in result++ def test_falls_back_to_bs4_when_trafilatura_not_installed(self):+ with patch.dict(sys.modules, {"trafilatura": None}):+ result = extract_html_content(SAMPLE_HTML)+ assert "Real content here." in result