"""Build 50 clean / 50 paired illumination episodes; never alter the source.""" from __future__ import annotations import argparse from collections import Counter from concurrent.futures import ProcessPoolExecutor, as_completed import copy import hashlib import io import json import os from pathlib import Path import random import shutil import time os.environ.setdefault('OMP_NUM_THREADS', '1') os.environ.setdefault('OPENBLAS_NUM_THREADS', '1') os.environ.setdefault('MKL_NUM_THREADS', '1') import numpy as np from PIL import Image, ImageDraw import pyarrow as pa import pyarrow.parquet as pq from datasets import Features, Image as HFImage import lighting pa.set_cpu_count(1) pa.set_io_thread_count(1) CAMERAS = tuple('observation.images.' + c for c in lighting.CAMERAS) REINDEX = ('episode_index', 'index') def digest(path): with Path(path).open('rb') as f: return hashlib.file_digest(f, 'sha256').hexdigest() def write_json(path, data): Path(path).write_text(json.dumps(data, indent=2, ensure_ascii=False, allow_nan=False)+'\n') def write_jsonl(path, rows): Path(path).write_text(''.join(json.dumps(row, ensure_ascii=False, allow_nan=False)+'\n' for row in rows)) def read_jsonl(path): return [json.loads(line) for line in Path(path).read_text().splitlines() if line] def image_array(value): if value['bytes'] is None: raise ValueError('Expected embedded image bytes') with Image.open(io.BytesIO(value['bytes'])) as image: image.load() rgb = np.asarray(image.convert('RGB')) if rgb.shape != (224, 224, 3) or rgb.dtype != np.uint8: raise ValueError(f'Unexpected image {rgb.shape}/{rgb.dtype}') return rgb def histogram_add(hist, rgb): for c in range(3): hist[c] += np.bincount(rgb[...,c].ravel(), minlength=256) def image_stats(hist, frames): values = np.arange(256, dtype=np.float64)/255 count = hist.sum(1) mean = (hist*values).sum(1)/count var = np.maximum((hist*values**2).sum(1)/count-mean**2, 0) return {'min': [float(values[np.flatnonzero(row)[0]]) for row in hist], 'max': [float(values[np.flatnonzero(row)[-1]]) for row in hist], 'mean': mean.tolist(), 'std': np.sqrt(var).tolist(), 'count': [frames]} def numeric_stats(column): values = np.asarray(column.to_pylist(), dtype=np.float64) return {'min': values.min(0).tolist(), 'max': values.max(0).tolist(), 'mean': values.mean(0).tolist(), 'std': values.std(0).tolist(), 'count': [len(values)]} def reindex(table, episode, start): table = table.set_column(table.schema.get_field_index('episode_index'), 'episode_index', pa.array(np.full(table.num_rows, episode, np.int64))) table = table.set_column(table.schema.get_field_index('index'), 'index', pa.array(np.arange(start,start+table.num_rows,dtype=np.int64))) features = Features.from_arrow_schema(table.schema) for camera in CAMERAS: features[camera] = HFImage() return table.replace_schema_metadata(features.arrow_schema.metadata) def process_pair(job): root, source_root = Path(job['root']), Path(job['source_root']) source = job['source'] old = source['episode_index'] source_path = source_root/'data/chunk-000'/f'episode_{old:06d}.parquet' before = digest(source_path) assert before == source['parquet']['sha256'], 'Source parquet differs from recorded SHA256' table = pq.read_table(source_path) n = table.num_rows assert n == source['length'] assert table['frame_index'].to_pylist() == list(range(n)) assert set(table['episode_index'].to_pylist()) == {old} expected_original, expected_changed = ({c:hashlib.sha256() for c in CAMERAS} for _ in range(2)) original_hist, changed_hist = ({c:np.zeros((3,256),np.int64) for c in CAMERAS} for _ in range(2)) source_images = {c:table[c].to_pylist() for c in CAMERAS} changed_images = {c:[] for c in CAMERAS} stamps = np.asarray(table['source_timestamp_ns'].to_pylist(),np.int64) times = (stamps-stamps[0]).astype(np.float64)*1e-9 assert np.all(np.diff(times)>0) recipe = tuple(job['recipe']) changed_frames = {c:0 for c in CAMERAS} sample = None started = time.monotonic() for frame in range(n): raw = {c:image_array(source_images[c][frame]) for c in CAMERAS} altered = lighting.apply_at_time(raw, recipe, float(times[frame])) for c in CAMERAS: clean, aug = raw[c], altered[c] expected_original[c].update(clean.tobytes()) expected_changed[c].update(aug.tobytes()) histogram_add(original_hist[c],clean) histogram_add(changed_hist[c],aug) changed_frames[c] += int(not np.array_equal(clean,aug)) output = io.BytesIO() Image.fromarray(aug).save(output,format='PNG',compress_level=1) changed_images[c].append({'bytes':output.getvalue(),'path':None}) if frame == n//2: sample = (raw,altered) assert sum(changed_frames.values())>0 clean = reindex(table,job['pair_id'],job['clean_start']) augmented = table for c in CAMERAS: augmented = augmented.set_column(augmented.schema.get_field_index(c), c, pa.array(changed_images[c],type=table.schema.field(c).type)) augmented = reindex(augmented,job['pair_id']+50,job['augmented_start']) source_non_rgb = table.drop(list(CAMERAS)+list(REINDEX)).replace_schema_metadata(None) hashes, stats, decoded_counts = {}, {}, {} for kind, output, expected, hist in [('clean',clean,expected_original,original_hist), ('perturbed',augmented,expected_changed,changed_hist)]: episode = job['pair_id']+(50 if kind=='perturbed' else 0) relative = f'data/chunk-000/episode_{episode:06d}.parquet' path = root/relative if path.exists(): raise FileExistsError(path) pq.write_table(output,path,compression='zstd',row_group_size=256) reread = pq.read_table(path) assert reread.num_rows==n assert reread.drop(list(CAMERAS)+list(REINDEX)).replace_schema_metadata(None).equals(source_non_rgb) assert reread['episode_index'].to_pylist()==[episode]*n expected_start=job['augmented_start'] if kind=='perturbed' else job['clean_start'] assert reread['index'].to_pylist()==list(range(expected_start,expected_start+n)) for c in CAMERAS: decoded = hashlib.sha256() for record in reread[c].to_pylist(): decoded.update(image_array(record).tobytes()) assert decoded.hexdigest()==expected[c].hexdigest(), 'Decoded pixels differ after serialization' if kind=='clean': assert reread[c].equals(table[c]), 'Clean encoded image bytes changed' hashes[kind]={'path':relative,'sha256':digest(path),'bytes':path.stat().st_size, 'decoded_rgb_sha256':{c:h.hexdigest() for c,h in expected.items()}} episode_stats = {k:numeric_stats(reread[k]) for k in ('observation.state','action')} for c in CAMERAS: st=image_stats(hist[c],n) for key in ('min','max','mean','std'): st[key]=np.asarray(st[key]).reshape(3,1,1).tolist() episode_stats[c]=st stats[kind]={'episode_index':episode,'stats':episode_stats} decoded_counts[kind]=n*len(CAMERAS) assert digest(source_path)==before, 'Source was modified during build' preview=Image.new('RGB',(224*3,224*2+44),'white') draw=ImageDraw.Draw(preview) draw.text((8,6),f'Pair {job["pair_id"]:02d} | source ep {old} | {recipe[0]} | tier {recipe[1]}',fill='black') for i,c in enumerate(CAMERAS): preview.paste(Image.fromarray(sample[0][c]),(224*i,22)) preview.paste(Image.fromarray(sample[1][c]),(224*i,246)) preview.save(root/'provenance/previews'/f'pair_{job["pair_id"]:02d}.jpg',quality=90) return dict(pair_id=job['pair_id'],original_episode_id=old,source_basename=Path(source['source']).name, original_split='stage2_train',length=n,clean_episode_id=job['pair_id'],perturbed_episode_id=job['pair_id']+50, clean_global_start=job['clean_start'],perturbed_global_start=job['augmented_start'], recipe=dict(category=recipe[0],tier=recipe[1],seed=recipe[2],parameters=lighting.parameters(*recipe)), source_parquet_sha256=before,source_mcap_sha256=source['source_sha256'], source_mcap_sha256_evidence=source['source_sha256_evidence'],outputs=hashes,stats=stats, rgb_changed_frames=changed_frames,decoded_images=decoded_counts, non_rgb_equal=True,source_unchanged=True,seconds=time.monotonic()-started) def aggregate_stats(episodes): output={} for key in episodes[0]['stats']: values=[row['stats'][key] for row in episodes] counts=np.asarray([v['count'][0] for v in values],np.float64) total=counts.sum() mean=sum(n*np.asarray(v['mean']) for n,v in zip(counts,values))/total variance=sum(n*(np.asarray(v['std'])**2+(np.asarray(v['mean'])-mean)**2) for n,v in zip(counts,values))/total output[key]=dict(min=np.minimum.reduce([v['min'] for v in values]).tolist(), max=np.maximum.reduce([v['max'] for v in values]).tolist(),mean=mean.tolist(), std=np.sqrt(variance).tolist(),count=[int(total)]) return output def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--source',required=True,help='Original LeRobot v2.1 dataset directory') parser.add_argument('--split',required=True,help='Historical source split JSON') parser.add_argument('--output',default='TipDex-Data') parser.add_argument('--recipes',default=str(Path(__file__).resolve().parents[1]/'provenance/pairs.jsonl'),help='Released per-source recipes, including fixed seeds') parser.add_argument('--workers',type=int,default=2) args=parser.parse_args() if args.workers not in (1,2,3,4): raise ValueError('Use 1 to 4 CPU workers') root,src=Path(args.output),Path(args.source) if root.exists(): raise FileExistsError(f'Refuse to overwrite existing dataset: {root}') split=json.loads(Path(args.split).read_text()) rows=read_jsonl(src/'meta/episode_sources.jsonl') frequencies=Counter(row['source'] for row in rows) selected=sorted([row for row in rows if row['source'] in split['stage2_train'] and frequencies[row['source']]==1],key=lambda row:row['episode_index']) assert len(selected)==50 and len({r['source'] for r in selected})==50 assert not {r['source'] for r in selected}&set(split['stage2_dev']+split['final_eval']) assert all(split['episodes'][str(r['episode_index'])]=={k:r[k] for k in ('source','global_start','length')} for r in selected) assert sum(row['length'] for row in selected)==47086 root.mkdir(parents=True,exist_ok=False) for rel in ('data/chunk-000','meta','provenance/previews','code'): (root/rel).mkdir(parents=True) shutil.copy2(Path(__file__),root/'code/build_dataset.py') shutil.copy2(Path(lighting.__file__),root/'code/lighting.py') shutil.copy2(src/'meta/tasks.jsonl',root/'meta/tasks.jsonl') sidecars=[] for row in selected: relative=Path('meta/raw_streams')/Path(row['source']).stem source_folder=src/relative assert (source_folder/'tactile.parquet').is_file() for source_path in sorted(source_folder.rglob('*')): if source_path.is_file(): relative_path=source_path.relative_to(src) output_path=root/relative_path output_path.parent.mkdir(parents=True,exist_ok=True) source_hash=digest(source_path) shutil.copy2(source_path,output_path) assert digest(output_path)==source_hash==digest(source_path) sidecars.append(dict(path=str(relative_path),bytes=output_path.stat().st_size,sha256=source_hash)) assert len(sidecars)==450 write_json(root/'provenance/raw_sidecars.json',dict(files=sidecars,source_count=50,bytes=sum(p['bytes'] for p in sidecars))) tiers=[0]*6+[1]*3+[2] rng=random.Random(20261120) category_tiers={c:rng.sample(tiers,len(tiers)) for c in lighting.CATEGORIES} released_recipes={row['source_basename']:row['recipe'] for row in read_jsonl(Path(args.recipes))} jobs=[] cursor=0 for i,row in enumerate(selected): category=lighting.CATEGORIES[i%5] tier=category_tiers[category][i//5] recorded=released_recipes[Path(row['source']).name] assert (recorded['category'],recorded['tier']) == (category,tier) seed=int(recorded['seed']) jobs.append(dict(root=str(root),source_root=str(src),source=row,pair_id=i, clean_start=cursor,augmented_start=47086+cursor,recipe=(category,tier,seed))) cursor+=row['length'] selection=dict(source_dataset=src.name,original_sources=63,original_episodes=65, selected_sources=50,selected_frames=47086,final_episodes=100,final_frames=94172, selection_rule='Select all single-segment original MCAP sources in historical stage2_train; exclude its one split source (original episodes 6,7).', excluded_dev_source_count=8,excluded_final_eval_source_count=4, split_sha256=digest(args.split),source_info_sha256=digest(src/'meta/info.json'), lighting_sha256=digest(root/'code/lighting.py'),builder_sha256=digest(root/'code/build_dataset.py'), recipe_assignment='Original episode order; categories round-robin; each category has 6 mild,3 moderate,1 severe; shuffled tiers with Python Random(20261120); fixed seeds loaded from the released per-source recipes.', source_episode_ids=[r['episode_index'] for r in selected],cpu_workers=args.workers) write_json(root/'provenance/selection.json',selection) results=[] started=time.monotonic() with ProcessPoolExecutor(max_workers=args.workers) as pool: futures=[pool.submit(process_pair,job) for job in jobs] for future in as_completed(futures): result=future.result();results.append(result) print(json.dumps({'completed_pairs':len(results),'total_pairs':50,'pair_id':result['pair_id'], 'pair_seconds':round(result['seconds'],1),'elapsed_seconds':round(time.monotonic()-started,1)}),flush=True) results.sort(key=lambda row:row['pair_id']) episode_stats=sorted([r['stats'][kind] for r in results for kind in ('clean','perturbed')],key=lambda row:row['episode_index']) write_jsonl(root/'meta/episodes_stats.jsonl',episode_stats) write_json(root/'meta/stats.json',aggregate_stats(episode_stats)) episodes=[];sources=[] for r in results: for kind,ep,start in [('clean',r['clean_episode_id'],r['clean_global_start']),('perturbed',r['perturbed_episode_id'],r['perturbed_global_start'])]: episodes.append(dict(episode_index=ep,length=r['length'],tasks=['Move the egg into the box.'])) sources.append(dict(episode_index=ep,length=r['length'],global_start=start, source=r['source_basename'],original_episode_id=r['original_episode_id'], variant=kind,pair_id=r['pair_id'],historical_split='stage2_train', parquet=r['outputs'][kind],recipe=r['recipe'] if kind=='perturbed' else None)) write_jsonl(root/'meta/episodes.jsonl',sorted(episodes,key=lambda row:row['episode_index'])) write_jsonl(root/'meta/episode_sources.jsonl',sorted(sources,key=lambda row:row['episode_index'])) write_jsonl(root/'provenance/pairs.jsonl',[{k:v for k,v in r.items() if k!='stats'} for r in results]) info=json.loads((src/'meta/info.json').read_text()) info.update(total_episodes=100,total_frames=94172,total_videos=0,total_chunks=1,splits={'train':'0:100'}) info['tactile_raw_sidecars']='meta/raw_streams/{source_stem}/tactile.parquet retains every original packet and acquisition metadata for each selected source, including duplicate timestamps and packets beyond labeled frames. One unchanged sidecar set is shared by each clean/perturbed pair; all nine original raw numeric streams per selected source are bundled.' info['paired_illumination_dataset']=dict(clean_episodes='0:50',perturbed_episodes='50:100',pairs='provenance/pairs.jsonl',independent_source_recordings=50) write_json(root/'meta/info.json',info) readme='''--- language: - en tags: - robotics - lerobot - tactile - synthetic-data pretty_name: TipDex-Data task_categories: - robotics configs: - config_name: default data_files: - split: train path: data/chunk-000/*.parquet --- # TipDex-Data This dataset contains **50 original converted robot demonstration episodes and 50 synthetic RGB illumination variants**, totaling **100 episodes, 94,172 frames, and 50 independent source recordings**. Task: “Move the egg into the box.” Synthetic variants are derived observations paired with the original recorded actions; they are not additional physical demonstrations or proof of successful execution under changed lighting. ## Data and pairing - LeRobot v2.1 layout; all 100 episodes are in `train`. Episodes 0–49 are original; episode `i+50` is the perturbed counterpart of episode `i`. - Three embedded RGB views (`top`, `left_wrist`, `right_wrist`), each 224×224; no external videos are required. Original encoded image bytes are unchanged. Perturbed RGB is stored as lossless PNG. - Action: 13 measured right arm/hand joint coordinates. State: 19 coordinates. Tactile: 364 raw uint16 transport words, not a verified physical taxel/pressure map. - All original per-frame observations, actions, flags, tasks, frame indices and timestamps are preserved. Only `episode_index` and global `index` are renumbered; only RGB is perturbed in the derived episodes. - `provenance/pairs.jsonl` contains original source basenames, episode IDs, recipes, seeds, decoded RGB hashes and file hashes. `meta/episode_sources.jsonl` maps every output episode. - These 50 recordings are the single-segment sources in the historical training partition. The one split training source and all 8 development / 4 final-evaluation sources are excluded. Do not split paired variants or frames of the same source across train/evaluation. ## Synthetic perturbations Five categories contain 10 derived episodes each: low exposure, strong exposure, directional illumination, moving soft shadow / periodic exposure, and asymmetric camera illumination. Every category has 6 mild (0.25–1 EV magnitude), 3 moderate (1–2.5 EV), and 1 severe (2.5–4 EV) recipes. These are EV parameter-magnitude tiers, not calibrated image-distortion or task-difficulty scores. A fixed recipe and seed are used for each complete episode. Original source timestamps drive smooth temporal changes. Inverse sRGB, linear-domain exposure, clipping, and sRGB encoding follow the copied lighting code. Strong exposure may saturate pixels. Moving shadows are synthetic, not actual human occlusions. Some recipes intentionally preserve one or two camera views. The lighting implementation is reused from the 2026-11-19 experiment. This release materializes new complete-episode variants with the documented balanced assignment; it is not an export of the old anchor-feature cache. `code/build_dataset.py` records the deterministic selection and recipe assignment. ## Read the data ```python from pathlib import Path from datasets import load_dataset root = Path('/path/to/downloaded/dataset') ds = load_dataset('parquet', data_files={'train': str(root / 'data/chunk-000/*.parquet')})['train'] image = ds[0]['observation.images.top'] # PIL RGB image action = ds[0]['action'] ``` Alternatively, download the repository with `huggingface_hub.snapshot_download(repo_id=REPO_ID, repo_type='dataset')` and point a LeRobot v2.1-compatible reader to that root. Read `meta/info.json` for the original timestamp, action, camera alignment, and tactile validity semantics. FPS is nominally 30; retain the recorded timestamps for temporal analysis. The nine original raw numeric/command/tactile stream sidecars for each selected source are bundled unchanged under `meta/raw_streams/{source_stem}/` (450 files, shared by each pair). Raw MCAP files are not bundled. ## Validation `provenance/validation.json` reports the checks: 100 complete episodes; 50 one-to-one pairs; all 282,516 stored camera images fully decoded; clean image bytes unchanged; lossless perturbed pixels checked against the deterministic transform; all non-RGB payloads identical except the two index fields; no development/final-evaluation source overlap; source parquet SHA256 unchanged. Statistics are recalculated for state, action and RGB; image statistics use every pixel and population standard deviation. `provenance/sha256_manifest.json` inventories every other release file. The data has not been newly adjudicated for task success. Preserve the original validity flags. No new license is granted by this packaging operation; consult the data owner for reuse permission. ''' (root/'README.md').write_text(readme) validation=dict(status='passed',episodes=100,pairs=50,independent_sources=50,frames=94172, decoded_images=sum(sum(r['decoded_images'].values()) for r in results), all_non_rgb_payloads_equal=True,index_fields_reassigned=['episode_index','index'], original_image_bytes_unchanged=True,perturbed_decoded_pixels_match_transform=True, selected_source_parquet_hashes_match_original_metadata=True,source_hashes_unchanged=True, raw_sidecar_files=450,raw_sidecars_bytes=sum(p['bytes'] for p in sidecars),raw_sidecars_byte_identical=True, excluded_dev_and_final_eval=True,category_counts=dict(Counter(r['recipe']['category'] for r in results)), tier_counts_by_category={c:dict(Counter(str(r['recipe']['tier']) for r in results if r['recipe']['category']==c)) for c in lighting.CATEGORIES}, elapsed_seconds=time.monotonic()-started,versions=dict(numpy=np.__version__,pyarrow=pa.__version__)) assert validation['decoded_images']==282516 assert validation['category_counts']=={c:10 for c in lighting.CATEGORIES} assert all(counts=={'0':6,'1':3,'2':1} for counts in validation['tier_counts_by_category'].values()) assert len(list((root/'data/chunk-000').glob('*.parquet')))==100 write_json(root/'provenance/validation.json',validation) files=[{'path':str(p.relative_to(root)),'bytes':p.stat().st_size,'sha256':digest(p)} for p in sorted(root.rglob('*')) if p.is_file()] write_json(root/'provenance/sha256_manifest.json',{'algorithm':'sha256','excludes':['provenance/sha256_manifest.json'],'files':files}) print(json.dumps({'status':'COMPLETE','root':str(root),'file_count':len(files)+1,'bytes':sum(f['bytes'] for f in files),'validation':validation}),flush=True) if __name__=='__main__': main()