|
from pathlib import Path |
|
from typing import List |
|
|
|
import datasets |
|
|
|
logger = datasets.logging.get_logger(__name__) |
|
|
|
_DESCRIPTION = "A generic image folder" |
|
|
|
|
|
class ImageFolder(datasets.GeneratorBasedBuilder): |
|
def _info(self): |
|
|
|
folder=None |
|
if isinstance(self.config.data_files, str): |
|
folder = self.config.data_files |
|
elif isinstance(self.config.data_files, dict): |
|
folder = self.config.data_files.get('train', None) |
|
|
|
if folder is None: |
|
raise RuntimeError() |
|
|
|
classes = sorted([x.name.lower() for x in Path(folder).glob('*/**')]) |
|
|
|
return datasets.DatasetInfo( |
|
description=_DESCRIPTION, |
|
features=datasets.Features( |
|
{ |
|
"file": datasets.Value("string"), |
|
"labels": datasets.features.ClassLabel(names=classes) |
|
} |
|
), |
|
) |
|
|
|
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]: |
|
|
|
data_files = self.config.data_files |
|
|
|
if isinstance(data_files, str): |
|
return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={'archive_path': data_files})] |
|
|
|
splits = [] |
|
for split_name, folder in data_files.items(): |
|
splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={'archive_path': folder})) |
|
|
|
return splits |
|
|
|
def _generate_examples(self, archive_path): |
|
labels = self.info.features['labels'] |
|
logger.info("generating examples from = %s", archive_path) |
|
extensions = {'.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp'} |
|
for i, path in enumerate(Path(archive_path).glob('**/*')): |
|
if path.suffix in extensions: |
|
yield i, {'file': path.as_posix(), 'labels': labels.encode_example(path.parent.name.lower())} |
|
|