File size: 1,549 Bytes
ebdcebe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from datasets import DatasetInfo, GeneratorBasedBuilder, SplitGenerator, Split, Value, Features

class MyDataset(GeneratorBasedBuilder):
    def _info(self):
        return DatasetInfo(
            description="Custom dataset with images and labels in separate folders",
            features=Features({
                "image": Value("string"),   # filepath, will cast later
                "label": Value("string")
            }),
        )

    def _split_generators(self, dl_manager):
        data_dir = self.config.data_dir or ""
        return [
            SplitGenerator(name=Split.TRAIN, gen_kwargs={"split_dir": os.path.join(data_dir, "train")}),
            SplitGenerator(name=Split.TEST, gen_kwargs={"split_dir": os.path.join(data_dir, "test")}),
        ]

    def _generate_examples(self, split_dir):
        image_dir = os.path.join(split_dir, "images")
        label_dir = os.path.join(split_dir, "labels")

        idx = 0
        for image_name in sorted(os.listdir(image_dir)):
            if not image_name.lower().endswith((".jpg", ".png", ".jpeg")):
                continue

            image_path = os.path.join(image_dir, image_name)
            label_path = os.path.join(label_dir, os.path.splitext(image_name)[0] + ".txt")

            if not os.path.exists(label_path):
                continue

            with open(label_path, "r") as f:
                label = f.read().strip()

            yield idx, {
                "image": image_path,
                "label": label,
            }
            idx += 1