Create pdf2png.py
Browse files- pdf2png.py +88 -0
pdf2png.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = ["pypdfium2>=4.30", "pillow>=10"]
|
| 4 |
+
# ///
|
| 5 |
+
r"""Render every page of every PDF under INPUT to PNG under OUTPUT, one folder per PDF:
|
| 6 |
+
|
| 7 |
+
INPUT/1850s/vol1.pdf -> OUTPUT/1850s/vol1/page-0001.png, page-0002.png, ...
|
| 8 |
+
|
| 9 |
+
PDFs finished on an earlier run are skipped, so a run that stops partway
|
| 10 |
+
(e.g. a job hitting its timeout) can simply be started again.
|
| 11 |
+
|
| 12 |
+
uv run pdf2png.py ./pdfs ./pages
|
| 13 |
+
|
| 14 |
+
hf jobs uv run --flavor cpu-upgrade --timeout 2h \
|
| 15 |
+
-v hf://datasets/USER/pdfs:/in -v hf://buckets/USER/pages:/out \
|
| 16 |
+
-- https://huggingface.co/datasets/USER/scripts/resolve/main/pdf2png.py /in /out
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import pypdfium2 as pdfium
|
| 26 |
+
|
| 27 |
+
DONE = ".done" # written into a PDF's output folder once all of its pages are saved
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def convert(pdf_path: Path, out_dir: Path, dpi: int, grayscale: bool) -> int:
|
| 31 |
+
pdf = pdfium.PdfDocument(pdf_path)
|
| 32 |
+
try:
|
| 33 |
+
pdf.init_forms() # so filled-in form fields render as they do in a viewer
|
| 34 |
+
n = len(pdf)
|
| 35 |
+
width = max(4, len(str(n)))
|
| 36 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
for i in range(n):
|
| 38 |
+
page = pdf[i]
|
| 39 |
+
image = page.render(scale=dpi / 72, grayscale=grayscale).to_pil()
|
| 40 |
+
# still lossless; ~3x faster than the default level on scans, files ~10% larger
|
| 41 |
+
image.save(out_dir / f"page-{i + 1:0{width}d}.png", compress_level=1)
|
| 42 |
+
page.close()
|
| 43 |
+
finally:
|
| 44 |
+
pdf.close()
|
| 45 |
+
(out_dir / DONE).touch()
|
| 46 |
+
return n
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main() -> None:
|
| 50 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 51 |
+
parser.add_argument("input", type=Path, help="folder of PDFs (searched recursively), or a single PDF")
|
| 52 |
+
parser.add_argument("output", type=Path, help="folder to write the PNGs to")
|
| 53 |
+
parser.add_argument("--dpi", type=int, default=300, help="render resolution (default: 300)")
|
| 54 |
+
parser.add_argument("--grayscale", action="store_true", help="8-bit grayscale PNGs: smaller files, faster")
|
| 55 |
+
parser.add_argument("--workers", type=int, default=int(os.environ.get("CPU_CORES") or os.cpu_count() or 1),
|
| 56 |
+
help="parallel processes (default: one per CPU core)")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
|
| 59 |
+
if args.input.is_file():
|
| 60 |
+
root, pdfs = args.input.parent, [args.input]
|
| 61 |
+
else:
|
| 62 |
+
root = args.input
|
| 63 |
+
pdfs = sorted(p for p in root.rglob("*") if p.suffix.lower() == ".pdf" and p.is_file())
|
| 64 |
+
todo = {}
|
| 65 |
+
for pdf in pdfs:
|
| 66 |
+
out_dir = args.output / pdf.relative_to(root).with_suffix("")
|
| 67 |
+
if not (out_dir / DONE).exists():
|
| 68 |
+
todo[pdf] = out_dir
|
| 69 |
+
print(f"{len(pdfs)} PDFs found, {len(pdfs) - len(todo)} already done, {len(todo)} to convert", flush=True)
|
| 70 |
+
if not todo:
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
failed = []
|
| 74 |
+
with ProcessPoolExecutor(min(args.workers, len(todo))) as pool:
|
| 75 |
+
futures = {pool.submit(convert, pdf, out, args.dpi, args.grayscale): pdf for pdf, out in todo.items()}
|
| 76 |
+
for i, future in enumerate(as_completed(futures), 1):
|
| 77 |
+
name = futures[future].relative_to(root)
|
| 78 |
+
try:
|
| 79 |
+
print(f"[{i}/{len(todo)}] {name}: {future.result()} pages", flush=True)
|
| 80 |
+
except Exception as e:
|
| 81 |
+
failed.append(str(name))
|
| 82 |
+
print(f"[{i}/{len(todo)}] {name}: FAILED ({e})", flush=True)
|
| 83 |
+
if failed:
|
| 84 |
+
sys.exit(f"{len(failed)} PDF(s) failed: {', '.join(failed)}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
main()
|