zhizeng115's picture
Complete four-task dataset and portable code release
7e7a152 verified
Raw History Blame Contribute Delete
6.33 kB
"""Observation-gated silver expert. Off-screen direction never uses target bearing."""
import json,sys,hashlib,random,collections,math
from pathlib import Path
R=Path(__file__).resolve().parents[2];sys.path[:0]=[str(R),str(R/'tools')]
from hvs_core import bbox_visible_fraction,circular_delta,in_interval
from sound_search_core import score
from training.hvs_audio_fourtask.data import ActionDataset,load_image,policy_messages
def read(p):return [json.loads(l) for l in Path(p).open() if l.strip()]
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def atomic(p,x):
p=Path(p);p.parent.mkdir(parents=True,exist_ok=True);t=p.with_suffix('.tmp');t.write_text(json.dumps(x,indent=2));t.replace(p)
def target(e):
l=e['label'];return (l['center'],l['source_bbox'],l.get('visible_pixels',0)) if e['task']=='HOS' else tuple(l['candidates'][l['target_index']][k] for k in ['center','bbox','visible_pixels'])
def visible(e,pose):
center,bbox,pixels=target(e)
return pixels>0 and bbox_visible_fraction(bbox,(512,2048),*pose)>=.5
def expert(e,pose):
# This gate is an annotation-derived viewport proxy, not a pixel-level recognizer.
# A target outside the current viewport can never affect the exploration action.
if not visible(e,pose):return 'rotate',60,int(-15-pose[1]),'explore'
center,_,_=target(e);dy=round(circular_delta(center[0],pose[0]));dp=round(center[1]-pose[1])
if abs(dy)<=8 and abs(dp)<=5:return 'submit',int(pose[0]),int(pose[1]),'confirm'
return 'rotate',max(-60,min(60,dy)),max(-30,min(30,dp)),'align'
def result(e,pose,submitted):
if e['task']!='HOS':return score(pose,e['label'],submitted)['success']
a=e['label']['annotation'];return bool(submitted and in_interval(pose[0],a['yaw'],True,30) and in_interval(pose[1],a['pitch'],False,20))
def pose_after(pose,op,y,p):return pose[:] if op=='submit' else [(pose[0]+y)%360,max(-90,min(90,pose[1]+p))]
def seed_for(s):return int(hashlib.sha256(s.encode()).hexdigest()[:12],16)
def build(cfg):
out=Path(cfg['output_root'])/'data';out.mkdir(parents=True,exist_ok=True)
maps={e['id']:e for e in read(R/'datasets/omini_360_benchmark_v0_1/private/episode_map.jsonl')}
sound={e['id']:e for e in read(R/'datasets/omini_sound_search_v1/private/labels.jsonl')}
audit=dict(test_targets_used=False,source_audit_sha=sha(Path(cfg['source_data'])/'audit.json'),splits={},limitations=['Viewport gate is spherical bbox silver proxy, not pixel segmentation or human confirmation.','Same-class sound-source binding remains annotation-supervised; asset/pretraining exposure unknown.','Fixed scan is target-independent but is not an optimal exploration planner.'])
identities={}
for split in ['train','validation']:
old=read(Path(cfg['source_data'])/f'{split}.jsonl');first={}
for row in old:first.setdefault(row['episode_id'],row)
labels={l['task_id']:l for l in read(R/f'datasets/omini_360_benchmark_v0_1/private/static_labels/hos_{split}.jsonl')}
episodes=[]
for eid,row in sorted(first.items()):
label=labels[maps[eid]['task_id']] if row['task']=='HOS' else sound[eid];assert label['split']==split
episodes.append(dict(id=eid,task=row['task'],split=split,scene=row['scene'],clip_id=row['clip_id'],instruction=row['instruction'],initial_pose=row['pose'],panorama=row['observations'][-1]['panorama'],audio_path=row['audio_path'],label=label))
identities[split]={k:{e[k] for e in episodes} for k in ['scene','clip_id']}
rows=[];kinds=collections.Counter();excluded=[]
for e in episodes:
for variant in range(3 if split=='train' else 1):
rng=random.Random(seed_for(e['id']+str(variant)));pose=e['initial_pose'][:];hist=[]
if variant:
# Inject physically executed, target-independent mistakes; teach recovery only.
for _ in range(variant):
dy=rng.choice([-120,-90,-45,45,90,120]);dp=rng.choice([-15,0,15]);action=f'<answer>rotate({dy},{dp})</answer>'
hist.append((pose[:],action));pose=pose_after(pose,'rotate',dy,dp)
pending=[];submitted=False
for step in range(10-variant):
op,y,p,kind=expert(e,pose);action=f'<answer>{op}({y},{p})</answer>'
if kind=='explore':assert (y,p)==(60,-15-pose[1]) and not visible(e,pose)
if op=='submit':assert visible(e,pose) and result(e,pose,True)
hs=hist[-2:];pending.append(dict(id=f"{e['id']}:v{variant}:{step}",episode_id=e['id'],task=e['task'],split=split,scene=e['scene'],clip_id=e['clip_id'],instruction=e['instruction'],pose=pose[:],observations=[dict(panorama=e['panorama'],pose=x[0]) for x in hs]+[dict(panorama=e['panorama'],pose=pose[:])],history_actions=[x[1] for x in hs],audio_path=e['audio_path'],audio_end_s=10. if e['audio_path'] else None,reference=None,dynamic=False,answers=[action],supervision_kind=kind,recovery_prefix_steps=variant))
hist.append((pose[:],action));pose=pose_after(pose,op,y,p)
if op=='submit':submitted=True;break
# Never label an unobserved object with a privileged turn or false submit.
if not submitted:excluded.append(dict(id=e['id'],variant=variant,reason='visibility-gated expert did not succeed within budget'))
for row in pending:rows.append(row);kinds[row['supervision_kind']]+=1
for name,values in [(f'{split}.jsonl',rows),(f'{split}_episodes.jsonl',episodes)]:
p=out/name;s=''.join(json.dumps(x,ensure_ascii=False)+'\n' for x in values)
if p.exists():assert p.read_text()==s,'Data drift'
else:p.write_text(s)
audit['splits'][split]=dict(rows=len(rows),episodes=len(episodes),tasks=dict(collections.Counter(r['task'] for r in rows)),kinds=dict(kinds),recovery_rows=sum(r['recovery_prefix_steps']>0 for r in rows),incomplete_expert_trajectories=excluded,sha256=sha(out/f'{split}.jsonl'),episodes_sha256=sha(out/f'{split}_episodes.jsonl'))
for k in identities['train']:assert not identities['train'][k]&identities['validation'][k]
oldaudit=json.loads((Path(cfg['source_data'])/'audit.json').read_text());assert oldaudit['train_validation_test_scene_clip_disjoint'];audit['train_validation_test_scene_clip_disjoint']=True
# Outputs sent to the model are whitelisted in ActionDataset; labels never enter prompts.
atomic(out/'audit.json',audit);print(json.dumps({k:{q:v for q,v in a.items() if q!='incomplete_expert_trajectories'} for k,a in audit['splits'].items()}))
if __name__=='__main__':build(json.loads(Path(__file__).with_name('config.json').read_text()))