File size: 1,915 Bytes
cc11703
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import datasets
import tarfile
from datasets import Features, Value
from datasets.download.download_manager import DownloadManager
from typing import List, NamedTuple, TypedDict, Generator
from PIL import Image

Example = TypedDict('Example', {
  'index': int,
  'tar': str,
  'tar_path': str,
  'img': Image.Image,
})

class KeyedExample(NamedTuple):
    key: int
    example: Example

tar_count = 5
files = [f'./{ix:05d}.tar' for ix in range(tar_count)]

class MyWebdataset(datasets.GeneratorBasedBuilder):
    VERSION = '1.0.0'
    
    def _info(self) -> datasets.DatasetInfo:
        print(__file__)
        return datasets.DatasetInfo(
            description="OpenAI guided-diffusion 256px class-conditional unguided samples (50k)",
            features=Features({
                'index': Value('uint32'),
                'tar': Value('string'),
                'tar_path': Value('string'),
                'img': datasets.Image(),
            }),
        )
    
    def _split_generators(self, dl_manager: DownloadManager) -> List[datasets.SplitGenerator]:
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"filepaths": dl_manager.download(files)},
            )
        ]

    def _generate_examples(self, filepaths: List[str]) -> Generator[KeyedExample, None, None]:
        index = 0
        for filepath in filepaths:
            with tarfile.open(filepath, "r:") as tar:
                for member in tar.getmembers():
                    with tar.extractfile(member.name) as f:
                        pil: Image.Image = Image.open(f)
                        yield KeyedExample(index, Example(
                            index=index,
                            tar=filepath,
                            tar_path=member.path,
                            img=pil,
                        ))
                        index += 1