File size: 3,131 Bytes
aaf8747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3
"""Extract one manifest-selected clip, verifying member hashes; stdlib only."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import tarfile


def safe_relative(name):
    path = PurePosixPath(name)
    if path.is_absolute() or '..' in path.parts or '\\' in name:
        raise ValueError(f'Unsafe relative path: {name!r}')
    return path


def find_sample(root, sample_id):
    with (root / 'manifests/train.jsonl').open(encoding='utf-8') as stream:
        for line in stream:
            row = json.loads(line)
            if sample_id is None or row['sample_id'] == sample_id:
                return row
    raise ValueError(f'Sample not found: {sample_id}')


def extract(root, sample_id, destination):
    row = find_sample(root, sample_id)
    shard = (root / safe_relative(row['shard'])).resolve()
    shard.relative_to(root.resolve())
    if destination.exists():
        raise FileExistsError(f'Choose a new output directory: {destination}')
    destination.mkdir(parents=True)
    files = {}
    try:
        with tarfile.open(shard, 'r:') as archive:
            for kind, name in row['members'].items():
                relative = safe_relative(name)
                if len(relative.parts) != 1:
                    raise ValueError(f'Expected a flat sample member: {name}')
                member = archive.getmember(name)
                if not member.isfile():
                    raise ValueError(f'Expected regular file: {name}')
                expected = row['sha256'].get(kind)
                if not expected:
                    raise ValueError(f'No expected hash for {kind}')
                path = destination / relative.name
                digest = hashlib.sha256()
                source = archive.extractfile(member)
                if source is None:
                    raise ValueError(f'Unreadable member: {name}')
                with source, path.open('xb') as output:
                    while chunk := source.read(1024 * 1024):
                        digest.update(chunk)
                        output.write(chunk)
                if digest.hexdigest() != expected:
                    path.unlink()
                    raise ValueError(f'SHA256 mismatch: {name}')
                files[kind] = str(path)
        return {'sample_id': row['sample_id'], 'shard': row['shard'],
                'num_frames': row['num_frames'], 'fps': row['fps'],
                'duration_seconds': row['duration_seconds'], 'files': files}
    except Exception:
        # Verified files may remain for inspection; no existing directory is overwritten.
        raise


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--release-root', type=Path, required=True)
    parser.add_argument('--sample-id', help='Defaults to the first manifest row')
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    result = extract(args.release_root, args.sample_id, args.output)
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()