Datasets:
Download code/dynamic_demo/export.py from Heiheihaha17/MESH-Benchmark: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/datasets/Heiheihaha17/MESH-Benchmark/resolve/main/code/dynamic_demo/export.py
- Command line
-
hf download hf://datasets/Heiheihaha17/MESH-Benchmark/code/dynamic_demo/export.py
-
curl -L -o export.py https://huggingface.co/datasets/Heiheihaha17/MESH-Benchmark/resolve/main/code/dynamic_demo/export.py
12.6 kB
| """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) | |