File size: 7,523 Bytes
e9aab75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce17d5
 
 
 
 
 
 
 
 
 
 
 
 
 
49d665a
e9aab75
 
 
1ce17d5
 
e9aab75
 
 
 
 
 
 
 
 
f82197a
f22f65b
 
 
e9aab75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ce17d5
 
 
e9aab75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f22f65b
e9aab75
 
 
 
 
 
 
 
 
 
 
 
f82197a
e9aab75
f82197a
 
e9aab75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee65240
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# Copyright 2022 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 (Ryerson Vision Lab Complex Document Information Processing) dataset"""


import os
import numpy as np
from tqdm import tqdm
import datasets


_CITATION = """\
@inproceedings{harley2015icdar,
    title = {Evaluation of Deep Convolutional Nets for Document Image Classification and Retrieval},
    author = {Adam W Harley and Alex Ufkes and Konstantinos G Derpanis},
    booktitle = {International Conference on Document Analysis and Recognition ({ICDAR})}},
    year = {2015}
}
"""


_DESCRIPTION = """\
The RVL-CDIP (Ryerson Vision Lab Complex Document Information Processing) dataset consists of 400,000 grayscale images in 16 classes, with 25,000 images per class. There are 320,000 training images, 40,000 validation images, and 40,000 test images.
"""


_HOMEPAGE = "https://www.cs.cmu.edu/~aharley/rvl-cdip/"


_LICENSE = "https://www.industrydocuments.ucsf.edu/help/copyright/"


_URLS = {
    "rvl-cdip": "https://huggingface.co/datasets/rvl_cdip/resolve/main/data/rvl-cdip.tar.gz",
}

_METADATA_URLS = {
    "train": "https://huggingface.co/datasets/rvl_cdip/resolve/main/data/train.txt",
    "test": "https://huggingface.co/datasets/rvl_cdip/resolve/main/data/test.txt",
    "val": "https://huggingface.co/datasets/rvl_cdip/resolve/main/data/val.txt",
}

_CLASSES = [
    "letter",
    "form",
    "email",
    "handwritten",
    "advertisement",
    "scientific report",
    "scientific publication",
    "specification",
    "file folder",
    "news article",
    "budget",
    "invoice",
    "presentation",
    "questionnaire",
    "resume",
    "memo",
]

_IMAGES_DIR = "images/"


class OCRConfig(datasets.BuilderConfig):
    """BuilderConfig for RedCaps."""

    def __init__(self, name, **kwargs):
        """BuilderConfig for RedCaps.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        assert "description" not in kwargs
        super(OCRConfig, self).__init__(
            version=datasets.Version("1.0.0", ""), name=name, **kwargs
        )


class RvlCdip_EasyOcr(datasets.GeneratorBasedBuilder):
    """Ryerson Vision Lab Complex Document Information Processing dataset."""

    VERSION = datasets.Version("1.0.0")
    BUILDER_CONFIGS = [OCRConfig("default")]
    DEFAULT_CONFIG_NAME = "default"

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "image": datasets.Image(),
                    "label": datasets.ClassLabel(names=_CLASSES),
                    "words": datasets.Sequence(datasets.Value("string")),
                    "boxes": datasets.Sequence(
                        datasets.Sequence(datasets.Value("int32"))
                    ),
                }
            ),
            homepage=_HOMEPAGE,
            citation=_CITATION,
            license=_LICENSE,
        )

    def _split_generators(self, dl_manager):
        if self.config.data_files:
            archive_path = self.config.data_files["binary"][0]
        else:
            archive_path = dl_manager.download(
                _URLS["rvl-cdip"]
            )  # only download images if need be
        labels_path = dl_manager.download(_METADATA_URLS)
        from pdb import set_trace

        set_trace()
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "archive_iterator": dl_manager.iter_archive(archive_path),
                    "labels_filepath": labels_path["train"],
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "archive_iterator": dl_manager.iter_archive(archive_path),
                    "labels_filepath": labels_path["test"],
                    "split": "test",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "archive_iterator": dl_manager.iter_archive(archive_path),
                    "labels_filepath": labels_path["val"],
                    "split": "validation",
                },
            ),
        ]

    @staticmethod
    def _get_image_to_class_map(data):
        image_to_class_id = {}
        for item in data:
            image_path, class_id = item.split(" ")
            image_path = os.path.join(_IMAGES_DIR, image_path)
            image_to_class_id[image_path] = int(class_id)

        return image_to_class_id

    @staticmethod
    def _get_image_to_OCR(OCR_dir, split):
        def parse_easyOCR_box(box):
            # {'x0': 39, 'y0': 39, 'x1': 498, 'y1': 82, 'width': 459, 'height': 43}
            return (box["x0"], box["y0"], box["x1"], box["y1"])

        if OCR_dir is None:
            return {}
        image_to_OCR = {}
        data = np.load(
            os.path.join(OCR_dir, f"Easy_{split[0].upper()+split[1:]}_Data.npy"),
            allow_pickle=True,
        )
        for ex in tqdm(data, desc="Loading OCR data"):
            w, h = ex["images"][0]["image_width"], ex["images"][0]["image_height"]
            filename = ex["images"][0]["file_name"]
            words = ex["word-level annotations"][0]["ocred_text"]
            box_info = ex["word-level annotations"][0]["ocred_boxes"]
            boxes = [parse_easyOCR_box(box) for box in box_info]
            assert len(boxes) == len(words)
            image_to_OCR[filename] = (words, boxes)
        return image_to_OCR

    @staticmethod
    def _path_to_OCR(image_to_OCR, file_path):
        # obtain text and boxes given file_path
        words, boxes = None, None
        if file_path in image_to_OCR:
            words, boxes = image_to_OCR[file_path]
        return words, boxes

    def _generate_examples(self, archive_iterator, labels_filepath, split):
        with open(labels_filepath, encoding="utf-8") as f:
            data = f.read().splitlines()

        image_to_OCR = self._get_image_to_OCR(self.config.data_dir, split)
        image_to_class_id = self._get_image_to_class_map(data)

        for file_path, file_obj in archive_iterator:
            if file_path.startswith(_IMAGES_DIR):
                if file_path in image_to_class_id:
                    class_id = image_to_class_id[file_path]
                    label = _CLASSES[class_id]
                    words, boxes = self._path_to_OCR(image_to_OCR, file_path)
                    a = dict(
                        id=file_path,
                        image={"path": file_path, "bytes": file_obj.read()},
                        label=label,
                        words=words,
                        boxes=boxes,
                    )
                    yield file_path, a