File size: 2,556 Bytes
51b0b52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reassemble uploaded byte shards into the exact original NPY file."""
import argparse,hashlib,json,shutil
from pathlib import Path

def sha(path):
    h=hashlib.sha256()
    with path.open('rb') as stream:
        while data:=stream.read(8*1024**2): h.update(data)
    return h.hexdigest()

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parent)
    args=parser.parse_args();root=args.root.resolve()
    manifest=json.loads((root/'asset_manifest.json').read_text(encoding='utf-8'))
    for item in manifest.get('reassemble',[]):
        target=(root/item['path']).resolve()
        if not target.is_relative_to(root):raise ValueError('Path escapes asset root')
        target.parent.mkdir(parents=True,exist_ok=True)
        if target.exists():
            if target.stat().st_size!=item['bytes'] or sha(target)!=item['sha256']:
                raise ValueError('Existing output differs; refusing overwrite')
            print('Already verified:',item['path']);continue
        if shutil.disk_usage(target.parent).free<item['bytes']:
            raise RuntimeError('Insufficient space for the restored NPY; shards are retained')
        temp=target.with_name(target.name+'.restoring')
        digest=hashlib.sha256();written=0
        try:
            with temp.open('xb') as output:
                for part in item['parts']:
                    if part['byte_offset']!=written:raise ValueError('Non-contiguous shards')
                    source=(root/part['path']).resolve()
                    if not source.is_relative_to(root) or source.stat().st_size!=part['bytes']:
                        raise ValueError('Missing or invalid shard')
                    part_hash=hashlib.sha256()
                    with source.open('rb') as stream:
                        while data:=stream.read(8*1024**2):
                            output.write(data);part_hash.update(data);digest.update(data);written+=len(data)
                    if part_hash.hexdigest()!=part['sha256']:raise ValueError('Shard checksum mismatch')
            if written!=item['bytes'] or digest.hexdigest()!=item['sha256']:
                raise ValueError('Restored NPY checksum mismatch')
            temp.rename(target)
        except Exception:
            # Retain partial output for inspection; never remove existing user files.
            raise
        print('Restored and verified:',item['path'])

if __name__=='__main__':main()