td02_urban-surface-textures / td02_urban-surface-textures.py
alexjc's picture
Loader script based on td01.
59762fc
raw
history blame
4.32 kB
# 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/td02_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"]}