File size: 2,490 Bytes
9bc4c0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read local or public-Hub WebDataset shards without extracting image files."""
import argparse
import io
import json
import tarfile
from pathlib import Path
from urllib.request import urlopen
from PIL import Image

def samples(fileobj):
    """Yield (PIL image, metadata, text) while retaining only one sample in RAM."""
    with tarfile.open(fileobj=fileobj, mode='r|*') as archive:
        pending = {}
        current = None
        for member in archive:
            key, extension = member.name.rsplit('.', 1)
            if current is not None and key != current:
                if set(pending) != {'png', 'json', 'txt'}:
                    raise ValueError('Incomplete WebDataset sample: ' + current)
                metadata = json.loads(pending['json'])
                with Image.open(io.BytesIO(pending['png'])) as im:
                    yield im.convert('RGB'), metadata, pending['txt'].decode()
                pending = {}
            current = key
            if extension in pending:
                raise ValueError('Repeated member: ' + member.name)
            pending[extension] = archive.extractfile(member).read()
        if pending:
            if set(pending) != {'png', 'json', 'txt'}:
                raise ValueError('Incomplete WebDataset sample: ' + current)
            with Image.open(io.BytesIO(pending['png'])) as im:
                yield im.convert('RGB'), json.loads(pending['json']), pending['txt'].decode()

if __name__ == '__main__':
    p=argparse.ArgumentParser()
    p.add_argument('shard',help='Local TAR path, https URL, or shard filename in --repo')
    p.add_argument('--repo',default='laion/Anim-E-Ghibli-Backgrounds-FLUX-9B')
    p.add_argument('--revision',default='main')
    p.add_argument('--limit',type=int,default=5)
    a=p.parse_args()
    if Path(a.shard).is_file():
        source=open(a.shard,'rb')
    else:
        url=a.shard if a.shard.startswith('https://') else f'https://huggingface.co/datasets/{a.repo}/resolve/{a.revision}/data/{a.shard}'
        source=urlopen(url,timeout=90)
    with source:
        for i,(image,metadata,text) in enumerate(samples(source)):
            print(json.dumps(dict(id=metadata['id'],size=image.size,primary_class=metadata.get('primary_class'),
                subcategory=metadata.get('subcategory'),personality_id=metadata.get('personality_id'),
                emotion=metadata.get('emotion'),seed=metadata['seed'],prompt=text),ensure_ascii=False))
            if i+1>=a.limit: break