File size: 2,029 Bytes
51f2e1e | 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 | """Verify downloaded uncompressed files against the SHA256 inventory."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
def sha(path):
h=hashlib.sha256()
with path.open('rb') as f:
for b in iter(lambda:f.read(4*1024**2),b''):h.update(b)
return h.hexdigest()
def verify(root,collection):
manifest=json.loads((root/'metadata/manifest.json').read_text())
inventory=root/manifest['file_inventory']['path']
if inventory.stat().st_size!=manifest['file_inventory']['bytes'] or sha(inventory)!=manifest['file_inventory']['sha256']:
raise ValueError('File inventory checksum mismatch')
files=size=0
prefix={'qlib':'qlib/','minutes':'A股分钟/','all':''}[collection]
with inventory.open() as f:
for line in f:
row=json.loads(line);rel=PurePosixPath(row['path'])
if rel.is_absolute() or '..' in rel.parts:raise ValueError('Unsafe inventory path')
if not row['path'].startswith(prefix):continue
path=root.joinpath(*rel.parts)
if not path.is_file() or path.stat().st_size!=row['bytes'] or sha(path)!=row['sha256']:
raise ValueError('File verification failed: '+row['path'])
files+=1;size+=row['bytes']
if files%10000==0:print(f'Verified {files:,} files / {size:,} bytes',flush=True)
selected=[c for c in manifest['collections'] if c['path_in_repo'].startswith(prefix)]
if files!=sum(c['files'] for c in selected) or size!=sum(c['bytes'] for c in selected):
raise ValueError('Collection totals mismatch')
return {'collection':collection,'files':files,'bytes':size,'sha256_verified':True}
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--repo',type=Path,default=Path('./stock_dataset'))
p.add_argument('--collection',choices=['qlib','minutes','all'],default='all')
args=p.parse_args();print(json.dumps(verify(args.repo,args.collection),indent=2))
if __name__=='__main__':main()
|