Datasets:
Download tools/export_simulation.py from diffusion-gif/trick-prediction-simulation-data: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/diffusion-gif/trick-prediction-simulation-data/resolve/main/tools/export_simulation.py
- Command line
-
hf download hf://datasets/diffusion-gif/trick-prediction-simulation-data/tools/export_simulation.py
-
curl -L -o export_simulation.py https://huggingface.co/datasets/diffusion-gif/trick-prediction-simulation-data/resolve/main/tools/export_simulation.py
11.1 kB
| #!/usr/bin/env python3 | |
| """Export ONLY licensed simulation records from a prepared joint SFT snapshot. | |
| Original files are read-only. HMAC key/ID mapping stay in a separate private | |
| work directory. Runtime account/API metadata and unknown-source media never | |
| enter the public allowlist. This is not a full original-dataset anonymizer. | |
| """ | |
| import argparse,collections,concurrent.futures,hashlib,hmac,io,json,os,secrets,tarfile,zipfile | |
| from pathlib import Path | |
| import numpy as np | |
| from PIL import Image | |
| from schema import SOURCES,BODIES,TEXT_RISK,validate | |
| BUDGET=1024**3 | |
| def sha(path): | |
| h=hashlib.sha256() | |
| with Path(path).open('rb') as f: | |
| for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b) | |
| return h.hexdigest() | |
| def dump(path,data):path.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n') | |
| def frame_bundle(source): | |
| path=Path(source['frames_root'])/source['npz'] | |
| before=path.stat();buffer=io.BytesIO();images=[];encoded_hashes=[] | |
| with np.load(path,allow_pickle=False) as arrays,zipfile.ZipFile(buffer,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as output: | |
| if set(arrays.files)!={f'f{i}' for i in range(8)}:raise ValueError('Unknown source NPZ fields') | |
| for i in range(8): | |
| arr=arrays[f'f{i}'] | |
| if arr.dtype!=np.uint8 or arr.ndim!=1 or not 100<=arr.size<=8*1024*1024:raise ValueError('Unexpected frame encoding') | |
| encoded=arr.tobytes();image=Image.open(io.BytesIO(encoded)) | |
| if image.format not in ('JPEG','PNG') or image.getexif():raise ValueError('Unreviewed frame metadata/EXIF') | |
| if set(image.info)-{'jfif','jfif_version','jfif_unit','jfif_density','gamma','srgb'}:raise ValueError('Additional image metadata found') | |
| image.load() | |
| if list(reversed(image.size))!=source['hw']:raise ValueError('Source image dimensions differ') | |
| # Only pre-existing encoded observation bytes; no resize/re-encode or future frames. | |
| encoded_hashes.append(hashlib.sha256(encoded).hexdigest()) | |
| if source.get('_make_preview'):images.append(image.convert('RGB').copy()) | |
| npy=io.BytesIO();np.lib.format.write_array(npy,arr,allow_pickle=False) | |
| info=zipfile.ZipInfo(f'f{i}.npy',date_time=(1980,1,1,0,0,0));info.compress_type=zipfile.ZIP_DEFLATED;info.external_attr=0o644<<16 | |
| output.writestr(info,npy.getvalue()) | |
| after=path.stat() | |
| if (before.st_size,before.st_mtime_ns)!=(after.st_size,after.st_mtime_ns):raise ValueError('Source changed during read') | |
| return buffer.getvalue(),encoded_hashes,images | |
| class Sharder: | |
| def __init__(self,root,split):self.root=root;self.split=split;self.index=-1;self.handle=None;self.rows=[];self.shards=[];self.size=0 | |
| def close(self): | |
| if self.handle is None:return | |
| self.handle.close();temp=self.root/(self.name+'.partial');target=self.root/self.name | |
| entries={r['media_member']:r for r in self.rows} | |
| with tarfile.open(temp,'r:') as f: | |
| for member in f: | |
| if not member.isfile() or member.name not in entries:raise ValueError('Unexpected tar member') | |
| data=f.extractfile(member).read() | |
| if hashlib.sha256(data).hexdigest()!=entries.pop(member.name)['media_sha256']:raise ValueError('Tar member readback SHA256 differs') | |
| if entries:raise ValueError('Missing tar member') | |
| if target.exists():raise ValueError('Will not overwrite an existing archive') | |
| temp.replace(target);self.shards.append({'path':'data/archives/'+self.name,'bytes':target.stat().st_size,'sha256':sha(target),'members':len(self.rows)}) | |
| self.handle=None;self.rows=[] | |
| def add(self,row,data): | |
| padded=((len(data)+511)//512)*512+512 | |
| if self.handle is not None and self.size+padded>BUDGET:self.close() | |
| if self.handle is None: | |
| self.index+=1;self.name=f'{self.split}-{self.index:05d}.tar';self.size=0 | |
| self.handle=tarfile.open(self.root/(self.name+'.partial'),'w:') | |
| row['media_archive']='data/archives/'+self.name | |
| info=tarfile.TarInfo(row['media_member']);info.size=len(data);info.mtime=0;info.uid=info.gid=0;info.uname=info.gname='';info.mode=0o644 | |
| self.handle.addfile(info,io.BytesIO(data));self.size+=padded;self.rows.append(dict(row)) | |
| def main(): | |
| p=argparse.ArgumentParser(description=__doc__);p.add_argument('--sft-root',required=True,type=Path);p.add_argument('--cot-run',required=True,type=Path);p.add_argument('--output',required=True,type=Path);p.add_argument('--privacy-work-root',required=True,type=Path);p.add_argument('--workers',type=int,default=4);a=p.parse_args() | |
| out=a.output.resolve();private=a.privacy_work_root.resolve() | |
| if private==out or out in private.parents:raise ValueError('Private mapping/key must be outside public payload') | |
| if (out/'PUBLIC_RELEASE_MANIFEST.json').exists():raise ValueError('Completed output already exists; use validator instead of overwriting') | |
| (out/'data/archives').mkdir(parents=True,exist_ok=True);(out/'previews').mkdir(exist_ok=True);private.mkdir(parents=True,exist_ok=True);private.chmod(0o700) | |
| if list((out/'data/archives').iterdir()):raise ValueError('Will not overwrite previous archives') | |
| key_path=private/'pseudonym_key' | |
| if not key_path.exists():key_path.write_bytes(secrets.token_bytes(32));key_path.chmod(0o600) | |
| key=key_path.read_bytes() | |
| def pseudonym(value):return hmac.new(key,value.encode(),hashlib.sha256).hexdigest()[:32] | |
| rows_by_split={};by_id={};groups={};excluded=collections.Counter();previews=set();source_counts={};media_rows=[];shards=[];seen=set() | |
| for split in ('train','heldout'): | |
| selected=[];group_set=set();counts=collections.Counter() | |
| for line in (a.sft_root/(split+'.jsonl')).open(): | |
| s=json.loads(line);body=s.get('source') | |
| if body not in BODIES:excluded[str(body)]+=1;continue | |
| if s['joint_id'] in by_id:raise ValueError('Repeated original source ID') | |
| source='DexMimicGen' if body=='dmg' else 'RoboTwin2.0' | |
| row={k:s[k] for k in ('task','coordinate_space','point_names','n_hist','n_fut','forecast_arm_count','history','anchor','future_delta','hw')} | |
| row.update(sample_id=pseudonym('sample:'+s['joint_id']),group_id=pseudonym('group:'+body+':'+s['joint_episode_group']),split=split,source_dataset=source,license=SOURCES[source],robot_body=body,media_archive=f'data/archives/{split}-00000.tar',media_member='',media_sha256='0'*64) | |
| row['media_member']=row['sample_id']+'.npz';validate(row) | |
| if row['sample_id'] in seen:raise ValueError('Duplicate pseudonymous ID') | |
| seen.add(row['sample_id']);group_set.add(row['group_id']);counts[body]+=1 | |
| s['_make_preview']=split=='train' and body not in previews | |
| if s['_make_preview']:previews.add(body) | |
| selected.append((s,row));by_id[s['joint_id']]=row | |
| rows_by_split[split]=selected;groups[split]=group_set;source_counts[split]=dict(counts) | |
| if groups['train']&groups['heldout']:raise ValueError('Source episode groups leak across splits') | |
| if (len(rows_by_split['train']),len(rows_by_split['heldout']))!=(14253,3168):raise ValueError('Unexpected reviewed simulation snapshot count') | |
| mapping=private/'id_mapping.jsonl' | |
| with mapping.open('w') as f: | |
| for original,row in by_id.items():f.write(json.dumps({'original_id':original,'public_id':row['sample_id']})+'\n') | |
| mapping.chmod(0o600) | |
| preview_rows=[] | |
| for split,selected in rows_by_split.items(): | |
| sharder=Sharder(out/'data/archives',split) | |
| with (out/'data'/(split+'.jsonl')).open('w') as labels,concurrent.futures.ThreadPoolExecutor(max_workers=a.workers) as pool: | |
| for number,((source,row),(data,encoded_hashes,images)) in enumerate(zip(selected,pool.map(frame_bundle,(s for s,r in selected))),1): | |
| row['media_sha256']=hashlib.sha256(data).hexdigest();sharder.add(row,data);validate(row) | |
| labels.write(json.dumps(row,separators=(',',':'))+'\n') | |
| media_rows.append({'sample_id':row['sample_id'],'media_archive':row['media_archive'],'media_member':row['media_member'],'bytes':len(data),'sha256':row['media_sha256'],'encoded_frame_SHA256':encoded_hashes}) | |
| if images: | |
| name=f'preview_{len(preview_rows)+1:02d}.gif';images[0].save(out/'previews'/name,save_all=True,append_images=images[1:],duration=180,loop=0) | |
| preview_rows.append({'path':'previews/'+name,'sample_id':row['sample_id'],'source_dataset':row['source_dataset'],'robot_body':row['robot_body'],'task':row['task'],'kind':'observed_simulation_frames_not_predictions'}) | |
| if number%1000==0:print(f'{split}: {number}/{len(selected)} observations packaged and image metadata checked',flush=True) | |
| sharder.close();shards+=sharder.shards | |
| dump(out/'SHARDS.json',{'shards':shards,'every_tar_member_independently_SHA256_verified':True}) | |
| with (out/'MEDIA_MANIFEST.jsonl').open('w') as f: | |
| for row in media_rows:f.write(json.dumps(row,separators=(',',':'))+'\n') | |
| dump(out/'previews/manifest.json',preview_rows) | |
| # Pick the exact publicly returned response version referenced by saved quality checks. | |
| reviews={} | |
| for line in (a.cot_run/'quality_reviews.jsonl').open(): | |
| r=json.loads(line);reviews[r['id']]=r | |
| candidates={} | |
| for line in (a.cot_run/'candidates.jsonl').open(): | |
| c=json.loads(line);r=reviews.get(c['id']) | |
| if c['id'] in by_id and r and hashlib.sha256(c['public_content'].encode()).hexdigest()==r['public_content_sha256']:candidates[c['id']]=c | |
| rationale_counts=collections.Counter();text_withheld=0 | |
| with (out/'data/public_rationales.jsonl').open('w') as f: | |
| for original,c in candidates.items(): | |
| text=c.get('reasoning') or '';row=by_id[original];review=reviews[original] | |
| if c.get('future_GT_sent_to_generator') is not False or not text or len(text)>20000 or TEXT_RISK.search(text) or original in text: | |
| text_withheld+=1;continue | |
| status='eligible_weak_draft' if review.get('eligible_for_weak_supervision') and c.get('machine_format_role_check_pass') else 'held_for_review' | |
| pub={'sample_id':row['sample_id'],'split':row['split'],'public_rationale':text,'status':status,'generation_source':'DeepSeek published API response','human_approved':False,'faithfulness_verified':False,'future_GT_sent_to_generator':False,'teacher_numeric_prediction_generated':False} | |
| f.write(json.dumps(pub,separators=(',',':'))+'\n');rationale_counts[status]+=1 | |
| report={'scope':'licensed RoboTwin2.0 and DexMimicGen prepared simulation observation/trajectory subset', | |
| 'counts':{k:len(v) for k,v in rows_by_split.items()},'by_body':source_counts, | |
| 'raw_media_records':len(media_rows),'public_rationales':sum(rationale_counts.values()),'rationale_quality_counts':dict(rationale_counts), | |
| 'rationales_withheld_for_sensitive_or_unverified_text':text_withheld,'excluded_unknown_license_sources':dict(excluded), | |
| 'source_observation_image_bytes_preserved':True,'all_image_frames_decoded_and_metadata_checked':True, | |
| 'image_EXIF_and_nonallowlisted_metadata_present':False,'original_IDs_paths_timestamps_account_API_metadata_exported':False, | |
| 'key_or_mapping_exported':False,'each_tar_and_member_readback_SHA256_verified':True, | |
| 'source_episode_groups_separate':True,'source_files_modified':False,'teacher_API_calls':0,'GPU_used':False, | |
| 'full_original_356GB_collection_published':False,'new_training_or_model_predictions':False} | |
| dump(out/'SANITIZATION_REPORT.json',report) | |
| print(json.dumps(report,ensure_ascii=False,indent=2),flush=True) | |
| if __name__=='__main__':main() | |