|
import requests |
|
from pathlib import Path |
|
from typing import List |
|
import datasets |
|
|
|
logger = datasets.logging.get_logger(__name__) |
|
|
|
_URLS = {'train': 'https://huggingface.co/datasets/auto-cats-and-dogs/resolve/main/train.tar.gz'} |
|
_NAMES = ['cat', 'dog'] |
|
|
|
class ImageFolder(datasets.GeneratorBasedBuilder): |
|
def _info(self): |
|
return datasets.DatasetInfo( |
|
features=datasets.Features( |
|
dict( |
|
file=datasets.Value("string"), |
|
labels=datasets.features.ClassLabel(names=_NAMES) |
|
) |
|
), |
|
) |
|
|
|
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]: |
|
|
|
data_files = dl_manager.download_and_extract(_URLS) |
|
if isinstance(data_files, str): |
|
return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs=dict(archive_path=data_files))] |
|
|
|
splits = [] |
|
for split_name, folder in data_files.items(): |
|
splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs=dict(archive_path=folder))) |
|
|
|
return splits |
|
|
|
def _generate_examples(self, archive_path): |
|
labels = self.info.features['labels'] |
|
extensions = set(('.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, dict(file=path.as_posix(), labels=labels.encode_example(path.parent.name.lower())) |
|
|