File size: 12,649 Bytes
6a16e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Export only the five agreed task families, public prompts and paired views."""
from __future__ import annotations

import argparse
import copy
import math
from pathlib import Path

import numpy as np

from .common import SR, VERSION, active, geometry, grid, jsonl, position, read, tokens, uid, velocity, write


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


def robot_trace(scene):
    return [dict(robot_id=r['entity_id'],yaw_deg=round(r['yaw_deg']),height_m=round(r['initial_xyz_m'][1],1),
        positions=[[s/SR]+[round(float(x),1) for x in position(r,s/SR)] for s in grid(scene)]) for r in scene['robots']]


def prompt(scene,recordings,task,query,receiver_ids,reference=None):
    lines=['You are given FOA recordings of the same dynamic speech scene.']
    for rid in receiver_ids:
        lines.append(rid+': <|AUDIO|><|spatial|>')
    lines += [f"Audio covers [0.000, {scene['duration_samples']/SR:.3f}) seconds on one synchronized scene clock.",
        'Use global scene times 0.0, 0.1, 0.2, ... strictly before the end of the recording.',
        'Label the physical source position at the indicated scene time. Acoustic propagation delay remains in the audio.',
        'Each robot recording has its own playback ideally removed; other robot playback may be audible.',
        'Only human speech is a target. Robot playback is interference.',
        'FOA is 16 kHz ACN/SN3D [W,Y,Z,X]; X=front, Y=left, Z=up in each receiver frame.',
        'World coordinates are [x,y,z] meters, +y up. Yaw 0 faces world -z; positive yaw turns towards +x.',
        'Robot yaw and height stay constant; robots may translate horizontally.',
        'Known robot positions below are rounded to 0.1 m; times are seconds. Yaw is rounded to whole degrees.']
    import json
    for r in robot_trace(scene):
        lines.append(r['robot_id']+f": yaw {r['yaw_deg']} degrees; [time,x,y,z] = "+json.dumps(r['positions'],separators=(',',':')))
    lines.append('Known robot playback log:')
    for s in scene['playback_sources']:
        for e in s['events']:
            lines.append(s['entity_id']+f": [{e['start_sample']/SR:.3f}, {e['end_sample']/SR:.3f}) s; text "+json.dumps(e['text']))
    if reference:
        lines += ['Use '+reference+' as the direction and distance reference at each time.',
            'Azimuth: front 0 degrees, left +90, right -90; elevation is positive upwards.',
            'Directions are absolute DOA in the current receiver frame, not changes from an initial direction.']
    if task=='DOA_TRAJECTORY':
        lines += [f"Return {len(scene['humans'])} human speaker tracks. Keep a stable arbitrary track_id for each person across all turns.",
            'Return JSON {"tracks":[{"track_id":"S1","frames":[{"time_s":0.0,"active":false}, ...]}, ...]}.',
            'Include every requested grid time in every track. active indicates emitted human speech, excluding phonetic pauses and reverberation-only tails.',
            'When active=true, add "doa_deg":[azimuth,elevation]. Do not output a location when active=false.']
    elif task=='RANGE_TRAJECTORY':
        lines += [f"Select the human speaking during [{query['cue_time_range_s'][0]:.3f}, {query['cue_time_range_s'][1]:.3f}) s whose direction at {query['selection_time_s']:.3f} s is in azimuth sector [{query['initial_sector_deg'][0]}, {query['initial_sector_deg'][1]}) degrees.",
            'The sector selects the person only at the initial selection time. Continue following that same person even after they leave the sector.',
            'Return JSON {"frames":[{"time_s":0.0,"active":false}, ...]} covering every grid time.',
            'When this person emits speech, set active=true and add "distance_m": a positive distance from the current microphone. Otherwise set active=false.']
    elif task=='TEXT_TRAJECTORY':
        lines += ['Find the human saying '+json.dumps(query['transcript'])+'.',
            'Follow this same person during ALL their speech turns in the whole supplied clip, including turns with different words.',
            'Return JSON {"frames":[{"time_s":0.0,"active":false}, ...]} covering every grid time.',
            'When this person emits speech, set active=true and add "xyz_m":[x,y,z] in WORLD coordinates. Otherwise set active=false.']
    else:
        lines += ['The wake phrase is '+json.dumps(query['wake_phrase'])+'.',
            'Match complete words at the BEGINNING of a human utterance, ignoring case and punctuation. Repeated matches by the same human count as one person.',
            'If exactly one distinct human matches, transcribe ALL of that person\'s speech in the input clip, including the wake phrase and speech before/after it, in time order.',
            'Do not transcribe any other person or any robot playback. If no human or multiple humans match, return an empty string.',
            'Return only the transcription text, with no explanation.']
    return '\n'.join(lines)


def export(root):
    recipe=read(root/'data/recipe.json');rendering=read(root/'data/rendering.json')
    inputs=[];gold=[];pairs=[];browser=[]
    for scene in recipe['scenes']:
        recordings=[r for r in rendering['recordings'] if r['branch']==scene['branch']]
        by_robot={r['receiver_id']:r for r in recordings};h=scene['humans'][0]
        queries=[]
        for rid in ('R01','R02'):
            r=next(r for r in scene['robots'] if r['entity_id']==rid)
            queries.append(('DOA_TRAJECTORY','edge',[rid],rid,{},
                dict(tracks=[dict(track_id=s['entity_id'],frames=frames(scene,s,r,'doa_deg')) for s in scene['humans']]),'humans',None))
            anchor=next(s for s in grid(scene) if active(h,s))/SR
            az=geometry(h,r,anchor)['doa_deg'][0];low=int(math.floor(az/30.)*30)
            cue=dict(selection_time_s=anchor,cue_time_range_s=[anchor,anchor+.2],initial_sector_deg=[low,low+30])
            queries.append(('RANGE_TRAJECTORY','edge',[rid],rid,cue,
                dict(frames=frames(scene,h,r,'distance_m')),'H01',None))
        queries.append(('TEXT_TRAJECTORY','cloud',['R01','R02'],None,dict(transcript=h['events'][0]['text']),
            dict(frames=frames(scene,h,kind='xyz_m')),'H01',None))
        positive=' '.join(tokens(h['events'][0]['text'])[:2])
        robot_phrase=' '.join(tokens(scene['playback_sources'][0]['events'][0]['text'])[:2])
        for case,phrase in [('unique_human',positive),('no_match','violet lantern'),('robot_only',robot_phrase)]:
            matched=[]
            for human in scene['humans']:
                if any(tokens(e['text'])[:len(tokens(phrase))]==tokens(phrase) for e in human['events']):matched.append(human)
            if case=='unique_human' and (len(matched)!=1 or matched[0]['entity_id']!='H01'):
                raise ValueError('Wake phrase not unique at an utterance prefix')
            if case!='unique_human' and matched:raise ValueError('Negative wake phrase unexpectedly matches a human')
            answer=' '.join(e['text'] for e in sorted(h['events'],key=lambda e:e['start_sample'])) if matched else ''
            for ids in [['R01'],['R02'],['R01','R02']]:
                queries.append(('KW_ASR','cloud' if len(ids)>1 else 'edge',ids,None,
                    dict(wake_phrase=phrase),answer,'H01' if matched else 'none',case))
        samples=[]
        for task,setting,ids,ref,query,answer,target,case in queries:
            qgroup=uid(scene['scene_id'],task,case or '',target)
            sid=uid(qgroup,*ids);tgroup=uid(scene['scene_id'],target)
            p=prompt(scene,recordings,task,query,ids,ref)
            row=dict(schema_version=VERSION,sample_id=sid,scene_id=scene['scene_id'],
                scene_group_id=scene['scene_group_id'],view_id=uid(scene['scene_id'],*ids),
                task_id=task,setting=setting,receiver_ids=ids,reference_robot_id=ref,
                query_group_id=qgroup,target_group_id=tgroup,query=query,
                time_window_samples=[0,scene['duration_samples']],evaluation_step_samples=1600,
                target_policy='human_only',recording_ids=[by_robot[x]['recording_id'] for x in ids],
                audio_bindings=[dict(receiver_id=x,path=by_robot[x]['path'],sha256=by_robot[x]['sha256'],
                    sample_rate_hz=SR,channels=['W','Y','Z','X'],global_start_sample=0) for x in ids],
                known_robot_poses=robot_trace(scene),robot_playback_log=[dict(robot_id=s['entity_id'],
                    start_sample=e['start_sample'],end_sample=e['end_sample'],text=e['text']) for s in scene['playback_sources'] for e in s['events']],
                output_schema='string' if task=='KW_ASR' else 'tracks' if task=='DOA_TRAJECTORY' else 'frames',
                rendered_prompt=p)
            g=dict(sample_id=sid,scene_id=scene['scene_id'],task_id=task,setting=setting,
                branch=scene['branch'],target_source_id=target,keyword_case=case,output=answer,
                expected_times_s=[s/SR for s in grid(scene)])
            inputs.append(row);gold.append(g)
            example=copy.deepcopy(answer)
            if task=='DOA_TRAJECTORY':
                for tr in example['tracks']:
                    tr['track_id']='S'+str(1+list(scene['humans']).index(next(s for s in scene['humans'] if s['entity_id']==tr['track_id'])))
                    for f in tr['frames']:
                        if f['active']:
                            f['doa_deg'][0]=(f['doa_deg'][0]+8+180)%360-180
                            f['doa_deg'][1]+=2
            elif task in ('RANGE_TRAJECTORY','TEXT_TRAJECTORY'):
                for f in example['frames']:
                    if f['active']:
                        if task=='RANGE_TRAJECTORY':f['distance_m']+=.35
                        else:f['xyz_m'][0]+=.35
            elif case=='unique_human':
                ts=answer.split();example=' '.join(ts[:-1])
            elif case=='robot_only':example=scene['playback_sources'][0]['events'][0]['text']
            samples.append(dict(input=row,gold=g,example_prediction=example,
                prediction_provenance='deterministic demonstration perturbation; not model inference'))
        for qgroup in sorted({s['input']['query_group_id'] for s in samples}):
            grouped=[s['input'] for s in samples if s['input']['query_group_id']==qgroup]
            pairs.append(dict(scene_id=scene['scene_id'],query_group_id=qgroup,
                target_group_id=grouped[0]['target_group_id'],task_id=grouped[0]['task_id'],
                samples=[dict(sample_id=s['sample_id'],receiver_ids=s['receiver_ids']) for s in grouped]))
        display=copy.deepcopy(scene)
        for e in display['humans']+display['robots']:
            e['moving']=bool(np.linalg.norm(e['displacement_m']))
            e['trajectory']=[dict(time_s=t/SR,xyz_m=position(e,t/SR).tolist(),
                velocity_mps=velocity(e,t/SR).tolist(),speed_mps=float(np.linalg.norm(velocity(e,t/SR))),
                relative_to_robots_m={r['entity_id']:(position(e,t/SR)-position(r,t/SR)).tolist()
                    for r in scene['robots'] if r['entity_id']!=e['entity_id']}) for t in grid(scene)]
        browser.append(dict(scene=display,recordings=recordings,samples=samples))
    jsonl(root/'data/inputs.jsonl',inputs);jsonl(root/'data/gold.jsonl',gold);jsonl(root/'data/pairs.jsonl',pairs)
    jsonl(root/'data/prompts.jsonl',[dict(sample_id=r['sample_id'],rendered_prompt=r['rendered_prompt']) for r in inputs])
    write(root/'data/demo.json',dict(schema_version=VERSION,parent_static_scene_id=recipe['parent_static_scene_id'],
        output_step_s=.1,room=recipe['room'],scene_count=len(browser),scenes=browser,
        audio_preview_method=rendering.get('binaural_decoding',{}).get('method','two virtual cardioid channels L=0.5W+0.5Y, R=0.5W-0.5Y; not HRTF binaural'),
        raw_audio_format='16000 Hz FLOAT WAV, ACN/SN3D [W,Y,Z,X]',
        model_inference_performed=False,renderer_approximation=recipe['rendering_method']))
    if rendering.get('binaural_decoding'):
        exported=read(root/'data/demo.json');exported['binaural_decoding']=rendering['binaural_decoding'];write(root/'data/demo.json',exported)
    print('EXPORTED',len(inputs),'samples',len(pairs),'query groups',flush=True)


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