File size: 2,305 Bytes
69c079d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Load one checksum-verified histogram locally or from a Hugging Face dataset."""
import argparse
import csv
import hashlib
from pathlib import Path

import h5py


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group()
    source.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
    source.add_argument('--repo-id', help='Published Hugging Face dataset ID: owner/name')
    parser.add_argument('--revision', default='main', help='Use a commit hash for reproducibility')
    parser.add_argument('--source', choices=['synthetic', 'experimental'], default='experimental')
    parser.add_argument('--fold', help='For example: fold_1')
    parser.add_argument('--split', choices=['train', 'validation', 'test', 'unassigned'])
    args = parser.parse_args()

    def resolve(filename):
        if args.repo_id:
            from huggingface_hub import hf_hub_download
            return Path(hf_hub_download(repo_id=args.repo_id, filename=filename,
                                       repo_type='dataset', revision=args.revision))
        return args.root / filename

    with resolve('manifest.csv').open(newline='') as handle:
        row = next((r for r in csv.DictReader(handle)
                    if r['source'] == args.source
                    and (not args.fold or r['fold'] == args.fold)
                    and (not args.split or r['split'] == args.split)), None)
    if row is None:
        parser.error('No sample matches the requested source, fold, and split')
    filename = resolve(row['path'])
    if hashlib.sha256(filename.read_bytes()).hexdigest() != row['sha256']:
        raise ValueError(f'Checksum mismatch: {filename}')
    with h5py.File(filename, 'r') as handle:
        histogram = handle[row['h5_key']][()]
    expected_shape = tuple(int(row[k]) for k in ('height', 'width', 'bins'))
    if histogram.shape != expected_shape or str(histogram.dtype) != row['dtype']:
        raise ValueError(f'Schema mismatch: {filename}')
    print(f"{row['path']}\nlabel={row['label_name']} ({row['label']}), "
          f"fold={row['fold'] or 'none'}, split={row['split']}\n"
          f"shape={histogram.shape}, dtype={histogram.dtype}, sha256=verified")


if __name__ == '__main__':
    main()