File size: 36,981 Bytes
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6d6d08
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4999b4
 
 
 
 
 
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d5b4c0
6860975
 
 
 
 
 
 
 
 
 
1d5b4c0
 
6860975
 
 
 
 
 
 
1d5b4c0
 
 
 
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d5b4c0
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d5b4c0
6860975
 
 
 
 
 
 
1d5b4c0
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4999b4
 
1d5b4c0
 
f4999b4
6860975
 
 
 
 
 
 
 
 
 
 
1d5b4c0
 
 
f4999b4
6860975
 
1d5b4c0
6860975
 
 
1d5b4c0
6860975
 
1d5b4c0
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4999b4
6860975
 
 
 
 
 
 
1d5b4c0
6860975
 
 
1d5b4c0
6860975
 
 
d6d6d08
 
6860975
 
 
 
1d5b4c0
 
 
6860975
 
 
 
 
 
 
 
 
 
d6d6d08
 
6860975
1d5b4c0
6860975
 
 
 
 
 
 
d6d6d08
6860975
 
 
 
 
 
 
 
 
 
 
1d5b4c0
6860975
1d5b4c0
6860975
 
 
 
 
1d5b4c0
 
6860975
 
 
 
 
d6d6d08
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4999b4
 
 
 
 
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d5b4c0
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4999b4
 
 
 
1d5b4c0
f4999b4
 
 
 
 
 
 
 
6860975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
"""Build a small, source-pinned RoboDojo browsing dataset; never snapshot the upstream repo.

python scripts/build_dataset.py prepare|download|render|package|validate|publish
"""
from __future__ import annotations
import argparse
import concurrent.futures as cf
import hashlib
import json
import shutil
import subprocess
import time
from pathlib import Path
from urllib.parse import quote

import requests
from bs4 import BeautifulSoup
from huggingface_hub import HfApi

ROOT = Path(__file__).resolve().parents[1]
WORK = ROOT / 'work'
OUT = ROOT if (ROOT / 'provenance/task_catalog.json').exists() else ROOT / 'dataset'
SOURCE = 'RoboDojo-Benchmark/RoboDojo'
DEST = 'Travor278/RoboDojo-Task-Examples'
BROWSER_URL = 'https://travor278-robodojo-task-examples.static.hf.space'
DOC = 'https://robodojo-benchmark.com'
GROUPS = ['Generalization', 'Memory', 'Precision', 'Long-Horizon', 'Open', 'DLC']
LOCAL_EPISODES = [0, 49, 99]


def read(path):
    return json.loads(path.read_text(encoding='utf-8'))


