WitneyWW's picture
Add files using upload-large-folder tool
9ade843 verified
Raw History Blame Contribute Delete
4.78 kB
"""Score AEA single-person protocol clips for spatial completeness + spatial-audio usefulness."""
import json, os, math, re, numpy as np
B = '/mnt/work_new/weihanxu/aea_filtered_1105'
AEA = '/mnt/data_new/AEA'
STATIONARY = re.compile(r'fry|sizzl|cook|boil|kettle|microwave|water|faucet|tap run|sink|wash|dryer|fan|tv|music|timer|alarm|beep|ring|bell|blender|grind|coffee|machine|toaster|hum|vacuum|oven|extractor|radio|phone', re.I)
SKIP = re.compile(r'speech|mic|exhal|breath|laugh|footstep|movement|rustl|fabric|cough|sniff', re.I)
def quat_rot(q):
x, y, z, w = q
return np.array([[1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)],
[2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)],
[2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)]])
def load_traj(rec):
tg = json.load(open(f'{B}/annotations/legacy/traj_gaze/{rec}.json'))
t0 = float(tg[0]['tracking_timestamp']) - tg[0]['frame_index'] / 20.0
T, R = [], []
for x in tg:
if x['trajectory']:
T.append(float(x['tracking_timestamp']) - t0); R.append(quat_rot(x['trajectory']['orientation_quaternion']))
R = np.array(R)
# choose the device axis that is most horizontal on average (world z = up)
horiz = [np.mean(1 - np.abs(R[:, 2, k])) for k in range(3)]
k = int(np.argmax(horiz)); fwd = R[:, :, k]
yaw = np.unwrap(np.arctan2(fwd[:, 1], fwd[:, 0]))
return t0, np.array(T), yaw, len(tg), sum(1 for x in tg if x['trajectory'])
def official(rec):
p = f'{AEA}/{rec}/mps'
has = lambda f: os.path.exists(f'{p}/{f}') and os.path.getsize(f'{p}/{f}') > 0
return {'closed_loop': has('slam/closed_loop_trajectory.csv'), 'calib': has('slam/online_calibration.jsonl'),
'eye_gaze': has('eye_gaze/general_eye_gaze.csv'), 'semidense_points': has('slam/semidense_points.csv.gz'),
'speech_csv': os.path.exists(f'{AEA}/{rec}/speech.csv'), 'vrs': os.path.exists(f'{AEA}/{rec}/recording.vrs')}
def main():
idx = json.load(open(f'{B}/index.json'))
cache, out = {}, []
for c in idx['protocol_clips']:
rec = c['recording']
if rec not in cache: cache[rec] = load_traj(rec)
t0, T, yaw, nf, nt = cache[rec]
a, b = c['clip_start_sec'], c['clip_end_sec']
sounds = json.load(open(f'{B}/annotations/legacy/sound/{rec}_sound.json'))
ev = []
for e in sounds:
s, t = e['start_time'] - t0, e['stop_time'] - t0
if t < a or s > b or SKIP.search(e['sound_event'] + ' ' + e.get('object', '')): continue
s, t = max(s, a), min(t, b)
m = (T >= s) & (T <= max(t, s + 0.05))
if not m.any(): continue
y0 = yaw[m][0]
# head turn within the event and 2 s after onset (orienting)
m2 = (T >= s) & (T <= s + 2.0)
turn = float(np.degrees(np.max(np.abs(yaw[m2] - y0)))) if m2.any() else 0.0
stat = bool(STATIONARY.search(e['sound_event'] + ' ' + e.get('object', '')))
off = float(np.sum(np.abs(np.degrees(yaw[m] - y0)) > 60) / 20.0) if stat else 0.0
ev.append({'label': e['sound_event'], 'object': e.get('object', ''), 'start': round(s, 2), 'end': round(t, 2),
'stationary': stat, 'offaxis_sec': round(off, 2), 'turn_deg_2s': round(turn, 1)})
mc = (T >= a) & (T <= b)
yaw_range = float(np.degrees(np.ptp(yaw[mc]))) if mc.any() else 0
traj_cov = float(mc.sum() / max(1, (b - a) * 20))
off = official(rec)
sp_complete = sum([off['closed_loop'], off['calib'], off['eye_gaze']]) + (traj_cov > 0.9)
n_ev = len(ev); n_stat = sum(e['stationary'] for e in ev)
off_sec = sum(e['offaxis_sec'] for e in ev); n_turn = sum(e['turn_deg_2s'] > 45 for e in ev)
dur = b - a
out.append({**{k: c[k] for k in ('seg_id', 'recording', 'goal', 'steps', 'clip_start_sec', 'clip_end_sec', 'protocol_score', 'clip')},
'duration_sec': round(dur, 1), 'official': off, 'traj_coverage_20fps': round(traj_cov, 3),
'spatial_complete_0to4': sp_complete, 'head_yaw_range_deg': round(yaw_range, 1),
'n_sound_events': n_ev, 'n_stationary_sound': n_stat, 'offaxis_sound_sec': round(off_sec, 1),
'n_orienting_turns': n_turn, 'sound_events': ev})
json.dump(out, open(os.path.join(os.path.dirname(__file__), 'scores.json'), 'w'), indent=1, ensure_ascii=False)
for o in sorted(out, key=lambda o: -o['offaxis_sound_sec']):
print(f"{o['seg_id']:34s} {o['duration_sec']:6.0f}s sp={o['spatial_complete_0to4']} ev={o['n_sound_events']:3d} stat={o['n_stationary_sound']:3d} off={o['offaxis_sound_sec']:6.1f}s turn={o['n_orienting_turns']:3d} yawR={o['head_yaw_range_deg']:6.0f} {o['goal'][:45]}")
main()