File size: 8,988 Bytes
db2aec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
218
219
220
221
222
# 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.
"""SynthTiger synthetic OCR dataset in huggingface format.

https://github.com/clovaai/synthtiger
https://drive.google.com/drive/folders/1faHxo6gVeUmmFKJf8dxFZf_yRjamUL96
synthtiger_v1.1.zip (38G) (md5: b2757a7e2b5040b14ed64c473533b592)

Unpacked dataset structure:
```
gt.txt
images/
    0/
        0.jpg
        1.jpg
        ...
        9998.jpg
        9999.jpg
    1/
    ...
    998/
        ...
    999/
        9990000.jpg
        9990001.jpg
        ...
        9999998.jpg
        9999999.jpg
```

gt.txt format (tab delimited):
```
images/0/0.jpg	10
images/0/1.jpg	date:
...
images/999/9999998.jpg	STUFFIER
images/999/9999999.jpg	Re:
```"""
import os
import shutil

from PIL import Image

import datasets


_CITATION = """\
@inproceedings{yim2021synthtiger,
  title={Synthtiger: Synthetic text image generator towards better text recognition models},
  author={Yim, Moonbin and Kim, Yoonsik and Cho, Han-Cheol and Park, Sungrae},
  booktitle={International Conference on Document Analysis and Recognition},
  pages={109--124},
  year={2021},
  organization={Springer}
}
"""

_DESCRIPTION = """\
A synthetic scene text OCR dataset derived from the
[SynthTIGER](https://github.com/clovaai/synthtiger) generator.
"""

_HOMEPAGE = "https://github.com/clovaai/synthtiger"

_LICENSE = """\
SynthTIGER
Copyright (c) 2021-present NAVER Corp.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

_FOLDER_URL = "https://drive.google.com/drive/folders/18wjIad7_R9AXqXlQ4bhgOxMZY_8XRCdh?usp=sharing"
_PART_URLS = {
    "synthtiger_v1.1.zip.00": "https://drive.google.com/file/d/1ELxTy95sAFQ1ZD81QqS_dbMBnqi6N7aR/view?usp=sharing",
    "synthtiger_v1.1.zip.01": "https://drive.google.com/file/d/1mf9rNBlAVC_xMRUkXmjJSyIBhVgPstPR/view?usp=sharing",
    "synthtiger_v1.1.zip.02": "https://drive.google.com/file/d/1AN0d96JaCZRq37UP3ZHTnEjl-1YwXajR/view?usp=sharing",
    "synthtiger_v1.1.zip.03": "https://drive.google.com/file/d/1WCj-S7GXDlRpLEcHRdnIyjVZTcoY1zJU/view?usp=sharing",
    "synthtiger_v1.1.zip.04": "https://drive.google.com/file/d/1iWOh-dUUSTDOD9jYbSSe5Iq1qiDyYtOg/view?usp=sharing",
    "synthtiger_v1.1.zip.05": "https://drive.google.com/file/d/1QtEoZpNsTCUtq4DuZ5IwdJpuFpeNJCXK/view?usp=sharing",
    "synthtiger_v1.1.zip.06": "https://drive.google.com/file/d/1lTlRRxqkhkgA3CMJ5cSz2-6n_F07KnJ-/view?usp=sharing",
    "synthtiger_v1.1.zip.07": "https://drive.google.com/file/d/1iERfjCHzX9_i-WchYazaK9mF6--41r6b/view?usp=sharing",
    "synthtiger_v1.1.zip.08": "https://drive.google.com/file/d/1pxhGbTP3tDMh8cJTz-d7A-gq4_nWSZIO/view?usp=sharing",
    "synthtiger_v1.1.zip.09": "https://drive.google.com/file/d/1WJ-QrHsp6joWAU5JVs3TgpMCvz-E4YKq/view?usp=sharing",
    "synthtiger_v1.1.zip.10": "https://drive.google.com/file/d/1Pp3TRa60oUDHLIhN0oQ_y4SukXxfIjcw/view?usp=sharing",
}
_ARCHIVE_ROOT = "synthtiger_v1.1"


def _get_google_drive_url(url):
    """Re-format the "Get link" version of a Google Drive URL."""
    base_url = "https://drive.google.com/uc?id="
    split_url = url.split("/")
    return base_url + split_url[5]


class Synthtiger(datasets.GeneratorBasedBuilder):
    """A synthtetic scene text OCR dataset generated by SynthTIGER."""

    VERSION = datasets.Version("1.1.0")

    def _info(self):
        """Define dataset metadata and feature types."""
        features = datasets.Features(
            {
                "image": datasets.Image(),
                "transcript": datasets.Value("string"),
                "height": datasets.Value("uint32"),
                "width": datasets.Value("uint32"),
                "aspect_ratio": datasets.Value("float32"),
                "script": datasets.Value("string"),
                "lang": datasets.Value("string"),
            }
        )

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            supervised_keys=("image", "transcript"),
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Build split metadata and fetch data if needed."""
        folder_url = _FOLDER_URL
        part_urls = {k: _get_google_drive_url(v) for k, v in _PART_URLS.items()}

        def custom_download(src_url: str, dest_path: str):
            """Internal utility to download and combine archive parts.

            As of October 23, 2021, the SynthTIGER dataset v1.1 is distributed
            via Google Drive. It is a ~38Gb zip file split into 11 parts of
            ~3.5Gb each with the `split` utility. This means that the parts
            are not usable archives on their own, they must be concatenated
            back into the whole zip file before any of the contents can be
            extracted.

            This inner function provides a closure around the `dl_manager` and
            `part_urls` variables so that the download manager's custom
            download function can track and cache the download of the parts as
            well as the concatenated version. This makes it easier to re-start
            an interrupted download of the parts at the cost of disk space.

            The `src_url` is chosen to be the viewable folder url for Google
            Drive, but it serves no purpose except to be a hashable string
            that allows the concatenated archive to be cached.

            The parts of the download will not be cleaned up. This would be
            easy to add if needed, since the paths are known, but keeping them
            makes the download manager's stats more accurate. The parts should
            not be needed once the full archive has been cached and can be
            deleted manually.
            """
            downloaded_part_paths = dl_manager.download(part_urls)
            with open(dest_path, "wb") as concatenated_file:
                for name, path in downloaded_part_paths.items():
                    with open(path, "rb") as part_file:
                        shutil.copyfileobj(part_file, concatenated_file)
            return dest_path

        archive_path = dl_manager.download_custom(folder_url, custom_download)
        extracted_dir = dl_manager.extract(archive_path, num_proc=1)
        data_dir = os.path.join(extracted_dir, _ARCHIVE_ROOT)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "data_dir": data_dir,
                    "split": "train",
                },
            ),
        ]

    def _generate_examples(self, data_dir, split):
        """Iterate over dataset images and annotations."""
        gt_path = os.path.join(data_dir, "gt.txt")
        with open(gt_path, encoding="utf-8") as gt_file:
            for key, line in enumerate(gt_file):
                rel_path, transcript = line.strip().split("\t")
                image_path = os.path.join(data_dir, rel_path)
                image = Image.open(image_path)
                width, height = image.size
                aspect_ratio = width / height
                yield key, {
                    "image": image,
                    "transcript": transcript,
                    "height": height,
                    "width": width,
                    "aspect_ratio": aspect_ratio,
                    "script": "Latn",
                    "lang": "en",
                }