"""Shared frozen protocol helpers for the full dynamic test set.""" from __future__ import annotations import gzip,hashlib,json,math,os,socket from pathlib import Path from datetime import datetime,timezone import numpy as np from dynamic_demo.common import SR,active,angular,sha,speech_activity,tokens STEP=3200 VERSION='dish_dynamic_test_v1' BRANCHES=['easy_human','easy_robot','hard_joint_a','hard_joint_b'] def now():return datetime.now(timezone.utc).isoformat() def require_cluster(): if 'debug' in socket.gethostname().lower() or not os.environ.get('KUBERNETES_SERVICE_HOST'): raise RuntimeError('Generation, rendering and full acceptance require an allocated CPU job') def uid(*parts):return hashlib.sha256(json.dumps((VERSION,)+parts,sort_keys=True,separators=(',',':')).encode()).hexdigest()[:24] def read(path):return json.loads(Path(path).read_text()) def rows(path): opener=gzip.open if str(path).endswith('.gz') else open with opener(path,'rt') as f: for line in f: if line.strip():yield json.loads(line) def write(path,value): p=Path(path);p.parent.mkdir(parents=True,exist_ok=True);tmp=p.with_name(p.name+'.'+str(os.getpid())+'.tmp') tmp.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False)+'\n');tmp.replace(p) def jsonl(path,values): p=Path(path);p.parent.mkdir(parents=True,exist_ok=True);tmp=p.with_name(p.name+'.'+str(os.getpid())+'.tmp') with tmp.open('w') as f: for v in values:f.write(json.dumps(v,ensure_ascii=False,separators=(',',':'),allow_nan=False)+'\n') tmp.replace(p) def position(entity,t): u=np.clip((np.asarray(t,dtype=float)-entity.get('motion_start_s',0.))/entity['motion_duration_s'],0.,1.) s=10*u**3-15*u**4+6*u**5 return np.asarray(entity['initial_xyz_m'])+np.expand_dims(s,-1)*np.asarray(entity['displacement_m']) def velocity(entity,t): raw=(np.asarray(t,dtype=float)-entity.get('motion_start_s',0.))/entity['motion_duration_s'] u=np.clip(raw,0.,1.);speed=(30*u**2-60*u**3+30*u**4)/entity['motion_duration_s'] return np.expand_dims(speed,-1)*np.asarray(entity['displacement_m']) def geometry(source,receiver,t): x,y,z=map(float,position(source,t)-position(receiver,t)) az=(-(math.degrees(math.atan2(x,-z))-receiver['yaw_deg'])+180)%360-180 return dict(doa_deg=[az,math.degrees(math.atan2(y,math.hypot(x,z)))], distance_m=math.sqrt(x*x+y*y+z*z),xyz_m=position(source,t).tolist()) def grid(scene):return list(range(0,scene['duration_samples'],STEP)) def nodes(entity,step): if not np.any(entity['displacement_m']):return [0.] start=entity.get('motion_start_s',0.);end=start+entity['motion_duration_s'] return sorted(set([0.,round(start,9),round(end,9)]+[round(float(t),9) for t in np.arange(start,end,step)])) def max_internal_gap(events): spans=sorted([pair for e in events for pair in e['activity_samples']]) if not spans:raise ValueError('No emitted target speech') merged=[] for a,b in spans: if merged and a<=merged[-1][1]:merged[-1][1]=max(merged[-1][1],b) else:merged.append([a,b]) return max(((b[0]-a[1])/SR for a,b in zip(merged,merged[1:])),default=0.)