File size: 4,764 Bytes
5bbd053
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export public replay assets; never publish raw run logs or local paths."""
import json, shutil, subprocess
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'logs/combined-gpt55-160-20261005T074317Z'
OUT=Path(__file__).resolve().parent/'dist'
(OUT/'episodes').mkdir(exist_ok=True)
(OUT/'videos').mkdir(exist_ok=True)

def public_result(value):
    from export_agent_records import redact
    if isinstance(value, str):
        return redact(value)
    if isinstance(value, dict):
        return {k: public_result(v) for k, v in value.items() if k != 'traceback'}
    if isinstance(value, list):
        return [public_result(v) for v in value]
    return value


def export(row, source=SRC, prefix=""):

    ident=prefix+f"{row['suite']}_task-{row['task']:02d}_seed-{row['seed']}"
    src=source/row['suite']/f"task-{row['task']:02d}-seed-{row['seed']}"
    states=json.loads((src/'states.json').read_text())['steps']
    stats=json.loads(next(src.glob('transcript*.json')).read_text()).get('stats',{})
    probe=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_entries','stream=nb_frames,duration','-of','json',str(src/'episode.mp4')]))['streams'][0]
    frames=int(probe['nb_frames']);cursor=0;actions=[]
    for st in states[1:]:
        c=st.get('command',{});v=st.get('result',{});a=c.get('action','unknown')
        if v.get('error'): n=0
        elif a=='pi0_place': n=v['steps_used']
        elif a.startswith('pi0') and v.get('error') == "vla.predict: unknown RPC method: 'vla.predict'": n=0
        elif a.startswith('pi0'): n=v['chunks_used']*5
        elif a=='set_gripper': n=v['steps']
        else:
            n=v['steps_used'];default={'move_to':80,'move_pose':150,'rotate_wrist':40,'rotate_pitch':40}.get(a)
            if default and n<c.get('max_steps',default) and not (st.get('terminated') or st.get('truncated')): n-=1
        if not prefix and (row['suite'],row['task'],row['seed'],st['step_idx'])==('libero_10_task',4,1,23):n-=1
        actions.append({'step':st['step_idx'],'tool':a,'kind':'vla' if a.startswith('pi0') else 'primitive','start':cursor/20,'end':(cursor+n)/20,'command':c,'result':public_result(v),'terminated':bool(st.get('terminated'))})
        cursor+=n
    # A convergence check on the final loop iteration reports max_steps although
    # it advances no frame. Resolve only a unique move_to candidate, backed by
    # its tolerance result and the independently measured video frame count.
    if prefix and cursor - frames == 1:
        candidates = [i for i, action in enumerate(actions)
                      if action['tool'] == 'move_to'
                      and not action['terminated']
                      and action['result']['steps_used'] == action['result']['max_steps']
                      and action['result']['final_dist_m'] < action['command'].get('tol', .012)]
        if len(candidates) == 1:
            index = candidates[0]
            actions[index]['end'] -= 1 / 20
            actions[index]['mappingNote'] = '最后一次循环是收敛检查,没有推进环境;用视频总帧数与唯一候选调用核对。'
            for action in actions[index + 1:]:
                action['start'] -= 1 / 20
                action['end'] -= 1 / 20
            cursor -= 1
    # set_gripper reports requested steps even when native success stops it early.
    if cursor != frames and actions[-1]['tool']=='set_gripper' and actions[-1]['terminated']:
        excess=cursor-frames
        assert 0 < excess < actions[-1]['command']['steps']
        actions[-1]['end']=frames/20
        cursor=frames
    assert cursor==frames, (ident,cursor,frames)
    item={'id':ident,'suite':row['suite'],'task':row['task'],'seed':row['seed'],'success':row['environment_success'],'instruction':states[0]['extras']['task_language'],'duration':float(probe['duration']),'gptRounds':stats.get('turns_used'),'vlaCalls':sum(a['kind']=='vla' for a in actions),'actionsCount':len(actions),'frames':frames,'mappedFrames':cursor,'aligned':frames==cursor,'video':f'videos/{ident}.mp4'}
    (OUT/'episodes'/f'{ident}.json').write_text(json.dumps({**item,'actions':actions},ensure_ascii=False))
    shutil.copyfile(src/'episode.mp4',OUT/item['video'])
    return item
if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=8) as pool: rows=list(pool.map(export,json.loads((SRC/'summary.json').read_text())['results']))
    (OUT/'catalog.json').write_text(json.dumps(rows,ensure_ascii=False))
    print('Exported',len(rows),'episodes; aligned',sum(x['aligned'] for x in rows))
    print(json.dumps([{k:r[k] for k in ('id','frames','mappedFrames')} for r in rows if not r['aligned']],indent=2))