pierreguillou commited on
Commit
389e375
1 Parent(s): bc6730e

Delete data/DocLayNet-small.py

Browse files
Files changed (1) hide show
  1. data/DocLayNet-small.py +0 -233
data/DocLayNet-small.py DELETED
@@ -1,233 +0,0 @@
1
- # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- # DocLayNet License: https://github.com/DS4SD/DocLayNet/blob/main/LICENSE
16
- # Apache License 2.0
17
-
18
- """
19
- DocLayNet small is a about 1% of the dataset DocLayNet (more information at https://huggingface.co/datasets/pierreguillou/DocLayNet-small)
20
- DocLayNet: A Large Human-Annotated Dataset for Document-Layout Analysis
21
- DocLayNet dataset:
22
- - DocLayNet core dataset: https://codait-cos-dax.s3.us.cloud-object-storage.appdomain.cloud/dax-doclaynet/1.0.0/DocLayNet_core.zip
23
- - DocLayNet extra dataset: https://codait-cos-dax.s3.us.cloud-object-storage.appdomain.cloud/dax-doclaynet/1.0.0/DocLayNet_extra.zip
24
- """
25
-
26
- import json
27
- import os
28
- import small64
29
- from PIL import Image
30
- import datasets
31
-
32
- # Find for instance the citation on arxiv or on the dataset repo/website
33
- _CITATION = """\
34
- @article{doclaynet2022,
35
- title = {DocLayNet: A Large Human-Annotated Dataset for Document-Layout Analysis},
36
- doi = {10.1145/3534678.353904},
37
- url = {https://arxiv.org/abs/2206.01062},
38
- author = {Pfitzmann, Birgit and Auer, Christoph and Dolfi, Michele and Nassar, Ahmed S and Staar, Peter W J},
39
- year = {2022}
40
- }
41
- """
42
-
43
- # You can copy an official description
44
- _DESCRIPTION = """\
45
- Accurate document layout analysis is a key requirement for high-quality PDF document conversion. With the recent availability of public, large ground-truth datasets such as PubLayNet and DocBank, deep-learning models have proven to be very effective at layout detection and segmentation. While these datasets are of adequate size to train such models, they severely lack in layout variability since they are sourced from scientific article repositories such as PubMed and arXiv only. Consequently, the accuracy of the layout segmentation drops significantly when these models are applied on more challenging and diverse layouts. In this paper, we present \textit{DocLayNet}, a new, publicly available, document-layout annotation dataset in COCO format. It contains 80863 manually annotated pages from diverse data sources to represent a wide variability in layouts. For each PDF page, the layout annotations provide labelled bounding-boxes with a choice of 11 distinct classes. DocLayNet also provides a subset of double- and triple-annotated pages to determine the inter-annotator agreement. In multiple experiments, we provide smallline accuracy scores (in mAP) for a set of popular object detection models. We also demonstrate that these models fall approximately 10\% behind the inter-annotator agreement. Furthermore, we provide evidence that DocLayNet is of sufficient size. Lastly, we compare models trained on PubLayNet, DocBank and DocLayNet, showing that layout predictions of the DocLayNet-trained models are more robust and thus the preferred choice for general-purpose document-layout analysis.
46
- """
47
-
48
- _HOMEPAGE = "https://developer.ibm.com/exchanges/data/all/doclaynet/"
49
-
50
- _LICENSE = "https://github.com/DS4SD/DocLayNet/blob/main/LICENSE"
51
-
52
- # The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
53
- # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
54
- # _URLS = {
55
- # "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip",
56
- # "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip",
57
- # }
58
-
59
- # functions
60
- def load_image(image_path):
61
- image = Image.open(image_path).convert("RGB")
62
- w, h = image.size
63
- return image, (w, h)
64
-
65
- logger = datasets.logging.get_logger(__name__)
66
-
67
-
68
- class DocLayNetConfig(datasets.BuilderConfig):
69
- """BuilderConfig for DocLayNet small"""
70
-
71
- def __init__(self, **kwargs):
72
- """BuilderConfig for DocLayNet small.
73
- Args:
74
- **kwargs: keyword arguments forwarded to super.
75
- """
76
- super(DocLayNetConfig, self).__init__(**kwargs)
77
-
78
-
79
- class DocLayNet(datasets.GeneratorSmalldBuilder):
80
- """
81
- DocLayNet small is a about 1% of the dataset DocLayNet (more information at https://huggingface.co/datasets/pierreguillou/DocLayNet-small)
82
- DocLayNet: A Large Human-Annotated Dataset for Document-Layout Analysis
83
- DocLayNet dataset:
84
- - DocLayNet core dataset: https://codait-cos-dax.s3.us.cloud-object-storage.appdomain.cloud/dax-doclaynet/1.0.0/DocLayNet_core.zip
85
- - DocLayNet extra dataset: https://codait-cos-dax.s3.us.cloud-object-storage.appdomain.cloud/dax-doclaynet/1.0.0/DocLayNet_extra.zip
86
- """
87
-
88
- VERSION = datasets.Version("1.1.0")
89
-
90
- # This is an example of a dataset with multiple configurations.
91
- # If you don't want/need to define several sub-sets in your dataset,
92
- # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
93
-
94
- # If you need to make complex sub-parts in the datasets with configurable options
95
- # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
96
- # BUILDER_CONFIG_CLASS = MyBuilderConfig
97
-
98
- # You will be able to load one or the other configurations in the following list with
99
- # data = datasets.load_dataset('my_dataset', 'first_domain')
100
- # data = datasets.load_dataset('my_dataset', 'second_domain')
101
- BUILDER_CONFIGS = [
102
- DocLayNetConfig(name="DocLayNet", version=datasets.Version("1.0.0"), description="DocLayNeT small dataset"),
103
- ]
104
-
105
- #DEFAULT_CONFIG_NAME = "DocLayNet" # It's not mandatory to have a default configuration. Just use one if it make sense.
106
-
107
- def _info(self):
108
-
109
- features = datasets.Features(
110
- {
111
- "id": datasets.Value("string"),
112
- "texts": datasets.Sequence(datasets.Value("string")),
113
- "bboxes_block": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
114
- "bboxes_line": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))),
115
- "categories": datasets.Sequence(
116
- datasets.features.ClassLabel(
117
- names=["Caption", "Footnote", "Formula", "List-item", "Page-footer", "Page-header", "Picture", "Section-header", "Table", "Text", "Title"]
118
- )
119
- ),
120
- "image": datasets.features.Image(),
121
- "pdf": datasets.Value("string"),
122
- "page_hash": datasets.Value("string"), # unique identifier, equal to filename
123
- "original_filename": datasets.Value("string"), # original document filename
124
- "page_no": datasets.Value("int32"), # page number in original document
125
- "num_pages": datasets.Value("int32"), # total pages in original document
126
- "original_width": datasets.Value("int32"), # width in pixels @72 ppi
127
- "original_height": datasets.Value("int32"), # height in pixels @72 ppi
128
- "coco_width": datasets.Value("int32"), # with in pixels in PNG and COCO format
129
- "coco_height": datasets.Value("int32"), # with in pixels in PNG and COCO format
130
- "collection": datasets.Value("string"), # sub-collection name
131
- "doc_category": datasets.Value("string"), # category type of the document
132
-
133
- }
134
- )
135
-
136
- return datasets.DatasetInfo(
137
- # This is the description that will appear on the datasets page.
138
- description=_DESCRIPTION,
139
- # This defines the different columns of the dataset and their types
140
- features=features, # Here we define them above because they are different between the two configurations
141
- # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
142
- # specify them. They'll be used if as_supervised=True in builder.as_dataset.
143
- # supervised_keys=("sentence", "label"),
144
- # Homepage of the dataset for documentation
145
- homepage=_HOMEPAGE,
146
- # License for the dataset if available
147
- license=_LICENSE,
148
- # Citation for the dataset
149
- citation=_CITATION,
150
- )
151
-
152
- def _split_generators(self, dl_manager):
153
- # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
154
- # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
155
-
156
- # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
157
- # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
158
- # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
159
-
160
- downloaded_file = dl_manager.download_and_extract("https://huggingface.co/datasets/pierreguillou/DocLayNet-small/resolve/main/data/dataset_small.zip")
161
- return [
162
- datasets.SplitGenerator(
163
- name=datasets.Split.TRAIN,
164
- # These kwargs will be passed to _generate_examples
165
- gen_kwargs={
166
- "filepath": f"{downloaded_file}/dataset_small/train/",
167
- "split": "train",
168
- },
169
- ),
170
- datasets.SplitGenerator(
171
- name=datasets.Split.VALIDATION,
172
- # These kwargs will be passed to _generate_examples
173
- gen_kwargs={
174
- "filepath": f"{downloaded_file}/dataset_small/val/",
175
- "split": "dev",
176
- },
177
- ),
178
- datasets.SplitGenerator(
179
- name=datasets.Split.TEST,
180
- # These kwargs will be passed to _generate_examples
181
- gen_kwargs={
182
- "filepath": f"{downloaded_file}/dataset_small/test/",
183
- "split": "test"
184
- },
185
- ),
186
- ]
187
-
188
- def _generate_examples(self, filepath, split):
189
- logger.info("⏳ Generating examples from = %s", filepath)
190
- ann_dir = os.path.join(filepath, "annotations")
191
- img_dir = os.path.join(filepath, "images")
192
- pdf_dir = os.path.join(filepath, "pdfs")
193
- for guid, file in enumerate(sorted(os.listdir(ann_dir))):
194
- texts = []
195
- bboxes_block = []
196
- bboxes_line = []
197
- categories = []
198
- # get json
199
- file_path = os.path.join(ann_dir, file)
200
- with open(file_path, "r", encoding="utf8") as f:
201
- data = json.load(f)
202
- # get image
203
- image_path = os.path.join(img_dir, file)
204
- image_path = image_path.replace("json", "png")
205
- image, size = load_image(image_path)
206
- # get pdf
207
- pdf_path = os.path.join(pdf_dir, file)
208
- pdf_path = pdf_path.replace("json", "pdf")
209
- with open(pdf_path, "rb") as pdf_file:
210
- pdf_bytes = pdf_file.read()
211
- pdf_encoded_string = small64.b64encode(pdf_bytes)
212
- # get all data
213
-
214
- for item in data["metadata"]:
215
- page_hash = item["page_hash"]
216
- original_filename = item["original_filename"]
217
- page_no = item["page_no"]
218
- num_pages = item["num_pages"]
219
- original_width = item["original_width"]
220
- original_height = item["original_height"]
221
- coco_width = item["coco_width"]
222
- coco_height = item["coco_height"]
223
- collection = item["collection"]
224
- doc_category = item["doc_category"]
225
-
226
- for item in data["form"]:
227
- text_example, category_example, bbox_block_example, bbox_line_example = item["text"], item["category"], item["box"], item["box_line"]
228
- texts.append(text_example)
229
- categories.append(category_example)
230
- bboxes_block.append(bbox_block_example)
231
- bboxes_line.append(bbox_line_example)
232
-
233
- yield guid, {"id": str(guid), "texts": texts, "bboxes_block": bboxes_block, "bboxes_line": bboxes_line, "categories": categories, "image": image, "pdf": pdf_encoded_string, "page_hash": page_hash, "original_filename": original_filename, "page_no": page_no, "num_pages": num_pages, "original_width": original_width, "original_height": original_height, "coco_width": coco_width, "coco_height": coco_height, "collection": collection, "doc_category": doc_category}