Datasets:
Add files using upload-large-folder tool
Browse files- code/dynamic_demo/binaural.py +128 -0
- code/dynamic_demo/fetch_cache.py +31 -0
- code/dynamic_demo/package.py +80 -0
- code/dynamic_demo/requirements.txt +18 -0
- code/dynamic_demo/score.py +167 -0
- code/exhibition_dataset/README.zh.md +111 -0
- code/exhibition_dataset/__init__.py +1 -0
- code/exhibition_dataset/ablations.py +51 -0
- code/exhibition_dataset/common.py +135 -0
- code/exhibition_dataset/export.py +293 -0
- code/exhibition_dataset/finalize.py +304 -0
- code/exhibition_dataset/kernel_geometry.py +40 -0
- code/exhibition_dataset/loader.py +127 -0
- code/exhibition_dataset/noise.py +65 -0
- code/exhibition_dataset/plan.py +567 -0
- code/exhibition_dataset/reproduce.py +79 -0
- code/exhibition_dataset/runtime.sh +14 -0
- code/exhibition_dataset/score.py +290 -0
- code/exhibition_dataset/sources.py +122 -0
- code/exhibition_dataset/worker.py +116 -0
code/dynamic_demo/binaural.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Post-process existing receiver-local ACN/SN3D FOA into HRTF auditions.
|
| 2 |
+
|
| 3 |
+
No Habitat simulator, source speech, room RIR or task regeneration is involved.
|
| 4 |
+
The regularized first-order projection follows the project's existing static
|
| 5 |
+
FOA headphone decoder. Fixed head orientation follows each receiver's front.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
import argparse
|
| 9 |
+
import math
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import h5py
|
| 13 |
+
import numpy as np
|
| 14 |
+
import soundfile as sf
|
| 15 |
+
from scipy.signal import fftconvolve, resample_poly
|
| 16 |
+
|
| 17 |
+
from .common import SR, read, sha, write
|
| 18 |
+
|
| 19 |
+
HRTF_SHA256='647cebf09bd0ed5fca359c071d888779325a5c3376669b120029df817e7ea2bd'
|
| 20 |
+
HRTF_URL='https://sofacoustics.org/data/sofatoolbox_test/MIT_KEMAR_normal_pinna.sofa'
|
| 21 |
+
METHOD='MIT KEMAR measured HRIRs projected onto receiver-local first-order ACN/SN3D; FIR binaural convolution'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def text_attribute(x):
|
| 25 |
+
if isinstance(x,h5py.Empty):return None
|
| 26 |
+
return x.decode('utf-8') if isinstance(x,bytes) else str(x)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def decoder_filters(path,target_rate=SR,ridge_fraction=1e-6):
|
| 30 |
+
if sha(path)!=HRTF_SHA256:raise ValueError('Pinned MIT KEMAR HRTF checksum mismatch')
|
| 31 |
+
with h5py.File(path,'r') as f:
|
| 32 |
+
convention=text_attribute(f.attrs.get('SOFAConventions',''))
|
| 33 |
+
if convention!='SimpleFreeFieldHRIR':raise ValueError('Expected anechoic SimpleFreeFieldHRIR')
|
| 34 |
+
positions=np.asarray(f['SourcePosition'],np.float64)
|
| 35 |
+
if text_attribute(f['SourcePosition'].attrs.get('Type','')).lower()!='spherical':
|
| 36 |
+
raise ValueError('Expected azimuth/elevation SOFA measurements')
|
| 37 |
+
ir=np.asarray(f['Data.IR'],np.float64)
|
| 38 |
+
sample_rate=int(round(float(np.asarray(f['Data.SamplingRate']).ravel()[0])))
|
| 39 |
+
if np.any(np.abs(np.asarray(f['Data.Delay']))>1e-12):raise ValueError('Unimplemented separate HRIR delays')
|
| 40 |
+
ears=np.asarray(f['ReceiverPosition'],np.float64).squeeze()
|
| 41 |
+
if ir.ndim!=3 or ir.shape[:2]!=(len(positions),2) or ears.shape!=(2,3):raise ValueError('Unexpected SOFA shape')
|
| 42 |
+
# SOFA +Y is left; output channel order is always [left ear, right ear].
|
| 43 |
+
if ears[0,1]<ears[1,1]:ir=ir[:,::-1];ears=ears[::-1]
|
| 44 |
+
if not ears[0,1]>0>ears[1,1]:raise ValueError('Ear coordinate convention is ambiguous')
|
| 45 |
+
attribution={k:text_attribute(f.attrs.get(k,'')) for k in ('AuthorContact','License','References')}
|
| 46 |
+
az,el=np.deg2rad(positions[:,0]),np.deg2rad(positions[:,1])
|
| 47 |
+
# SN3D plane-wave coefficients, in the same [W,Y,Z,X] order as original FOA.
|
| 48 |
+
basis=np.column_stack([np.ones(len(positions)),np.sin(az)*np.cos(el),np.sin(el),np.cos(az)*np.cos(el)])
|
| 49 |
+
gram=basis.T@basis;ridge=ridge_fraction*np.trace(gram)/4
|
| 50 |
+
fitted=np.linalg.solve(gram+ridge*np.eye(4),basis.T@ir.reshape(len(positions),-1))
|
| 51 |
+
filters=fitted.reshape(4,2,ir.shape[-1]).transpose(1,0,2)
|
| 52 |
+
divisor=math.gcd(sample_rate,target_rate)
|
| 53 |
+
if sample_rate!=target_rate:filters=resample_poly(filters,target_rate//divisor,sample_rate//divisor,axis=-1)
|
| 54 |
+
filters=filters.astype(np.float32)
|
| 55 |
+
if not np.isfinite(filters).all() or not np.any(filters):raise ValueError('Invalid binaural FIR bank')
|
| 56 |
+
metadata=dict(method=METHOD,hrtf_source_url=HRTF_URL,hrtf_sha256=HRTF_SHA256,
|
| 57 |
+
hrtf_measurements=len(positions),source_rate_hz=sample_rate,target_rate_hz=target_rate,
|
| 58 |
+
ear_order=['left','right'],sofa_convention=convention,regularization=ridge_fraction,
|
| 59 |
+
filter_samples=filters.shape[-1],basis_condition_number=float(np.linalg.cond(gram)),
|
| 60 |
+
head_orientation='forward aligned with receiver-local +X; no additional world-yaw rotation',
|
| 61 |
+
filter_delay_policy='causal HRIR delay retained equally on the scene clock; no independent ear shift',
|
| 62 |
+
clip_policy='same samples as original FOA; reject any significant FIR tail truncation',
|
| 63 |
+
approximation='first-order HRTF projection; generic KEMAR head, no individual/headphone equalization',
|
| 64 |
+
attribution=dict(authors=['Bill Gardner','Keith Martin'],institution='MIT Media Laboratory',
|
| 65 |
+
original_measurement_terms_url='https://sound.media.mit.edu/resources/KEMAR.html',
|
| 66 |
+
original_measurement_terms='Free use with citation of the measurement authors',
|
| 67 |
+
sofa_embedded_metadata=attribution))
|
| 68 |
+
return filters,metadata
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def decode_foa(wave,filters):
|
| 72 |
+
if wave.ndim!=2 or wave.shape[1]!=4 or not np.isfinite(wave).all():raise ValueError('Expected finite N x 4 FOA')
|
| 73 |
+
full=np.zeros((len(wave)+filters.shape[-1]-1,2),np.float64)
|
| 74 |
+
for ear in range(2):
|
| 75 |
+
for component in range(4):full[:,ear]+=fftconvolve(wave[:,component],filters[ear,component],mode='full')
|
| 76 |
+
total=float(np.sum(full*full));tail=float(np.sum(full[len(wave):]**2))
|
| 77 |
+
if total<=0 or not np.isfinite(full).all():raise ValueError('Invalid binaural output')
|
| 78 |
+
if tail>total*1e-7:raise ValueError('Significant binaural FIR tail would be cut at scene end')
|
| 79 |
+
return full[:len(wave)].astype(np.float32),tail/total
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def convert(root):
|
| 83 |
+
rendering=read(root/'data/rendering.json');demo=read(root/'data/demo.json')
|
| 84 |
+
task_names=['inputs.jsonl','gold.jsonl','pairs.jsonl','prompts.jsonl','recipe.json']
|
| 85 |
+
task_hashes={name:sha(root/'data'/name) for name in task_names}
|
| 86 |
+
path=root/'assets/hrtf/MIT_KEMAR_normal_pinna.sofa';filters,metadata=decoder_filters(path)
|
| 87 |
+
decoded=[]
|
| 88 |
+
all_records=rendering['recordings']+[d for r in rendering['recordings'] for d in r.get('diagnostics',{}).values()]
|
| 89 |
+
for record in all_records:
|
| 90 |
+
foa=root/record['path']
|
| 91 |
+
if sha(foa)!=record['sha256']:raise ValueError('Original FOA has changed')
|
| 92 |
+
wave,rate=sf.read(foa,dtype='float32')
|
| 93 |
+
if rate!=SR or len(wave)!=record['samples']:raise ValueError('FOA timeline changed')
|
| 94 |
+
output,tail=decode_foa(wave,filters);decoded.append((record,output,tail))
|
| 95 |
+
peak=max(float(np.max(np.abs(x))) for _,x,_ in decoded);gain=.9/peak
|
| 96 |
+
metadata.update(hrtf_asset=str(path.relative_to(root)),common_audition_gain=gain,unscaled_maximum_peak=peak,
|
| 97 |
+
audit_scope='FOA-to-binaural postprocessing only; original FOA means the input to this decoding run',
|
| 98 |
+
source_motion_revision=read(root/'data/recipe.json').get('motion_revision'),
|
| 99 |
+
output_format='16000 Hz PCM_16 stereo WAV [left ear,right ear]',recording_count=len(rendering['recordings']),
|
| 100 |
+
diagnostic_recording_count=len(decoded)-len(rendering['recordings']),audition_file_count=len(decoded),
|
| 101 |
+
derived_from_existing_foa=True,foa_hashes_preserved=True,task_file_hashes_preserved=True)
|
| 102 |
+
audit=[]
|
| 103 |
+
for record,output,tail in decoded:
|
| 104 |
+
suffix='_'+record['diagnostic_source_id']+'_only' if record.get('diagnostic_source_id') else ''
|
| 105 |
+
out=root/'audio'/record['branch']/(record['receiver_id']+suffix+'_binaural.wav')
|
| 106 |
+
sf.write(out,output*gain,SR,subtype='PCM_16')
|
| 107 |
+
record.update(preview_path=str(out.relative_to(root)),preview_sha256=sha(out),
|
| 108 |
+
preview_method=METHOD,preview_channels=['left','right'],preview_sample_rate_hz=SR,
|
| 109 |
+
preview_samples=len(output),preview_gain=gain)
|
| 110 |
+
if sha(root/record['path'])!=record['sha256']:raise ValueError('Conversion modified input FOA')
|
| 111 |
+
audit.append(dict(branch=record['branch'],receiver_id=record['receiver_id'],source_foa_sha256=record['sha256'],
|
| 112 |
+
diagnostic_source_id=record.get('diagnostic_source_id'),
|
| 113 |
+
binaural_sha256=record['preview_sha256'],samples=len(output),truncated_tail_energy_fraction=tail,
|
| 114 |
+
left_rms=float(np.sqrt(np.mean(output[:,0].astype(float)**2)))*gain,
|
| 115 |
+
right_rms=float(np.sqrt(np.mean(output[:,1].astype(float)**2)))*gain))
|
| 116 |
+
by_id={r['recording_id']:r for r in rendering['recordings']}
|
| 117 |
+
for scene in demo['scenes']:scene['recordings']=[by_id[r['recording_id']] for r in scene['recordings']]
|
| 118 |
+
demo['audio_preview_method']=METHOD;demo['binaural_decoding']=metadata;rendering['binaural_decoding']=metadata
|
| 119 |
+
for name,h in task_hashes.items():
|
| 120 |
+
if sha(root/'data'/name)!=h:raise ValueError('Task or scene metadata changed')
|
| 121 |
+
write(root/'data/rendering.json',rendering);write(root/'data/demo.json',demo)
|
| 122 |
+
write(root/'data/binaural.json',dict(passed=True,**metadata,recordings=audit,
|
| 123 |
+
unchanged_task_file_sha256=task_hashes,room_or_foa_regenerated=False))
|
| 124 |
+
print('Decoded existing FOA:',len(decoded),'binaural clips; original FOA and task hashes unchanged',flush=True)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__=='__main__':
|
| 128 |
+
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);a=p.parse_args();convert(a.root.resolve())
|
code/dynamic_demo/fetch_cache.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download verified frozen RIR cache archives from the public demo URL."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import tempfile
|
| 7 |
+
import urllib.request
|
| 8 |
+
from zipfile import ZipFile
|
| 9 |
+
from .common import sha
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
p=argparse.ArgumentParser();p.add_argument('--base-url',required=True);p.add_argument('--work',type=Path,required=True)
|
| 14 |
+
a=p.parse_args();base=a.base_url.rstrip('/')+'/'
|
| 15 |
+
with urllib.request.urlopen(base+'cache/manifest.json',timeout=60) as response:manifest=json.load(response)
|
| 16 |
+
out=a.work/'rirs';out.mkdir(parents=True,exist_ok=True)
|
| 17 |
+
with tempfile.TemporaryDirectory() as temp:
|
| 18 |
+
for record in manifest['archives']:
|
| 19 |
+
archive=Path(temp)/Path(record['path']).name
|
| 20 |
+
urllib.request.urlretrieve(base+record['path'],archive)
|
| 21 |
+
if sha(archive)!=record['sha256']:raise ValueError('Cache download checksum mismatch')
|
| 22 |
+
with ZipFile(archive) as z:
|
| 23 |
+
for name in z.namelist():
|
| 24 |
+
path=Path(name)
|
| 25 |
+
if path.is_absolute() or len(path.parts)!=1 or path.suffix not in ('.json','.npy'):
|
| 26 |
+
raise ValueError('Unexpected cache archive entry')
|
| 27 |
+
z.extractall(out)
|
| 28 |
+
print('Verified',record['path'])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if __name__=='__main__':main()
|
code/dynamic_demo/package.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a scoped public reproduction bundle and optional frozen RIR archives."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import argparse
|
| 4 |
+
import shutil
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from zipfile import ZIP_DEFLATED, ZipFile
|
| 7 |
+
from .common import read,sha,write
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def package(root,work=None,reuse_cache=False):
|
| 11 |
+
repo=Path(__file__).resolve().parents[1]
|
| 12 |
+
folder=root/'reproduction';folder.mkdir(exist_ok=True)
|
| 13 |
+
modules=['__init__.py','common.py','motion.py','continuous.py','diagnostics.py','render.py','export.py','score.py','validate.py','Dockerfile','requirements.txt','fetch_cache.py','package.py','binaural.py']
|
| 14 |
+
for name in modules:
|
| 15 |
+
destination=folder/'dynamic_demo'/name;destination.parent.mkdir(parents=True,exist_ok=True)
|
| 16 |
+
shutil.copyfile(repo/'dynamic_demo'/name,destination)
|
| 17 |
+
for name in ['tests/test_protocol.py','tests/parity.mjs','tests/browser.cjs','tests/test_binaural.py','tests/test_diagnostics.py']:
|
| 18 |
+
destination=folder/'dynamic_demo'/name;destination.parent.mkdir(parents=True,exist_ok=True)
|
| 19 |
+
shutil.copyfile(repo/'dynamic_demo'/name,destination)
|
| 20 |
+
for name in ['native/source_xyz.patch','configs/native_environment.json']:
|
| 21 |
+
destination=folder/'generation'/name;destination.parent.mkdir(parents=True,exist_ok=True)
|
| 22 |
+
shutil.copyfile(repo/'generation'/name,destination)
|
| 23 |
+
cache_manifest=[]
|
| 24 |
+
if work:
|
| 25 |
+
cache=work/'rirs';recipe=read(root/'data/recipe.json')
|
| 26 |
+
write(cache/'cache_context.json',dict(renderer=recipe['renderer'],foa_mapping=recipe['foa_mapping'],
|
| 27 |
+
room_assets_sha256=recipe['room_assets_sha256']))
|
| 28 |
+
cache_dir=root/'cache';cache_dir.mkdir(exist_ok=True)
|
| 29 |
+
covered=set()
|
| 30 |
+
if reuse_cache and (cache_dir/'manifest.json').exists():
|
| 31 |
+
cache_manifest=read(cache_dir/'manifest.json')['archives']
|
| 32 |
+
for record in cache_manifest:
|
| 33 |
+
archive=root/record['path']
|
| 34 |
+
if sha(archive)!=record['sha256']:raise ValueError('Reusable cache archive checksum mismatch')
|
| 35 |
+
with ZipFile(archive) as z:
|
| 36 |
+
covered.update(z.namelist())
|
| 37 |
+
if 'cache_context.json' in z.namelist() and z.read('cache_context.json')!=(cache/'cache_context.json').read_bytes():
|
| 38 |
+
raise ValueError('Reusable archives belong to another room/renderer')
|
| 39 |
+
else:
|
| 40 |
+
for archive in cache_dir.glob('RIR-cache-*.zip'):archive.unlink()
|
| 41 |
+
groups=[];part=[];size=0
|
| 42 |
+
records=read(root/'data/rendering.json')['rir_records']
|
| 43 |
+
paths=[cache/'cache_context.json']+[cache/(r['rir_id']+suffix) for r in records for suffix in ('.json','.npy')]
|
| 44 |
+
for p in sorted(paths):
|
| 45 |
+
if not p.is_file():raise ValueError('Required frozen RIR cache file missing: '+str(p))
|
| 46 |
+
if p.name in covered:continue
|
| 47 |
+
if part and size+p.stat().st_size>40*1024*1024:groups.append(part);part=[];size=0
|
| 48 |
+
part.append(p);size+=p.stat().st_size
|
| 49 |
+
if part:groups.append(part)
|
| 50 |
+
for index,paths in enumerate(groups,len(cache_manifest)+1):
|
| 51 |
+
archive=cache_dir/f'RIR-cache-{index:02d}.zip'
|
| 52 |
+
with ZipFile(archive,'w',ZIP_DEFLATED,compresslevel=5) as z:
|
| 53 |
+
for p in paths:z.write(p,p.name)
|
| 54 |
+
cache_manifest.append(dict(path=str(archive.relative_to(root)),sha256=sha(archive),
|
| 55 |
+
bytes=archive.stat().st_size,files=len(paths)))
|
| 56 |
+
write(cache_dir/'manifest.json',dict(description='Optional frozen native RIR cache; unpack into WORK/rirs',
|
| 57 |
+
archives=cache_manifest,rir_count=len(read(root/'data/rendering.json')['rir_records'])))
|
| 58 |
+
zip_path=root/'reproduction.zip'
|
| 59 |
+
with ZipFile(zip_path,'w',ZIP_DEFLATED,compresslevel=5) as z:
|
| 60 |
+
# No paths outside this demo; no credentials, full benchmark, old releases or author operations.
|
| 61 |
+
for p in sorted(root.rglob('*')):
|
| 62 |
+
relative=p.relative_to(root)
|
| 63 |
+
# The outer manifest hashes this zip; including it here would be stale/circular.
|
| 64 |
+
if not p.is_file() or p in (zip_path,root/'manifest.json') or relative.parts[0] in ('cache','reproduction') or '__pycache__' in relative.parts:continue
|
| 65 |
+
z.write(p,'demo/dynamic/'+str(relative))
|
| 66 |
+
for p in sorted(folder.rglob('*')):
|
| 67 |
+
if p.is_file():z.write(p,str(p.relative_to(folder)))
|
| 68 |
+
z.write(root/'README.md','README.md')
|
| 69 |
+
manifest=[]
|
| 70 |
+
for p in sorted(root.rglob('*')):
|
| 71 |
+
if p.is_file() and 'reproduction' not in p.relative_to(root).parts and p!=root/'manifest.json':
|
| 72 |
+
manifest.append(dict(path=str(p.relative_to(root)),sha256=sha(p),bytes=p.stat().st_size))
|
| 73 |
+
write(root/'manifest.json',dict(description='Only public demo files; frozen inputs and generated outputs',files=manifest))
|
| 74 |
+
print('PACKAGED',zip_path.stat().st_size,'bytes;',len(cache_manifest),'optional cache archives')
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__=='__main__':
|
| 78 |
+
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--work',type=Path)
|
| 79 |
+
p.add_argument('--reuse-cache',action='store_true',help='Keep verified same-room archives and append missing kernels')
|
| 80 |
+
a=p.parse_args();package(a.root.resolve(),a.work.resolve() if a.work else None,a.reuse_cache)
|
code/dynamic_demo/requirements.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Environment used by the current frozen generation and acceptance run (Python 3.12).
|
| 2 |
+
numpy==2.3.5
|
| 3 |
+
scipy==1.18.0
|
| 4 |
+
soundfile==0.14.0
|
| 5 |
+
numpy-quaternion==2024.0.13
|
| 6 |
+
numba==0.67.0
|
| 7 |
+
llvmlite==0.49.0
|
| 8 |
+
attrs==26.1.0
|
| 9 |
+
GitPython==3.1.59
|
| 10 |
+
imageio==2.37.4
|
| 11 |
+
imageio-ffmpeg==0.6.0
|
| 12 |
+
matplotlib==3.11.1
|
| 13 |
+
pillow==12.3.0
|
| 14 |
+
tqdm==4.70.0
|
| 15 |
+
packaging==26.3
|
| 16 |
+
scikit-build-core==1.0.3
|
| 17 |
+
pybind11==3.1.0
|
| 18 |
+
h5py==3.15.1
|
code/dynamic_demo/score.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal demo scorer. Full-benchmark thresholds remain a separate protocol.
|
| 2 |
+
|
| 3 |
+
DOA associations are fixed for the ENTIRE clip. Missing positions receive 180
|
| 4 |
+
degrees in DOA mean/variance; distance and world errors accompany coverage and
|
| 5 |
+
all-reference-frame success, so selective omission cannot hide failures.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import itertools
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
from .common import angular, read, tokens, write
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def finite(x):
|
| 19 |
+
return isinstance(x,(float,int)) and not isinstance(x,bool) and math.isfinite(x)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def frame_map(output,times,kind):
|
| 23 |
+
valid=isinstance(output,dict) and isinstance(output.get('frames'),list)
|
| 24 |
+
if not valid:return {},False
|
| 25 |
+
expected={round(t*10) for t in times};result={};duplicates=set()
|
| 26 |
+
for f in output['frames']:
|
| 27 |
+
if not isinstance(f,dict) or not finite(f.get('time_s')):
|
| 28 |
+
valid=False;continue
|
| 29 |
+
t=f['time_s'];key=round(t*10)
|
| 30 |
+
if abs(t-key/10)>1e-6 or key not in expected or not isinstance(f.get('active'),bool):
|
| 31 |
+
valid=False;continue
|
| 32 |
+
if key in result or key in duplicates:
|
| 33 |
+
result.pop(key,None);duplicates.add(key);valid=False;continue
|
| 34 |
+
if f['active']:
|
| 35 |
+
v=f.get(kind)
|
| 36 |
+
good=finite(v) and v>0 if kind=='distance_m' else (
|
| 37 |
+
isinstance(v,list) and len(v)==(2 if kind=='doa_deg' else 3) and all(finite(x) for x in v))
|
| 38 |
+
if kind=='doa_deg' and good:good=-90<=v[1]<=90
|
| 39 |
+
if not good:valid=False;continue
|
| 40 |
+
result[key]=f
|
| 41 |
+
if set(result)!=expected:valid=False
|
| 42 |
+
return result,valid
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def edit_distance(a,b):
|
| 46 |
+
row=list(range(len(b)+1))
|
| 47 |
+
for i,x in enumerate(a,1):
|
| 48 |
+
new=[i]
|
| 49 |
+
for j,y in enumerate(b,1):new.append(min(row[j]+1,new[-1]+1,row[j-1]+(x!=y)))
|
| 50 |
+
row=new
|
| 51 |
+
return row[-1]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def stats(errors):
|
| 55 |
+
if not errors:return dict(mean_error=None,variance_error=None,rmse=None)
|
| 56 |
+
mean=sum(errors)/len(errors)
|
| 57 |
+
return dict(mean_error=mean,variance_error=sum((e-mean)**2 for e in errors)/len(errors),
|
| 58 |
+
rmse=math.sqrt(sum(e*e for e in errors)/len(errors)))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def score(gold,prediction):
|
| 62 |
+
task=gold['task_id'];answer=gold['output'];times=gold['expected_times_s']
|
| 63 |
+
if task=='KW_ASR':
|
| 64 |
+
valid=isinstance(prediction,str);p=tokens(prediction) if valid else [];r=tokens(answer)
|
| 65 |
+
if not r:
|
| 66 |
+
return dict(format_valid=valid,keyword_case=gold['keyword_case'],reference_words=0,
|
| 67 |
+
edits=0,wer=None,empty_correct=valid and not p,exact_match=valid and not p)
|
| 68 |
+
edits=edit_distance(r,p)
|
| 69 |
+
return dict(format_valid=valid,keyword_case=gold['keyword_case'],reference_words=len(r),
|
| 70 |
+
edits=edits,wer=edits/len(r),empty_correct=None,exact_match=valid and p==r)
|
| 71 |
+
if task=='DOA_TRAJECTORY':
|
| 72 |
+
refs=answer['tracks'];raw=prediction.get('tracks',[]) if isinstance(prediction,dict) else []
|
| 73 |
+
valid=isinstance(raw,list) and isinstance(prediction,dict) and 'tracks' in prediction
|
| 74 |
+
if not isinstance(raw,list) or len(raw)>8:raw=[];valid=False
|
| 75 |
+
track_ids=[tr.get('track_id') for tr in raw if isinstance(tr,dict)]
|
| 76 |
+
if len(track_ids)!=len(raw) or any(not isinstance(x,str) or not x for x in track_ids) or len(set(track_ids))!=len(track_ids):
|
| 77 |
+
raw=[];valid=False
|
| 78 |
+
maps=[]
|
| 79 |
+
for tr in raw:
|
| 80 |
+
m,v=frame_map(tr,times,'doa_deg');maps.append(m);valid&=v
|
| 81 |
+
if len(raw)!=len(refs):valid=False
|
| 82 |
+
while len(maps)<len(refs):maps.append({})
|
| 83 |
+
def cost(ref,m):
|
| 84 |
+
return sum(angular(f['doa_deg'],m[round(f['time_s']*10)]['doa_deg'])
|
| 85 |
+
if round(f['time_s']*10) in m and m[round(f['time_s']*10)]['active'] else 180.
|
| 86 |
+
for f in ref['frames'] if f['active'])
|
| 87 |
+
assignment=min(itertools.permutations(range(len(maps)),len(refs)),
|
| 88 |
+
key=lambda p:sum(cost(refs[i],maps[j]) for i,j in enumerate(p)))
|
| 89 |
+
errors=[];total=observed=success=tp=fp=fn=0;association={}
|
| 90 |
+
for i,j in enumerate(assignment):
|
| 91 |
+
ref=refs[i];m=maps[j];association[ref['track_id']]=raw[j]['track_id'] if j<len(raw) else None
|
| 92 |
+
for f in ref['frames']:
|
| 93 |
+
p=m.get(round(f['time_s']*10));on=bool(p and p['active'])
|
| 94 |
+
tp+=f['active'] and on;fp+=not f['active'] and on;fn+=f['active'] and not on
|
| 95 |
+
if f['active']:
|
| 96 |
+
total+=1
|
| 97 |
+
e=angular(f['doa_deg'],p['doa_deg']) if on else 180.
|
| 98 |
+
errors.append(e);observed+=on;success+=on and e<=20.
|
| 99 |
+
for j,m in enumerate(maps):
|
| 100 |
+
if j not in assignment:fp+=sum(f['active'] for f in m.values())
|
| 101 |
+
switches=0
|
| 102 |
+
for m in maps:
|
| 103 |
+
previous=None
|
| 104 |
+
for key in sorted(m):
|
| 105 |
+
f=m[key]
|
| 106 |
+
if not f['active']:continue
|
| 107 |
+
candidates=[]
|
| 108 |
+
for ref in refs:
|
| 109 |
+
rf=ref['frames'][key]
|
| 110 |
+
if rf['active']:candidates.append((angular(rf['doa_deg'],f['doa_deg']),ref['track_id']))
|
| 111 |
+
if not candidates:continue
|
| 112 |
+
e,identity=min(candidates)
|
| 113 |
+
if e<=20:
|
| 114 |
+
if previous is not None and previous!=identity:switches+=1
|
| 115 |
+
previous=identity
|
| 116 |
+
return dict(format_valid=bool(valid),units='degrees; variance degrees squared',**stats(errors),
|
| 117 |
+
reference_active_frames=total,covered_frames=observed,coverage=observed/max(total,1),
|
| 118 |
+
success_rate_20deg=success/max(total,1),active_precision=tp/max(tp+fp,1),
|
| 119 |
+
active_recall=tp/max(tp+fn,1),missed_frames=fn,false_positive_frames=fp,
|
| 120 |
+
identity_switches_diagnostic=switches,whole_clip_assignment=association)
|
| 121 |
+
kind='distance_m' if task=='RANGE_TRAJECTORY' else 'xyz_m'
|
| 122 |
+
m,valid=frame_map(prediction,times,kind);errors=[];total=tp=fp=fn=success=0
|
| 123 |
+
for f in answer['frames']:
|
| 124 |
+
p=m.get(round(f['time_s']*10));on=bool(p and p['active'])
|
| 125 |
+
tp+=f['active'] and on;fp+=not f['active'] and on;fn+=f['active'] and not on
|
| 126 |
+
if f['active']:
|
| 127 |
+
total+=1
|
| 128 |
+
if on:
|
| 129 |
+
e=abs(f[kind]-p[kind]) if kind=='distance_m' else math.dist(f[kind],p[kind])
|
| 130 |
+
errors.append(e);success+=e<=.5
|
| 131 |
+
return dict(format_valid=valid,units='meters; variance meters squared',**stats(errors),
|
| 132 |
+
reference_active_frames=total,covered_frames=len(errors),coverage=len(errors)/max(total,1),
|
| 133 |
+
success_rate_0_5m=success/max(total,1),active_precision=tp/max(tp+fp,1),
|
| 134 |
+
active_recall=tp/max(tp+fn,1),missed_frames=fn,false_positive_frames=fp)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def main():
|
| 138 |
+
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True)
|
| 139 |
+
p.add_argument('--predictions',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
|
| 140 |
+
a=p.parse_args();gold=[json.loads(x) for x in (a.root/'data/gold.jsonl').read_text().splitlines() if x.strip()]
|
| 141 |
+
known={g['sample_id'] for g in gold};preds={}
|
| 142 |
+
for line in a.predictions.read_text().splitlines():
|
| 143 |
+
if not line.strip():continue
|
| 144 |
+
row=json.loads(line);sid=row.get('sample_id')
|
| 145 |
+
if sid not in known or sid in preds:raise ValueError('Unknown or duplicate sample_id: '+str(sid))
|
| 146 |
+
preds[sid]=row.get('output')
|
| 147 |
+
rows=[dict(sample_id=g['sample_id'],task_id=g['task_id'],setting=g['setting'],branch=g['branch'],
|
| 148 |
+
**score(g,preds.get(g['sample_id']))) for g in gold]
|
| 149 |
+
groups={}
|
| 150 |
+
for row in rows:
|
| 151 |
+
key='/'.join([row['branch'],row['task_id'],row['setting']]);groups.setdefault(key,[]).append(row)
|
| 152 |
+
summary={}
|
| 153 |
+
for key,values in groups.items():
|
| 154 |
+
summary[key]=dict(samples=len(values),format_valid_fraction=sum(r['format_valid'] for r in values)/len(values))
|
| 155 |
+
if values[0]['task_id']=='KW_ASR':
|
| 156 |
+
refs=sum(r['reference_words'] for r in values);edits=sum(r['edits'] for r in values)
|
| 157 |
+
neg=[r for r in values if not r['reference_words']]
|
| 158 |
+
summary[key].update(corpus_wer=edits/refs if refs else None,
|
| 159 |
+
empty_correct_fraction=sum(r['empty_correct'] for r in neg)/len(neg) if neg else None)
|
| 160 |
+
else:
|
| 161 |
+
total=sum(r['reference_active_frames'] for r in values)
|
| 162 |
+
summary[key]['coverage']=sum(r['covered_frames'] for r in values)/max(total,1)
|
| 163 |
+
write(a.output,dict(scorer_version='dish_dynamic_demo_v1',samples=len(rows),
|
| 164 |
+
missing_predictions=len(known-set(preds)),summary=summary,per_sample=rows))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if __name__=='__main__':main()
|
code/exhibition_dataset/README.zh.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 展厅共享配置的静态与动态测试集
|
| 2 |
+
|
| 3 |
+
本版本每类包含 **100 套固定展厅 × 每厅 20 个物理样本 = 2,000 个样本**,共 4,000 个静态/动态物理样本。一个样本包含全部机器人录音、每个机器人的独立端侧视角,以及接收全部机器人的一个云端视角。问题、接收视角和提示信息变体不重复计入物理样本数。
|
| 4 |
+
|
| 5 |
+
本目录是新版生成和评测入口,与 `generation/` 的历史静态版本、`dynamic_dataset/` 的已发布动态版本分别使用输出目录。生成进度不等于发行完成;只有全量渲染、归一化、导出、验收和评分自检通过后,才写入 `release.complete.json`。
|
| 6 |
+
|
| 7 |
+
## 固定房间与成组变体
|
| 8 |
+
|
| 9 |
+
每厅固定网格、尺寸、展柜布局、材料频率响应及声学校准结果。100 厅从已有通过验收的展厅中按面积/RT60 九格分层选取,覆盖中心展柜、周边展柜和开放中心三种室内布局。这里的开放中心仍是有墙的展厅,不是开放空间。
|
| 10 |
+
|
| 11 |
+
| 每厅的组 | 静态物理样本 | 动态物理样本 | 保持/改变的条件 |
|
| 12 |
+
|---|---:|---:|---|
|
| 13 |
+
| 机器人/人声数量 | 9 | 9 | 1–3 机器人 × 1–3 人声;新增机器人只增加接收点,关闭播放声,共有接收点的录音完全相同 |
|
| 14 |
+
| 环境噪声 | 4 | 4 | 干净、20/10/0 dB;同组只改变同一噪声的发声增益 |
|
| 15 |
+
| 距离、干扰、播放/运动控制 | 7 | 7 | 静态:基准、近/远目标、干扰延迟、弱/强竞争语音、关闭播放;动态:人动、机器人动、两种共同运动、整体同向平移、慢速、快速 |
|
| 16 |
+
|
| 17 |
+
静态近/远变体只改变 H01 沿 R01 原方位射线的位置;干扰延迟为 0.8 秒,竞争语音增益为 ±6 dB。近目标距离 1.6 m;远目标在合法展厅空间中选择约 4.1–5.4 m,接受配方保存实际值。
|
| 18 |
+
|
| 19 |
+
动态慢/中/快峰值速度为 0.65/0.73/0.8 m/s。每个移动体平移超过 2 m,机器人高度与朝向不变,使用连续 minimum-jerk 轨迹。总时长在原有约 7.5–9.4 秒范围内,实际配方选择 8.4/8.8/9.0 秒。主要移动目标使用约 5.6–6.3 秒的连续真人语音;不拼接、重复或变速,内部能量静默不超过 0.35 秒。
|
| 20 |
+
|
| 21 |
+
动态共 1,000 个 easy、1,000 个 hard。每厅的控制组含 5 个基本运动条件与 2 个速度条件:50 厅提供完整人动慢/中/快三元组,另 50 厅提供共同运动的中/快对照。整体平移用于检验“世界坐标在动、相对方位和距离保持不变”的坐标系一致性。
|
| 22 |
+
|
| 23 |
+
静动共有 2,000 条严格对应链接:1,400 个不同静态样本对应全部 2,000 个动态样本,其中每厅的控制组基准对应 7 种运动。静态录音没有为这些运动分支重复计数,其余 600 个静态样本用于独立消融。
|
| 24 |
+
|
| 25 |
+
## 真实噪声与接收端统计
|
| 26 |
+
|
| 27 |
+
80 个噪声组使用经过自动非语音筛选的真实 ESC-50 录音,20 个组使用可复现的合成风扇声。真实类别为键盘、吸尘设备与时钟,107 个不同原始录音候选中保留 93 个、排除 14 个。噪声仅作干扰,不新增环境事件任务。
|
| 28 |
+
|
| 29 |
+
ESC-50 提交固定为 `33c8ce9eb2cf0b1c2f8bcf322eb349b6be34dbb6`;Silero VAD 提交为 `1e261b036686cd0017d500ee96acd1c4ba572a9d`,JIT SHA256 为 `e1122837f4154c511485fe0b9c64455f7b929c96fbb8d79fbdb336383ebd3720`。筛选条件为每个 32 ms 块的语音概率小于 0.35;保留逐文件证据和排除记录,未声称完成逐条人工试听。
|
| 30 |
+
|
| 31 |
+
真实素材保留可能存在的原录音声学特性,不宣称消声室录音。每个噪声作为展厅中的固定声源经过同一房间 RIR 渲染,前置 2.5 秒传播预热,再裁取场景片段;5 秒噪声录音只对噪声做带 100 ms 平滑交叠的循环延长。
|
| 32 |
+
|
| 33 |
+
20/10/0 dB 的定义是**静态 R01、H01 发声活动时段内,W 通道目标/环境噪声能量比**。得到一次噪声发声增益后,各机器人和静动配对保持该增益,因此其他接收点、移动后的实际 SNR 可以不同。metadata 保存每个说话人/接收点的实际 SNR、SIR、SINR 和遮挡时间标签。归一化以同组全部静态与动态录音的共同峰值为基准,保持所有相对声级。
|
| 34 |
+
|
| 35 |
+
ESC-50 真实素材及其衍生混音遵守 CC BY-NC 4.0,LibriSpeech 原语音遵守 CC BY 4.0;原始许可、URL、文件 ID 和 SHA 随数据保留。项目代码的既有权利不会由生成脚本重新指定。
|
| 36 |
+
|
| 37 |
+
## 音频、时钟与任务
|
| 38 |
+
|
| 39 |
+
FOA 为 16 kHz float32 WAV,ACN/SN3D `[W,Y,Z,X]`。世界 +Y 向上,yaw=0 面向世界 -Z;方位左正右负。没有双耳文件、同步偏差、时钟漂移或丢片段。R01 不发声,R02/R03 可以播放;每个接收点理想移除自己的播放,其他播放作干扰。
|
| 40 |
+
|
| 41 |
+
**声源和接收器 RIR 均每 0.2 秒取样,动态所有空间输出和公开机器人位姿均每 0.5 秒取样。两个间隔独立。** 时间网格从 0 开始,严格小于片段总时长。标签保留全精度;prompt 中位置、区域边界保留���位小数米,方位查询和 yaw 为整数。区域与发声体保持 20 cm 边界余量,距离查询保持 1° 扇区边界余量。
|
| 42 |
+
|
| 43 |
+
| 模式/部署 | 任务 | 输出 |
|
| 44 |
+
|---|---|---|
|
| 45 |
+
| 静态端侧 | DOA、RANGE、TEXT_DOA、DOA_ASR、KW_ASR | 所有人声与其他机器人的播放方向;指定人的距离、方向或完整转录 |
|
| 46 |
+
| 静态云端 | C1_SETLOC、C2_REGION_ASR、C3_TEXTLOC、KW_ASR | 人声位置集合;区域内人的转录;文本对应人的世界坐标;关键词目标的完整转录 |
|
| 47 |
+
| 动态端侧 | DOA_TRAJECTORY、RANGE_TRAJECTORY、KW_ASR | 所有人声绝对 DOA 轨迹;初始发声帧+方位扇区指定人的距离轨迹;关键词目标的完整转录 |
|
| 48 |
+
| 动态云端 | TEXT_TRAJECTORY、KW_ASR | 给定文本对应人的世界坐标轨迹;关键词目标的完整转录 |
|
| 49 |
+
|
| 50 |
+
动态空间轨迹只以人声为目标。每个时间点输出 `time_s` 与 `active`;发声时加 `doa_deg`、`distance_m` 或 `xyz_m`,静默时省略坐标,静默时不计空间误差。DOA 的说话人 ID 在整段片段内保持稳定,评分只做一次全片段身份匹配。
|
| 51 |
+
|
| 52 |
+
唤醒词为真人语句开头的连续 1–3 个整词;每道正例最多命中一个人,返回该人在片段内的全部语音,包含唤醒词。没人命中或只有机器人命中时返回字面空字符串 `""`。不生成多人命中的问题。
|
| 53 |
+
|
| 54 |
+
## 文件与对应关系
|
| 55 |
+
|
| 56 |
+
输出根目录包含 `config.json`、`private/recipes.jsonl`、`private/rooms.jsonl`、`shared/`,以及独立的 `static/`、`dynamic/`:
|
| 57 |
+
|
| 58 |
+
- `public/test/scenes.jsonl`:`scene_id` 是共享房间配置 ID,含尺寸、布局、RT60 校准和资产 hash。
|
| 59 |
+
- `public/test/episodes.jsonl`:`episode_id` 是具体物理样本 ID,含时长、机器人 IDs、位姿与已知播放。
|
| 60 |
+
- `public/test/recordings.jsonl`、`views.jsonl`:录音及 N 个端侧视角、1 个完整云端视角的绑定。
|
| 61 |
+
- `public/test/inputs.jsonl`、`prompts.jsonl`、`index.jsonl`:逐题模型输入、已渲染 prompt、随机访问索引。
|
| 62 |
+
- `public/test/pairs.jsonl`:同题端侧/云端关系;`target_group_id` 将不同接收器的同一人联系起来,DOA 和距离仍按各自收音器计算。
|
| 63 |
+
- `public/test/physical_pairs.jsonl`:静动对应链接。
|
| 64 |
+
- `public/test/keyword_variants.jsonl`:同目标 1/2/3 词句首查询;比较时取所有词数都有效的样本交集,只向模型提供所选查询。
|
| 65 |
+
- `private/test/episodes.jsonl`:真人和机器人的原始语音、身份、裁剪、事件、全精度位置/速度轨迹、相对机器人几何和接收端声学统计。
|
| 66 |
+
- `private/test/gold.jsonl`:逐题完整参考答案;`private/ablation_groups.jsonl`:明确的物理消融对照与改变因素。
|
| 67 |
+
|
| 68 |
+
模型每次只看到一道题的输入和对应 FOA,不能读取私有答案、其他题的文本查询或 creator-side 配方。`loader.Dataset.load` 同时删除 prompt 和结构化输入中被消融的信息。
|
| 69 |
+
|
| 70 |
+
模型加载器默认要求对应模式的 `release.complete.json` 验收通过;显式检查未发行的小样本时才使用 `--allow-pilot` 或 `Dataset(..., allow_pilot=True)`。
|
| 71 |
+
|
| 72 |
+
## 生成、续跑与完整验收
|
| 73 |
+
|
| 74 |
+
本机 `runtime.sh` 使用已经锁定的 Habitat 音频环境;其他机器沿用 `dynamic_demo/Dockerfile` 的 native 编译环境和版本。其 RLR 声学射线计算主要使用 CPU,GPU 编号仅显式绑定所选节点环境,不能据此声称 GPU 加速。Docker/个人复现机可设置 `DISH_ALLOW_LOCAL_RENDER=1`,集群生成仍要求已分配的计算节点。
|
| 75 |
+
|
| 76 |
+
本版本实际数值环境为 Python 3.12、NumPy 2.5.2、SciPy 1.18.0、SoundFile 0.14.0、numpy-quaternion 2024.0.13。使用旧 native Docker 环境后,执行 `python -m pip install -r exhibition_dataset/requirements-native.txt` 对齐数值包;完整实际环境随输出保存在 `provenance/environment.json`。
|
| 77 |
+
|
| 78 |
+
从已经冻结的输入 bundle/完整数据根目录复现,不重新随机挑素材:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
python -m exhibition_dataset.reproduce --bundle /path/to/frozen_dataset --root /path/to/new_output --stage initialize
|
| 82 |
+
python -m exhibition_dataset.reproduce --root /path/to/new_output --stage static --processes 16
|
| 83 |
+
python -m exhibition_dataset.reproduce --root /path/to/new_output --stage dynamic --processes 32
|
| 84 |
+
python -m exhibition_dataset.reproduce --root /path/to/new_output --stage finalize --processes 16
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
初始化校验原始语音与真实噪声字节,重建并校验房间资产,恢复全部接受配方。静态/动态可在两台节点同时运行;动态噪声组会等待静态作业生成共享增益。每个 native 子进程独占一组,300 秒没有内核进度时至多重启 3 次,保留同配方及校验后的临时 RIR 缓存。完成 marker 才表示整组通过;不同作业不能并发写同一组。
|
| 88 |
+
|
| 89 |
+
跨节点协助渲染时,先选未开始的组;native 入口通过共享文件系统的 `flock` 串行化同组写入,等待锁时持续记录心跳。实际运行前须验证共享文件系统支持跨节点互斥。本轮已��两台计算节点验证。
|
| 90 |
+
|
| 91 |
+
`preflight` 检查全部 4,000 个配方、严格配对、连续语音、主要人声发声期间 >2 m 的移动与每道题的标准答案可评分性。`finalize` 联合归一化、导出 metadata/prompt/标签、校验所有 FOA 和视角关系、验证人数消融的公共录音字节相同,并运行完美参考答案与全缺失预测的评分自检。该自检是评分器校验,不是模型测试结果。
|
| 92 |
+
|
| 93 |
+
同一时刻的实体间距之外,还检查卷积实际需要的跨发射/接收 RIR 节点组合,排除小于 0.1 m、进入 native 声源近场数值奇异区的组合。本轮 6 组运动方向按该规则重采样;静态位置、语音、噪声、峰值速度、条件和静动配对不变。重采样以 0.2 m 留余量,旧配方、改变的 episode IDs 和恢复记录保存在 `private/repairs/` 与逐组配方中。
|
| 94 |
+
|
| 95 |
+
`reports/` 保存逐组进度、RIR 验收与失败恢复记录。原生 Monte Carlo RIR 不保证跨进程/机器的混音字节相同;复现保证相同接受素材、几何、运动、声学参数和验收协议。发行 WAV 的 SHA 用于核验发行资产。
|
| 96 |
+
|
| 97 |
+
## 模型测试与消融
|
| 98 |
+
|
| 99 |
+
在仓库根目录实现 `my_adapter.predict(model_input)`,返回任务指定 JSON 对象/数值/转录。`model_input['audio']` 保留各接收点的四通道数组,不应简单混合多个接收点后当作完整多点输入。
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
python -m exhibition_dataset.loader --root /path/to/dataset/dynamic --adapter my_adapter:predict --output predictions.jsonl
|
| 103 |
+
python -m exhibition_dataset.loader --root /path/to/dataset/dynamic --adapter my_adapter:predict --context without_peer_poses --output predictions_without_peers.jsonl
|
| 104 |
+
python -m exhibition_dataset.score --root /path/to/dataset/dynamic --predictions predictions.jsonl --output scores
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
信息消融覆盖同伴位姿、播放时间、播放内容、全部播放信息、房间信息,以及完整房间布局/材料。云端始终保留所接收机器人的必要坐标标定;“移除同伴位姿”只移除未接收音频的机器人的位姿。
|
| 108 |
+
|
| 109 |
+
误差报告含均值、总体方差、RMSE、覆盖率、缺失帧、额外活动帧和身份切换诊断。缺失 DOA 按 180° 进入误差统计;距离/世界坐标误差只在有效覆盖帧统计,同时必须报告全部参考帧分母的成功率和覆盖率。ASR 报正例 corpus WER 和负例空字符串准确率。KW-ASR 另报严格配对的云端相对平均端侧收益。
|
| 110 |
+
|
| 111 |
+
同一份固定预测同时计算角度 5/10/20/30/45°、距离与世界坐标 0.25/0.5/1/1.5/2 m 的宽容度曲线。结果按机器人数量、人声数量、布局、RT60、噪声及目标/接收器运动分层。统计置信区间应按展厅或匹配组抽样;不能把相关接收视角、变体、复用语音裁剪当作独立数据,也不能把调宽阈值写成模型能力改善。本版本为测试集;跨房间和原语音的训练/验证隔离需要实验方另外执行。
|
code/exhibition_dataset/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Matched exhibition-hall static/dynamic benchmark generation, version 1."""
|
code/exhibition_dataset/ablations.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit matched physical interventions; context changes reuse audio."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from .common import uid
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def group_manifest(group,mode):
|
| 8 |
+
episodes=group[mode+'_episodes']
|
| 9 |
+
named={e.get('condition_name',e['branch']):e for e in episodes}
|
| 10 |
+
pairs=[]
|
| 11 |
+
def pair(left,right,factors,kind='one_factor'):
|
| 12 |
+
if left not in named or right not in named:
|
| 13 |
+
return
|
| 14 |
+
pairs.append(dict(pair_id=uid(group['group_id'],mode,left,right),
|
| 15 |
+
reference_episode_id=named[left]['episode_id'],
|
| 16 |
+
variant_episode_id=named[right]['episode_id'],
|
| 17 |
+
changed_factors=factors,intervention_type=kind))
|
| 18 |
+
family=group['family_type']
|
| 19 |
+
if family=='count':
|
| 20 |
+
for humans in [1,2,3]:
|
| 21 |
+
for n in [1,2]:
|
| 22 |
+
pair(f'robots_{n}_humans_{humans}',f'robots_{n+1}_humans_{humans}',
|
| 23 |
+
['receiver_count'])
|
| 24 |
+
for robots in [1,2,3]:
|
| 25 |
+
for n in [1,2]:
|
| 26 |
+
pair(f'robots_{robots}_humans_{n}',f'robots_{robots}_humans_{n+1}',
|
| 27 |
+
['human_count'])
|
| 28 |
+
elif family=='noise':
|
| 29 |
+
for level in [20,10,0]:
|
| 30 |
+
pair('clean','snr_'+str(level),['environmental_noise_emission_gain'])
|
| 31 |
+
pair('snr_20','snr_10',['environmental_noise_emission_gain'])
|
| 32 |
+
pair('snr_10','snr_0',['environmental_noise_emission_gain'])
|
| 33 |
+
elif mode=='static':
|
| 34 |
+
for name,factor in [('target_near','H01_position'),('target_far','H01_position'),
|
| 35 |
+
('delayed_interference','interference_start_time'),
|
| 36 |
+
('weaker_competing_speech','competing_speech_emitted_gain'),
|
| 37 |
+
('stronger_competing_speech','competing_speech_emitted_gain'),
|
| 38 |
+
('robot_playback_off','other_robot_playback_presence')]:
|
| 39 |
+
pair('baseline',name,[factor])
|
| 40 |
+
else:
|
| 41 |
+
pair('easy_human_slow','easy_human',['H01_peak_speed'])
|
| 42 |
+
pair('easy_human','easy_human_fast',['H01_peak_speed'])
|
| 43 |
+
pair('hard_joint_a','hard_joint_a_fast',['all_moving_entity_peak_speeds'])
|
| 44 |
+
pair('hard_joint_a','hard_joint_b',['entity_translation_vectors'])
|
| 45 |
+
pair('easy_human','hard_joint_a',['robot_motion','other_human_motion'],'combined')
|
| 46 |
+
pair('easy_robot','hard_joint_a',['other_robot_motion','human_motion'],'combined')
|
| 47 |
+
pair('hard_joint_a','shared_translation',['entity_translation_vectors'],'diagnostic')
|
| 48 |
+
return dict(group_id=group['group_id'],scene_id=group['scene_id'],mode=mode,
|
| 49 |
+
family_type=family,episode_ids=[e['episode_id'] for e in episodes],comparisons=pairs,
|
| 50 |
+
count_control_notes='Receiver-count variants disable all robot playback. Common receiver audio is byte-identical after joint normalization. Remove unobserved peer poses to isolate an edge audio comparison.',
|
| 51 |
+
independence='Compare within hall and family; these episodes are correlated.')
|
code/exhibition_dataset/common.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned identities, distinct acoustic/label clocks and receiver views."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import gzip
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import struct
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
from dynamic_dataset.common import geometry, position, velocity
|
| 15 |
+
from dynamic_demo.common import active, angular, speech_activity, tokens
|
| 16 |
+
|
| 17 |
+
VERSION = 'dish_exhibition_v1'
|
| 18 |
+
SR = 16000
|
| 19 |
+
LABEL_STEP = 8000 # 0.5 seconds; deliberately independent of RIR knots.
|
| 20 |
+
RIR_STEP_S = 0.2
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def read(path):
|
| 24 |
+
return json.loads(Path(path).read_text())
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def rows(path):
|
| 28 |
+
p = Path(path)
|
| 29 |
+
with (gzip.open(p, 'rt') if p.suffix == '.gz' else p.open()) as stream:
|
| 30 |
+
for line in stream:
|
| 31 |
+
if line.strip():
|
| 32 |
+
yield json.loads(line)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def write(path, value):
|
| 36 |
+
p = Path(path)
|
| 37 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
temporary = p.with_name(p.name + f'.{os.getpid()}.tmp')
|
| 39 |
+
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + '\n')
|
| 40 |
+
temporary.replace(p)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def jsonl(path, values):
|
| 44 |
+
p = Path(path)
|
| 45 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
temporary = p.with_name(p.name + f'.{os.getpid()}.tmp')
|
| 47 |
+
with temporary.open('w') as stream:
|
| 48 |
+
for value in values:
|
| 49 |
+
stream.write(json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False) + '\n')
|
| 50 |
+
temporary.replace(p)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def sha(path):
|
| 54 |
+
h = hashlib.sha256()
|
| 55 |
+
with Path(path).open('rb') as stream:
|
| 56 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
| 57 |
+
h.update(chunk)
|
| 58 |
+
return h.hexdigest()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def write_float_wav(path,wave,rate=SR):
|
| 62 |
+
"""Deterministic IEEE float WAV without libsndfile's dated PEAK chunk."""
|
| 63 |
+
data=np.asarray(wave,dtype='<f4',order='C')
|
| 64 |
+
if data.ndim!=2 or data.shape[1]!=4 or not np.isfinite(data).all():
|
| 65 |
+
raise ValueError('FOA must have four finite channels')
|
| 66 |
+
payload=data.tobytes()
|
| 67 |
+
fmt=struct.pack('<HHIIHH',3,4,rate,rate*16,16,32)
|
| 68 |
+
with Path(path).open('wb') as stream:
|
| 69 |
+
stream.write(b'RIFF'+struct.pack('<I',48+len(payload))+b'WAVE')
|
| 70 |
+
stream.write(b'fmt '+struct.pack('<I',16)+fmt)
|
| 71 |
+
stream.write(b'fact'+struct.pack('<II',4,len(data)))
|
| 72 |
+
stream.write(b'data'+struct.pack('<I',len(payload)))
|
| 73 |
+
stream.write(payload)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def uid(*parts):
|
| 77 |
+
text = json.dumps([VERSION, *parts], sort_keys=True, separators=(',', ':'), allow_nan=False)
|
| 78 |
+
return hashlib.sha256(text.encode()).hexdigest()[:24]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def grid(episode):
|
| 82 |
+
return list(range(0, episode['duration_samples'], LABEL_STEP))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def rir_nodes(entity):
|
| 86 |
+
if not np.any(entity['displacement_m']):
|
| 87 |
+
return [0.]
|
| 88 |
+
end = entity.get('motion_start_s', 0.) + entity['motion_duration_s']
|
| 89 |
+
count = int(np.ceil((end - 1e-9) / RIR_STEP_S))
|
| 90 |
+
return [round(i * RIR_STEP_S, 9) for i in range(count + 1)]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def views(episode):
|
| 94 |
+
"""N edge views plus one full-cloud view, including distinct 1-robot IDs."""
|
| 95 |
+
rids = [r['entity_id'] for r in episode['robots']]
|
| 96 |
+
for setting, observed in [('edge', [r]) for r in rids] + [('cloud', rids)]:
|
| 97 |
+
yield dict(view_id=uid(episode['episode_id'], 'view', setting, observed),
|
| 98 |
+
episode_id=episode['episode_id'], scene_id=episode['scene_id'],
|
| 99 |
+
setting=setting, receiver_ids=observed,
|
| 100 |
+
reference_robot_id=observed[0] if setting == 'edge' else None)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def frames(episode, human, receiver=None, kind='xyz_m'):
|
| 104 |
+
result = []
|
| 105 |
+
for sample in grid(episode):
|
| 106 |
+
time = sample / SR
|
| 107 |
+
f = dict(time_s=time, active=active(human, sample))
|
| 108 |
+
if f['active']:
|
| 109 |
+
f[kind] = position(human, time).tolist() if kind == 'xyz_m' else geometry(human, receiver, time)[kind]
|
| 110 |
+
result.append(f)
|
| 111 |
+
return result
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def robot_poses(episode):
|
| 115 |
+
times = grid(episode) if episode['mode'] == 'dynamic' else [0]
|
| 116 |
+
return [dict(robot_id=r['entity_id'], yaw_deg=round(r['yaw_deg']),
|
| 117 |
+
positions=[[s / SR] + [round(float(v), 1) for v in position(r, s / SR)] for s in times])
|
| 118 |
+
for r in episode['robots']]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def playback_log(episode):
|
| 122 |
+
return [dict(robot_id=r['entity_id'], start_sample=e['start_sample'], end_sample=e['end_sample'],
|
| 123 |
+
start_time_s=round(e['start_sample'] / SR, 3), end_time_s=round(e['end_sample'] / SR, 3), text=e['text'])
|
| 124 |
+
for r in episode['playback_sources'] for e in r['events']]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def canonical_physics(episode):
|
| 128 |
+
"""Reject duplicate audio-generating recipes even when bookkeeping IDs differ."""
|
| 129 |
+
return {k: copy.deepcopy(episode[k]) for k in
|
| 130 |
+
['duration_samples', 'humans', 'robots', 'playback_sources', 'noise', 'scene_id']}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def code_hashes():
|
| 134 |
+
root = Path(__file__).parent
|
| 135 |
+
return {p.name: sha(p) for p in sorted(root.glob('*.py'))}
|
code/exhibition_dataset/export.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unified public inputs, private labels, edge/cloud and ablation correspondence."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import Counter
|
| 6 |
+
import copy
|
| 7 |
+
import math
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
from .common import *
|
| 13 |
+
from .prompts import render, ablation_recipes
|
| 14 |
+
from .ablations import group_manifest
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def transcript(source):
|
| 18 |
+
return ' '.join(e['text'] for e in sorted(source['events'], key=lambda e:e['start_sample']))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def keyword_alternatives(episode, source):
|
| 22 |
+
words = tokens(source['events'][0]['text'])
|
| 23 |
+
result = []
|
| 24 |
+
for size in [1,2,3]:
|
| 25 |
+
prefix = words[:size]
|
| 26 |
+
if len(prefix) != size:
|
| 27 |
+
continue
|
| 28 |
+
matches = [h['entity_id'] for h in episode['humans'] if tokens(h['events'][0]['text'])[:size] == prefix]
|
| 29 |
+
if matches == [source['entity_id']]:
|
| 30 |
+
result.append(dict(wake_phrase=' '.join(prefix), word_count=size))
|
| 31 |
+
return result
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def region_at(point):
|
| 35 |
+
return dict(min_xyz_m=[round(math.floor(float(v)*10)/10-.2,1) for v in point],
|
| 36 |
+
max_xyz_m=[round(math.ceil(float(v)*10)/10+.2,1) for v in point])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def region_members(episode, region):
|
| 40 |
+
lo, hi = np.array(region['min_xyz_m']), np.array(region['max_xyz_m'])
|
| 41 |
+
members = []
|
| 42 |
+
for source in episode['humans']+episode.get('playback_sources',[]):
|
| 43 |
+
point = np.array(source['initial_xyz_m'])
|
| 44 |
+
inside = bool(np.all(point >= lo) and np.all(point < hi))
|
| 45 |
+
# Every point must be at least 20 cm from the nearest region face.
|
| 46 |
+
boundary = float(np.min(np.minimum(point-lo,hi-point))) if inside else float(np.linalg.norm(np.maximum(np.maximum(lo-point,point-hi),0)))
|
| 47 |
+
if boundary < .2-1e-9:
|
| 48 |
+
return None
|
| 49 |
+
if inside and source['entity_type']=='human':
|
| 50 |
+
members.append(source['entity_id'])
|
| 51 |
+
return members
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def negative_region(episode, room, rng):
|
| 55 |
+
from dynamic_dataset.geometry import points_clear
|
| 56 |
+
width, _, depth = room['room_size_m']
|
| 57 |
+
for _ in range(5000):
|
| 58 |
+
point = [rng.uniform(-width/2+.7,width/2-.7), 1.5, rng.uniform(-depth/2+.7,depth/2-.7)]
|
| 59 |
+
if not points_clear(point, room, .35):
|
| 60 |
+
continue
|
| 61 |
+
region = region_at(point)
|
| 62 |
+
if region_members(episode, region) == []:
|
| 63 |
+
return region
|
| 64 |
+
raise ValueError('Cannot create an unambiguous empty region')
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def private_metadata(episode, group):
|
| 68 |
+
private = copy.deepcopy(episode)
|
| 69 |
+
times = [s/SR for s in grid(episode)] if episode['mode'] == 'dynamic' else [0.]
|
| 70 |
+
for entity in private['humans'] + private['robots'] + private['playback_sources']:
|
| 71 |
+
displacement = np.array(entity['displacement_m'])
|
| 72 |
+
length = float(np.linalg.norm(displacement))
|
| 73 |
+
entity.update(is_moving=length>0, movement_distance_m=length,
|
| 74 |
+
motion_direction_world=(displacement/length).tolist() if length else None,
|
| 75 |
+
peak_speed_mps=1.875*length/entity['motion_duration_s'],
|
| 76 |
+
positions_world_m=[[t]+position(entity,t).tolist() for t in times],
|
| 77 |
+
velocities_world_mps=[[t]+velocity(entity,t).tolist() for t in times])
|
| 78 |
+
entity['relative_to_robots'] = {}
|
| 79 |
+
for robot in episode['robots']:
|
| 80 |
+
if robot['entity_id'] == entity['entity_id']:
|
| 81 |
+
entity['relative_to_robots'][robot['entity_id']] = dict(same_entity=True)
|
| 82 |
+
else:
|
| 83 |
+
entity['relative_to_robots'][robot['entity_id']] = [dict(time_s=t,
|
| 84 |
+
relative_position_world_m=(position(entity,t)-position(robot,t)).tolist(),
|
| 85 |
+
**geometry(entity,robot,t)) for t in times]
|
| 86 |
+
private['room_acoustic_configuration'] = dict(room_id=group['room_id'],
|
| 87 |
+
asset_hashes=group['room_assets_sha256'])
|
| 88 |
+
return private
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def queries_for(episode, group, prefixes, excluded, include_keywords=True):
|
| 92 |
+
"""Yield task, deployment, receivers, reference, query, answer, target, case."""
|
| 93 |
+
rids = [r['entity_id'] for r in episode['robots']]
|
| 94 |
+
all_views = [(v['setting'],v['receiver_ids'],v['reference_robot_id']) for v in views(episode)]
|
| 95 |
+
if episode['mode'] == 'dynamic':
|
| 96 |
+
for robot in episode['robots']:
|
| 97 |
+
yield ('DOA_TRAJECTORY','edge',[robot['entity_id']],robot['entity_id'],
|
| 98 |
+
dict(human_source_count=len(episode['humans'])),
|
| 99 |
+
dict(tracks=[dict(track_id=h['entity_id'],frames=frames(episode,h,robot,'doa_deg')) for h in episode['humans']]),
|
| 100 |
+
'all_humans',None)
|
| 101 |
+
for human in episode['humans']:
|
| 102 |
+
for robot in episode['robots']:
|
| 103 |
+
cue = next(q for q in episode['geometry_audit']['range_queries']
|
| 104 |
+
if q['source_id']==human['entity_id'] and q['receiver_id']==robot['entity_id'])
|
| 105 |
+
query = {k:v for k,v in cue.items() if k not in ['source_id','receiver_id']}
|
| 106 |
+
yield ('RANGE_TRAJECTORY','edge',[robot['entity_id']],robot['entity_id'],query,
|
| 107 |
+
dict(frames=frames(episode,human,robot,'distance_m')),human['entity_id'],None)
|
| 108 |
+
yield ('TEXT_TRAJECTORY','cloud',rids,None,dict(transcript=transcript(human)),
|
| 109 |
+
dict(frames=frames(episode,human)),human['entity_id'],None)
|
| 110 |
+
else:
|
| 111 |
+
for robot in episode['robots']:
|
| 112 |
+
rid = robot['entity_id']
|
| 113 |
+
sources = episode['humans']+[s for s in episode['playback_sources'] if s['entity_id']!=rid]
|
| 114 |
+
yield ('DOA','edge',[rid],rid,dict(source_count=len(sources)),
|
| 115 |
+
[geometry(s,robot,0.)['doa_deg'] for s in sources],'all_speech',None)
|
| 116 |
+
for human in episode['humans']:
|
| 117 |
+
cue = next(q for q in episode['geometry_audit']['range_queries']
|
| 118 |
+
if q['source_id']==human['entity_id'] and q['receiver_id']==rid)
|
| 119 |
+
g = geometry(human,robot,0.)
|
| 120 |
+
yield ('RANGE','edge',[rid],rid,dict(azimuth_sector_deg=cue['initial_sector_deg']),g['distance_m'],human['entity_id'],None)
|
| 121 |
+
yield ('TEXT_DOA','edge',[rid],rid,dict(transcript=transcript(human)),g['doa_deg'],human['entity_id'],None)
|
| 122 |
+
yield ('DOA_ASR','edge',[rid],rid,dict(doa_deg=[round(v) for v in g['doa_deg']]),transcript(human),human['entity_id'],None)
|
| 123 |
+
yield ('C1_SETLOC','cloud',rids,None,dict(human_source_count=len(episode['humans'])),
|
| 124 |
+
[h['initial_xyz_m'] for h in episode['humans']],'all_humans',None)
|
| 125 |
+
for human in episode['humans']:
|
| 126 |
+
yield ('C3_TEXTLOC','cloud',rids,None,dict(transcript=transcript(human)),human['initial_xyz_m'],human['entity_id'],None)
|
| 127 |
+
region = region_at(human['initial_xyz_m'])
|
| 128 |
+
if region_members(episode,region) == [human['entity_id']]:
|
| 129 |
+
yield ('C2_REGION_ASR','cloud',rids,None,dict(region=region),transcript(human),human['entity_id'],'unique_human')
|
| 130 |
+
else:
|
| 131 |
+
excluded.append(dict(episode_id=episode['episode_id'],task_id='C2_REGION_ASR',
|
| 132 |
+
source_id=human['entity_id'],reason='20 cm region-face guard or unique target failed'))
|
| 133 |
+
rng = np.random.default_rng(int(uid('negative-region',episode['episode_id']),16)%2**32)
|
| 134 |
+
yield ('C2_REGION_ASR','cloud',rids,None,dict(region=negative_region(episode,group['room'],rng)),'','no_match','no_match')
|
| 135 |
+
if not include_keywords:
|
| 136 |
+
return
|
| 137 |
+
keyword_queries = []
|
| 138 |
+
for index,human in enumerate(episode['humans']):
|
| 139 |
+
alternatives = keyword_alternatives(episode,human)
|
| 140 |
+
if not alternatives:
|
| 141 |
+
excluded.append(dict(episode_id=episode['episode_id'],task_id='KW_ASR',
|
| 142 |
+
source_id=human['entity_id'],reason='No unique 1/2/3-word human prefix'))
|
| 143 |
+
continue
|
| 144 |
+
desired = 1+(group['room_index']+index)%3
|
| 145 |
+
selected = min(alternatives,key=lambda a:abs(a['word_count']-desired))
|
| 146 |
+
keyword_queries.append((dict(wake_phrase=selected['wake_phrase']),
|
| 147 |
+
transcript(human),human['entity_id'],'unique_human'))
|
| 148 |
+
beginnings = [tokens(e['text']) for s in episode['humans']+episode['playback_sources'] for e in s['events']]
|
| 149 |
+
absent = next(p for p in prefixes if not any(w[:len(tokens(p))]==tokens(p) for w in beginnings))
|
| 150 |
+
keyword_queries.append((dict(wake_phrase=absent),'','no_match','no_match'))
|
| 151 |
+
robot_only = []
|
| 152 |
+
for source in episode['playback_sources']:
|
| 153 |
+
for size in [1,2,3]:
|
| 154 |
+
prefix = tokens(source['events'][0]['text'])[:size]
|
| 155 |
+
if prefix and not any(tokens(h['events'][0]['text'])[:size]==prefix for h in episode['humans']):
|
| 156 |
+
robot_only.append(' '.join(prefix))
|
| 157 |
+
if robot_only:
|
| 158 |
+
keyword_queries.append((dict(wake_phrase=robot_only[0]),'','robot_only','robot_only'))
|
| 159 |
+
for query,answer,target,case in keyword_queries:
|
| 160 |
+
for setting,observed,reference in all_views:
|
| 161 |
+
yield ('KW_ASR',setting,observed,None,query,answer,target,case)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def export(root, mode, pilot=False, indices=None):
|
| 165 |
+
root = root.resolve()
|
| 166 |
+
destination = root/mode
|
| 167 |
+
groups = [read(p) for p in sorted((root/'private/plans').glob('*.json'))]
|
| 168 |
+
if pilot:
|
| 169 |
+
groups = [g for g in groups if (destination/'reports/groups'/(g['group_id']+'.json')).exists()]
|
| 170 |
+
if indices is not None:
|
| 171 |
+
groups=[g for g in groups if g['index'] in indices]
|
| 172 |
+
prefixes = sorted({' '.join(tokens(e['text'])[:3]) for g in groups for h in g['material_inventory']
|
| 173 |
+
if h['entity_type']=='human' for e in h['events']},key=lambda p:uid('absent-prefix',p))
|
| 174 |
+
data = {k:[] for k in ['scenes','episodes','recordings','views','inputs','prompts','gold','private_episodes','pairs','excluded','physical_pairs','keyword_variants','ablation_groups']}
|
| 175 |
+
seen_halls = set()
|
| 176 |
+
rooms={r['room_id']:r for r in rows(root/'private/rooms.jsonl')}
|
| 177 |
+
for group in groups:
|
| 178 |
+
report = read(destination/'reports/groups'/(group['group_id']+'.json'))
|
| 179 |
+
if not report.get('final_normalization_applied') and not pilot:
|
| 180 |
+
raise ValueError('Cannot publish unnormalized raw mixtures')
|
| 181 |
+
recs = {(r['episode_id'],r['receiver_robot_id']):r for r in report['recordings']}
|
| 182 |
+
if group['scene_id'] not in seen_halls:
|
| 183 |
+
seen_halls.add(group['scene_id'])
|
| 184 |
+
room = group['room']
|
| 185 |
+
acoustic=rooms[group['room_id']]['acoustic_check']
|
| 186 |
+
data['scenes'].append(dict(scene_id=group['scene_id'],room_id=group['room_id'],
|
| 187 |
+
room_family_id=uid('room-family',group['room_assets_sha256']['geometry.glb']),
|
| 188 |
+
environment='exhibition_hall',room_dimensions_m=[round(v,1) for v in room['room_size_m']],
|
| 189 |
+
layout_template=room['template'],area_m2=room['area_m2'],area_bin=room['area_bin'],rt_bin=room['rt_bin'],
|
| 190 |
+
measured_midfrequency_rt60_s=acoustic['room_midfrequency_rt60_median_s'],
|
| 191 |
+
rt60_target_bin_s=acoustic['target_bin_s'],rt60_measurement_method=acoustic['method'],
|
| 192 |
+
asset_directory='public/assets/rooms/'+group['room_id'],asset_hashes=group['room_assets_sha256']))
|
| 193 |
+
for episode in group[mode+'_episodes']:
|
| 194 |
+
eid = episode['episode_id']
|
| 195 |
+
poses, played = robot_poses(episode),playback_log(episode)
|
| 196 |
+
public = dict(schema_version=VERSION,scene_id=episode['scene_id'],episode_id=eid,
|
| 197 |
+
episode_group_id=group['group_id'],condition_id=episode['condition_id'],mode=mode,
|
| 198 |
+
duration_samples=episode['duration_samples'],sample_rate_hz=SR,
|
| 199 |
+
label_step_s=.5 if mode=='dynamic' else None,scene_robot_ids=[r['entity_id'] for r in episode['robots']],
|
| 200 |
+
known_robot_poses=poses,known_robot_playback=played,strict_sync=True,own_playback_policy='ideal_own_only')
|
| 201 |
+
data['episodes'].append(public)
|
| 202 |
+
private = private_metadata(episode,group)
|
| 203 |
+
private['acoustic_measurements'] = [m for m in report['acoustic_measurements'] if m['episode_id']==eid]
|
| 204 |
+
data['private_episodes'].append(private)
|
| 205 |
+
data['recordings'].extend(r for r in report['recordings'] if r['episode_id']==eid)
|
| 206 |
+
for view in views(episode):
|
| 207 |
+
view['recording_ids'] = [recs[(eid,r)]['recording_id'] for r in view['receiver_ids']]
|
| 208 |
+
data['views'].append(view)
|
| 209 |
+
for task,setting,observed,reference,query,answer,target,case in queries_for(episode,group,prefixes,data['excluded']):
|
| 210 |
+
nonce = group['evaluation_id_nonce']
|
| 211 |
+
query_group = uid(eid,'query',task,target,query,nonce)
|
| 212 |
+
view_id = uid(eid,'view',setting,observed)
|
| 213 |
+
sid = uid(eid,view_id,task,query_group)
|
| 214 |
+
bindings = [dict(slot=i,robot_id=r,recording_id=recs[(eid,r)]['recording_id'],
|
| 215 |
+
path=recs[(eid,r)]['path'],sha256=recs[(eid,r)]['sha256']) for i,r in enumerate(observed)]
|
| 216 |
+
sample = dict(schema_version=VERSION,sample_id=sid,scene_id=episode['scene_id'],episode_id=eid,
|
| 217 |
+
episode_group_id=group['group_id'],condition_id=episode['condition_id'],view_id=view_id,
|
| 218 |
+
query_group_id=query_group,target_group_id=uid(eid,'target',target,nonce),task_id=task,
|
| 219 |
+
setting=setting,mode=mode,receiver_ids=observed,reference_robot_id=reference,
|
| 220 |
+
recording_ids=[b['recording_id'] for b in bindings],audio_bindings=bindings,
|
| 221 |
+
query=query,duration_samples=episode['duration_samples'],time_window_samples=[0,episode['duration_samples']],
|
| 222 |
+
sample_rate_hz=SR,label_step_samples=LABEL_STEP if mode=='dynamic' else None,
|
| 223 |
+
known_robot_poses=poses,known_robot_playback=played,
|
| 224 |
+
room_dimensions_m=[round(float(v),1) for v in group['room']['room_size_m']],
|
| 225 |
+
known_room=dict(room_dimensions_m=[round(v,1) for v in group['room']['room_size_m']],
|
| 226 |
+
measured_midfrequency_rt60_s=round(rooms[group['room_id']]['acoustic_check']['room_midfrequency_rt60_median_s'],3),
|
| 227 |
+
materials=[{k:m[k] for k in ['name','absorption','scattering','transmission','labels']}
|
| 228 |
+
for m in json.loads(rooms[group['room_id']]['files']['materials.json'])['materials']],
|
| 229 |
+
surfaces=[dict(name=s['name'],center_m=[round(v,1) for v in s['location']],
|
| 230 |
+
size_m=[round(v,1) for v in s['size']],material_label=s['class_']) for s in group['room']['surfaces']]),
|
| 231 |
+
prompt_template_version=VERSION+'.1')
|
| 232 |
+
g = dict(sample_id=sid,scene_id=episode['scene_id'],episode_id=eid,scene_group_id=group['group_id'],
|
| 233 |
+
episode_group_id=group['group_id'],query_group_id=query_group,target_group_id=sample['target_group_id'],
|
| 234 |
+
task_id=task,setting=setting,mode=mode,target_source_id=target,keyword_case=case,
|
| 235 |
+
branch=episode['branch'],difficulty=episode['difficulty'],room_id=group['room_id'],
|
| 236 |
+
area_bin=group['room']['area_bin'],rt_bin=group['room']['rt_bin'],
|
| 237 |
+
num_humans=len(episode['humans']),num_robots=len(episode['robots']),
|
| 238 |
+
noise_type=episode['noise']['kind'] if episode['noise']['enabled'] else 'clean',
|
| 239 |
+
noise_nominal_snr_db=episode['noise'].get('nominal_snr_db') if episode['noise']['enabled'] else None,
|
| 240 |
+
layout_template=group['room']['template'],
|
| 241 |
+
target_human_motion='moving' if any(np.any(h['displacement_m']) for h in episode['humans'] if target in ['all_humans','all_speech',h['entity_id']]) else 'stationary',
|
| 242 |
+
observed_receiver_motion='moving' if any(np.any(r['displacement_m']) for r in episode['robots'] if r['entity_id'] in observed) else 'stationary',
|
| 243 |
+
expected_times_s=[s/SR for s in grid(episode)] if mode=='dynamic' else [],output=answer)
|
| 244 |
+
if task == 'DOA':
|
| 245 |
+
g['source_roles'] = ['human']*len(episode['humans']) + ['robot']*sum(s['entity_id']!=reference for s in episode['playback_sources'])
|
| 246 |
+
data['inputs'].append(sample)
|
| 247 |
+
data['prompts'].append(dict(sample_id=sid,prompt_template_version=sample['prompt_template_version'],rendered_prompt=render(sample)))
|
| 248 |
+
data['gold'].append(g)
|
| 249 |
+
if task=='KW_ASR' and case=='unique_human':
|
| 250 |
+
human=next(h for h in episode['humans'] if h['entity_id']==target)
|
| 251 |
+
for choice in keyword_alternatives(episode,human):
|
| 252 |
+
data['keyword_variants'].append(dict(sample_id=sid,word_count=choice['word_count'],
|
| 253 |
+
query=dict(wake_phrase=choice['wake_phrase'])))
|
| 254 |
+
data['pairs'].append(dict(query_group_id=query_group,sample_id=sid,episode_id=eid,
|
| 255 |
+
setting=setting,receiver_ids=observed,target_group_id=sample['target_group_id']))
|
| 256 |
+
data['physical_pairs'].extend(group['static_dynamic_pairs'])
|
| 257 |
+
data['ablation_groups'].append(group_manifest(group,mode))
|
| 258 |
+
if not pilot and (len(data['episodes'])!=2000 or len(data['scenes'])!=100):
|
| 259 |
+
raise ValueError('Export must include 100 halls and exactly 2000 physical episodes')
|
| 260 |
+
for name in ['scenes','episodes','recordings','views','inputs','prompts','pairs','physical_pairs','keyword_variants']:
|
| 261 |
+
jsonl(destination/'public/test'/(name+'.jsonl'),data[name])
|
| 262 |
+
for name,key in [('gold','gold'),('episodes','private_episodes'),('query_exclusions','excluded')]:
|
| 263 |
+
jsonl(destination/'private/test'/(name+'.jsonl'),data[key])
|
| 264 |
+
jsonl(destination/'private/ablation_groups.jsonl',data['ablation_groups'])
|
| 265 |
+
write(destination/'public/evaluation_protocol.json',dict(schema_version=VERSION,mode=mode,
|
| 266 |
+
label_step_s=.5 if mode=='dynamic' else None,source_rir_step_s=.2,receiver_rir_step_s=.2,
|
| 267 |
+
thresholds=dict(doa_deg=20.,distance_m=.5,world_m=.5),
|
| 268 |
+
targets='Dynamic spatial tasks: humans only, robot playback is interference; static DOA also includes other robot playback.',
|
| 269 |
+
inference='Each prediction sees one sample only; do not access private truth or sibling task queries/transcripts.',
|
| 270 |
+
scoring='Fixed whole-clip track identity. Silence not scored spatially; activity/coverage reported. Missing predictions remain failures.'))
|
| 271 |
+
write(destination/'public/ablation_recipes.json',ablation_recipes())
|
| 272 |
+
with (destination/'public/test/index.jsonl').open('w') as output:
|
| 273 |
+
for sample in data['inputs']:
|
| 274 |
+
output.write(json.dumps({k:sample[k] for k in ['sample_id','episode_id','scene_id','task_id','setting','mode']},separators=(',',':'))+'\n')
|
| 275 |
+
summary = dict(schema_version=VERSION,mode=mode,halls=len(data['scenes']),physical_episodes=len(data['episodes']),
|
| 276 |
+
recordings=len(data['recordings']),edge_views=sum(v['setting']=='edge' for v in data['views']),
|
| 277 |
+
cloud_views=sum(v['setting']=='cloud' for v in data['views']),task_requests=len(data['inputs']),
|
| 278 |
+
tasks=dict(Counter(r['setting']+'/'+r['task_id'] for r in data['inputs'])),
|
| 279 |
+
label_step_s=.5 if mode=='dynamic' else None,source_rir_step_s=.2,receiver_rir_step_s=.2,
|
| 280 |
+
ambiguous_queries_excluded=len(data['excluded']),binaural_recordings=0,pilot=pilot)
|
| 281 |
+
write(destination/'summary.json',summary)
|
| 282 |
+
print('EXPORT COMPLETE',mode,summary['physical_episodes'],'episodes',summary['task_requests'],'questions',flush=True)
|
| 283 |
+
return summary
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == '__main__':
|
| 287 |
+
parser=argparse.ArgumentParser()
|
| 288 |
+
parser.add_argument('--root',type=Path,required=True)
|
| 289 |
+
parser.add_argument('--mode',choices=['static','dynamic'],required=True)
|
| 290 |
+
parser.add_argument('--pilot',action='store_true')
|
| 291 |
+
parser.add_argument('--indices',type=int,nargs='*')
|
| 292 |
+
a=parser.parse_args()
|
| 293 |
+
export(a.root,a.mode,a.pilot,a.indices)
|
code/exhibition_dataset/finalize.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Joint normalization, independent full acceptance and frozen reproduction recipes."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from collections import Counter,defaultdict
|
| 6 |
+
import copy
|
| 7 |
+
import gzip
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import time
|
| 12 |
+
import sys
|
| 13 |
+
import importlib.metadata
|
| 14 |
+
import subprocess
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import soundfile as sf
|
| 18 |
+
|
| 19 |
+
from .common import *
|
| 20 |
+
from .export import export,keyword_alternatives,region_members
|
| 21 |
+
from .loader import build_index,Dataset
|
| 22 |
+
from .plan import audit_geometry
|
| 23 |
+
from .prompts import render
|
| 24 |
+
from .score import evaluate
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def normalize_family(root,group):
|
| 28 |
+
journal_path=root/'private/normalization'/(group['group_id']+'.json')
|
| 29 |
+
reports={mode:read(root/mode/'reports/groups'/(group['group_id']+'.json')) for mode in ['static','dynamic']}
|
| 30 |
+
gain=.9/max(r['raw_peak'] for r in reports.values())
|
| 31 |
+
journal=read(journal_path) if journal_path.exists() else dict(gain=gain,recordings={})
|
| 32 |
+
if journal['gain']!=gain:
|
| 33 |
+
raise ValueError('Joint family normalization gain changed')
|
| 34 |
+
for mode,report in reports.items():
|
| 35 |
+
for recording in report['recordings']:
|
| 36 |
+
key=mode+'/'+recording['recording_id']
|
| 37 |
+
path=root/mode/recording['path']
|
| 38 |
+
current=sha(path)
|
| 39 |
+
previous=journal['recordings'].get(key)
|
| 40 |
+
if previous and current in [previous['normalized_sha256'],previous.get('previous_normalized_sha256')]:
|
| 41 |
+
# Earlier pilot normalization used a timestamped PEAK header.
|
| 42 |
+
# Canonicalizing an already-normalized file never scales again.
|
| 43 |
+
wave,rate=sf.read(path,dtype='float32')
|
| 44 |
+
temporary=path.with_suffix('.normalized.tmp.wav')
|
| 45 |
+
write_float_wav(temporary,wave,rate)
|
| 46 |
+
target_hash=sha(temporary)
|
| 47 |
+
if target_hash!=current:
|
| 48 |
+
previous['previous_normalized_sha256']=current
|
| 49 |
+
previous['normalized_sha256']=target_hash
|
| 50 |
+
write(journal_path,journal)
|
| 51 |
+
temporary.replace(path)
|
| 52 |
+
else:
|
| 53 |
+
temporary.unlink()
|
| 54 |
+
recording.update(sha256=target_hash,common_final_gain=gain)
|
| 55 |
+
continue
|
| 56 |
+
if previous and current!=previous['raw_sha256']:
|
| 57 |
+
raise ValueError('Normalization encountered an unexpected audio checksum')
|
| 58 |
+
if not previous and report.get('final_normalization_applied'):
|
| 59 |
+
if current!=recording['sha256']:
|
| 60 |
+
raise ValueError('Normalized recording changed')
|
| 61 |
+
continue
|
| 62 |
+
raw_hash=current
|
| 63 |
+
wave,rate=sf.read(path,dtype='float32')
|
| 64 |
+
wave=(wave*gain).astype(np.float32)
|
| 65 |
+
if not np.isfinite(wave).all() or float(np.max(np.abs(wave)))>.900001:
|
| 66 |
+
raise ValueError('Joint normalization overflow')
|
| 67 |
+
temporary=path.with_suffix('.normalized.tmp.wav')
|
| 68 |
+
write_float_wav(temporary,wave,rate)
|
| 69 |
+
target_hash=sha(temporary)
|
| 70 |
+
journal['recordings'][key]=dict(raw_sha256=raw_hash,normalized_sha256=target_hash)
|
| 71 |
+
write(journal_path,journal) # recovery knows both hashes BEFORE replacement
|
| 72 |
+
temporary.replace(path)
|
| 73 |
+
recording.update(sha256=target_hash,common_final_gain=gain)
|
| 74 |
+
if not report.get('acoustic_power_normalization_applied'):
|
| 75 |
+
for measurement in report['acoustic_measurements']:
|
| 76 |
+
for key in ['target_power','competing_speech_power','environmental_noise_power']:
|
| 77 |
+
measurement['raw_'+key]=measurement[key]
|
| 78 |
+
measurement[key]*=gain**2
|
| 79 |
+
measurement['power_stage']='published FOA after joint family normalization'
|
| 80 |
+
report['acoustic_power_normalization_applied']=True
|
| 81 |
+
report.update(final_normalization_applied=True,common_final_gain=gain)
|
| 82 |
+
write(root/mode/'reports/groups'/(group['group_id']+'.json'),report)
|
| 83 |
+
journal['complete']=True
|
| 84 |
+
write(journal_path,journal)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def scoring_selftest(destination):
|
| 88 |
+
gold=list(rows(destination/'private/test/gold.jsonl'))
|
| 89 |
+
oracle=destination/'reports/scorer_selftest/oracle.jsonl'
|
| 90 |
+
jsonl(oracle,[dict(sample_id=g['sample_id'],output=g['output']) for g in gold])
|
| 91 |
+
result=evaluate(destination,oracle,destination/'reports/scorer_selftest/perfect')
|
| 92 |
+
for key,values in result['metrics'].items():
|
| 93 |
+
if '/branch/' in key or '/robots/' in key or '/humans/' in key or '/rt_bin/' in key or '/case/' in key:
|
| 94 |
+
continue
|
| 95 |
+
if values['format_valid_fraction']!=1.:
|
| 96 |
+
raise ValueError('Scorer rejects its own canonical answers: '+key)
|
| 97 |
+
if 'corpus_wer' in values:
|
| 98 |
+
if values['corpus_wer'] not in [0.,None] or values['negative_empty_accuracy'] not in [1.,None]:
|
| 99 |
+
raise ValueError('ASR oracle score is not perfect')
|
| 100 |
+
else:
|
| 101 |
+
if values['coverage']!=1. or values['mean_error'] is None or values['mean_error']>1e-5:
|
| 102 |
+
raise ValueError('Spatial oracle score is not perfect')
|
| 103 |
+
missing=destination/'reports/scorer_selftest/missing.jsonl'
|
| 104 |
+
jsonl(missing,[])
|
| 105 |
+
failures=evaluate(destination,missing,destination/'reports/scorer_selftest/missing')
|
| 106 |
+
if failures['samples']!=len(gold) or failures['missing_predictions']!=len(gold):
|
| 107 |
+
raise ValueError('Missing predictions escaped the denominator')
|
| 108 |
+
write(destination/'reports/scorer_selftest/complete.json',dict(passed=True,oracle_predictions_are_not_model_inference=True,
|
| 109 |
+
perfect_answer_samples=len(gold),all_missing_samples_counted=len(gold)))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def audit(root,mode,pilot=False):
|
| 113 |
+
destination=root/mode
|
| 114 |
+
episodes=list(rows(destination/'private/test/episodes.jsonl'))
|
| 115 |
+
public={e['episode_id']:e for e in rows(destination/'public/test/episodes.jsonl')}
|
| 116 |
+
inputs=list(rows(destination/'public/test/inputs.jsonl'))
|
| 117 |
+
prompts={r['sample_id']:r for r in rows(destination/'public/test/prompts.jsonl')}
|
| 118 |
+
gold={r['sample_id']:r for r in rows(destination/'private/test/gold.jsonl')}
|
| 119 |
+
recordings={r['recording_id']:r for r in rows(destination/'public/test/recordings.jsonl')}
|
| 120 |
+
view_rows=list(rows(destination/'public/test/views.jsonl'))
|
| 121 |
+
byepisode={e['episode_id']:e for e in episodes}
|
| 122 |
+
bygroup={g['group_id']:g for g in rows(root/'private/recipes.jsonl')} if (root/'private/recipes.jsonl').exists() else {
|
| 123 |
+
read(p)['group_id']:read(p) for p in (root/'private/plans').glob('*.json')}
|
| 124 |
+
if len(inputs)!=len({s['sample_id'] for s in inputs}) or set(prompts)!=set(gold) or len(gold)!=len(inputs):
|
| 125 |
+
raise ValueError('Sample, prompt and answer identities differ')
|
| 126 |
+
if not pilot and (len(episodes)!=2000 or len({e['scene_id'] for e in episodes})!=100):
|
| 127 |
+
raise ValueError('Wrong final physical/hall count')
|
| 128 |
+
hall_counts=Counter(e['scene_id'] for e in episodes)
|
| 129 |
+
if not pilot and set(hall_counts.values())!={20}:
|
| 130 |
+
raise ValueError('A hall does not contain exactly 20 episodes')
|
| 131 |
+
for episode in episodes:
|
| 132 |
+
group=bygroup[episode['episode_group_id']]
|
| 133 |
+
if audit_geometry(episode,group['room'],episode['family_type']=='count') is None:
|
| 134 |
+
raise ValueError('Geometry or range ambiguity audit failed')
|
| 135 |
+
expected=list(views(episode))
|
| 136 |
+
actual=[v for v in view_rows if v['episode_id']==episode['episode_id']]
|
| 137 |
+
if len(actual)!=len(expected) or {(v['setting'],tuple(v['receiver_ids'])) for v in actual}!={(v['setting'],tuple(v['receiver_ids'])) for v in expected}:
|
| 138 |
+
raise ValueError('Incorrect single-receiver/full-cloud views')
|
| 139 |
+
for human in episode['humans']:
|
| 140 |
+
event=human['events'][0]
|
| 141 |
+
if event['end_sample']>episode['duration_samples']-round(2.25*SR):
|
| 142 |
+
raise ValueError('Insufficient human reverberation tail budget')
|
| 143 |
+
if human['source_quality']['maximum_internal_silence_s']>.35:
|
| 144 |
+
raise ValueError('Discontinuous target speech')
|
| 145 |
+
for source in episode['playback_sources']:
|
| 146 |
+
robot=next(r for r in episode['robots'] if r['entity_id']==source['entity_id'])
|
| 147 |
+
if source['entity_id']=='R01':
|
| 148 |
+
raise ValueError('R01 playback role changed')
|
| 149 |
+
if any(source[k]!=robot[k] for k in ['initial_xyz_m','displacement_m','motion_start_s','motion_duration_s','yaw_deg']):
|
| 150 |
+
raise ValueError('Playback did not follow its robot')
|
| 151 |
+
for recording in recordings.values():
|
| 152 |
+
path=destination/recording['path']
|
| 153 |
+
if sha(path)!=recording['sha256']:
|
| 154 |
+
raise ValueError('Published FOA checksum mismatch')
|
| 155 |
+
wave,rate=sf.read(path,dtype='float32')
|
| 156 |
+
if wave.shape!=(recording['num_samples'],4) or rate!=SR or not np.isfinite(wave).all() or float(np.max(np.abs(wave)))>.900001:
|
| 157 |
+
raise ValueError('Invalid published FOA shape/amplitude')
|
| 158 |
+
for sample in inputs:
|
| 159 |
+
g=gold[sample['sample_id']]
|
| 160 |
+
episode=byepisode[sample['episode_id']]
|
| 161 |
+
if sample['mode']!=mode or sample['scene_id']!=episode['scene_id']:
|
| 162 |
+
raise ValueError('Hall/episode/mode identity mismatch')
|
| 163 |
+
if sample['setting']=='cloud' and sample['receiver_ids']!=[r['entity_id'] for r in episode['robots']]:
|
| 164 |
+
raise ValueError('Cloud does not contain all robots')
|
| 165 |
+
for binding in sample['audio_bindings']:
|
| 166 |
+
record=recordings[binding['recording_id']]
|
| 167 |
+
if binding['path']!=record['path'] or binding['sha256']!=record['sha256'] or record['episode_id']!=sample['episode_id']:
|
| 168 |
+
raise ValueError('Question bound to the wrong receiver recording')
|
| 169 |
+
if prompts[sample['sample_id']]['rendered_prompt']!=render(sample):
|
| 170 |
+
raise ValueError('Prompt does not match public metadata')
|
| 171 |
+
if mode=='dynamic' and g['expected_times_s']!=[s/SR for s in grid(episode)]:
|
| 172 |
+
raise ValueError('Dynamic answer has an incorrect 0.5-second grid')
|
| 173 |
+
if sample['task_id']=='KW_ASR':
|
| 174 |
+
phrase=tokens(sample['query']['wake_phrase'])
|
| 175 |
+
hits=[h for h in episode['humans'] if tokens(h['events'][0]['text'])[:len(phrase)]==phrase]
|
| 176 |
+
if len(hits)>1:
|
| 177 |
+
raise ValueError('Multi-human wake prefix was generated')
|
| 178 |
+
expected=' '.join(e['text'] for e in hits[0]['events']) if hits else ''
|
| 179 |
+
if g['output']!=expected:
|
| 180 |
+
raise ValueError('Wake-prefix target or full transcription mismatch')
|
| 181 |
+
if sample['task_id']=='C2_REGION_ASR':
|
| 182 |
+
members=region_members(episode,sample['query']['region'])
|
| 183 |
+
if members is None or len(members)>1 or (g['output']=='' and members):
|
| 184 |
+
raise ValueError('Region boundary or target ambiguity')
|
| 185 |
+
expected=next((' '.join(e['text'] for e in h['events']) for h in episode['humans'] if h['entity_id'] in members),'')
|
| 186 |
+
if g['output']!=expected:
|
| 187 |
+
raise ValueError('Region transcription does not match its human target')
|
| 188 |
+
task=sample['task_id']
|
| 189 |
+
target=next((h for h in episode['humans'] if h['entity_id']==g['target_source_id']),None)
|
| 190 |
+
receiver=next((r for r in episode['robots'] if r['entity_id']==sample['reference_robot_id']),None)
|
| 191 |
+
if task=='DOA_TRAJECTORY':
|
| 192 |
+
expected=dict(tracks=[dict(track_id=h['entity_id'],frames=frames(episode,h,receiver,'doa_deg')) for h in episode['humans']])
|
| 193 |
+
elif task in ['RANGE_TRAJECTORY','TEXT_TRAJECTORY']:
|
| 194 |
+
expected=dict(frames=frames(episode,target,receiver,'distance_m') if task=='RANGE_TRAJECTORY' else frames(episode,target))
|
| 195 |
+
elif task=='DOA':
|
| 196 |
+
sources=episode['humans']+[s for s in episode['playback_sources'] if s['entity_id']!=sample['reference_robot_id']]
|
| 197 |
+
expected=[geometry(s,receiver,0.)['doa_deg'] for s in sources]
|
| 198 |
+
elif task in ['RANGE','TEXT_DOA']:
|
| 199 |
+
expected=geometry(target,receiver,0.)['distance_m' if task=='RANGE' else 'doa_deg']
|
| 200 |
+
elif task=='C1_SETLOC':
|
| 201 |
+
expected=[h['initial_xyz_m'] for h in episode['humans']]
|
| 202 |
+
elif task=='C3_TEXTLOC':
|
| 203 |
+
expected=target['initial_xyz_m']
|
| 204 |
+
elif task=='DOA_ASR':
|
| 205 |
+
expected=' '.join(e['text'] for e in target['events'])
|
| 206 |
+
else:
|
| 207 |
+
expected=g['output']
|
| 208 |
+
if g['output']!=expected:
|
| 209 |
+
raise ValueError('Speaker/receiver geometry or task reference mismatch')
|
| 210 |
+
# Common count variants really reuse the same single-receiver audio, not
|
| 211 |
+
# just similar recipes. All robot playback is disabled in this family.
|
| 212 |
+
count_groups=defaultdict(list)
|
| 213 |
+
for episode in episodes:
|
| 214 |
+
if episode['family_type']=='count':
|
| 215 |
+
count_groups[(episode['episode_group_id'],len(episode['humans']))].append(episode)
|
| 216 |
+
for related in count_groups.values():
|
| 217 |
+
for rid in ['R01','R02']:
|
| 218 |
+
selected=[e for e in related if rid in [r['entity_id'] for r in e['robots']]]
|
| 219 |
+
hashes={next(r['sha256'] for r in recordings.values() if r['episode_id']==e['episode_id'] and r['receiver_robot_id']==rid) for e in selected}
|
| 220 |
+
if len(hashes)>1:
|
| 221 |
+
raise ValueError('Robot-count control changed a common recording')
|
| 222 |
+
report=dict(passed=True,halls=len(hall_counts),physical_episodes=len(episodes),questions=len(inputs),
|
| 223 |
+
recordings=len(recordings),views=len(view_rows),label_step_s=.5 if mode=='dynamic' else None,
|
| 224 |
+
exact_count_audio_correspondence=True,human_listening_audit_completed=False,model_inference_performed=False)
|
| 225 |
+
write(destination/'reports/acceptance.json',report)
|
| 226 |
+
return report
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def finalize(root):
|
| 230 |
+
from dynamic_dataset.runtime import ensure_compute
|
| 231 |
+
ensure_compute()
|
| 232 |
+
root=Path(root).resolve()
|
| 233 |
+
groups=list(rows(root/'private/recipes.jsonl'))
|
| 234 |
+
if not read(root/'reports/preflight.complete.json')['passed']:
|
| 235 |
+
raise ValueError('Full recipe/task preflight must pass before release')
|
| 236 |
+
if len(groups)!=300:
|
| 237 |
+
raise ValueError('Incomplete 100-hall plan')
|
| 238 |
+
for mode in ['static','dynamic']:
|
| 239 |
+
completed=read(root/mode/'reports/render.complete.json')
|
| 240 |
+
if not completed['passed'] or completed['groups']!=300:
|
| 241 |
+
raise ValueError('Cannot freeze incomplete rendering')
|
| 242 |
+
for index,group in enumerate(groups):
|
| 243 |
+
normalize_family(root,group)
|
| 244 |
+
if index%20==0:
|
| 245 |
+
print('JOINT NORMALIZATION',index,'/ 300',flush=True)
|
| 246 |
+
acceptance={}
|
| 247 |
+
for mode in ['static','dynamic']:
|
| 248 |
+
destination=root/mode
|
| 249 |
+
for name,target in [('assets/rooms',root/'shared/rooms'),('assets/noise',root/'shared/noise')]:
|
| 250 |
+
link=destination/'public'/name
|
| 251 |
+
link.parent.mkdir(parents=True,exist_ok=True)
|
| 252 |
+
if not link.exists():
|
| 253 |
+
link.symlink_to(target,target_is_directory=True)
|
| 254 |
+
export(root,mode)
|
| 255 |
+
build_index(destination)
|
| 256 |
+
acceptance[mode]=audit(root,mode)
|
| 257 |
+
scoring_selftest(destination)
|
| 258 |
+
recipes=root/'private/reproduction/recipes.jsonl.gz'
|
| 259 |
+
recipes.parent.mkdir(parents=True,exist_ok=True)
|
| 260 |
+
with gzip.open(recipes,'wt') as stream:
|
| 261 |
+
for group in groups:
|
| 262 |
+
stream.write(json.dumps(group,separators=(',',':'),allow_nan=False)+'\n')
|
| 263 |
+
native=Path(__file__).parent.parent/'dynamic_demo/render.py'
|
| 264 |
+
repo=Path(__file__).parent.parent
|
| 265 |
+
dependencies=['dynamic_dataset/common.py','dynamic_dataset/prepare.py','dynamic_dataset/frame_score.py',
|
| 266 |
+
'dynamic_dataset/score.py','dynamic_demo/common.py','dynamic_demo/render.py',
|
| 267 |
+
'generation/native/build_static_v1_scene.py']
|
| 268 |
+
try:
|
| 269 |
+
revision=subprocess.check_output(['git','rev-parse','HEAD'],cwd=repo,text=True).strip()
|
| 270 |
+
except (OSError,subprocess.CalledProcessError):
|
| 271 |
+
revision=None
|
| 272 |
+
environment=dict(python=sys.version,packages={name:importlib.metadata.version(name) for name in
|
| 273 |
+
['numpy','scipy','soundfile','numpy-quaternion']},
|
| 274 |
+
native_protocol=read(Path(__file__).parent.parent/'generation/configs/native_environment.json'))
|
| 275 |
+
write(root/'provenance/environment.json',environment)
|
| 276 |
+
from .sources import SILERO_REVISION,SILERO_SHA256,ESC_REVISION
|
| 277 |
+
lock=dict(schema_version=VERSION,config=read(root/'config.json'),code_sha256=code_hashes(),
|
| 278 |
+
repository_revision=revision,shared_dependency_sha256={name:sha(repo/name) for name in dependencies},
|
| 279 |
+
native_renderer_sha256=sha(native),recipes_sha256=sha(recipes),
|
| 280 |
+
room_manifest_sha256=sha(root/'private/rooms.jsonl'),noise_manifest_sha256=sha(root/'shared/noise/catalog.jsonl'),
|
| 281 |
+
environment=environment,noise_source_revision=ESC_REVISION,
|
| 282 |
+
speech_screening_model_revision=SILERO_REVISION,speech_screening_model_sha256=SILERO_SHA256)
|
| 283 |
+
write(root/'reproduction.lock.json',lock)
|
| 284 |
+
import shutil
|
| 285 |
+
shutil.copyfile(Path(__file__).parent/'README.zh.md',root/'README.zh.md')
|
| 286 |
+
snapshot=root/'private/reproduction/code'
|
| 287 |
+
snapshot.mkdir(parents=True,exist_ok=True)
|
| 288 |
+
for path in Path(__file__).parent.iterdir():
|
| 289 |
+
if path.suffix in ['.py','.sh','.md','.txt']:
|
| 290 |
+
shutil.copyfile(path,snapshot/path.name)
|
| 291 |
+
for mode in ['static','dynamic']:
|
| 292 |
+
write(root/mode/'release.complete.json',dict(passed=True,mode=mode,halls=100,physical_episodes=2000,
|
| 293 |
+
label_step_s=.5 if mode=='dynamic' else None,source_rir_step_s=.2,receiver_rir_step_s=.2,
|
| 294 |
+
acceptance=acceptance[mode],scorer_selftest_passed=True))
|
| 295 |
+
write(root/'release.complete.json',dict(passed=True,halls=100,static_physical_episodes=2000,dynamic_physical_episodes=2000,
|
| 296 |
+
acceptance=acceptance,label_step_s=.5,source_rir_step_s=.2,receiver_rir_step_s=.2,
|
| 297 |
+
code_sha256=code_hashes(),model_inference_performed=False,human_listening_audit_completed=False))
|
| 298 |
+
print('RELEASE COMPLETE: 2000 STATIC + 2000 DYNAMIC',flush=True)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
if __name__=='__main__':
|
| 302 |
+
parser=argparse.ArgumentParser()
|
| 303 |
+
parser.add_argument('--root',type=Path,required=True)
|
| 304 |
+
finalize(parser.parse_args().root)
|
code/exhibition_dataset/kernel_geometry.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Keep native two-time source/receiver combinations outside the near singularity.
|
| 2 |
+
|
| 3 |
+
This is distinct from same-time body collision checking. The frozen RIR
|
| 4 |
+
approximation evaluates emission and reception positions at different knots.
|
| 5 |
+
Only combinations needed by the finite convolution horizon are inspected.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from .common import SR,position,rir_nodes
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def minimum_kernel_separation(episode,ir_time_s=2.5):
|
| 15 |
+
minimum=float('inf')
|
| 16 |
+
detail=None
|
| 17 |
+
for source in episode['humans']+episode['playback_sources']:
|
| 18 |
+
sn=rir_nodes(source)
|
| 19 |
+
for i,te in enumerate(sn):
|
| 20 |
+
support_lo=sn[i-1] if i else 0.
|
| 21 |
+
support_hi=sn[i+1] if i+1<len(sn) else episode['duration_samples']/SR
|
| 22 |
+
spans=[(max(support_lo,e['start_sample']/SR),min(support_hi,e['end_sample']/SR)) for e in source['events']]
|
| 23 |
+
spans=[(a,b) for a,b in spans if b>a]
|
| 24 |
+
if not spans:
|
| 25 |
+
continue
|
| 26 |
+
for receiver in episode['robots']:
|
| 27 |
+
if source['entity_id']==receiver['entity_id']:
|
| 28 |
+
continue
|
| 29 |
+
rn=rir_nodes(receiver)
|
| 30 |
+
for j,tr in enumerate(rn):
|
| 31 |
+
left=rn[j-1] if j else 0.
|
| 32 |
+
right=rn[j+1] if j+1<len(rn) else episode['duration_samples']/SR
|
| 33 |
+
if not any(right>a and left<b+ir_time_s+.001 for a,b in spans):
|
| 34 |
+
continue
|
| 35 |
+
distance=float(np.linalg.norm(position(source,te)-position(receiver,tr)))
|
| 36 |
+
if distance<minimum:
|
| 37 |
+
minimum=distance
|
| 38 |
+
detail=dict(source_id=source['entity_id'],receiver_id=receiver['entity_id'],
|
| 39 |
+
emission_knot_s=te,reception_knot_s=tr,distance_m=distance)
|
| 40 |
+
return minimum,detail
|
code/exhibition_dataset/loader.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Blind single-question loading and concrete input-information ablations."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import importlib
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import soundfile as sf
|
| 10 |
+
|
| 11 |
+
from .common import read,rows,jsonl,sha
|
| 12 |
+
from .prompts import render,ablation_recipes
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def build_index(root):
|
| 16 |
+
root=Path(root)
|
| 17 |
+
offsets={}
|
| 18 |
+
for kind in ['inputs','prompts']:
|
| 19 |
+
with (root/'public/test'/f'{kind}.jsonl').open('rb') as stream:
|
| 20 |
+
while True:
|
| 21 |
+
offset=stream.tell()
|
| 22 |
+
line=stream.readline()
|
| 23 |
+
if not line:
|
| 24 |
+
break
|
| 25 |
+
row=json.loads(line)
|
| 26 |
+
sid=row['sample_id']
|
| 27 |
+
offsets.setdefault(sid,{})[kind+'_offset']=offset
|
| 28 |
+
if kind=='inputs':
|
| 29 |
+
offsets[sid].update({k:row[k] for k in ['sample_id','episode_id','scene_id','task_id','setting','mode']})
|
| 30 |
+
if any('inputs_offset' not in r or 'prompts_offset' not in r for r in offsets.values()):
|
| 31 |
+
raise ValueError('Input/prompt inventory mismatch')
|
| 32 |
+
jsonl(root/'public/test/index.jsonl',offsets.values())
|
| 33 |
+
return len(offsets)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Dataset:
|
| 37 |
+
def __init__(self,root,allow_pilot=False):
|
| 38 |
+
self.root=Path(root)
|
| 39 |
+
receipt=self.root/'release.complete.json'
|
| 40 |
+
if not allow_pilot and (not receipt.exists() or read(receipt).get('passed') is not True):
|
| 41 |
+
raise ValueError('Dataset acceptance is incomplete; --allow-pilot is only for explicit pilot checks')
|
| 42 |
+
self.index={r['sample_id']:r for r in rows(self.root/'public/test/index.jsonl')}
|
| 43 |
+
self.contexts={r['id']:r for r in ablation_recipes()['input_context']}
|
| 44 |
+
def ids(self):
|
| 45 |
+
return sorted(self.index)
|
| 46 |
+
def _read(self,kind,sid):
|
| 47 |
+
with (self.root/'public/test'/f'{kind}.jsonl').open('rb') as stream:
|
| 48 |
+
stream.seek(self.index[sid][kind+'_offset'])
|
| 49 |
+
return json.loads(stream.readline())
|
| 50 |
+
def load(self,sid,context='full',audio=True):
|
| 51 |
+
sample=self._read('inputs',sid)
|
| 52 |
+
configuration=self.contexts[context]
|
| 53 |
+
prompt_renderer=render
|
| 54 |
+
if sample.get('task_protocol_version')=='dish_exhibition_v3.tasks.2':
|
| 55 |
+
from exhibition_v3.prompts import render as prompt_renderer
|
| 56 |
+
# No raw dataset row, sibling questions, source IDs or private labels are
|
| 57 |
+
# sent to the model adapter. Context ablations remove structured fields
|
| 58 |
+
# as well as removing them from the rendered prompt.
|
| 59 |
+
poses=[p for p in sample['known_robot_poses'] if configuration['peer_poses'] or p['robot_id'] in sample['receiver_ids']]
|
| 60 |
+
playback=[]
|
| 61 |
+
if configuration['playback_times'] or configuration['playback_text']:
|
| 62 |
+
for event in sample['known_robot_playback']:
|
| 63 |
+
public=dict(robot_id=event['robot_id'])
|
| 64 |
+
if configuration['playback_times']:
|
| 65 |
+
public.update(start_time_s=event['start_time_s'],end_time_s=event['end_time_s'])
|
| 66 |
+
if configuration['playback_text']:
|
| 67 |
+
public['text']=event['text']
|
| 68 |
+
playback.append(public)
|
| 69 |
+
model_input=dict(sample_id=sid,task_id=sample['task_id'],setting=sample['setting'],mode=sample['mode'],
|
| 70 |
+
receiver_ids=sample['receiver_ids'],reference_robot_id=sample['reference_robot_id'],
|
| 71 |
+
duration_samples=sample['duration_samples'],sample_rate_hz=16000,
|
| 72 |
+
label_step_s=.5 if sample['mode']=='dynamic' else None,query=sample['query'],
|
| 73 |
+
robot_poses=poses,robot_playback=playback,prompt=prompt_renderer(sample,configuration),
|
| 74 |
+
audio_bindings=sample['audio_bindings'])
|
| 75 |
+
if configuration['room']=='dimensions':
|
| 76 |
+
model_input['room_dimensions_m']=sample['room_dimensions_m']
|
| 77 |
+
elif configuration['room']=='layout':
|
| 78 |
+
model_input['room_configuration']=sample['known_room']
|
| 79 |
+
if audio:
|
| 80 |
+
waveforms=[]
|
| 81 |
+
for binding in sample['audio_bindings']:
|
| 82 |
+
path=self.root/binding['path']
|
| 83 |
+
if sha(path)!=binding['sha256']:
|
| 84 |
+
raise ValueError('Model audio checksum mismatch')
|
| 85 |
+
wave,rate=sf.read(path,dtype='float32')
|
| 86 |
+
if rate!=16000 or wave.shape!=(sample['duration_samples'],4):
|
| 87 |
+
raise ValueError('Invalid model audio shape')
|
| 88 |
+
waveforms.append(wave)
|
| 89 |
+
model_input['audio']=waveforms
|
| 90 |
+
return model_input
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def run(root,adapter,output,task=None,setting=None,context='full',limit=0,shard=0,shards=1,allow_pilot=False):
|
| 94 |
+
dataset=Dataset(root,allow_pilot=allow_pilot)
|
| 95 |
+
module,name=adapter.split(':',1)
|
| 96 |
+
predict=getattr(importlib.import_module(module),name)
|
| 97 |
+
output=Path(output)
|
| 98 |
+
output.parent.mkdir(parents=True,exist_ok=True)
|
| 99 |
+
completed={r['sample_id'] for r in rows(output)} if output.exists() else set()
|
| 100 |
+
count=0
|
| 101 |
+
with output.open('a') as stream:
|
| 102 |
+
for index,sid in enumerate(dataset.ids()):
|
| 103 |
+
row=dataset.index[sid]
|
| 104 |
+
if index%shards!=shard or sid in completed or (task and row['task_id']!=task) or (setting and row['setting']!=setting):
|
| 105 |
+
continue
|
| 106 |
+
prediction=predict(dataset.load(sid,context))
|
| 107 |
+
stream.write(json.dumps(dict(sample_id=sid,output=prediction),allow_nan=False)+'\n')
|
| 108 |
+
stream.flush()
|
| 109 |
+
count+=1
|
| 110 |
+
if limit and count>=limit:
|
| 111 |
+
break
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__=='__main__':
|
| 115 |
+
parser=argparse.ArgumentParser()
|
| 116 |
+
parser.add_argument('--root',type=Path,required=True)
|
| 117 |
+
parser.add_argument('--adapter',required=True)
|
| 118 |
+
parser.add_argument('--output',type=Path,required=True)
|
| 119 |
+
parser.add_argument('--task')
|
| 120 |
+
parser.add_argument('--setting',choices=['edge','cloud'])
|
| 121 |
+
parser.add_argument('--context',default='full')
|
| 122 |
+
parser.add_argument('--limit',type=int,default=0)
|
| 123 |
+
parser.add_argument('--shard',type=int,default=0)
|
| 124 |
+
parser.add_argument('--shards',type=int,default=1)
|
| 125 |
+
parser.add_argument('--allow-pilot',action='store_true',help='Allow an unfinished pilot dataset for a smoke check')
|
| 126 |
+
a=parser.parse_args()
|
| 127 |
+
run(a.root,a.adapter,a.output,a.task,a.setting,a.context,a.limit,a.shard,a.shards,a.allow_pilot)
|
code/exhibition_dataset/noise.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproducible, non-speech noise sources with explicit synthetic provenance.
|
| 2 |
+
|
| 3 |
+
These are acoustic interference conditions, never sound-event targets. Each
|
| 4 |
+
noise waveform/location is shared across all receivers and paired variants.
|
| 5 |
+
They are not advertised as measured HVAC or anechoic recordings.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from scipy.signal import butter, sosfilt
|
| 11 |
+
from .common import SR
|
| 12 |
+
|
| 13 |
+
KINDS = ['ventilation', 'fan', 'equipment', 'keyboard']
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def waveform(spec, samples, root=None):
|
| 17 |
+
rng = np.random.default_rng(spec['seed'])
|
| 18 |
+
if spec.get('recording'):
|
| 19 |
+
import soundfile as sf
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from .common import sha
|
| 22 |
+
record = spec['recording']
|
| 23 |
+
path = Path(root)/record['audio_asset']
|
| 24 |
+
if sha(path) != record['sha256']:
|
| 25 |
+
raise ValueError('Real noise asset checksum changed')
|
| 26 |
+
wave, rate = sf.read(path, dtype='float32')
|
| 27 |
+
if rate != SR or wave.ndim != 1:
|
| 28 |
+
raise ValueError('Prepared noise is not mono16k')
|
| 29 |
+
wave = np.roll(wave, int(rng.integers(len(wave))))
|
| 30 |
+
fade = min(1600, len(wave)//4)
|
| 31 |
+
result = wave.copy()
|
| 32 |
+
while len(result) < samples:
|
| 33 |
+
weights = np.linspace(0, np.pi/2, fade)
|
| 34 |
+
result[-fade:] = result[-fade:]*np.cos(weights) + wave[:fade]*np.sin(weights)
|
| 35 |
+
result = np.r_[result, wave[fade:]]
|
| 36 |
+
result = result[:samples]
|
| 37 |
+
return (result/max(float(np.sqrt(np.mean(result.astype(float)**2))), 1e-12)).astype(np.float32)
|
| 38 |
+
t = np.arange(samples) / SR
|
| 39 |
+
white = rng.normal(size=samples)
|
| 40 |
+
if spec['kind'] == 'ventilation':
|
| 41 |
+
result = sosfilt(butter(3, [50, 1500], fs=SR, btype='bandpass', output='sos'), white)
|
| 42 |
+
result += .15 * np.sin(2 * np.pi * spec['hum_hz'] * t)
|
| 43 |
+
elif spec['kind'] == 'fan':
|
| 44 |
+
result = sosfilt(butter(3, [80, 4000], fs=SR, btype='bandpass', output='sos'), white)
|
| 45 |
+
result *= .65 + .35 * np.sin(2 * np.pi * spec['modulation_hz'] * t) ** 2
|
| 46 |
+
result += .1 * np.sin(2 * np.pi * spec['hum_hz'] * t)
|
| 47 |
+
elif spec['kind'] == 'equipment':
|
| 48 |
+
result = .3 * sosfilt(butter(3, 1800, fs=SR, output='sos'), white)
|
| 49 |
+
result += sum(np.sin(2 * np.pi * spec['hum_hz'] * k * t) / k for k in range(1, 7))
|
| 50 |
+
result *= .9 + .1 * np.sin(2 * np.pi * spec['modulation_hz'] * t)
|
| 51 |
+
elif spec['kind'] == 'keyboard':
|
| 52 |
+
result = np.zeros(samples)
|
| 53 |
+
cursor = float(rng.uniform(.03, .25))
|
| 54 |
+
while cursor < samples / SR:
|
| 55 |
+
length = int(rng.integers(180, 700))
|
| 56 |
+
a = round(cursor * SR)
|
| 57 |
+
b = min(samples, a + length)
|
| 58 |
+
click = rng.normal(size=b - a) * np.exp(-np.arange(b - a) / (length / 5))
|
| 59 |
+
result[a:b] += click * rng.uniform(.4, 1.4)
|
| 60 |
+
cursor += float(rng.uniform(.08, .45))
|
| 61 |
+
result = sosfilt(butter(2, [200, 6500], fs=SR, btype='bandpass', output='sos'), result)
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError('Unknown non-speech noise recipe')
|
| 64 |
+
result = result / max(float(np.sqrt(np.mean(result ** 2))), 1e-12)
|
| 65 |
+
return result.astype(np.float32)
|
code/exhibition_dataset/plan.py
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Freeze 100 halls and 20 distinct static + 20 dynamic episodes per hall.
|
| 2 |
+
|
| 3 |
+
Per hall: nine nested robot/human-count conditions, four noise conditions,
|
| 4 |
+
seven static controls, and seven dynamic motion/speed controls. Variants share
|
| 5 |
+
source files, crops and timelines unless the declared intervention changes
|
| 6 |
+
them. An identical static recipe is never counted repeatedly for motion forks.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
from collections import Counter, defaultdict
|
| 12 |
+
import copy
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import secrets
|
| 16 |
+
import shutil
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from dynamic_dataset.prepare import SpeechPool, freeze_room
|
| 21 |
+
from dynamic_dataset.geometry import points_clear
|
| 22 |
+
from dynamic_dataset.runtime import ensure_compute
|
| 23 |
+
from dynamic_demo.render import visible
|
| 24 |
+
from .common import *
|
| 25 |
+
from .noise import KINDS
|
| 26 |
+
|
| 27 |
+
MOTIONS = ['easy_human', 'easy_robot', 'hard_joint_a', 'hard_joint_b']
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def config():
|
| 31 |
+
return dict(schema_version=VERSION, seed=20261003, hall_count=100,
|
| 32 |
+
episodes_per_hall_per_mode=20, physical_episode_count_per_mode=2000,
|
| 33 |
+
label_step_s=.5, label_step_samples=LABEL_STEP,
|
| 34 |
+
source_rir_step_s=.2, receiver_rir_step_s=.2, sample_rate_hz=SR,
|
| 35 |
+
human_counts=[1, 2, 3], robot_counts=[1, 2, 3],
|
| 36 |
+
duration_bounds_s=[7.5, 9.4], maximum_speed_mps=.8,
|
| 37 |
+
minimum_moving_displacement_m=2., entity_clearance_m=.6,
|
| 38 |
+
native_minimum_two_time_kernel_separation_m=.1,
|
| 39 |
+
wall_furniture_clearance_m=.25, region_boundary_margin_m=.2,
|
| 40 |
+
sector_boundary_margin_deg=1., target_maximum_internal_silence_s=.35,
|
| 41 |
+
motion_model='minimum-jerk horizontal translation; fixed height/yaw',
|
| 42 |
+
noise_reference_human='H01', noise_reference_robot='R01',
|
| 43 |
+
noise_reference='static R01 W-channel target-active power; one emission gain shared by all receivers and modes',
|
| 44 |
+
snr_levels_db=[20., 10., 0.], own_playback_policy='ideal_own_only',
|
| 45 |
+
playback_roles='R01 silent; R02/R03 may play speech; never rotate these roles',
|
| 46 |
+
waveform='16 kHz float32 FOA WAV, ACN/SN3D [W,Y,Z,X]',
|
| 47 |
+
views='one edge per robot plus one cloud containing every robot, including cloud with one robot',
|
| 48 |
+
scope='exhibition halls; test only; no clock errors, packet loss, binaural files or exact Doppler',
|
| 49 |
+
family_sizes=dict(count=9, noise=4, controls_static=7, controls_dynamic=7),
|
| 50 |
+
environmental_noise_material_policy='80 real-recording noise families and 20 synthetic fan families; non-speech only')
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def select_rooms(release):
|
| 54 |
+
available = [r for r in rows(release / 'rooms.jsonl.gz') if r['split'] == 'test']
|
| 55 |
+
strata = defaultdict(list)
|
| 56 |
+
for room in available:
|
| 57 |
+
strata[(room['layout']['area_bin'], room['layout']['rt_bin'])].append(room)
|
| 58 |
+
selected = []
|
| 59 |
+
for key, rooms in sorted(strata.items()):
|
| 60 |
+
rooms.sort(key=lambda r: uid('room-selection', r['room_id']))
|
| 61 |
+
selected.extend(rooms[:len(rooms) // 2])
|
| 62 |
+
if len(selected) != 100:
|
| 63 |
+
raise ValueError('Accepted room inventory does not support the declared 100-room quota')
|
| 64 |
+
return sorted(selected, key=lambda r: uid('hall-order', r['room_id']))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def source_event(pool, entity_id, excluded, start, duration, minimum, maximum, rng):
|
| 68 |
+
policy = dict(minimum_target_aligned_span_s=minimum, maximum_target_aligned_span_s=maximum,
|
| 69 |
+
tail_budget_s=2.25, target_maximum_internal_silence_s=.35)
|
| 70 |
+
event, speaker, quality = pool.select(entity_id, None, excluded, start, duration, rng, policy)
|
| 71 |
+
return event, speaker, quality
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def materials(pool, family, duration, rng):
|
| 75 |
+
humans = []
|
| 76 |
+
played = []
|
| 77 |
+
used = set()
|
| 78 |
+
for index in range(3):
|
| 79 |
+
hid = f'H{index + 1:02d}'
|
| 80 |
+
minimum, maximum = ((6.02, 6.3) if family == 'controls' else (5.6, 5.9)) if index == 0 else (3.05, 3.6)
|
| 81 |
+
start = .2 if index == 0 else .55 + .30 * (index - 1)
|
| 82 |
+
event, speaker, quality = source_event(pool, hid, used, start, duration, minimum, maximum, rng)
|
| 83 |
+
used.add(speaker)
|
| 84 |
+
humans.append(dict(entity_id=hid, entity_type='human', speaker_id=speaker, events=[event],
|
| 85 |
+
emitted_rms_dbfs=float(rng.uniform(-23, -19)), source_quality=quality))
|
| 86 |
+
for index in [2, 3]:
|
| 87 |
+
rid = f'R{index:02d}'
|
| 88 |
+
event, speaker, quality = source_event(pool, rid, used, .45 + .6 * (index - 2), duration, .5, .9, rng)
|
| 89 |
+
used.add(speaker)
|
| 90 |
+
played.append(dict(entity_id=rid, entity_type='robot', speaker_id=speaker, events=[event],
|
| 91 |
+
emitted_rms_dbfs=-25., source_quality=quality))
|
| 92 |
+
return humans, played
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def cues(episode):
|
| 96 |
+
result = []
|
| 97 |
+
for human in episode['humans']:
|
| 98 |
+
samples = [s for s in grid(episode) if active(human, s)]
|
| 99 |
+
if not samples:
|
| 100 |
+
return None
|
| 101 |
+
anchor = samples[0] / SR
|
| 102 |
+
for receiver in episode['robots']:
|
| 103 |
+
angle = geometry(human, receiver, anchor)['doa_deg'][0]
|
| 104 |
+
low = int(math.floor(angle / 30)) * 30
|
| 105 |
+
high = low + 30
|
| 106 |
+
rounded = copy.deepcopy(receiver)
|
| 107 |
+
rounded['initial_xyz_m'] = [round(float(x), 1) for x in position(receiver, anchor)]
|
| 108 |
+
rounded['displacement_m'] = [0., 0., 0.]
|
| 109 |
+
rounded_angle = geometry(human, rounded, anchor)['doa_deg'][0]
|
| 110 |
+
if not low + 1 < angle < high - 1 or not low + 1 < rounded_angle < high - 1:
|
| 111 |
+
return None
|
| 112 |
+
selected = [h['entity_id'] for h in episode['humans'] if (episode.get('mode') == 'static' or active(h, samples[0]))
|
| 113 |
+
and low <= geometry(h, receiver, anchor)['doa_deg'][0] < high]
|
| 114 |
+
if selected != [human['entity_id']]:
|
| 115 |
+
return None
|
| 116 |
+
result.append(dict(source_id=human['entity_id'], receiver_id=receiver['entity_id'],
|
| 117 |
+
selection_time_s=anchor, cue_time_range_s=[anchor, round(anchor + .2, 9)],
|
| 118 |
+
initial_sector_deg=[low, high]))
|
| 119 |
+
return result
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def audit_geometry(episode, room, require_r1_visible=False):
|
| 123 |
+
times = np.arange(0., episode['duration_samples'] / SR, .05)
|
| 124 |
+
entities = episode['humans'] + episode['robots']
|
| 125 |
+
points = [position(e, times) for e in entities]
|
| 126 |
+
minimum = math.inf
|
| 127 |
+
for entity, point in zip(entities, points):
|
| 128 |
+
if not points_clear(point, room, .25):
|
| 129 |
+
return None
|
| 130 |
+
distance = float(np.linalg.norm(entity['displacement_m']))
|
| 131 |
+
speed = 1.875 * distance / entity['motion_duration_s']
|
| 132 |
+
if distance and (distance <= 2. or speed > .80000001):
|
| 133 |
+
return None
|
| 134 |
+
if entity['motion_start_s'] + entity['motion_duration_s'] > episode['duration_samples'] / SR:
|
| 135 |
+
return None
|
| 136 |
+
for index, point in enumerate(points):
|
| 137 |
+
for other in points[index + 1:]:
|
| 138 |
+
minimum = min(minimum, float(np.linalg.norm((point - other)[:, [0, 2]], axis=1).min()))
|
| 139 |
+
if minimum < .6:
|
| 140 |
+
return None
|
| 141 |
+
if episode.get('mode')=='dynamic' and any(np.any(e['displacement_m']) for e in episode['humans']+episode['playback_sources']) and any(np.any(r['displacement_m']) for r in episode['robots']):
|
| 142 |
+
from .kernel_geometry import minimum_kernel_separation
|
| 143 |
+
# Native direct-path handling is singular inside its source radius.
|
| 144 |
+
# Same-time body clearance alone does not protect two-time RIR knots.
|
| 145 |
+
if minimum_kernel_separation(episode)[0]<.1:
|
| 146 |
+
return None
|
| 147 |
+
if episode.get('mode') == 'static':
|
| 148 |
+
for receiver in episode['robots']:
|
| 149 |
+
directions = [geometry(h, receiver, 0.)['doa_deg'] for h in episode['humans']]
|
| 150 |
+
if any(angular(a, b) < 8. for i, a in enumerate(directions) for b in directions[i+1:]):
|
| 151 |
+
return None
|
| 152 |
+
for human in episode['humans']:
|
| 153 |
+
for time in times[::2]:
|
| 154 |
+
receivers = episode['robots'][:1] if require_r1_visible else episode['robots']
|
| 155 |
+
if not any(visible(position(human, time), position(r, time), room) for r in receivers):
|
| 156 |
+
return None
|
| 157 |
+
selected = cues(episode)
|
| 158 |
+
if selected is None:
|
| 159 |
+
return None
|
| 160 |
+
return dict(minimum_horizontal_entity_clearance_m=minimum, range_queries=selected)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def base_geometry(humans, played, room, rng, duration, shared_vector=None, robot_count=3, human_count=3):
|
| 164 |
+
width, height, depth = room['room_size_m']
|
| 165 |
+
entities = []
|
| 166 |
+
for index in range(robot_count):
|
| 167 |
+
entities.append(dict(entity_id=f'R{index + 1:02d}', entity_type='robot',
|
| 168 |
+
yaw_deg=int(rng.integers(-180, 180)),
|
| 169 |
+
playback_role='silent' if index == 0 else 'may_play',
|
| 170 |
+
fixed_height_m=float(rng.uniform(1.15, 1.50))))
|
| 171 |
+
entities += [dict(h, yaw_deg=0, fixed_height_m=float(rng.uniform(1.30, 1.85))) for h in humans[:human_count]]
|
| 172 |
+
placed = []
|
| 173 |
+
for entity in entities:
|
| 174 |
+
for _ in range(1000):
|
| 175 |
+
point = np.array([rng.uniform(-width / 2 + .6, width / 2 - .6), entity['fixed_height_m'],
|
| 176 |
+
rng.uniform(-depth / 2 + .6, depth / 2 - .6)])
|
| 177 |
+
swept = point if shared_vector is None else point + np.linspace(0,1,25)[:,None]*np.asarray(shared_vector)
|
| 178 |
+
if points_clear(swept, room, .4) and all(np.linalg.norm((point - other)[[0, 2]]) > .85 for other in placed):
|
| 179 |
+
break
|
| 180 |
+
else:
|
| 181 |
+
raise ValueError('No clear entity placement')
|
| 182 |
+
entity.update(initial_xyz_m=point.tolist(), displacement_m=[0., 0., 0.],
|
| 183 |
+
motion_start_s=.25, motion_duration_s=5.5)
|
| 184 |
+
placed.append(point)
|
| 185 |
+
receivers, people = entities[:robot_count], entities[robot_count:]
|
| 186 |
+
by_id = {r['entity_id']:r for r in receivers}
|
| 187 |
+
playback = [dict(s, **{k: copy.deepcopy(by_id[s['entity_id']][k]) for k in
|
| 188 |
+
['initial_xyz_m', 'yaw_deg', 'displacement_m', 'motion_start_s', 'motion_duration_s']})
|
| 189 |
+
for s in played if s['entity_id'] in by_id]
|
| 190 |
+
return dict(duration_samples=round(duration * SR), humans=people, robots=receivers,
|
| 191 |
+
playback_sources=playback, noise=dict(enabled=False))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def synchronize_playback(episode):
|
| 195 |
+
by_id = {r['entity_id']: r for r in episode['robots']}
|
| 196 |
+
for source in episode['playback_sources']:
|
| 197 |
+
for key in ['initial_xyz_m', 'yaw_deg', 'displacement_m', 'motion_start_s', 'motion_duration_s']:
|
| 198 |
+
source[key] = copy.deepcopy(by_id[source['entity_id']][key])
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def movement(base, branch, vectors, speed=.73):
|
| 202 |
+
episode = copy.deepcopy(base)
|
| 203 |
+
entities = episode['humans'] + episode['robots']
|
| 204 |
+
ids = ([episode['humans'][0]['entity_id']] if branch.startswith('easy_human') else
|
| 205 |
+
[episode['robots'][0]['entity_id']] if branch == 'easy_robot' else
|
| 206 |
+
[e['entity_id'] for e in entities])
|
| 207 |
+
for entity in entities:
|
| 208 |
+
if entity['entity_id'] in ids:
|
| 209 |
+
displacement = vectors[entity['entity_id']]
|
| 210 |
+
entity['displacement_m'] = displacement
|
| 211 |
+
entity['motion_duration_s'] = 1.875 * float(np.linalg.norm(displacement)) / speed
|
| 212 |
+
synchronize_playback(episode)
|
| 213 |
+
episode.update(mode='dynamic', branch=branch,
|
| 214 |
+
difficulty='easy' if branch.startswith('easy_') else 'hard', moving_entity_ids=ids)
|
| 215 |
+
return episode
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def choose_vectors(base, rng, room=None):
|
| 219 |
+
vectors = {}
|
| 220 |
+
for entity in base['humans'] + base['robots']:
|
| 221 |
+
for attempt in range(100):
|
| 222 |
+
angle = float(rng.uniform(-math.pi, math.pi))
|
| 223 |
+
length = float(rng.uniform(2.025, 2.075))
|
| 224 |
+
vector = [length * math.cos(angle), 0., length * math.sin(angle)]
|
| 225 |
+
swept = np.asarray(entity['initial_xyz_m']) + np.linspace(0,1,30)[:,None]*np.asarray(vector)
|
| 226 |
+
if room is None or points_clear(swept,room,.25):
|
| 227 |
+
vectors[entity['entity_id']] = vector
|
| 228 |
+
break
|
| 229 |
+
else:
|
| 230 |
+
raise ValueError('No legal >2 m translation for an entity')
|
| 231 |
+
return vectors
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def static_version(base, branch='baseline'):
|
| 235 |
+
result = copy.deepcopy(base)
|
| 236 |
+
result.update(mode='static', branch=branch, difficulty='static', moving_entity_ids=[])
|
| 237 |
+
return result
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def apply_robot_human_count(base, robots, humans):
|
| 241 |
+
result = copy.deepcopy(base)
|
| 242 |
+
result['robots'] = result['robots'][:robots]
|
| 243 |
+
result['humans'] = result['humans'][:humans]
|
| 244 |
+
result['playback_sources'] = [] # pure physical-count experiment; no playback confound
|
| 245 |
+
return result
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def assemble(base, family, room_index, vectors, room, rng, second_vectors=None, common_vector=None,
|
| 249 |
+
static_only=False, frozen_statics=None):
|
| 250 |
+
statics, dynamics = [], []
|
| 251 |
+
links = []
|
| 252 |
+
if family == 'count':
|
| 253 |
+
branch = MOTIONS[room_index % 4]
|
| 254 |
+
for robots in [1, 2, 3]:
|
| 255 |
+
for humans in [1, 2, 3]:
|
| 256 |
+
variant = apply_robot_human_count(base, robots, humans)
|
| 257 |
+
name = f'robots_{robots}_humans_{humans}'
|
| 258 |
+
statics.append(static_version(variant, name))
|
| 259 |
+
dynamics.append(movement(variant, branch, vectors))
|
| 260 |
+
dynamics[-1]['condition_name'] = name
|
| 261 |
+
links.append((len(statics) - 1, len(dynamics) - 1, ['motion']))
|
| 262 |
+
elif family == 'noise':
|
| 263 |
+
robots, humans = 1 + room_index % 3, 1 + (room_index // 3) % 3
|
| 264 |
+
variant = copy.deepcopy(base)
|
| 265 |
+
variant['robots'], variant['humans'] = variant['robots'][:robots], variant['humans'][:humans]
|
| 266 |
+
variant['playback_sources'] = [s for s in variant['playback_sources'] if s['entity_id'] in [r['entity_id'] for r in variant['robots']]]
|
| 267 |
+
noise = dict(kind=KINDS[room_index % len(KINDS)], seed=int(rng.integers(2**31)),
|
| 268 |
+
hum_hz=float(rng.uniform(45, 130)), modulation_hz=float(rng.uniform(4, 15)),
|
| 269 |
+
source_positions_world_m=[], provenance='synthetic_non_speech_v1')
|
| 270 |
+
width, _, depth = room['room_size_m']
|
| 271 |
+
for _ in range(1000):
|
| 272 |
+
p = [float(rng.uniform(-width/2+.4, width/2-.4)), 2.1, float(rng.uniform(-depth/2+.4, depth/2-.4))]
|
| 273 |
+
if points_clear(p, room, .25) and all(np.linalg.norm(np.asarray(p)-np.asarray(e['initial_xyz_m'])) > .8 for e in base['humans'] + base['robots']):
|
| 274 |
+
noise['source_positions_world_m'] = [p]
|
| 275 |
+
break
|
| 276 |
+
if not noise['source_positions_world_m']:
|
| 277 |
+
return None
|
| 278 |
+
for level in [None, 20., 10., 0.]:
|
| 279 |
+
condition = copy.deepcopy(variant)
|
| 280 |
+
condition['noise'] = dict(noise, enabled=level is not None, nominal_snr_db=level)
|
| 281 |
+
name = 'clean' if level is None else f'snr_{int(level)}'
|
| 282 |
+
statics.append(static_version(condition, name))
|
| 283 |
+
dynamics.append(movement(condition, MOTIONS[(room_index + 1) % 4], vectors))
|
| 284 |
+
dynamics[-1]['condition_name'] = name
|
| 285 |
+
links.append((len(statics) - 1, len(dynamics) - 1, ['motion']))
|
| 286 |
+
else:
|
| 287 |
+
variant = copy.deepcopy(base)
|
| 288 |
+
count = 2 + room_index % 2
|
| 289 |
+
variant['robots'], variant['humans'] = variant['robots'][:count], variant['humans'][:count]
|
| 290 |
+
variant['playback_sources'] = [s for s in variant['playback_sources'] if s['entity_id'] in [r['entity_id'] for r in variant['robots']]]
|
| 291 |
+
statics.append(static_version(variant))
|
| 292 |
+
far_distance=float(rng.uniform(4.1,5.4))
|
| 293 |
+
for name, distance in [('target_near', 1.6), ('target_far', far_distance)]:
|
| 294 |
+
changed = copy.deepcopy(variant)
|
| 295 |
+
person, robot = changed['humans'][0], changed['robots'][0]
|
| 296 |
+
delta = np.array(person['initial_xyz_m']) - np.array(robot['initial_xyz_m'])
|
| 297 |
+
horizontal = delta[[0, 2]]
|
| 298 |
+
wanted = math.sqrt(max(distance**2-delta[1]**2, .1))
|
| 299 |
+
person['initial_xyz_m'] = (np.array(robot['initial_xyz_m']) +
|
| 300 |
+
np.array([horizontal[0]*wanted/np.linalg.norm(horizontal), delta[1], horizontal[1]*wanted/np.linalg.norm(horizontal)])).tolist()
|
| 301 |
+
statics.append(static_version(changed, name))
|
| 302 |
+
delayed = copy.deepcopy(variant)
|
| 303 |
+
for source in delayed['humans'][1:] + delayed['playback_sources']:
|
| 304 |
+
for event in source['events']:
|
| 305 |
+
for key in ['start_sample', 'end_sample']:
|
| 306 |
+
event[key] += 12800
|
| 307 |
+
event['activity_samples'] = [[a+12800, b+12800] for a, b in event['activity_samples']]
|
| 308 |
+
for word in event['words']:
|
| 309 |
+
word['start_sample'] += 12800
|
| 310 |
+
word['end_sample'] += 12800
|
| 311 |
+
statics.append(static_version(delayed, 'delayed_interference'))
|
| 312 |
+
for name, gain in [('weaker_competing_speech', -6.), ('stronger_competing_speech', 6.)]:
|
| 313 |
+
changed = copy.deepcopy(variant)
|
| 314 |
+
for source in changed['humans'][1:] + changed['playback_sources']:
|
| 315 |
+
source['emitted_rms_dbfs'] += gain
|
| 316 |
+
statics.append(static_version(changed, name))
|
| 317 |
+
changed = copy.deepcopy(variant)
|
| 318 |
+
changed['playback_sources'] = []
|
| 319 |
+
statics.append(static_version(changed, 'robot_playback_off'))
|
| 320 |
+
for branch in MOTIONS:
|
| 321 |
+
candidate_vectors = vectors if branch != 'hard_joint_b' else (second_vectors or vectors)
|
| 322 |
+
dynamics.append(movement(variant, branch, candidate_vectors))
|
| 323 |
+
shared = {e['entity_id']: (common_vector or vectors['H01']) for e in variant['humans'] + variant['robots']}
|
| 324 |
+
dynamics.append(movement(variant, 'shared_translation', shared))
|
| 325 |
+
fast_branch = 'easy_human_fast' if room_index % 2 == 0 else 'hard_joint_a_fast'
|
| 326 |
+
for branch, speed in [('easy_human_slow', .65), (fast_branch, .8)]:
|
| 327 |
+
dynamics.append(movement(variant, branch, vectors, speed))
|
| 328 |
+
links = [(0, index, ['motion']) for index in range(7)]
|
| 329 |
+
if frozen_statics is not None:
|
| 330 |
+
statics=copy.deepcopy(frozen_statics)
|
| 331 |
+
geometry_cache = {}
|
| 332 |
+
for episode in statics + ([] if static_only else dynamics):
|
| 333 |
+
require_r1 = family == 'count'
|
| 334 |
+
# Noise level/source RMS do not change geometry or selection cues.
|
| 335 |
+
geometry_entities = [{k:v for k,v in e.items() if k not in ['emitted_rms_dbfs', 'source_quality']}
|
| 336 |
+
for e in episode['humans'] + episode['robots']]
|
| 337 |
+
key = uid('geometry-check', geometry_entities, episode['duration_samples'], require_r1)
|
| 338 |
+
if key not in geometry_cache:
|
| 339 |
+
geometry_cache[key] = audit_geometry(episode, room, require_r1)
|
| 340 |
+
check = geometry_cache[key]
|
| 341 |
+
if check is None:
|
| 342 |
+
return None
|
| 343 |
+
episode['geometry_audit'] = check
|
| 344 |
+
return statics, dynamics, links
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def constrained_controls(base, room_index, room, rng, common_vector):
|
| 348 |
+
"""Keep a valid static control set while searching feasible motion forks.
|
| 349 |
+
|
| 350 |
+
Resampling every actor's placement whenever one motion fork fails makes
|
| 351 |
+
tight furnished halls needlessly unlikely. Motion directions are a free
|
| 352 |
+
variable, so search them independently after freezing the static controls.
|
| 353 |
+
"""
|
| 354 |
+
initial = assemble(base, 'controls', room_index,
|
| 355 |
+
{e['entity_id']:common_vector for e in base['humans']+base['robots']},
|
| 356 |
+
room, rng, common_vector=common_vector,static_only=True)
|
| 357 |
+
if initial is None or audit_geometry(initial[1][4],room) is None:
|
| 358 |
+
return None
|
| 359 |
+
# Find the two independent joint motions separately. Each direction set is
|
| 360 |
+
# also used by the corresponding easy / speed fork, so those must pass too.
|
| 361 |
+
accepted=[]
|
| 362 |
+
for branch in ['hard_joint_a','hard_joint_b']:
|
| 363 |
+
for attempt in range(160):
|
| 364 |
+
try:
|
| 365 |
+
vectors=choose_vectors(base,rng,room)
|
| 366 |
+
except ValueError:
|
| 367 |
+
continue
|
| 368 |
+
checks=[movement(base,branch,vectors)]
|
| 369 |
+
if branch=='hard_joint_a':
|
| 370 |
+
checks += [movement(base,'easy_human',vectors),movement(base,'easy_robot',vectors),
|
| 371 |
+
movement(base,'easy_human_slow',vectors,.65),
|
| 372 |
+
movement(base,'easy_human_fast' if room_index%2==0 else 'hard_joint_a_fast',vectors,.8)]
|
| 373 |
+
if all(audit_geometry(e,room) is not None for e in checks):
|
| 374 |
+
accepted.append(vectors)
|
| 375 |
+
break
|
| 376 |
+
else:
|
| 377 |
+
return None
|
| 378 |
+
return assemble(base,'controls',room_index,accepted[0],room,rng,accepted[1],common_vector,
|
| 379 |
+
frozen_statics=initial[0])
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def plan_family(root, pool, room, room_index, family, index, noise_catalog, frozen_materials=None):
|
| 383 |
+
seed = int(uid('family-seed', room_index, family), 16) % 2**32
|
| 384 |
+
rng = np.random.default_rng(seed)
|
| 385 |
+
if frozen_materials is None:
|
| 386 |
+
duration = 9.0 if family == 'controls' else float(rng.choice([8.4, 8.8]))
|
| 387 |
+
humans, played = materials(pool, family, duration, rng)
|
| 388 |
+
else:
|
| 389 |
+
duration = frozen_materials['duration']
|
| 390 |
+
humans, played = frozen_materials['humans'],frozen_materials['played']
|
| 391 |
+
rng.bit_generator.state = frozen_materials['geometry_rng_state']
|
| 392 |
+
for attempt in range(6000):
|
| 393 |
+
common_vector = None
|
| 394 |
+
robot_count=human_count=3
|
| 395 |
+
if family=='noise':
|
| 396 |
+
robot_count,human_count=1+room_index%3,1+(room_index//3)%3
|
| 397 |
+
elif family=='controls':
|
| 398 |
+
robot_count=human_count=2+room_index%2
|
| 399 |
+
if family == 'controls':
|
| 400 |
+
angle=float(rng.uniform(-math.pi,math.pi))
|
| 401 |
+
common_vector=[2.05*math.cos(angle),0.,2.05*math.sin(angle)]
|
| 402 |
+
try:
|
| 403 |
+
base = base_geometry(humans, played, room['layout'], rng, duration, common_vector,robot_count,human_count)
|
| 404 |
+
except ValueError:
|
| 405 |
+
continue
|
| 406 |
+
if family == 'controls' and not 2.4 <= np.linalg.norm(np.asarray(base['humans'][0]['initial_xyz_m'])-np.asarray(base['robots'][0]['initial_xyz_m'])) <= 3.8:
|
| 407 |
+
continue
|
| 408 |
+
# Select integer yaw using both static and initial dynamic uniqueness.
|
| 409 |
+
for robot in base['robots']:
|
| 410 |
+
for yaw in rng.permutation(np.arange(-180, 180)):
|
| 411 |
+
robot['yaw_deg'] = int(yaw)
|
| 412 |
+
isolated = dict(base, mode='static', robots=[robot])
|
| 413 |
+
if cues(isolated) is not None:
|
| 414 |
+
break
|
| 415 |
+
else:
|
| 416 |
+
break
|
| 417 |
+
else:
|
| 418 |
+
synchronize_playback(base)
|
| 419 |
+
if family=='controls':
|
| 420 |
+
built=constrained_controls(base,room_index,room['layout'],rng,common_vector)
|
| 421 |
+
else:
|
| 422 |
+
try:
|
| 423 |
+
vectors = choose_vectors(base, rng, room['layout'])
|
| 424 |
+
except ValueError:
|
| 425 |
+
continue
|
| 426 |
+
built = assemble(base, family, room_index, vectors, room['layout'], rng)
|
| 427 |
+
if built is not None:
|
| 428 |
+
statics, dynamics, links = built
|
| 429 |
+
if family == 'noise':
|
| 430 |
+
if room_index % 5 == 4:
|
| 431 |
+
for episode in statics + dynamics:
|
| 432 |
+
episode['noise']['kind'] = 'fan'
|
| 433 |
+
else:
|
| 434 |
+
category = ['keyboard_typing', 'vacuum_cleaner', 'clock_tick'][room_index % 3]
|
| 435 |
+
entries = [r for r in noise_catalog if r['category'] == category]
|
| 436 |
+
chosen = entries[(room_index // 3) % len(entries)]
|
| 437 |
+
for episode in statics + dynamics:
|
| 438 |
+
episode['noise'].update(kind=category, provenance='real_ESC50_screened_v1',
|
| 439 |
+
recording=chosen, extension_policy='100 ms equal-power cyclic crossfade; noise only')
|
| 440 |
+
scene_id = uid('hall', room['room_id'], room['asset_hashes'])
|
| 441 |
+
group_id = uid('family', scene_id, family)
|
| 442 |
+
nonce = secrets.token_hex(16)
|
| 443 |
+
for mode, episodes in [('static', statics), ('dynamic', dynamics)]:
|
| 444 |
+
for ordinal, episode in enumerate(episodes):
|
| 445 |
+
episode.update(scene_id=scene_id, room_id=room['room_id'], episode_group_id=group_id,
|
| 446 |
+
family_type=family, split='test', sample_rate_hz=SR,
|
| 447 |
+
label_step_s=.5, source_rir_step_s=.2, receiver_rir_step_s=.2)
|
| 448 |
+
episode['condition_id'] = uid(group_id, mode, 'condition', ordinal)
|
| 449 |
+
episode['episode_id'] = uid(group_id, mode, ordinal, canonical_physics(episode))
|
| 450 |
+
pairs = [dict(static_episode_id=statics[a]['episode_id'], dynamic_episode_id=dynamics[b]['episode_id'],
|
| 451 |
+
changed_factors=changed, same_room=True, same_speech_materials=True,
|
| 452 |
+
same_emission_schedule=True, same_initial_positions=True,
|
| 453 |
+
same_emitted_gains_and_noise=True) for a, b, changed in links]
|
| 454 |
+
return dict(schema_version=VERSION, group_id=group_id, index=index, scene_id=scene_id,
|
| 455 |
+
room_id=room['room_id'], room_index=room_index, family_type=family,
|
| 456 |
+
evaluation_id_nonce=nonce, seed=seed, geometry_attempt=attempt,
|
| 457 |
+
material_inventory=humans+played,
|
| 458 |
+
static_episodes=statics, dynamic_episodes=dynamics, static_dynamic_pairs=pairs,
|
| 459 |
+
room=room['layout'], room_assets_sha256=room['asset_hashes'], foa_mapping=room['mapping'],
|
| 460 |
+
renderer={**room['mapping']['renderer'], 'threadCount': 2},
|
| 461 |
+
source_node_step_s=.2, receiver_node_step_s=.2)
|
| 462 |
+
if attempt and attempt % 500 == 0:
|
| 463 |
+
print('GEOMETRY RETRY', room_index, family, attempt, flush=True)
|
| 464 |
+
raise ValueError(f'Cannot make matched {family} family in {room["room_id"]}')
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def plan_payload(payload):
|
| 468 |
+
return plan_family(**payload)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def prepare(root, release, corpus, inventory, processes=16):
|
| 472 |
+
ensure_compute()
|
| 473 |
+
root, release, corpus = root.resolve(), release.resolve(), corpus.resolve()
|
| 474 |
+
expected = config()
|
| 475 |
+
expected.update(source_catalog_sha256=sha(corpus/'source_catalog.jsonl'),
|
| 476 |
+
speech_inventory_sha256=sha(inventory/'source_candidates.json'),
|
| 477 |
+
accepted_room_inventory_sha256=sha(release/'rooms.jsonl.gz'),
|
| 478 |
+
noise_inventory_sha256=sha(root/'shared/noise/catalog.jsonl'))
|
| 479 |
+
if (root/'config.json').exists() and read(root/'config.json') != expected:
|
| 480 |
+
raise ValueError('Configuration changed; use a new generation root')
|
| 481 |
+
write(root/'config.json', expected)
|
| 482 |
+
rooms = select_rooms(release)
|
| 483 |
+
for room in rooms:
|
| 484 |
+
freeze_room(root/'shared/rooms'/room['room_id'], room)
|
| 485 |
+
jsonl(root/'private/rooms.jsonl', rooms)
|
| 486 |
+
candidates = read(inventory/'source_candidates.json')
|
| 487 |
+
noise_catalog = list(rows(root/'shared/noise/catalog.jsonl'))
|
| 488 |
+
pool = SpeechPool(candidates, corpus, root)
|
| 489 |
+
resumed = {}
|
| 490 |
+
material_plans = {}
|
| 491 |
+
for room_index, room in enumerate(rooms):
|
| 492 |
+
for family_index, family in enumerate(['count', 'noise', 'controls']):
|
| 493 |
+
index = 3*room_index+family_index
|
| 494 |
+
path = root/'private/plans'/f'{index:04d}.json'
|
| 495 |
+
material_path = root/'private/material_plans'/f'{index:04d}.json'
|
| 496 |
+
if not path.exists() and not material_path.exists():
|
| 497 |
+
continue
|
| 498 |
+
group = read(path) if path.exists() else None
|
| 499 |
+
if group is not None:
|
| 500 |
+
resumed[index] = group
|
| 501 |
+
if material_path.exists():
|
| 502 |
+
material_plans[index] = read(material_path)
|
| 503 |
+
seen = set()
|
| 504 |
+
inventories = [material_plans[index]['humans']+material_plans[index]['played']] if index in material_plans else [group['material_inventory']]
|
| 505 |
+
for sources in inventories:
|
| 506 |
+
for source in sources:
|
| 507 |
+
for event in source['events']:
|
| 508 |
+
a, b = event['original_word_indices']
|
| 509 |
+
key = (event['original_source_sha256'], a, b)
|
| 510 |
+
if key not in seen:
|
| 511 |
+
pool.used.add(key)
|
| 512 |
+
pool.counts[event['original_source_sha256']] += 1
|
| 513 |
+
seen.add(key)
|
| 514 |
+
groups = dict(resumed)
|
| 515 |
+
payloads = []
|
| 516 |
+
for room_index, room in enumerate(rooms):
|
| 517 |
+
for family_index, family in enumerate(['count', 'noise', 'controls']):
|
| 518 |
+
index = 3*room_index+family_index
|
| 519 |
+
if index in resumed:
|
| 520 |
+
continue
|
| 521 |
+
else:
|
| 522 |
+
if index not in material_plans:
|
| 523 |
+
seed = int(uid('family-seed', room_index, family), 16) % 2**32
|
| 524 |
+
rng = np.random.default_rng(seed)
|
| 525 |
+
duration = 9.0 if family == 'controls' else float(rng.choice([8.4,8.8]))
|
| 526 |
+
humans,played = materials(pool,family,duration,rng)
|
| 527 |
+
material_plans[index] = dict(seed=seed,duration=duration,humans=humans,played=played,
|
| 528 |
+
geometry_rng_state=rng.bit_generator.state)
|
| 529 |
+
write(root/'private/material_plans'/f'{index:04d}.json',material_plans[index])
|
| 530 |
+
payloads.append(dict(root=root,pool=None,room=room,room_index=room_index,family=family,
|
| 531 |
+
index=index,noise_catalog=noise_catalog,frozen_materials=material_plans[index]))
|
| 532 |
+
if index%20==0:
|
| 533 |
+
print('MATERIALS FROZEN',index,flush=True)
|
| 534 |
+
payloads.sort(key=lambda p: (['noise','count','controls'].index(p['family']),p['index']))
|
| 535 |
+
from concurrent.futures import ProcessPoolExecutor,as_completed
|
| 536 |
+
with ProcessPoolExecutor(max_workers=processes) as executor:
|
| 537 |
+
futures={executor.submit(plan_payload,p):p for p in payloads}
|
| 538 |
+
for future in as_completed(futures):
|
| 539 |
+
group=future.result()
|
| 540 |
+
groups[group['index']]=group
|
| 541 |
+
write(root/'private/plans'/f'{group['index']:04d}.json',group)
|
| 542 |
+
print('PLAN',group['index'],group['room_id'],group['family_type'],'attempt',group['geometry_attempt'],flush=True)
|
| 543 |
+
groups=[groups[i] for i in sorted(groups)]
|
| 544 |
+
for mode in ['static', 'dynamic']:
|
| 545 |
+
episodes = [e for g in groups for e in g[mode+'_episodes']]
|
| 546 |
+
if len(episodes) != 2000 or len({e['episode_id'] for e in episodes}) != 2000:
|
| 547 |
+
raise ValueError('Physical episode count/identity mismatch')
|
| 548 |
+
counts = Counter(e['scene_id'] for e in episodes)
|
| 549 |
+
if set(counts.values()) != {20}:
|
| 550 |
+
raise ValueError('Wrong per-room count')
|
| 551 |
+
jsonl(root/mode/'private/episodes.jsonl', episodes)
|
| 552 |
+
write(root/mode/'config.json', dict(expected, mode=mode))
|
| 553 |
+
jsonl(root/'private/recipes.jsonl', groups)
|
| 554 |
+
write(root/'reports/prepare.complete.json', dict(passed=True, halls=100, groups=300,
|
| 555 |
+
static_episodes=2000, dynamic_episodes=2000,
|
| 556 |
+
static_dynamic_pairs=sum(len(g['static_dynamic_pairs']) for g in groups)))
|
| 557 |
+
print('PREPARE COMPLETE', flush=True)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
if __name__ == '__main__':
|
| 561 |
+
p = argparse.ArgumentParser()
|
| 562 |
+
p.add_argument('--root', type=Path, required=True)
|
| 563 |
+
p.add_argument('--release', type=Path, required=True)
|
| 564 |
+
p.add_argument('--corpus', type=Path, required=True)
|
| 565 |
+
p.add_argument('--inventory', type=Path, required=True)
|
| 566 |
+
a = p.parse_args()
|
| 567 |
+
prepare(a.root, a.release, a.corpus, a.inventory)
|
code/exhibition_dataset/reproduce.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Initialize exact accepted inputs, then reproduce FOA and the whole protocol.
|
| 2 |
+
|
| 3 |
+
The bundle is creator-side: it contains frozen source/geometry truth. Never
|
| 4 |
+
mount it in a blind model-inference process.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import shutil
|
| 11 |
+
|
| 12 |
+
from .common import read,rows,write,jsonl,sha
|
| 13 |
+
from dynamic_dataset.prepare import freeze_room
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def copy_verified(source,target,digest=None):
|
| 17 |
+
digest=digest or sha(source)
|
| 18 |
+
if target.exists():
|
| 19 |
+
if sha(target)!=digest:
|
| 20 |
+
raise ValueError('Different frozen input at '+str(target))
|
| 21 |
+
return
|
| 22 |
+
if sha(source)!=digest:
|
| 23 |
+
raise ValueError('Frozen source checksum mismatch')
|
| 24 |
+
target.parent.mkdir(parents=True,exist_ok=True)
|
| 25 |
+
shutil.copyfile(source,target)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def initialize(bundle,root):
|
| 29 |
+
bundle,root=Path(bundle).resolve(),Path(root).resolve()
|
| 30 |
+
if bundle==root:
|
| 31 |
+
raise ValueError('Choose a separate reproduction output root')
|
| 32 |
+
groups=list(rows(bundle/'private/recipes.jsonl'))
|
| 33 |
+
rooms=list(rows(bundle/'private/rooms.jsonl'))
|
| 34 |
+
if len(groups)!=300 or len(rooms)!=100:
|
| 35 |
+
raise ValueError('Expected a complete 100-hall frozen input bundle')
|
| 36 |
+
for name in ['config.json','private/recipes.jsonl','private/rooms.jsonl','shared/noise/catalog.jsonl']:
|
| 37 |
+
copy_verified(bundle/name,root/name)
|
| 38 |
+
source_paths={event['audio_asset']:event['original_source_sha256'] for group in groups
|
| 39 |
+
for source in group['material_inventory'] for event in source['events']}
|
| 40 |
+
for rel,digest in source_paths.items():
|
| 41 |
+
copy_verified(bundle/rel,root/rel,digest)
|
| 42 |
+
for record in rows(bundle/'shared/noise/catalog.jsonl'):
|
| 43 |
+
for field,digest_field in [('audio_asset','sha256'),('original_path','original_sha256')]:
|
| 44 |
+
copy_verified(bundle/record[field],root/record[field],record[digest_field])
|
| 45 |
+
for name in ['ESC50_LICENSE','ESC50_README.md','esc50.csv','silero_vad.jit','rejected.jsonl']:
|
| 46 |
+
copy_verified(bundle/'shared/noise'/name,root/'shared/noise'/name)
|
| 47 |
+
for room in rooms:
|
| 48 |
+
freeze_room(root/'shared/rooms'/room['room_id'],room)
|
| 49 |
+
for group in groups:
|
| 50 |
+
write(root/'private/plans'/f'{group["index"]:04d}.json',group)
|
| 51 |
+
write(root/'reports/prepare.complete.json',dict(passed=True,halls=100,groups=300,
|
| 52 |
+
static_episodes=2000,dynamic_episodes=2000,initialized_from_accepted_bundle=True))
|
| 53 |
+
write(root/'reports/reproduction_input.json',dict(bundle=str(bundle),
|
| 54 |
+
native_rir_bitwise_identity_promised=False,
|
| 55 |
+
exact_inputs='Same originals, crops, emission schedules/gains, room assets, trajectories, noise and query identities.'))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__=='__main__':
|
| 59 |
+
parser=argparse.ArgumentParser()
|
| 60 |
+
parser.add_argument('--bundle',type=Path)
|
| 61 |
+
parser.add_argument('--root',type=Path,required=True)
|
| 62 |
+
parser.add_argument('--stage',choices=['initialize','static','dynamic','finalize','all'],default='all')
|
| 63 |
+
parser.add_argument('--processes',type=int,default=8)
|
| 64 |
+
a=parser.parse_args()
|
| 65 |
+
if a.stage in ['initialize','all']:
|
| 66 |
+
if a.bundle is None:
|
| 67 |
+
parser.error('--bundle is required when initializing')
|
| 68 |
+
initialize(a.bundle,a.root)
|
| 69 |
+
if a.stage in ['static','all']:
|
| 70 |
+
from .worker import worker
|
| 71 |
+
worker(a.root,'static',a.processes)
|
| 72 |
+
if a.stage in ['dynamic','all']:
|
| 73 |
+
from .worker import worker
|
| 74 |
+
worker(a.root,'dynamic',a.processes)
|
| 75 |
+
if a.stage in ['finalize','all']:
|
| 76 |
+
from .preflight import inspect
|
| 77 |
+
from .finalize import finalize
|
| 78 |
+
inspect(a.root,a.processes)
|
| 79 |
+
finalize(a.root)
|
code/exhibition_dataset/runtime.sh
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
exhibition_repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
| 4 |
+
exhibition_bench=$(cd "$exhibition_repo/../.." && pwd)
|
| 5 |
+
export PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
|
| 6 |
+
export OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 MKL_NUM_THREADS=2
|
| 7 |
+
export MAGNUM_LOG=quiet HABITAT_SIM_LOG=quiet
|
| 8 |
+
export PYTHONPATH="$exhibition_repo:$exhibition_bench/multi_robot_benchmark/analyses/dynamic_demo_v1_20261001/operations/python${PYTHONPATH:+:$PYTHONPATH}"
|
| 9 |
+
cd "$exhibition_repo"
|
| 10 |
+
if [[ -f "$exhibition_bench/soundspaces_demo/scripts/run_soundspaces_runtime.sh" ]]; then
|
| 11 |
+
exec bash "$exhibition_bench/soundspaces_demo/scripts/run_soundspaces_runtime.sh" "$@"
|
| 12 |
+
fi
|
| 13 |
+
# Portable native environments (e.g. dynamic_demo/Dockerfile) use their Python.
|
| 14 |
+
exec "${DISH_PYTHON:-python}" "$@"
|
code/exhibition_dataset/score.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal scoring of static and 0.5-second dynamic exhibition tasks.
|
| 2 |
+
|
| 3 |
+
Predictions: JSONL {sample_id, output}. Missing/invalid predictions remain in
|
| 4 |
+
the full denominator. Spatial error statistics are accompanied by coverage
|
| 5 |
+
and tolerance success. Dynamic DOA uses one identity assignment for the whole
|
| 6 |
+
clip. Threshold curves reuse the SAME frozen prediction file.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
from collections import Counter, defaultdict
|
| 12 |
+
import gzip
|
| 13 |
+
import itertools
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
from scipy.optimize import linear_sum_assignment
|
| 20 |
+
|
| 21 |
+
from dynamic_dataset.score import safe_score
|
| 22 |
+
from dynamic_dataset.frame_score import frame_map, edit_distance
|
| 23 |
+
from .common import VERSION, angular, tokens, rows, sha, write
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def finite(value):
|
| 27 |
+
return type(value) in [float,int] and math.isfinite(value)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def decode(value, task):
|
| 31 |
+
if isinstance(value,str):
|
| 32 |
+
text=value.strip()
|
| 33 |
+
if text.startswith('```') and text.endswith('```'):
|
| 34 |
+
text=text.split('\n',1)[-1].rsplit('```',1)[0].strip()
|
| 35 |
+
if task in ['KW_ASR','DOA_ASR','C2_REGION_ASR']:
|
| 36 |
+
if text == '""':
|
| 37 |
+
return ''
|
| 38 |
+
return value
|
| 39 |
+
try:
|
| 40 |
+
value=json.loads(text,parse_constant=lambda _: (_ for _ in ()).throw(ValueError('Non-finite JSON')))
|
| 41 |
+
except (ValueError,TypeError):
|
| 42 |
+
return None
|
| 43 |
+
return value
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def spatial_static(gold, prediction):
|
| 47 |
+
task, answer = gold['task_id'],gold['output']
|
| 48 |
+
degree = task in ['DOA','TEXT_DOA']
|
| 49 |
+
reference = answer if task in ['DOA','C1_SETLOC'] else [answer]
|
| 50 |
+
if task == 'RANGE':
|
| 51 |
+
valid = finite(prediction) and prediction > 0
|
| 52 |
+
errors = [abs(answer-prediction)] if valid else [None]
|
| 53 |
+
elif task in ['DOA','C1_SETLOC']:
|
| 54 |
+
dimension = 2 if task == 'DOA' else 3
|
| 55 |
+
valid = isinstance(prediction,list) and len(prediction)==len(reference)
|
| 56 |
+
points = prediction if isinstance(prediction,list) and len(prediction)<=8 else []
|
| 57 |
+
points = [p for p in points if isinstance(p,list) and len(p)==dimension and all(finite(v) for v in p)
|
| 58 |
+
and (not degree or (-180<=p[0]<=180 and -90<=p[1]<=90))]
|
| 59 |
+
valid = valid and len(points)==len(reference)
|
| 60 |
+
n=max(len(points),len(reference))
|
| 61 |
+
costs=np.full((len(reference),n),1e6)
|
| 62 |
+
for i,target in enumerate(reference):
|
| 63 |
+
for j,point in enumerate(points):
|
| 64 |
+
costs[i,j]=angular(target,point) if degree else math.dist(target,point)
|
| 65 |
+
indices,mapping=linear_sum_assignment(costs)
|
| 66 |
+
errors=[None]*len(reference)
|
| 67 |
+
for i,j in zip(indices,mapping):
|
| 68 |
+
if j<len(points):
|
| 69 |
+
errors[i]=float(costs[i,j])
|
| 70 |
+
else:
|
| 71 |
+
dimension=2 if task == 'TEXT_DOA' else 3
|
| 72 |
+
valid = isinstance(prediction,list) and len(prediction)==dimension and all(finite(v) for v in prediction)
|
| 73 |
+
if degree and valid:
|
| 74 |
+
valid = -180<=prediction[0]<=180 and -90<=prediction[1]<=90
|
| 75 |
+
errors = [(angular(answer,prediction) if degree else math.dist(answer,prediction)) if valid else None]
|
| 76 |
+
# Static DOA requests humans AND other robot playback, so the main score
|
| 77 |
+
# includes both. Role-specific diagnostics allow a human-only comparison
|
| 78 |
+
# against the dynamic task without dropping requested targets silently.
|
| 79 |
+
if task=='DOA':
|
| 80 |
+
role_errors={role:[e for e,r in zip(errors,gold['source_roles']) if r==role] for role in ['human','robot']}
|
| 81 |
+
else:
|
| 82 |
+
role_errors=None
|
| 83 |
+
if degree:
|
| 84 |
+
statistics_errors=[e if e is not None else 180. for e in errors]
|
| 85 |
+
else:
|
| 86 |
+
statistics_errors=[e for e in errors if e is not None]
|
| 87 |
+
return dict(format_valid=bool(valid),units='degrees' if degree else 'meters',
|
| 88 |
+
errors=errors,statistics_errors=statistics_errors,total=len(errors),
|
| 89 |
+
covered=sum(e is not None for e in errors),speech_role_errors_diagnostic=role_errors)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def dynamic_errors(gold,prediction,result):
|
| 93 |
+
task=gold['task_id']
|
| 94 |
+
times=gold['expected_times_s']
|
| 95 |
+
step=.5
|
| 96 |
+
if task=='DOA_TRAJECTORY':
|
| 97 |
+
raw=prediction.get('tracks',[]) if isinstance(prediction,dict) else []
|
| 98 |
+
valid_ids=isinstance(raw,list) and len(raw)<=8 and all(isinstance(t,dict) and isinstance(t.get('track_id'),str) and t['track_id'] for t in raw)
|
| 99 |
+
tracks={t['track_id']:t for t in raw} if valid_ids and len({t['track_id'] for t in raw})==len(raw) else {}
|
| 100 |
+
errors=[]
|
| 101 |
+
for reference in gold['output']['tracks']:
|
| 102 |
+
identity=result['whole_clip_assignment'].get(reference['track_id'])
|
| 103 |
+
mapped,_=frame_map(tracks.get(identity),times,'doa_deg',step)
|
| 104 |
+
for frame in reference['frames']:
|
| 105 |
+
if not frame['active']:
|
| 106 |
+
continue
|
| 107 |
+
p=mapped.get(round(frame['time_s']/step))
|
| 108 |
+
value=p['doa_deg'] if p and p['active'] else None
|
| 109 |
+
valid=value is not None and -180<=value[0]<=180 and -90<=value[1]<=90
|
| 110 |
+
errors.append(angular(frame['doa_deg'],value) if valid else None)
|
| 111 |
+
return errors
|
| 112 |
+
key='distance_m' if task=='RANGE_TRAJECTORY' else 'xyz_m'
|
| 113 |
+
mapped,_=frame_map(prediction,times,key,step)
|
| 114 |
+
errors=[]
|
| 115 |
+
for frame in gold['output']['frames']:
|
| 116 |
+
if not frame['active']:
|
| 117 |
+
continue
|
| 118 |
+
p=mapped.get(round(frame['time_s']/step))
|
| 119 |
+
value=p[key] if p and p['active'] else None
|
| 120 |
+
valid=value is not None and (abs(value)<=1000 if key=='distance_m' else all(abs(v)<=1000 for v in value))
|
| 121 |
+
errors.append((abs(frame[key]-value) if key=='distance_m' else math.dist(frame[key],value)) if valid else None)
|
| 122 |
+
return errors
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def one(gold,prediction):
|
| 126 |
+
task=gold['task_id']
|
| 127 |
+
prediction=decode(prediction,task)
|
| 128 |
+
if task in ['KW_ASR','DOA_ASR','C2_REGION_ASR']:
|
| 129 |
+
valid=isinstance(prediction,str)
|
| 130 |
+
target=tokens(gold['output'])
|
| 131 |
+
given=tokens(prediction) if valid else []
|
| 132 |
+
edits=edit_distance(target,given)
|
| 133 |
+
return dict(format_valid=valid,asr=True,reference_words=len(target),edits=edits,
|
| 134 |
+
negative=not target,empty_correct=valid and not prediction.strip(),
|
| 135 |
+
exact_match=valid and target==given and (bool(target) or not prediction.strip()))
|
| 136 |
+
if task.endswith('TRAJECTORY'):
|
| 137 |
+
result=safe_score(gold,prediction)
|
| 138 |
+
errors=dynamic_errors(gold,prediction,result)
|
| 139 |
+
degree=task=='DOA_TRAJECTORY'
|
| 140 |
+
return dict(format_valid=result['format_valid'],asr=False,
|
| 141 |
+
units='degrees' if degree else 'meters',errors=errors,total=len(errors),
|
| 142 |
+
covered=sum(e is not None for e in errors),
|
| 143 |
+
statistics_errors=[e if e is not None else 180. for e in errors] if degree else [e for e in errors if e is not None],
|
| 144 |
+
missed_frames=result['missed_frames'],false_positive_frames=result['false_positive_frames'],
|
| 145 |
+
identity_switches_diagnostic=result.get('identity_switches_diagnostic',0))
|
| 146 |
+
return dict(spatial_static(gold,prediction),asr=False)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class Accumulator:
|
| 150 |
+
def __init__(self):
|
| 151 |
+
self.values=Counter()
|
| 152 |
+
self.success=Counter()
|
| 153 |
+
self.is_asr=None
|
| 154 |
+
self.units=None
|
| 155 |
+
def add(self,result,thresholds):
|
| 156 |
+
v=self.values
|
| 157 |
+
v['samples']+=1
|
| 158 |
+
v['format_valid']+=result['format_valid']
|
| 159 |
+
self.is_asr=result['asr']
|
| 160 |
+
if self.is_asr:
|
| 161 |
+
v['reference_words']+=result['reference_words']
|
| 162 |
+
v['edits']+=result['edits'] if result['reference_words'] else 0
|
| 163 |
+
v['negative_samples']+=result['negative']
|
| 164 |
+
v['empty_correct']+=result['negative'] and result['empty_correct']
|
| 165 |
+
v['exact_match']+=result['exact_match']
|
| 166 |
+
return
|
| 167 |
+
self.units=result['units']
|
| 168 |
+
v['reference_positions']+=result['total']
|
| 169 |
+
v['covered_positions']+=result['covered']
|
| 170 |
+
errors=result['statistics_errors']
|
| 171 |
+
v['error_count']+=len(errors)
|
| 172 |
+
v['error_sum']+=sum(errors)
|
| 173 |
+
v['error_square_sum']+=sum(e*e for e in errors)
|
| 174 |
+
v['missed_frames']+=result.get('missed_frames',0)
|
| 175 |
+
v['false_positive_frames']+=result.get('false_positive_frames',0)
|
| 176 |
+
v['identity_switches']+=result.get('identity_switches_diagnostic',0)
|
| 177 |
+
for threshold in thresholds:
|
| 178 |
+
self.success[str(threshold)]+=sum(e is not None and e<=threshold for e in result['errors'])
|
| 179 |
+
def finish(self):
|
| 180 |
+
v=self.values
|
| 181 |
+
result=dict(samples=v['samples'],format_valid_fraction=v['format_valid']/max(v['samples'],1))
|
| 182 |
+
if self.is_asr:
|
| 183 |
+
result.update(corpus_wer=v['edits']/v['reference_words'] if v['reference_words'] else None,
|
| 184 |
+
reference_words=v['reference_words'],word_edits=v['edits'],negative_samples=v['negative_samples'],
|
| 185 |
+
negative_empty_accuracy=v['empty_correct']/v['negative_samples'] if v['negative_samples'] else None,
|
| 186 |
+
exact_match_fraction=v['exact_match']/max(v['samples'],1))
|
| 187 |
+
else:
|
| 188 |
+
count=v['error_count']
|
| 189 |
+
mean=v['error_sum']/count if count else None
|
| 190 |
+
result.update(units=self.units,reference_positions=v['reference_positions'],covered_positions=v['covered_positions'],
|
| 191 |
+
coverage=v['covered_positions']/max(v['reference_positions'],1),mean_error=mean,
|
| 192 |
+
variance_error=max(0.,v['error_square_sum']/count-mean**2) if count else None,
|
| 193 |
+
rmse=math.sqrt(v['error_square_sum']/count) if count else None,
|
| 194 |
+
tolerance_success={k:n/max(v['reference_positions'],1) for k,n in self.success.items()},
|
| 195 |
+
missed_frames=v['missed_frames'],false_positive_frames=v['false_positive_frames'],
|
| 196 |
+
identity_switches_diagnostic=v['identity_switches'])
|
| 197 |
+
return result
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def evaluate(root,predictions,output,score_fn=None):
|
| 201 |
+
root,output=Path(root),Path(output)
|
| 202 |
+
score_fn=score_fn or one
|
| 203 |
+
output.mkdir(parents=True,exist_ok=True)
|
| 204 |
+
known={r['sample_id'] for r in rows(root/'public/test/index.jsonl')}
|
| 205 |
+
# Freeze the prediction bytes before opening gold; duplicate IDs become failures.
|
| 206 |
+
digest=sha(predictions)
|
| 207 |
+
given={}
|
| 208 |
+
duplicates=set()
|
| 209 |
+
invalid=0
|
| 210 |
+
for row in rows(predictions):
|
| 211 |
+
sid=row.get('sample_id')
|
| 212 |
+
if sid not in known:
|
| 213 |
+
invalid+=1
|
| 214 |
+
continue
|
| 215 |
+
if sid in given or sid in duplicates:
|
| 216 |
+
given.pop(sid,None)
|
| 217 |
+
duplicates.add(sid)
|
| 218 |
+
else:
|
| 219 |
+
given[sid]=row.get('output')
|
| 220 |
+
accumulators=defaultdict(Accumulator)
|
| 221 |
+
keyword_pairs=defaultdict(list)
|
| 222 |
+
total=missing=0
|
| 223 |
+
with gzip.open(output/'per_sample.jsonl.gz','wt') as stream:
|
| 224 |
+
for gold in rows(root/'private/test/gold.jsonl'):
|
| 225 |
+
total+=1
|
| 226 |
+
prediction=given.get(gold['sample_id'])
|
| 227 |
+
missing+=gold['sample_id'] not in given
|
| 228 |
+
try:
|
| 229 |
+
result=score_fn(gold,prediction)
|
| 230 |
+
except (ValueError,TypeError,KeyError,IndexError,OverflowError):
|
| 231 |
+
result=score_fn(gold,None)
|
| 232 |
+
result['format_valid']=False
|
| 233 |
+
thresholds=[5.,10.,20.,30.,45.] if result.get('units')=='degrees' else [.25,.5,1.,1.5,2.]
|
| 234 |
+
base=gold['setting']+'/'+gold['task_id']
|
| 235 |
+
keys=[base,base+'/robots/'+str(gold['num_robots']),base+'/humans/'+str(gold['num_humans']),
|
| 236 |
+
base+'/rt_bin/'+str(gold['rt_bin']),base+'/branch/'+gold['branch'],
|
| 237 |
+
base+'/noise/'+gold.get('noise_type','unspecified'),
|
| 238 |
+
base+'/noise_snr/'+str(gold.get('noise_nominal_snr_db')),
|
| 239 |
+
base+'/layout/'+gold.get('layout_template','unspecified'),
|
| 240 |
+
base+'/motion/target_'+gold.get('target_human_motion','unspecified')+'/receiver_'+gold.get('observed_receiver_motion','unspecified')]
|
| 241 |
+
case=gold.get('case',gold.get('keyword_case'))
|
| 242 |
+
if case is not None:
|
| 243 |
+
keys.append(base+'/case/'+case)
|
| 244 |
+
if 'cue_type' in gold:keys.append(base+'/cue/'+gold['cue_type'])
|
| 245 |
+
if 'evaluation_group' in gold:keys.append(base+'/selection/'+gold['evaluation_group'])
|
| 246 |
+
for key in keys:
|
| 247 |
+
accumulators[key].add(result,thresholds)
|
| 248 |
+
for role,errors in (result.get('speech_role_errors_diagnostic') or {}).items():
|
| 249 |
+
if errors:
|
| 250 |
+
specific=dict(result,errors=errors,total=len(errors),covered=sum(e is not None for e in errors),
|
| 251 |
+
statistics_errors=[e if e is not None else 180. for e in errors])
|
| 252 |
+
accumulators[base+'/source_role/'+role].add(specific,thresholds)
|
| 253 |
+
if gold['task_id']=='KW_ASR':
|
| 254 |
+
keyword_pairs[gold['query_group_id']].append(dict(setting=gold['setting'],
|
| 255 |
+
wer=result['edits']/result['reference_words'] if result['reference_words'] else None,
|
| 256 |
+
exact=result['exact_match']))
|
| 257 |
+
stream.write(json.dumps(dict(sample_id=gold['sample_id'],episode_id=gold['episode_id'],
|
| 258 |
+
scene_id=gold['scene_id'],task_id=gold['task_id'],setting=gold['setting'],**result),
|
| 259 |
+
separators=(',',':'),allow_nan=False)+'\n')
|
| 260 |
+
if total!=len(known):
|
| 261 |
+
raise ValueError('Public/gold sample inventory mismatch')
|
| 262 |
+
wer_gains=[]
|
| 263 |
+
exact_gains=[]
|
| 264 |
+
for values in keyword_pairs.values():
|
| 265 |
+
edges=[v for v in values if v['setting']=='edge']
|
| 266 |
+
cloud=next(v for v in values if v['setting']=='cloud')
|
| 267 |
+
if cloud['wer'] is not None:
|
| 268 |
+
wer_gains.append(sum(v['wer'] for v in edges)/len(edges)-cloud['wer'])
|
| 269 |
+
exact_gains.append(float(cloud['exact'])-sum(float(v['exact']) for v in edges)/len(edges))
|
| 270 |
+
report=dict(scorer_version=VERSION+'.1',label_step_s=.5,samples=total,missing_predictions=missing,
|
| 271 |
+
prediction_sha256=digest,duplicate_prediction_ids=len(duplicates),unknown_prediction_rows=invalid,
|
| 272 |
+
metrics={k:v.finish() for k,v in sorted(accumulators.items())},
|
| 273 |
+
paired_kw_asr=dict(query_groups=len(keyword_pairs),positive_query_groups=len(wer_gains),
|
| 274 |
+
mean_cloud_wer_improvement_over_mean_edge=sum(wer_gains)/len(wer_gains) if wer_gains else None,
|
| 275 |
+
mean_cloud_exact_match_improvement_over_mean_edge=sum(exact_gains)/len(exact_gains) if exact_gains else None),
|
| 276 |
+
protocol='All-reference denominators. DOA omissions count as 180 degrees in errors. Metric errors accompany coverage. Fixed identity across the whole dynamic clip.',
|
| 277 |
+
independence='Bootstrap over hall and matched family; receiver views, conditions and source crops are correlated.',
|
| 278 |
+
threshold_curves='Computed from one frozen prediction file; larger tolerance changes the criterion, not model predictions.')
|
| 279 |
+
write(output/'metrics.json',report)
|
| 280 |
+
print('SCORED',total,'questions;',missing,'missing',flush=True)
|
| 281 |
+
return report
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
if __name__=='__main__':
|
| 285 |
+
parser=argparse.ArgumentParser()
|
| 286 |
+
parser.add_argument('--root',type=Path,required=True)
|
| 287 |
+
parser.add_argument('--predictions',type=Path,required=True)
|
| 288 |
+
parser.add_argument('--output',type=Path,required=True)
|
| 289 |
+
args=parser.parse_args()
|
| 290 |
+
evaluate(args.root,args.predictions,args.output)
|
code/exhibition_dataset/sources.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pin and screen real non-speech noise from the original ESC-50 repository.
|
| 2 |
+
|
| 3 |
+
The screening model is an asset-selection aid, not a benchmark baseline.
|
| 4 |
+
Per-file VAD evidence and all rejections are retained. Automatic screening is
|
| 5 |
+
not advertised as a completed human listening audit.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import csv
|
| 11 |
+
import io
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import urllib.request
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
|
| 16 |
+
from .common import sha, uid, write, jsonl
|
| 17 |
+
|
| 18 |
+
ESC_REVISION = '33c8ce9eb2cf0b1c2f8bcf322eb349b6be34dbb6'
|
| 19 |
+
ESC_URL = 'https://raw.githubusercontent.com/karolpiczak/ESC-50/' + ESC_REVISION
|
| 20 |
+
CATEGORIES = ['keyboard_typing', 'vacuum_cleaner', 'clock_tick']
|
| 21 |
+
SILERO_REVISION = '1e261b036686cd0017d500ee96acd1c4ba572a9d'
|
| 22 |
+
SILERO_SHA256 = 'e1122837f4154c511485fe0b9c64455f7b929c96fbb8d79fbdb336383ebd3720'
|
| 23 |
+
SILERO_URL = 'https://raw.githubusercontent.com/snakers4/silero-vad/' + SILERO_REVISION + '/src/silero_vad/data/silero_vad.jit'
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def fetch(url, target):
|
| 27 |
+
target = Path(target)
|
| 28 |
+
if target.exists():
|
| 29 |
+
return
|
| 30 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
temporary = target.with_suffix(target.suffix + '.part')
|
| 32 |
+
last = None
|
| 33 |
+
for _ in range(3):
|
| 34 |
+
try:
|
| 35 |
+
with urllib.request.urlopen(url, timeout=45) as response, temporary.open('wb') as output:
|
| 36 |
+
while True:
|
| 37 |
+
chunk = response.read(1024*1024)
|
| 38 |
+
if not chunk:
|
| 39 |
+
break
|
| 40 |
+
output.write(chunk)
|
| 41 |
+
temporary.replace(target)
|
| 42 |
+
return
|
| 43 |
+
except Exception as error:
|
| 44 |
+
last = error
|
| 45 |
+
raise RuntimeError('Could not fetch pinned public noise asset') from last
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def prepare_noise(root):
|
| 49 |
+
from dynamic_dataset.runtime import ensure_compute
|
| 50 |
+
ensure_compute()
|
| 51 |
+
import math
|
| 52 |
+
import numpy as np
|
| 53 |
+
import soundfile as sf
|
| 54 |
+
from scipy.signal import resample_poly
|
| 55 |
+
import torch
|
| 56 |
+
root = Path(root)
|
| 57 |
+
folder = root/'shared/noise'
|
| 58 |
+
fetch(ESC_URL+'/meta/esc50.csv', folder/'esc50.csv')
|
| 59 |
+
fetch(ESC_URL+'/LICENSE', folder/'ESC50_LICENSE')
|
| 60 |
+
fetch(ESC_URL+'/README.md', folder/'ESC50_README.md')
|
| 61 |
+
fetch(SILERO_URL, folder/'silero_vad.jit')
|
| 62 |
+
if sha(folder/'silero_vad.jit') != SILERO_SHA256:
|
| 63 |
+
raise ValueError('Speech-screening model checksum differs from the pinned selection model')
|
| 64 |
+
candidates = [r for r in csv.DictReader((folder/'esc50.csv').open()) if r['category'] in CATEGORIES]
|
| 65 |
+
# Use each original recording only once in this material inventory.
|
| 66 |
+
originals = set()
|
| 67 |
+
candidates = [r for r in sorted(candidates, key=lambda r: uid('noise-order', r['filename']))
|
| 68 |
+
if not (r['src_file'] in originals or originals.add(r['src_file']))]
|
| 69 |
+
with ThreadPoolExecutor(max_workers=8) as workers:
|
| 70 |
+
list(workers.map(lambda r: fetch(ESC_URL+'/audio/'+r['filename'], folder/'originals'/r['filename']), candidates))
|
| 71 |
+
torch.set_num_threads(2)
|
| 72 |
+
model = torch.jit.load(str(folder/'silero_vad.jit'), map_location='cpu').eval()
|
| 73 |
+
accepted, rejected = [], []
|
| 74 |
+
for row in candidates:
|
| 75 |
+
path = folder/'originals'/row['filename']
|
| 76 |
+
wave, rate = sf.read(path, dtype='float32')
|
| 77 |
+
if wave.ndim != 1:
|
| 78 |
+
wave = wave.mean(axis=1)
|
| 79 |
+
common = math.gcd(int(rate), 16000)
|
| 80 |
+
wave = resample_poly(wave, 16000//common, int(rate)//common).astype(np.float32)
|
| 81 |
+
model.reset_states()
|
| 82 |
+
probabilities = []
|
| 83 |
+
with torch.inference_mode():
|
| 84 |
+
for offset in range(0, len(wave), 512):
|
| 85 |
+
chunk = np.pad(wave[offset:offset+512], (0, max(0, 512-len(wave[offset:offset+512]))))
|
| 86 |
+
probabilities.append(float(model(torch.from_numpy(chunk), 16000).item()))
|
| 87 |
+
maximum = max(probabilities)
|
| 88 |
+
above = sum(p >= .5 for p in probabilities)*512/16000
|
| 89 |
+
evidence = dict(vad_model_sha256=SILERO_SHA256, vad_model_revision=SILERO_REVISION, maximum_speech_probability=maximum,
|
| 90 |
+
speech_probability_above_0_5_s=above, threshold_maximum_probability=.35,
|
| 91 |
+
human_listening_audit_completed=False)
|
| 92 |
+
record = dict(noise_id=uid('ESC50', row['src_file']), source='ESC-50', category=row['category'],
|
| 93 |
+
original_source_id=row['src_file'], original_fold=int(row['fold']),
|
| 94 |
+
filename=row['filename'], revision=ESC_REVISION, url=ESC_URL+'/audio/'+row['filename'],
|
| 95 |
+
original_path=str(path.relative_to(root)), original_sha256=sha(path),
|
| 96 |
+
source_license='CC BY-NC 4.0', original_sample_rate_hz=int(rate),
|
| 97 |
+
screening=evidence, acoustic_status='near-source recording with possible residual original acoustics; not claimed anechoic')
|
| 98 |
+
if maximum >= .35 or float(np.sqrt(np.mean(wave.astype(float)**2))) < 1e-5:
|
| 99 |
+
rejected.append(dict(record, reason='speech screening or negligible signal'))
|
| 100 |
+
continue
|
| 101 |
+
processed = folder/'mono16k'/(row['filename']+'.wav')
|
| 102 |
+
processed.parent.mkdir(parents=True, exist_ok=True)
|
| 103 |
+
sf.write(processed, wave, 16000, subtype='FLOAT')
|
| 104 |
+
record.update(audio_asset=str(processed.relative_to(root)), sha256=sha(processed),
|
| 105 |
+
num_samples=len(wave), sample_rate_hz=16000, resampler='scipy.signal.resample_poly')
|
| 106 |
+
accepted.append(record)
|
| 107 |
+
if any(sum(r['category'] == category for r in accepted) < 4 for category in CATEGORIES):
|
| 108 |
+
raise ValueError('Insufficient screened real noise in one declared class; inspect rejected inventory')
|
| 109 |
+
jsonl(root/'shared/noise/catalog.jsonl', accepted)
|
| 110 |
+
jsonl(root/'shared/noise/rejected.jsonl', rejected)
|
| 111 |
+
write(root/'reports/noise.complete.json', dict(passed=True, accepted=len(accepted), rejected=len(rejected),
|
| 112 |
+
categories={c:sum(r['category'] == c for r in accepted) for c in CATEGORIES},
|
| 113 |
+
repository_revision=ESC_REVISION, vad_model_sha256=SILERO_SHA256, vad_model_revision=SILERO_REVISION,
|
| 114 |
+
noise_license='Real ESC-50-derived mixtures: CC BY-NC 4.0; clean speech uses LibriSpeech CC BY 4.0',
|
| 115 |
+
speech_filter='No accepted 32 ms chunk reaches speech probability 0.35; automatic screening only'))
|
| 116 |
+
print('REAL NOISE READY', len(accepted), 'rejected', len(rejected), flush=True)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == '__main__':
|
| 120 |
+
parser = argparse.ArgumentParser()
|
| 121 |
+
parser.add_argument('--root', type=Path, required=True)
|
| 122 |
+
prepare_noise(parser.parse_args().root)
|
code/exhibition_dataset/worker.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Durable allocated-node supervisor with native-stall recovery and streaming plans."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import shutil
|
| 9 |
+
import subprocess
|
| 10 |
+
import tempfile
|
| 11 |
+
import time
|
| 12 |
+
|
| 13 |
+
from .common import read, write
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def supervise(root,mode,group,gpu,timeout=300.):
|
| 17 |
+
marker=root/mode/'reports/groups'/(group['group_id']+'.json')
|
| 18 |
+
if marker.exists():
|
| 19 |
+
return read(marker)
|
| 20 |
+
cache=Path(tempfile.mkdtemp(prefix='dish-exh-'+mode+'-'+str(group['index'])+'-'))
|
| 21 |
+
log=root/mode/'reports/logs'/f'{group["index"]:04d}.log'
|
| 22 |
+
log.parent.mkdir(parents=True,exist_ok=True)
|
| 23 |
+
script=Path(__file__).parent/'runtime.sh'
|
| 24 |
+
command=['bash',str(script),'-m','exhibition_dataset.render','--root',str(root),'--mode',mode,
|
| 25 |
+
'--index',str(group['index']),'--gpu',str(gpu),'--cache-dir',str(cache)]
|
| 26 |
+
restarts=[]
|
| 27 |
+
success=False
|
| 28 |
+
try:
|
| 29 |
+
for attempt in range(1,4):
|
| 30 |
+
started=time.time()
|
| 31 |
+
with log.open('a') as output:
|
| 32 |
+
process=subprocess.Popen(command,stdout=output,stderr=subprocess.STDOUT)
|
| 33 |
+
while process.poll() is None:
|
| 34 |
+
progress=cache/'progress.json'
|
| 35 |
+
last=max(started,progress.stat().st_mtime if progress.exists() else started)
|
| 36 |
+
if time.time()-last>timeout:
|
| 37 |
+
process.kill()
|
| 38 |
+
process.wait()
|
| 39 |
+
restarts.append(dict(attempt=attempt,reason='native_kernel_stall',
|
| 40 |
+
progress=read(progress) if progress.exists() else None))
|
| 41 |
+
break
|
| 42 |
+
time.sleep(1)
|
| 43 |
+
if marker.exists():
|
| 44 |
+
success=True
|
| 45 |
+
result=read(marker)
|
| 46 |
+
write(root/mode/'reports/recovery'/(group['group_id']+'.json'),
|
| 47 |
+
dict(passed=True,attempts=attempt,restarts=restarts,reused_same_recipe=True))
|
| 48 |
+
return result
|
| 49 |
+
restarts.append(dict(attempt=attempt,exit_code=process.returncode,reason='worker_exit'))
|
| 50 |
+
raise RuntimeError('Group '+str(group['index'])+' failed three native attempts; see '+str(log))
|
| 51 |
+
finally:
|
| 52 |
+
if success:
|
| 53 |
+
shutil.rmtree(cache)
|
| 54 |
+
else:
|
| 55 |
+
write(root/mode/'reports/recovery'/(group['group_id']+'.json'),
|
| 56 |
+
dict(passed=False,restarts=restarts,recovery_cache=str(cache)))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def worker(root,mode,processes,prepare_exit_file=None):
|
| 60 |
+
from dynamic_dataset.runtime import ensure_compute
|
| 61 |
+
ensure_compute()
|
| 62 |
+
root=Path(root).resolve()
|
| 63 |
+
queued=set()
|
| 64 |
+
failures=[]
|
| 65 |
+
active={}
|
| 66 |
+
report=root/mode/'reports/worker.status.json'
|
| 67 |
+
started=time.time()
|
| 68 |
+
with ThreadPoolExecutor(max_workers=processes) as executor:
|
| 69 |
+
while True:
|
| 70 |
+
plans=[read(p) for p in sorted((root/'private/plans').glob('*.json'))]
|
| 71 |
+
pending=[g for g in plans if g['index'] not in queued]
|
| 72 |
+
pending.sort(key=lambda g:(['noise','count','controls'].index(g['family_type']),g['index']))
|
| 73 |
+
for group in pending[:max(0,processes-len(active))]:
|
| 74 |
+
future=executor.submit(supervise,root,mode,group,group['index']%8)
|
| 75 |
+
active[future]=group
|
| 76 |
+
queued.add(group['index'])
|
| 77 |
+
for future in list(active):
|
| 78 |
+
if not future.done():
|
| 79 |
+
continue
|
| 80 |
+
group=active.pop(future)
|
| 81 |
+
try:
|
| 82 |
+
result=future.result()
|
| 83 |
+
if not result['passed']:
|
| 84 |
+
raise RuntimeError('Render report did not pass')
|
| 85 |
+
print('COMPLETE',mode,group['index'],round(result['wall_seconds'],1),'s',flush=True)
|
| 86 |
+
except Exception as error:
|
| 87 |
+
failures.append(dict(index=group['index'],group_id=group['group_id'],error=str(error)))
|
| 88 |
+
print('FAILED',mode,group['index'],str(error),flush=True)
|
| 89 |
+
done=len(list((root/mode/'reports/groups').glob('*.json')))
|
| 90 |
+
write(report,dict(mode=mode,phase='rendering',pid=os.getpid(),concurrency=processes,
|
| 91 |
+
plans_available=len(plans),groups_completed=done,active_indices=[g['index'] for g in active.values()],
|
| 92 |
+
failed=failures,wall_seconds=time.time()-started))
|
| 93 |
+
prepared=(root/'reports/prepare.complete.json').exists()
|
| 94 |
+
if prepared and len(queued)==300 and not active:
|
| 95 |
+
break
|
| 96 |
+
if prepare_exit_file and Path(prepare_exit_file).exists() and Path(prepare_exit_file).read_text().strip()!='0':
|
| 97 |
+
raise RuntimeError('Planning failed; do not declare a partial benchmark complete')
|
| 98 |
+
if failures and not active and prepared and not pending:
|
| 99 |
+
break
|
| 100 |
+
time.sleep(5)
|
| 101 |
+
result=dict(passed=not failures and done==300,mode=mode,groups=done,failures=failures,
|
| 102 |
+
wall_seconds=time.time()-started)
|
| 103 |
+
write(root/mode/'reports/render.complete.json',result)
|
| 104 |
+
if not result['passed']:
|
| 105 |
+
raise RuntimeError('Incomplete rendering; resume after correcting the logged failed groups')
|
| 106 |
+
print('FULL RENDER COMPLETE',mode,done,'families',flush=True)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__=='__main__':
|
| 110 |
+
parser=argparse.ArgumentParser()
|
| 111 |
+
parser.add_argument('--root',type=Path,required=True)
|
| 112 |
+
parser.add_argument('--mode',choices=['static','dynamic'],required=True)
|
| 113 |
+
parser.add_argument('--processes',type=int,default=32)
|
| 114 |
+
parser.add_argument('--prepare-exit-file',type=Path)
|
| 115 |
+
a=parser.parse_args()
|
| 116 |
+
worker(a.root,a.mode,a.processes,a.prepare_exit_file)
|