def write(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')


def fetch(url, path, sha=None, size=None):
    if path.exists() and (not size or path.stat().st_size == size):
        if not sha or hashlib.sha256(path.read_bytes()).hexdigest() == sha:
            return path.stat().st_size
    path.parent.mkdir(parents=True, exist_ok=True)
    for attempt in range(4):
        try:
            with requests.get(url, stream=True, timeout=(20, 120)) as r:
                r.raise_for_status()
                temporary = path.with_suffix(path.suffix + '.part')
                with temporary.open('wb') as f:
                    for chunk in r.iter_content(1024 * 1024):
                        f.write(chunk)
            if size and temporary.stat().st_size != size:
                raise ValueError(f'Size mismatch: {path}')
            if sha and hashlib.sha256(temporary.read_bytes()).hexdigest() != sha:
                raise ValueError(f'SHA256 mismatch: {path}')
            temporary.replace(path)
            return path.stat().st_size
        except Exception:
            if attempt == 3:
                raise
            time.sleep(1 + attempt)


def source_url(path, revision):
    return f'https://huggingface.co/datasets/{SOURCE}/resolve/{revision}/{path}'


def own_url(path):
    return f'https://huggingface.co/datasets/{DEST}/resolve/main/{path}'


def viewer_media_path(path):
    # Dataset Viewer accepts repo-qualified hf:// paths with an explicit revision.
    # HTTPS resolve URLs work in browsers/datasets but are rejected by its renderer.
    return f'hf://datasets/{DEST}@main/{path}'


def prepare():
    api = HfApi()
    revision = api.dataset_info(SOURCE).sha
    # Download only tiny metadata, task HTML and directory listings.
    for name in ['tasks.jsonl', 'info.json', 'episodes.jsonl']:
        fetch(source_url(f'data/RoboDojo_lerobot_v21_video/meta/{name}', revision), WORK / name)
    fetch(DOC + '/doc/sim-tasks/', WORK / 'sim-tasks.html')
    main = BeautifulSoup((WORK / 'sim-tasks.html').read_text(encoding='utf-8'), 'html.parser').select_one('.sl-markdown-content')
    pages = [(a.get_text(' ', strip=True), a['href']) for a in main.find_all('a')
             if a.get('href', '').startswith('/doc/sim-tasks/')
             and a['href'].split('/')[-2] not in ['domain-randomization', 'parallel-environments']]
    official_tasks = [json.loads(x) for x in (WORK / 'tasks.jsonl').read_text().splitlines()]
    raw_folders = {Path(x.path).name.lower(): Path(x.path).name
                   for x in api.list_repo_tree(SOURCE, repo_type='dataset', revision=revision, path_in_repo='data/RoboDojo')}
    by_instruction = {' '.join(x['task'].split()): x['task_index'] for x in official_tasks}
    # The website updated these descriptions after the v2.1 instruction metadata.
    # Keep both texts and validate IDs from each selected trajectory.
    documented_instruction_updates = {'build-tower': 1, 'organize-table': 17}
    tasks = []
    for catalog, (name, path) in enumerate(pages, 1):
        slug = path.split('/')[-2]
        fetch(DOC + path, WORK / f'{slug}.html')
        m = BeautifulSoup((WORK / f'{slug}.html').read_text(encoding='utf-8'), 'html.parser').select_one('.sl-markdown-content')
        tables = m.select('table')
        fields = {r.th.get_text(' ', strip=True): r.td.get_text(' ', strip=True)
                  for r in tables[0].select('tr') if r.th and r.td}
        scoring = [{'score': r.th.get_text(' ', strip=True), 'condition': r.td.get_text(' ', strip=True)}
                   for table in tables[1:] for r in table.select('tr') if r.th and r.td
                   and r.th.get_text(' ', strip=True) != 'Score']
        index = by_instruction.get(' '.join(fields['Instruction'].split()), documented_instruction_updates.get(slug))
        task_key = raw_folders.get(slug.replace('-', '_').lower(), slug.replace('-', '_'))
        category = 'DLC' if slug == 'dlc' else fields['Category']
        videos = [{'label': figure.figcaption.get_text(' ', strip=True) if figure.figcaption else 'Simulation demo',
                   'url': DOC + figure.source['src']} for figure in m.select('figure') if figure.source]
        if not videos:
            videos = [{'label': 'Simulation demo', 'url': DOC + v['src']} for v in m.select('video source')]
        config = f'task_{index:02d}_{task_key}' if index is not None else f'catalog_{catalog:02d}_{task_key}'
        tasks.append(dict(catalog_number=catalog, task_index=index, task_key=task_key, task_name=name,
                          category=category, doc_url=DOC + path, fields=fields, scoring=scoring,
                          documentation_videos=videos, config=config,
                          dataset_instruction=official_tasks[index]['task'] if index is not None else None,
                          instruction_match=(fields['Instruction'] == official_tasks[index]['task']) if index is not None else None,
                          data_status='official_demonstrations' if index is not None else 'eval_only_no_published_demonstrations'))
    assert len(tasks) == 43
    assert sorted(t['task_index'] for t in tasks if t['task_index'] is not None) == list(range(35))
    episodes = [json.loads(x) for x in (WORK / 'episodes.jsonl').read_text().splitlines()]
    episodes_by_task = {}
    for task in official_tasks:
        episodes_by_task[task['task_index']] = [x for x in episodes if x['tasks'] == [task['task']]]
        assert len(episodes_by_task[task['task_index']]) == 100

    def listing(task):
        p = f"data/RoboDojo/{task['task_key']}/arx_x5/preview_video"
        return task['task_key'], {Path(x.path).name: x for x in api.list_repo_tree(
            SOURCE, repo_type='dataset', revision=revision, path_in_repo=p)}
    with cf.ThreadPoolExecutor(max_workers=6) as executor:
        listings = dict(executor.map(listing, [t for t in tasks if t['task_index'] is not None]))
    plan = []
    samples = []
    for task in tasks:
        index = task['task_index']
        if index is not None:
            for local in LOCAL_EPISODES:
                ep = episodes_by_task[index][local]
                eid = ep['episode_index']
                media_dir = f"media/{task['task_key']}/episode_{local:07d}"
                sample = dict(task_key=task['task_key'], task_index=index, episode_index=eid,
                              source_local_episode=local, frame_count=ep['length'], fps=25, views={})
                for view, camera in [('top', 'cam_head'), ('left', 'cam_left_wrist'), ('right', 'cam_right_wrist')]:
                    filename = f'episode_{local:07d}_{camera}.mp4'
                    obj = listings[task['task_key']][filename]
                    target = f'{media_dir}/{view}.mp4'
                    sample['views'][view] = dict(path=target, source_path=obj.path, source_sha256=obj.lfs.sha256,
                                                 source_bytes=obj.size, camera=camera)
                    plan.append(dict(url=source_url(obj.path, revision), path=target, sha256=obj.lfs.sha256, bytes=obj.size))
                parquet_source = f'data/RoboDojo_lerobot_v21_video/data/chunk-{eid//1000:03d}/episode_{eid:06d}.parquet'
                parquet_target = f"trajectories/{task['task_key']}/episode_{eid:06d}.parquet"
                sample['trajectory_path'] = parquet_target
                sample['trajectory_source_path'] = parquet_source
                sample['synchronized_views_path'] = f'{media_dir}/top_left_right.mp4'
                sample['preview_path'] = f'{media_dir}/top_left_right.jpg'
                plan.append(dict(url=source_url(parquet_source, revision), path=parquet_target))
                samples.append(sample)
        for demo in task['documentation_videos']:
            # Standard demos are already covered by official three-camera episodes.
            if index is None or 'Random' in demo['label']:
                target = f"media/{task['task_key']}/{'random' if 'Random' in demo['label'] else 'documentation'}.mp4"
                demo['path'] = target
                if 'Random' in demo['label']:
                    demo['available_views'] = ['top']
                    demo['unavailable_views'] = ['left', 'right']
                    demo['camera_note'] = '公开的官网 Random MP4 只有头部相机视角;对应的左右腕相机录像未在官网及官方 HF 任务数据中找到。画面里的双臂不等于有腕部相机视频。'
                plan.append(dict(url=demo['url'], path=target))
    image = main.find('img')
    # The official HTML points to /images/axes.png (404); its asset lives under /doc/.
    axis_path = image['src'] if image['src'].startswith('/doc/') else '/doc' + image['src']
    plan.append(dict(url=DOC + axis_path, path='reference/world_axes.png'))
    for key in ['domain-randomization', 'parallel-environments']:
        fetch(DOC + f'/doc/sim-tasks/{key}/', WORK / f'{key}.html')
        m = BeautifulSoup((WORK / f'{key}.html').read_text(encoding='utf-8'), 'html.parser').select_one('.sl-markdown-content')
        for v in m.select('video source'):
            plan.append(dict(url=DOC + v['src'], path=f'reference/{key}.mp4'))
        (OUT / 'reference').mkdir(parents=True, exist_ok=True)
        (OUT / 'reference' / f'{key}.txt').write_text(m.get_text('\n', strip=True), encoding='utf-8')
    write(OUT / 'provenance/task_catalog.json', tasks)
    write(OUT / 'provenance/selected_episodes.json', samples)
    write(WORK / 'download_plan.json', plan)
    write(OUT / 'provenance/source.json', dict(repo_id=SOURCE, revision=revision, source_format='RoboDojo raw H.264 previews + LeRobot v2.1 trajectories',
        task_index_source='data/RoboDojo_lerobot_v21_video/meta/tasks.jsonl', retrieved_date='2026-10-03',
        episode_selection=LOCAL_EPISODES, source_catalog_task_count=43, official_dataset_task_count=35,
        background_annotation='The upstream metadata does not label background IDs. Three spaced episode IDs are sampled per task; distinct background coverage is not guaranteed.',
        camera_mapping={'top': 'cam_head (raw preview); cam_high (LeRobot)', 'left': 'cam_left_wrist', 'right': 'cam_right_wrist'}, view_order=['top', 'left', 'right']))
    for filename in ['tasks.jsonl', 'info.json']:
        shutil.copy2(WORK / filename, OUT / 'provenance' / filename)
    print(f'Prepared {len(tasks)} tasks, {len(samples)} full demonstrations, {len(plan)} selected downloads.', flush=True)
    print(f'Known preview video bytes: {sum(x.get("bytes",0) for x in plan):,}', flush=True)


def download():
    plan = read(WORK / 'download_plan.json')
    def run(x):
        return fetch(x['url'], OUT / x['path'], x.get('sha256'), x.get('bytes'))
    total = 0
    with cf.ThreadPoolExecutor(max_workers=8) as executor:
        futures = [executor.submit(run, x) for x in plan]
        for i, future in enumerate(cf.as_completed(futures), 1):
            total += future.result()
            if i % 20 == 0 or i == len(plan):
                print(f'Downloaded {i}/{len(plan)}, {total/1e6:.1f} MB', flush=True)
    write(OUT / 'provenance/download_summary.json', dict(file_count=len(plan), selected_bytes=total,
        hdf5_downloaded=0, checkpoint_downloaded=0, upstream_snapshot_downloaded=False))


def probe(path):
    result = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_streams', '-of', 'json', str(path)],
                            capture_output=True, text=True, check=True)
    return json.loads(result.stdout)['streams'][0]


