"""Generate a free static HF Space from selected benchmark metadata."""
from pathlib import Path
import json,re,shutil
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
DATA=ROOT if (ROOT/'provenance/source.json').exists() else ROOT/'dataset'
OUT=ROOT/'space'
JS=r'''
const DATA=JSON.parse(document.getElementById('catalog').textContent);
const esc=x=>String(x??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const media=p=>DATA.media_base+p.split('/').map(encodeURIComponent).join('/');
const file=p=>DATA.file_base+p.split('/').map(encodeURIComponent).join('/');
const link=(u,t)=>`${esc(t)} `;
const tasks=[...DATA.tasks].sort((a,b)=>a.task_index-b.task_index);
const groups=[...new Set(tasks.map(t=>t.category))];
let current=null,query='',group='all',mode='combined';
function drawList(){
document.getElementById('groups').innerHTML=['all',...groups].map(g=>`${g==='all'?'全部':esc(g)}${g==='all'?tasks.length:tasks.filter(t=>t.category===g).length} `).join('');
const numeric=/^\d+$/.test(query.trim());
const shown=tasks.filter(t=>(numeric||group==='all'||t.category===group)&&(numeric?t.task_index===Number(query):`${t.name} ${t.instruction} ${t.source_filename??''}`.toLowerCase().includes(query.toLowerCase())));
document.getElementById('listCount').textContent=`${shown.length} / ${tasks.length}`;
document.getElementById('taskList').innerHTML=shown.map(t=>`${t.task_index} ${esc(t.name)} `).join('')||'
没有匹配的精选任务序号。
';
document.querySelectorAll('[data-group]').forEach(b=>b.onclick=()=>{group=b.dataset.group;drawList()});
document.querySelectorAll('[data-task]').forEach(b=>b.onclick=()=>{selectTask(b.dataset.task);window.scrollTo({top:0})});
}
function selectTask(id,historyUpdate=true){document.querySelectorAll('video').forEach(v=>v.pause());current=tasks.find(t=>t.task_index===Number(id));if(historyUpdate)history.replaceState({},'',`?task=${id}`);drawList();drawTask();document.querySelector('.task-link.active')?.scrollIntoView({block:'nearest'});}
function player(p,poster=''){return ` `}
function episode(s){
const n=s.views.length;
const content=mode==='combined'?`${s.views.map(v=>`${esc(v.label)} `).join('')}
${player(s.composite_path,s.preview_path)}
`:``;
return `EPISODE ${s.episode_index} 官方 task_index=${s.task_index} · ${s.frame_count} frames · ${s.fps} FPS · ${(s.frame_count/s.fps).toFixed(2)} s
OFFICIAL DATA EXTRACT ${content}${s.source_filename?`${esc(s.source_filename)}
`:''}
`;
}
function drawTask(){
const top=`${esc(DATA.name)} / ${DATA.samples.length} SELECTED EPISODES / ${DATA.source.camera_order.length} CAMERAS${link(DATA.repo_url,'HF 数据仓库 ↗')}${link(DATA.github_url,'官方代码 ↗')}
`;
if(!current){document.getElementById('main').innerHTML=top+'精选集中没有这个序号 请从左侧选择,或输入已收录的官方 task_index。
';return}
const t=current,idx=tasks.indexOf(t),ss=DATA.samples.filter(s=>s.task_index===t.task_index),dynamic=DATA.name==='DynamicVLA';
document.title=`Task ${t.task_index} · ${t.name} · ${DATA.name}`;
let html=top+`${dynamic?'DOM 有 3 类任务,但官方 task_index 对应具体语言 / 场景配置。本页是三类各 6 条精选示例,不是完整 140,932 条任务目录。':'ReflexBench 的全部 6 个官方 task_index,每任务 3 条精选完整 episode。上游记录本身多为约 1 秒,此处没有截短、慢放或补帧。'} 单臂 Franka;相机名称保留上游定义。
${esc(t.category)} · SIMULATION
${t.task_index}
${esc(t.name)} OFFICIAL task_index = ${t.task_index} ← 上一个 下一个 →
成功标准 ↓ Instruction ${dynamic?'· 可读呈现':'· 官方数据原文'}
${esc(t.instruction)}
`;
if(t.instruction_note)html+=`${esc(t.instruction_note)}
`;
if(t.instruction_metadata)html+=`原始 instruction 元数据与所有对象 / 容器别名 ${esc(JSON.stringify(t.instruction_metadata,null,2))} `;
html+=`${esc(t.description)}
RobotFranka · 单臂
Published cameras${esc(DATA.source.camera_order.join(' / '))}
Official reference${link(t.doc_url,'成功条件源码 / 文档 ↗')}
${t.official_gym_id?`
Gym ID${esc(t.official_gym_id)}
`:''}
完整 MP4 示例 ${dynamic?'OPPOSITE → WRIST → SIDE;每路均为同一个官方 episode。':'FIXED → WRIST;原始 LeRobot 合并视频按官方 episode 时间区间提取。'}
相机同步 MP4 各路 MP4
${ss.map(episode).join('')} `;
html+=`
Success · 成功与评估标准 这是任务的评估逻辑,不能据此为示例赋分。公开 LeRobot 特征未保存逐条示教的成功标记,actual_episode_success 为 null;没有另行运行模拟器验证示例结果。
`;
if(t.profile)html+=`官方评估 profile / task phases ${esc(JSON.stringify(t.profile,null,2))} `;
html+=` `;
document.getElementById('main').innerHTML=html;
for(const [name,step] of [['previous',-1],['next',1]])document.getElementById(name).onclick=()=>{query='';document.getElementById('search').value='';selectTask(tasks[idx+step].task_index);window.scrollTo({top:0})};
document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{const y=scrollY;document.querySelectorAll('video').forEach(v=>v.pause());mode=b.dataset.mode;drawTask();window.scrollTo({top:y})});
bindVideos();
}
function bindVideos(){
document.querySelectorAll('[data-episode]').forEach(el=>{const vs=[...el.querySelectorAll('video')],error=el.querySelector('.error');vs.forEach(v=>v.onerror=()=>{error.hidden=false;error.textContent='此 MP4 加载失败,可用下方文件链接直接打开。'});if(vs.length===1)return;let timer=null;const pause=()=>{vs.forEach(v=>v.pause());clearInterval(timer);timer=null};el.querySelector('[data-play]').onclick=async()=>{try{vs.forEach(v=>{if(v.readyState)v.currentTime=vs[0].currentTime});await Promise.all(vs.map(v=>v.play()));clearInterval(timer);timer=setInterval(()=>{if(!el.isConnected){clearInterval(timer);return}for(const v of vs.slice(1))if(v.readyState&&Math.abs(v.currentTime-vs[0].currentTime)>.2)v.currentTime=vs[0].currentTime},300)}catch(e){pause();error.hidden=false;error.textContent='请点击原播放器,或切换到同步合并 MP4。'}};el.querySelector('[data-pause]').onclick=pause;el.querySelector('[data-reset]').onclick=()=>{pause();vs.forEach(v=>{if(v.readyState)v.currentTime=0})};vs[0].addEventListener('pause',pause);vs[0].addEventListener('ended',pause);});
}
document.getElementById('search').oninput=e=>{query=e.target.value;drawList()};
selectTask(new URLSearchParams(location.search).get('task')??tasks[0].task_index,false);
'''
def build():
source=json.loads((DATA/'provenance/source.json').read_text(encoding='utf-8'))
tasks=json.loads((DATA/'provenance/tasks.json').read_text(encoding='utf-8'))
samples=json.loads((DATA/'provenance/samples.json').read_text(encoding='utf-8'))
publication=json.loads(((ROOT/'publication.json') if (ROOT/'publication.json').exists() else (DATA/'provenance/media_publication.json')).read_text(encoding='utf-8'))
media_revision=publication['dataset_commit_sha']
payload=dict(name=NAME,tasks=tasks,samples=samples,source=source,repo_url=f'https://huggingface.co/datasets/Travor278/{NAME}-Task-Examples',github_url='https://github.com/'+source['code_repository'],media_base=f'https://huggingface.co/datasets/Travor278/{NAME}-Task-Examples/resolve/{media_revision}/',file_base=f'https://huggingface.co/datasets/Travor278/{NAME}-Task-Examples/blob/{media_revision}/')
template=(ROOT/'browser/base.html').read_text(encoding='utf-8')
template=re.sub(r'',template,flags=re.S)
template=re.sub(r'',lambda m:'',template,flags=re.S)
template=template.replace('RoboDojo',NAME).replace('工具演示 ','')
template=template.replace('https://huggingface.co/datasets/Travor278/RoboDojo-Task-Examples',payload['repo_url'])
n=len(samples[0]['views']);aspect=f'{320*n}/{348 if NAME=="ReflexBench" else 268}'
extra=f'.combined video{{aspect-ratio:{aspect}}}.view video{{aspect-ratio:{"1/1" if NAME=="ReflexBench" else "4/3"}}}.big-id{{font-size:46px;letter-spacing:-2px}}.benchmark-note{{font-size:11px;line-height:1.8;color:var(--muted);padding:13px 16px;border:1px solid var(--line);margin-bottom:22px;background:#e7ecde}}.metadata{{font-size:12px;background:var(--white);border:1px solid var(--line);padding:13px 16px;margin:12px 0}}.metadata summary{{cursor:pointer}}.metadata pre{{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.7;font-size:11px}}.success p{{font-size:15px}}.source-name{{padding:0 16px 12px;overflow-wrap:anywhere}}.task-heading{{flex-wrap:wrap}}.task-link .id{{font-size:11px;min-width:40px}}.toplinks{{flex-wrap:wrap}}'
template=template.replace('',extra+'')
encoded=json.dumps(payload,ensure_ascii=False,separators=(',',':')).replace('','<\\/')
OUT.mkdir(exist_ok=True);(OUT/'index.html').write_text(template.replace('__DATA__',encoded),encoding='utf-8')
(OUT/'README.md').write_text(f'''---
title: {NAME} Task Examples
emoji: 🦾
colorFrom: green
colorTo: gray
sdk: static
app_file: index.html
fullWidth: true
---
# {NAME} Simulation Task Browser
Official task-indexed selected MP4 episodes, instructions and source-grounded success rules.
This static Space references videos in the selected dataset; no duplicated media or simulation assets.
Dataset: {payload['repo_url']}
''',encoding='utf-8')
print(f'Built {NAME} browser: {len(tasks)} official instruction IDs, {len(samples)} episodes, media revision {media_revision}')
if __name__=='__main__':build()