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(pdf): report Docling fallback in technical mode (#255)
XuJian9822d8d7bf77
diff --git a/book_to_skill/parsers/pdf.py b/book_to_skill/parsers/pdf.pyindex 8708bc5..0bd22d6 100644--- a/book_to_skill/parsers/pdf.py+++ b/book_to_skill/parsers/pdf.py@@ -149,23 +149,20 @@ def extract_with_docling(pdf_path: str) -> str | None:from docling.datamodel.pipeline_options import PdfPipelineOptionsfrom docling.datamodel.base_models import InputFormatfrom docling.document_converter import PdfFormatOption-- pipeline_options = PdfPipelineOptions()- pipeline_options.do_ocr = False- pipeline_options.do_table_structure = True-- converter = DocumentConverter(- format_options={- InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)- }- )- result = converter.convert(pdf_path)- return result.document.export_to_markdown()except ImportError:return None- except Exception as e:- print(f" [warn] extract_with_docling failed: {type(e).__name__}: {e}", file=sys.stderr)- return None++ pipeline_options = PdfPipelineOptions()+ pipeline_options.do_ocr = False+ pipeline_options.do_table_structure = True++ converter = DocumentConverter(+ format_options={+ InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)+ }+ )+ result = converter.convert(pdf_path)+ return result.document.export_to_markdown()def count_pages(pdf_path: str) -> int:diff --git a/book_to_skill/utils.py b/book_to_skill/utils.pyindex 82cb43e..b35395e 100644--- a/book_to_skill/utils.py+++ b/book_to_skill/utils.py@@ -1154,6 +1154,7 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: sttext = ""method = ""+ fallback_reason = Nonepages = 0pages_label = "sections"images_dropped = None@@ -1196,13 +1197,32 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st" ocrmypdf input.pdf output.pdf")if extraction_mode == "technical":- print("Mode: technical — using Docling (layout-aware)...", end=" ", flush=True)- text = extract_with_docling(input_str)+ print("Mode: technical — using Docling (layout-aware)...")+ try:+ text = extract_with_docling(input_str)+ except Exception as exc:+ fallback_reason = "docling_failed"+ print(+ f"WARNING: Docling failed ({type(exc).__name__}: {exc}); "+ "using the PDF text fallback chain.",+ file=sys.stderr,+ )+ text = Noneif text and text.strip():method = "docling"print("OK")else:- print("not available, falling back to pdftotext")+ if fallback_reason is None:+ if text is None:+ fallback_reason = "docling_unavailable"+ detail = "Docling is unavailable"+ else:+ fallback_reason = "docling_empty"+ detail = "Docling produced no text"+ print(+ f"WARNING: {detail}; using the PDF text fallback chain.",+ file=sys.stderr,+ )extraction_mode = "text"if extraction_mode == "text" or not text:@@ -1308,6 +1328,7 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st"filename": input_path.name,"format": document_format,"extraction_method": method,+ "fallback_reason": fallback_reason,"file_size_mb": round(file_size_mb, 2),"sha256": file_sha256,pages_label: pages,@@ -1505,6 +1526,7 @@ def main():"filename": src["filename"],"format": src["format"],"extraction_method": src["extraction_method"],+ "fallback_reason": src["fallback_reason"],"file_size_mb": src["file_size_mb"],"sha256": src["sha256"],"pages": src["pages"],diff --git a/tests/test_docling_fallback.py b/tests/test_docling_fallback.pynew file mode 100644index 0000000..9d30844--- /dev/null+++ b/tests/test_docling_fallback.py@@ -0,0 +1,108 @@+import json+import sys+from types import ModuleType, SimpleNamespace++import pytest++from book_to_skill import utils+from book_to_skill.parsers.pdf import extract_with_docling+++def test_docling_runtime_error_reaches_the_fallback(monkeypatch):+ class FailingConverter:+ def __init__(self, **_kwargs):+ pass++ def convert(self, _path):+ raise OSError("model cache unavailable")++ modules = {+ "docling": ModuleType("docling"),+ "docling.datamodel": ModuleType("docling.datamodel"),+ "docling.document_converter": ModuleType("docling.document_converter"),+ "docling.datamodel.pipeline_options": ModuleType(+ "docling.datamodel.pipeline_options"+ ),+ "docling.datamodel.base_models": ModuleType("docling.datamodel.base_models"),+ }+ modules["docling.document_converter"].DocumentConverter = FailingConverter+ modules["docling.document_converter"].PdfFormatOption = lambda **_kwargs: None+ modules["docling.datamodel.pipeline_options"].PdfPipelineOptions = SimpleNamespace+ modules["docling.datamodel.base_models"].InputFormat = SimpleNamespace(PDF="pdf")+ for name, module in modules.items():+ monkeypatch.setitem(sys.modules, name, module)++ with pytest.raises(OSError, match="model cache unavailable"):+ extract_with_docling("book.pdf")+++ ("docling_result", "expected_reason"),+ [(None, "docling_unavailable"), ("", "docling_empty")],+)+def test_technical_pdf_records_fallback_reason(+ tmp_path, monkeypatch, docling_result, expected_reason+):+ pdf = tmp_path / "book.pdf"+ pdf.write_bytes(b"%PDF-1.4\nfixture")+ monkeypatch.setattr(utils, "prepare_dependencies", lambda *_: None)+ monkeypatch.setattr(utils, "looks_image_only", lambda *_: False)+ monkeypatch.setattr(utils, "extract_with_docling", lambda *_: docling_result)+ monkeypatch.setattr(+ utils, "extract_with_pdftotext", lambda *_: "# Technical book\n\nText only."+ )+ monkeypatch.setattr(utils, "count_pages", lambda *_: 1)++ result = utils.extract_single_file(pdf, "technical", "no")++ assert result["extraction_method"] == "pdftotext"+ assert result["fallback_reason"] == expected_reason+++def test_docling_runtime_failure_is_recorded_in_metadata(tmp_path, monkeypatch, capsys):+ pdf = tmp_path / "book.pdf"+ pdf.write_bytes(b"%PDF-1.4\nfixture")+ output_dir = tmp_path / "output"+ monkeypatch.setattr(utils, "OUTPUT_DIR", output_dir)+ monkeypatch.setattr(utils, "OUTPUT_TEXT", output_dir / "full_text.txt")+ monkeypatch.setattr(utils, "OUTPUT_META", output_dir / "metadata.json")+ monkeypatch.setattr(+ sys,+ "argv",+ ["extract.py", str(pdf), "--mode", "technical", "--no-install-missing"],+ )+ monkeypatch.setattr(utils, "prepare_dependencies", lambda *_: None)+ monkeypatch.setattr(utils, "looks_image_only", lambda *_: False)+ monkeypatch.setattr(utils, "count_pages", lambda *_: 1)+ monkeypatch.setattr(+ utils, "extract_with_pdftotext", lambda *_: "# Technical book\n\nText only."+ )++ def fail_docling(_path):+ raise OSError("model cache unavailable")++ monkeypatch.setattr(utils, "extract_with_docling", fail_docling)++ utils.main()++ metadata = json.loads((output_dir / "metadata.json").read_text(encoding="utf-8"))+ assert metadata["extraction_mode"] == "technical"+ assert metadata["extraction_method"] == "pdftotext"+ assert metadata["sources"][0]["fallback_reason"] == "docling_failed"+ assert "Docling failed" in capsys.readouterr().err+++def test_successful_docling_has_no_fallback_reason(tmp_path, monkeypatch):+ pdf = tmp_path / "book.pdf"+ pdf.write_bytes(b"%PDF-1.4\nfixture")+ monkeypatch.setattr(utils, "prepare_dependencies", lambda *_: None)+ monkeypatch.setattr(utils, "looks_image_only", lambda *_: False)+ monkeypatch.setattr(+ utils, "extract_with_docling", lambda *_: "# Technical book\n\n| A | B |"+ )+ monkeypatch.setattr(utils, "count_pages", lambda *_: 1)++ result = utils.extract_single_file(pdf, "technical", "no")++ assert result["extraction_method"] == "docling"+ assert result["fallback_reason"] is None