# /// script # requires-python = ">=3.10" # dependencies = ["pypdfium2>=4.30", "pillow>=10", "pyarrow>=15", "huggingface-hub>=1.0"] # /// r"""Render every page of every PDF under INPUT to PNG, saved either as files in a folder or as a Hugging Face dataset with one row per page: OUTPUT ./pages -> pages/1850s/vol1/page-0001.png, page-0002.png, ... OUTPUT hf://datasets/USER/X -> rows of (image, pdf, page) in Parquet, one file per PDF: data/1850s/vol1.parquet, ... PDFs finished on an earlier run are skipped either way, so a run that stops partway (e.g. a job hitting its timeout) can simply be started again. uv run pdf2png.py ./pdfs ./pages hf jobs uv run --flavor cpu-upgrade --timeout 3h -s HF_TOKEN -v hf://datasets/USER/pdfs:/in \ -- https://huggingface.co/datasets/USER/scripts/resolve/main/pdf2png.py /in hf://datasets/USER/pages """ import argparse import io import json import os import sys import tempfile from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq import pypdfium2 as pdfium from huggingface_hub import CommitOperationAdd, HfApi from huggingface_hub.utils import disable_progress_bars DONE = ".done" # folder output: written into a PDF's folder once all of its pages are saved COMMIT_FILES, COMMIT_BYTES = 50, 5 * 10**9 # dataset output: commit every 50 PDFs or 5 GB, whichever comes first ROW_GROUP_BYTES = 100 * 10**6 # keeps Parquet row groups small enough for the dataset viewer FEATURES = {"image": {"_type": "Image"}, "pdf": {"dtype": "string", "_type": "Value"}, "page": {"dtype": "int32", "_type": "Value"}} SCHEMA = pa.schema( [("image", pa.struct([("bytes", pa.binary()), ("path", pa.string())])), ("pdf", pa.string()), ("page", pa.int32())], metadata={"huggingface": json.dumps({"info": {"features": FEATURES}})}, # so `image` loads as images ) README = """--- configs: - config_name: default data_files: "data/**/*.parquet" --- Pages rendered from PDFs with pdf2png.py: one row per page, with `image` (PNG), `pdf` and `page` columns. """ def render(pdf_path: Path, dpi: int, grayscale: bool): """Yield (filename, PNG bytes) for each page of a PDF.""" pdf = pdfium.PdfDocument(pdf_path) try: pdf.init_forms() # so filled-in form fields render as they do in a viewer n = len(pdf) for i in range(n): page = pdf[i] buf = io.BytesIO() # still lossless; ~3x faster than the default level on scans, files ~10% larger page.render(scale=dpi / 72, grayscale=grayscale).to_pil().save(buf, "PNG", compress_level=1) page.close() yield f"page-{i + 1:0{max(4, len(str(n)))}d}.png", buf.getvalue() finally: pdf.close() def to_folder(pdf_path: Path, out_dir: Path, dpi: int, grayscale: bool) -> int: out_dir.mkdir(parents=True, exist_ok=True) n = 0 for n, (filename, png) in enumerate(render(pdf_path, dpi, grayscale), 1): (out_dir / filename).write_bytes(png) (out_dir / DONE).touch() return n def to_parquet(pdf_path: Path, out_file: Path, name: str, dpi: int, grayscale: bool) -> int: out_file.parent.mkdir(parents=True, exist_ok=True) stem = Path(name).with_suffix("").as_posix() rows, size, n = [], 0, 0 with pq.ParquetWriter(out_file, SCHEMA) as writer: for n, (filename, png) in enumerate(render(pdf_path, dpi, grayscale), 1): rows.append({"image": {"bytes": png, "path": f"{stem}/{filename}"}, "pdf": name, "page": n}) size += len(png) if size >= ROW_GROUP_BYTES: writer.write_table(pa.Table.from_pylist(rows, SCHEMA)) rows, size = [], 0 if rows: writer.write_table(pa.Table.from_pylist(rows, SCHEMA)) return n def push(api: HfApi, repo: str, staging: Path, files: list) -> None: """Commit finished Parquet files to the dataset repo, then delete the local copies.""" if files: ops = [CommitOperationAdd(path_in_repo=f.relative_to(staging).as_posix(), path_or_fileobj=f) for f in files] api.create_commit(repo, ops, commit_message=f"Add {len(files)} PDFs", repo_type="dataset") print(f"committed {len(files)} PDFs to {repo}", flush=True) for f in files: f.unlink() files.clear() def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("input", type=Path, help="folder of PDFs (searched recursively), or a single PDF") parser.add_argument("output", help="folder for the PNGs, or hf://datasets/USER/NAME for a dataset") parser.add_argument("--dpi", type=int, default=300, help="render resolution (default: 300)") parser.add_argument("--grayscale", action="store_true", help="8-bit grayscale PNGs: smaller files, faster") parser.add_argument("--private", action="store_true", help="make the dataset repo private, if it gets created") parser.add_argument("--workers", type=int, default=int(os.environ.get("CPU_CORES") or os.cpu_count() or 1), help="parallel processes (default: one per CPU core)") args = parser.parse_args() if args.input.is_file(): root, pdfs = args.input.parent, [args.input] else: root = args.input pdfs = sorted(p for p in root.rglob("*") if p.suffix.lower() == ".pdf" and p.is_file()) names = {pdf: pdf.relative_to(root).as_posix() for pdf in pdfs} stems = {pdf: pdf.relative_to(root).with_suffix("").as_posix() for pdf in pdfs} todo = {} # pdf -> (worker, *args) repo = args.output.removeprefix("hf://datasets/").strip("/") if args.output.startswith("hf://datasets/") else None if repo: disable_progress_bars() api = HfApi() # authenticates with HF_TOKEN (pass it to a job with -s HF_TOKEN) api.create_repo(repo, repo_type="dataset", private=args.private or None, exist_ok=True) existing = set(api.list_repo_files(repo, repo_type="dataset")) if "README.md" not in existing: api.upload_file(path_or_fileobj=README.encode(), path_in_repo="README.md", repo_id=repo, repo_type="dataset", commit_message="Add dataset card") tmp = tempfile.TemporaryDirectory(prefix="pdf2png-") # removed when the script exits staging = Path(tmp.name) for pdf in pdfs: target = f"data/{stems[pdf]}.parquet" if target not in existing: todo[pdf] = (to_parquet, pdf, staging / target, names[pdf], args.dpi, args.grayscale) else: for pdf in pdfs: out_dir = Path(args.output, stems[pdf]) if not (out_dir / DONE).exists(): todo[pdf] = (to_folder, pdf, out_dir, args.dpi, args.grayscale) print(f"{len(pdfs)} PDFs found, {len(pdfs) - len(todo)} already done, {len(todo)} to convert", flush=True) if not todo: return failed, pending = [], [] with ProcessPoolExecutor(min(args.workers, len(todo))) as pool: futures = {pool.submit(*job): pdf for pdf, job in todo.items()} try: for i, future in enumerate(as_completed(futures), 1): pdf = futures[future] try: n = future.result() except Exception as e: failed.append(names[pdf]) print(f"[{i}/{len(todo)}] {names[pdf]}: FAILED ({e})", flush=True) continue print(f"[{i}/{len(todo)}] {names[pdf]}: {n} pages", flush=True) if repo: pending.append(todo[pdf][2]) if len(pending) >= COMMIT_FILES or sum(f.stat().st_size for f in pending) >= COMMIT_BYTES: push(api, repo, staging, pending) if repo: push(api, repo, staging, pending) except BaseException: pool.shutdown(cancel_futures=True) # stop rendering PDFs whose output can't be saved raise if failed: sys.exit(f"{len(failed)} PDF(s) failed: {', '.join(failed)}") if __name__ == "__main__": main()