Skip to content

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

fix(epub): report unextracted source images (#134)

Nathan728212835abe
diff --git a/SKILL.md b/SKILL.md
index 908dea3..bb860ba 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -165,7 +165,7 @@ Before extraction, the script checks optional Python packages needed for the det
This creates:
- `<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`.
+- `<tempdir>/book_skill_work/metadata.json` — overall combined size, words, pages, token counts, dropped EPUB image counts, and a detailed list of individual processed `sources`.
Read `<tempdir>/book_skill_work/metadata.json` to inspect the results.
@@ -178,6 +178,7 @@ Read `<tempdir>/book_skill_work/metadata.json` and present the user with an esti
```
📖 Sources detected: <total_sources> source(s)
<list each source filename and format from the sources metadata list>
+<if images_dropped > 5: warn that N source images were not read>
📄 Combined Pages/Sections: ~<N> | Words: ~<N> | Total tokens: ~<N>K
💰 Estimated token cost (Full Conversion / Update):
@@ -515,6 +516,7 @@ the relevant chapter file before answering.
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 the agent directly.
+<if images_dropped > 5: state that N source images were not read>
```
---
diff --git a/book_to_skill/parsers/epub.py b/book_to_skill/parsers/epub.py
index eedfd8a..9031094 100644
--- a/book_to_skill/parsers/epub.py
+++ b/book_to_skill/parsers/epub.py
@@ -7,6 +7,20 @@ import sys
from book_to_skill.parsers.html import _HTMLTextExtractor
+_IMAGE_EXTENSIONS = (
+ ".avif",
+ ".bmp",
+ ".gif",
+ ".jpeg",
+ ".jpg",
+ ".png",
+ ".svg",
+ ".tif",
+ ".tiff",
+ ".webp",
+)
+
+
def extract_with_ebooklib(epub_path: str) -> str | None:
try:
import ebooklib
@@ -123,3 +137,15 @@ def count_epub_chapters(epub_path: str) -> int:
except Exception:
return 0
+
+def count_epub_images(epub_path: str) -> int:
+ """Count image members whose content the text-only EPUB parsers omit."""
+ try:
+ with zipfile.ZipFile(epub_path) as zf:
+ return sum(
+ not info.is_dir() and info.filename.lower().endswith(_IMAGE_EXTENSIONS)
+ for info in zf.infolist()
+ )
+ except (OSError, zipfile.BadZipFile):
+ return 0
+
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index e750e64..efeca4f 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -46,10 +46,16 @@ from book_to_skill.parsers.epub import (
extract_with_ebooklib,
extract_with_zipfile,
count_epub_chapters,
+ count_epub_images,
)
from book_to_skill.sanitize import sanitize_extracted_text
+# Covers and decorative assets are common in prose EPUBs, so only surface the
+# omission when the archive contains more than five images.
+_EPUB_IMAGE_NOTICE_THRESHOLD = 5
+
+
# CJK codepoints: ideographs + extensions, kana, hangul, CJK punctuation, and
# fullwidth forms. These are not whitespace-delimited, so counting "words" on a
# Chinese/Japanese book collapses it to a handful of tokens; count them directly.
@@ -637,6 +643,7 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st
method = ""
pages = 0
pages_label = "sections"
+ images_dropped = None
if ext == ".epub":
print(f"Extracting EPUB: {input_str}")
@@ -659,6 +666,13 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st
)
pages = count_epub_chapters(input_str)
pages_label = "spine_items"
+ images_dropped = count_epub_images(input_str)
+ if images_dropped > _EPUB_IMAGE_NOTICE_THRESHOLD:
+ print(
+ f" [warn] {input_path.name} contains {images_dropped} image(s); "
+ "their content is not extracted",
+ file=sys.stderr,
+ )
elif ext == ".pdf":
print(f"Extracting PDF: {input_str}")
if looks_image_only(input_str):
@@ -783,6 +797,7 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st
"chars": len(text),
"words": len(text.split()),
"estimated_tokens": tokens,
+ "images_dropped": images_dropped,
"text": text,
**structure,
}
@@ -924,6 +939,9 @@ def main():
total_chars = len(consolidated_text)
total_words = len(consolidated_text.split())
total_tokens = estimate_tokens(consolidated_text)
+ total_images_dropped = sum(
+ src["images_dropped"] or 0 for src in extracted_sources
+ )
# Detect structure from source content only. The generated SOURCE banners in
# full_text.txt use rows of "=", which can otherwise become phantom setext
@@ -953,6 +971,7 @@ def main():
"words": total_words,
"estimated_tokens": total_tokens,
"estimated_tokens_human": f"~{total_tokens // 1000}K",
+ "images_dropped": total_images_dropped,
"output_text": str(OUTPUT_TEXT),
"total_sources": len(extracted_sources),
"sources": [
@@ -967,6 +986,7 @@ def main():
"chars": src["chars"],
"words": src["words"],
"estimated_tokens": src["estimated_tokens"],
+ "images_dropped": src["images_dropped"],
"chapters_detected": src["chapters_detected"],
"chapters_method": src["chapters_method"],
"has_toc": src["has_toc"]
diff --git a/tests/test_epub_image_reporting.py b/tests/test_epub_image_reporting.py
new file mode 100644
index 0000000..89d8dec
--- /dev/null
+++ b/tests/test_epub_image_reporting.py
@@ -0,0 +1,77 @@
+import json
+import sys
+import zipfile
+from unittest import mock
+
+from book_to_skill.utils import extract_single_file, main
+
+
+def _make_epub_with_images(path, image_count=2):
+ manifest_images = "\n".join(
+ f'<item id="image-{index}" href="images/image-{index}.png" media-type="image/png"/>'
+ for index in range(image_count)
+ )
+ with zipfile.ZipFile(path, "w") as archive:
+ archive.writestr("mimetype", "application/epub+zip")
+ archive.writestr(
+ "META-INF/container.xml",
+ '<?xml version="1.0"?>'
+ '<container><rootfiles><rootfile full-path="OEBPS/content.opf"/>'
+ "</rootfiles></container>",
+ )
+ archive.writestr(
+ "OEBPS/content.opf",
+ '<package><manifest><item id="chapter" href="chapter.xhtml" '
+ 'media-type="application/xhtml+xml"/>'
+ f"{manifest_images}</manifest>"
+ '<spine><itemref idref="chapter"/></spine></package>',
+ )
+ archive.writestr(
+ "OEBPS/chapter.xhtml",
+ "<html><body><h1>Chapter 1</h1><p>Extracted prose.</p></body></html>",
+ )
+ for index in range(image_count):
+ archive.writestr(f"OEBPS/images/image-{index}.png", b"not-a-real-png")
+ return path
+
+
+def test_epub_extraction_reports_material_dropped_images(tmp_path, capsys):
+ source = _make_epub_with_images(tmp_path / "figures.epub", image_count=6)
+
+ with mock.patch("book_to_skill.utils.prepare_dependencies"):
+ result = extract_single_file(source, "text", "no")
+
+ assert result["images_dropped"] == 6
+ stderr = capsys.readouterr().err
+ assert "6 image(s)" in stderr
+ assert "content is not extracted" in stderr
+
+
+def test_epub_extraction_keeps_cover_only_book_quiet(tmp_path, capsys):
+ source = _make_epub_with_images(tmp_path / "novel.epub", image_count=1)
+
+ with mock.patch("book_to_skill.utils.prepare_dependencies"):
+ result = extract_single_file(source, "text", "no")
+
+ assert result["images_dropped"] == 1
+ assert "content is not extracted" not in capsys.readouterr().err
+
+
+def test_main_persists_epub_image_loss_in_source_and_total_metadata(
+ tmp_path, monkeypatch
+):
+ source = _make_epub_with_images(tmp_path / "figures.epub", image_count=3)
+ output_dir = tmp_path / "output"
+ output_meta = output_dir / "metadata.json"
+
+ monkeypatch.setattr(sys, "argv", ["extract.py", str(source), "--install-missing", "no"])
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_DIR", output_dir)
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_TEXT", output_dir / "full_text.txt")
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_META", output_meta)
+ monkeypatch.setattr("book_to_skill.utils.prepare_dependencies", lambda *args: None)
+
+ main()
+
+ metadata = json.loads(output_meta.read_text(encoding="utf-8"))
+ assert metadata["images_dropped"] == 3
+ assert metadata["sources"][0]["images_dropped"] == 3