def render():
    from PIL import Image, ImageDraw
    samples = read(OUT / 'provenance/selected_episodes.json')
    label = Image.new('RGB', (960, 28), '#142032')
    drawer = ImageDraw.Draw(label)
    for x, text in [(12, 'TOP / HEAD'), (332, 'LEFT WRIST'), (652, 'RIGHT WRIST')]:
        drawer.text((x, 7), text, fill='white')
    labels_path = WORK / 'labels.png'
    label.save(labels_path)
    def run(sample):
        target = OUT / sample['synchronized_views_path']
        if not target.exists():
            command = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y']
            for view in ['top', 'left', 'right']:
                command += ['-i', str(OUT / sample['views'][view]['path'])]
            command += ['-loop', '1', '-i', str(labels_path), '-filter_complex',
                '[0:v]scale=320:240,setsar=1[a];[1:v]scale=320:240,setsar=1[b];[2:v]scale=320:240,setsar=1[c];'
                '[a][b][c]hstack=inputs=3[views];[3:v]format=yuv420p[labels];[labels][views]vstack=inputs=2:shortest=1[out]',
                '-map', '[out]', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '24', '-pix_fmt', 'yuv420p',
                '-threads', '2', '-r', '25', '-frames:v', str(sample['frame_count']), '-movflags', '+faststart', str(target)]
            subprocess.run(command, check=True, capture_output=True)
        preview = OUT / sample['preview_path']
        if not preview.exists():
            subprocess.run(['ffmpeg', '-v', 'error', '-y', '-ss', '0', '-i', str(target), '-frames:v', '1', '-q:v', '3', str(preview)],
                           check=True, capture_output=True)
        return sample['task_key'], sample['episode_index']
    with cf.ThreadPoolExecutor(max_workers=3) as executor:
        futures = [executor.submit(run, s) for s in samples]
        for i, f in enumerate(cf.as_completed(futures), 1):
            f.result()
            if i % 10 == 0 or i == len(samples):
                print(f'Rendered {i}/{len(samples)} synchronized three-view videos', flush=True)


