"""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=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 01 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=.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)