Spaces:
Sleeping
Sleeping
File size: 1,042 Bytes
a03961a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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 |