|
import os |
|
from io import BytesIO |
|
from tqdm import tqdm |
|
from typing import Callable, Dict, List, Literal, NamedTuple, Optional, Tuple, Union |
|
|
|
from datasets import load_dataset, logging |
|
from PIL import Image |
|
|
|
import fitz as PyMuPDF |
|
|
|
logger = logging.get_logger(__name__) |
|
|
|
def pymupdf_image_extraction(data: bytes): |
|
images = [] |
|
with PyMuPDF.open(stream=data, filetype="pdf") as pdf_file: |
|
for page_index in range(len(pdf_file)): |
|
page = pdf_file[page_index] |
|
for image_index, img in enumerate(page.get_images(), start=1): |
|
xref = img[0] |
|
base_image = pdf_file.extract_image(xref) |
|
image_bytes = base_image["image"] |
|
im = Image.open(BytesIO(image_bytes)) |
|
images.append(im) |
|
return images |
|
|
|
|
|
def batch_get_images(streams): |
|
return { |
|
"images": |
|
[pymupdf_image_extraction(pdf_stream) for pdf_stream in tqdm(streams, desc="get_images")] |
|
|
|
} |
|
|
|
|
|
def pymupdf_page_extraction(pdf_stream): |
|
try: |
|
return len(PyMuPDF.open(stream=pdf_stream, filetype="pdf")) |
|
except Exception as e: |
|
logger.warning(f"{e}") |
|
return 0 |
|
|
|
|
|
def batch_get_pages(streams): |
|
return { |
|
"pages": |
|
[pymupdf_page_extraction(pdf_stream) for pdf_stream in tqdm(streams, desc="get_pages")], |
|
} |
|
|
|
|
|
testds = load_dataset("jordyvl/rvl_cdip_multi", cache_dir="/mnt/lerna/data/HFcache", split="test", revision="d3a654c9f63f14d0aaa94e08aa30aa3dc20713c1") |
|
|
|
func = lambda batch: batch_get_pages(batch["file"]) |
|
testds = testds.map(func, batched=True, keep_in_memory=False) |
|
testds = testds.filter(lambda example: example["pages"] != 0) |
|
|
|
func = lambda batch: batch_get_images(batch["file"]) |
|
testds = testds.map(func, batched=True, keep_in_memory=False) |
|
|
|
import pdb; pdb.set_trace() |
|
|
|
""" |
|
Filter based on page count? |
|
""" |
|
|