Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix(extractor): translate post-extraction stat errors (#228)

Stamina9f08d343d694f
diff --git a/book_to_skill/pdf_inspector_integration.py b/book_to_skill/pdf_inspector_integration.py
index f1e4616..2d0d817 100644
--- a/book_to_skill/pdf_inspector_integration.py
+++ b/book_to_skill/pdf_inspector_integration.py
@@ -7,6 +7,8 @@ import sys
from pathlib import Path
from typing import Any
+from book_to_skill.exceptions import ExtractionError
+
_MIN_NATIVE_CONFIDENCE = 0.90
_INSPECTIONS: dict[str, dict[str, Any]] = {}
@@ -143,7 +145,12 @@ def _result_from_inspector(
pages = inspection.get("page_count") or utils_module.count_pages(str(input_path))
tokens = utils_module.estimate_tokens(text)
- file_size_mb = os.path.getsize(input_path) / (1024 * 1024)
+ try:
+ file_size_mb = os.path.getsize(input_path) / (1024 * 1024)
+ except OSError as exc:
+ raise ExtractionError(
+ f"Could not read file size for {input_path.name}: {exc}"
+ ) from exc
return {
"source_file": str(input_path.resolve()),
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index 5d40424..441934e 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -1015,7 +1015,12 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st
f" chapters: {structure['chapters_detected']} "
f"({structure['chapters_method']})"
)
- file_size_mb = os.path.getsize(input_str) / (1024 * 1024)
+ try:
+ file_size_mb = os.path.getsize(input_str) / (1024 * 1024)
+ except OSError as exc:
+ raise ExtractionError(
+ f"Could not read file size for {input_path.name}: {exc}"
+ ) from exc
return {
"source_file": str(input_path.resolve()),
diff --git a/tests/test_batch_resilience_unreadable.py b/tests/test_batch_resilience_unreadable.py
index dbe21d4..43d13f5 100644
--- a/tests/test_batch_resilience_unreadable.py
+++ b/tests/test_batch_resilience_unreadable.py
@@ -20,8 +20,8 @@ import pytest
ROOT_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT_DIR))
+import book_to_skill.utils as utils # noqa: E402
from book_to_skill.exceptions import ExtractionError # noqa: E402
-from book_to_skill.utils import extract_single_file, main # noqa: E402
def _make_unreadable(path: Path) -> Path:
@@ -43,7 +43,7 @@ def test_unreadable_unknown_suffix_raises_extraction_error(tmp_path):
bad = _make_unreadable(tmp_path / "mystery.dat")
try:
with pytest.raises(ExtractionError) as excinfo:
- extract_single_file(bad, "text", "no")
+ utils.extract_single_file(bad, "text", "no")
assert "mystery.dat" in str(excinfo.value)
finally:
bad.chmod(stat.S_IRUSR | stat.S_IWUSR)
@@ -61,8 +61,6 @@ def test_batch_survives_unreadable_source(tmp_path, monkeypatch, capsys):
# config caches OUTPUT_* at import time; point the module constants at the
# temp workdir so the run does not touch the shared default.
import book_to_skill.config as config
- import book_to_skill.utils as utils
-
for module in (config, utils):
monkeypatch.setattr(module, "OUTPUT_DIR", workdir, raising=False)
monkeypatch.setattr(module, "OUTPUT_TEXT", workdir / "full_text.txt", raising=False)
@@ -73,7 +71,7 @@ def test_batch_survives_unreadable_source(tmp_path, monkeypatch, capsys):
)
try:
- main()
+ utils.main()
finally:
bad.chmod(stat.S_IRUSR | stat.S_IWUSR)
@@ -89,7 +87,7 @@ def test_batch_survives_unreadable_source(tmp_path, monkeypatch, capsys):
def test_missing_file_still_reports_not_found(tmp_path):
"""The pre-existing not-found path is unchanged."""
with pytest.raises(ExtractionError) as excinfo:
- extract_single_file(tmp_path / "nope.dat", "text", "no")
+ utils.extract_single_file(tmp_path / "nope.dat", "text", "no")
assert "File not found" in str(excinfo.value)
@@ -99,5 +97,52 @@ def test_readable_unknown_suffix_still_rejected_by_format(tmp_path):
odd.write_bytes(b"not a pdf or a zip")
with pytest.raises(ExtractionError) as excinfo:
- extract_single_file(odd, "text", "no")
+ utils.extract_single_file(odd, "text", "no")
assert "Unsupported format" in str(excinfo.value)
+
+
+def test_post_extraction_stat_failure_raises_extraction_error(tmp_path, monkeypatch):
+ source = tmp_path / "book.md"
+ source.write_text("Chapter 1\nContent", encoding="utf-8")
+
+ def fail_getsize(_path):
+ raise PermissionError("file became unavailable")
+
+ monkeypatch.setattr(os.path, "getsize", fail_getsize)
+
+ with pytest.raises(ExtractionError, match="Could not read file size"):
+ utils.extract_single_file(source, "text", "no")
+
+
+def test_batch_survives_post_extraction_stat_failure(tmp_path, monkeypatch):
+ bad = tmp_path / "a.md"
+ good = tmp_path / "b.md"
+ bad.write_text("Chapter 1\nFirst source", encoding="utf-8")
+ good.write_text("Chapter 2\nSecond source", encoding="utf-8")
+
+ real_getsize = os.path.getsize
+
+ def flaky_getsize(path):
+ if Path(path) == bad:
+ raise PermissionError("file became unavailable")
+ return real_getsize(path)
+
+ monkeypatch.setattr(os.path, "getsize", flaky_getsize)
+
+ workdir = tmp_path / "work"
+ import book_to_skill.config as config
+ for module in (config, utils):
+ monkeypatch.setattr(module, "OUTPUT_DIR", workdir, raising=False)
+ monkeypatch.setattr(module, "OUTPUT_TEXT", workdir / "full_text.txt", raising=False)
+ monkeypatch.setattr(module, "OUTPUT_META", workdir / "metadata.json", raising=False)
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["extract.py", str(bad), str(good), "--install-missing", "no"],
+ )
+
+ utils.main()
+
+ text = (workdir / "full_text.txt").read_text(encoding="utf-8")
+ assert "Second source" in text
+ assert "First source" not in text
diff --git a/tests/test_pdf_inspector_integration.py b/tests/test_pdf_inspector_integration.py
index e8cce59..caf18d9 100644
--- a/tests/test_pdf_inspector_integration.py
+++ b/tests/test_pdf_inspector_integration.py
@@ -5,6 +5,7 @@ from types import SimpleNamespace
import pytest
import book_to_skill.pdf_inspector_integration as integration
+from book_to_skill.exceptions import ExtractionError
def _fake_result(**overrides):
@@ -185,6 +186,48 @@ def test_hook_uses_inspector_for_clean_text_pdf(tmp_path, monkeypatch):
assert integration._INSPECTIONS[str(pdf.resolve())] == inspection
+def test_hook_translates_post_extraction_stat_failure(tmp_path, monkeypatch):
+ integration._reset_state_for_tests()
+ pdf = tmp_path / "book.pdf"
+ pdf.write_bytes(b"%PDF-1.7\nfixture")
+
+ fake_utils = SimpleNamespace(
+ extract_single_file=lambda *_args: {"extraction_method": "legacy"},
+ sanitize_extracted_text=lambda text: (text, 0),
+ detect_structure=lambda _text: {
+ "chapters_detected": 1,
+ "chapters_method": "numeric",
+ "chapter_headings_sample": ["Chapter 1"],
+ "has_toc": False,
+ },
+ count_pages=lambda _path: 12,
+ estimate_tokens=lambda _text: 42,
+ )
+ inspection = {
+ "confidence": 0.99,
+ "page_count": 12,
+ "pdf_type": "text_based",
+ "native_markdown_trusted": True,
+ "pages_needing_ocr": [],
+ "has_encoding_issues": False,
+ }
+ monkeypatch.setattr(
+ integration,
+ "inspect_pdf",
+ lambda _path: ("Chapter 1\nBody", inspection),
+ )
+
+ def fail_getsize(_path):
+ raise PermissionError("unavailable")
+
+ monkeypatch.setattr(integration.os.path, "getsize", fail_getsize)
+
+ integration.install_pdf_inspector_hook(fake_utils)
+
+ with pytest.raises(ExtractionError, match="Could not read file size"):
+ fake_utils.extract_single_file(pdf, "text", "no")
+
+
def test_hook_keeps_technical_mode_on_existing_pipeline(tmp_path, monkeypatch):
integration._reset_state_for_tests()
pdf = tmp_path / "book.pdf"