Download convert_pdfs.py from divinity-library/scripts: direct link, hf CLI and curl.
- Browser
- Download file 1.66 kB
-
https://huggingface.co/datasets/divinity-library/scripts/resolve/main/convert_pdfs.py
- Command line
-
hf download hf://datasets/divinity-library/scripts/convert_pdfs.py
-
curl -L -o convert_pdfs.py https://huggingface.co/datasets/divinity-library/scripts/resolve/main/convert_pdfs.py
1.66 kB
| from pathlib import Path | |
| import fitz | |
| input_dir = Path("/Users/productivity/Downloads/Approaching_Religion/AllPDFS") | |
| output_dir = Path("/Users/productivity/Downloads/Approaching_Religion/PNGs") | |
| DPI = 300 | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| pdf_files = sorted( | |
| p for p in input_dir.glob("*.pdf") | |
| if p.is_file() | |
| ) | |
| total_pages = 0 | |
| failed_files = [] | |
| print(f"Found {len(pdf_files)} PDF files.") | |
| for file_number, pdf_path in enumerate(pdf_files, start=1): | |
| try: | |
| with fitz.open(pdf_path) as pdf: | |
| pdf_output = output_dir / pdf_path.stem | |
| pdf_output.mkdir(parents=True, exist_ok=True) | |
| page_count = len(pdf) | |
| print( | |
| f"[{file_number}/{len(pdf_files)}] " | |
| f"{pdf_path.name}: {page_count} pages" | |
| ) | |
| for page_number, page in enumerate(pdf, start=1): | |
| pix = page.get_pixmap( | |
| dpi=DPI, | |
| colorspace=fitz.csRGB, | |
| alpha=False | |
| ) | |
| output_file = ( | |
| pdf_output / | |
| f"{pdf_path.stem}_page_{page_number:04d}.png" | |
| ) | |
| pix.save(output_file) | |
| total_pages += page_count | |
| except Exception as exc: | |
| failed_files.append((pdf_path.name, str(exc))) | |
| print(f"ERROR: {pdf_path.name}: {exc}") | |
| print("\nConversion complete.") | |
| print(f"Successfully converted pages: {total_pages}") | |
| print(f"Failed PDFs: {len(failed_files)}") | |
| if failed_files: | |
| print("\nFiles requiring attention:") | |
| for filename, error in failed_files: | |
| print(f"- {filename}: {error}") |