File size: 5,427 Bytes
ed15331 |
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
# Copyright 2023 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.
"""RVL-CDIP_mp (Ryerson Vision Lab Complex Document Information Processing) -Extended -Multipage dataset"""
import os
import datasets
from pathlib import Path
from typing import List
from tqdm import tqdm
datasets.logging.set_verbosity_info()
logger = datasets.logging.get_logger(__name__)
MODE = "binary"
_CITATION = """
@inproceedings{bdpc,
title = {Beyond Document Page Classification},
author = {Anonymous},
booktitle = {Under Review},
year = {2023}
}
"""
_DESCRIPTION = """\
The RVL-CDIP (Ryerson Vision Lab Complex Document Information Processing) dataset consists of originally retrieved documents in 16 classes.
There were +-500 documents from the original dataset that could not be retrieved based on the metadata or were corrupt in IDL.
"""
_HOMEPAGE = "https://www.cs.cmu.edu/~aharley/rvl-cdip/"
_LICENSE = "https://www.industrydocuments.ucsf.edu/help/copyright/"
SOURCE = "bdpc/rvl_cdip_mp"
_BACKOFF_folder = "/mnt/lerna/data/RVL-CDIP_pdf"
_CLASSES = [
"letter",
"form",
"email",
"handwritten",
"advertisement",
"scientific_report",
"scientific_publication",
"specification",
"file_folder",
"news_article",
"budget",
"invoice",
"presentation",
"questionnaire",
"resume",
"memo",
]
def open_pdf_binary(pdf_file):
with open(pdf_file, "rb") as f:
return f.read()
class RvlCdipMp(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="default",
version=datasets.Version("1.0.0", ""),
description="",
)
]
def __init__(self, *args, examples_per_class=None, **kwargs):
super().__init__(*args, **kwargs)
# examples per class to stop generating
self.examples_per_class = examples_per_class
@property
def manual_download_instructions(self):
return (
"To use RVL-CDIP_multi you have to download it manually. Please extract all files in one folder and load the dataset with: "
"`datasets.load_dataset('bdpc/rvl_cdip_mp', data_dir='path/to/folder/folder_name')`"
)
def _info(self):
# DEFAULT_WRITER_BATCH_SIZE
folder = None
if isinstance(self.config.data_files, str):
folder = self.config.data_files # needs to be extracted cuz zip/tar
else:
if isinstance(self.config.data_dir, str):
folder = self.config.data_dir # contains the folder structure at someone local disk
else:
folder = _BACKOFF_folder # my local path, others should set data_dir or data_files
self.config.data_dir = folder
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"file": datasets.Value("binary"), # datasets.Sequence(datasets.Image()),
"labels": datasets.features.ClassLabel(names=_CLASSES),
}
),
task_templates=None,
)
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
if os.path.isdir(self.config.data_dir):
data_files = {
labelset: os.path.join(self.config.data_dir, labelset)
for labelset in sorted(os.listdir(self.config.data_dir), reverse=True)
if not "csv" in labelset
}
elif self.config.data_dir.endswith(".tar.gz"):
archive_path = dl_manager.download(self.config.data_dir)
data_files = dl_manager.iter_archive(archive_path)
raise NotImplementedError()
elif self.config.data_dir.endswith(".zip"):
archive_path = dl_manager.download_and_extract(self.config.data_dir)
data_files = dl_manager.iter_archive(archive_path)
raise NotImplementedError()
splits = []
for split_name, folder in data_files.items():
print(folder)
splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"archive_path": folder}))
return splits
def _generate_examples(self, archive_path):
labels = self.info.features["labels"]
extensions = {".pdf", ".PDF"}
for i, path in tqdm(enumerate(Path(archive_path).glob("**/*/*")), desc=f"{archive_path}"):
if path.suffix in extensions:
try:
images = open_pdf_binary(path)
yield path.name, {
"file": images,
"labels": labels.encode_example(path.parent.name.lower()),
}
except Exception as e:
logger.warning(f"{e} failed to parse {i}")
|