File size: 10,737 Bytes
347d9a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Full acceptance of source continuity, geometry, paired bindings and formal gold."""
from __future__ import annotations
import argparse,copy,math
from collections import Counter
from pathlib import Path
import numpy as np
import soundfile as sf
from .common import *
from .geometry import audit,range_queries
from .loader import Dataset
from .prompts import render
from .export import frames
from .score import safe_score,evaluate
from .runtime import ensure_compute


def acceptance(root,pilot=False):
    ensure_compute();root=root.resolve();config=read(root/'config.json');summary=read(root/'summary.json')
    assert not (root/'public/preview').exists()
    assert summary['binaural_previews']==0
    groups=list(rows(root/'private/recipes.jsonl'))
    if pilot:groups=[g for g in groups if (root/'reports/groups'/(g['group_id']+'.json')).exists()]
    expected_scenes={s['scene_id']:(s,g) for g in groups for s in g['scenes']}
    planned_groups={g['group_id']:g for g in groups}
    assert len(groups)==(summary['paired_motion_groups'] if pilot else 500)
    assert len(expected_scenes)==(summary['physical_scenes'] if pilot else 2000)
    public={r['scene_id']:r for r in rows(root/'public/test/scenes.jsonl')};assert set(public)==set(expected_scenes)
    dataset=Dataset(root);bindings={};golds={r['sample_id']:r for r in rows(root/'private/test/gold.jsonl')}
    assert set(dataset.index)==set(golds)
    sources={};tasks=Counter();branches=Counter();audio_count=0;rir_count=0;max_gap=0.;max_step=0.;native_tail=0.;unique_crops=set();crop_groups={}
    for group_index,group in enumerate(groups,1):
        report=read(root/'reports/groups'/(group['group_id']+'.json'));assert report['passed']
        assert not any(f['path'].startswith('public/preview/') for f in report['files'])
        for file in report['files']:assert sha(root/file['path'])==file['sha256']
        for r in rows(root/report['rir_audit_path']):
            rir_count+=1;native_tail=max(native_tail,r['native_final_50ms_energy_fraction']);assert r['native_final_50ms_energy_fraction']<=1e-7
            if r['los']:
                assert r['direct_angle_error_deg']<=3.;assert abs(r['direct_delay_s']-r['geometric_delay_s'])<=.003
        shared=None
        for scene in group['scenes']:
            sid=scene['scene_id'];branches[scene['branch']]+=1
            if not pilot:
                donor=scene['absent_keyword_provenance'];other=planned_groups[donor['group_id']]
                assert other['group_id']!=group['group_id']
                assert other['scenes'][0]['keywords'][donor['target_id']]==scene['keywords']['no_match']
            assert audit(scene,group['room'],full_visibility=True) is not None
            assert scene['duration_samples']==group['parent_static_duration_samples'] if config['duration_policy']=='static' else True
            # Matched branch groups use identical source events, initial body positions, poses and durations.
            signature=[(e['entity_id'],e['initial_xyz_m'],e.get('events')) for e in scene['humans']+scene['robots']+scene['playback_sources']]
            if shared is None:shared=signature
            else:assert signature==shared
            assert len(scene['moving_entity_ids'])==1 if scene['difficulty']=='easy' else len(scene['moving_entity_ids'])==len(scene['humans'])+len(scene['robots'])
            for human in scene['humans']:
                assert len(human['events'])==1
                event=human['events'][0];path=root/event['audio_asset'];digest=event['original_source_sha256']
                if digest not in sources:
                    assert sha(path)==digest;sources[digest]=sf.read(path,dtype='float32')[0]
                full=sources[digest];a,b=event['crop_samples'];assert 0<=a<b<=len(full)
                actual=speech_activity(full[a:b],event['start_sample']);assert actual==event['activity_samples']
                gap=max_internal_gap([event]);max_gap=max(max_gap,gap);assert gap<=config['target_maximum_internal_silence_s']
                assert event['end_sample']<=scene['duration_samples']-round(config['tail_budget_s']*SR)
                assert all(w['alignment_score']>=config['minimum_word_alignment_score'] for w in event['words'])
                cue=tokens(scene['keywords'][human['entity_id']]);assert tokens(event['text'])[:len(cue)]==cue
                assert sum(tokens(h['events'][0]['text'])[:len(cue)]==cue for h in scene['humans'])==1
                unique_crops.add((digest,*event['original_word_indices']))
                crop_groups.setdefault((digest,*event['original_word_indices']),set()).add(group['group_id'])
            for e in scene['humans']+scene['robots']:
                xyz=position(e,np.array(grid(scene))/SR);step=float(np.max(np.linalg.norm(np.diff(xyz,axis=0),axis=1)));max_step=max(max_step,step);assert step<=.161
            for robot in scene['robots']:
                rec=next(r for r in report['recordings'] if r['scene_id']==sid and r['receiver_robot_id']==robot['entity_id'])
                assert not any(k.startswith('preview_') for k in rec)
                wave,rate=sf.read(root/rec['path'],dtype='float32')
                assert rate==SR and wave.shape==(scene['duration_samples'],4)
                assert np.isfinite(wave).all() and 0<float(np.max(np.abs(wave)))<=.901
                audio_count+=1
        if group_index%25==0 or group_index==len(groups):
            print('ACCEPTANCE AUDIO/GEOMETRY',group_index,'/',len(groups),'groups;',rir_count,'RIRs',flush=True)
    for sample_index,sample_id in enumerate(dataset.ids(),1):
        row,prompt=dataset.sample(sample_id);g=golds[sample_id];scene,group=expected_scenes[row['scene_id']]
        assert prompt==render(scene,row['task_id'],row['query'],row['receiver_ids'],row['reference_robot_id'])
        assert all(term not in row for term in ['output','humans','target_source_id','ground_truth','source_quality','evaluation_id_nonce'])
        assert row['setting']==('edge' if len(row['receiver_ids'])==1 else 'cloud')
        assert row['time_window_samples']==[0,scene['duration_samples']]
        for slot,b in enumerate(row['audio_bindings']):
            r=dataset.recordings[b['recording_id']];assert b['slot']==slot and r['scene_id']==row['scene_id'] and r['receiver_robot_id']==row['receiver_ids'][slot]
            assert b['path']==r['path'] and b['sha256']==r['sha256']
            bindings.setdefault((row['scene_id'],b['robot_id']),set()).add((b['path'],b['sha256']))
        task=row['task_id'];tasks[row['setting']+'/'+task]+=1
        if task=='DOA_TRAJECTORY':
            robot=next(r for r in scene['robots'] if r['entity_id']==row['reference_robot_id'])
            assert g['output']==dict(tracks=[dict(track_id=h['entity_id'],frames=frames(scene,h,robot,'doa_deg')) for h in scene['humans']])
        elif task in ['RANGE_TRAJECTORY','TEXT_TRAJECTORY']:
            h=next(h for h in scene['humans'] if h['entity_id']==g['target_source_id'])
            if task=='RANGE_TRAJECTORY':
                robot=next(r for r in scene['robots'] if r['entity_id']==row['reference_robot_id'])
                assert g['output']==dict(frames=frames(scene,h,robot,'distance_m'))
                cue=next(c for c in range_queries(scene) if c['source_id']==h['entity_id'] and c['receiver_id']==robot['entity_id'])
                assert row['query']=={k:v for k,v in cue.items() if k not in ['source_id','receiver_id']}
            else:assert g['output']==dict(frames=frames(scene,h)) and row['query']['transcript']==h['events'][0]['text']
        else:
            cue=tokens(row['query']['wake_phrase']);matched=[h for h in scene['humans'] if tokens(h['events'][0]['text'])[:len(cue)]==cue]
            assert len(matched)<=1
            assert g['output']==(matched[0]['events'][0]['text'] if matched else '')
        result=safe_score(g,g['output']);assert result['format_valid']
        if task=='KW_ASR':assert result['exact_match']
        else:assert result['coverage']==1. and abs(result['mean_error'])<1e-5
        if sample_index%5000==0 or sample_index==len(dataset.index):
            print('ACCEPTANCE PROMPT/GOLD',sample_index,'/',len(dataset.index),flush=True)
    assert all(len(v)==1 for v in bindings.values())
    assert all(len(v)==1 for v in crop_groups.values()),'An exact human crop is reused across distinct motion groups'
    assert tasks==Counter(summary['tasks']) and branches==Counter(summary['branches'])
    for pair in rows(root/'public/test/pairs.jsonl'):
        samples=[dataset.sample(r['sample_id'])[0] for r in pair['samples']];s,g=expected_scenes[pair['scene_id']]
        expected=len(s['robots'])+int(pair['task_id']=='KW_ASR') if pair['task_id']!='TEXT_TRAJECTORY' else 1
        assert len(samples)==expected and all(r['query_group_id']==pair['query_group_id'] and r['target_group_id']==pair['target_group_id'] for r in samples)
        assert len({r['sample_id'] for r in samples})==expected
        assert len({golds[r['sample_id']]['target_source_id'] for r in samples})==1
    # Formal CLI oracle is a plumbing check, never a model baseline.
    oracle=root/'reports/acceptance/oracle_predictions.jsonl'
    jsonl(oracle,(dict(sample_id=sid,output=golds[sid]['output']) for sid in dataset.ids()))
    scored=evaluate(root,oracle,root/'reports/acceptance/oracle_scores',True)
    assert scored['missing_predictions']==0
    for value in scored['summary'].values():
        assert value['format_valid_fraction']==1.
        if 'coverage' in value:assert value['coverage']==1. and abs(value['mean_error'])<1e-5
        if 'exact_match_fraction' in value:assert value['exact_match_fraction']==1.
    for sid in list(dataset.ids())[::max(1,len(dataset.index)//24)]:dataset.load(sid)
    result=dict(passed=True,pilot=pilot,completed_at=now(),physical_scenes=len(expected_scenes),paired_motion_groups=len(groups),
        foa_recordings=audio_count,binaural_previews=0,task_requests=len(dataset.index),tasks=dict(tasks),branches=dict(branches),native_rirs=rir_count,
        maximum_native_tail_fraction=native_tail,maximum_target_internal_silence_s=max_gap,maximum_0_2s_motion_step_m=max_step,
        unique_human_source_crops=len(unique_crops),edge_cloud_shared_waveforms=True,prompt_and_gold_recomputed=True,
        geometry_accepted=True,oracle_scoring_passed=True,public_loader_checked=True,model_inference_performed=False,human_listening_audit_completed=False)
    write(root/'reports/acceptance.json',result);print('ACCEPTANCE PASSED',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();acceptance(a.root,a.pilot)