dagger / code /1027_run /merge_shards.py
yqi19's picture
Upload code/1027_run/merge_shards.py with huggingface_hub
dba700f verified
Raw History Blame Contribute Delete
2.47 kB
#!/usr/bin/env python3
"""Merge multiple shard collect_meta dirs into a single output dir.
Usage: merge_shards.py shard0/ shard1/ ... final_dir/ target_kept
"""
import json, os, sys, shutil, glob
*shard_dirs, final_dir, target_str = sys.argv[1:]
target = int(target_str)
os.makedirs(final_dir, exist_ok=True)
ep_out = os.path.join(final_dir, 'episodes')
vid_out = os.path.join(final_dir, 'videos')
os.makedirs(ep_out, exist_ok=True)
all_eps = []
kept_total = 0
n_attempted = 0
base_meta = None
for shard in shard_dirs:
meta_f = os.path.join(shard, 'collect_meta.json')
if not os.path.exists(meta_f):
print(f"[merge] no meta in {shard}, skipping")
continue
meta = json.load(open(meta_f))
if base_meta is None:
base_meta = {k: v for k, v in meta.items() if k not in ('episodes', 'n_kept', 'n_attempted')}
n_attempted += meta.get('n_attempted', 0)
for ep in meta.get('episodes', []):
if not ep.get('success', False) and ep.get('ep_index') is None:
continue # failed episode, skip
old_idx = ep.get('ep_index', kept_total)
new_idx = kept_total
# Copy episode npz
src_npz = os.path.join(shard, 'episodes', f'ep_{old_idx:06d}.npz')
dst_npz = os.path.join(ep_out, f'ep_{new_idx:06d}.npz')
if os.path.exists(src_npz):
shutil.copy2(src_npz, dst_npz)
# Copy videos
src_vid = os.path.join(shard, 'videos', str(old_idx))
dst_vid = os.path.join(vid_out, str(new_idx))
if os.path.isdir(src_vid):
shutil.copytree(src_vid, dst_vid, dirs_exist_ok=True)
ep2 = dict(ep)
ep2['ep_index'] = new_idx
all_eps.append(ep2)
kept_total += 1
if kept_total >= target:
break
if kept_total >= target:
break
if base_meta is None:
base_meta = {}
base_meta['n_kept'] = kept_total
base_meta['n_attempted'] = n_attempted
base_meta['episodes'] = all_eps
meta_out = os.path.join(final_dir, 'collect_meta.json')
json.dump(base_meta, open(meta_out + '.tmp', 'w'), indent=1, default=float)
os.replace(meta_out + '.tmp', meta_out)
# Copy instructions.json from first shard that has it
for shard in shard_dirs:
src = os.path.join(shard, 'instructions.json')
if os.path.exists(src):
shutil.copy2(src, os.path.join(final_dir, 'instructions.json'))
break
print(f"[merge] done: {kept_total} kept / {n_attempted} attempted -> {final_dir}")