File size: 4,317 Bytes
79c4b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38243f7
79c4b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7d2a68
 
 
 
79c4b52
 
f7d2a68
79c4b52
 
 
 
 
38243f7
 
79c4b52
 
 
 
 
 
 
 
 
f7d2a68
79c4b52
 
 
f7d2a68
 
 
 
 
 
 
 
79c4b52
 
 
 
 
 
 
f7d2a68
 
 
 
 
 
 
 
79c4b52
 
f7d2a68
 
79c4b52
 
f7d2a68
 
 
 
 
 
79c4b52
f7d2a68
79c4b52
 
 
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
# Copyright (c) 2022, texture.design.
#
# 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.

import json

import datasets


DESCRIPTION = """\
Multi-photo texture captures in outdoor nature scenes focusing on the ground.  Each set contains variations of the same texture theme.
"""

REPO_PREFIX = "https://huggingface.co/datasets/texturedesign/td01_natural-ground-textures"
DOWNLOAD_PREFIX = REPO_PREFIX + "/resolve/main"

INDEX_URLS = {
    "train": REPO_PREFIX + "/raw/main/train/metadata.jsonl",
    "test": REPO_PREFIX + "/raw/main/test/metadata.jsonl",
}


class NaturalGroundTextures(datasets.GeneratorBasedBuilder):

    VERSION = datasets.Version("0.1.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="JXL@4K", version=VERSION, description="The original resolution dataset."),
        datasets.BuilderConfig(name="JXL@2K", version=VERSION, description="Half-resolution dataset."),
        datasets.BuilderConfig(name="JXL@1K", version=VERSION, description="Quarter-resolution dataset."),
        datasets.BuilderConfig(name="PNG@1K", version=VERSION, description="Fallback version of the dataset."),
    ]

    DEFAULT_CONFIG_NAME = "JXL@2K"

    def _info(self):
        return datasets.DatasetInfo(
            description=DESCRIPTION,
            citation="",
            homepage="https://huggingface.co/texturedesign",
            license="cc-by-nc-4.0",
            features=datasets.Features(
                {
                    "image": datasets.Image(),
                    "set": datasets.Value("uint8"),
                }
            )
        )

    def _split_generators(self, dl_manager):
        data_dir = dl_manager.download(INDEX_URLS)
        train_lines = [json.loads(l) for l in open(data_dir["train"], "r", encoding="utf-8").readlines()]
        test_lines = [json.loads(l) for l in open(data_dir["test"], "r", encoding="utf-8").readlines()]

        def _get_file_url(row, split):
            file_name = row['file_name']
            if self.config.name[:3] == "PNG":
                file_name = file_name.replace('.jxl', '.png')
            return (DOWNLOAD_PREFIX + '/' + split + '/' + file_name)

        train_files = dl_manager.download([_get_file_url(row, split='train') for row in train_lines])
        test_files = dl_manager.download([_get_file_url(row, split='test') for row in test_lines])

        return [
            datasets.SplitGenerator(datasets.Split.TRAIN, dict(lines=train_lines, filenames=train_files)),
            datasets.SplitGenerator(datasets.Split.TEST, dict(lines=test_lines, filenames=test_files)),
        ]

    def _generate_examples(self, lines, filenames):
        try:
            if self.config.name[:3] == "JXL":
                from jxlpy import JXLImagePlugin
            import PIL.Image
        except (ImportError, ModuleNotFoundError):
            logger = datasets.logging.get_logger()
            logger.critical('\n\n\nERROR: Please install `jxlpy` from PyPI to use JPEG-XL images.\n')
            raise SystemExit

        for key, (data, filename) in enumerate(zip(lines, filenames)):
            # Load the images from disk with the correct format.
            image = PIL.Image.open(filename, formats=[self.config.name[:3].lower()])
            sz = image.size

            # PNG files only available at quarter resolution.
            if self.config.name[:3] == "PNG":
                sz = (sz*4, sz*4)

            # Resize the images as specified by the user.
            if self.config.name[-2:] == "1K":
                image = image.resize(size=(sz[0]//4, sz[1]//4), resample=PIL.Image.Resampling.LANCZOS)
            elif self.config.name[-2:] == "2K":
                image = image.resize(size=(sz[0]//2, sz[1]//2), resample=PIL.Image.Resampling.LANCZOS)

            yield key, {"image": image, "set": data["set"]}