Spaces:
Paused
Paused
Download modules/render_page.py from Rachel7/hvac_fable: direct link, hf CLI and curl.
- Browser
- Download file 1.65 kB
-
https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/modules/render_page.py
- Command line
-
hf download hf://spaces/Rachel7/hvac_fable/modules/render_page.py
-
curl -L -o render_page.py https://huggingface.co/spaces/Rachel7/hvac_fable/resolve/main/modules/render_page.py
1.65 kB
| """Render one PDF page (optionally downscaled) to a PNG. | |
| Used two ways: | |
| * imported in-process by the server when its Python has PyMuPDF (fitz), or | |
| * run as a subprocess via the .venv Python (which always has fitz) otherwise. | |
| CLI: python render_page.py <pdf> <page_1based> <out_png> [--dpi 150] [--max-px 2600] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from pathlib import Path | |
| def render(pdf_path, page_1based: int, out_png, dpi: int = 150, max_px: int = 2600) -> str: | |
| import fitz | |
| from PIL import Image | |
| Image.MAX_IMAGE_PIXELS = None | |
| doc = fitz.open(str(pdf_path)) | |
| page = doc.load_page(int(page_1based) - 1) | |
| mat = fitz.Matrix(dpi / 72.0, dpi / 72.0) | |
| pix = page.get_pixmap(matrix=mat, alpha=False) | |
| img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) | |
| # Downscale for the browser so 300-DPI sheets aren't 12000px monsters. | |
| if max_px and max(img.size) > max_px: | |
| scale = max_px / max(img.size) | |
| img = img.resize((max(1, int(img.width * scale)), max(1, int(img.height * scale))), | |
| Image.LANCZOS) | |
| out_png = Path(out_png) | |
| out_png.parent.mkdir(parents=True, exist_ok=True) | |
| img.save(out_png, format="PNG") | |
| return str(out_png) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("pdf") | |
| ap.add_argument("page", type=int) | |
| ap.add_argument("out_png") | |
| ap.add_argument("--dpi", type=int, default=150) | |
| ap.add_argument("--max-px", type=int, default=2600) | |
| a = ap.parse_args() | |
| print(render(a.pdf, a.page, a.out_png, a.dpi, a.max_px)) | |