Heiheihaha17's picture
Add files using upload-large-folder tool
2e20433 verified
Raw History Blame Contribute Delete
15.5 kB
"""Validate the public generated bundle and Python/browser scoring parity."""
from __future__ import annotations
import argparse
import copy
import json
import math
import os
from pathlib import Path
import subprocess
import tempfile
import numpy as np
import soundfile as sf
from .common import SR, STEP, active, geometry, grid, position, read, sha, tokens, write
from .render import validate_geometry
from .score import score
def compare(a,b,path='root'):
if isinstance(a,dict):
assert isinstance(b,dict) and set(a)==set(b),(path,a,b)
for k,v in a.items():compare(v,b[k],path+'.'+k)
elif isinstance(a,list):
assert isinstance(b,list) and len(a)==len(b),path
for i,(v,w) in enumerate(zip(a,b)):compare(v,w,path+str(i))
elif isinstance(a,(int,float)) and not isinstance(a,bool):
assert math.isclose(a,b,abs_tol=2e-5,rel_tol=1e-6),(path,a,b)
else:assert a==b,(path,a,b)
def validate(root,work=None,node=None):
recipe=read(root/'data/recipe.json');rendering=read(root/'data/rendering.json');demo=read(root/'data/demo.json')
assert len(demo['scenes'])==3 and len(rendering['recordings'])==6
assert len({s['duration_samples'] for s in recipe['scenes']})==1
assert recipe['parent_static_duration_samples']==recipe['scenes'][0]['duration_samples']
assert not demo['model_inference_performed'] and not rendering['model_inference_performed']
assert recipe['renderer']['temporalCoherence'] is False
geometry_audit=validate_geometry(recipe)
motion_observability=[]
for scene in recipe['scenes']:
for human in scene['humans']:
times=[s/SR for s in grid(scene) if active(human,s)]
for receiver in scene['robots']:
azimuths=np.unwrap(np.deg2rad([geometry(human,receiver,t)['doa_deg'][0] for t in times]))
motion_observability.append(dict(branch=scene['branch'],source_id=human['entity_id'],
receiver_id=receiver['entity_id'],first_active_time_s=times[0],last_active_time_s=times[-1],
first_active_doa_deg=geometry(human,receiver,times[0])['doa_deg'],
last_active_doa_deg=geometry(human,receiver,times[-1])['doa_deg'],
source_displacement_between_first_last_active_m=float(np.linalg.norm(position(human,times[-1])-position(human,times[0]))),
active_azimuth_span_deg=float(np.degrees(np.ptp(azimuths)))))
for name,h in recipe['room_assets_sha256'].items():assert sha(root/'assets/room'/name)==h
for scene in recipe['scenes']:
for e in scene['humans']+scene['robots']:
p=position(e,np.arange(0,scene['duration_samples']/SR,.01));assert np.ptp(p[:,1])==0
moving=np.linalg.norm(e['displacement_m'])>0
assert moving==(e['entity_id'] in scene['moving_entity_ids'])
for human in scene['humans']:
for evt in human['events']:
assert sha(root/evt['audio_asset'])==evt['original_source_sha256']
assert evt['end_sample']-evt['start_sample']==evt['crop_samples'][1]-evt['crop_samples'][0]
assert all(evt['start_sample']<=a<b<=evt['end_sample'] for a,b in evt['activity_samples'])
assert evt['text']==' '.join(w['word'] for w in evt['words'])
assert evt['words'][0]['start_sample']-evt['start_sample']<=SR*.04
if human['entity_id']=='H01' and recipe.get('continuous_speech_check'):
assert len(human['events'])==1
spans=human['events'][0]['activity_samples']
assert max((y[0]-x[1])/SR for x,y in zip(spans,spans[1:]))<=.35
assert (spans[-1][1]-spans[0][0])/SR>=6.
# All branches must retain the same voices, turns and exactly the same duration.
for h,original in zip(scene['humans'],recipe['scenes'][0]['humans']):
assert h['speaker_id']==original['speaker_id'] and h['events']==original['events']
audio=[]
binaural=rendering.get('binaural_decoding')
if binaural:
from .binaural import decoder_filters, decode_foa
filters,_=decoder_filters(root/binaural['hrtf_asset'])
for rec in rendering['recordings']:
assert sha(root/rec['path'])==rec['sha256']
assert sha(root/rec['preview_path'])==rec['preview_sha256']
wave,sr=sf.read(root/rec['path'],dtype='float32');preview,psr=sf.read(root/rec['preview_path'],dtype='float32')
assert sr==psr==SR and wave.shape==(recipe['parent_static_duration_samples'],4) and preview.shape==(len(wave),2)
assert np.isfinite(wave).all() and 0<float(np.max(np.abs(wave)))<=.90001
# Audition must decode the exact raw FOA, with PCM quantization only.
expected=(decode_foa(wave,filters)[0]*binaural['common_audition_gain']) if binaural else np.column_stack([.5*(wave[:,0]+wave[:,1]),.5*(wave[:,0]-wave[:,1])])
assert float(np.max(np.abs(preview-expected)))<1/32768+1e-7
for diagnostic in rec.get('diagnostics',{}).values():
isolated,isr=sf.read(root/diagnostic['path'],dtype='float32')
audition,asr=sf.read(root/diagnostic['preview_path'],dtype='float32')
assert isr==asr==SR and isolated.shape==wave.shape and audition.shape==preview.shape
assert sha(root/diagnostic['path'])==diagnostic['sha256'] and sha(root/diagnostic['preview_path'])==diagnostic['preview_sha256']
target=decode_foa(isolated,filters)[0]*binaural['common_audition_gain']
assert float(np.max(np.abs(audition-target)))<1/32768+1e-7
if work:
stem=next(s for s in read(work/'render.complete.json')['stem_records'] if s['branch']==rec['branch']
and s['receiver_id']==rec['receiver_id'] and s['source_id']==diagnostic['diagnostic_source_id'])
np.testing.assert_array_equal(isolated,np.load(stem['path'],allow_pickle=False))
if work:
stems=read(work/'render.complete.json')['stem_records']
selected=[s for s in stems if s['branch']==rec['branch'] and s['receiver_id']==rec['receiver_id']]
assert all(s['source_id']!=rec['receiver_id'] for s in selected)
assert {s['source_id'] for s in selected}==({'H01','H02','R02'}-{rec['receiver_id']})
reconstructed=sum(np.load(s['path'],allow_pickle=False) for s in selected)
np.testing.assert_allclose(wave,reconstructed,atol=1e-7)
tail_start=round(8.5*SR)
audio.append(dict(branch=rec['branch'],receiver_id=rec['receiver_id'],samples=len(wave),
peak=float(np.max(np.abs(wave))),rms=float(np.sqrt(np.mean(wave.astype(float)**2))),
final_0_386s_energy_fraction=float(np.sum(wave[tail_start:].astype(float)**2)/np.sum(wave.astype(float)**2))))
oracle=[];cases=[];all_samples=[]
for sd in demo['scenes']:
scene=sd['scene'];assert len(sd['samples'])==14
for sample in sd['samples']:
row,g=sample['input'],sample['gold'];all_samples.append(sample)
assert row['sample_id']==g['sample_id']
assert row['time_window_samples']==[0,scene['duration_samples']]
assert g['expected_times_s']==[x/SR for x in grid(scene)]
assert row['evaluation_step_samples']==STEP
assert len(row['receiver_ids'])==len(row['audio_bindings'])==len(row['recording_ids'])
assert row['setting']==('cloud' if len(row['receiver_ids'])>1 else 'edge')
assert 'humans' not in row and 'gold' not in row and 'target_source_id' not in row
assert all(h['speaker_id'] not in row['rendered_prompt'] for h in scene['humans'])
assert not(row['task_id']=='TEXT_TRAJECTORY' and row['setting']=='edge')
assert 'delta' not in row['query'] and 'ΔDOA' not in row['rendered_prompt']
for trace,robot in zip(row['known_robot_poses'],scene['robots']):
assert trace['yaw_deg']==round(robot['yaw_deg'])
assert trace['positions']==[[t/SR]+[round(float(x),1) for x in position(robot,t/SR)] for t in grid(scene)]
output=g['output'];s=score(g,output);assert s['format_valid']
if row['task_id']=='KW_ASR':
cue=tokens(row['query']['wake_phrase']);assert 1<=len(cue)<=3
matched=[h for h in scene['humans'] if any(tokens(e['text'])[:len(cue)]==cue for e in h['events'])]
assert len(matched)<=1
expected=' '.join(e['text'] for e in sorted(matched[0]['events'],key=lambda e:e['start_sample'])) if matched else ''
assert output==expected and s['exact_match']
else:
assert s['coverage']==1 and s['mean_error']<1e-5
if row['task_id']=='DOA_TRAJECTORY':assert {t['track_id'] for t in output['tracks']}=={'H01','H02'}
else:
human=next(h for h in scene['humans'] if h['entity_id']==g['target_source_id'])
receiver=next((r for r in scene['robots'] if r['entity_id']==row['reference_robot_id']),None)
for f in output['frames']:
assert f['active']==active(human,round(f['time_s']*SR))
if f['active']:
if receiver:assert abs(f['distance_m']-np.linalg.norm(position(human,f['time_s'])-position(receiver,f['time_s'])))<1e-10
else:np.testing.assert_allclose(f['xyz_m'],position(human,f['time_s']))
if receiver:
q=row['query'];t=q['selection_time_s'];lo,hi=q['initial_sector_deg'];az=geometry(human,receiver,t)['doa_deg'][0]
assert lo+1<az<hi-1,'Ambiguous sector boundary'
# The one-decimal public receiver pose must still pick the same human.
rounded=copy.deepcopy(receiver);rounded['initial_xyz_m']=[round(float(x),1) for x in position(receiver,t)];rounded['displacement_m']=[0,0,0];rounded['yaw_deg']=round(receiver['yaw_deg'])
az=geometry(human,rounded,t)['doa_deg'][0];assert lo+1<az<hi-1
selected=[h['entity_id'] for h in scene['humans'] if active(h,round(t*SR)) and lo<=geometry(h,receiver,t)['doa_deg'][0]<hi]
assert selected==[human['entity_id']]
oracle.append(dict(sample_id=g['sample_id'],output=output))
predictions=[output,sample['example_prediction'],None]
if row['task_id']!='KW_ASR':
partial=copy.deepcopy(output);frame_sets=[t['frames'] for t in partial['tracks']] if row['task_id']=='DOA_TRAJECTORY' else [partial['frames']]
for fs in frame_sets:del fs[len(fs)//2:]
predictions.append(partial)
invalid=copy.deepcopy(output);fs=invalid['tracks'][0]['frames'] if row['task_id']=='DOA_TRAJECTORY' else invalid['frames'];fs.append(copy.deepcopy(fs[0]));predictions.append(invalid)
for prediction in predictions:cases.append(dict(gold=g,prediction=prediction))
assert len(all_samples)==42 and len({s['input']['sample_id'] for s in all_samples})==42
pairs=[json.loads(x) for x in (root/'data/pairs.jsonl').read_text().splitlines()]
assert len(pairs)==18
byid={s['input']['sample_id']:s for s in all_samples}
for pair in pairs:
samples=[byid[v['sample_id']] for v in pair['samples']]
assert len({s['input']['scene_id'] for s in samples})==1
assert len({s['gold']['target_source_id'] for s in samples})==1
if pair['task_id']=='KW_ASR':assert len(samples)==3 and len({s['gold']['output'] for s in samples})==1
elif pair['task_id'] in ('DOA_TRAJECTORY','RANGE_TRAJECTORY'):
assert len(samples)==2 and samples[0]['gold']['output']!=samples[1]['gold']['output']
else:assert len(samples)==1
los=[r for r in rendering['rir_records'] if r['los']]
assert los and max(r['direct_angle_error_deg'] for r in los)<3
assert max(r['native_final_50ms_energy_fraction'] for r in rendering['rir_records'])<1e-7
parity=None
if node:
with tempfile.TemporaryDirectory() as temp:
p=Path(temp)/'cases.json';write(p,cases)
result=subprocess.run([node,str(Path(__file__).parent/'tests/parity.mjs'),str(p)],capture_output=True,text=True,check=True)
browser=json.loads(result.stdout);assert len(browser)==len(cases)
for c,js in zip(cases,browser):compare(score(c['gold'],c['prediction']),js)
parity=dict(passed=True,cases=len(cases),numeric_tolerance=2e-5)
report=dict(passed=True,scene_count=3,recording_count=6,task_sample_count=42,query_group_count=18,
duration_samples=recipe['parent_static_duration_samples'],duration_s=recipe['parent_static_duration_samples']/SR,
output_step_s=.1,oracle_passed_samples=len(oracle),python_browser_parity=parity,
audio_checks=audio,rir_count=len(rendering['rir_records']),los_checked_rirs=len(los),
maximum_los_direct_angle_error_deg=max(r['direct_angle_error_deg'] for r in los),
maximum_native_final_50ms_energy_fraction=max(r['native_final_50ms_energy_fraction'] for r in rendering['rir_records']),
geometry_audit=geometry_audit,motion_observability=motion_observability,
human_listening_audit_completed=False,model_inference_performed=False)
if binaural:
report['binaural_postprocessing']=dict(passed=True,recordings=6,
original_foa_hashes_preserved=True,room_or_foa_regenerated=False,
preview_method=binaural['method'])
if recipe.get('continuous_speech_check'):
continuity=read(root/'data/continuity.json')
inspected=continuity['direct_component_check']
assert continuity['passed'] and inspected['passed']
assert inspected['coverage']>=.8 and inspected['p95_angle_error_deg']<3
assert inspected['maximum_adjacent_0_1s_angle_change_deg']<10
if work:
from .diagnostics import inspect_direct_component
scene=next(s for s in recipe['scenes'] if s['branch']=='easy_human')
repeated=inspect_direct_component(root,work,recipe,scene,scene['humans'][0],scene['robots'][0])
compare(inspected,repeated)
report['continuous_motion_audio_check']=dict(passed=True,source_id='H01',
isolated_foa_and_binaural_checked=6,
maximum_internal_silence_s=max((y[0]-x[1])/SR for x,y in zip(recipe['scenes'][0]['humans'][0]['events'][0]['activity_samples'],recipe['scenes'][0]['humans'][0]['events'][0]['activity_samples'][1:])),
direction_check_scope='First-arrival component of exact existing RIRs, easy_human/R01; full reverberant intensity estimates are descriptive only',
first_arrival_waveform_direction_check={k:inspected[k] for k in ['coverage','p95_angle_error_deg','maximum_adjacent_0_1s_angle_change_deg']})
write(root/'data/validation.json',report)
# Downloadable oracle is for checking the scorer, never claimed as predictions.
from .common import jsonl
jsonl(root/'data/oracle_predictions.jsonl',oracle)
print(json.dumps(report,ensure_ascii=False,indent=2))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--work',type=Path);p.add_argument('--node')
a=p.parse_args();validate(a.root.resolve(),a.work.resolve() if a.work else None,a.node)