shunk031 commited on
Commit
8347ae6
1 Parent(s): 8ad7ef1

Initialize (#1)

Browse files

* add files

* update types

* update

* update README.md

* update test

* add settings for CI

* update script

.github/workflows/ci.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+ paths-ignore:
9
+ - "README.md"
10
+
11
+ jobs:
12
+ test:
13
+ runs-on: ubuntu-latest
14
+ strategy:
15
+ matrix:
16
+ python-version: ["3.9", "3.10"]
17
+
18
+ steps:
19
+ - uses: actions/checkout@v3
20
+
21
+ - name: Set up Python ${{ matrix.python-version }}
22
+ uses: actions/setup-python@v4
23
+ with:
24
+ python-version: ${{ matrix.python-version }}
25
+
26
+ - name: Install dependencies
27
+ run: |
28
+ pip install -U pip setuptools wheel poetry
29
+ poetry install
30
+
31
+ - name: Format
32
+ run: |
33
+ poetry run black --check .
34
+
35
+ - name: Lint
36
+ run: |
37
+ poetry run ruff .
38
+
39
+ - name: Type check
40
+ run: |
41
+ poetry run mypy . \
42
+ --ignore-missing-imports \
43
+ --no-strict-optional \
44
+ --no-site-packages \
45
+ --cache-dir=/dev/null
46
+
47
+ - name: Run tests
48
+ run: |
49
+ poetry run pytest --color=yes -rf
.github/workflows/push_to_hub.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face Hub
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows:
6
+ - CI
7
+ branches:
8
+ - main
9
+ types:
10
+ - completed
11
+
12
+ jobs:
13
+ push_to_hub:
14
+ runs-on: ubuntu-latest
15
+
16
+ steps:
17
+ - name: Checkout repository
18
+ uses: actions/checkout@v3
19
+
20
+ - name: Push to Huggingface hub
21
+ env:
22
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
23
+ HF_USERNAME: ${{ secrets.HF_USERNAME }}
24
+ run: |
25
+ git fetch --unshallow
26
+ git push --force https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/datasets/${HF_USERNAME}/PubLayNet main
.gitignore ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ # End of https://www.toptal.com/developers/gitignore/api/python
PubLayNet.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import pathlib
3
+ from collections import defaultdict
4
+ from dataclasses import asdict, dataclass
5
+ from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union
6
+
7
+ import datasets as ds
8
+ import numpy as np
9
+ from datasets.utils.logging import get_logger
10
+ from PIL import Image
11
+ from PIL.Image import Image as PilImage
12
+ from pycocotools import mask as cocomask
13
+ from tqdm.auto import tqdm
14
+
15
+ logger = get_logger(__name__)
16
+
17
+ JsonDict = Dict[str, Any]
18
+ ImageId = int
19
+ AnnotationId = int
20
+ LicenseId = int
21
+ CategoryId = int
22
+ Bbox = Tuple[float, float, float, float]
23
+
24
+ _DESCRIPTION = """\
25
+ PubLayNet is a dataset for document layout analysis. It contains images of research papers and articles and annotations for various elements in a page such as "text", "list", "figure" etc in these research paper images. The dataset was obtained by automatically matching the XML representations and the content of over 1 million PDF articles that are publicly available on PubMed Central.
26
+ """
27
+
28
+ _CITATION = """\
29
+ @inproceedings{zhong2019publaynet,
30
+ title={Publaynet: largest dataset ever for document layout analysis},
31
+ author={Zhong, Xu and Tang, Jianbin and Yepes, Antonio Jimeno},
32
+ booktitle={2019 International Conference on Document Analysis and Recognition (ICDAR)},
33
+ pages={1015--1022},
34
+ year={2019},
35
+ organization={IEEE}
36
+ }
37
+ """
38
+
39
+ _HOMEPAGE = "https://developer.ibm.com/exchanges/data/all/publaynet/"
40
+
41
+ _LICENSE = "CDLA-Permissive"
42
+
43
+ _URL = "https://dax-cdn.cdn.appdomain.cloud/dax-publaynet/1.0.0/publaynet.tar.gz"
44
+
45
+
46
+ class UncompressedRLE(TypedDict):
47
+ counts: List[int]
48
+ size: Tuple[int, int]
49
+
50
+
51
+ class CompressedRLE(TypedDict):
52
+ counts: bytes
53
+ size: Tuple[int, int]
54
+
55
+
56
+ @dataclass
57
+ class CategoryData(object):
58
+ category_id: int
59
+ name: str
60
+ supercategory: str
61
+
62
+ @classmethod
63
+ def from_dict(cls, json_dict: JsonDict) -> "CategoryData":
64
+ return cls(
65
+ category_id=json_dict["id"],
66
+ name=json_dict["name"],
67
+ supercategory=json_dict["supercategory"],
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class ImageData(object):
73
+ image_id: ImageId
74
+ file_name: str
75
+ width: int
76
+ height: int
77
+
78
+ @classmethod
79
+ def from_dict(cls, json_dict: JsonDict) -> "ImageData":
80
+ return cls(
81
+ image_id=json_dict["id"],
82
+ file_name=json_dict["file_name"],
83
+ width=json_dict["width"],
84
+ height=json_dict["height"],
85
+ )
86
+
87
+ @property
88
+ def shape(self) -> Tuple[int, int]:
89
+ return (self.height, self.width)
90
+
91
+
92
+ @dataclass
93
+ class AnnotationData(object):
94
+ annotation_id: AnnotationId
95
+ image_id: ImageId
96
+ segmentation: Union[np.ndarray, CompressedRLE]
97
+ area: float
98
+ iscrowd: bool
99
+ bbox: Bbox
100
+ category_id: int
101
+
102
+ @classmethod
103
+ def compress_rle(
104
+ cls,
105
+ segmentation: Union[List[List[float]], UncompressedRLE],
106
+ iscrowd: bool,
107
+ height: int,
108
+ width: int,
109
+ ) -> CompressedRLE:
110
+ if iscrowd:
111
+ rle = cocomask.frPyObjects(segmentation, h=height, w=width)
112
+ else:
113
+ rles = cocomask.frPyObjects(segmentation, h=height, w=width)
114
+ rle = cocomask.merge(rles) # type: ignore
115
+
116
+ return rle # type: ignore
117
+
118
+ @classmethod
119
+ def rle_segmentation_to_binary_mask(
120
+ cls, segmentation, iscrowd: bool, height: int, width: int
121
+ ) -> np.ndarray:
122
+ rle = cls.compress_rle(
123
+ segmentation=segmentation, iscrowd=iscrowd, height=height, width=width
124
+ )
125
+ return cocomask.decode(rle) # type: ignore
126
+
127
+ @classmethod
128
+ def rle_segmentation_to_mask(
129
+ cls,
130
+ segmentation: Union[List[List[float]], UncompressedRLE],
131
+ iscrowd: bool,
132
+ height: int,
133
+ width: int,
134
+ ) -> np.ndarray:
135
+ binary_mask = cls.rle_segmentation_to_binary_mask(
136
+ segmentation=segmentation, iscrowd=iscrowd, height=height, width=width
137
+ )
138
+ return binary_mask * 255
139
+
140
+ @classmethod
141
+ def from_dict(
142
+ cls,
143
+ json_dict: JsonDict,
144
+ images: Dict[ImageId, ImageData],
145
+ decode_rle: bool,
146
+ ) -> "AnnotationData":
147
+ segmentation = json_dict["segmentation"]
148
+ image_id = json_dict["image_id"]
149
+ image_data = images[image_id]
150
+ iscrowd = bool(json_dict["iscrowd"])
151
+
152
+ segmentation_mask = (
153
+ cls.rle_segmentation_to_mask(
154
+ segmentation=segmentation,
155
+ iscrowd=iscrowd,
156
+ height=image_data.height,
157
+ width=image_data.width,
158
+ )
159
+ if decode_rle
160
+ else cls.compress_rle(
161
+ segmentation=segmentation,
162
+ iscrowd=iscrowd,
163
+ height=image_data.height,
164
+ width=image_data.width,
165
+ )
166
+ )
167
+ return cls(
168
+ annotation_id=json_dict["id"],
169
+ image_id=image_id,
170
+ segmentation=segmentation_mask, # type: ignore
171
+ area=json_dict["area"],
172
+ iscrowd=iscrowd,
173
+ bbox=json_dict["bbox"],
174
+ category_id=json_dict["category_id"],
175
+ )
176
+
177
+
178
+ def load_json(json_path: pathlib.Path) -> JsonDict:
179
+ logger.info(f"Load from {json_path}")
180
+ with json_path.open("r") as rf:
181
+ json_dict = json.load(rf)
182
+ return json_dict
183
+
184
+
185
+ def load_image(image_path: pathlib.Path) -> PilImage:
186
+ return Image.open(image_path)
187
+
188
+
189
+ def load_categories_data(
190
+ category_dicts: List[JsonDict],
191
+ tqdm_desc: str = "Load categories",
192
+ ) -> Dict[CategoryId, CategoryData]:
193
+ categories = {}
194
+ for category_dict in tqdm(category_dicts, desc=tqdm_desc):
195
+ category_data = CategoryData.from_dict(category_dict)
196
+ categories[category_data.category_id] = category_data
197
+ return categories
198
+
199
+
200
+ def load_images_data(
201
+ image_dicts: List[JsonDict],
202
+ tqdm_desc="Load images",
203
+ ) -> Dict[ImageId, ImageData]:
204
+ images = {}
205
+ for image_dict in tqdm(image_dicts, desc=tqdm_desc):
206
+ image_data = ImageData.from_dict(image_dict)
207
+ images[image_data.image_id] = image_data
208
+ return images
209
+
210
+
211
+ def load_annotation_data(
212
+ label_dicts: List[JsonDict],
213
+ images: Dict[ImageId, ImageData],
214
+ decode_rle: bool,
215
+ tqdm_desc: str = "Load label data",
216
+ ) -> Dict[ImageId, List[AnnotationData]]:
217
+ labels = defaultdict(list)
218
+ label_dicts = sorted(label_dicts, key=lambda d: d["image_id"])
219
+
220
+ for label_dict in tqdm(label_dicts, desc=tqdm_desc):
221
+ label_data = AnnotationData.from_dict(
222
+ label_dict, images=images, decode_rle=decode_rle
223
+ )
224
+ labels[label_data.image_id].append(label_data)
225
+ return labels
226
+
227
+
228
+ def generate_train_val_examples(
229
+ annotations: Dict[ImageId, List[AnnotationData]],
230
+ image_dir: pathlib.Path,
231
+ images: Dict[ImageId, ImageData],
232
+ categories: Dict[CategoryId, CategoryData],
233
+ ):
234
+ for idx, image_id in enumerate(images.keys()):
235
+ image_data = images[image_id]
236
+ image_anns = annotations[image_id]
237
+
238
+ if len(image_anns) < 1:
239
+ logger.warning(f"No annotation found for image id: {image_id}.")
240
+ continue
241
+
242
+ image = load_image(image_path=image_dir / image_data.file_name)
243
+ example = asdict(image_data)
244
+ example["image"] = image
245
+
246
+ example["annotations"] = []
247
+ for ann in image_anns:
248
+ ann_dict = asdict(ann)
249
+ category = categories[ann.category_id]
250
+ ann_dict["category"] = asdict(category)
251
+ example["annotations"].append(ann_dict)
252
+
253
+ yield idx, example
254
+
255
+
256
+ def generate_test_examples(image_dir: pathlib.Path):
257
+ image_paths = [f for f in image_dir.iterdir() if f.suffix == ".jpg"]
258
+ image_paths = sorted(image_paths)
259
+
260
+ for idx, image_path in enumerate(image_paths):
261
+ image = load_image(image_path=image_path)
262
+ image_width, image_height = image.size
263
+ image_data = ImageData(
264
+ image_id=idx,
265
+ file_name=image_path.name,
266
+ width=image_width,
267
+ height=image_height,
268
+ )
269
+ example = asdict(image_data)
270
+ example["image"] = image
271
+ example["annotations"] = []
272
+ yield idx, example
273
+
274
+
275
+ @dataclass
276
+ class PubLayNetConfig(ds.BuilderConfig):
277
+ decode_rle: bool = False
278
+
279
+
280
+ class PubLayNetDataset(ds.GeneratorBasedBuilder):
281
+ VERSION = ds.Version("1.0.0")
282
+ BUILDER_CONFIG_CLASS = PubLayNetConfig
283
+ BUILDER_CONFIGS = [
284
+ PubLayNetConfig(
285
+ version=VERSION,
286
+ description="PubLayNet is a dataset for document layout analysis.",
287
+ )
288
+ ]
289
+
290
+ def _info(self) -> ds.DatasetInfo:
291
+ segmentation_feature = (
292
+ ds.Image()
293
+ if self.config.decode_rle
294
+ else {
295
+ "counts": ds.Value("binary"),
296
+ "size": ds.Sequence(ds.Value("int32")),
297
+ }
298
+ )
299
+ features = ds.Features(
300
+ {
301
+ "image_id": ds.Value("int32"),
302
+ "file_name": ds.Value("string"),
303
+ "width": ds.Value("int32"),
304
+ "height": ds.Value("int32"),
305
+ "image": ds.Image(),
306
+ "annotations": ds.Sequence(
307
+ {
308
+ "annotation_id": ds.Value("int32"),
309
+ "area": ds.Value("float32"),
310
+ "bbox": ds.Sequence(ds.Value("float32"), length=4),
311
+ "category": {
312
+ "category_id": ds.Value("int32"),
313
+ "name": ds.ClassLabel(
314
+ num_classes=5,
315
+ names=["text", "title", "list", "table", "figure"],
316
+ ),
317
+ "supercategory": ds.Value("string"),
318
+ },
319
+ "category_id": ds.Value("int32"),
320
+ "image_id": ds.Value("int32"),
321
+ "iscrowd": ds.Value("bool"),
322
+ "segmentation": segmentation_feature,
323
+ }
324
+ ),
325
+ }
326
+ )
327
+ return ds.DatasetInfo(
328
+ description=_DESCRIPTION,
329
+ citation=_CITATION,
330
+ homepage=_HOMEPAGE,
331
+ license=_LICENSE,
332
+ features=features,
333
+ )
334
+
335
+ def _split_generators(self, dl_manager: ds.DownloadManager):
336
+ base_dir = dl_manager.download_and_extract(_URL)
337
+ publaynet_dir = pathlib.Path(base_dir) / "publaynet"
338
+
339
+ return [
340
+ ds.SplitGenerator(
341
+ name=ds.Split.TRAIN,
342
+ gen_kwargs={
343
+ "image_dir": publaynet_dir / "train",
344
+ "label_path": publaynet_dir / "train.json",
345
+ },
346
+ ),
347
+ ds.SplitGenerator(
348
+ name=ds.Split.VALIDATION,
349
+ gen_kwargs={
350
+ "image_dir": publaynet_dir / "val",
351
+ "label_path": publaynet_dir / "val.json",
352
+ },
353
+ ),
354
+ ds.SplitGenerator(
355
+ name=ds.Split.TEST,
356
+ gen_kwargs={
357
+ "image_dir": publaynet_dir / "test",
358
+ },
359
+ ),
360
+ ]
361
+
362
+ def _generate_train_val_examples(
363
+ self, image_dir: pathlib.Path, label_path: pathlib.Path
364
+ ):
365
+ label_json = load_json(json_path=label_path)
366
+
367
+ images = load_images_data(image_dicts=label_json["images"])
368
+ categories = load_categories_data(category_dicts=label_json["categories"])
369
+
370
+ annotations = load_annotation_data(
371
+ label_dicts=label_json["annotations"],
372
+ images=images,
373
+ decode_rle=self.config.decode_rle,
374
+ )
375
+ yield from generate_train_val_examples(
376
+ annotations=annotations,
377
+ image_dir=image_dir,
378
+ images=images,
379
+ categories=categories,
380
+ )
381
+
382
+ def _generate_test_examples(self, image_dir: pathlib.Path):
383
+ yield from generate_test_examples(image_dir=image_dir)
384
+
385
+ def _generate_examples(
386
+ self, image_dir: pathlib.Path, label_path: Optional[pathlib.Path] = None
387
+ ):
388
+ if label_path is not None:
389
+ yield from self._generate_train_val_examples(
390
+ image_dir=image_dir,
391
+ label_path=label_path,
392
+ )
393
+ else:
394
+ yield from self._generate_test_examples(
395
+ image_dir=image_dir,
396
+ )
README.md ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ annotations_creators:
3
+ - machine-generated
4
+ language:
5
+ - en
6
+ language_creators:
7
+ - found
8
+ license:
9
+ - cdla-permissive
10
+ multilinguality:
11
+ - monolingual
12
+ pretty_name: PubLayNet
13
+ size_categories: []
14
+ source_datasets:
15
+ - original
16
+ tags:
17
+ - graphic design
18
+ - layout-generation
19
+ task_categories:
20
+ - image-classification
21
+ - image-segmentation
22
+ - image-to-text
23
+ - question-answering
24
+ - other
25
+ - multiple-choice
26
+ - token-classification
27
+ - tabular-to-text
28
+ - object-detection
29
+ - table-question-answering
30
+ - text-classification
31
+ - table-to-text
32
+ task_ids:
33
+ - multi-label-image-classification
34
+ - multi-class-image-classification
35
+ - semantic-segmentation
36
+ - image-captioning
37
+ - extractive-qa
38
+ - closed-domain-qa
39
+ - multiple-choice-qa
40
+ - named-entity-recognition
41
+ ---
42
+
43
+ # Dataset Card for PubLayNet
44
+
45
+ ## Table of Contents
46
+ - [Dataset Card Creation Guide](#dataset-card-creation-guide)
47
+ - [Table of Contents](#table-of-contents)
48
+ - [Dataset Description](#dataset-description)
49
+ - [Dataset Summary](#dataset-summary)
50
+ - [Supported Tasks and Leaderboards](#supported-tasks-and-leaderboards)
51
+ - [Languages](#languages)
52
+ - [Dataset Structure](#dataset-structure)
53
+ - [Data Instances](#data-instances)
54
+ - [Data Fields](#data-fields)
55
+ - [Data Splits](#data-splits)
56
+ - [Dataset Creation](#dataset-creation)
57
+ - [Curation Rationale](#curation-rationale)
58
+ - [Source Data](#source-data)
59
+ - [Initial Data Collection and Normalization](#initial-data-collection-and-normalization)
60
+ - [Who are the source language producers?](#who-are-the-source-language-producers)
61
+ - [Annotations](#annotations)
62
+ - [Annotation process](#annotation-process)
63
+ - [Who are the annotators?](#who-are-the-annotators)
64
+ - [Personal and Sensitive Information](#personal-and-sensitive-information)
65
+ - [Considerations for Using the Data](#considerations-for-using-the-data)
66
+ - [Social Impact of Dataset](#social-impact-of-dataset)
67
+ - [Discussion of Biases](#discussion-of-biases)
68
+ - [Other Known Limitations](#other-known-limitations)
69
+ - [Additional Information](#additional-information)
70
+ - [Dataset Curators](#dataset-curators)
71
+ - [Licensing Information](#licensing-information)
72
+ - [Citation Information](#citation-information)
73
+ - [Contributions](#contributions)
74
+
75
+ ## Dataset Description
76
+
77
+ - **Homepage:** https://developer.ibm.com/exchanges/data/all/publaynet/
78
+ - **Repository:** https://github.com/shunk031/huggingface-datasets_PubLayNet
79
+ - **Paper (Preprint):** https://arxiv.org/abs/1908.07836
80
+ - **Paper (ICDAR2019):** https://ieeexplore.ieee.org/document/8977963
81
+
82
+ ### Dataset Summary
83
+
84
+ PubLayNet is a dataset for document layout analysis. It contains images of research papers and articles and annotations for various elements in a page such as "text", "list", "figure" etc in these research paper images. The dataset was obtained by automatically matching the XML representations and the content of over 1 million PDF articles that are publicly available on PubMed Central.
85
+
86
+ ### Supported Tasks and Leaderboards
87
+
88
+ [More Information Needed]
89
+
90
+ ### Languages
91
+
92
+ [More Information Needed]
93
+
94
+ ## Dataset Structure
95
+
96
+ ### Data Instances
97
+
98
+ ```python
99
+ import datasets as ds
100
+
101
+ dataset = ds.load_dataset(
102
+ path="shunk031/PubLayNet",
103
+ decode_rle=True, # True if Run-length Encoding (RLE) is to be decoded and converted to binary mask.
104
+ )
105
+ ```
106
+
107
+ ### Data Fields
108
+
109
+ [More Information Needed]
110
+
111
+ ### Data Splits
112
+
113
+ [More Information Needed]
114
+
115
+ ## Dataset Creation
116
+
117
+ ### Curation Rationale
118
+
119
+ [More Information Needed]
120
+
121
+ ### Source Data
122
+
123
+ [More Information Needed]
124
+
125
+ #### Initial Data Collection and Normalization
126
+
127
+ [More Information Needed]
128
+
129
+ #### Who are the source language producers?
130
+
131
+ [More Information Needed]
132
+
133
+ ### Annotations
134
+
135
+ [More Information Needed]
136
+
137
+ #### Annotation process
138
+
139
+ [More Information Needed]
140
+
141
+ #### Who are the annotators?
142
+
143
+ [More Information Needed]
144
+
145
+ ### Personal and Sensitive Information
146
+
147
+ [More Information Needed]
148
+
149
+ ## Considerations for Using the Data
150
+
151
+ ### Social Impact of Dataset
152
+
153
+ [More Information Needed]
154
+
155
+ ### Discussion of Biases
156
+
157
+ [More Information Needed]
158
+
159
+ ### Other Known Limitations
160
+
161
+ [More Information Needed]
162
+
163
+ ## Additional Information
164
+
165
+ ### Dataset Curators
166
+
167
+ [More Information Needed]
168
+
169
+ ### Licensing Information
170
+
171
+ - [CDLA-Permissive](https://cdla.io/permissive-1-0/)
172
+
173
+ ### Citation Information
174
+
175
+
176
+ ```bibtex
177
+ @inproceedings{zhong2019publaynet,
178
+ title={Publaynet: largest dataset ever for document layout analysis},
179
+ author={Zhong, Xu and Tang, Jianbin and Yepes, Antonio Jimeno},
180
+ booktitle={2019 International Conference on Document Analysis and Recognition (ICDAR)},
181
+ pages={1015--1022},
182
+ year={2019},
183
+ organization={IEEE}
184
+ }
185
+ ```
186
+
187
+ ### Contributions
188
+
189
+ Thanks to [ibm-aur-nlp/PubLayNet](https://github.com/ibm-aur-nlp/PubLayNet) for creating this dataset.
poetry.lock ADDED
The diff for this file is too large to render. See raw diff
 
pyproject.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "huggingface-datasets-publaynet"
3
+ version = "0.1.0"
4
+ description = ""
5
+ authors = ["Shunsuke KITADA <[email protected]>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "^3.9"
10
+ datasets = { extras = ["vision"], version = "^2.14.6" }
11
+ pycocotools = "^2.0.7"
12
+
13
+ [tool.poetry.group.dev.dependencies]
14
+ ruff = "^0.1.1"
15
+ black = "^23.10.1"
16
+ mypy = "^1.6.1"
17
+ pytest = "^7.4.2"
18
+ types-pillow = "^10.1.0.0"
19
+ types-pycocotools = "^2.0.0.4"
20
+ types-tqdm = "^4.66.0.4"
21
+
22
+ [build-system]
23
+ requires = ["poetry-core"]
24
+ build-backend = "poetry.core.masonry.api"
tests/PubLayNet_test.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import datasets as ds
4
+ import pytest
5
+
6
+
7
+ @pytest.fixture
8
+ def dataset_path() -> str:
9
+ return "PubLayNet.py"
10
+
11
+
12
+ @pytest.mark.skipif(
13
+ condition=bool(os.environ.get("CI", False)),
14
+ reason=(
15
+ "Because this loading script downloads a large dataset, "
16
+ "we will skip running it on CI."
17
+ ),
18
+ )
19
+ @pytest.mark.parametrize(
20
+ argnames=("decode_rle"),
21
+ argvalues=(False, True),
22
+ )
23
+ @pytest.mark.parametrize(
24
+ argnames=("expected_num_train", "expected_num_valid", "expected_num_test"),
25
+ argvalues=((335703, 11245, 11405),),
26
+ )
27
+ def test_load_dataset(
28
+ dataset_path: str,
29
+ decode_rle: bool,
30
+ expected_num_train: int,
31
+ expected_num_valid: int,
32
+ expected_num_test: int,
33
+ ):
34
+ dataset = ds.load_dataset(path=dataset_path, decode_rle=decode_rle)
35
+ assert dataset["train"].num_rows == expected_num_train
36
+ assert dataset["validation"].num_rows == expected_num_valid
37
+ assert dataset["test"].num_rows == expected_num_test
tests/__init__.py ADDED
File without changes