def package():
    import datasets
    import yaml
    from datasets import Dataset, Features, Value, Video, Image
    tasks = read(OUT / 'provenance/task_catalog.json')
    samples = read(OUT / 'provenance/selected_episodes.json')
    source = read(OUT / 'provenance/source.json')
    rows = []
    for t in tasks:
        scoring = '\n'.join(f"{s['score']}: {s['condition']}" for s in t['scoring']) or 'Not provided on the official task page.'
        common = dict(task_index=t['task_index'], task_name=t['task_name'], category=t['category'], task_key=t['task_key'],
            catalog_number=t['catalog_number'], instruction=t['fields']['Instruction'], dataset_instruction=t['dataset_instruction'], description=t['fields']['Description'],
            scoring=scoring, platform=t['fields']['Platform'], data_source=t['fields']['Data Source'], usage=t['fields']['Usage'],
            comment=t['fields'].get('Comment', ''), official_task_page=t['doc_url'], source_revision=source['revision'],
            actual_episode_score=None, background_id=None)
        for s in [x for x in samples if x['task_key'] == t['task_key']]:
            row = dict(common, episode_index=s['episode_index'], source_local_episode=s['source_local_episode'],
                row_kind='official_demonstration', variant='standard / sampled scene',
                synchronized_views=dict(path=viewer_media_path(s['synchronized_views_path']), bytes=None),
                top=dict(path=viewer_media_path(s['views']['top']['path']), bytes=None),
                left=dict(path=viewer_media_path(s['views']['left']['path']), bytes=None),
                right=dict(path=viewer_media_path(s['views']['right']['path']), bytes=None), official_demo=None,
                preview=dict(path=viewer_media_path(s['preview_path']), bytes=None), trajectory_url=own_url(s['trajectory_path']),
                source_top_url=source_url(s['views']['top']['source_path'], source['revision']),
                source_right_url=source_url(s['views']['right']['source_path'], source['revision']),
                source_left_url=source_url(s['views']['left']['source_path'], source['revision']),
                source_trajectory_url=source_url(s['trajectory_source_path'], source['revision']),
                fps=s['fps'], frame_count=s['frame_count'], duration_seconds=s['frame_count']/s['fps'],
                notes='Official full three-camera preview; no frames sampled out. Synchronized view is a resized composite. Background ID and episode score are not published.' + (' Website instruction differs from official v2.1 dataset_instruction; the demo belongs to the dataset version.' if t['instruction_match'] is False else ''))
            rows.append(row)
        for demo in t['documentation_videos']:
            if 'path' in demo:
                rows.append(dict(common, episode_index=None, source_local_episode=None,
                    row_kind='documentation_random_eval' if 'Random' in demo['label'] else 'documentation_eval_only',
                    variant=demo['label'], synchronized_views=None,
                    top=dict(path=viewer_media_path(demo['path']), bytes=None) if 'Random' in demo['label'] else None,
                    left=None, right=None,
                    official_demo=dict(path=viewer_media_path(demo['path']), bytes=None), preview=None, trajectory_url='',
                    source_top_url='', source_right_url='', source_left_url='', source_trajectory_url='',
                    fps=None, frame_count=None, duration_seconds=None,
                    notes=f"Official website demo: {demo['url']}. No published three-camera training demonstration for this variant. Scoring is from the base task page." + (' Only the head-camera MP4 is publicly provided; corresponding left/right wrist videos were not found in audited official sources.' if 'Random' in demo['label'] else '')))
    # Lead with the actual official task IDs. Documentation-only tasks follow.
    rows.sort(key=lambda r: (r['task_index'] if r['task_index'] is not None else 100+r['catalog_number'],
                             r['episode_index'] if r['episode_index'] is not None else 999999))
    order = ['task_index', 'task_name', 'episode_index', 'synchronized_views', 'top', 'left', 'right', 'official_demo',
             'category', 'instruction', 'dataset_instruction', 'scoring', 'variant', 'row_kind', 'catalog_number', 'source_local_episode',
             'task_key', 'description', 'platform', 'data_source', 'usage', 'comment', 'preview', 'frame_count', 'fps',
             'duration_seconds', 'trajectory_url', 'official_task_page', 'source_top_url', 'source_left_url', 'source_right_url',
             'source_trajectory_url', 'source_revision', 'actual_episode_score', 'background_id', 'notes']
    ints = {'task_index', 'episode_index', 'catalog_number', 'source_local_episode', 'frame_count', 'fps'}
    videos = {'synchronized_views', 'top', 'right', 'left', 'official_demo'}
    features = Features({k: Video(decode=False) if k in videos else Image(decode=False) if k == 'preview'
                         else Value('int32') if k in ints else Value('float64') if k in {'duration_seconds', 'actual_episode_score'}
                         else Value('string') for k in order})
    ds = Dataset.from_list([{k: r[k] for k in order} for r in rows], features=features)
    configs = [dict(config_name='all', default=True, data_files=[dict(split='examples', path='data/all.parquet')])]
    (OUT / 'data').mkdir(exist_ok=True)
    ds.to_parquet(str(OUT / 'data/all.parquet'), batch_size=50)
    for group in GROUPS:
        name = group.lower().replace('-', '_')
        indices = [i for i,r in enumerate(rows) if r['category'] == group]
        ds.select(indices).to_parquet(str(OUT / f'data/{name}.parquet'), batch_size=50)
        configs.append(dict(config_name=name, data_files=[dict(split='examples', path=f'data/{name}.parquet')]))
    for t in tasks:
        indices = [i for i,r in enumerate(rows) if r['task_key'] == t['task_key']]
        assert indices, t['task_key']
        ds.select(indices).to_parquet(str(OUT / f"data/{t['config']}.parquet"), batch_size=50)
        configs.append(dict(config_name=t['config'], data_files=[dict(split='examples', path=f"data/{t['config']}.parquet")]))
    reference_rows = [dict(tool_name=k, video={'path': viewer_media_path(f'reference/{k}.mp4'), 'bytes': None},
        documentation=(OUT / f'reference/{k}.txt').read_text(encoding='utf-8'), source_url=DOC+f'/doc/sim-tasks/{k}/')
        for k in ['domain-randomization', 'parallel-environments']]
    Dataset.from_list(reference_rows, features=Features({'tool_name':Value('string'), 'video':Video(decode=False),
        'documentation':Value('string'), 'source_url':Value('string')})).to_parquet(str(OUT / 'data/reference_tools.parquet'), batch_size=2)
    configs.append(dict(config_name='reference_tools', data_files=[dict(split='examples', path='data/reference_tools.parquet')]))
    write(OUT / 'provenance/viewer_rows.json', [{k:v for k,v in r.items() if k not in videos | {'preview'}} for r in rows])
    frontmatter = dict(language=['en', 'zh'], license='other', license_name='upstream-robodojo-terms',
        license_link='LICENSE.md', pretty_name='RoboDojo Task Examples — official task index / top / left / right',
        tags=['robotics', 'robodojo', 'video', 'bimanual', 'task-catalog'], configs=configs)
    card = ['---', yaml.safe_dump(frontmatter, sort_keys=False, allow_unicode=True).rstrip(), '---',
        '# RoboDojo Task Examples',
        '\n**按官方 task_index 找任务,按 top → left wrist → right wrist 看完整示教。**',
        '\n43 个官网任务页面 · 35 个有公开示教的任务 · 每任务 3 条完整示教 · 12 个 random-layout 官网演示 · 8 个 Open eval-only 官网演示。',
        '\n这是精选浏览集,不是官方完整训练集。数据源:[官方 HF 数据](https://huggingface.co/datasets/RoboDojo-Benchmark/RoboDojo) / [官方任务文档](https://robodojo-benchmark.com/doc/sim-tasks/)。',
        '\n## 快速定位任务',
        f'\n[打开 MP4 任务浏览页]({BROWSER_URL}/?task=0)。下表「直接浏览 / 打开」按官方序号进入对应任务,支持六大类筛选、完整 MP4 播放和评分标准。',
        '\nHF 原生表格 Viewer 仍是可选入口,后台处理期间可能不可用;下表的直接浏览入口不依赖表格索引。',
        '\n- `task_index`:官方 LeRobot v2.1 `meta/tasks.jsonl` 的 **0–34**,没有重新编号。',
        '- `catalog_number`:本仓库对官网目录顺序的辅助编号 **C01–C43**,不是官方 task_index。',
        '- `episode_index`:官方 LeRobot 全局 episode ID;`source_local_episode`:原始任务目录的 episode 文件编号。',
        '- Open 类 8 个任务的 `task_index` / `episode_index` 为 null;只展示官网 eval-only 演示,不伪造示教。',
        '- `synchronized_views` 把同一 episode 的 **TOP / LEFT WRIST / RIGHT WRIST** 合成一行,同步播放,完整时长、25 FPS。',
        '- `top` / `left` / `right` 保留官方原始 H.264 预览视频(640×480),逐字节校验 SHA256。TOP 对应官方 `cam_head`(LeRobot 命名 `cam_high`),不是新生成的正交俯视相机。',
        '- Random version:官网公开 MP4 是 TOP / HEAD 单相机视角。画面里有双臂,但在已核查的官网和官方 HF 任务数据中未找到对应 LEFT / RIGHT 腕部录像,浏览页明确标记缺失。',
        '- `trajectory_url` 可下载该 episode 的官方动作与状态 Parquet(14 维双臂关节)。这是关节示教数据,不是未提供的笛卡尔腕部位姿。',
        '- `scoring` 是任务评分规则;官方未给每条示教评分,所以 `actual_episode_score` 为 null。',
        '- `instruction` 来自当前官网;`dataset_instruction` 来自官方 v2.1 数据。Build Tower / Organize Table 的两者有差异,页面逐项展示;不可把旧版示教当作已完成新版目标。',
        '- 每任务取原始 episode 0 / 49 / 99。官方没有背景 ID 标签,所以 `background_id` 为 null;多行是实际不同示教场景,不保证覆盖所有背景种类。random-layout 演示单列且标为 eval-only。',
        '\n## World-axis orientation 与分类',
        '\n![World-axis orientation](reference/world_axes.png)',
        '\nX 红 / Y 绿 / Z 蓝。箭头位置只用于展示方向,并不代表世界坐标系原点。分类沿用该标题下官网列出的六组。',
        '\n| 官方 task_index | 官网目录 | Task | Category | 直接浏览 |', '| --- | --- | --- | --- | --- |']
    for t in sorted(tasks, key=lambda t: t['task_index'] if t['task_index'] is not None else 100+t['catalog_number']):
        idx = str(t['task_index']) if t['task_index'] is not None else '—(eval-only)'
        token = str(t['task_index']) if t['task_index'] is not None else t['task_key']
        viewer = f"{BROWSER_URL}/?task={quote(token, safe='')}"
        card.append(f"| **{idx}** | C{t['catalog_number']:02d} | [{t['task_name']}]({t['doc_url']}) | {t['category']} | [打开]({viewer}) |")
    card.extend(['\n## 各任务示例、instruction 与评分', '\n每一行是同一 episode 的 top / left / right。点开同步视频可同时看三个视角;官网演示与正式示教分开标注。'])
    for group in GROUPS:
        card.append(f'\n## {group}')
        for t in [x for x in tasks if x['category'] == group]:
            idx = f"task_index={t['task_index']}" if t['task_index'] is not None else 'task_index=null · eval-only'
            card.extend([f"\n### {t['task_name']} · {idx} · C{t['catalog_number']:02d}",
                f"\n**Instruction:** {t['fields']['Instruction']}", f"\n**Description:** {t['fields']['Description']}",
                f"\n**Platform:** {t['fields']['Platform']} · **Data Source:** {t['fields']['Data Source']} · **Usage:** {t['fields']['Usage']}",
                f"\n[官方任务页]({t['doc_url']}) · [MP4 任务浏览]({BROWSER_URL}/?task={quote(str(t['task_index']) if t['task_index'] is not None else t['task_key'], safe='')}) · [HF 表格 Viewer(可选)](https://huggingface.co/datasets/{DEST}/viewer/{t['config']}/examples)"])
            if t['fields'].get('Comment'):
                card.append(f"\n**Comment:** {t['fields']['Comment']}")
            if t['instruction_match'] is False:
                card.append(f"\n**官方数据版本的 instruction(与当前官网不同):** {t['dataset_instruction']}")
            if t['scoring']:
                card.extend(['\n| Score | Condition |', '| --- | --- |'])
                card.extend(f"| {s['score']} | {s['condition'].replace('|', ' / ')} |" for s in t['scoring'])
            else:
                card.append('\n**Scoring:** 官网未提供该任务的评分标准。')
            ss = [s for s in samples if s['task_key'] == t['task_key']]
            if ss:
                card.extend(['\n| 官方 episode / 原始文件编号 | TOP → LEFT WRIST → RIGHT WRIST(同一帧) | 完整示教 |', '| --- | --- | --- |'])
                for s in ss:
                    card.append(f"| **{s['episode_index']}** / {s['source_local_episode']:07d} | ![Top / left / right]({s['preview_path']}) | [同步视频]({s['synchronized_views_path']}) · [top]({s['views']['top']['path']}) · [left]({s['views']['left']['path']}) · [right]({s['views']['right']['path']}) · [动作/状态]({s['trajectory_path']}) |")
            else:
                card.append('\n**公开示教数据:无(官方标记 eval-only)。** 官网演示如下:')
            for demo in t['documentation_videos']:
                if 'path' in demo:
                    card.append(f"\n**{demo['label']} · 官网演示(非训练示教):** [视频]({demo['path']}) · [官网原文件]({demo['url']})")
                    if 'Random' in demo['label']:
                        card.append('\n**视角可用性:** TOP / HEAD 已公开;LEFT WRIST 和 RIGHT WRIST 对应录像未公开(已核查官网与官方 HF 任务目录)。')
                else:
                    card.append(f"\n[官网 {demo['label']}]({demo['url']})")
    card.extend(['\n## 更多官网可展示内容',
        '\n[Domain Randomization](https://robodojo-benchmark.com/doc/sim-tasks/domain-randomization/):布局、材质、照明和背景随机化;[说明快照](reference/domain-randomization.txt)。',
        '\n[Parallel Environments](https://robodojo-benchmark.com/doc/sim-tasks/parallel-environments/):同一进程的并行模拟环境;[说明快照](reference/parallel-environments.txt)。',
        f'\n两段官网工具演示已保存,可在 [工具演示浏览页]({BROWSER_URL}/?task=reference) 直接播放。',
        '\n## 来源与复现', f"\n官方 HF 固定 revision:`{source['revision']}`。官网内容抓取日期:2026-10-03。",
        '\n完整对应表、每个相机文件的原始路径 / SHA256 / 大小、选取 episode、下载统计均在 `provenance/`。视频未下载 HDF5、深度图、assets 或 checkpoint。',
        '\n`python scripts/build_dataset.py prepare` → `download` → `render` → `package` → `validate` → `publish`。',
        '\n```python', 'from datasets import load_dataset', f'ds = load_dataset("{DEST}", "task_30_stack_bowls", split="examples")',
        '# official task_index=30; episode_index=3000, 3049, 3099', '```',
        '\n## 许可与署名',
        '\n本仓库为非官方精选整理;数据与演示归 RoboDojo 作者所有。HF 仓库标记 Apache-2.0,而当前代码仓库 README 另有非商业条款描述、LICENSE 文件为 MIT。来源声明存在差异,详见 [LICENSE.md](LICENSE.md);保留来源,不扩大原作者授予的使用权。'])
    (OUT / 'README.md').write_text('\n'.join(card)+'\n', encoding='utf-8')
    license_text = '# Upstream RoboDojo terms and attribution\n\nThis is an unofficial curated subset, not an ownership or relicensing claim.\n\n'
    license_text += f'- Official HF dataset metadata at revision {source["revision"]} declares Apache-2.0: https://huggingface.co/datasets/{SOURCE}\n'
    license_text += '- The upstream GitHub README describes non-commercial research terms, while its LICENSE file contains MIT. These source statements are inconsistent. Consult the maintainers for usage beyond clearly granted rights.\n'
    license_text += '- Source task text, scoring rules, website demos and dataset previews are credited to RoboDojo-Benchmark and the RoboDojo authors. All upstream rights and notices are retained.\n\n'
    upstream_license = WORK / 'official-code/LICENSE'
    if upstream_license.exists():
        license_text += '## Upstream code/documentation LICENSE snapshot\n\n'+upstream_license.read_text(encoding='utf-8')
    elif (OUT / 'LICENSE.md').exists():
        marker = '## Upstream code/documentation LICENSE snapshot\n\n'
        previous = (OUT / 'LICENSE.md').read_text(encoding='utf-8')
        if marker in previous:
            license_text += marker + previous.split(marker, 1)[1]
    (OUT / 'LICENSE.md').write_text(license_text, encoding='utf-8')
    (OUT / 'scripts').mkdir(exist_ok=True)
    shutil.copy2(__file__, OUT / 'scripts/build_dataset.py')
    (OUT / 'scripts/requirements.txt').write_text('huggingface_hub>=1.0\nrequests\nbeautifulsoup4\ndatasets>=4.0\npyarrow\nPillow\nPyYAML\n# ffmpeg and ffprobe must be on PATH\n', encoding='utf-8')
    print(f'Packaged {len(rows)} rows in {len(configs)} native HF viewer subsets.', flush=True)


