Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
.DS_Store
__pycache__/

.google-books-browser/
.internet-archive-browser/
*-pages/

# Python virtual environments
__pycache__/
.venv/
venv/
env/
37 changes: 35 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ structured derivatives of scanned PDFs.

## Web toolbench

The dependency-free [web interface](web/index.html) keeps Google Books export,
The dependency-free [web interface](web/index.html) keeps Google Books and Internet Archive export,
OCR, local AI review, and compression in separate reusable modules. Each panel
validates its own inputs and builds the corresponding local CLI command.

Expand All @@ -24,7 +24,7 @@ leave its Terminal window open to keep the server running.
The interface follows the system appearance by default. Use the **Dark mode /
Light mode** button in the top-right corner to override it; the preference is
saved in your browser. The interface still only **builds commands**. It does not
run Google Books exports or PDF enhancement jobs itself.
run book exports or PDF enhancement jobs itself.

Run the frontend tests with `npm test`.

Expand Down Expand Up @@ -52,6 +52,39 @@ to `BOOK_ID.pdf`. The exporter resumes from existing captures, advances until
the reader stops, and removes the final reader-completion capture before PDF
assembly.

## Internet Archive export

`export-archive-book.py` captures individual scans from Internet Archive's
BookReader, including books opened in two-page mode. It accepts an item ID or
the full details URL and uses the same `img2pdf` and Playwright dependencies
listed above.

```sh
python3 export-archive-book.py https://archive.org/details/transformationof00seli/mode/2up
```

Playwright opens a visible Chromium browser window. The exporter pauses and
waits for you before capturing anything:

1. In that browser window, sign in and borrow the book if required.
2. Open the reader and wait until the book's pages are visible.
3. Return to the Terminal window where you ran the command and press **Enter**
to start exporting. Keep the browser open while the export runs.

Your login is saved for future runs. Only pages available to that reader
session can be captured. The linked book has a restricted PDF download;
this tool captures the reader rather than downloading that private file.
Full-book export requires reader access to all scans.

Captures default to `transformationof00seli-archive-pages/` and the PDF to
`transformationof00seli.pdf`. Use `--output-dir` and `--output-pdf` to change
these. `--start 1 --end 10` exports an inclusive range of scan positions
(including covers and front matter, rather than printed page numbers).
Existing captures at those positions are reused on rerun. Keep each capture
directory dedicated to one book. All requested scans must succeed before the
PDF is assembled; if access or loading fails, captures remain for resuming.
Sign-in state is retained in the local `.internet-archive-browser` profile.

## OCR, compression, and structure tagging

The lossless PDF workflow can create searchable OCR, identify heading levels,
Expand Down
155 changes: 155 additions & 0 deletions export-archive-book.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Capture pages rendered by Internet Archive's BookReader into a PDF."""

import argparse
from pathlib import Path
import re
import time
from urllib.parse import urlsplit

import img2pdf
from playwright.sync_api import sync_playwright


PROFILE = Path(".internet-archive-browser")


def book_id(value):
value = value.strip()
if "://" in value:
url = urlsplit(value)
parts = url.path.split("/")
if (url.scheme not in ("http", "https")
or url.netloc.lower() not in ("archive.org", "www.archive.org")
or len(parts) < 3 or parts[1] != "details"):
raise argparse.ArgumentTypeError("Use an archive.org/details book URL.")
value = parts[2]
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", value):
raise argparse.ArgumentTypeError("Use an Internet Archive item ID or details URL.")
return value


def positive_integer(value):
try:
number = int(value)
except ValueError:
raise argparse.ArgumentTypeError("Expected a positive whole number.") from None
if number < 1:
raise argparse.ArgumentTypeError("Expected a positive whole number.")
return number


