Heiheihaha17's picture
Add files using upload-large-folder tool
347d9a3 verified
Raw History Blame Contribute Delete
22.1 kB
"""Freeze 500 matched speech/layout groups and 2,000 distinct motion scenes."""
from __future__ import annotations
import argparse,copy,shutil
from collections import Counter,defaultdict
from pathlib import Path
import numpy as np
import soundfile as sf
from .common import *
from .geometry import initial_positions,audit
from .inventory import rows as inventory_rows
def default_config(mode='static'):
return dict(schema_version=VERSION,seed=20261001,physical_scene_count=2000,paired_group_count=500,
branch_counts={b:500 for b in BRANCHES},difficulty_counts=dict(easy=1000,hard=1000),
duration_policy=mode,fixed_duration_s=10.,minimum_parent_duration_s=7.5,
sample_rate_hz=SR,evaluation_step_samples=STEP,output_step_s=.2,
source_node_step_s=.2,receiver_node_step_s=.2,motion_model='minimum-jerk horizontal translation; fixed height and yaw',
minimum_moving_displacement_m=2.,maximum_human_speed_mps=.8,maximum_robot_speed_mps=.8,
minimum_entity_clearance_m=.6,wall_and_furniture_clearance_m=.25,
minimum_target_aligned_span_s=4.78,maximum_target_aligned_span_s=6.3,
target_maximum_internal_silence_s=.35,minimum_word_alignment_score=.5,
maximum_word_gap_s=.3,tail_budget_s=2.25,target_material_policy='one contiguous real-speech crop; no internal splicing, inserted silence, repetition or time stretching',
target_policy='All humans are targets of DOA; all human events satisfy continuity. Other tasks select individual humans.',
absent_keyword_policy='real positive prefix from another matched group, absent from current human/robot utterance beginnings',
own_playback_policy='ideal_own_only',strict_sync=True,no_environment_events=True,
waveform_storage='16 kHz float32 WAV, four-channel ACN/SN3D [W,Y,Z,X]',
preview_policy='none; dynamic test recordings are four-channel FOA only',
rir_cache_policy='verified per-group cache on allocated-node temporary storage; archive RIR metadata, not kernels',
scientific_scope='Synthetic quasi-static two-time RIR propagation, not exact Doppler; test-only data, no measured recordings')
class SpeechPool:
def __init__(self,candidates,corpus,root):
self.candidates=candidates;self.corpus=corpus;self.root=root;self.counts=Counter();self.used=set();self.waves={}
def select(self,sid,parent_voice,excluded,start,duration,rng,config):
lo=config['minimum_target_aligned_span_s'];hi=min(config['maximum_target_aligned_span_s'],duration-config['tail_budget_s']-start-.05)
options=[]
for c in self.candidates:
if c['speaker_id'] in excluded or c['aligned_run_duration_s']<lo:continue
options.append(c)
if not options:raise ValueError('Insufficient distinct target voices')
# Prefer original identity if it has suitable long speech; source reuse is balanced.
preferred=[c for c in options if c['speaker_id']==parent_voice]
if preferred:options=preferred+options
jitter={c['source_sha256']:float(rng.uniform(0,.3)) for c in options}
options.sort(key=lambda c:(0 if c['speaker_id']==parent_voice else 1,self.counts[c['source_sha256']]+jitter[c['source_sha256']]))
for c in options:
ws=c['words'];first,last=c['run_word_indices'];windows=[]
for a in range(first,last):
for b in range(a+1,last+1):
span=ws[b-1]['end_s']-ws[a]['start_s']
if span>hi:break
if span>=lo and (c['source_sha256'],a,b) not in self.used:windows.append((a,b))
if not windows:continue
for index in rng.permutation(len(windows))[:50]:
a,b=windows[int(index)]
digest=c['source_sha256'];source=self.corpus/'extracted'/c['original_corpus_path']
if digest not in self.waves:self.waves[digest]=sf.read(source,dtype='float32')[0]
full=self.waves[digest]
left=max(0.,ws[a]['start_s']-.02,(ws[a-1]['end_s']+ws[a]['start_s'])/2 if a else 0.)
right=min(len(full)/SR,ws[b-1]['end_s']+.025,(ws[b-1]['end_s']+ws[b]['start_s'])/2 if b<len(ws) else len(full)/SR)
crop=[round(left*SR),round(right*SR)];offset=round(start*SR)
spans=speech_activity(full[crop[0]:crop[1]],offset)
if not spans or offset+crop[1]-crop[0]>round((duration-config['tail_budget_s'])*SR):continue
evt=dict(event_id=uid(sid,digest,a,b,offset),source_id=sid,
audio_asset='private/assets/sources/'+digest+source.suffix,
original_source_sha256=digest,original_corpus_path=c['original_corpus_path'],
crop_samples=crop,start_sample=offset,end_sample=offset+crop[1]-crop[0],
text=' '.join(w['word'] for w in ws[a:b]),activity_samples=spans,
words=[dict(word=w['word'],start_sample=offset+round(w['start_s']*SR)-crop[0],
end_sample=offset+round(w['end_s']*SR)-crop[0],alignment_score=w['mean_score']) for w in ws[a:b]],
original_word_indices=[a,b],aligner=c['aligner'],aligner_weights_sha256=c['aligner_weights_sha256'],
source_license='CC BY 4.0',source_split='test')
if max_internal_gap([evt])>config['target_maximum_internal_silence_s']:continue
dst=self.root/evt['audio_asset'];dst.parent.mkdir(parents=True,exist_ok=True)
if not dst.exists():shutil.copyfile(source,dst)
if sha(dst)!=digest:raise ValueError('Frozen original checksum mismatch')
self.used.add((digest,a,b));self.counts[digest]+=1
return evt,c['speaker_id'],dict(parent_speaker_id=parent_voice,selected_speaker_id=c['speaker_id'],
identity_reused=c['speaker_id']==parent_voice,maximum_internal_silence_s=max_internal_gap([evt]),
crop_duration_s=(crop[1]-crop[0])/SR,aligned_span_s=ws[b-1]['end_s']-ws[a]['start_s'])
raise ValueError('No unused continuous source crop fits this duration')
def freeze_room(root,room):
folder=root/'assets/room';folder.mkdir(parents=True,exist_ok=True)
from generation.native.build_static_v1_scene import build_glb
surfaces=[(s['name'],s['class_'],s['location'],s['size']) for s in room['layout']['surfaces']]
build_glb(folder/'geometry.glb',surfaces,room['room_id']);shutil.copyfile(folder/'geometry.glb',folder/'geometry.semantic.glb')
for n,text in room['files'].items():(folder/n).write_text(text)
for n,digest in room['asset_hashes'].items():
if sha(folder/n)!=digest:raise ValueError('Frozen room asset checksum mismatch')
write(folder/'layout.json',room['layout'])
def playback(parent,corpus,root,robots):
result=[]
physical={s['source_id']:s for s in parent['physical_scene']['sources']}
for m in parent['materials']:
sid=m['scene_source_id']
if not sid.startswith('R'):continue
source=corpus/'extracted'/m['corpus_path'];digest=m['sha256']
if sha(source)!=digest:raise ValueError('Robot source checksum mismatch')
name='private/assets/sources/'+digest+source.suffix;dst=root/name;dst.parent.mkdir(parents=True,exist_ok=True)
if not dst.exists():shutil.copyfile(source,dst)
wave,rate=sf.read(source,dtype='float32');a=m.get('crop_start_sample',0);b=m.get('crop_end_sample',len(wave));start=round(parent['emission_starts'][sid]*SR)
if rate!=SR or wave.ndim!=1:raise ValueError('Robot speech must be 16 kHz mono')
robot=next(r for r in robots if r['entity_id']==sid)
result.append(dict(entity_id=sid,entity_type='robot',speaker_id=m['speaker_id'],initial_xyz_m=robot['initial_xyz_m'],
yaw_deg=robot['yaw_deg'],displacement_m=[0.,0.,0.],motion_start_s=0.,motion_duration_s=5.,
emitted_rms_dbfs=-25.,events=[dict(event_id=uid('robot',digest,a,b,start),source_id=sid,audio_asset=name,
original_source_sha256=digest,original_corpus_path=m['corpus_path'],crop_samples=[a,b],start_sample=start,end_sample=start+b-a,
text=m['transcript'],activity_samples=speech_activity(wave[a:b],start),words=[],source_license='CC BY 4.0',source_split='test')]))
return result
def choose_keywords(humans,robots,rng):
result={}
for h in humans:
text=tokens(h['events'][0]['text']);sizes=[int(x) for x in rng.permutation([1,2,3])]
for size in sizes:
cue=text[:size]
if sum(tokens(g['events'][0]['text'])[:size]==cue for g in humans)==1:
result[h['entity_id']]=' '.join(cue);break
else:return None
# Robot-only prefixes must not select any human.
robot_candidates=[]
for r in robots:
for e in r['events']:
for size in [1,2,3]:
cue=tokens(e['text'])[:size]
if cue and not any(tokens(h['events'][0]['text'])[:len(cue)]==cue for h in humans):robot_candidates.append(' '.join(cue))
if not robot_candidates:return None
result['robot_only']=str(rng.choice(robot_candidates))
for cue in ['violet lantern','copper moon','silent orchard','velvet compass','amber valley']:
if not any(tokens(e['text'])[:len(tokens(cue))]==tokens(cue) for s in humans+robots for e in s['events']):
result['no_match']=cue;break
if 'no_match' not in result:return None
return result
def construct_group(parent,room,index,pool,root,config,plan_geometry=True):
seed=int(uid(config['seed'],'group',index,parent['scene_id']),16)%2**32;rng=np.random.default_rng(seed)
duration=parent['frames']/SR if config['duration_policy']=='static' else config['fixed_duration_s']
group_id=uid('paired_group',index,parent['scene_id'],config)
template=dict(schema_version=VERSION,scene_group_id=group_id,parent_static_scene_id=parent['scene_id'],split='test',
room_id=room['room_id'],duration_samples=parent['frames'] if config['duration_policy']=='static' else round(duration*SR),
sample_rate_hz=SR,evaluation_step_samples=STEP,strict_sync=True,own_playback_policy='ideal_own_only',
coordinate_convention=dict(world_up='+Y',yaw_zero='world -Z',yaw_positive='toward world +X',azimuth_positive='left'),
motion_model=config['motion_model'],humans=[],robots=[],playback_sources=[])
entities={e['entity_id']:e for e in parent['truth']['entities']}
for r in parent['physical_scene']['robot_poses']:
sid=r['robot_id'];template['robots'].append(dict(entity_id=sid,entity_type='robot',initial_xyz_m=r['microphone_position_m'],yaw_deg=r['yaw_deg'],
displacement_m=[0.,0.,0.],motion_start_s=0.,motion_duration_s=5.,playback_role='playback' if entities[sid]['has_playback'] else 'silent',
coincident_microphone_and_loudspeaker_centers=True))
template['playback_sources']=playback(parent,pool.corpus,root,template['robots'])
excluded={r['speaker_id'] for r in template['playback_sources']};source_qc=[]
for i,original in enumerate([e for e in parent['truth']['entities'] if e['entity_type']=='human']):
sid=original['entity_id'];start=round((.18+.08*i+float(rng.uniform(0,.02)))*SR)/SR
evt,voice,qc=pool.select(sid,original['speaker_id'],excluded,start,duration,rng,config);excluded.add(voice)
template['humans'].append(dict(entity_id=sid,entity_type='human',speaker_id=voice,initial_xyz_m=original['position_world_m'],yaw_deg=0.,
displacement_m=[0.,0.,0.],motion_start_s=evt['words'][0]['start_sample']/SR,
motion_duration_s=(evt['words'][-1]['end_sample']-evt['words'][0]['start_sample'])/SR,
emitted_rms_dbfs=round(float(rng.uniform(-23.,-19.)),3),events=[evt]))
source_qc.append(dict(source_id=sid,**qc))
keywords=choose_keywords(template['humans'],template['playback_sources'],rng)
if keywords is None:raise ValueError('Ambiguous wake prefixes; retry selection')
movement_start=min(h['motion_start_s'] for h in template['humans']);movement_duration=min(h['motion_duration_s'] for h in template['humans'])
for r in template['robots']:r['motion_start_s']=movement_start;r['motion_duration_s']=movement_duration
payload=dict(template=template,parent=parent,room=room,index=index,config=config,seed=seed,group_id=group_id,keywords=keywords,source_qc=source_qc)
return plan_motion(payload) if plan_geometry else payload
def plan_motion(payload):
template=payload['template'];parent=payload['parent'];room=payload['room'];index=payload['index'];config=payload['config']
seed=payload['seed'];group_id=payload['group_id'];keywords=payload['keywords'];source_qc=payload['source_qc']
rng=np.random.default_rng(seed+1);originals=copy.deepcopy(template)
for outer in range(50):
template=copy.deepcopy(originals)
reused=initial_positions(template['robots']+template['humans'],room['layout'],rng,force=outer>0)
scenes=[]
for branch in BRANCHES:
picked=None
for trial in range(120):
scene=copy.deepcopy(template);scene['branch']=branch;scene['difficulty']='easy' if branch.startswith('easy') else 'hard'
moving=[scene['humans'][0]['entity_id']] if branch=='easy_human' else [scene['robots'][index%len(scene['robots'])]['entity_id']] if branch=='easy_robot' else [e['entity_id'] for e in scene['humans']+scene['robots']]
scene['moving_entity_ids']=moving
for e in scene['humans']+scene['robots']:
if e['entity_id'] in moving:
limit=min(2.7,e['motion_duration_s']*.8/1.875-.005)
if limit<=2.005:raise ValueError('Selected speech is too short for >2 m motion')
length=float(rng.uniform(2.005,limit));angle=float(rng.uniform(-np.pi,np.pi))
e['displacement_m']=[length*np.cos(angle),0.,length*np.sin(angle)]
for s in scene['playback_sources']:
r=next(r for r in scene['robots'] if r['entity_id']==s['entity_id'])
for k in ['initial_xyz_m','displacement_m','motion_start_s','motion_duration_s','yaw_deg']:s[k]=copy.deepcopy(r[k])
check=audit(scene,room['layout'],full_visibility=False)
if check is None:continue
check=audit(scene,room['layout'],full_visibility=True)
if check is None:continue
scene['scene_id']=uid(group_id,branch,[e['initial_xyz_m']+e['displacement_m'] for e in scene['humans']+scene['robots']])
scene['geometry_audit']=check;scene['keywords']=keywords;scene['source_quality']=source_qc
scene['initial_geometry_reused']=reused;scene['geometry_attempt']=outer;scene['motion_attempt']=trial
picked=scene;break
if picked is None:break
scenes.append(picked)
if len(scenes)==len(BRANCHES):return dict(schema_version=VERSION,group_id=group_id,index=index,seed=seed,parent_static_scene_id=parent['scene_id'],
parent_static_duration_samples=parent['frames'],room_id=room['room_id'],room=room['layout'],room_assets_sha256=room['asset_hashes'],
foa_mapping=room['mapping'],renderer={**parent['renderer'],'threadCount':2},source_node_step_s=config['source_node_step_s'],
receiver_node_step_s=config['receiver_node_step_s'],source_quality=source_qc,scenes=scenes)
raise ValueError('No unambiguous collision-free motion group in this parent room')
def plan_motion_safe(payload):
try:return plan_motion(payload)
except ValueError as e:return dict(error=str(e),index=payload['index'])
def prepare(release,corpus,inventory,root,mode='static',limit=500):
require_cluster();config=default_config(mode);config['source_catalog_sha256']=sha(corpus/'source_catalog.jsonl');config['parent_release_sha256']=sha(release/'release.json')
config['generation_code_sha256']={name:sha(Path(__file__).parent/name) for name in ['common.py','geometry.py','inventory.py','prepare.py','conditions.py']}
config['native_renderer_code_sha256']=sha(Path(__file__).parent.parent/'dynamic_demo/render.py')
config['speech_inventory_sha256']=sha(inventory/'source_candidates.json')
config_path=root/'config.json'
if config_path.exists() and read(config_path)!=config:raise ValueError('Frozen config changed; use a new dataset root')
write(config_path,config)
candidates=read(inventory/'source_candidates.json');pool=SpeechPool(candidates,corpus,root)
by_room=defaultdict(list)
for p in rows(release/'unified_test.jsonl.gz'):
if p['physical_scene']['humans']>=2 and (mode!='static' or p['frames']/SR>=config['minimum_parent_duration_s']):by_room[p['room_id']].append(p)
rooms={r['room_id']:r for r in rows(release/'rooms.jsonl.gz') if r['split']=='test' and r['room_id'] in by_room}
room_names=sorted(rooms,key=lambda k:uid(config['seed'],k));groups=[]
payloads=[];saved={};parent_usage=Counter();rejections=[]
# Reserve ALL resumed crops before filling any missing index. Loading them
# only in index order would let an early missing group reuse a later crop.
for index in range(limit):
path=root/'private/plans'/f'{index:04d}.json'
if not path.exists():continue
group=read(path);saved[index]=group;parent_usage[group['parent_static_scene_id']]+=1
for human in group['scenes'][0]['humans']:
event=human['events'][0];pool.used.add((event['original_source_sha256'],*event['original_word_indices']));pool.counts[event['original_source_sha256']]+=1
for index in range(limit):
paths=root/'private/plans'/f'{index:04d}.json'
if index in saved:continue
room_id=room_names[index%len(room_names)];parents=sorted(by_room[room_id],key=lambda p:(p['physical_scene']['humans']!=2+int(index%3==2),parent_usage[p['scene_id']],uid(index,p['scene_id'])))
payload=None
for parent in parents:
try:payload=construct_group(parent,rooms[room_id],index,pool,root,config,plan_geometry=False)
except ValueError as e:
print('MATERIAL RETRY',index,str(e),flush=True);continue
parent_usage[parent['scene_id']]+=1;break
if payload is None:raise RuntimeError('No continuous materials for room '+room_id)
payloads.append(payload)
from concurrent.futures import ProcessPoolExecutor
workers=min(16,max(1,limit));results=[]
with ProcessPoolExecutor(max_workers=workers) as executor:
futures=[executor.submit(plan_motion_safe,p) for p in payloads]
for payload,future in zip(payloads,futures):
result=future.result();index=payload['index']
if 'error' in result:
rejections.append(dict(index=index,room_id=payload['room']['room_id'],reason=result['error']))
# Preserve valid physics rather than force a path into an unsuitable room.
result=None
for offset in range(1,len(room_names)+1):
alternate=room_names[(index+offset)%len(room_names)]
parents=sorted(by_room[alternate],key=lambda p:(parent_usage[p['scene_id']],uid(index,p['scene_id'])))
for parent in parents[:3]:
try:attempt=construct_group(parent,rooms[alternate],index,pool,root,config)
except ValueError:continue
result=attempt;parent_usage[parent['scene_id']]+=1;break
if result is not None:break
if result is None:raise RuntimeError('No legal motion group for index '+str(index))
saved[index]=result
canonical_room=root/'public/assets/rooms'/result['room_id']
if not (canonical_room/'assets/room/geometry.glb').exists():freeze_room(canonical_room,rooms[result['room_id']])
write(root/'private/plans'/f'{index:04d}.json',result)
print('PREPARED GROUP',index,result['group_id'],result['room_id'],flush=True)
groups=[saved[i] for i in range(limit)]
if len(groups)>1:
from .conditions import finalize
groups=finalize(groups)
for group in groups:write(root/'private/plans'/f"{group['index']:04d}.json",group)
write(root/'reports/geometry_rejections.json',rejections)
pool.counts=Counter(e['original_source_sha256'] for g in groups for h in g['scenes'][0]['humans'] for e in h['events'])
pool.used={(e['original_source_sha256'],*e['original_word_indices']) for g in groups for h in g['scenes'][0]['humans'] for e in h['events']}
jsonl(root/'private/recipes.jsonl',groups)
write(root/'reports/plan.json',dict(prepared_groups=len(groups),physical_scenes=len(groups)*4,target_physical_scenes=2000,
rooms=len({g['room_id'] for g in groups}),parents=len({g['parent_static_scene_id'] for g in groups}),
branches=dict(Counter(s['branch'] for g in groups for s in g['scenes'])),humans=dict(Counter(len(g['scenes'][0]['humans']) for g in groups)),
receivers=dict(Counter(len(g['scenes'][0]['robots']) for g in groups)),source_originals=len(pool.counts),
source_crops=len(pool.used),source_reuse_maximum=max(pool.counts.values(),default=0),
duration_policy=mode,source_quality_check=True,grouped_sampling_unit='500 paired motion groups; views and tasks are not independent scenes'))
print('PLAN COMPLETE',len(groups)*4,'physical scenes',flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--release',type=Path,required=True);p.add_argument('--corpus',type=Path,required=True);p.add_argument('--inventory',type=Path,required=True)
p.add_argument('--root',type=Path,required=True);p.add_argument('--duration-mode',choices=['static','fixed10'],default='static');p.add_argument('--groups',type=int,default=500)
a=p.parse_args();prepare(a.release,a.corpus,a.inventory,a.root,a.duration_mode,a.groups)