pipe_m / extract_data.py
Jlz2's picture
Add 4,663 training pairs and portable known-stem synthesis pipeline
e1d44f1 verified
Raw History Blame Contribute Delete
5.75 kB
"""Verify dataset archive hashes, safely extract audio, and verify pair hashes."""
import argparse,hashlib,json,tarfile
from pathlib import Path,PurePosixPath
from load_train import default_train,load_train
def sha(path):
h=hashlib.sha256()
with path.open('rb') as f:
for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
return h.hexdigest()
def safe_parts(value):
p=PurePosixPath(value)
if p.is_absolute() or '..' in p.parts or '\\' in value or ':' in value or not p.parts:raise ValueError('Unsafe archive/manifest path: '+value)
return p.parts
def records(manifest):
files=manifest['files']
if isinstance(files,dict):return [{'path':k,**({'sha256':v} if isinstance(v,str) else v)} for k,v in files.items()]
if not isinstance(files,list):raise ValueError('Manifest files must be a list or path mapping')
return files
def default_manifest(root):
for value in ('P0/known_stem_mix/_shared/data/data_manifest.json','_shared/data/data_manifest.json'):
if (root/value).is_file():return root/value
raise FileNotFoundError('Provide --manifest for the archive/metadata SHA256 manifest')
def extract(repo_root,manifest_path=None,train=None,subtypes=None):
root=Path(repo_root).resolve();manifest_path=Path(manifest_path) if manifest_path else default_manifest(root)
items=records(json.loads(manifest_path.read_text()));seen=set();archives=[]
# Verify every packaged metadata/archive file before writing extracted audio.
for item in items:
name=item['path'];parts=safe_parts(name)
if subtypes and 'known_stem_mix' in parts:
subtype=parts[parts.index('known_stem_mix')+1]
if subtype!='_shared' and subtype not in subtypes:continue
if name in seen:raise ValueError('Duplicate manifest path: '+name)
seen.add(name);path=root.joinpath(*parts)
expected=item['sha256']
if len(expected)!=64 or any(c not in '0123456789abcdef' for c in expected):raise ValueError('Invalid SHA256: '+name)
if sha(path)!=expected:raise ValueError('Archive/metadata hash mismatch: '+name)
if name.endswith('.tar'):archives.append(path)
expected_audio={}
for row in load_train(root,train or default_train(root),subtypes):
for path_key,hash_key in (('input_audio','source_sha256'),('target_audio','target_sha256')):
path=Path(row[path_key]);expected=row[hash_key]
if path in expected_audio and expected_audio[path]!=expected:raise ValueError('Conflicting pair hashes: '+str(path))
expected_audio[path]=expected
count=0
for archive in archives:
destination=archive.parent
with tarfile.open(archive,'r:') as t:
members=t.getmembers();targets=set()
for member in members:
parts=safe_parts(member.name)
if not (member.isdir() or member.isfile()) or member.issym() or member.islnk():raise ValueError('Only regular files/directories are allowed: '+member.name)
path=destination.joinpath(*parts)
if not path.resolve().is_relative_to(root):raise ValueError('Extraction path escapes repository: '+member.name)
for existing in (path,*path.parents):
if existing==root:break
if existing.is_symlink():raise ValueError('Extraction path contains a symlink: '+member.name)
if member.isfile() and path.resolve() not in expected_audio:raise ValueError('Archive file is not listed in train: '+member.name)
if str(path) in targets:raise ValueError('Duplicate archive member: '+member.name)
targets.add(str(path))
for member in members:
path=destination.joinpath(*safe_parts(member.name))
if member.isdir():path.mkdir(parents=True,exist_ok=True);continue
path.parent.mkdir(parents=True,exist_ok=True)
temp=path.with_name(path.name+'.partial')
created=False
try:
with t.extractfile(member) as src,temp.open('xb') as dst:
created=True
for b in iter(lambda:src.read(8*1024*1024),b''):dst.write(b)
expected=expected_audio[path.resolve()]
if sha(temp)!=expected:raise ValueError('Archive member hash mismatch: '+member.name)
if path.exists():
if sha(path)!=expected:raise ValueError('Existing audio differs; refusing to overwrite: '+str(path))
else:temp.replace(path)
finally:
if created and temp.exists():temp.unlink()
count+=1
checked={}
for row in load_train(root,train or default_train(root),subtypes):
for path_key,hash_key in (('input_audio','source_sha256'),('target_audio','target_sha256')):
path=Path(row[path_key]);expected=row[hash_key]
if path in checked and checked[path]!=expected:raise ValueError('Conflicting pair hashes: '+str(path))
if path not in checked:
if sha(path)!=expected:raise ValueError('Extracted audio hash mismatch: '+str(path))
checked[path]=expected
return {'archives_verified':len(archives),'files_extracted':count,'audio_hashes_verified':len(checked)}
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--repo-root',type=Path,required=True);p.add_argument('--manifest',type=Path);p.add_argument('--train');p.add_argument('--subtype',action='append');args=p.parse_args();print(json.dumps(extract(args.repo_root,args.manifest,args.train,args.subtype)))
if __name__=='__main__':main()