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
Prompt to install optional extractors
zuwasi18edd2138669
diff --git a/SKILL.md b/SKILL.mdindex c3d7f2d..f6f89e1 100644--- a/SKILL.md+++ b/SKILL.md@@ -142,9 +142,15 @@ if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; thenPYTHON_BIN="python"fi-"$PYTHON_BIN" "$SCRIPT_PATH" "$BOOK_PATH" --mode <BOOK_TYPE>+"$PYTHON_BIN" "$SCRIPT_PATH" "$BOOK_PATH" --mode <BOOK_TYPE> --install-missing ask```+Before extraction, the script checks optional Python packages needed for the detected format. If a better extractor is missing, it prompts the user with the available fallback, for example:++> "DOCX extraction uses python-docx if installed, otherwise a stdlib ZIP/XML parser. Missing package(s) detected. Do you want to install? y=install, n=fallback"++Use `--install-missing yes` to install missing Python packages without prompting, `--install-missing no` or `--no-install-missing` to always use fallbacks, or `BOOK_SKILL_INSTALL_MISSING=yes|no|ask` to set the behavior by environment variable. Non-interactive sessions default to fallback unless install mode is explicitly `yes`.+- PDF `--mode technical` → uses Docling (layout-aware, preserves tables and code blocks as markdown)- PDF `--mode text` → uses pdftotext → PyPDF2 → pdfminer fallback chain (fast, plain text)- EPUB → uses ebooklib + BeautifulSoup4, then stdlib ZIP/HTML fallback@@ -152,7 +158,7 @@ fi- TXT/Markdown/reStructuredText/AsciiDoc → reads directly as text- HTML → uses BeautifulSoup4, then stdlib HTML fallback- RTF → uses striprtf, then a basic regex fallback-- MOBI/AZW/AZW3 → uses Calibre `ebook-convert` when installed+- MOBI/AZW/AZW3 → uses Calibre `ebook-convert` when installed. Calibre is an external app, not a pip package, so the script reports how to install it if missing.This creates:- `<tempdir>/book_skill_work/full_text.txt` — full extracted textdiff --git a/scripts/extract.py b/scripts/extract.pyindex bd48d04..612d5ff 100644--- a/scripts/extract.py+++ b/scripts/extract.py@@ -27,6 +27,7 @@ Set BOOK_SKILL_WORKDIR to override the output directory.import htmlimport html.parser+import importlib.utilimport jsonimport osimport re@@ -58,6 +59,16 @@ SUPPORTED_EXTENSIONS = {*CALIBRE_EBOOK_EXTENSIONS,}+PYTHON_DEPENDENCIES = {+ "docling": "docling",+ "PyPDF2": "PyPDF2",+ "pdfminer": "pdfminer.six",+ "ebooklib": "ebooklib",+ "bs4": "beautifulsoup4",+ "docx": "python-docx",+ "striprtf": "striprtf",+}+def estimate_tokens(text: str) -> int:return int(len(text.split()) / WORDS_PER_TOKEN)@@ -67,6 +78,151 @@ def supported_formats_message() -> str:return ", ".join(sorted(SUPPORTED_EXTENSIONS))+def python_module_available(module_name: str) -> bool:+ return importlib.util.find_spec(module_name) is not None+++def missing_python_packages(module_names: list[str]) -> list[str]:+ missing = []+ for module_name in module_names:+ if not python_module_available(module_name):+ missing.append(PYTHON_DEPENDENCIES[module_name])+ return missing+++def install_python_packages(packages: list[str]) -> bool:+ if not packages:+ return True++ print(f"Installing missing Python package(s): {', '.join(packages)}")+ try:+ result = subprocess.run(+ [sys.executable, "-m", "pip", "install", *packages],+ text=True,+ timeout=600,+ )+ except Exception as exc:+ print(f"Package installation failed: {exc}", file=sys.stderr)+ return False++ importlib.invalidate_caches()+ return result.returncode == 0+++def normalize_install_mode(argv: list[str]) -> str:+ mode = os.environ.get("BOOK_SKILL_INSTALL_MISSING", "ask").lower()+ if "--no-install-missing" in argv:+ return "no"+ if "--install-missing" in argv:+ idx = argv.index("--install-missing")+ if idx + 1 < len(argv) and not argv[idx + 1].startswith("--"):+ mode = argv[idx + 1].lower()+ else:+ mode = "yes"+ if mode in {"1", "true", "y", "yes", "install"}:+ return "yes"+ if mode in {"0", "false", "n", "no", "fallback", "skip"}:+ return "no"+ return "ask"+++def offer_dependency_install(+ *,+ feature: str,+ module_names: list[str],+ fallback: str | None,+ install_mode: str,+) -> None:+ packages = missing_python_packages(module_names)+ if not packages:+ return++ message = f"{feature} uses {', '.join(packages)} if installed"+ if fallback:+ message += f", otherwise {fallback}"+ message += "."+ print(message)++ should_install = False+ if install_mode == "yes":+ should_install = True+ elif install_mode == "ask" and sys.stdin.isatty():+ answer = input("Missing package(s) detected. Do you want to install? y=install, n=fallback: ").strip().lower()+ should_install = answer in {"y", "yes", "install"}+ else:+ if fallback:+ print("Non-interactive mode or install disabled; using fallback.")+ else:+ print("Non-interactive mode or install disabled; installation skipped.")++ if not should_install:+ if fallback:+ print(f"Using fallback: {fallback}.")+ return++ if install_python_packages(packages):+ still_missing = missing_python_packages(module_names)+ if not still_missing:+ print("Package installation complete.")+ return+ print(f"Package installation incomplete; still missing: {', '.join(still_missing)}", file=sys.stderr)+ else:+ print("Package installation failed.", file=sys.stderr)++ if fallback:+ print(f"Using fallback: {fallback}.")+++def prepare_dependencies(ext: str, extraction_mode: str, install_mode: str) -> None:+ if ext == ".pdf" and extraction_mode == "technical":+ offer_dependency_install(+ feature="Technical PDF extraction",+ module_names=["docling"],+ fallback="the PDF text fallback chain",+ install_mode=install_mode,+ )++ if ext == ".pdf" and not shutil.which("pdftotext"):+ offer_dependency_install(+ feature="PDF text extraction",+ module_names=["PyPDF2", "pdfminer"],+ fallback="any installed Python PDF parser; extraction fails if none are available",+ install_mode=install_mode,+ )++ if ext == ".epub":+ offer_dependency_install(+ feature="EPUB extraction",+ module_names=["ebooklib", "bs4"],+ fallback="a stdlib ZIP/HTML parser",+ install_mode=install_mode,+ )++ if ext in HTML_EXTENSIONS:+ offer_dependency_install(+ feature="HTML extraction",+ module_names=["bs4"],+ fallback="a stdlib HTML parser",+ install_mode=install_mode,+ )++ if ext == ".docx":+ offer_dependency_install(+ feature="DOCX extraction",+ module_names=["docx"],+ fallback="a stdlib ZIP/XML parser",+ install_mode=install_mode,+ )++ if ext == ".rtf":+ offer_dependency_install(+ feature="RTF extraction",+ module_names=["striprtf"],+ fallback="a basic regex cleanup fallback",+ install_mode=install_mode,+ )++def read_text_file(path: str) -> str | None:for encoding in ("utf-8-sig", "utf-8", "cp1252", "latin-1"):try:@@ -434,11 +590,12 @@ def extract_with_docling(pdf_path: str) -> str | None:def main():if len(sys.argv) < 2:- print("Usage: extract.py <path-to-document> [--mode technical|text]", file=sys.stderr)+ print("Usage: extract.py <path-to-document> [--mode technical|text] [--install-missing ask|yes|no]", file=sys.stderr)print(f"Supported formats: {supported_formats_message()}", file=sys.stderr)sys.exit(1)input_path = sys.argv[1]+ install_mode = normalize_install_mode(sys.argv)# Parse --mode flagextraction_mode = "text"@@ -487,6 +644,15 @@ def main():sys.exit(1)OUTPUT_DIR.mkdir(parents=True, exist_ok=True)+ prepare_dependencies(ext, extraction_mode, install_mode)++ if ext in CALIBRE_EBOOK_EXTENSIONS and not shutil.which("ebook-convert"):+ print(+ "MOBI/AZW/AZW3 extraction requires Calibre's ebook-convert command. "+ "Install Calibre and ensure ebook-convert is on PATH, then rerun this command.",+ file=sys.stderr,+ )+ sys.exit(1)if ext == ".epub":print(f"Extracting EPUB: {input_path}")