Spaces:
Sleeping
Sleeping
| import fitz # PyMuPDF | |
| import numpy as np | |
| import cv2 | |
| import tempfile | |
| import os | |
| from pathlib import Path | |
| def pdf_to_images(pdf_path, dpi=200): | |
| doc = fitz.open(pdf_path) | |
| pages = [] | |
| for page_num in range(len(doc)): | |
| page = doc[page_num] | |
| mat = fitz.Matrix(dpi / 72, dpi / 72) | |
| pix = page.get_pixmap(matrix=mat, alpha=False) | |
| img_array = np.frombuffer(pix.samples, dtype=np.uint8) | |
| img_array = img_array.reshape(pix.height, pix.width, 3) | |
| img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) | |
| pages.append((page_num + 1, img_bgr)) | |
| doc.close() | |
| return pages | |
| def ensure_output_dir(path= "outputs"): | |
| output_dir = Path(path) | |
| output_dir.mkdir(exist_ok=True) | |
| return output_dir | |
| def get_temp_path(page_num): | |
| tmp_dir = Path("outputs/tmp") | |
| tmp_dir.mkdir(parents=True, exist_ok=True) | |
| return str(tmp_dir / f"page_{page_num}.jpg") | |
| def cleanup_temp(path): | |
| try: | |
| if os.path.exists(path): | |
| os.remove(path) | |
| except Exception: | |
| pass |