coderofpears commited on
Commit
94d9b65
·
verified ·
1 Parent(s): 31441cc

publish portable stage runner + frozen sources

Browse files
Files changed (1) hide show
  1. pear15/dataset_archive.py +163 -0
pear15/dataset_archive.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded flat tar transport for a verified BPE corpus; no model dependencies."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import shutil
7
+ import tarfile
8
+ import tempfile
9
+
10
+ from .scratch_data import manifest_fingerprint, verify_dataset
11
+
12
+ MAX_BYTES = 3_000_000_000
13
+
14
+
15
+ def digest(path):
16
+ value = hashlib.sha256()
17
+ with Path(path).open('rb') as stream:
18
+ for block in iter(lambda: stream.read(8 * 1024**2), b''):
19
+ value.update(block)
20
+ return value.hexdigest()
21
+
22
+
23
+ def flat_name(name):
24
+ if (not isinstance(name, str) or not name or name in {'.', '..'}
25
+ or '/' in name or '\\' in name or ':' in name):
26
+ raise ValueError('Archive members must be flat safe filenames')
27
+ return name
28
+
29
+
30
+ def members(manifest):
31
+ entries = [*manifest['files']]
32
+ for field in ('document_index', 'candidate_ledger', 'split_registry'):
33
+ if manifest.get(field):
34
+ entries.append(manifest[field])
35
+ names = [flat_name(entry['path']) for entry in entries]
36
+ if len(names) != len(set(names)) or {'manifest.json', 'report.json'} & set(names):
37
+ raise ValueError('Duplicate or reserved member names')
38
+ if len(names) > 20000 or sum(e['bytes'] for e in entries) > MAX_BYTES:
39
+ raise ValueError('Dataset exceeds transport bound')
40
+ return entries
41
+
42
+
43
+ def pack(source, report_path, output, *, expected_fingerprint=None):
44
+ source, report_path, output = Path(source), Path(report_path), Path(output)
45
+ if output.exists() or Path(str(output) + '.json').exists():
46
+ raise FileExistsError('Choose a new archive output')
47
+ manifest = verify_dataset(source)
48
+ fingerprint = manifest_fingerprint(manifest)
49
+ report = json.loads(report_path.read_text(encoding='utf-8'))
50
+ if (report.get('success') is not True or report['dataset_fingerprint'] != fingerprint
51
+ or (expected_fingerprint and fingerprint != expected_fingerprint)
52
+ or report['manifest_sha256'] != digest(source / 'manifest.json')):
53
+ raise ValueError('Dataset/report/expected identity mismatch')
54
+ for split in ('train', 'validation'):
55
+ if sum(e['tokens'] for e in manifest['files'] if e['split'] == split) != report[split + '_tokens']:
56
+ raise ValueError('Reported token count mismatch')
57
+ entries = members(manifest)
58
+ for entry in entries:
59
+ path = source / entry['path']
60
+ if path.stat().st_size != entry['bytes'] or digest(path) != entry['sha256']:
61
+ raise ValueError('Archive member changed or failed checksum')
62
+ if report_path.stat().st_size > 2 * 1024**2:
63
+ raise ValueError('Unexpectedly large source report')
64
+ ordered = [('manifest.json', source / 'manifest.json')]
65
+ ordered.extend((entry['path'], source / entry['path']) for entry in entries)
66
+ ordered.append(('report.json', report_path))
67
+ temporary = output.with_name(output.name + '.partial')
68
+ try:
69
+ with tarfile.open(temporary, 'x:', format=tarfile.USTAR_FORMAT) as archive:
70
+ for name, path in ordered:
71
+ info = tarfile.TarInfo(flat_name(name))
72
+ info.size, info.mtime, info.mode = path.stat().st_size, 0, 0o644
73
+ with path.open('rb') as stream:
74
+ archive.addfile(info, stream)
75
+ if temporary.stat().st_size > MAX_BYTES:
76
+ raise ValueError('Archive exceeds 3GB transport bound')
77
+ temporary.rename(output)
78
+ finally:
79
+ if temporary.exists():
80
+ temporary.unlink()
81
+ result = {'format': 'pear15-bpe-tar-transport-v1', 'success': True,
82
+ 'archive': output.name, 'archive_bytes': output.stat().st_size,
83
+ 'archive_sha256': digest(output), 'dataset_fingerprint': fingerprint,
84
+ 'manifest_sha256': digest(source / 'manifest.json'),
85
+ 'report_bytes': report_path.stat().st_size, 'report_sha256': digest(report_path),
86
+ 'train_tokens': report['train_tokens'], 'validation_tokens': report['validation_tokens'],
87
+ 'member_count': len(ordered), 'source_sha256': digest(__file__)}
88
+ Path(str(output) + '.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
89
+ return result
90
+
91
+
92
+ def unpack(archive_path, transport, destination):
93
+ archive_path, destination = Path(archive_path), Path(destination)
94
+ if destination.exists():
95
+ raise FileExistsError('Extraction requires a fresh destination')
96
+ if (transport.get('format') != 'pear15-bpe-tar-transport-v1'
97
+ or transport.get('success') is not True
98
+ or not 0 < transport['archive_bytes'] <= MAX_BYTES
99
+ or archive_path.stat().st_size != transport['archive_bytes']
100
+ or digest(archive_path) != transport['archive_sha256']):
101
+ raise ValueError('Archive transport checksum/size mismatch')
102
+ stage = Path(tempfile.mkdtemp(prefix='.' + destination.name + '-', dir=destination.parent))
103
+ seen, expected, manifest = set(), {}, None
104
+ try:
105
+ with tarfile.open(archive_path, 'r:') as archive:
106
+ for index, member in enumerate(archive):
107
+ name = flat_name(member.name)
108
+ if not member.isfile() or member.linkname or name in seen:
109
+ raise ValueError('Non-file/link/duplicate tar member')
110
+ seen.add(name)
111
+ stream = archive.extractfile(member)
112
+ if index == 0:
113
+ if name != 'manifest.json' or member.size > 16 * 1024**2:
114
+ raise ValueError('First member must be a bounded manifest')
115
+ raw = stream.read(16 * 1024**2 + 1)
116
+ if hashlib.sha256(raw).hexdigest() != transport['manifest_sha256']:
117
+ raise ValueError('Archived manifest checksum mismatch')
118
+ manifest = json.loads(raw)
119
+ if manifest_fingerprint(manifest) != transport['dataset_fingerprint']:
120
+ raise ValueError('Archived dataset fingerprint mismatch')
121
+ expected = {entry['path']: entry for entry in members(manifest)}
122
+ expected['report.json'] = {'bytes': transport['report_bytes'],
123
+ 'sha256': transport['report_sha256']}
124
+ if sum(e['bytes'] for e in expected.values()) + len(raw) > MAX_BYTES:
125
+ raise ValueError('Extracted data exceeds cap')
126
+ (stage / name).write_bytes(raw)
127
+ continue
128
+ entry = expected.get(name)
129
+ if entry is None or type(entry['bytes']) is not int or member.size != entry['bytes']:
130
+ raise ValueError('Unexpected tar member or byte count')
131
+ sha, count = hashlib.sha256(), 0
132
+ with (stage / name).open('xb') as target:
133
+ for block in iter(lambda: stream.read(1024 * 1024), b''):
134
+ count += len(block)
135
+ if count > entry['bytes']:
136
+ raise ValueError('Member exceeded declared bound')
137
+ sha.update(block)
138
+ target.write(block)
139
+ if count != entry['bytes'] or sha.hexdigest() != entry['sha256']:
140
+ raise ValueError('Extracted member checksum mismatch')
141
+ if manifest is None or seen != {'manifest.json', *expected}:
142
+ raise ValueError('Incomplete archive')
143
+ verify_dataset(stage)
144
+ stage.rename(destination)
145
+ finally:
146
+ if stage.exists():
147
+ shutil.rmtree(stage)
148
+ return manifest
149
+
150
+
151
+ def main():
152
+ parser = argparse.ArgumentParser(description=__doc__)
153
+ parser.add_argument('--source', type=Path, required=True)
154
+ parser.add_argument('--report', type=Path, required=True)
155
+ parser.add_argument('--output', type=Path, required=True)
156
+ parser.add_argument('--expected-fingerprint')
157
+ args = parser.parse_args()
158
+ print(json.dumps(pack(args.source, args.report, args.output,
159
+ expected_fingerprint=args.expected_fingerprint), indent=2), flush=True)
160
+
161
+
162
+ if __name__ == '__main__':
163
+ main()