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: initial release of book-to-skill
Virgilio Borges7295b94e0d46
diff --git a/README.md b/README.mdnew file mode 100644index 0000000..f3e0bca--- /dev/null+++ b/README.md@@ -0,0 +1,179 @@+<h1 align="center">📚 book-to-skill</h1>++<p align="center">+ <strong>Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.</strong>+</p>++<p align="center">+ <img src="https://img.shields.io/badge/Claude_Code-Skill-blueviolet?style=for-the-badge" alt="Claude Code Skill">+ <img src="https://img.shields.io/badge/effort-high-orange?style=for-the-badge" alt="Effort: high">+ <img src="https://img.shields.io/badge/License-MIT-blue?style=for-the-badge" alt="MIT License">+</p>++<p align="center">+ <a href="#-why">Why</a> ·+ <a href="#-what-it-generates">What it generates</a> ·+ <a href="#-usage">Usage</a> ·+ <a href="#-requirements">Requirements</a> ·+ <a href="#-how-it-works">How it works</a> ·+ <a href="#-install">Install</a>+</p>++---++## 🤔 Why++You buy a great technical book. You read it once. Three months later you can't remember chapter 7 existed.++The usual workarounds don't help:+- 📄 "Let me just search the PDF" → you get a list of pages, not answers+- 🧠 "I'll ask Claude about this book" → it either hallucinates or says it doesn't have the content+- 📝 "I'll take notes as I read" → you end up with a 200-line doc you never open again++**book-to-skill solves this by turning the PDF into a structured skill Claude loads on demand.**++Once installed, you just type `/your-book-slug replication` and Claude reads the right chapter and answers from the actual content. No hallucination. No digging through PDFs. The book becomes part of your workflow.++---++## 📦 What it generates++Running `/book-to-skill your-book.pdf` creates a full skill at `~/.claude/skills/<slug>/`:++| File | Purpose | Size |+|------|---------|------|+| `SKILL.md` | Core mental models + chapter index | ~4,000 tokens |+| `chapters/ch01-*.md` … | One file per chapter, loaded on-demand | ~1,000 tokens each |+| `glossary.md` | Every key term, alphabetically sorted with chapter refs | ~1,500 tokens |+| `patterns.md` | All techniques, algorithms, and design patterns | ~2,000 tokens |+| `cheatsheet.md` | Decision tables and quick-reference rules | ~1,000 tokens |++**Chapter files are loaded on-demand** — they don't count against the skill budget until you ask about that topic.++---++## 🚀 Usage++```+/book-to-skill <path-to-pdf> [skill-name-slug]+```++**Examples:**++```bash+# Derive skill name from filename+/book-to-skill ~/Downloads/designing-data-intensive-applications.pdf++# Specify a custom slug+/book-to-skill ~/books/clean-code.pdf clean-code++# Full path with explicit name+/book-to-skill /tmp/ddd-evans.pdf domain-driven-design+```++After the skill is created, use it like any other Claude Code skill:++```bash+/designing-data-intensive-apps # load core mental models+/designing-data-intensive-apps replication # find and explain a topic+/designing-data-intensive-apps ch05 # dive into chapter 5+/designing-data-intensive-apps "what chapters do you have?"+```++---++## 🔧 Requirements++At least one PDF extraction tool must be installed:++| Tool | Install | Quality |+|------|---------|---------|+| `pdftotext` (poppler) | `sudo apt install poppler-utils` | ⭐⭐⭐ Best layout fidelity |+| `PyPDF2` | `pip3 install PyPDF2` | ⭐⭐ Good |+| `pdfminer.six` | `pip3 install pdfminer.six` | ⭐⭐ Good fallback |++The extraction script tries them in order and uses the first available. If none is found, it tells you exactly which command to run.++---++## ⚙️ How it works++```+ │+ ▼+scripts/extract.py ← tries pdftotext → PyPDF2 → pdfminer+ │+ ├── /tmp/book_skill_work/full_text.txt+ └── /tmp/book_skill_work/metadata.json+ │+ ▼+ Claude analyzes structure+ (title, author, chapters, ToC)+ │+ ▼+ Generates per-chapter summaries (800–1,200 tokens each)+ Generates glossary, patterns, cheatsheet+ Generates master SKILL.md with core mental models+ │+ ▼+ ~/.claude/skills/<slug>/ ✅ written+ /tmp/book_skill_work/ 🗑️ cleaned up+```++<details>+<summary>Design principles (click to expand)</summary>++1. **Density over completeness** — a 1,000-token summary beats a 10,000-token excerpt+2. **Practitioner voice** — "Use X when Y", not "The book explains X"+3. **Front-loaded SKILL.md** — compaction keeps the first ~5,000 tokens; the most important content comes first+4. **On-demand chapters** — the topic index tells Claude which file to read; chapters load only when needed+5. **Never raw text** — always synthesize, summarize, extract signal from the source++</details>++---++## 📥 Install++Copy this into your Claude Code session:++```+Install book-to-skill: https://raw.githubusercontent.com/YOUR_USERNAME/YOUR_REPO/main/SKILL.md+```++Or manually:++```bash+mkdir -p ~/.claude/skills/book-to-skill/scripts++curl -o ~/.claude/skills/book-to-skill/SKILL.md \+ https://raw.githubusercontent.com/YOUR_USERNAME/YOUR_REPO/main/SKILL.md++curl -o ~/.claude/skills/book-to-skill/scripts/extract.py \+ https://raw.githubusercontent.com/YOUR_USERNAME/YOUR_REPO/main/scripts/extract.py+```++Then in any Claude Code session:++```bash+/book-to-skill ~/path/to/your-book.pdf+```++---++## 📁 Repository structure++```+book-to-skill/+├── SKILL.md # Skill definition + step-by-step instructions+├── scripts/+│ └── extract.py # PDF extraction (pdftotext / PyPDF2 / pdfminer)+└── README.md # This file+```++---++## License++MITdiff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..13ed582--- /dev/null+++ b/SKILL.md@@ -0,0 +1,260 @@+---+name: book-to-skill+description: Converts a technical book PDF into a structured Claude Code skill with indexed chapters, core mental models, patterns, glossary, and cheatsheet. Use when the user wants to study a technical book through Claude, reference a book during work, or build a reusable knowledge base from any PDF.+when_to_use: Trigger phrases — "turn this book into a skill", "create a skill from this PDF", "I want to study X book", "add this book to my skills", "convert PDF to skill". Accepts a path to a PDF and optional skill name slug.+disable-model-invocation: true+context: fork+agent: general-purpose+allowed-tools: Bash(python3 *) Bash(pdftotext *) Bash(mkdir *) Bash(cp *) Bash(find *) Bash(wc *) Bash(echo *) Bash(cat *) Bash(date *) Read Write Glob Grep+argument-hint: <path-to-pdf> [skill-name-slug]+arguments: [pdf_path, skill_name]+effort: high+---++# Book-to-Skill Converter++Convert a technical book PDF into a well-structured Claude Code skill optimized for study and reference.++## Input+- `$0` — absolute or relative path to the PDF file+- `$1` — (optional) skill name slug, e.g. `designing-data-apps`. Derived from filename if omitted.++---++## Step 0 — Out-of-scope check++If the argument is NOT a path to a PDF, stop and respond:+> "book-to-skill requires a PDF path. Usage: `/book-to-skill /path/to/book.pdf [skill-name]`"++---++## Step 1 — Validate input++```bash+test -f "$0" && echo "FILE_OK" || echo "FILE_NOT_FOUND: $0"+file "$0" | grep -i pdf && echo "IS_PDF" || echo "NOT_PDF"+```++If the file is not found or not a PDF, stop with a clear error message.++---++## Step 2 — Extract text from PDF++Run the extraction script:++```bash+python3 ~/.claude/skills/book-to-skill/scripts/extract.py "$0"+```++This creates:+- `/tmp/book_skill_work/full_text.txt` — full extracted text+- `/tmp/book_skill_work/metadata.json` — title, estimated pages, token count, size++Read `/tmp/book_skill_work/metadata.json` to understand what was extracted.++---++## Step 3 — Analyze book structure++Read the first 8,000 characters of `/tmp/book_skill_work/full_text.txt` to identify:+- Book **title** and **author(s)**+- **Chapter structure** (look for "Chapter N", "PART I", numbered headings, table of contents)+- **Core themes** and subject domain+- Approximate number of chapters++Then read the Table of Contents section if present to map all chapters.++---++## Step 4 — Determine skill name++If `$1` was provided, use it as the skill slug.+Otherwise, derive from the book title: lowercase, hyphens, no special chars.+Example: "Designing Data-Intensive Applications" → `designing-data-intensive-apps`++Check that `~/.claude/skills/<skill_name>/` does NOT already exist.+If it does, append `-2` or ask the user before overwriting.++---++## Step 5 — Create skill directory structure++```bash+mkdir -p ~/.claude/skills/<skill_name>/chapters+```++---++## Step 6 — Generate chapter summaries++**TOKEN BUDGET RULE — CRITICAL:**+- Each chapter summary file: **800–1,200 tokens** (dense, not verbose)+- Files are loaded on-demand — they are NOT capped per se, but keep them useful and tight++For EACH chapter/major section identified in Step 3:++Read the corresponding section of `/tmp/book_skill_work/full_text.txt` (use character offsets or grep for chapter headings).++Create `~/.claude/skills/<skill_name>/chapters/ch<NN>-<slug>.md` with this structure:++```markdown+# Chapter N: <Full Title>++## Core Idea+<1–2 sentences: the single most important thing this chapter teaches>++## Key Concepts+- **<Term>**: <precise definition in 1 sentence>+- **<Term>**: <precise definition in 1 sentence>+(5–10 most important terms from this chapter)++## Mental Models+<2–4 frameworks or thinking tools introduced. Write as "Use X when Y" or "Think of X as Y">++## Patterns & Techniques+<Concrete approaches, algorithms, or methods. Numbered list. Action-oriented.>++## Key Takeaways+1. <Actionable insight>+2. <Actionable insight>+3. <Actionable insight>+(3–7 takeaways that a practitioner must remember)++## Connects To+- **Ch N**: <why this chapter relates>+- **<Concept>**: <external concept or standard it connects with>+```++---++## Step 7 — Generate supporting files++### glossary.md+Create `~/.claude/skills/<skill_name>/glossary.md`:+- Every significant term from the book, alphabetically sorted+- Format: `**Term** — definition (Ch N)`+- Max 1,500 tokens++### patterns.md+Create `~/.claude/skills/<skill_name>/patterns.md`:+- All concrete techniques, design patterns, algorithms from the book+- Format: `## Pattern Name\n**When to use**: ...\n**How**: ...\n**Trade-offs**: ...`+- Max 2,000 tokens++### cheatsheet.md+Create `~/.claude/skills/<skill_name>/cheatsheet.md`:+- Decision tables, comparison matrices, quick-reference rules+- The content you'd want on a single printed page+- Max 1,000 tokens++---++## Step 8 — Generate the master SKILL.md++**CRITICAL TOKEN BUDGET: Keep SKILL.md body under 4,000 tokens.**+Compaction truncates from the END — put the most important content FIRST.++Create `~/.claude/skills/<skill_name>/SKILL.md`:++```markdown+---+name: <skill_name>+description: Knowledge base from "<Full Title>" by <Author(s)>. Use when working with <key topics, 3–6 terms>. Covers <N> chapters on <brief scope sentence>.+when_to_use: <10–15 trigger phrases based on book topics and terms. Comma-separated.>+allowed-tools: Read Grep+argument-hint: [topic, chapter number, or concept]+---++# <Full Title>+**Author**: <Author(s)> | **Pages**: ~<N> | **Chapters**: <N> | **Generated**: <YYYY-MM-DD>++## How to Use This Skill++- **Without arguments** — `/skill-name` loads core mental models for reference+- **With a topic** — `/skill-name replication` → I find and read the relevant chapter+- **With chapter** — `/skill-name ch05` → I load that specific chapter+- **Browse** — ask "what chapters do you have?" to see the full index++When you ask about a topic not covered in Core Mental Models below, I will read+the relevant chapter file before answering.++---++## Core Mental Models+<!-- ~2,000 tokens: the 10–15 most important concepts from the ENTIRE book.+ Written as dense, actionable knowledge. Not summaries — practitioner insights.+ Use imperative: "Use X when Y", "Prefer X over Y because Z", "When X, always Y". -->++<generate 2,000 tokens of the most critical insights from the entire book here>++---++## Chapter Index++| # | Title | Key Topics |+|---|-------|------------|+| [ch01](chapters/ch01-<slug>.md) | <Title> | <topic1>, <topic2>, <topic3> |+| [ch02](chapters/ch02-<slug>.md) | <Title> | <topic1>, <topic2>, <topic3> |+...++## Topic Index++<!-- Alphabetical. Major terms → chapter(s) that cover them. -->+- **<Term>** → ch<N>[, ch<N>]+- **<Term>** → ch<N>++## Supporting Files++- [glossary.md](glossary.md) — all key terms with definitions+- [patterns.md](patterns.md) — all techniques and design patterns+- [cheatsheet.md](cheatsheet.md) — quick reference tables and decision guides++---++## Scope & Limits++This skill covers the book content only. For hands-on implementation in your codebase,+combine with project-specific tools. For topics beyond this book, check related skills+or ask Claude directly.+```++---++## Step 9 — Cleanup and report++```bash+rm -rf /tmp/book_skill_work+```++Then report to the user:++```+✅ Skill created: ~/.claude/skills/<skill_name>/++📚 Book: <Full Title> — <Author>+📄 Pages: ~<N> | Chapters: <N>++Files generated:+ SKILL.md — core concepts + index (~X tokens)+ chapters/ — <N> chapter summaries (~X tokens each)+ glossary.md — key terms+ patterns.md — techniques & patterns+ cheatsheet.md — quick reference++Usage:+ /<skill_name> → load core mental models+ /<skill_name> <topic> → find and explain a topic+ /<skill_name> ch<N> → dive into a specific chapter+```++---++## Quality Rules++1. **Density over completeness** — a 1,000-token summary beats a 10,000-token excerpt+2. **Practitioner voice** — write "Use X when Y", not "The book explains X"+3. **Front-load SKILL.md** — compaction keeps the first 5,000 tokens; most important content comes first+4. **Chapter files are on-demand** — they don't count against skill budget until loaded+5. **Never copy raw book text** — always synthesize, summarize, extract signal+6. **Topic index is critical** — it's how Claude navigates to the right chapter filediff --git a/scripts/extract.py b/scripts/extract.pynew file mode 100644index 0000000..caff726--- /dev/null+++ b/scripts/extract.py@@ -0,0 +1,202 @@+#!/usr/bin/env python3+"""+Extract text from a PDF file for book-to-skill processing.++Tries extraction methods in order:+ 1. pdftotext (poppler-utils) — best quality+ 2. PyPDF2 — common Python library+ 3. pdfminer.six — thorough fallback++Outputs:+ /tmp/book_skill_work/full_text.txt — full extracted text+ /tmp/book_skill_work/metadata.json — stats and metadata+"""++import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++OUTPUT_DIR = Path("/tmp/book_skill_work")+OUTPUT_TEXT = OUTPUT_DIR / "full_text.txt"+OUTPUT_META = OUTPUT_DIR / "metadata.json"++WORDS_PER_TOKEN = 0.75 # approximate+++def estimate_tokens(text: str) -> int:+ return int(len(text.split()) / WORDS_PER_TOKEN)+++def extract_with_pdftotext(pdf_path: str) -> str | None:+ if not shutil.which("pdftotext"):+ return None+ try:+ result = subprocess.run(+ ["pdftotext", "-layout", pdf_path, "-"],+ capture_output=True, text=True, timeout=120+ )+ if result.returncode == 0 and result.stdout.strip():+ return result.stdout+ except Exception:+ pass+ return None+++def extract_with_pypdf2(pdf_path: str) -> str | None:+ try:+ import PyPDF2+ text_parts = []+ with open(pdf_path, "rb") as f:+ reader = PyPDF2.PdfReader(f)+ for page in reader.pages:+ try:+ text_parts.append(page.extract_text() or "")+ except Exception:+ text_parts.append("")+ return "\n".join(text_parts)+ except ImportError:+ return None+ except Exception:+ return None+++def extract_with_pdfminer(pdf_path: str) -> str | None:+ try:+ from pdfminer.high_level import extract_text+ return extract_text(pdf_path)+ except ImportError:+ return None+ except Exception:+ return None+++def count_pages(pdf_path: str) -> int:+ # Try pdfinfo first+ if shutil.which("pdfinfo"):+ try:+ result = subprocess.run(+ ["pdfinfo", pdf_path], capture_output=True, text=True, timeout=15+ )+ for line in result.stdout.splitlines():+ if line.startswith("Pages:"):+ return int(line.split(":")[1].strip())+ except Exception:+ pass+ # Fallback: count form-feed chars (pdftotext -layout uses \f between pages)+ try:+ import PyPDF2+ with open(pdf_path, "rb") as f:+ return len(PyPDF2.PdfReader(f).pages)+ except Exception:+ return 0+++def detect_structure(text: str) -> dict:+ """Detect chapter count and table of contents presence."""+ import re+ lines = text[:50000].splitlines()++ # 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 = [l.strip() for l in lines if chapter_pattern.match(l)]++ # Look for ToC indicators+ toc_keywords = ["table of contents", "contents", "índice", "sumário"]+ has_toc = any(kw in text[:5000].lower() for kw in toc_keywords)++ return {+ "chapters_detected": len(chapters_found),+ "chapter_headings_sample": chapters_found[:10],+ "has_toc": has_toc,+ }+++def main():+ if len(sys.argv) < 2:+ print("Usage: extract.py <path-to-pdf>", file=sys.stderr)+ sys.exit(1)++ pdf_path = sys.argv[1]++ if not os.path.exists(pdf_path):+ print(f"ERROR: File not found: {pdf_path}", file=sys.stderr)+ sys.exit(1)++ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)++ print(f"Extracting: {pdf_path}")+ print("Trying pdftotext...", end=" ", flush=True)+ text = extract_with_pdftotext(pdf_path)++ if text:+ method = "pdftotext"+ print("OK")+ else:+ print("not available")+ print("Trying PyPDF2...", end=" ", flush=True)+ text = extract_with_pypdf2(pdf_path)+ if text:+ method = "PyPDF2"+ print("OK")+ else:+ print("not available")+ print("Trying pdfminer.six...", end=" ", flush=True)+ text = extract_with_pdfminer(pdf_path)+ if text:+ method = "pdfminer"+ print("OK")+ else:+ print("FAILED")+ print(+ "\nERROR: Could not extract text from PDF.\n"+ "Install one of: poppler-utils (pdftotext), PyPDF2, or pdfminer.six\n"+ " sudo apt install poppler-utils\n"+ " pip3 install PyPDF2\n"+ " pip3 install pdfminer.six",+ file=sys.stderr,+ )+ sys.exit(1)++ # Write full text+ OUTPUT_TEXT.write_text(text, encoding="utf-8")++ pages = count_pages(pdf_path)+ tokens = estimate_tokens(text)+ structure = detect_structure(text)+ file_size_mb = os.path.getsize(pdf_path) / (1024 * 1024)++ metadata = {+ "source_file": str(Path(pdf_path).resolve()),+ "filename": Path(pdf_path).name,+ "extraction_method": method,+ "file_size_mb": round(file_size_mb, 2),+ "pages": pages,+ "chars": len(text),+ "words": len(text.split()),+ "estimated_tokens": tokens,+ "estimated_tokens_human": f"~{tokens // 1000}K",+ "output_text": str(OUTPUT_TEXT),+ **structure,+ }++ OUTPUT_META.write_text(json.dumps(metadata, indent=2, ensure_ascii=False))++ print(f"\n📖 Extraction complete:")+ print(f" Method : {method}")+ print(f" Pages : {pages}")+ print(f" Words : {len(text.split()):,}")+ print(f" Tokens : ~{tokens // 1000}K")+ print(f" Chapters: {structure['chapters_detected']} detected")+ print(f" ToC : {'yes' if structure['has_toc'] else 'not detected'}")+ print(f"\n Text → {OUTPUT_TEXT}")+ print(f" Meta → {OUTPUT_META}")+++if __name__ == "__main__":+ main()