Download scripts/compact_arms.py from kimyg119/Igris_Teleop_Box_Palletizing: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/kimyg119/Igris_Teleop_Box_Palletizing/resolve/main/scripts/compact_arms.py
- Command line
-
hf download hf://datasets/kimyg119/Igris_Teleop_Box_Palletizing/scripts/compact_arms.py
-
curl -L -o compact_arms.py https://huggingface.co/datasets/kimyg119/Igris_Teleop_Box_Palletizing/resolve/main/scripts/compact_arms.py
10.6 kB
| """Build a numerical-data delta from the full 15 Hz LeRobot v3 snapshot. | |
| Videos are never read, rewritten, or copied. Apply the output over a copy of | |
| the source snapshot and remove the obsolete files listed in deletion_paths.json. | |
| Run build, then verify, with the same --source and --output directories. | |
| """ | |
| import argparse | |
| import csv | |
| import json | |
| from copy import deepcopy | |
| from pathlib import Path | |
| import numpy as np | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| from lerobot.datasets.feature_utils import get_hf_features_from_features | |
| PARENT = 'fe7d322039f38fdcafa3aeae53d850157dbc1cef' | |
| JOINTS = [f'{side}_{joint}' for side in ['left', 'right'] for joint in | |
| ['shoulder_pitch','shoulder_roll','shoulder_yaw','elbow_pitch', | |
| 'wrist_yaw','wrist_roll','wrist_pitch']] | |
| ARM_KEYS = ['observation.state','action','observation.joint_tau_est_Nm'] | |
| WRENCH_KEYS = ['observation.tcp_wrench_left_est','observation.tcp_wrench_right_est'] | |
| REQUIRED = ['timestamp','frame_index','episode_index','index','task_index'] | |
| NUMERIC = ARM_KEYS + WRENCH_KEYS + REQUIRED | |
| def read(path): | |
| return json.loads(path.read_text()) | |
| def write(path, value): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| path.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n') | |
| def matrix(table, key): | |
| column = table[key].combine_chunks() | |
| return column.values.to_numpy().reshape(len(column), column.type.list_size) | |
| def selections(info): | |
| result = {} | |
| for key in ARM_KEYS: | |
| names = [n.removesuffix('.pos') for n in info['features'][key]['names']] | |
| assert len(names) == len(set(names)) == 31 | |
| result[key] = [names.index(joint) for joint in JOINTS] | |
| return result | |
| def projected_stats(stats, selection): | |
| return {key: value if key == 'count' else [value[i] for i in selection] | |
| for key, value in stats.items()} | |
| def build(source, output): | |
| info = read(source/'meta/info.json') | |
| assert info['fps'] == 15 and info['total_frames'] == 463905 | |
| selected = selections(info) | |
| cameras = [k for k,v in info['features'].items() if v['dtype']=='video' and k!='observation.images.realsense'] | |
| kept = NUMERIC+cameras | |
| definitions = {k:deepcopy(info['features'][k]) for k in kept} | |
| for key in ARM_KEYS: | |
| definitions[key]['shape'] = [14] | |
| definitions[key]['names'] = [info['features'][key]['names'][i] for i in selected[key]] | |
| info['features'] = definitions | |
| hf = get_hf_features_from_features(definitions) | |
| arrow_metadata = {b'huggingface':json.dumps({'info':{'features':hf.to_dict()}}).encode()} | |
| availability = {} | |
| frames = 0 | |
| for path in sorted((source/'data').rglob('*.parquet')): | |
| table = pq.read_table(path) | |
| indices = table['episode_index'].to_numpy() | |
| joint_valid = matrix(table,'observation.joint_valid')[:,selected['observation.state']] | |
| assert np.all(joint_valid == 1) | |
| torque_valid = matrix(table,'observation.joint_tau_valid')[:,selected['observation.joint_tau_est_Nm']] | |
| wrench_valid = matrix(table,'observation.tcp_wrench_valid') | |
| camera_indices = [read(source/'meta/info.json')['features']['observation.camera_valid']['names'].index(k) for k in cameras] | |
| camera_valid = matrix(table,'observation.camera_valid')[:,camera_indices] | |
| arrays = {} | |
| for key in NUMERIC: | |
| if key in ARM_KEYS: | |
| values = matrix(table,key)[:,selected[key]] | |
| arrays[key] = pa.FixedSizeListArray.from_arrays(pa.array(values.ravel()),14) | |
| else: | |
| arrays[key] = table[key] | |
| result = pa.table(arrays).replace_schema_metadata(arrow_metadata) | |
| target = output/path.relative_to(source) | |
| target.parent.mkdir(parents=True,exist_ok=True) | |
| with pq.ParquetWriter(target,result.schema,compression='zstd') as writer: | |
| for eid in np.unique(indices): | |
| rows = np.flatnonzero(indices == eid) | |
| tv = torque_valid[rows] | |
| assert np.all(tv == tv[0,0]) and tv[0,0] in (0,1) | |
| assert np.all(wrench_valid[rows] == tv[0,0]) | |
| cv = camera_valid[rows] | |
| assert np.all(cv == cv[0]) | |
| if not tv[0,0]: | |
| for key in [ARM_KEYS[2]]+WRENCH_KEYS: | |
| assert np.all(matrix(result,key)[rows] == 0) | |
| availability[int(eid)] = dict(has_torque=bool(tv[0,0]), | |
| available_cameras=[k for k,v in zip(cameras,cv[0]) if v]) | |
| assert np.array_equal(rows,np.arange(rows[0],rows[-1]+1)) | |
| writer.write_table(result.slice(int(rows[0]),len(rows)),row_group_size=len(rows)) | |
| frames += len(table) | |
| assert frames == 463905 and len(availability) == 834 | |
| assert sum(v['has_torque'] for v in availability.values()) == 796 | |
| write(output/'meta/info.json',info) | |
| stats = read(source/'meta/stats.json') | |
| stats = {k:projected_stats(stats[k],selected[k]) if k in ARM_KEYS else stats[k] for k in kept} | |
| write(output/'meta/stats.json',stats) | |
| with (source/'episode_mapping.csv').open() as f: | |
| environments = {int(row['episode_index']):row['environment'] for row in csv.DictReader(f)} | |
| ep_paths = sorted((source/'meta/episodes').rglob('*.parquet')) | |
| for path in ep_paths: | |
| updated = [] | |
| for row in pq.read_table(path).to_pylist(): | |
| result = {} | |
| for key,value in row.items(): | |
| if key.startswith('source/'): | |
| continue | |
| if key.startswith('stats/'): | |
| _,feature,stat = key.split('/') | |
| if feature not in kept: | |
| continue | |
| if feature in ARM_KEYS and stat != 'count': | |
| value = [value[i] for i in selected[feature]] | |
| result[key] = value | |
| eid = row['episode_index'] | |
| result.update(availability[eid], environment=environments[eid]) | |
| updated.append(result) | |
| target = output/path.relative_to(source) | |
| target.parent.mkdir(parents=True,exist_ok=True) | |
| pq.write_table(pa.Table.from_pylist(updated),target,compression='zstd',row_group_size=100) | |
| obsolete = ['meta/sessions.parquet'] + [p.relative_to(source).as_posix() for p in sorted((source/'scripts').glob('*.py')) if p.name != 'make_overview.py'] | |
| obsolete += [p.relative_to(source).as_posix() for p in sorted((source/'videos/observation.images.realsense').rglob('*.mp4'))] | |
| write(output/'deletion_paths.json',obsolete) | |
| summary = read(source/'summary.json') | |
| summary.update(source_revision=PARENT,joint_axes=14,numeric_signal_columns=5, | |
| standard_index_columns=5,tactile_representation='heatmap images only', | |
| video_files_modified=0,torque_availability='meta/episodes.has_torque') | |
| write(output/'summary.json',summary) | |
| print(json.dumps(dict(episodes=834,frames=frames,features=len(kept),frame_columns=NUMERIC)),flush=True) | |
| def verify(source, output): | |
| info = read(output/'meta/info.json') | |
| source_info = read(source/'meta/info.json') | |
| stats = read(output/'meta/stats.json') | |
| cameras = [k for k,v in source_info['features'].items() if v['dtype']=='video' and k!='observation.images.realsense'] | |
| assert set(info['features']) == set(NUMERIC+cameras) == set(stats) | |
| for key in ARM_KEYS: | |
| assert info['features'][key]['shape'] == [14] | |
| assert [n.removesuffix('.pos') for n in info['features'][key]['names']] == JOINTS | |
| for stat,value in stats[key].items(): | |
| assert len(value) == (1 if stat == 'count' else 14) | |
| for key in cameras: | |
| assert info['features'][key] == source_info['features'][key] | |
| ep_rows = {r['episode_index']:r for path in (output/'meta/episodes').rglob('*.parquet') | |
| for r in pq.read_table(path).to_pylist()} | |
| total = 0 | |
| torque_frames = 0 | |
| for path in sorted((source/'data').rglob('*.parquet')): | |
| old = pq.read_table(path) | |
| new = pq.read_table(output/path.relative_to(source)) | |
| assert new.column_names == NUMERIC | |
| assert len(new) == len(old) | |
| embedded = json.loads(new.schema.metadata[b'huggingface'])['info']['features'] | |
| assert set(embedded) == set(NUMERIC) | |
| for key in NUMERIC: | |
| if key in ARM_KEYS: | |
| np.testing.assert_array_equal(matrix(new,key),matrix(old,key)[:,15:29]) | |
| else: | |
| assert new[key].equals(old[key]),key | |
| np.testing.assert_array_equal(new['index'].to_numpy(),np.arange(total,total+len(new))) | |
| eids = new['episode_index'].to_numpy() | |
| for eid in np.unique(eids): | |
| rows = np.flatnonzero(eids == eid) | |
| episode = ep_rows[int(eid)] | |
| assert episode['length'] == len(rows) | |
| assert episode['has_torque'] == bool(matrix(old,'observation.tcp_wrench_valid')[rows[0],0]) | |
| assert not any(k.startswith('source/') for k in episode) | |
| for name in [k for k in episode if k.startswith('stats/')]: | |
| assert name.split('/')[1] in info['features'] | |
| for key in ARM_KEYS+WRENCH_KEYS: | |
| values = matrix(new,key)[rows].astype(np.float64) | |
| assert np.isfinite(values).all() | |
| np.testing.assert_allclose(values.mean(axis=0),episode[f'stats/{key}/mean'],rtol=1e-6,atol=1e-7) | |
| if not episode['has_torque'] and key not in ARM_KEYS[:2]: | |
| assert np.all(values==0) | |
| torque_frames += len(rows)*episode['has_torque'] | |
| total += len(new) | |
| assert total == 463905 and len(ep_rows) == 834 and torque_frames == 431172 | |
| report = dict(passed=True,source_revision=PARENT,episodes=834,frames=total, | |
| fps=15,arm_joint_order=JOINTS,frame_columns=NUMERIC,numeric_signal_columns=5, | |
| required_index_columns=5,video_features=cameras,video_files_modified=0, | |
| exact_retained_value_comparison=True,episode_statistics_checked=True, | |
| torque_episodes=796,torque_frames=torque_frames,missing_torque_episodes=38, | |
| missing_torque_frames=total-torque_frames) | |
| write(output/'validation.json',report) | |
| print(json.dumps(report,indent=2),flush=True) | |
| if __name__ == '__main__': | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('action',choices=['build','verify']) | |
| parser.add_argument('--source',type=Path,required=True) | |
| parser.add_argument('--output',type=Path,required=True) | |
| args=parser.parse_args() | |
| {'build':build,'verify':verify}[args.action](args.source,args.output) | |