def validate():
    import pyarrow.parquet as pq
    tasks = read(OUT / 'provenance/task_catalog.json')
    samples = read(OUT / 'provenance/selected_episodes.json')
    failures = []
    def check(s):
        errors = []
        data = pq.read_table(OUT / s['trajectory_path'])
        if data.num_rows != s['frame_count']:
            errors.append(f"trajectory frames {data.num_rows} != {s['frame_count']}")
        if set(data['task_index'].to_pylist()) != {s['task_index']}:
            errors.append('wrong official task_index')
        if set(data['episode_index'].to_pylist()) != {s['episode_index']}:
            errors.append('wrong official episode_index')
        if data['frame_index'].to_pylist() != list(range(data.num_rows)):
            errors.append('non-contiguous frames')
        view_stats = {}
        for v in ['top', 'left', 'right']:
            m = s['views'][v]
            p = OUT / m['path']
            if hashlib.sha256(p.read_bytes()).hexdigest() != m['source_sha256']:
                errors.append(v+' official checksum mismatch')
            stat = probe(p)
            view_stats[v] = {k:stat.get(k) for k in ['codec_name', 'width', 'height', 'nb_frames', 'duration', 'avg_frame_rate']}
            if int(stat['nb_frames']) != s['frame_count']:
                errors.append(f"{v} preview frames {stat['nb_frames']} != trajectory frames {s['frame_count']}")
        combined = probe(OUT / s['synchronized_views_path'])
        if int(combined['nb_frames']) != s['frame_count'] or (combined['width'], combined['height']) != (960,268):
            errors.append('composite shape/frames mismatch')
        return dict(task_index=s['task_index'], episode_index=s['episode_index'], errors=errors, views=view_stats)
    with cf.ThreadPoolExecutor(max_workers=5) as executor:
        results = list(executor.map(check, samples))
    for r in results:
        if r['errors']:
            failures.append(r)
    table = pq.read_table(OUT / 'data/all.parquet')
    assert table.num_rows == 125
    assert len(set(table['task_key'].to_pylist())) == 43
    assert len(samples) == 105
    assert sorted({s['task_index'] for s in samples}) == list(range(35))
    assert all(len([s for s in samples if s['task_key']==t['task_key']]) == 3 for t in tasks if t['task_index'] is not None)
    # Validate every subset, including reference_tools, against the renderer's
    # actual accepted URL format, rather than only testing browser file URLs.
    for parquet in (OUT / 'data').glob('*.parquet'):
        subset = pq.read_table(parquet)
        for column in ['synchronized_views','top','left','right','official_demo','preview','video']:
            if column not in subset.column_names:
                continue
            for x in subset[column].to_pylist():
                if x:
                    prefix = f'hf://datasets/{DEST}@main/'
                    assert x['path'].startswith(prefix), (parquet.name, column, x['path'])
                    relative = x['path'][len(prefix):]
                    assert (OUT / relative).exists(), relative
    all_files = list(OUT.rglob('*'))
    report = dict(passed=not failures, failures=failures, catalog_tasks=43, official_tasks=35, demonstrations=105,
                  website_demo_rows=20, viewer_rows=125, total_files=sum(p.is_file() for p in all_files),
                  dataset_bytes=sum(p.stat().st_size for p in all_files if p.is_file()), episode_checks=results)
    write(OUT / 'provenance/validation.json', report)
    print(json.dumps({k:v for k,v in report.items() if k != 'episode_checks'}, indent=2), flush=True)
    if failures:
        raise SystemExit('Validation failed; no publication allowed.')


def publish():
    report = read(OUT / 'provenance/validation.json')
    assert report['passed']
    api = HfApi()
    assert api.whoami()['name'] == DEST.split('/')[0]
    repo = api.create_repo(DEST, repo_type='dataset', private=False, exist_ok=True)
    print('Repository:', repo, flush=True)
    commit = api.upload_folder(repo_id=DEST, repo_type='dataset', folder_path=str(OUT),
        commit_message='Add source-verified task index, 105 synchronized demonstrations and complete task documentation')
    write(WORK / 'publication.json', dict(repo_id=DEST, repo_url=str(repo), commit_url=str(commit), commit_sha=commit.oid))
    print('Published:', commit, flush=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('stage', choices=['prepare','download','render','package','validate','publish'])
    args = parser.parse_args()
    WORK.mkdir(exist_ok=True)
    OUT.mkdir(exist_ok=True)
    globals()[args.stage]()