nateraw commited on
Commit
5ebd8e8
1 Parent(s): a959fbe

Create imagefolder.py

Browse files
Files changed (1) hide show
  1. imagefolder.py +53 -0
imagefolder.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ import pyarrow as pa
6
+
7
+ import datasets
8
+
9
+
10
+ logger = datasets.utils.logging.get_logger(__name__)
11
+
12
+
13
+ @dataclass
14
+ class ImageFolderConfig(datasets.BuilderConfig):
15
+ """BuilderConfig for ImageFolder."""
16
+
17
+ features: Optional[datasets.Features] = None
18
+
19
+ @property
20
+ def schema(self):
21
+ return pa.schema(self.features.type) if self.features is not None else None
22
+
23
+
24
+ class ImageFolder(datasets.GeneratorBasedBuilder):
25
+
26
+ BUILDER_CONFIG_CLASS = ImageFolderConfig
27
+
28
+ def _info(self):
29
+ return datasets.DatasetInfo(
30
+ features=datasets.Features(
31
+ {"image_file_path": datasets.Value("string"), "labels": datasets.Value("string")}
32
+ ),
33
+ )
34
+
35
+ def _split_generators(self, dl_manager):
36
+ if not self.config.data_files:
37
+ raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}")
38
+
39
+ data_files = self.config.data_files
40
+ if isinstance(data_files, str):
41
+ folder = data_files
42
+ return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"archive_path": folder})]
43
+ splits = []
44
+ for split_name, folder in data_files.items():
45
+ splits.append(datasets.SplitGenerator(name=split_name, gen_kwargs={"archive_path": folder}))
46
+ return splits
47
+
48
+ def _generate_examples(self, archive_path):
49
+ logger.info("generating examples from = %s", archive_path)
50
+ extensions = {".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp"}
51
+ for i, path in enumerate(Path(archive_path).glob("**/*")):
52
+ if path.suffix in extensions:
53
+ yield i, {"image_file_path": path.as_posix(), "labels": path.parent.name.lower()}