File size: 3,103 Bytes
9346a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

import datasets
import pyarrow as pa
from datasets.features import ClassLabel, Image
from datasets.tasks import ImageClassification

logger = datasets.utils.logging.get_logger(__name__)


@dataclass
class ImageFolderConfig(datasets.BuilderConfig):
    """BuilderConfig for ImageFolder."""

    features: Optional[datasets.Features] = None

    @property
    def schema(self):
        return (
            pa.schema(self.features.type)
            if self.features is not None
            else None
        )


class ImageFolder(datasets.GeneratorBasedBuilder):

    BUILDER_CONFIG_CLASS = ImageFolderConfig

    def _info(self):
        filepaths = None
        if isinstance(self.config.data_files, str):
            filepaths = self.config.data_files
        elif isinstance(self.config.data_files, dict):
            filepaths = self.config.data_files.get("train", None)
        if filepaths is None:
            raise RuntimeError("data_files must be specified")

        classes = sorted(
            [Path(file_path).parent.name.lower() for file_path in filepaths]
        )

        # Remove duplicates
        classes = list(set(classes))

        return datasets.DatasetInfo(
            features=datasets.Features(
                {
                    "image_filepath": Image(),
                    "labels": ClassLabel(names=classes),
                }
            ),
            task_templates=[
                ImageClassification(
                    image_column="image_filepath",
                    label_column="labels",
                )
            ],
        )

    def _split_generators(self, dl_manager):
        if not self.config.data_files:
            raise ValueError(
                f"At least one data file must be specified, but got data_files={self.config.data_files}"
            )

        data_files = self.config.data_files
        if isinstance(data_files, str):
            file_paths = data_files
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={"file_paths": file_paths},
                )
            ]
        splits = []
        for split_name, file_paths in data_files.items():
            splits.append(
                datasets.SplitGenerator(
                    name=split_name, gen_kwargs={"file_paths": file_paths}
                )
            )
        return splits

    def _generate_examples(self, file_paths):
        logger.info("generating examples from = %s", file_paths)
        extensions = {
            ".jpg",
            ".jpeg",
            ".png",
            ".ppm",
            ".bmp",
            ".pgm",
            ".tif",
            ".tiff",
            ".webp",
        }
        for i, path in enumerate(file_paths):
            path = Path(path)
            if path.suffix in extensions:
                yield i, {
                    "image_filepath": path.as_posix(),
                    "labels": path.parent.name.lower(),
                }