File size: 31,997 Bytes
578663d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""Build selective EmbodiedSWE task examples. Stages: prepare, demos, extract, render, package.
Retains source-pinned manifests; never downloads assets, weights, or full video shards.
"""
from pathlib import Path
import ast,collections,concurrent.futures as cf,hashlib,io,json,re,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]
OUT=ROOT if (ROOT/'provenance/source.json').exists() else ROOT/'dataset'
WORK=ROOT/'work';CODE=WORK/'official-code'
DEST='Travor278/EmbodiedSWE-Task-Examples'
SITE='https://embodiedswe.github.io/'
SESSION=requests.Session();SESSION.mount('https://',HTTPAdapter(max_retries=Retry(total=4,backoff_factor=.6,status_forcelist=[429,500,502,503,504])))
REPOS={
 'bulb':'bulb_franka_pinkik.jointtarget_15hz_generalization_train_20260921',
 'nut_thread':'nut_thread_franka_ik.jointtarget_20hz_20260905',
 'pc_gpu':'pc_gpu_franka_osc.jointpos_15hz_20260907',
 'pc_ram':'pc_ram_franka_osc.jointpos_15hz_20260907',
 'pc_gpu_ram':'pc_gpu_ram_franka_osc.jointpos_15hz_20260907',
 'tool_packing':'tool_packing_franka_diffik.jointtarget_15hz_20260910',
 'pen_holder':'pen_holder_franka_diffik.jointtarget_15hz_20260909',
 'coffee':'coffee_franka_joint.jointtarget_60hz_20260907',
 'clear_organic_objects':'clear_organic_agent_ab_A400.jointtarget_20hz_20260918',
 'slice':'cutting_slice_franka_diffik.jointtarget_15hz_train_20260919',
}
GRADERS={
 'allen_bolt':'assembly/allen_bolt_assembly','bulb':'assembly/bulb_assembly','ikea_table':'assembly/ikea_table_assembly','so101':'assembly/so101_assembly',
 'nut_thread':'assembly/nut_thread_assembly','pc_gpu':'assembly/pc_gpu_assembly','pc_gpu_ram':'assembly/pc_gpu_ram_assembly','pc_ram':'assembly/pc_ram_assembly','pc_motherboard':'assembly/pc_motherboard_assembly',
 'pen_holder':'packing/pen_holder','tool_packing':'packing/tool_packing','egg_carton':'packing/egg_carton','clear_organic_objects':'packing/clear_organic_objects',
 'coffee':'puzzle/coffee_service','spatula':'puzzle/spatula_flip_serve','syringe':'puzzle/syringe_dosing','push_shapes':'puzzle/push_shapes','classify_objects':'puzzle/classify_objects','stack_blocks':'puzzle/stack_blocks',
 'tshirt':'deformable/tshirt','latte':'deformable/latte','dumpling':'deformable/dumpling','shoe_knot':'deformable/shoe_knot',
 'slice':'cutting/slice_food','dice':'cutting/dice_food','fruit_delivery':'locomanip/fruit_delivery','box_to_bin':'locomanip/box_to_bin','wheel_carry':'locomanip/wheel_carry',
}

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 source_url(repo,revision,path):return f'https://huggingface.co/datasets/{repo}/resolve/{revision}/{path}'
def media_path(path):return f'hf://datasets/{DEST}@main/{path}'
def keep_source(path):
    dst=OUT/'reference'/path;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(CODE/path,dst)

class HTTPRangeFile(io.RawIOBase):
    def __init__(self,url,size,block=1048576):self.url=url;self.resolved_url=None;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:
            key=self.pos//self.block
            if key not in self.cache:
                start=key*self.block;end=min(self.size,start+self.block)-1
                # Resolve the signed CDN address once, then issue bounded ranges
                # directly. Repeated HF redirects dominate small-range latency.
                r=SESSION.get(self.resolved_url or self.url,headers={'Range':f'bytes={start}-{end}'},timeout=(20,120))
                if r.status_code in [401,403] and self.resolved_url:
                    self.resolved_url=None
                    r=SESSION.get(self.url,headers={'Range':f'bytes={start}-{end}'},timeout=(20,120))
                r.raise_for_status();self.resolved_url=r.url
                assert r.status_code==206 and r.headers.get('Content-Range','').startswith(f'bytes {start}-'), 'Range unsupported; full-shard download refused'
                self.cache[key]=r.content;self.transferred+=len(r.content)
                if len(self.cache)>32:self.cache.popitem(last=False)
            b=self.cache[key];offset=self.pos%self.block;take=min(n,len(b)-offset)
            if take<=0:raise EOFError('truncated range')
            out.append(b[offset:offset+take]);self.pos+=take;n-=take
        return b''.join(out)

def prepare():
    if all((OUT/'provenance'/f).exists() for f in ['tasks.json','samples.json','source.json']):print('Using retained source-pinned manifests.');return
    from huggingface_hub import HfApi
    api=HfApi();site=(WORK/'site.js').read_text(encoding='utf-8');gallery=read(WORK/'gallery.json')
    block=re.search(r'var CATALOG = \[(.*?)\n  \];',site,re.S).group(1)
    catalog=re.findall(r"\['([^']*)','([^']*)','([^']*)',([ABG]),'([^']*)'\]",block);assert len(catalog)==28
    code_rev=subprocess.check_output(['git','-C',str(CODE),'rev-parse','HEAD'],text=True).strip()
    tasks=[];samples=[]
    for number,(suite,web_scene,objective,emb,difficulty) in enumerate(catalog,1):
        key={'SO_101':'so101'}.get(web_scene,web_scene.lower());clip=next((c for c in gallery if c['scene']==key),None)
        grader_suite,grader_name=GRADERS[key].split('/')
        relative=f'robobench/suites/{grader_suite}/grader/{grader_name}.py';src=(CODE/relative).read_text(encoding='utf-8');tree=ast.parse(src);cls=next(n for n in tree.body if isinstance(n,ast.ClassDef) and any(isinstance(a,ast.Assign) and getattr(a.targets[0],'id','')=='RUBRIC' for a in n.body))
        rubric_expr=next(a.value for a in cls.body if isinstance(a,ast.Assign) and getattr(a.targets[0],'id','')=='RUBRIC')
        if isinstance(rubric_expr,ast.Subscript):
            variants=ast.literal_eval(next(a.value for a in cls.body if isinstance(a,ast.Assign) and getattr(a.targets[0],'id','')=='RUBRICS'));rubric=variants[ast.literal_eval(rubric_expr.slice)]
        else:rubric=ast.literal_eval(rubric_expr);variants=None
        total=sum(x[1] for x in rubric)
        stages=[dict(stage=x[0],weight=x[1],normalized_weight=x[1]/total,mode=x[2] if len(x)>2 else 'live') for x in rubric]
        success=next(n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name=='check_success')
        task=dict(catalog_number=number,scene_key=key,official_scene_id=f'{grader_suite}.{key}',category=suite,name=clip['name'] if clip else {'shoe_knot':'Shoelace half-knot','dice':'Food dicing'}[key],instruction=objective,difficulty=difficulty,catalog_embodiments={'A':'Franka / xArm7 / Gen3','B':'Bimanual Franka','G':'Unitree G1'}[emb],rubric=stages,rubric_variants=variants,grader_description=ast.get_docstring(tree),grader_summary=ast.get_docstring(cls),success_source=ast.get_source_segment(src,success),grader_source_path=relative,grader_url=f'https://github.com/EmbodiedSWE/EmbodiedSWE/blob/{code_rev}/{relative}',gallery=None,dataset_source=None)
        if clip:task['gallery']=dict(path=f'media/{key}/website_demo.mp4',url=SITE+f"assets/video/{clip['f']}.mp4",website_playback_rate=clip['sp'],camera_label='WEBSITE RENDER VIEW')
        keep_source(relative)
        if key in REPOS:
            directory=WORK/'metadata'/REPOS[key];d=read(directory/'discovery.json');episodes=read(directory/'episodes.json');info=d['info'];repo=d['repo_id'];revision=d['revision'];official_tasks=pq.read_table(directory/'tasks.parquet').to_pylist()
            by_instruction={t.get('task',t.get('__index_level_0__')):t['task_index'] for t in official_tasks}
            if key=='slice':
                chosen=[]
                for tid in [0,5,21]:
                    match=next(t for t in official_tasks if t['task_index']==tid);inst=match.get('task',match.get('__index_level_0__'));selected=next(e for e in episodes if e['tasks']==[inst]);chosen.append(selected)
            elif len(official_tasks)>=3:
                chosen=[next(e for e in episodes if e['tasks']==[t.get('task',t.get('__index_level_0__'))]) for t in [official_tasks[0],official_tasks[len(official_tasks)//2],official_tasks[-1]]]
            else:chosen=[episodes[0],episodes[len(episodes)//2],episodes[-1]]
            cameras=[k.removeprefix('observation.images.') for k,v in info['features'].items() if v['dtype']=='video']
            # Single-arm camera placement order: scene view(s), wrist. Never fake left/right labels.
            cameras=sorted(cameras,key=lambda c:(c=='wrist',{'front':0,'front_wide':0,'high':1,'side':1,'corner':1}.get(c,2)))
            task['dataset_source']=dict(repo_id=repo,revision=revision,format=info['codebase_version'],fps=info['fps'],total_episodes=info['total_episodes'],camera_order=cameras,task_index_scope='local to this source repository; not a benchmark-global task ID',robot_type=info['robot_type'],selected_episodes=[e['episode_index'] for e in chosen],source_license_metadata=d['license'])
            for file in ['info.json','tasks.parquet','bake.json','modality.json']:
                if (directory/file).exists():
                    dst=OUT/'provenance/source_metadata'/key/file;dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(directory/file,dst)
            requested=[]
            for e in chosen:
                requested.append(info['data_path'].format(chunk_index=e['data/chunk_index'],file_index=e['data/file_index']))
                for c in cameras:
                    prefix=f'videos/observation.images.{c}'
                    requested.append(info['video_path'].format(video_key=f'observation.images.{c}',chunk_index=e[prefix+'/chunk_index'],file_index=e[prefix+'/file_index']))
            paths={x.path:x for x in api.get_paths_info(repo,sorted(set(requested)),repo_type='dataset',revision=revision)}
            for ep in chosen:
                eid=ep['episode_index'];inst=ep['tasks'][0];tid=by_instruction[inst];folder=f'media/{key}/episode_{eid:06d}';views=[]
                for c in cameras:
                    prefix=f'videos/observation.images.{c}';p=info['video_path'].format(video_key=f'observation.images.{c}',chunk_index=ep[prefix+'/chunk_index'],file_index=ep[prefix+'/file_index']);obj=paths[p]
                    views.append(dict(camera=c,label=c.upper().replace('_',' '),path=f'{folder}/{c}.mp4',source_path=p,source_bytes=obj.size,source_sha256=obj.lfs.sha256 if obj.lfs else None,from_timestamp=ep[prefix+'/from_timestamp'],to_timestamp=ep[prefix+'/to_timestamp']))
                data_path=info['data_path'].format(chunk_index=ep['data/chunk_index'],file_index=ep['data/file_index']);obj=paths[data_path]
                samples.append(dict(catalog_number=number,scene_key=key,source_repo=repo,source_revision=revision,task_index=tid,episode_index=eid,frame_count=ep['length'],fps=info['fps'],instruction=inst,views=views,trajectory_source_path=data_path,trajectory_source_bytes=obj.size,trajectory_path=f'trajectories/{key}/episode_{eid:06d}.parquet',composite_path=f'{folder}/synchronized.mp4',preview_path=f'{folder}/preview.jpg',metadata=ep))
            print(key,'selected IDs',[e['episode_index'] for e in chosen],'cameras',cameras,flush=True)
        tasks.append(task)
    assert len(tasks)==28 and len(samples)==30
    for path in ['LICENSE','README.md','robobench/README.md','robobench/robots/franka.py','robobench/core/robot.py','robobench/core/grader.py','vla/README.md','vla/convert/README.md']:keep_source(path)
    shutil.copy2(CODE/'LICENSE',OUT/'LICENSE')
    write(OUT/'provenance/tasks.json',tasks);write(OUT/'provenance/samples.json',samples)
    write(OUT/'provenance/source.json',dict(benchmark='EmbodiedSWE',code_repository='EmbodiedSWE/EmbodiedSWE',code_revision=code_rev,project_url=SITE+'#benchmark',retrieved_date='2026-10-05',catalog_number_scope='C01–C28 are this browser’s auxiliary numbers in website catalog order; use suite.scene as the official task identifier.',task_index_scope='Official LeRobot task_index and episode_index are LOCAL TO EACH SOURCE REPOSITORY. Keep source_repo to disambiguate.',sample_policy='Three complete selected episodes per dataset-backed scene; instruction/food diversity where source has multiple tasks, otherwise first/middle/last.',scoring_note='Current public grader source may differ from the historical data-generation graders. Do not infer actual scores from current rubric or clip appearance.',camera_note='Single-arm datasets have front/front_wide/high/side/corner and one wrist camera, depending on scene. Website demos expose only their recorded view; missing views are not invented.',total_scenes=28,website_demos=26,source_datasets=10,selected_episodes=30,franka_wrist_camera={'parent_link':'panda_hand','eye_m':[0.0465,-.02,.036],'target_m':[.0465,-.02,.3],'focal_mm':10.5,'coordinate_frame':'parent link local frame, not world frame','virtual_mount_note':'This is a simulated optical extrinsic; it is not a physical screw-hole measurement.'}))

def demos():
    tasks=read(OUT/'provenance/tasks.json')
    def run(t):
        d=t['gallery']
        if not d:return
        dst=OUT/d['path'];dst.parent.mkdir(parents=True,exist_ok=True)
        if not dst.exists():
            r=SESSION.get(d['url'],timeout=90);r.raise_for_status();dst.write_bytes(r.content)
        d['sha256']=hashlib.sha256(dst.read_bytes()).hexdigest();d['bytes']=dst.stat().st_size
    with cf.ThreadPoolExecutor(max_workers=5) as ex:list(ex.map(run,tasks))
    write(OUT/'provenance/tasks.json',tasks);print('Saved 26 official website MP4 clips, total',sum(t['gallery']['bytes'] for t in tasks if t['gallery']),flush=True)

def encode(frames,path,fps):
    import av
    path.parent.mkdir(parents=True,exist_ok=True)
    with av.open(str(path),'w',options={'movflags':'+faststart'}) as output:
        stream=None;count=0
        for f in frames:
            if stream is None:
                stream=output.add_stream('libx264',rate=fps);stream.width=f.width;stream.height=f.height;stream.pix_fmt='yuv420p';stream.options={'crf':'22','preset':'veryfast','threads':'2'}
            f=f.reformat(format='yuv420p');f.pts=count;f.time_base=Fraction(1,fps)
            for packet in stream.encode(f):output.mux(packet)
            count+=1
        if stream is None:raise ValueError('No source frames')
        for packet in stream.encode():output.mux(packet)
    return count

def extract():
    import av
    samples=read(OUT/'provenance/samples.json');jobs=collections.defaultdict(list)
    report_path=OUT/'provenance/download_report.json'
    summary=read(report_path).get('files',[]) if report_path.exists() else []
    for s in samples:
        jobs[(s['source_repo'],s['source_revision'],s['trajectory_source_path'],'data')].append(s)
        for v in s['views']:jobs[(s['source_repo'],s['source_revision'],v['source_path'],'video')].append((s,v))
    def run(key,entries):
        repo,rev,path,kind=key
        size=entries[0]['trajectory_source_bytes'] if kind=='data' else entries[0][1]['source_bytes']
        reader=HTTPRangeFile(source_url(repo,rev,path),size)
        if kind=='data':
            if all((OUT/s['trajectory_path']).exists() for s in entries):return None
            file=pq.ParquetFile(reader)
            # Episode-index statistics allow whole unused row groups to be skipped.
            for s in entries:
                target=OUT/s['trajectory_path']
                if target.exists():continue
                table=pq.read_table(reader,filters=[('episode_index','=',s['episode_index'])])
                assert table.num_rows==s['frame_count'],(s['scene_key'],s['episode_index'],table.num_rows,s['frame_count'])
                assert set(table['task_index'].to_pylist())=={s['task_index']}
                target.parent.mkdir(parents=True,exist_ok=True);pq.write_table(table,target)
                print('Trajectory',s['scene_key'],s['episode_index'],table.num_rows,flush=True)
        else:
            if all((OUT/v['path']).exists() for s,v in entries):return None
            with av.open(reader) as container:
                stream=container.streams.video[0]
                for s,v in sorted(entries,key=lambda x:x[1]['from_timestamp']):
                    target=OUT/v['path']
                    if target.exists():
                        v['output_sha256']=hashlib.sha256(target.read_bytes()).hexdigest()
                        continue
                    start=v['from_timestamp'];fps=s['fps'];container.seek(int(start/stream.time_base),stream=stream,backward=True)
                    def frames():
                        count=0
                        for f in container.decode(stream):
                            if f.time+1e-5<start:continue
                            if count>=s['frame_count']:break
                            expected=start+count/fps
                            assert abs(f.time-expected)<1/fps*.55,(s['scene_key'],s['episode_index'],v['camera'],f.time,expected)
                            yield f;count+=1
                        assert count==s['frame_count'],(s['scene_key'],s['episode_index'],count,s['frame_count'])
                    count=encode(frames(),target,fps);v['output_sha256']=hashlib.sha256(target.read_bytes()).hexdigest()
                    print('Video',s['scene_key'],s['episode_index'],v['camera'],count,'frames',flush=True)
        return dict(repo_id=repo,revision=rev,path=path,kind=kind,full_source_bytes=size,received_range_bytes=reader.transferred)
    with cf.ThreadPoolExecutor(max_workers=4) as ex:
        futures={ex.submit(run,k,e):k for k,e in jobs.items()}
        for f in cf.as_completed(futures):
            result=f.result()
            if result:summary.append(result)
            write(OUT/'provenance/samples.json',samples)
            write(OUT/'provenance/download_report.json',dict(whole_video_shards_downloaded=False,assets_downloaded=False,checkpoints_downloaded=False,range_bytes_received=sum(x['received_range_bytes'] for x in summary),byte_count_scope='Completed source-group reads only; incomplete reads interrupted during resume may add uncounted overhead.',files=summary))
    print('Selective range bytes:',sum(x['received_range_bytes'] for x in summary),flush=True)

def render():
    from PIL import Image,ImageDraw
    samples=read(OUT/'provenance/samples.json')
    def run(s):
        n=len(s['views']);fps=s['fps'];target=OUT/s['composite_path']
        # Allows rendering to overlap selective extraction without ever reading
        # an unfinished MP4 (its moov/nb_frames only exist after the writer closes).
        deadline=time.monotonic()+1800
        while True:
            complete=True
            for v in s['views']:
                p=OUT/v['path']
                if not p.exists():complete=False;break
                r=subprocess.run(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=nb_frames','-of','json',str(p)],capture_output=True,text=True)
                try:valid=r.returncode==0 and int(json.loads(r.stdout)['streams'][0]['nb_frames'])==s['frame_count']
                except (ValueError,KeyError,IndexError):valid=False
                if not valid:complete=False;break
            if complete:break
            if time.monotonic()>deadline:raise TimeoutError(f"Source cameras not finished: {s['scene_key']} {s['episode_index']}")
            time.sleep(2)
        if not target.exists():
            labels=Image.new('RGB',(320*n,28),'#14251e');draw=ImageDraw.Draw(labels)
            for i,v in enumerate(s['views']):draw.text((i*320+10,8),v['label'],fill='white')
            label_path=WORK/f"labels-{s['scene_key']}-{s['episode_index']}.png";labels.save(label_path)
            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:240,setsar=1[c{i}]' for i in range(n))+';'+''.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','-preset','veryfast','-crf','23','-pix_fmt','yuv420p','-threads','2','-frames:v',str(s['frame_count']),'-r',str(fps),'-movflags','+faststart',str(target)];subprocess.run(cmd,check=True,capture_output=True)
        if not (OUT/s['preview_path']).exists():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)
        print('Rendered',s['scene_key'],s['episode_index'],flush=True)
    with cf.ThreadPoolExecutor(max_workers=3) as ex:list(ex.map(run,samples))
    checks=[]
    for s in samples:
        data=pq.read_table(OUT/s['trajectory_path']);assert data.num_rows==s['frame_count'];assert set(data['task_index'].to_pylist())=={s['task_index']};assert set(data['episode_index'].to_pylist())=={s['episode_index']}
        videos=[]
        for path in [v['path'] for v in s['views']]+[s['composite_path']]:
            stat=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=codec_name,width,height,nb_frames,duration,avg_frame_rate','-of','json',str(OUT/path)],text=True))['streams'][0]
            assert stat['codec_name']=='h264' and int(stat['nb_frames'])==s['frame_count'],(path,stat)
            assert abs(float(Fraction(stat['avg_frame_rate']))-s['fps'])<.001
            videos.append(dict(path=path,**stat))
        checks.append(dict(scene_key=s['scene_key'],source_repo=s['source_repo'],task_index=s['task_index'],episode_index=s['episode_index'],videos=videos))
    write(OUT/'provenance/validation.json',dict(passed=True,selected_episodes=30,official_task_scenes=28,website_demos=26,checks=checks));print('All 30 episode IDs, source task IDs, frame counts and FPS verified.',flush=True)

def package():
    import yaml
    from datasets import Dataset,Features,Value,Video
    tasks=read(OUT/'provenance/tasks.json');samples=read(OUT/'provenance/samples.json');source=read(OUT/'provenance/source.json');rows=[]
    for t in tasks:
        common=dict(catalog_number=t['catalog_number'],scene_key=t['scene_key'],official_scene_id=t['official_scene_id'],task_name=t['name'],category=t['category'],difficulty=t['difficulty'],benchmark_instruction=t['instruction'],rubric=json.dumps(t['rubric']),grading_description=t['grader_description'],success_source=t['success_source'],grader_url=t['grader_url'],actual_episode_score=None,actual_episode_success=None)
        for s in [s for s in samples if s['scene_key']==t['scene_key']]:
            camera_dict={v['camera']:dict(path=media_path(v['path']),bytes=None) for v in s['views']}
            row=dict(common,row_kind='official_dataset_episode',source_repo=s['source_repo'],source_revision=s['source_revision'],task_index=s['task_index'],episode_index=s['episode_index'],instruction=s['instruction'],synchronized=dict(path=media_path(s['composite_path']),bytes=None),view_1=camera_dict[s['views'][0]['camera']],view_1_name=s['views'][0]['camera'],view_2=camera_dict[s['views'][1]['camera']],view_2_name=s['views'][1]['camera'],view_3=camera_dict[s['views'][2]['camera']] if len(s['views'])>2 else None,view_3_name=s['views'][2]['camera'] if len(s['views'])>2 else '',website_demo=None,frame_count=s['frame_count'],fps=s['fps'],duration_seconds=s['frame_count']/s['fps'],trajectory_url=f'https://huggingface.co/datasets/{DEST}/resolve/main/'+s['trajectory_path'],notes='Source task_index / episode_index are local to source_repo. H.264 transcode keeps every selected source frame at its original dataset FPS; any upstream idle filtering remains part of the official data. Current public rubric is not a measured score for this episode.')
            rows.append(row)
        d=t['gallery']
        if d:rows.append(dict(common,row_kind='official_website_demo',source_repo='',source_revision='',task_index=None,episode_index=None,instruction=t['instruction'],synchronized=None,view_1=None,view_1_name='',view_2=None,view_2_name='',view_3=None,view_3_name='',website_demo=dict(path=media_path(d['path']),bytes=None),frame_count=None,fps=None,duration_seconds=None,trajectory_url='',notes=f"Official website clip: {d['url']}. Website playback rate {d['website_playback_rate']}x; this browser defaults to 1x of the published file. No paired camera/trajectory inferred."))
        if not d and not t['dataset_source']:rows.append(dict(common,row_kind='catalog_only_no_published_clip',source_repo='',source_revision='',task_index=None,episode_index=None,instruction=t['instruction'],synchronized=None,view_1=None,view_1_name='',view_2=None,view_2_name='',view_3=None,view_3_name='',website_demo=None,frame_count=None,fps=None,duration_seconds=None,trajectory_url='',notes='The official website currently has no demonstration clip, and no corresponding public HF demonstration dataset was located. Keep task objective and published grading source.'))
    videos={'synchronized','view_1','view_2','view_3','website_demo'};ints={'catalog_number','task_index','episode_index','frame_count','fps'}
    features=Features({k:Video(decode=False) if k in videos else Value('int64') if k in ints else Value('float64') if k in ['duration_seconds','actual_episode_score'] 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,ids,default=False):
        p=f'data/{name}.parquet';ds.select(ids).to_parquet(str(OUT/p),batch_size=32);c=dict(config_name=name,data_files=[dict(split='examples',path=p)])
        if default:c['default']=True
        configs.append(c)
    subset('all',list(range(len(rows))),True)
    for t in tasks:subset('scene_'+t['scene_key'],[i for i,r in enumerate(rows) if r['scene_key']==t['scene_key']])
    for group in sorted({t['category'] for t in tasks}):subset(group.lower(),[i for i,r in enumerate(rows) if r['category']==group])
    header=dict(language=['en','zh'],license='other',license_name='upstream-embodiedswe-terms',license_link=f'https://huggingface.co/datasets/{DEST}/blob/main/NOTICE.md',pretty_name='EmbodiedSWE Simulation Task Examples',tags=['robotics','video','simulation'],configs=configs)
    browser='https://travor278-embodiedswe-task-examples.static.hf.space'
    lines=['---',yaml.safe_dump(header,allow_unicode=True,sort_keys=False).rstrip(),'---','# EmbodiedSWE Simulation Task Examples',f'\n[打开任务 MP4 浏览页]({browser}/?task=bulb)', '\n28 个官网场景 · 26 段官网 MP4 · 10 个官方数据来源各 3 条完整 episode,共 30 条多相机示教。shoe_knot 与 dice 暂无官方展示视频,保留任务目录和评分标准。',
        '\n**序号规则:** 本页 C01–C28 是按官网目录顺序生成的辅助编号,官方任务以 `suite.scene` 标识。LeRobot `task_index` 和 `episode_index` 都只在各自 `source_repo` 内有效,绝不能把各库的 task_index=0 当成同一任务。',
        '\n**相机:** 按官方实际提供的 front/front_wide/high/side/corner/wrist 展示,单臂 wrist 不伪装成 left/right。官网演示只展示其原有视角。',
        '\n**评分:** 来自当前公开代码的 BaseGrader 与具体 RUBRIC,progress 是归一化权重和。live=当前值;once=历史最好;final=交付末端才评估。历史数据生成使用的 grader 可能不同;示例没有公开逐条分数,因此 actual_episode_score/success 留空。',
        f'\n[Franka 腕部相机说明]({browser}/?task=camera-guide) · [官方任务页](https://embodiedswe.github.io/#benchmark)',
        '\n| 辅助目录号 | 官方 scene ID | Task | Category | 直接浏览 |','|---|---|---|---|---|']
    for t in tasks:lines.append(f"| C{t['catalog_number']:02d} | `{t['official_scene_id']}` | {t['name']} | {t['category']} | [打开]({browser}/?task={t['scene_key']}) |")
    for t in tasks:
        lines.extend([f"\n## C{t['catalog_number']:02d} · {t['name']} · {t['official_scene_id']}",f"\n**Instruction / objective:** {t['instruction']}",f"\n**Difficulty:** {t['difficulty']} · **官网列出的 evaluated on:** {t['catalog_embodiments']}",f"\n[MP4 浏览]({browser}/?task={t['scene_key']}) · [官方评分源码]({t['grader_url']})",'\n| Stage | Weight | Normalized share | Mode |','|---|---|---|---|'])
        lines.extend(f"| {s['stage']} | {s['weight']} | {s['normalized_weight']:.2%} | {s['mode']} |" for s in t['rubric'])
        lines.extend(['\n```python',t['success_source'],'```'])
        if t['dataset_source']:lines.append(f"\n**Official dataset:** [{t['dataset_source']['repo_id']}](https://huggingface.co/datasets/{t['dataset_source']['repo_id']}) · {t['dataset_source']['fps']} FPS · cameras: {', '.join(t['dataset_source']['camera_order'])}")
        for s in [s for s in samples if s['scene_key']==t['scene_key']]:
            lines.extend([f"\n**source task_index={s['task_index']} / episode_index={s['episode_index']}** · {s['frame_count']} frames / {s['fps']} FPS / {s['frame_count']/s['fps']:.2f} s",f"\n**Dataset instruction:** {s['instruction']}",f"\n![Source camera composite]({s['preview_path']})",f"\n[同步 MP4]({s['composite_path']}) · "+' · '.join(f"[{v['camera']} MP4]({v['path']})" for v in s['views'])+f" · [官方轨迹 Parquet]({s['trajectory_path']})"])
        if t['gallery']:lines.append(f"\n[官网展示 MP4]({t['gallery']['path']}) · 网站原始播放倍率 {t['gallery']['website_playback_rate']}x;该示例不等同于公开三相机训练轨迹。")
        else:lines.append('\n官方目录中该任务目前没有公开展示 MP4。')
    lines.extend(['\n## 来源与复现',f'\n代码 revision:`{source["code_revision"]}`。官网抓取日期:2026-10-05。','\n保留各数据源固定 revision、源文件大小与校验和、官方 episode 时间区间和元数据、源码评分说明。合并源视频采用 HTTP Range 读取选定 episode;不下载完整 assets、权重或整库。','\n脚本 `scripts/build_examples.py` 可基于保留的 manifests 运行 demos/extract/render/package;浏览页源码保留在 browser/ 与 scripts/build_browser.py。','\n官方代码采用 Apache-2.0;部分源数据未单列许可元数据。本整理保留各来源权利与署名,不另行扩张许可;见 NOTICE.md、LICENSE 和 reference/。'])
    (OUT/'README.md').write_text('\n'.join(lines)+'\n',encoding='utf-8');(OUT/'scripts').mkdir(exist_ok=True)
    (OUT/'NOTICE.md').write_text('# Source attribution and terms\n\nUnofficial curated examples. Official task code, descriptions and episodes are credited to the EmbodiedSWE authors.\n\nThe upstream code LICENSE is Apache-2.0 and is retained verbatim in LICENSE. Some official HF datasets declare Apache-2.0; others do not declare a dataset-specific license in their card metadata. Per-source metadata is preserved in provenance/tasks.json. Website clips are credited and linked to their original project-page files. This curation does not create additional rights or replace upstream terms.\n',encoding='utf-8')
    if Path(__file__).resolve()!=(OUT/'scripts/build_examples.py').resolve():shutil.copy2(__file__,OUT/'scripts/build_examples.py')
    print('Packaged',len(rows),'rows in',len(configs),'native HF subsets.',flush=True)

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