def parse_args(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("book", type=book_id, help="Item ID or archive.org/details URL.")
parser.add_argument("--output-dir", type=Path, help="Default: <item-id>-archive-pages.")
parser.add_argument("--output-pdf", type=Path, help="Default: <item-id>.pdf.")
parser.add_argument("--start", type=positive_integer, default=1,
help="First scan position, including front matter (one-based).")
parser.add_argument("--end", type=positive_integer,
help="Last scan position, inclusive (default: end of book).")
args = parser.parse_args(argv)
if args.end is not None and args.end < args.start:
parser.error("--end must be at least --start")
return args


def wait_until(page, predicate, timeout=30):
# Poll from Python: BookReader's CSP can block wait_for_function's eval.
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return
page.wait_for_timeout(200)
raise RuntimeError("Reader page unavailable or not fully loaded. Check reader access and retry.")


def reader_count(page):
wait_until(page, lambda: page.evaluate(
"""() => Boolean(window.br?.book?.getNumLeafs()
&& [1, 2, 3].includes(window.br.mode)
&& document.querySelector('.BRpageimage'))"""))
return page.evaluate("() => window.br.book.getNumLeafs()")


def capture_scan(page, index):
"""Capture only the requested scan, never a neighboring or loading page."""
page.evaluate("() => { if (window.br.mode !== 1) window.br.switchMode(1); }")
page.evaluate("index => window.br.jumpToIndex(index)", index)
image = page.locator(f'.BRpagecontainer[data-index="{index}"] .BRpageimage')

def ready():
# currentIndex() tracks the top of the scroll viewport. At the end of
# the book it can remain on an earlier scan even with this image loaded.
# The container's data-index identifies the requested scan directly.
return (image.count() == 1
and image.evaluate("img => img.complete && img.naturalWidth > 200 && img.naturalHeight > 200"))

wait_until(page, ready)
# Capture the rendered image element, without reader chrome or OCR overlays.
return image.screenshot(type="png", timeout=30000)


def assemble_pdf(paths, destination):
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_suffix(destination.suffix + ".tmp")
try:
with temporary.open("wb") as stream:
img2pdf.convert([str(path) for path in paths], outputstream=stream)
temporary.replace(destination)
finally:
temporary.unlink(missing_ok=True)


def export_pages(page, output_dir, output_pdf, start=1, end=None):
total = reader_count(page)
end = total if end is None else end
if start > total or end > total:
raise ValueError(f"Scan range exceeds the reader's {total} scans.")
output_dir.mkdir(parents=True, exist_ok=True)
paths = []
for number in range(start, end + 1):
path = output_dir / f"{number:04d}.png"
# Keep scan numbering stable on resume, including identical blank pages.
if not path.exists():
png = capture_scan(page, number - 1)
temporary = path.with_suffix(".png.tmp")
temporary.write_bytes(png)
temporary.replace(path)
print(f"Captured scan {number}/{total}: {path}", flush=True)
else:
print(f"Using existing scan {number}: {path}", flush=True)
paths.append(path)
assemble_pdf(paths, output_pdf)
print(f"Created: {output_pdf} ({len(paths)} pages, scans {start}–{end})")


def main():
args = parse_args()
output_dir = args.output_dir or Path(f"{args.book}-archive-pages")
output_pdf = args.output_pdf or Path(f"{args.book}.pdf")
with sync_playwright() as p:
context = p.chromium.launch_persistent_context(
str(PROFILE), headless=False,
viewport={"width": 1800, "height": 2200}, device_scale_factor=2)
try:
page = context.pages[0] if context.pages else context.new_page()
page.goto(f"https://archive.org/details/{args.book}/mode/1up",
wait_until="domcontentloaded", timeout=60000)
print("Internet Archive is open in a visible browser window controlled by Playwright.")
print("1. In that browser, sign in and borrow the book if required.")
print("2. Open the reader and wait until the book's pages are visible.")
print("3. Return to this Terminal window and press Enter to start exporting.")
print("The exporter waits here until you press Enter. Your login is saved for future runs.")
print("Only pages available in this reader session can be exported.")
input("Press Enter here in Terminal when you are ready to export... ")
export_pages(page, output_dir, output_pdf, args.start, args.end)
finally:
context.close()


if __name__ == "__main__":
try:
main()
except (RuntimeError, ValueError) as exc:
raise SystemExit(f"Export stopped: {exc} Captures are retained; rerun to resume.") from None
15 changes: 15 additions & 0 deletions tests/frontend-command-builders.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import { aiReview } from "../web/js/tools/ai-review.js";
import { compression } from "../web/js/tools/compression.js";
import { googleExport } from "../web/js/tools/google-export.js";
import { archiveExport } from "../web/js/tools/archive-export.js";
import { ocr } from "../web/js/tools/ocr.js";

test("Google export builds isolated output arguments", () => {
Expand All @@ -17,6 +18,20 @@ test("Google export rejects path-like IDs", () => {
assert.throws(() => googleExport.build({ bookId: "../book" }), /Book ID may contain/);
});

test("Internet Archive accepts the linked two-page URL and scan range", () => {
assert.equal(archiveExport.build({
book: "https://archive.org/details/transformationof00seli/mode/2up",
start: "2", end: "10", outputPdf: "Wall Street.pdf",
}), "python3 export-archive-book.py transformationof00seli --output-pdf 'Wall Street.pdf' --start 2 --end 10");
});

test("Internet Archive rejects unsafe sources and reversed ranges", () => {
for (const book of ["../book", "--help", "https://example.org/details/book", "https://archive.org.evil.test/details/book", "https://user@archive.org/details/book"]) {
assert.throws(() => archiveExport.build({ book }));
}
assert.throws(() => archiveExport.build({ book: "book", start: "10", end: "2" }), /Last scan/);
});

test("OCR preserves paths with spaces", () => {
assert.equal(
ocr.build({ input: "Source Scan.pdf", output: "OCR Copy.pdf" }),
Expand Down
116 changes: 116 additions & 0 deletions tests/test_export_archive_book.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"""Internet Archive parsing, scan selection, and PDF assembly regressions."""
import argparse
import importlib.util
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch

from PIL import Image
from playwright.sync_api import sync_playwright

spec = importlib.util.spec_from_file_location(
"archive_exporter", Path(__file__).resolve().parents[1] / "export-archive-book.py")
exporter = importlib.util.module_from_spec(spec)
spec.loader.exec_module(exporter)


class InputTests(unittest.TestCase):
def test_linked_url_and_id(self):
for source in ["transformationof00seli",
"https://archive.org/details/transformationof00seli/mode/2up"]:
self.assertEqual(exporter.book_id(source), "transformationof00seli")

def test_rejects_unsafe_sources(self):
for source in ["../book", "--help", "https://example.org/details/book",
"https://user@archive.org/details/book", "https://archive.org/details/"]:
with self.subTest(source=source), self.assertRaises(argparse.ArgumentTypeError):
exporter.book_id(source)

def test_invalid_ranges(self):
for args in [["book", "--start", "0"], ["book", "--start", "10", "--end", "2"]]:
with self.assertRaises(SystemExit):
exporter.parse_args(args)


class CaptureTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.playwright = sync_playwright().start()
cls.browser = cls.playwright.chromium.launch()

@classmethod
def tearDownClass(cls):
cls.browser.close()
cls.playwright.stop()

def setUp(self):
self.directory = TemporaryDirectory()
self.root = Path(self.directory.name)
self.page = self.browser.new_page()
self.page.set_content('''<script>
window.br = {
mode: 2, index: 0, book: {getNumLeafs: () => 3},
switchMode(mode) { this.mode = mode; },
currentIndex() { return this.index; },
jumpToIndex(index) {
this.index = index;
setTimeout(() => {
const canvas = document.createElement('canvas');
canvas.width = 300; canvas.height = 400;
const context = canvas.getContext('2d');
context.fillStyle = index === 0 ? 'navy' : 'white';
context.fillRect(0, 0, 300, 400);
const container = document.createElement('div');
container.className = 'BRpagecontainer';
container.dataset.index = index;
const image = new Image(); image.className = 'BRpageimage';
image.src = canvas.toDataURL(); container.append(image);
document.body.replaceChildren(container);
}, 100);
}
};
</script><img class="BRpageimage">''')

def tearDown(self):
self.page.close()
self.directory.cleanup()

def test_delayed_scans_preserve_identical_blank_pages_and_resume_holes(self):
captures = self.root / "pages"
captures.mkdir()
Image.new("RGB", (300, 400), "white").save(captures / "0003.png")
pdf = self.root / "book.pdf"
exporter.export_pages(self.page, captures, pdf)
self.assertEqual(self.page.evaluate("br.mode"), 1)
self.assertEqual(len(list(captures.glob("*.png"))), 3)
with Image.open(captures / "0001.png") as first, Image.open(captures / "0002.png") as second:
self.assertEqual(first.getpixel((10, 10))[:3], (0, 0, 128))
self.assertEqual(second.getpixel((10, 10))[:3], (255, 255, 255))
import pikepdf
with pikepdf.open(pdf) as document:
self.assertEqual(len(document.pages), 3)

def test_unavailable_scan_preserves_existing_pdf(self):
pdf = self.root / "book.pdf"
pdf.write_bytes(b"existing document")
with patch.object(exporter, "capture_scan", side_effect=RuntimeError("unavailable")):
with self.assertRaisesRegex(RuntimeError, "unavailable"):
exporter.export_pages(self.page, self.root / "pages", pdf)
self.assertEqual(pdf.read_bytes(), b"existing document")

def test_final_scan_exports_when_viewport_counter_stays_on_previous_scan(self):
self.page.evaluate("() => { br.currentIndex = () => 1; }")
pdf = self.root / "book.pdf"
exporter.export_pages(self.page, self.root / "pages", pdf)
import pikepdf
with pikepdf.open(pdf) as document:
self.assertEqual(len(document.pages), 3)

def test_range_beyond_reader_is_rejected(self):
with self.assertRaisesRegex(ValueError, "3 scans"):
exporter.export_pages(self.page, self.root / "pages", self.root / "book.pdf", end=4)


if __name__ == "__main__":
unittest.main()
Loading
Loading