Heiheihaha17's picture
Add files using upload-large-folder tool
eef0c43 verified
Raw History Blame Contribute Delete
14.1 kB
"""Independent acceptance of pairing, geometry, rendered files and scoring."""
from __future__ import annotations
import argparse,collections,copy,math
from pathlib import Path
import numpy as np
import soundfile as sf
from .common import *
from .score import one
from .loader import Dataset
from .prompts import render
from .tasks import TASK_VERSION,evidence,support_fraction,circular_error,TRANSCRIPTION_SCOPE
from exhibition_dataset.export import transcript
def invariant(episode):
return dict(duration_samples=episode['duration_samples'],room_id=episode['room_id'],noise=episode['noise'],
entities=[{k:e[k] for k in ['entity_id','entity_type','initial_xyz_m','yaw_deg','events','speaker_id','emitted_rms_dbfs','playback_role'] if k in e}
for e in episode['humans']+episode['robots']+episode['playback_sources']])
def validate(root,pilot=False):
ensure_compute();plans=[read(p) for p in sorted((root/'private/plans').glob('*.json'))]
exported={mode:{e['episode_id'] for e in rows(root/mode/'public/test/episodes.jsonl')} for mode in ['static','dynamic']}
if pilot:
# Validate exactly the export snapshot while background workers keep
# completing additional bases. Extra completed audio is not yet public.
plans=[g for g in plans if all(e['episode_id'] in exported[mode] for mode in ['static','dynamic'] for e in g[mode+'_episodes'])]
elif len(plans)!=800:raise ValueError('Expected 800 bases')
if not plans:raise ValueError('No complete bases')
for mode in ['static','dynamic']:
assert exported[mode]=={e['episode_id'] for g in plans for e in g[mode+'_episodes']},'Export omitted or duplicated a base derivative'
identities=set();files=set();motions=[];durations=[];noisy=0;snrs=collections.Counter();modes=collections.Counter();noise_types=collections.Counter()
for g in plans:
episodes=g['static_episodes']+g['dynamic_episodes'];base=episodes[0]
assert len(episodes)==3 and len({e['episode_id'] for e in episodes})==3
assert episodes[1]['variant_seed']!=episodes[2]['variant_seed']
assert invariant(base)==invariant(episodes[1])==invariant(episodes[2])
assert episodes[1]['moving_entity_ids'] and episodes[2]['moving_entity_ids']
noisy+=base['noise']['enabled'];snrs[str(base['noise'].get('nominal_snr_db'))]+=1;noise_types[base['noise']['kind']]+=1
assert base['duration_samples']<=30*SR
durations.append(base['duration_samples']/SR)
transcripts=[tuple(tokens(h['events'][0]['text'])) for h in base['humans']]
assert len(set(transcripts))==len(transcripts),'Ambiguous transcript query in base'
for h in base['humans']:
identities.add(h['speaker_id'])
e=h['events'][0];files.add(e['original_source_sha256'])
assert e['words'] and ' '.join(w['word'] for w in e['words'])==e['text']
assert min(w['alignment_score'] for w in e['words'])>=.5
assert all((b[0]-a[1])/SR<=.35+1e-9 for a,b in zip(e['activity_samples'],e['activity_samples'][1:]))
for episode in episodes[1:]:
modes[episode['branch']]+=1
for entity in episode['humans']+episode['robots']:
length=float(np.linalg.norm(entity['displacement_m']))
if length==0:continue
speed=1.875*length/entity['motion_duration_s']
assert 1.5-1e-8<=length<=5+1e-8 and .4-1e-8<=speed<=.8+1e-8
source=entity if entity['entity_type']=='human' else episode['humans'][0]
words=source['events'][0]['words']
assert entity['motion_start_s']>=words[0]['start_sample']/SR-1e-8
assert entity['motion_start_s']+entity['motion_duration_s']<=words[-1]['end_sample']/SR+1e-8
motions.append(dict(length_m=length,peak_speed_mps=speed))
report=read(root/'reports/bases'/f"{g['index']:04d}.json")
assert report['passed']
for record in report['recordings']:
path=root/record['path'];assert sha(path)==record['sha256']
wave,rate=sf.read(path,dtype='float32')
assert rate==SR and wave.shape==(base['duration_samples'],4) and np.isfinite(wave).all()
assert float(np.max(np.abs(wave)))<=.900001
assert record['common_final_gain']==report['common_final_gain']
if report['noise_calibration']:
anchor=next(m for m in report['acoustic_measurements'] if m['episode_id']==base['episode_id'] and m['receiver_id']=='R01' and m['source_id']=='H01')
assert abs(anchor['snr_db']-base['noise']['nominal_snr_db'])<.001
if not pilot:assert len(identities)>=200 and noisy==760 and len(plans)==800
mode_reports={};physical={e['episode_id']:e for g in plans for e in g['static_episodes']+g['dynamic_episodes']}
for mode in ['static','dynamic']:
dest=root/mode;episodes={e['episode_id']:e for e in rows(dest/'public/test/episodes.jsonl')}
views=collections.defaultdict(list)
for v in rows(dest/'public/test/views.jsonl'):views[v['episode_id']].append(v)
for eid,e in episodes.items():
expected=e['scene_robot_ids'];items=views[eid]
assert len(items)==len(expected)+1
assert sorted(v['receiver_ids'][0] for v in items if v['setting']=='edge')==sorted(expected)
assert [v['receiver_ids'] for v in items if v['setting']=='cloud']==[expected]
inputs={s['sample_id']:s for s in rows(dest/'public/test/inputs.jsonl')}
prompts={s['sample_id']:s for s in rows(dest/'public/test/prompts.jsonl')}
gold={g['sample_id']:g for g in rows(dest/'private/test/gold.jsonl')}
assert set(inputs)==set(prompts)==set(gold)
checked=0;negative=0;content_pairs=collections.defaultdict(list);asr_pairs=collections.defaultdict(list)
allowed=({'DOA','RANGE','TEXT_DOA','TEXT_RANGE','DOA_RANGE_ASR','C1_SETLOC','C2_REGION_ASR','C3_TEXTLOC'} if mode=='static'
else {'DOA_TRAJECTORY','RANGE_TRAJECTORY','TEXT_TRAJECTORY','SPATIAL_ASR','WORLD_TRAJECTORY_ASR'})
assert not (dest/'public/test/keyword_variants.jsonl').exists()
for sid,g in gold.items():
s=inputs[sid];e=episodes[s['episode_id']]
assert s['task_id'] in allowed and s['task_protocol_version']==TASK_VERSION
assert 'keyword_case' not in g and 'wake_phrase' not in s['query']
assert prompts[sid]['rendered_prompt']==render(s)
assert 'as the direction and microphone-distance reference' not in prompts[sid]['rendered_prompt']
assert s['receiver_ids']==([s['receiver_ids'][0]] if s['setting']=='edge' else e['scene_robot_ids'])
assert s['reference_robot_id']==(s['receiver_ids'][0] if s['setting']=='edge' else None)
assert len(s['audio_bindings'])==len(s['receiver_ids'])
assert g['task_id']==s['task_id']
if mode=='dynamic':assert g['expected_times_s']==[x/SR for x in range(0,s['duration_samples'],8000)]
result=one(g,copy.deepcopy(g['output']))
assert result['format_valid'],(sid,g['task_id'],result)
if result['asr']:assert result['exact_match']
else:
assert result['covered']==result['total']
assert all(x is not None and x<1e-4 for x in result['errors'])
missing=one(g,None);assert not missing['format_valid']
scene=physical[s['episode_id']]
if g['task_id'] in ['TEXT_DOA','TEXT_RANGE']:
content_pairs[s['content_localization_pair_id']].append(s)
h=next(h for h in scene['humans'] if h['entity_id']==g['target_source_id'])
r=next(r for r in scene['robots'] if r['entity_id']==s['reference_robot_id'])
assert s['query']['transcript']==transcript(h)
if g['task_id']=='TEXT_RANGE':assert abs(g['output']-geometry(h,r,0.)['distance_m'])<1e-9
if g['task_id'] in ['DOA_RANGE_ASR','SPATIAL_ASR','WORLD_TRAJECTORY_ASR']:
query=s['query'];h=next(h for h in scene['humans'] if h['entity_id']==g['target_source_id'])
r=next((r for r in scene['robots'] if r['entity_id']==s['reference_robot_id']),None)
assert 'reference_robot_id' not in query
assert query['transcription_scope']==TRANSCRIPTION_SCOPE and g['output']==transcript(h)
ev=evidence(scene,r,query,h['entity_id'])
assert ev['passed'] and ev==g['cue_evidence']
for anchor in query.get('anchors',[]):
if 'azimuth_deg' in anchor:assert anchor['azimuth_deg']==round(anchor['azimuth_deg'])
if 'doa_deg' in anchor:assert all(v==round(v) for v in anchor['doa_deg'])
if 'distance_m' in anchor:assert anchor['distance_m']==round(anchor['distance_m'],1)
if g['task_id']=='SPATIAL_ASR':
anchors=query['anchors'];assert len(anchors)==2
a,b=[v['time_s'] for v in anchors];assert b-a>=1.
assert all(t*2==round(t*2) and active(h,round(t*SR)) and support_fraction(h,t)>=.5 for t in [a,b])
ga,gb=geometry(h,r,a),geometry(h,r,b)
da=circular_error(ga['doa_deg'][0],gb['doa_deg'][0]);dr=abs(ga['distance_m']-gb['distance_m'])
assert (da>=20-1e-8 if query['cue_type']=='azimuth' else dr>=.5-1e-8 if query['cue_type']=='distance' else da>=20-1e-8 or dr>=.5-1e-8)
assert s['setting']=='edge'
asr_pairs[s['target_group_id']].append(s)
if g['task_id']=='WORLD_TRAJECTORY_ASR':
assert s['setting']=='cloud' and query['coordinate_frame']=='world' and r is None
assert [f['time_s'] for f in query['frames']]==[t/SR for t in grid(scene)]
assert all(set(f)=={'time_s','xyz_m'} and len(f['xyz_m'])==3 and all(v==round(v,1) for v in f['xyz_m']) for f in query['frames'])
asr_pairs[s['target_group_id']].append(s)
if result['asr'] and not g['output']:negative+=1
checked+=1
for pair in content_pairs.values():
assert len(pair)==2 and {s['task_id'] for s in pair}=={'TEXT_DOA','TEXT_RANGE'}
assert pair[0]['query']==pair[1]['query'] and pair[0]['receiver_ids']==pair[1]['receiver_ids']
assert gold[pair[0]['sample_id']]['target_source_id']==gold[pair[1]['sample_id']]['target_source_id']
matched_asr_targets=0
for pair in asr_pairs.values():
clouds=[s for s in pair if s['setting']=='cloud'];edges=[s for s in pair if s['setting']=='edge']
assert len(clouds)==1
assert len({s['receiver_ids'][0] for s in edges})==len(edges)
assert len({gold[s['sample_id']]['output'] for s in pair})==1
assert len({gold[s['sample_id']]['target_source_id'] for s in pair})==1
matched_asr_targets+=bool(edges)
variants=list(rows(dest/'public/test/spatial_query_variants.jsonl'))
for variant in variants:
sid=variant['sample_id'];s=inputs[sid];g=gold[sid];scene=physical[s['episode_id']]
r=next(r for r in scene['robots'] if r['entity_id']==s['reference_robot_id'])
assert evidence(scene,r,variant['query'],g['target_source_id'])['passed']
dataset=Dataset(dest,allow_pilot=True)
representative={s['task_id']:sid for sid,s in inputs.items()}
for sid in representative.values():
blind=dataset.load(sid,audio=True)
assert 'output' not in blind and 'target_source_id' not in blind and 'speaker_id' not in blind
assert 'reference_robot_id' not in blind and 'reference_robot_id' not in blind['query']
reduced=dataset.load(sid,context='without_peer_poses',audio=False)
assert all(p['robot_id'] in reduced['receiver_ids'] for p in reduced['robot_poses'])
for variant in variants[:10]:
reduced=dataset.load(variant['sample_id'],audio=False,cue_variant=variant['variant_id'])
assert reduced['query']==variant['query']
mode_reports[mode]=dict(physical_episodes=len(episodes),questions=checked,negative_asr_questions=negative,
task_counts=dict(collections.Counter(s['setting']+'/'+s['task_id'] for s in inputs.values())),
text_doa_range_pairs=len(content_pairs),spatial_asr_target_groups=len(asr_pairs),
spatial_asr_targets_with_both_settings=matched_asr_targets,
spatial_query_variants=len(variants),spatial_cue_uniqueness_passed=True,
view_correspondence_passed=True,oracle_scoring_passed=True,missing_prediction_rejection_passed=True,blind_loader_passed=True)
result=dict(passed=True,pilot=pilot,task_protocol_version=TASK_VERSION,base_scenes=len(plans),human_identities=len(identities),human_original_recordings=len(files),
noisy_bases=noisy,noise_types=dict(noise_types),nominal_snr_counts=dict(snrs),motion_modes=dict(modes),
duration_range_s=[min(durations),max(durations)],
motion_length_range_m=[min(m['length_m'] for m in motions),max(m['length_m'] for m in motions)],
peak_speed_range_mps=[min(m['peak_speed_mps'] for m in motions),max(m['peak_speed_mps'] for m in motions)],
modes=mode_reports,scope='Rendered-audio integrity, mathematical labels, paired invariants and scoring. Not baseline model inference or human listening.')
write(root/'acceptance.json',result)
if not pilot:
for mode in ['static','dynamic']:write(root/mode/'release.complete.json',dict(passed=True,schema_version=VERSION,task_protocol_version=TASK_VERSION,acceptance_sha256=sha(root/'acceptance.json')))
print('ACCEPTANCE',result,flush=True);return result
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();validate(a.root,a.pilot)