Updated script to output a dataset
Browse files- pdf2png.py +119 -29
pdf2png.py
CHANGED
|
@@ -1,57 +1,116 @@
|
|
| 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
|
|
|
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
PDFs finished on an earlier run are skipped, so a run that stops
|
| 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
|
| 15 |
-
-
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
-
def
|
|
|
|
| 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 |
-
|
| 40 |
# still lossless; ~3x faster than the default level on scans, files ~10% larger
|
| 41 |
-
|
| 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",
|
| 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()
|
|
@@ -61,25 +120,56 @@ def main() -> None:
|
|
| 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 |
-
|
| 65 |
-
for pdf in pdfs
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
if failed:
|
| 84 |
sys.exit(f"{len(failed)} PDF(s) failed: {', '.join(failed)}")
|
| 85 |
|
|
|
|
| 1 |
# /// script
|
| 2 |
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = ["pypdfium2>=4.30", "pillow>=10", "pyarrow>=15", "huggingface-hub>=1.0"]
|
| 4 |
# ///
|
| 5 |
+
r"""Render every page of every PDF under INPUT to PNG, saved either as files in a
|
| 6 |
+
folder or as a Hugging Face dataset with one row per page:
|
| 7 |
|
| 8 |
+
OUTPUT ./pages -> pages/1850s/vol1/page-0001.png, page-0002.png, ...
|
| 9 |
+
OUTPUT hf://datasets/USER/X -> rows of (image, pdf, page) in Parquet, one file per PDF:
|
| 10 |
+
data/1850s/vol1.parquet, ...
|
| 11 |
|
| 12 |
+
PDFs finished on an earlier run are skipped either way, so a run that stops
|
| 13 |
+
partway (e.g. a job hitting its timeout) can simply be started again.
|
| 14 |
|
| 15 |
uv run pdf2png.py ./pdfs ./pages
|
| 16 |
|
| 17 |
+
hf jobs uv run --flavor cpu-upgrade --timeout 3h -s HF_TOKEN -v hf://datasets/USER/pdfs:/in \
|
| 18 |
+
-- https://huggingface.co/datasets/USER/scripts/resolve/main/pdf2png.py /in hf://datasets/USER/pages
|
|
|
|
| 19 |
"""
|
| 20 |
|
| 21 |
import argparse
|
| 22 |
+
import io
|
| 23 |
+
import json
|
| 24 |
import os
|
| 25 |
import sys
|
| 26 |
+
import tempfile
|
| 27 |
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 28 |
from pathlib import Path
|
| 29 |
|
| 30 |
+
import pyarrow as pa
|
| 31 |
+
import pyarrow.parquet as pq
|
| 32 |
import pypdfium2 as pdfium
|
| 33 |
+
from huggingface_hub import CommitOperationAdd, HfApi
|
| 34 |
+
from huggingface_hub.utils import disable_progress_bars
|
| 35 |
|
| 36 |
+
DONE = ".done" # folder output: written into a PDF's folder once all of its pages are saved
|
| 37 |
+
COMMIT_FILES, COMMIT_BYTES = 50, 5 * 10**9 # dataset output: commit every 50 PDFs or 5 GB, whichever comes first
|
| 38 |
+
ROW_GROUP_BYTES = 100 * 10**6 # keeps Parquet row groups small enough for the dataset viewer
|
| 39 |
+
FEATURES = {"image": {"_type": "Image"}, "pdf": {"dtype": "string", "_type": "Value"},
|
| 40 |
+
"page": {"dtype": "int32", "_type": "Value"}}
|
| 41 |
+
SCHEMA = pa.schema(
|
| 42 |
+
[("image", pa.struct([("bytes", pa.binary()), ("path", pa.string())])), ("pdf", pa.string()), ("page", pa.int32())],
|
| 43 |
+
metadata={"huggingface": json.dumps({"info": {"features": FEATURES}})}, # so `image` loads as images
|
| 44 |
+
)
|
| 45 |
+
README = """---
|
| 46 |
+
configs:
|
| 47 |
+
- config_name: default
|
| 48 |
+
data_files: "data/**/*.parquet"
|
| 49 |
+
---
|
| 50 |
+
Pages rendered from PDFs with pdf2png.py: one row per page, with `image` (PNG), `pdf` and `page` columns.
|
| 51 |
+
"""
|
| 52 |
|
| 53 |
|
| 54 |
+
def render(pdf_path: Path, dpi: int, grayscale: bool):
|
| 55 |
+
"""Yield (filename, PNG bytes) for each page of a PDF."""
|
| 56 |
pdf = pdfium.PdfDocument(pdf_path)
|
| 57 |
try:
|
| 58 |
pdf.init_forms() # so filled-in form fields render as they do in a viewer
|
| 59 |
n = len(pdf)
|
|
|
|
|
|
|
| 60 |
for i in range(n):
|
| 61 |
page = pdf[i]
|
| 62 |
+
buf = io.BytesIO()
|
| 63 |
# still lossless; ~3x faster than the default level on scans, files ~10% larger
|
| 64 |
+
page.render(scale=dpi / 72, grayscale=grayscale).to_pil().save(buf, "PNG", compress_level=1)
|
| 65 |
page.close()
|
| 66 |
+
yield f"page-{i + 1:0{max(4, len(str(n)))}d}.png", buf.getvalue()
|
| 67 |
finally:
|
| 68 |
pdf.close()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def to_folder(pdf_path: Path, out_dir: Path, dpi: int, grayscale: bool) -> int:
|
| 72 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 73 |
+
n = 0
|
| 74 |
+
for n, (filename, png) in enumerate(render(pdf_path, dpi, grayscale), 1):
|
| 75 |
+
(out_dir / filename).write_bytes(png)
|
| 76 |
(out_dir / DONE).touch()
|
| 77 |
return n
|
| 78 |
|
| 79 |
|
| 80 |
+
def to_parquet(pdf_path: Path, out_file: Path, name: str, dpi: int, grayscale: bool) -> int:
|
| 81 |
+
out_file.parent.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
stem = Path(name).with_suffix("").as_posix()
|
| 83 |
+
rows, size, n = [], 0, 0
|
| 84 |
+
with pq.ParquetWriter(out_file, SCHEMA) as writer:
|
| 85 |
+
for n, (filename, png) in enumerate(render(pdf_path, dpi, grayscale), 1):
|
| 86 |
+
rows.append({"image": {"bytes": png, "path": f"{stem}/{filename}"}, "pdf": name, "page": n})
|
| 87 |
+
size += len(png)
|
| 88 |
+
if size >= ROW_GROUP_BYTES:
|
| 89 |
+
writer.write_table(pa.Table.from_pylist(rows, SCHEMA))
|
| 90 |
+
rows, size = [], 0
|
| 91 |
+
if rows:
|
| 92 |
+
writer.write_table(pa.Table.from_pylist(rows, SCHEMA))
|
| 93 |
+
return n
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def push(api: HfApi, repo: str, staging: Path, files: list) -> None:
|
| 97 |
+
"""Commit finished Parquet files to the dataset repo, then delete the local copies."""
|
| 98 |
+
if files:
|
| 99 |
+
ops = [CommitOperationAdd(path_in_repo=f.relative_to(staging).as_posix(), path_or_fileobj=f) for f in files]
|
| 100 |
+
api.create_commit(repo, ops, commit_message=f"Add {len(files)} PDFs", repo_type="dataset")
|
| 101 |
+
print(f"committed {len(files)} PDFs to {repo}", flush=True)
|
| 102 |
+
for f in files:
|
| 103 |
+
f.unlink()
|
| 104 |
+
files.clear()
|
| 105 |
+
|
| 106 |
+
|
| 107 |
def main() -> None:
|
| 108 |
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 109 |
parser.add_argument("input", type=Path, help="folder of PDFs (searched recursively), or a single PDF")
|
| 110 |
+
parser.add_argument("output", help="folder for the PNGs, or hf://datasets/USER/NAME for a dataset")
|
| 111 |
parser.add_argument("--dpi", type=int, default=300, help="render resolution (default: 300)")
|
| 112 |
parser.add_argument("--grayscale", action="store_true", help="8-bit grayscale PNGs: smaller files, faster")
|
| 113 |
+
parser.add_argument("--private", action="store_true", help="make the dataset repo private, if it gets created")
|
| 114 |
parser.add_argument("--workers", type=int, default=int(os.environ.get("CPU_CORES") or os.cpu_count() or 1),
|
| 115 |
help="parallel processes (default: one per CPU core)")
|
| 116 |
args = parser.parse_args()
|
|
|
|
| 120 |
else:
|
| 121 |
root = args.input
|
| 122 |
pdfs = sorted(p for p in root.rglob("*") if p.suffix.lower() == ".pdf" and p.is_file())
|
| 123 |
+
names = {pdf: pdf.relative_to(root).as_posix() for pdf in pdfs}
|
| 124 |
+
stems = {pdf: pdf.relative_to(root).with_suffix("").as_posix() for pdf in pdfs}
|
| 125 |
+
|
| 126 |
+
todo = {} # pdf -> (worker, *args)
|
| 127 |
+
repo = args.output.removeprefix("hf://datasets/").strip("/") if args.output.startswith("hf://datasets/") else None
|
| 128 |
+
if repo:
|
| 129 |
+
disable_progress_bars()
|
| 130 |
+
api = HfApi() # authenticates with HF_TOKEN (pass it to a job with -s HF_TOKEN)
|
| 131 |
+
api.create_repo(repo, repo_type="dataset", private=args.private or None, exist_ok=True)
|
| 132 |
+
existing = set(api.list_repo_files(repo, repo_type="dataset"))
|
| 133 |
+
if "README.md" not in existing:
|
| 134 |
+
api.upload_file(path_or_fileobj=README.encode(), path_in_repo="README.md", repo_id=repo,
|
| 135 |
+
repo_type="dataset", commit_message="Add dataset card")
|
| 136 |
+
tmp = tempfile.TemporaryDirectory(prefix="pdf2png-") # removed when the script exits
|
| 137 |
+
staging = Path(tmp.name)
|
| 138 |
+
for pdf in pdfs:
|
| 139 |
+
target = f"data/{stems[pdf]}.parquet"
|
| 140 |
+
if target not in existing:
|
| 141 |
+
todo[pdf] = (to_parquet, pdf, staging / target, names[pdf], args.dpi, args.grayscale)
|
| 142 |
+
else:
|
| 143 |
+
for pdf in pdfs:
|
| 144 |
+
out_dir = Path(args.output, stems[pdf])
|
| 145 |
+
if not (out_dir / DONE).exists():
|
| 146 |
+
todo[pdf] = (to_folder, pdf, out_dir, args.dpi, args.grayscale)
|
| 147 |
print(f"{len(pdfs)} PDFs found, {len(pdfs) - len(todo)} already done, {len(todo)} to convert", flush=True)
|
| 148 |
if not todo:
|
| 149 |
return
|
| 150 |
|
| 151 |
+
failed, pending = [], []
|
| 152 |
with ProcessPoolExecutor(min(args.workers, len(todo))) as pool:
|
| 153 |
+
futures = {pool.submit(*job): pdf for pdf, job in todo.items()}
|
| 154 |
+
try:
|
| 155 |
+
for i, future in enumerate(as_completed(futures), 1):
|
| 156 |
+
pdf = futures[future]
|
| 157 |
+
try:
|
| 158 |
+
n = future.result()
|
| 159 |
+
except Exception as e:
|
| 160 |
+
failed.append(names[pdf])
|
| 161 |
+
print(f"[{i}/{len(todo)}] {names[pdf]}: FAILED ({e})", flush=True)
|
| 162 |
+
continue
|
| 163 |
+
print(f"[{i}/{len(todo)}] {names[pdf]}: {n} pages", flush=True)
|
| 164 |
+
if repo:
|
| 165 |
+
pending.append(todo[pdf][2])
|
| 166 |
+
if len(pending) >= COMMIT_FILES or sum(f.stat().st_size for f in pending) >= COMMIT_BYTES:
|
| 167 |
+
push(api, repo, staging, pending)
|
| 168 |
+
if repo:
|
| 169 |
+
push(api, repo, staging, pending)
|
| 170 |
+
except BaseException:
|
| 171 |
+
pool.shutdown(cancel_futures=True) # stop rendering PDFs whose output can't be saved
|
| 172 |
+
raise
|
| 173 |
if failed:
|
| 174 |
sys.exit(f"{len(failed)} PDF(s) failed: {', '.join(failed)}")
|
| 175 |
|