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: add multi-source extraction and existing skill updating
Marcello Mendoa1d95a03f5e6
diff --git a/SKILL.md b/SKILL.mdindex 990acf1..b352919 100644--- a/SKILL.md+++ b/SKILL.md@@ -8,7 +8,7 @@ allowed-tools:- Write- Glob- Grep-argument-hint: <path-to-document> [skill-name-slug]+argument-hint: <path-to-document-folder-or-glob>... [skill-name-slug]---# Book-to-Skill Converter@@ -34,10 +34,10 @@ Books contain crystallized expertise: frameworks, principles, and techniques tha## Modes of Operation-Three paths available. Route based on what the user asks:+Four paths available. Route based on what the user asks:### 1. Full Conversion (Default)-**Trigger:** User provides a supported document path without special instructions+**Trigger:** User provides one or more document/directory/glob paths without special instructions**Action:** Run all steps below (Steps 0–9)**Output:** Complete skill with SKILL.md, chapters/, glossary, patterns, cheatsheet@@ -51,6 +51,11 @@ Three paths available. Route based on what the user asks:**Action:** Skip Steps 0–3, use the provided analysis as input, run Steps 4–9**Output:** Skill files from the provided analysis+### 4. Update / Fold-in (Existing Skill)+**Trigger:** User provides one or more new source paths and indicates they want to update an existing skill (either by pointing to the existing skill folder, providing a skill slug that already exists in `SKILLS_HOME`, or explicitly requesting an update).+**Action:** Run Step 0 (out-of-scope check), Step 1 (validate inputs), Step 1.5 (identify book type), and Step 2 (extract new files). Then skip to Step 5 (identify/detect existing skill path) and run the **Update / Fold-in Workflow** to merge the new content into the existing skill files.+**Output:** Updated existing skill with new/revised chapter summaries and merged indexes/glossaries.+---## Skill Locations@@ -68,34 +73,31 @@ Generated skills should default to `~/.config/agents/skills/` for Amp unless the## Step 0 — Out-of-scope check-If the argument is NOT a path to a supported document file, stop and respond:-> "book-to-skill requires a supported document path. Usage: `book-to-skill /path/to/book.pdf [skill-name]`, `book-to-skill /path/to/book.epub [skill-name]`, or another supported format such as `.docx`, `.md`, `.txt`, `.html`, `.rtf`, `.mobi`, or `.azw3`."+If no arguments are provided, stop and respond:+> "book-to-skill requires a supported document path, folder, or glob pattern. Usage: `book-to-skill <path-to-document-folder-or-glob>... [skill-name-slug]`"-Throughout the workflow, treat the first argument as `BOOK_PATH` and the optional second argument as `SKILL_NAME`.+Throughout the workflow:+- Identify the input paths and the optional skill slug.+- If the last argument is not a file, folder, or glob that exists or matches any files, and it looks like a skill slug (e.g. lowercase hyphens, alphanumeric), treat it as `SKILL_NAME`.+- Treat all other arguments as the list of `INPUT_PATHS`.+- If any input path is an existing skill directory (contains `SKILL.md` and a `chapters/` sub-folder), or if `SKILL_NAME` matches an existing skill slug in `SKILLS_HOME`, flag this run as an **Update/Fold-in** operation (Mode 4).---## Step 1 — Validate input-```bash-test -f "$BOOK_PATH" && echo "FILE_OK" || echo "FILE_NOT_FOUND: $BOOK_PATH"-case "${BOOK_PATH##*.}" in- pdf|PDF|epub|EPUB|docx|DOCX|txt|TXT|md|MD|markdown|MARKDOWN|rst|RST|adoc|ADOC|asciidoc|ASCIIDOC|html|HTML|htm|HTM|rtf|RTF|mobi|MOBI|azw|AZW|azw3|AZW3) echo "FORMAT_OK" ;;- *) echo "FORMAT_UNKNOWN" ;;-esac-```--Check the file extension (`.pdf`, `.epub`, `.docx`, `.txt`, `.md`, `.markdown`, `.rst`, `.adoc`, `.html`, `.htm`, `.rtf`, `.mobi`, `.azw`, `.azw3`) or magic bytes (`%PDF` or `PK` zip header for EPUB/DOCX).+Verify that there is at least one supported file, directory, or glob pattern among the `INPUT_PATHS`.+For directories and globs, expand them to find matching supported files (`.pdf`, `.epub`, `.docx`, `.txt`, `.md`, `.markdown`, `.rst`, `.adoc`, `.html`, `.htm`, `.rtf`, `.mobi`, `.azw`, `.azw3`).-If the file is not found or the format is not supported, stop with a clear error message listing supported formats.+If no supported files are found, stop with a clear error message.----## Step 1.5 — Identify book type+## Step 1.5 — Identify content typeBefore extracting, ask the user:-> "What kind of content does this book have? This helps me choose the best extraction method.+> "What kind of content do these sources have? This helps me choose the best extraction method.>> 1. **Technical** — has code blocks, tables, formulas, diagrams (e.g. programming books, academic papers, architecture guides)> 2. **Text-heavy** — mostly prose, few or no tables/code (e.g. management, productivity, narrative non-fiction)@@ -107,16 +109,16 @@ Store the answer as `BOOK_TYPE`:- Option 3 → `BOOK_TYPE=text`**If `BOOK_TYPE=technical`**, inform the user before proceeding:-> "📐 Technical mode selected — using Docling for structure-aware extraction (tables, code blocks, formulas preserved as markdown). This takes ~1.5s per page, so expect a few minutes for longer books. Starting now…"+> "📐 Technical mode selected — using Docling for structure-aware extraction (tables, code blocks, formulas preserved as markdown). This takes ~1.5s per page, so expect a few minutes for longer sources. Starting now…"**If `BOOK_TYPE=text`**, inform:-> "📄 Text mode selected — using the fastest suitable extractor for this file type. Plain text/Markdown/HTML are usually ready in seconds; PDFs use pdftotext when available."+> "📄 Text mode selected — using the fastest suitable extractor for each file type. Plain text/Markdown/HTML are usually ready in seconds; PDFs use pdftotext when available."----## Step 2 — Extract text from the source document+## Step 2 — Extract text from the source documents-Run the extraction script, passing the book type:+Run the extraction script, passing the input paths:```bashSCRIPT_PATH=""@@ -142,29 +144,16 @@ if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; thenPYTHON_BIN="python"fi-"$PYTHON_BIN" "$SCRIPT_PATH" "$BOOK_PATH" --mode <BOOK_TYPE> --install-missing ask+"$PYTHON_BIN" "$SCRIPT_PATH" $INPUT_PATHS --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-- DOCX → uses python-docx, then stdlib ZIP/XML fallback-- 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. Calibre is an external app, not a pip package, so the script reports how to install it if missing.+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. Non-interactive sessions default to fallback unless install mode is explicitly `yes`.This creates:-- `<tempdir>/book_skill_work/full_text.txt` — full extracted text-- `<tempdir>/book_skill_work/metadata.json` — title, estimated pages, token count, size, extraction_mode+- `<tempdir>/book_skill_work/full_text.txt` — combined extracted text of all sources with clear visually demarcated boundaries.+- `<tempdir>/book_skill_work/metadata.json` — overall combined size, words, pages, token counts, and a detailed list of individual processed `sources`.-Read the `output_text` path in `<tempdir>/book_skill_work/metadata.json` to understand what was extracted. The extractor uses the platform temp directory by default and supports `BOOK_SKILL_WORKDIR` if an explicit work directory is needed.+Read `<tempdir>/book_skill_work/metadata.json` to inspect the results.---@@ -173,12 +162,13 @@ Read the `output_text` path in `<tempdir>/book_skill_work/metadata.json` to undeRead `<tempdir>/book_skill_work/metadata.json` and present the user with an estimate **before doing any generation**:```-📖 Source detected: <filename> (<format>)-📄 Pages/Spine items/Sections: ~<N> | Words: ~<N> | Source tokens: ~<N>K+📖 Sources detected: <total_sources> source(s)+<list each source filename and format from the sources metadata list>+📄 Combined Pages/Sections: ~<N> | Words: ~<N> | Total tokens: ~<N>K-💰 Estimated token cost (Full Conversion):- Input (book reading + prompts): ~<N>K tokens- Output (skill files generated): ~<N>K tokens+💰 Estimated token cost (Full Conversion / Update):+ Input (reading + prompts): ~<N>K tokens+ Output (skill files generated/updated): ~<N>K tokensTotal: ~<N>K tokensReference prices (as of 2025):@@ -187,10 +177,10 @@ Read `<tempdir>/book_skill_work/metadata.json` and present the user with an esti⏱ Estimated time: ~<N> minutes-📁 Files to be generated:- SKILL.md + <N> chapter files + glossary + patterns + cheatsheet+📁 Files to be generated/updated:+ SKILL.md + chapter files + glossary + patterns + cheatsheet-➡ Proceed with Full Conversion? (or type "analyze only" to preview first)+➡ Proceed with Full Conversion / Update? (or type "analyze only" to preview first)```**How to estimate:**@@ -295,8 +285,13 @@ Choose the destination skill root:- **Amp legacy**: `~/.config/amp/skills` if that is the user's existing global skill location- **Claude Code**: `~/.claude/skills` if the user explicitly asks for Claude Code output-Set `SKILLS_HOME` to the selected root and check that `$SKILLS_HOME/<skill_name>/` does NOT already exist.-If it does, append `-2` or ask the user before overwriting.+Set `SKILLS_HOME` to the selected root and check if `$SKILLS_HOME/<skill_name>/` already exists.+If it does, prompt the user to choose:+1. **Update / Fold-in** (Mode 4) — integrate new files/content into the existing skill components.+2. **Overwrite** — delete and regenerate the skill from scratch.+3. **Rename** — append `-2` or use a different custom slug.++If the user selects **Update / Fold-in**, proceed immediately to the **Update / Fold-in Workflow** section after Step 2.5 (skipping Steps 3, 4, 6, 7, 8, 9).---@@ -509,6 +504,55 @@ Usage:---+## Update / Fold-in Workflow++When performing an Update/Fold-in operation on an existing skill at `$SKILLS_HOME/<skill_name>/`:++### 1. Read Existing Skill Structure+Read and parse the existing skill's files:+- Read `$SKILLS_HOME/<skill_name>/SKILL.md` to parse the existing **Chapter Index**, **Topic Index**, metadata (author, total chapters), and **Core Frameworks**.+- List all files in `$SKILLS_HOME/<skill_name>/chapters/` to find the highest chapter number (e.g. `ch12`).+- Read `$SKILLS_HOME/<skill_name>/glossary.md`, `$SKILLS_HOME/<skill_name>/patterns.md`, and `$SKILLS_HOME/<skill_name>/cheatsheet.md` to see what terms and frameworks are already indexed.++### 2. Match Content & Identify Revisions vs. Additions+Analyze the new extracted text in `<tempdir>/book_skill_work/full_text.txt` to identify if the new content represents:+- **Updates/Revisions to existing chapters**: If a section of the new content directly updates or expands an existing chapter's topic, read the existing chapter file, merge the new details into it, and rewrite the file.+- **New additions**: If the content introduces new chapters, papers, or separate sections, create **new chapter summary files** under `chapters/`. Start numbering these files after the highest existing chapter number (e.g. if the existing chapters stop at `ch12`, create `ch13-*.md`, `ch14-*.md`, etc.).++### 3. Generate or Update Chapter Summary Files+For each new or revised chapter:+- Read the corresponding section of the extracted new text.+- Follow the formatting guidelines in **Step 7** to build the summary.+- Write/update the file in `$SKILLS_HOME/<skill_name>/chapters/`.++### 4. Merge Supporting Files+- **Merge glossary.md**:+ - Read the existing `$SKILLS_HOME/<skill_name>/glossary.md`.+ - Extract all new terms and definitions from the new content (Step 8 glossary guidelines).+ - Combine and alphabetize the list of existing and new terms.+ - If a term already exists, append the new chapter/source references to it (e.g. `**Term** — definition (Ch 4, Ch 13)`).+ - Rewrite `$SKILLS_HOME/<skill_name>/glossary.md` with the fully merged, alphabetized list.+- **Merge patterns.md**:+ - Read existing `$SKILLS_HOME/<skill_name>/patterns.md`.+ - Extract any new techniques, algorithms, or patterns from the new content.+ - Append the new patterns, ensuring consistent formatting, and keeping the total length concise (under 2,500 tokens).+- **Merge cheatsheet.md**:+ - Read existing `$SKILLS_HOME/<skill_name>/cheatsheet.md`.+ - Extract new comparison rules, decision tables, or parameter guides.+ - Integrate them cleanly into the cheatsheet structure.++### 5. Re-generate the Master SKILL.md+Update the master skill file `$SKILLS_HOME/<skill_name>/SKILL.md`:+- **Metadata**: Increment the chapter count, update the estimated page count, and add the new source names if appropriate. Update the `Generated` date to the current date.+- **Core Frameworks**: Fold in the most high-impact mental models or principles from the new content (ensuring the overall file remains under 4,000 tokens).+- **Chapter Index**: Append the new chapters to the index table, linking to the newly created files.+- **Topic Index**: Merge the new topics alphabetically. If an existing topic is also covered in the new chapters, append the new chapter links to its line (e.g. `- **Topic** → ch05, ch13`).++### 6. Cleanup and Proceed to Step 10+Once the files are successfully written and merged, skip to **Step 10** to perform cleanup and print a custom update report summarizing the newly added chapters, merged glossary terms, and updated indices.++---+## Quality Rules1. **Extract structure, not summaries** — capture named frameworks, exact formulations, anti-patterns; not chapter recapsdiff --git a/scripts/extract.py b/scripts/extract.pyindex da9b005..4f03851 100644--- a/scripts/extract.py+++ b/scripts/extract.py@@ -25,6 +25,7 @@ Outputs:Set BOOK_SKILL_WORKDIR to override the output directory."""+import globimport htmlimport html.parserimport importlib.util@@ -593,42 +594,98 @@ def extract_with_docling(pdf_path: str) -> str | None:return None-def main():- if len(sys.argv) < 2:- 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 flag+def parse_arguments(argv: list[str]) -> tuple[list[str], str, str]:+ """Parse argv into (input_paths, extraction_mode, install_mode)."""+ input_paths = []extraction_mode = "text"- if "--mode" in sys.argv:- idx = sys.argv.index("--mode")- if idx + 1 < len(sys.argv):- extraction_mode = sys.argv[idx + 1].lower()++ args = argv[1:]+ i = 0+ while i < len(args):+ arg = args[i]+ if arg == "--mode":+ if i + 1 < len(args):+ extraction_mode = args[i+1].lower()+ i += 2+ else:+ i += 1+ elif arg == "--install-missing":+ if i + 1 < len(args) and not args[i+1].startswith("--"):+ i += 2+ else:+ i += 1+ elif arg == "--no-install-missing":+ i += 1+ elif arg.startswith("-"):+ i += 1+ else:+ input_paths.append(arg)+ i += 1++ install_mode = normalize_install_mode(argv)if extraction_mode not in ("technical", "text"):extraction_mode = "text"-- if not os.path.exists(input_path):- print(f"ERROR: File not found: {input_path}", file=sys.stderr)++ return input_paths, extraction_mode, install_mode+++def resolve_input_files(paths: list[str]) -> list[Path]:+ """Resolve paths including files, directories, and glob patterns to Path objects."""+ resolved = []+ for path_str in paths:+ # Check if it has glob wildcards+ if any(char in path_str for char in ("*", "?", "[")):+ glob_matches = glob.glob(path_str, recursive=True)+ for match in glob_matches:+ p = Path(match)+ if p.is_file():+ resolved.append(p.resolve())+ else:+ p = Path(path_str)+ if p.is_dir():+ for root, _, files in os.walk(p):+ for file in files:+ file_path = Path(root) / file+ if file_path.suffix.lower() in SUPPORTED_EXTENSIONS:+ resolved.append(file_path.resolve())+ else:+ # Keep even if it doesn't exist so the error check can report it+ resolved.append(p.resolve())++ # Deduplicate while preserving order, then sort by file path for consistency+ seen = set()+ unique_paths = []+ for path in resolved:+ resolved_path = path.resolve() if path.exists() else path+ if resolved_path not in seen:+ seen.add(resolved_path)+ unique_paths.append(resolved_path)++ unique_paths.sort(key=lambda x: str(x).lower())+ return unique_paths+++def extract_single_file(input_path: Path, extraction_mode: str, install_mode: str) -> dict:+ """Extract text and metadata from a single file path."""+ input_str = str(input_path)++ if not input_path.exists():+ print(f"ERROR: File not found: {input_str}", file=sys.stderr)sys.exit(1)-- input_file = Path(input_path)- ext = input_file.suffix.lower()++ ext = input_path.suffix.lower()document_format = ext.lstrip(".")-- # Sniff magic bytes as a fallback for files without useful extensions.++ # Sniff magic bytes if suffix is not supportedif ext not in SUPPORTED_EXTENSIONS:- with open(input_path, "rb") as f:+ with open(input_str, "rb") as f:header = f.read(8)if header[:4] == b"%PDF":ext = ".pdf"document_format = "pdf"elif header[:2] == b"PK":try:- with zipfile.ZipFile(input_path) as zf:+ with zipfile.ZipFile(input_str) as zf:names = set(zf.namelist())if "mimetype" in names and zf.read("mimetype").startswith(b"application/epub"):ext = ".epub"@@ -638,13 +695,13 @@ def main():document_format = "docx"else:print(- f"ERROR: Unsupported ZIP-based format '{input_file.name}'. Supported: {supported_formats_message()}",+ f"ERROR: Unsupported ZIP-based format '{input_path.name}'. Supported: {supported_formats_message()}",file=sys.stderr,)sys.exit(1)except (zipfile.BadZipFile, KeyError, OSError):print(- f"ERROR: Unsupported ZIP-based format '{input_file.name}'. Supported: {supported_formats_message()}",+ f"ERROR: Unsupported ZIP-based format '{input_path.name}'. Supported: {supported_formats_message()}",file=sys.stderr,)sys.exit(1)@@ -654,10 +711,9 @@ def main():file=sys.stderr,)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. "@@ -665,43 +721,48 @@ def main():file=sys.stderr,)sys.exit(1)-++ text = ""+ method = ""+ pages = 0+ pages_label = "sections"+if ext == ".epub":- print(f"Extracting EPUB: {input_path}")- text, method = extract_epub(input_path)- pages = count_epub_chapters(input_path)+ print(f"Extracting EPUB: {input_str}")+ text, method = extract_epub(input_str)+ pages = count_epub_chapters(input_str)pages_label = "spine_items"elif ext == ".pdf":- print(f"Extracting PDF: {input_path}")+ print(f"Extracting PDF: {input_str}")if extraction_mode == "technical":print("Mode: technical — using Docling (layout-aware)...", end=" ", flush=True)- text = extract_with_docling(input_path)+ text = extract_with_docling(input_str)if text:method = "docling"print("OK")else:print("not available, falling back to pdftotext")extraction_mode = "text"-- if extraction_mode == "text":++ if extraction_mode == "text" or not text:print("Mode: text — using pdftotext...")print("Trying pdftotext...", end=" ", flush=True)- text = extract_with_pdftotext(input_path)-+ text = extract_with_pdftotext(input_str)+if text:method = "pdftotext"print("OK")else:print("not available")print("Trying PyPDF2...", end=" ", flush=True)- text = extract_with_pypdf2(input_path)+ text = extract_with_pypdf2(input_str)if text:method = "PyPDF2"print("OK")else:print("not available")print("Trying pdfminer.six...", end=" ", flush=True)- text = extract_with_pdfminer(input_path)+ text = extract_with_pdfminer(input_str)if text:method = "pdfminer"print("OK")@@ -716,12 +777,12 @@ def main():file=sys.stderr,)sys.exit(1)-- pages = count_pages(input_path)++ pages = count_pages(input_str)pages_label = "pages"elif ext in TEXT_EXTENSIONS:- print(f"Extracting text document: {input_path}")- text = read_text_file(input_path)+ print(f"Extracting text document: {input_str}")+ text = read_text_file(input_str)if text is None or not text.strip():print("ERROR: Could not read text document", file=sys.stderr)sys.exit(1)@@ -729,8 +790,8 @@ def main():pages = 0pages_label = "sections"elif ext in HTML_EXTENSIONS:- print(f"Extracting HTML: {input_path}")- text = extract_html_file(input_path)+ print(f"Extracting HTML: {input_str}")+ text = extract_html_file(input_str)if text is None or not text.strip():print("ERROR: Could not extract text from HTML", file=sys.stderr)sys.exit(1)@@ -738,18 +799,18 @@ def main():pages = 0pages_label = "sections"elif ext == ".docx":- print(f"Extracting DOCX: {input_path}")- text, method = extract_docx(input_path)+ print(f"Extracting DOCX: {input_str}")+ text, method = extract_docx(input_str)pages = 0pages_label = "sections"elif ext == ".rtf":- print(f"Extracting RTF: {input_path}")- text, method = extract_rtf(input_path)+ print(f"Extracting RTF: {input_str}")+ text, method = extract_rtf(input_str)pages = 0pages_label = "sections"elif ext in CALIBRE_EBOOK_EXTENSIONS:- print(f"Extracting ebook with Calibre: {input_path}")- text = extract_with_ebook_convert(input_path)+ print(f"Extracting ebook with Calibre: {input_str}")+ text = extract_with_ebook_convert(input_str)if text is None or not text.strip():print(f"ERROR: Could not extract text from {ext}. Install Calibre and ensure ebook-convert is on PATH.",@@ -759,53 +820,121 @@ def main():method = "ebook-convert"pages = 0pages_label = "sections"- else:- print(- f"ERROR: Unsupported format '{ext}'. Supported: {supported_formats_message()}",- file=sys.stderr,- )- sys.exit(1)-- # Write full text- OUTPUT_TEXT.write_text(text, encoding="utf-8")-+tokens = estimate_tokens(text)structure = detect_structure(text)- file_size_mb = os.path.getsize(input_path) / (1024 * 1024)-- metadata = {- "source_file": str(Path(input_path).resolve()),- "filename": Path(input_path).name,+ file_size_mb = os.path.getsize(input_str) / (1024 * 1024)++ return {+ "source_file": str(input_path.resolve()),+ "filename": input_path.name,"format": document_format,"extraction_method": method,- "extraction_mode": extraction_mode,"file_size_mb": round(file_size_mb, 2),pages_label: pages,+ "pages_label": pages_label,+ "pages": pages,"chars": len(text),"words": len(text.split()),"estimated_tokens": tokens,- "estimated_tokens_human": f"~{tokens // 1000}K",- "output_text": str(OUTPUT_TEXT),+ "text": text,**structure,}- OUTPUT_META.write_text(json.dumps(metadata, indent=2, ensure_ascii=False))- page_label = {- "spine_items": "Spine items",- "pages": "Pages",- "sections": "Sections",- }.get(pages_label, pages_label.replace("_", " ").title())- page_line = f" {page_label}: {pages}"+def main():+ if len(sys.argv) < 2:+ print("Usage: extract.py <path-to-document-folder-or-glob>... [--mode technical|text] [--install-missing ask|yes|no]", file=sys.stderr)+ print(f"Supported formats: {supported_formats_message()}", file=sys.stderr)+ sys.exit(1)++ raw_input_paths, extraction_mode, install_mode = parse_arguments(sys.argv)++ if not raw_input_paths:+ print("ERROR: No input document, folder, or glob pattern specified.", file=sys.stderr)+ sys.exit(1)++ input_files = resolve_input_files(raw_input_paths)++ if not input_files:+ print(f"ERROR: No supported files found matching: {', '.join(raw_input_paths)}", file=sys.stderr)+ sys.exit(1)++ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)++ extracted_sources = []+ combined_texts = []++ for file_path in input_files:+ res = extract_single_file(file_path, extraction_mode, install_mode)+ extracted_sources.append(res)++ # Format the text with a clear boundary+ separator = f"\n\n{'=' * 80}\nSOURCE: {res['filename']} (Path: {res['source_file']})\n{'=' * 80}\n\n"+ combined_texts.append(separator + res["text"])++ # Combine texts+ consolidated_text = "".join(combined_texts).strip()++ # Write combined text+ OUTPUT_TEXT.write_text(consolidated_text, encoding="utf-8")++ # Consolidate metadata+ total_file_size_mb = sum(src["file_size_mb"] for src in extracted_sources)+ total_pages = sum(src["pages"] for src in extracted_sources)+ total_chars = len(consolidated_text)+ total_words = len(consolidated_text.split())+ total_tokens = estimate_tokens(consolidated_text)++ # Detect structure on consolidated text+ consolidated_structure = detect_structure(consolidated_text)++ metadata = {+ "source_file": "Consolidated from multiple sources" if len(extracted_sources) > 1 else extracted_sources[0]["source_file"],+ "filename": "multi-source" if len(extracted_sources) > 1 else extracted_sources[0]["filename"],+ "format": "mixed" if len(extracted_sources) > 1 else extracted_sources[0]["format"],+ "extraction_method": "multi-method" if len(extracted_sources) > 1 else extracted_sources[0]["extraction_method"],+ "extraction_mode": extraction_mode,+ "file_size_mb": round(total_file_size_mb, 2),+ "pages": total_pages,+ "chars": total_chars,+ "words": total_words,+ "estimated_tokens": total_tokens,+ "estimated_tokens_human": f"~{total_tokens // 1000}K",+ "output_text": str(OUTPUT_TEXT),+ "total_sources": len(extracted_sources),+ "sources": [+ {+ "source_file": src["source_file"],+ "filename": src["filename"],+ "format": src["format"],+ "extraction_method": src["extraction_method"],+ "file_size_mb": src["file_size_mb"],+ "pages": src["pages"],+ "pages_label": src["pages_label"],+ "chars": src["chars"],+ "words": src["words"],+ "estimated_tokens": src["estimated_tokens"],+ "chapters_detected": src["chapters_detected"],+ "has_toc": src["has_toc"]+ }+ for src in extracted_sources+ ],+ **consolidated_structure,+ }++ OUTPUT_META.write_text(json.dumps(metadata, indent=2, ensure_ascii=False))++ page_line = f" Total Pages: {total_pages}"print("\nExtraction complete:")- print(f" Format : {document_format.upper()}")- print(f" Method : {method}")+ print(f" Sources : {len(extracted_sources)} processed")+ print(f" Size : {total_file_size_mb:.2f} MB")print(page_line)- 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'}")- if not structure["has_toc"]:+ print(f" Words : {total_words:,}")+ print(f" Tokens : ~{total_tokens // 1000}K")+ print(f" Chapters: {consolidated_structure['chapters_detected']} detected overall")+ print(f" ToC : {'yes' if consolidated_structure['has_toc'] else 'not detected'}")+ if not consolidated_structure["has_toc"]:print(" WARN : No table of contents detected — chapter mapping in Step 3 ""will rely on heading scan only, which may miss or duplicate sections."