File size: 27,757 Bytes
adf2e22
 
 
 
 
 
 
 
 
 
 
 
 
8ae64da
adf2e22
 
 
8ae64da
adf2e22
 
 
 
 
 
 
72e49c9
 
 
 
 
 
 
adf2e22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae64da
 
 
adf2e22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72e49c9
adf2e22
 
 
72e49c9
adf2e22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae64da
 
adf2e22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ae64da
 
adf2e22
 
 
 
 
 
 
8ae64da
adf2e22
 
 
 
 
 
8ae64da
 
 
 
adf2e22
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""Selective official benchmark examples. Run: prepare, download, render, package, publish.
The same implementation supports ReflexBench and DynamicVLA using the workspace name.
"""
from pathlib import Path
import ast, collections, concurrent.futures as cf, hashlib, io, json, math, shutil, subprocess, sys, time
from fractions import Fraction
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import pyarrow as pa
import pyarrow.parquet as pq

ROOT=Path(__file__).resolve().parents[1]
NAME=json.loads((ROOT/'provenance/source.json').read_text(encoding='utf-8'))['benchmark'] if (ROOT/'provenance/source.json').exists() else ROOT.name
REFLEX=NAME=='ReflexBench'
REPO='cyx337/ReflexBench_dataset' if REFLEX else 'hzxie/DOM'
DEST=f'Travor278/{NAME}-Task-Examples'
WORK=ROOT/'work';OUT=ROOT if (ROOT/'provenance/source.json').exists() else ROOT/'dataset'
CODE=WORK/'official-code'
GITHUB='LxRoboticsLab/ReflexBench' if REFLEX else 'hzxie/DynamicVLA'
SESSION=requests.Session()
SESSION.mount('https://',HTTPAdapter(max_retries=Retry(total=4,backoff_factor=.6,status_forcelist=[429,500,502,503,504])))

def read(p):return json.loads(p.read_text(encoding='utf-8'))
def write(p,x):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(json.dumps(x,indent=2,ensure_ascii=False),encoding='utf-8')
def readable_instruction(meta):
    obj=meta['objects'][0];obj_phrase=obj if obj.lower().startswith(('the ','all ')) else 'the '+obj
    if meta['task']=='pick':return f'Pick up {obj_phrase}.'
    container=meta.get('containers',['target container'])[0]
    container_phrase=container if container.lower().startswith('the ') else 'the '+container
    pronoun='them' if 'set of objects' in obj.lower() else 'it'
    return f'Pick up {obj_phrase} and place {pronoun} in/on {container_phrase}.'
def url(p):return f'https://huggingface.co/datasets/{REPO}/resolve/{SOURCE_REV}/{p}'
def download_file(p,dst):
    if dst.exists():return
    dst.parent.mkdir(parents=True,exist_ok=True)
    with SESSION.get(url(p),stream=True,timeout=(20,120)) as r:
        r.raise_for_status()
        with dst.with_suffix(dst.suffix+'.part').open('wb') as f:
            for b in r.iter_content(1024*1024):f.write(b)
    dst.with_suffix(dst.suffix+'.part').replace(dst)

class RangeReader(io.RawIOBase):
    """Seekable HTTP range reader: no full video-shard download or hidden HF cache."""
    def __init__(self,path,size,block=262144):
        self.path=path;self.size=size;self.block=block;self.pos=0;self.cache=collections.OrderedDict();self.transferred=0
    def readable(self):return True
    def seekable(self):return True
    def tell(self):return self.pos
    def seek(self,offset,whence=0):
        self.pos=offset if whence==0 else self.pos+offset if whence==1 else self.size+offset
        if self.pos<0:raise ValueError('negative seek')
        return self.pos
    def read(self,n=-1):
        if n<0:n=self.size-self.pos
        n=min(n,self.size-self.pos);out=[]
        while n>0:
            index=self.pos//self.block
            if index not in self.cache:
                start=index*self.block;end=min(start+self.block,self.size)-1
                r=SESSION.get(url(self.path),headers={'Range':f'bytes={start}-{end}'},timeout=(20,90));r.raise_for_status()
                if r.status_code!=206 or not r.headers.get('Content-Range','').startswith(f'bytes {start}-'):
                    raise ValueError('Source did not honor bounded HTTP range')
                self.cache[index]=r.content;self.transferred+=len(r.content)
                if len(self.cache)>24:self.cache.popitem(last=False)
            b=self.cache[index];offset=self.pos%self.block;amount=min(n,len(b)-offset)
            if amount<=0:raise EOFError('truncated HTTP range')
            out.append(b[offset:offset+amount]);self.pos+=amount;n-=amount
        return b''.join(out)

def lookup_jsonl(path,target,field,size):
    """Locate a sorted metadata record using small byte ranges, retaining only matched rows."""
    low=0;high=size;low_id=0;high_id=(207306 if field=='episode_index' else 140932)
    for attempt in range(22):
        guess=int(low+(high-low)*max(0,min(1,(target-low_id)/max(1,high_id-low_id))))
        start=max(0,min(size-131072,guess-32768));end=min(size-1,start+131071)
        r=SESSION.get(url(path),headers={'Range':f'bytes={start}-{end}'},timeout=60);r.raise_for_status();assert r.status_code==206
        raw=r.content;position=start;records=[]
        for line in raw.splitlines(keepends=True):
            try:
                row=json.loads(line);records.append((row[field],position,row))
            except (ValueError,KeyError):pass
            position+=len(line)
        assert records
        for index,pos,row in records:
            if index==target:return row
        if target<records[0][0]:high=records[0][1];high_id=records[0][0]
        elif target>records[-1][0]:low=records[-1][1];low_id=records[-1][0]
        else:raise ValueError(f'Missing official metadata record {field}={target}')
    raise ValueError(f'Lookup failed: {path} {target}')

def keep_source(path):
    dst=OUT/'reference'/path;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(CODE/path,dst)

def prepare():
    if all((OUT/'provenance'/name).exists() for name in ['source.json','tasks.json','samples.json']):
        print('Using retained, source-pinned selected manifests; no new source metadata download is needed.',flush=True)
        return
    from huggingface_hub import HfApi
    api=HfApi();info=api.dataset_info(REPO);global SOURCE_REV;SOURCE_REV=info.sha
    code_rev=subprocess.check_output(['git','-C',str(CODE),'rev-parse','HEAD'],text=True).strip()
    tasks=[];samples=[]
    if REFLEX:
        table=pq.read_table(WORK/'episodes-file-000.parquet')
        columns=[c for c in table.column_names if not c.startswith('stats/')]
        eps=table.select(columns).to_pylist();official=pq.read_table(WORK/'tasks.parquet').to_pylist()
        keys=['ball_catching','conveyor_belt_pick_and_place','whack_a_mole','rolling_ball_interception','ball_throwing','rotating_peg_insertion']
        descriptions=['Catch a launched ball with a held container.','Pick from the moving conveyor and release into the bin.','Strike the active mole using the closed gripper during its popup window.','Intercept the ball or orange rolling down the ramp.','Throw the pre-grasped ball into the target bin.','Time peg insertion into the moving hole of a rotating disc.']
        rules=[
            'Episode success is task_phase == 4. The ball must remain in the virtual catch zone below the end effector for the configured consecutive-step threshold.',
            'Success requires the object inside the bin in environment-local coordinates: x in [-0.2,0.2], y in [-0.6,-0.3], z in [0.0,0.08] m.',
            'Unified evaluation success is valid_hits > 0. A valid hit requires proximity to the active mole, closed gripper and the configured dwell. Current eval profile uses 2.0 s popup, 0.3 s gap, 0 s initial delay and 3.0 s evaluation length. Completing the window schedule alone is not success.',
            'Episode success is task_phase == 4. The rolling object must stay in the virtual catch zone for the configured hold threshold.',
            'Success is task_phase == 2, meaning the ball entered the target bin. Documentation bounds relative to bin center: |x-cx| <= 0.13, |y-cy| <= 0.09, z in [0.02,0.18] m.',
            'Success is task_phase == 4. Peg tip enters the hole within its radius tolerance, descends at least 0.02 m below the disc surface, and holds for at least 5 control steps (task README).']
        profiles_source=(CODE/'scripts/evaluation/task_profiles.py').read_text(encoding='utf-8')
        profiles=next(ast.literal_eval(n.value) for n in ast.parse(profiles_source).body if isinstance(n,ast.AnnAssign) and getattr(n.target,'id','')=='TASK_PROFILES')
        for item,key,desc,rule in zip(official,keys,descriptions,rules):
            index=item['task_index'];local=[e for e in eps if e['tasks']==[item['task']]]
            relative=f'source/reflexbench/reflexbench/tasks/manager_based/{key}/README.md'
            task=dict(task_index=index,key=key,name=key.replace('_',' ').title(),category='Reaction-critical',instruction=item['task'],description=desc,success_rule=rule,profile=profiles[key],official_gym_id=profiles[key]['gym_id'],doc_url=f'https://github.com/{GITHUB}/blob/{code_rev}/{relative}',published_episode_count=len(local))
            tasks.append(task);keep_source(relative)
            for j in [0,len(local)//2,len(local)-1]:
                ep=local[j];eid=ep['episode_index'];views=[]
                for camera,label in [('fixed_cam','FIXED CAMERA'),('wrist_cam','WRIST CAMERA')]:
                    prefix=f'videos/observation.images.{camera}'
                    path=f"{prefix}/chunk-{ep[prefix+'/chunk_index']:03d}/file-{ep[prefix+'/file_index']:03d}.mp4"
                    obj=api.get_paths_info(REPO,[path],repo_type='dataset',revision=SOURCE_REV)[0]
                    views.append(dict(camera=camera,label=label,path=f'media/{key}/episode_{eid:06d}/{camera}.mp4',source_path=path,source_bytes=obj.size,from_timestamp=ep[prefix+'/from_timestamp'],to_timestamp=ep[prefix+'/to_timestamp']))
                samples.append(dict(task_index=index,task_key=key,episode_index=eid,frame_count=ep['length'],fps=25,instruction=item['task'],metadata=ep,views=views,trajectory_path=f'trajectories/{key}/episode_{eid:06d}.parquet',composite_path=f'media/{key}/episode_{eid:06d}/synchronized.mp4',preview_path=f'media/{key}/episode_{eid:06d}/preview.jpg'))
        for f in ['scripts/evaluation/task_profiles.py','scripts/data_collection/task_prompts.py']:keep_source(f)
        shutil.copy2(WORK/'tasks.parquet',OUT/'provenance'/'official_tasks.parquet')
        note='Six official task_index values 0–5. Single Franka arm; only fixed_cam and wrist_cam exist. Do not relabel the wrist as left/right. Success rules describe evaluation, not an unprovided per-demo score.'
    else:
        # Metadata-only range sampling. Two episodes from each distant window.
        windows={'long_horizon':['episode-window-0.json'], 'pick':['episode-window-0.08.json','episode-window-0.3.json','episode-window-0.42.json'],'place':['episode-window-0.54.json','episode-window-0.78.json','episode-window-0.999.json']}
        selected=[]
        for kind,files in windows.items():
            for filename in files:
                xs=read(WORK/filename)
                positions=[0,200,400,600,800,1000] if kind=='long_horizon' else [50,len(xs)-51]
                selected.extend(xs[i] for i in positions)
        for ep in selected:
            eid=ep['episode_index'];path=f'data/chunk-{eid//1000:03d}/episode_{eid:06d}.parquet';local=WORK/f'episode_{eid:06d}.parquet';download_file(path,local);table=pq.read_table(local);ids=set(table['task_index'].to_pylist());assert len(ids)==1;index=ids.pop();assert set(table['episode_index'].to_pylist())=={eid};assert table.num_rows==ep['length']
            task_meta=lookup_jsonl('meta/tasks.jsonl',index,'task_index',63111962);assert task_meta['task']==ep['tasks'];meta=json.loads(ep['tasks']);kind=meta['task'];cam=lookup_jsonl('meta/camera.jsonl',eid,'episode_index',173353120)
            obj=meta['objects'][0];container=meta.get('containers',[''])[0]
            instruction=readable_instruction(meta)
            # This deterministic sentence is a readable rendering, not a recorded literal prompt.
            rule='Success requires object-to-end-effector distance < tolerance and end-effector-to-configured-goal distance < tolerance. The current default tolerance is 0.015 m; per-scene overrides may differ.' if kind=='pick' else 'Success requires ALL target objects to satisfy the container-relative geometric placement check, and the end effector to return within tolerance of the configured goal. Current default return tolerance is 0.015 m; per-scene overrides may differ.'
            key=f'task_{index:06d}'
            task=dict(task_index=index,key=key,name=f'{kind.replace("_"," ").title()} · {container if kind=="long_horizon" else obj}',category={'pick':'Pick','place':'Place','long_horizon':'Long-Horizon'}[kind],instruction=instruction,instruction_note='根据官方结构化 instruction 和首个别名确定性呈现;原记录没有保存采集时使用的具体随机语言变体,完整别名见下方元数据。',instruction_metadata=meta,description=f'Official DOM simulation scenario {cam["filename"]}. Object/container aliases are preserved in the metadata.',success_rule=rule,doc_url=f'https://github.com/{GITHUB}/blob/{code_rev}/simulations/configs/termination_cfg.py',source_filename=cam['filename'],published_episode_count=None)
            if index not in {t['task_index'] for t in tasks}:tasks.append(task)
            views=[dict(camera=c,label=label,path=f'media/{key}/episode_{eid:06d}/{c}.mp4',source_path=f'videos/chunk-{eid//1000:03d}/observation.images.{c}/episode_{eid:06d}.mp4') for c,label in [('opst_cam','OPPOSITE CAMERA'),('wrist_cam','WRIST CAMERA'),('side_cam','SIDE CAMERA')]]
            samples.append(dict(task_index=index,task_key=key,episode_index=eid,frame_count=ep['length'],fps=25,instruction=instruction,instruction_metadata=meta,official_task_record=task_meta,camera_metadata=cam,source_filename=cam['filename'],views=views,trajectory_source_path=path,trajectory_path=f'trajectories/{key}/episode_{eid:06d}.parquet',composite_path=f'media/{key}/episode_{eid:06d}/synchronized.mp4',preview_path=f'media/{key}/episode_{eid:06d}/preview.jpg'))
            print(f'Mapped {kind} task_index={index} episode_index={eid} ({cam["filename"]})',flush=True)
        for f in ['simulations/configs/termination_cfg.py','utils/instruction_generator.py','simulations/helpers.py','simulations/configs/sim_cfg.yaml']:keep_source(f)
        note='DOM has 3 task families, not 3 task_index values: 140,932 structured instruction IDs and 207,306 episodes. This subset selects 6 demonstrations per family (18 total), preserving actual task_index/episode_index and structured instructions. All 3 published cameras are single-arm cameras: opposite, wrist, side, not top/left/right arms.'
    keep_source('LICENSE');keep_source('README.md')
    shutil.copy2(CODE/'LICENSE',OUT/'LICENSE')
    write(OUT/'provenance/tasks.json',tasks);write(OUT/'provenance/samples.json',samples)
    source=dict(benchmark=NAME,repo_id=REPO,revision=SOURCE_REV,code_repository=GITHUB,code_revision=code_rev,note=note,date='2026-10-03',video_policy='Complete selected episodes, converted to browser-friendly H.264 MP4 at original 25 FPS. No generated simulation rollouts.',actual_episode_score='Not published in released LeRobot features; null, not assumed successful.',episode_selection='First/middle/last episode per official task' if REFLEX else 'Two episodes from three spaced metadata windows for pick/place, six spaced long-horizon scenarios.',camera_order=[v['camera'] for v in samples[0]['views']])
    write(OUT/'provenance/source.json',source);shutil.copy2(WORK/'info.json',OUT/'provenance/official_info.json');print(note,flush=True)

def encode_frames(frames,path):
    import av
    path.parent.mkdir(parents=True,exist_ok=True)
    with av.open(str(path),'w') as output:
        stream=None;count=0
        for frame in frames:
            if stream is None:
                stream=output.add_stream('libx264',rate=25);stream.width=frame.width;stream.height=frame.height;stream.pix_fmt='yuv420p';stream.options={'crf':'18','preset':'fast'}
            frame=frame.reformat(format='yuv420p');frame.pts=count;frame.time_base=Fraction(1,25)
            for packet in stream.encode(frame):output.mux(packet)
            count+=1
        if stream is None:raise ValueError('No frames extracted')
        for packet in stream.encode():output.mux(packet)
    return count

def download():
    import av
    source=read(OUT/'provenance/source.json');samples=read(OUT/'provenance/samples.json');summary=[]
    if REFLEX:
        path='data/chunk-000/file-000.parquet';download_file(path,WORK/'trajectories.parquet');data=pq.read_table(WORK/'trajectories.parquet')
        for s in samples:
            table=data.filter(pa.compute.equal(data['episode_index'],s['episode_index']));assert table.num_rows==s['frame_count'];assert set(table['task_index'].to_pylist())=={s['task_index']};target=OUT/s['trajectory_path'];target.parent.mkdir(parents=True,exist_ok=True);pq.write_table(table,target)
        for view_index in range(2):
            model=samples[0]['views'][view_index];reader=RangeReader(model['source_path'],model['source_bytes']);container=av.open(reader);stream=container.streams.video[0]
            for s in sorted(samples,key=lambda s:s['episode_index']):
                view=s['views'][view_index];target=OUT/view['path']
                if target.exists():continue
                start=view['from_timestamp'];container.seek(int(start/stream.time_base),stream=stream,backward=True)
                def frames():
                    found=0
                    for f in container.decode(stream):
                        if f.time+0.00001<start:continue
                        if found>=s['frame_count']:break
                        yield f;found+=1
                    assert found==s['frame_count'],(s['episode_index'],found,s['frame_count'])
                n=encode_frames(frames(),target);view['output_sha256']=hashlib.sha256(target.read_bytes()).hexdigest();print('Extracted',view['camera'],s['episode_index'],n,'frames',flush=True)
            container.close();summary.append({'source_path':model['source_path'],'source_shard_size':reader.size,'range_bytes_received':reader.transferred})
    else:
        def run(s):
            cached_trajectory=WORK/f"episode_{s['episode_index']:06d}.parquet"
            download_file(s['trajectory_source_path'],cached_trajectory)
            target=OUT/s['trajectory_path'];target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(WORK/f"episode_{s['episode_index']:06d}.parquet",target)
            for v in s['views']:
                original=WORK/f"{s['episode_index']:06d}-{v['camera']}.mp4";download_file(v['source_path'],original)
                dst=OUT/v['path'];dst.parent.mkdir(parents=True,exist_ok=True)
                if not dst.exists():
                    subprocess.run(['ffmpeg','-v','error','-y','-i',str(original),'-c:v','libx264','-crf','18','-preset','fast','-pix_fmt','yuv420p','-movflags','+faststart',str(dst)],check=True,capture_output=True)
                v['source_sha256']=hashlib.sha256(original.read_bytes()).hexdigest();v['source_bytes']=original.stat().st_size;v['output_sha256']=hashlib.sha256(dst.read_bytes()).hexdigest()
            print('Downloaded/transcoded',s['episode_index'],flush=True)
        with cf.ThreadPoolExecutor(max_workers=4) as ex:list(ex.map(run,samples))
        summary=[dict(source_video_files=sum(len(s['views']) for s in samples),source_video_bytes=sum(v['source_bytes'] for s in samples for v in s['views']))]
    write(OUT/'provenance/samples.json',samples);write(OUT/'provenance/download_report.json',dict(details=summary,whole_repo_downloaded=False,assets_downloaded=False,checkpoints_downloaded=False))

def render():
    from PIL import Image,ImageDraw
    samples=read(OUT/'provenance/samples.json');n=len(samples[0]['views']);labels=Image.new('RGB',(320*n,28),'#14251e');draw=ImageDraw.Draw(labels)
    for i,v in enumerate(samples[0]['views']):draw.text((i*320+10,8),v['label'],fill='white')
    label_path=WORK/'labels.png';labels.save(label_path)
    def run(s):
        target=OUT/s['composite_path'];target.parent.mkdir(parents=True,exist_ok=True)
        if not target.exists():
            height=320 if REFLEX else 240;cmd=['ffmpeg','-v','error','-y']
            for v in s['views']:cmd+=['-i',str(OUT/v['path'])]
            cmd+=['-loop','1','-i',str(label_path)]
            filters=';'.join(f'[{i}:v]scale=320:{height},setsar=1[c{i}]' for i in range(n))+f';'+''.join(f'[c{i}]' for i in range(n))+f'hstack=inputs={n}[v];[{n}:v]format=yuv420p[l];[l][v]vstack=inputs=2:shortest=1[out]'
            cmd+=['-filter_complex',filters,'-map','[out]','-c:v','libx264','-crf','21','-preset','fast','-pix_fmt','yuv420p','-frames:v',str(s['frame_count']),'-r','25','-movflags','+faststart',str(target)];subprocess.run(cmd,check=True,capture_output=True)
        subprocess.run(['ffmpeg','-v','error','-y','-i',str(target),'-frames:v','1','-q:v','2',str(OUT/s['preview_path'])],check=True,capture_output=True)
    with cf.ThreadPoolExecutor(max_workers=3) as ex:list(ex.map(run,samples))
    checks=[]
    for s in samples:
        table=pq.read_table(OUT/s['trajectory_path']);assert table.num_rows==s['frame_count'];assert set(table['task_index'].to_pylist())=={s['task_index']}
        frames=[]
        for path in [v['path'] for v in s['views']]+[s['composite_path']]:
            r=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=codec_name,width,height,nb_frames,duration','-of','json',str(OUT/path)],text=True))['streams'][0]
            assert r['codec_name']=='h264' and int(r['nb_frames'])==s['frame_count'],(path,r,s['frame_count']);frames.append(dict(path=path,**r))
        checks.append(dict(task_index=s['task_index'],episode_index=s['episode_index'],videos=frames))
    write(OUT/'provenance/validation.json',dict(passed=True,episodes=len(samples),checks=checks));print('Verified full frame counts, task IDs and H.264 MP4:',len(samples),'episodes',flush=True)

def package():
    import yaml
    from datasets import Dataset,Features,Value,Video,Image
    tasks=read(OUT/'provenance/tasks.json');samples=read(OUT/'provenance/samples.json');source=read(OUT/'provenance/source.json');rows=[]
    for s in samples:
        t=next(t for t in tasks if t['task_index']==s['task_index'])
        row=dict(task_index=s['task_index'],task_name=t['name'],category=t['category'],episode_index=s['episode_index'],synchronized= {'path':f'hf://datasets/{DEST}@main/'+s['composite_path'],'bytes':None})
        for v in s['views']:row[v['camera']]={'path':f'hf://datasets/{DEST}@main/'+v['path'],'bytes':None}
        row.update(instruction=s['instruction'],instruction_metadata=json.dumps(s.get('instruction_metadata'),ensure_ascii=False),success_rule=t['success_rule'],actual_episode_success=None,frame_count=s['frame_count'],fps=25,duration_seconds=s['frame_count']/25,source_repo=REPO,source_revision=source['revision'],trajectory_url=f'https://huggingface.co/datasets/{DEST}/resolve/main/'+s['trajectory_path'],official_doc=t['doc_url'],source_filename=s.get('source_filename',''),camera_metadata=json.dumps(s.get('camera_metadata'),ensure_ascii=False))
        rows.append(row)
    video_columns=['synchronized']+source['camera_order'];features=Features({k:Video(decode=False) if k in video_columns else Value('int64') if k in ['task_index','episode_index','frame_count','fps'] else Value('float64') if k=='duration_seconds' else Value('bool') if k=='actual_episode_success' else Value('string') for k in rows[0]})
    ds=Dataset.from_list(rows,features=features);(OUT/'data').mkdir(exist_ok=True);configs=[]
    def subset(name,indices,default=False):
        p=f'data/{name}.parquet';ds.select(indices).to_parquet(str(OUT/p),batch_size=32);entry=dict(config_name=name,data_files=[dict(split='examples',path=p)])
        if default:entry['default']=True
        configs.append(entry)
    subset('all',list(range(len(rows))),True)
    for t in tasks:subset(f"task_{t['task_index']:06d}",[i for i,r in enumerate(rows) if r['task_index']==t['task_index']])
    for category in sorted({t['category'] for t in tasks}):subset(category.lower().replace('-','_'),[i for i,r in enumerate(rows) if r['category']==category])
    header=dict(language=['en','zh'],license='other',pretty_name=NAME+' Simulation Task Examples',configs=configs,tags=['robotics','video','simulation'])
    if REFLEX:header.update(license_name='upstream-reflexbench-terms',license_link='LICENSE')
    if not REFLEX:header.update(license_name='slab-license',license_link='LICENSE')
    browser=f'https://travor278-{NAME.lower()}-task-examples.static.hf.space'
    lines=['---',yaml.safe_dump(header,sort_keys=False,allow_unicode=True).rstrip(),'---',f'# {NAME} Simulation Task Examples',f'\n[打开 MP4 任务浏览页]({browser}/?task={tasks[0]["task_index"]})', '\n'+source['note'],
        '\n所有示例是完整 H.264 MP4。单臂相机保留官方名称:'+ ' / '.join(source['camera_order'])+'。每条有同步合并视频、各路原视频与官方动作/状态 Parquet。',
        '\n评估标准根据官方代码和文档整理;发布数据未保存逐条示教 success 标签,故 actual_episode_success 为 null。本文不编造 0–100 得分。',
        '\n| 官方 task_index | Task / instruction scenario | 分类 | 直接浏览 |','|---|---|---|---|']
    for t in sorted(tasks,key=lambda t:t['task_index']):lines.append(f"| {t['task_index']} | {t['name']} | {t['category']} | [打开]({browser}/?task={t['task_index']}) |")
    if REFLEX:lines.append('\nReflexBench 上游 episode 本身很短,多数选取记录只有约 1 秒。此处保持完整官方 length 和时间区间,没有人为截短、慢放或补帧。')
    for t in tasks:
        lines.extend([f"\n## task_index={t['task_index']} · {t['name']}",f"\n**Instruction:** {t['instruction']}",f"\n**Description:** {t['description']}",f"\n**Success / evaluation:** {t['success_rule']}",f"\n[官方说明]({t['doc_url']})"])
        if t.get('instruction_metadata'):lines.extend(['\n结构化原始 instruction(完整别名):','\n```json',json.dumps(t['instruction_metadata'],ensure_ascii=False,indent=2),'```','\n'+t['instruction_note']])
        if t.get('official_gym_id'):lines.append(f"\n**Gym ID:** `{t['official_gym_id']}`")
        for s in [s for s in samples if s['task_index']==t['task_index']]:lines.extend([f"\n**episode_index={s['episode_index']}** · {s['frame_count']} frames / {s['frame_count']/25:.2f} s",f"\n![Camera preview]({s['preview_path']})",f"\n[同步 MP4]({s['composite_path']}) · "+' · '.join(f"[{v['camera']} MP4]({v['path']})" for v in s['views'])+f" · [官方轨迹]({s['trajectory_path']})"])
    lines.extend(['\n## 来源、许可与复现',f'\n官方数据:[原仓库](https://huggingface.co/datasets/{REPO}) · 固定 revision `{source["revision"]}`。',f'\n官方代码:[GitHub](https://github.com/{GITHUB}) · revision `{source["code_revision"]}`。','\n保留上游 LICENSE 和来源文件在 `reference/`。ReflexBench 官方数据未单列许可证元数据;保留官方实现 BSD-3-Clause 来源,不扩大作者权利。' if REFLEX else '\n遵循上游 S-Lab License 1.0,仅允许非商业用途;见 LICENSE。','\n选择性提取记录、原始时间区间、task/episode 对应、相机元数据和校验均在 `provenance/`。不下载场景资产、模型权重或完整数据仓库。','\n复现脚本:`scripts/build_examples.py`。浏览页源码另见 `browser/` 和 `scripts/build_browser.py`。'])
    (OUT/'README.md').write_text('\n'.join(lines)+'\n',encoding='utf-8');(OUT/'scripts').mkdir(exist_ok=True)
    script_target=OUT/'scripts/build_examples.py'
    if Path(__file__).resolve()!=script_target.resolve():shutil.copy2(__file__,script_target)
    print('Packaged',len(rows),'rows,',len(configs),'native HF subsets',flush=True)

if __name__=='__main__':
    WORK.mkdir(exist_ok=True);(OUT/'provenance').mkdir(parents=True,exist_ok=True)
    if (OUT/'provenance/source.json').exists():SOURCE_REV=read(OUT/'provenance/source.json')['revision']
    globals()[sys.argv[1]]()