Skip to content

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

feat(pdf): clean pdftotext output (dehyphenate + strip repeated headers/footers) (#77)

Shubham Srivastava8989da98caba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38fe77b..f3c20a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **The `pdf` extra now installs `pypdf` instead of the deprecated `PyPDF2`**
(`pip install book-to-skill[pdf]`). `pypdf` is the maintained successor;
`PyPDF2` is end-of-life and no longer receives security fixes (#54).
+- PDF text from `pdftotext` is now cleaned before use: hyphenated line-wraps are
+ rejoined (`informa-\ntion` → `information`) and repeated running
+ headers/footers and per-page page numbers are stripped. Fewer tokens and
+ cleaner input for chapter detection; conservative (edges only, ≥3 pages, so
+ mid-page content is never removed).
### Fixed
- Consolidated chapter detection now analyzes extracted source text without the generated
diff --git a/book_to_skill/parsers/pdf.py b/book_to_skill/parsers/pdf.py
index 8b9d3c1..37bfd35 100644
--- a/book_to_skill/parsers/pdf.py
+++ b/book_to_skill/parsers/pdf.py
@@ -1,9 +1,50 @@
from __future__ import annotations
import os
+import re
import shutil
import subprocess
import sys
+from collections import Counter
+
+_PDF_PAGE_NUM = re.compile(r"^\s*(\d{1,4}|[ivxlcdm]{1,7})\s*$", re.IGNORECASE)
+_PDF_HYPHEN_WRAP = re.compile(r"(\w)-\n(\w)")
+
+
+def clean_pdftotext(text: str) -> str:
+ """Clean pdftotext '-layout' output (pages are form-feed delimited): drop
+ repeated running headers/footers and edge page numbers, and join words split
+ across a line by a hyphen."""
+ pages = text.split("\f")
+ if len(pages) >= 3:
+ # A top/bottom line repeated on > half the pages is boilerplate.
+ edge = Counter()
+ for p in pages:
+ nb = [ln.strip() for ln in p.splitlines() if ln.strip()]
+ if nb:
+ edge[nb[0]] += 1
+ edge[nb[-1]] += 1
+ boiler = {ln for ln, c in edge.items() if c > len(pages) / 2}
+ kept = []
+ for p in pages:
+ lines = p.splitlines()
+ nb_idx = [i for i, ln in enumerate(lines) if ln.strip()]
+ first = nb_idx[0] if nb_idx else None
+ last = nb_idx[-1] if nb_idx else None
+ for i, ln in enumerate(lines):
+ s = ln.strip()
+ if s in boiler:
+ continue
+ # Drop a bare page number only at a page edge (varies per page).
+ if i in (first, last) and _PDF_PAGE_NUM.match(s):
+ continue
+ kept.append(ln)
+ text = "\n".join(kept)
+ else:
+ text = text.replace("\f", "\n")
+ # ponytail: naive dehyphenation; may join a genuinely-hyphenated wrapped
+ # compound ("well-\nknown" -> "wellknown"). Dictionary-aware split if it bites.
+ return _PDF_HYPHEN_WRAP.sub(r"\1\2", text)
def extract_with_pdftotext(pdf_path: str) -> str | None:
@@ -17,7 +58,7 @@ def extract_with_pdftotext(pdf_path: str) -> str | None:
encoding="utf-8", errors="replace",
)
if result.returncode == 0 and result.stdout.strip():
- return result.stdout
+ return clean_pdftotext(result.stdout)
except Exception as e:
print(f" [warn] extract_with_pdftotext failed: {type(e).__name__}: {e}", file=sys.stderr)
return None
diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.py
index 046ee3a..0e158e7 100644
--- a/tests/test_book_to_skill.py
+++ b/tests/test_book_to_skill.py
@@ -1395,3 +1395,44 @@ class TestPdftotextEncoding:
assert pdf_parser.extract_with_pdftotext("x.pdf") == "Café — naïve"
assert captured.get("encoding") == "utf-8"
assert captured.get("errors") == "replace"
+
+
+class TestPdftotextCleanup:
+ """clean_pdftotext strips repeated headers/footers/page numbers and dehyphenates."""
+
+ def _pages(self, *pages):
+ return "\f".join(pages)
+
+ def test_repeated_header_and_edge_page_numbers_removed(self):
+ raw = self._pages(
+ *(f"BOOK TITLE\nReal content on page {n}.\n{n}" for n in (1, 2, 3))
+ )
+ out = pdf_parser.clean_pdftotext(raw)
+ assert "BOOK TITLE" not in out
+ assert not any(ln.strip() in {"1", "2", "3"} for ln in out.splitlines())
+ assert "Real content on page 1." in out
+
+ def test_hyphenated_wrap_is_rejoined(self):
+ raw = self._pages(*(f"H\nabout informa-\ntion here\n{n}" for n in (1, 2, 3)))
+ out = pdf_parser.clean_pdftotext(raw)
+ assert "information" in out
+ assert "informa-" not in out
+
+ def test_token_count_drops(self):
+ raw = self._pages(*(f"RUNNING HEAD\nbody text page {n}\n{n}" for n in (1, 2, 3)))
+ out = pdf_parser.clean_pdftotext(raw)
+ assert len(out.split()) < len(raw.split())
+
+ def test_mid_page_bare_number_is_kept(self):
+ # A bare number that is NOT at a page edge must survive.
+ raw = self._pages(*(f"HDR\nthe answer is 42\ntrailing\n{n}" for n in (1, 2, 3)))
+ out = pdf_parser.clean_pdftotext(raw)
+ assert "42" in out
+ assert "HDR" not in out
+
+ def test_single_page_keeps_content(self):
+ # < 3 pages: no header/footer removal, only dehyphenation.
+ out = pdf_parser.clean_pdftotext("Title\nword-\nwrap\n1")
+ assert "wordwrap" in out
+ assert "Title" in out
+ assert "1" in out