File size: 11,869 Bytes
347d9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Canonical model-only inputs, separate gold and matched receiver task groups."""
from __future__ import annotations
import argparse,copy,secrets
from collections import Counter
from pathlib import Path
import numpy as np
from .common import *
from .prompts import render,robot_poses,playback_log


def motion_state(entities):
    if not entities:return 'none'
    moving=[bool(np.any(entity['displacement_m'])) for entity in entities]
    return 'moving' if all(moving) else 'static' if not any(moving) else 'mixed'


def frames(scene,human,receiver=None,kind='xyz_m'):
    out=[]
    for sample in grid(scene):
        t=sample/SR;on=active(human,sample);f=dict(time_s=t,active=on)
        if on:f[kind]=position(human,t).tolist() if kind=='xyz_m' else geometry(human,receiver,t)[kind]
        out.append(f)
    return out


def private_scene(scene,group):
    result=copy.deepcopy(scene);times=[s/SR for s in grid(scene)]
    for e in result['humans']+result['robots']:
        e['is_moving']=bool(np.any(e['displacement_m']));e['positions_world_m']=[[t]+position(e,t).tolist() for t in times]
        e['velocities_world_mps']=[[t]+velocity(e,t).tolist() for t in times]
        e['speeds_mps']=[float(np.linalg.norm(velocity(e,t))) for t in times]
        length=float(np.linalg.norm(e['displacement_m']));e['motion_direction_world']=(np.asarray(e['displacement_m'])/length).tolist() if length else None
        e['relative_to_robots']={}
        for robot in scene['robots']:
            if robot['entity_id']==e['entity_id']:
                e['relative_to_robots'][robot['entity_id']]=dict(same_entity=True,distance_m=0.)
            else:e['relative_to_robots'][robot['entity_id']]=[dict(time_s=t,
                displacement_world_m=(position(e,t)-position(robot,t)).tolist(),**geometry(e,robot,t)) for t in times]
        if e['entity_type']=='human':
            spans=sorted(pair for event in e['events'] for pair in event['activity_samples']);on=e['motion_start_s'];off=on+e['motion_duration_s']
            voiced=sum(max(0.,min(b/SR,off)-max(a/SR,on)) for a,b in spans)
            gaps=[(a[1]/SR,b[0]/SR) for a,b in zip(spans,spans[1:]) if b[0]>a[1]]
            e['continuity_audit']=dict(maximum_internal_silence_s=max_internal_gap(e['events']),
                motion_interval_s=[on,off],voiced_fraction_during_motion=voiced/(off-on),
                maximum_displacement_during_internal_silence_m=max((float(np.linalg.norm(position(e,b)-position(e,a))) for a,b in gaps),default=0.))
    result['room_stratum']=dict(area_bin=group['room']['area_bin'],rt_bin=group['room']['rt_bin'],area_m2=group['room']['area_m2'])
    return result


def export(root,pilot=False):
    root=root.resolve();groups=list(rows(root/'private/recipes.jsonl'));config=read(root/'config.json')
    if pilot:groups=[g for g in groups if (root/'reports/groups'/(g['group_id']+'.json')).exists()]
    if not groups:raise ValueError('No completed motion groups to export')
    # A small candidate target vocabulary must not be recoverable by hashing
    # public scene/query values. Freeze a private ID salt, separate from physics.
    all_groups=list(rows(root/'private/recipes.jsonl'));nonces={}
    for group in all_groups:
        group.setdefault('evaluation_id_nonce',secrets.token_hex(16));nonces[group['group_id']]=group['evaluation_id_nonce']
    jsonl(root/'private/recipes.jsonl',all_groups)
    for group in groups:group['evaluation_id_nonce']=nonces[group['group_id']]
    inputs=[];prompts=[];gold=[];public_scenes=[];private_scenes=[];records=[];views=[];pairs=[];motion_groups=[]
    for group in groups:
        nonce=group['evaluation_id_nonce']
        report=read(root/'reports/groups'/(group['group_id']+'.json'))
        if not report['passed']:raise ValueError('Cannot export an unverified render')
        byscene={sid:[r for r in report['recordings'] if r['scene_id']==sid] for sid in report['scene_ids']}
        motion_groups.append(dict(scene_group_id=group['group_id'],parent_static_scene_id=group['parent_static_scene_id'],room_id=group['room_id'],
            scenes=[dict(scene_id=s['scene_id'],branch=s['branch'],difficulty=s['difficulty']) for s in group['scenes']]))
        for scene in group['scenes']:
            sid=scene['scene_id'];rids=[r['entity_id'] for r in scene['robots']];recs={r['receiver_robot_id']:r for r in byscene[sid]};records.extend(byscene[sid])
            pub=dict(schema_version=VERSION,scene_id=sid,scene_group_id=group['group_id'],parent_static_scene_id=group['parent_static_scene_id'],
                split='test',room_id=group['room_id'],branch=scene['branch'],difficulty=scene['difficulty'],duration_samples=scene['duration_samples'],
                sample_rate_hz=SR,evaluation_step_samples=STEP,scene_robot_ids=rids,robot_pose_trajectories=robot_poses(scene),
                robot_speech_metadata=playback_log(scene),room_asset_directory='public/assets/rooms/'+group['room_id']+'/assets/room',
                strict_sync=True,own_playback_policy='ideal_own_only',coordinate_convention=scene['coordinate_convention'])
            public_scenes.append(pub);private_scenes.append(private_scene(scene,group))
            for observed in [[rid] for rid in rids]+[rids]:
                views.append(dict(view_id=uid(sid,'view',observed),scene_id=sid,scene_group_id=group['group_id'],setting='cloud' if len(observed)>1 else 'edge',
                    receiver_ids=observed,recording_ids=[recs[r]['recording_id'] for r in observed]))
            queries=[]
            # Same whole-human DOA question, instantiated for every receiver.
            doa_group=uid(sid,'query','DOA_TRAJECTORY','all_humans',nonce)
            for robot in scene['robots']:
                rid=robot['entity_id'];queries.append(('DOA_TRAJECTORY',[rid],rid,{},
                    dict(tracks=[dict(track_id=h['entity_id'],frames=frames(scene,h,robot,'doa_deg')) for h in scene['humans']]),'all_humans',None,doa_group))
            for human in scene['humans']:
                hid=human['entity_id'];query_group=uid(sid,'query','RANGE_TRAJECTORY',hid,nonce)
                for robot in scene['robots']:
                    rid=robot['entity_id'];cue=next(q for q in scene['geometry_audit']['range_queries'] if q['source_id']==hid and q['receiver_id']==rid)
                    cue={k:v for k,v in cue.items() if k not in ['source_id','receiver_id']}
                    queries.append(('RANGE_TRAJECTORY',[rid],rid,cue,dict(frames=frames(scene,human,robot,'distance_m')),hid,None,query_group))
                queries.append(('TEXT_TRAJECTORY',rids,None,dict(transcript=human['events'][0]['text']),dict(frames=frames(scene,human)),hid,None,
                    uid(sid,'query','TEXT_TRAJECTORY',hid,nonce)))
            for target,phrase in scene['keywords'].items():
                case='unique_human' if target.startswith('H') else target;human=next((h for h in scene['humans'] if h['entity_id']==target),None)
                text=' '.join(e['text'] for e in sorted(human['events'],key=lambda e:e['start_sample'])) if human else ''
                query_group=uid(sid,'query','KW_ASR',target,phrase,nonce)
                for observed in [[rid] for rid in rids]+[rids]:queries.append(('KW_ASR',observed,None,dict(wake_phrase=phrase),text,target,case,query_group))
            collected={}
            for task,observed,reference,query,answer,target,case,query_group in queries:
                setting='cloud' if len(observed)>1 else 'edge';view_id=uid(sid,'view',observed);sample_id=uid(sid,view_id,task,query_group)
                binding=[dict(slot=i,robot_id=rid,recording_id=recs[rid]['recording_id'],path=recs[rid]['path'],sha256=recs[rid]['sha256']) for i,rid in enumerate(observed)]
                prompt=render(scene,task,query,observed,reference)
                row=dict(schema_version=VERSION,sample_id=sample_id,scene_id=sid,scene_group_id=group['group_id'],view_id=view_id,query_group_id=query_group,
                    target_group_id=uid(sid,'target',target,nonce),task_id=task,setting=setting,reference_robot_id=reference,
                    receiver_ids=observed,recording_ids=[recs[r]['recording_id'] for r in observed],audio_bindings=binding,
                    time_window_samples=[0,scene['duration_samples']],sample_rate_hz=SR,evaluation_step_samples=STEP,
                    query=query,known_robot_poses=robot_poses(scene),known_robot_playback=playback_log(scene),
                    prompt_template_version=VERSION+'.1',output_schema='transcription_string' if task=='KW_ASR' else 'human_tracks_json' if task=='DOA_TRAJECTORY' else 'trajectory_json')
                g=dict(sample_id=sample_id,scene_id=sid,scene_group_id=group['group_id'],query_group_id=query_group,target_group_id=row['target_group_id'],
                    task_id=task,setting=setting,branch=scene['branch'],difficulty=scene['difficulty'],target_source_id=target,
                    room_id=group['room_id'],area_bin=group['room']['area_bin'],rt_bin=group['room']['rt_bin'],
                    num_humans=len(scene['humans']),num_robots=len(rids),expected_times_s=[s/SR for s in grid(scene)],keyword_case=case,output=answer)
                target_humans=scene['humans'] if task=='DOA_TRAJECTORY' else [h for h in scene['humans'] if h['entity_id']==target]
                g['target_human_motion']=motion_state(target_humans)
                g['observed_receiver_motion']=motion_state([r for r in scene['robots'] if r['entity_id'] in observed])
                if case=='robot_only':
                    matching=[r['entity_id'] for r in scene['playback_sources'] if any(tokens(e['text'])[:len(tokens(query['wake_phrase']))]==tokens(query['wake_phrase']) for e in r['events'])]
                    g['keyword_observation_case']='robot_only_audible' if any(source!=receiver for source in matching for receiver in observed) else 'robot_only_removed'
                inputs.append(row);prompts.append(dict(sample_id=sample_id,prompt_template_version=row['prompt_template_version'],rendered_prompt=prompt));gold.append(g)
                collected.setdefault(query_group,dict(query_group_id=query_group,scene_id=sid,task_id=task,target_group_id=row['target_group_id'],samples=[]))['samples'].append(dict(sample_id=sample_id,view_id=view_id,setting=setting,receiver_ids=observed))
            pairs.extend(collected.values())
    if not pilot and len(public_scenes)!=2000:raise ValueError('Full export requires exactly 2,000 completed physical scenes')
    shuffled=sorted(zip(inputs,prompts,gold),key=lambda t:t[0]['sample_id'])
    inputs=[a for a,b,c in shuffled];prompts=[b for a,b,c in shuffled];gold=[c for a,b,c in shuffled]
    for name,data in [('scenes',public_scenes),('recordings',records),('views',views),('pairs',pairs),('inputs',inputs),('prompts',prompts),('motion_groups',motion_groups)]:jsonl(root/'public/test'/(name+'.jsonl'),data)
    jsonl(root/'private/test/scenes.jsonl',private_scenes);jsonl(root/'private/test/gold.jsonl',gold)
    report=dict(schema_version=VERSION,physical_scenes=len(public_scenes),paired_motion_groups=len(groups),rooms=len({s['room_id'] for s in public_scenes}),
        recordings=len(records),binaural_previews=0,views=len(views),task_requests=len(inputs),query_groups=len(pairs),
        tasks=dict(Counter((r['setting']+'/'+r['task_id']) for r in inputs)),branches=dict(Counter(s['branch'] for s in public_scenes)),
        output_step_s=.2,model_inference_performed=False,human_listening_audit_completed=False,pilot=pilot)
    write(root/'summary.json',report)
    from .loader import build_index
    assert build_index(root)==len(inputs)
    print('EXPORTED',report,flush=True)


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--pilot',action='store_true');a=p.parse_args();export(a.root,a.pilot)