# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """DUDE dataset loader""" import os from pathlib import Path import time import copy import json import numpy as np import pandas as pd from tqdm import tqdm from io import BytesIO tqdm.pandas() from joblib import Parallel, delayed import pdf2image import PyPDF2 from PIL import Image as PIL_Image from datasets import load_dataset_builder, load_dataset, logging logger = logging.get_logger(__name__) MAX_PAGES = 50 MAX_PDF_SIZE = 100000000 # almost 100MB MIN_WIDTH, MIN_HEIGHT = 150, 150 def load_json(json_path): return json.load(open(json_path, "r")) def save_json(json_path, data): with open(json_path, "w") as f: json.dump(data, f) def get_images_pdf2image(document_filepath): info = pdf2image.pdfinfo_from_path(document_filepath, userpw=None, poppler_path=None) maxPages = info["Pages"] maxPages = min(maxPages, maxPages) # logger.info(f"{document_filepath} has {str(maxPages)} pages") images = [] for page in range(1, maxPages + 1, 10): images.extend( pdf2image.convert_from_path( document_filepath, first_page=page, last_page=min(page + 10 - 1, maxPages) ) ) return images def pdf_to_images(document_filepath, converter="PyPDF2"): def images_to_pagenames(images, document_filepath, page_image_dir): page_image_names = [] for page_idx, page_image in enumerate(images): page_image_name = document_filepath.replace("PDF", "images").replace( ".pdf", f"_{page_idx}.jpg" ) page_image_names.append(page_image_name.replace(page_image_dir, "")) # without dir if not os.path.exists(page_image_name): page_image.convert("RGB").save(page_image_name) return page_image_names example = {} example["num_pages"] = 0 example["page_image_names"] = [] images = [] page_image_dir = "/".join(document_filepath.split("/")[:-1]).replace("PDF", "images") if not os.path.exists(page_image_dir): os.makedirs(page_image_dir) # if len(document_filepath) > MAX_PDF_SIZE: # logger.warning(f"too large document {len(example['document'])}") # return example reached_page_limit = False if converter == "PyPDF2": try: reader = PyPDF2.PdfReader(document_filepath) except Exception as e: logger.warning(f"read_pdf {e}") return example for p, page in enumerate(reader.pages): if reached_page_limit: break try: for image in page.images: if len(images) == MAX_PAGES: reached_page_limit = True break im = PIL_Image.open(BytesIO(image.data)) if im.width < MIN_WIDTH and im.height < MIN_HEIGHT: continue images.append(im) except Exception as e: logger.warning(f"get_images {e}") elif converter == "pdf2image": images = get_images_pdf2image(document_filepath) example["num_pages"] = len(images) if len(images) == 0: return example example["page_image_names"] = images_to_pagenames(images, document_filepath, page_image_dir) return example def pdf_to_images_block(document_paths_blocks, converter): new_doc_metadata = {} for document_filepath in document_paths_blocks: docId = document_filepath.split("/")[-1].replace(".pdf", "") new_doc_metadata[docId] = pdf_to_images(document_filepath, converter=converter) return new_doc_metadata def parse_textract_bbox(box): # 0.47840896, 0.12897822, 0.5341576 , 0.14347914 # x,w,y,h return np.array([box["Left"], box["Width"], box["Top"], box["Height"]]) def parse_azure_box(box, page_width, page_height): # Box in Azure are in format X top left, Y top left, X top right, Y top right, X bottom right, Y bottom right, X bottom left, Y bottom left # [14.1592, 3.8494, 28.668, 3.8494, 28.668, 8.0487, 13.9844, 7.8738] left = min(box[0], box[6]) right = max(box[2], box[4]) top = min(box[1], box[3]) bottom = max(box[5], box[7]) width = right - left height = bottom - top # Normalize left = left / page_width top = top / page_height width = width / page_width height = height / page_height return [left, width, top, height] def get_ocr_information(ocr_path, num_pages): ocr_info = load_json(ocr_path) ocr_pages = ocr_info[0]["DocumentMetadata"]["Pages"] if num_pages != ocr_pages: raise AssertionError("Pages from images and OCR not matching, should go for pdf2image") page_ocr_tokens = [[] for page_ix in range(num_pages)] page_ocr_boxes = [[] for page_ix in range(num_pages)] for ocr_block in ocr_info: for ocr_extraction in ocr_block["Blocks"]: if ocr_extraction["BlockType"] == "WORD": text = ocr_extraction["Text"].lower() bounding_box = parse_textract_bbox( ocr_extraction["Geometry"]["BoundingBox"] ).tolist() page = ocr_extraction["Page"] - 1 page_ocr_tokens[page].append(text) page_ocr_boxes[page].append(bounding_box) """ for page in range(num_pages): page_ocr_boxes[page] = np.array(page_ocr_boxes[page]) """ return page_ocr_tokens, page_ocr_boxes def create_header(split, version, has_answer): header = { "creation_time": time.time(), "version": version, "dataset_type": split, "has_answer": has_answer, } return header def get_document_info(documents_metadata, docId): doc_metadata = documents_metadata[docId] num_pages = doc_metadata["num_pages"] page_image_names = doc_metadata["page_image_names"] return num_pages, page_image_names def format_answers(answers_list): answers_list = list(set([answer.lower() for answer in answers_list])) return answers_list def create_imdb_record_from_json( record, documents_metadata, documents_ocr_info, split, include_answers ): docId = record["docId"].split("_")[0] # document_filepath = documents_dict[docId] try: num_pages, page_image_names = get_document_info(documents_metadata, docId) document_ocr_info = documents_ocr_info[docId] except Exception as e: print( "Missing: ", e, docId, ) return {} if include_answers: answers = format_answers(record["answers"]) else: answers = None imdb_record = { "question_id": record["questionId"], "question": record["question"], "docId": docId, "image_name": page_image_names, "num_pages": num_pages, "ocr_tokens": document_ocr_info["ocr_tokens"], "ocr_normalized_boxes": document_ocr_info["ocr_boxes"], "set_name": split, "answers": answers, "answer_page": None, "extra": { # 'question_type': record['qtype'], # 'industry': record['industry'], # 'category': record['category'], "answer_type": record["answer_type"], }, } return imdb_record def create_imdb_from_json( data, documents_metadata, documents_ocr_info, split, version, include_answers=True ): imdb_header = create_header(split, version, include_answers) imdb_records = [] for record in tqdm(data): imdb_record = create_imdb_record_from_json( record, documents_metadata, documents_ocr_info, split, include_answers ) if imdb_record: imdb_records.append(imdb_record) imdb = [imdb_header] + imdb_records return imdb if __name__ == "__main__": dataset = load_dataset( "../DUDE_loader/DUDE_loader.py", "DUDE", data_dir="/home/jordy/Downloads/DUDE_train-val-test_binaries", ) splits = dataset.keys() for split in splits: if split != "val": continue split_indices = [] OCR_paths = [] document_paths = [] for i, x in enumerate(dataset[split]): if x["data_split"] != split: continue if x["document"] not in document_paths: document_paths.append(x["document"]) OCR_paths.append(x["OCR"]) split_indices.append(i) # document_paths = document_paths[:30] # OCR_paths = OCR_paths[:30] # 1. PDF to image dir and collect document metadata (num_pages, page_image_names) documents_metadata_filename = f"{split}-documents_metadata.json" if os.path.exists(documents_metadata_filename): print(f"Loading from disk: {documents_metadata_filename}") documents_metadata = load_json(documents_metadata_filename) else: documents_metadata = {} num_jobs = 1 block_size = int(len(document_paths) / num_jobs) + 1 print(f"{block_size} * {num_jobs} = {block_size*num_jobs} ({len(document_paths)})") document_blocks = [ document_paths[block_size * i : block_size * i + block_size] for i in range(num_jobs) ] print( "chunksize", len(set([docId for doc_block in document_blocks for docId in doc_block])), ) parallel_results = Parallel(n_jobs=num_jobs)( delayed(pdf_to_images_block)(document_blocks[i], "pdf2image") for i in range(num_jobs) ) for block_result in parallel_results: for docId, metadata in tqdm(block_result.items()): if docId not in documents_metadata: documents_metadata[docId] = metadata save_json(documents_metadata_filename, documents_metadata) # 2. Process OCR to obtain doc_ocr_info documents_ocr_filename = f"{split}-documents_ocr.json" if os.path.exists(documents_ocr_filename) and False: print(f"Loading from disk: {documents_ocr_filename}") documents_ocr_info = load_json(documents_ocr_filename) else: documents_ocr_info = {} no_ocr = [] error_ocr = [] for i, document_filepath in enumerate(document_paths): docId = document_filepath.split("/")[-1].replace(".pdf", "") try: ocr_tokens, ocr_boxes = get_ocr_information( OCR_paths[i], documents_metadata[docId]["num_pages"] ) documents_ocr_info[docId] = {"ocr_tokens": ocr_tokens, "ocr_boxes": ocr_boxes} except AssertionError as e: print(f"image2pages issue: {e}") error_ocr.append(docId) except IndexError as e: print(f"pages issue: {e}") error_ocr.append(docId) except FileNotFoundError: print(f"FileNotFoundError issue: {e}") no_ocr.append(docId) except KeyError: print(f"Keyerror issue: {e}") error_ocr.append(docId) save_json(documents_ocr_filename, documents_ocr_info) imdb = create_imdb_from_json( dataset[split], # .select(split_indices), documents_metadata=documents_metadata, documents_ocr_info=documents_ocr_info, split=split, version="0.1", include_answers=True, ) np.save(f"{split}_imdb.npy", imdb) # dump to lerna import pdb pdb.set_trace() # breakpoint 930f4f6a // # page_image_dir = '/'.join(dataset['val']['document'][0].split("/")[:-1]).replace('PDF', 'images') # if not os.path.exists(page_image_dir): # os.makedirs(page_image_dir) # dataset.info.features """ Describe all steps that need to happen after loading HF DUDE dataset Change functions page_images_dir 2. Process OCR to obtain doc_ocr_info """ # update dataset with # for split in SPLITS # documents_metadata # doc_ocr_info # dict to unique docs # documents_metadata[docId] = {"num_pages": num_pages, "page_image_names": image_names} # doc_ocr_info[docId] = {"ocr_tokens": ocr_tokens, "ocr_boxes": ocr_boxes} """ train_imdb = create_imdb_from_json( train_data, documents_metadata=documents_metadata, documents_ocr_info=doc_ocr_info, split="train", version="0.1", include_answers=True, ) np.save("Imdb/train_imdb.npy", train_imdb) document_paths = [] num_jobs = 6 block_size = int(len(document_ids) / num_jobs) + 1 print(f"{block_size} * {num_jobs} = {block_size*num_jobs} ({len(document_ids)})") parallel_results = Parallel(n_jobs=num_jobs)( delayed(get_document_metadata_block)(documents_metadata, documents, documents_blocks[i]) for i in range(num_jobs) ) """