ProbeScout-features / restore_patch_features.py
Ian100's picture
Add frozen Main17 features assets (13-13)
51b0b52 verified
Raw History Blame Contribute Delete
2.56 kB
"""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()