Download code/training/hvs_audio_fourtask/data.py from zhizeng115/EchoScout-FourTask: direct link, hf CLI and curl.
- Browser
- Download file 8.39 kB
-
https://huggingface.co/datasets/zhizeng115/EchoScout-FourTask/resolve/main/code/training/hvs_audio_fourtask/data.py
- Command line
-
hf download hf://datasets/zhizeng115/EchoScout-FourTask/code/training/hvs_audio_fourtask/data.py
-
curl -L -o data.py https://huggingface.co/datasets/zhizeng115/EchoScout-FourTask/resolve/main/code/training/hvs_audio_fourtask/data.py
8.39 kB
| """Four-task data. Test identity metadata is exclusion-only; no test targets enter training.""" | |
| import json,hashlib,collections,random,re | |
| from pathlib import Path | |
| ROOT=Path(__file__).resolve().parents[2] | |
| TASKS=['HOS','sound_class','duration','order'] | |
| 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 build(cfg): | |
| out=Path(cfg['data_output']);out.mkdir(parents=True,exist_ok=True) | |
| held={s:{k:set() for k in ['scene','clip_id']} for s in ['validation','test']} | |
| for name,meta in [('omini_360_benchmark_v0_1','private/episode_map.jsonl'),('omini_sound_search_v1','private/labels.jsonl')]: | |
| ds=ROOT/'datasets'/name;mp={x['id']:x for x in read(ds/meta)} | |
| for split in held: | |
| for e in read(ds/'public'/f'{split}.jsonl'): | |
| if name.startswith('omini_360') and e['task_type']!='HOS':continue | |
| for k in held[split]:held[split][k].add(mp[e['id']][k]) | |
| audit=dict(tasks=TASKS,test_targets_used=False,source_hashes={},splits={},limitations=['Pretrained HVS and audio encoder exposure is unknown.','Object and audio asset disjointness not established.','Existing trajectories use geometric expert supervision; partially observed oracle ambiguity remains.']) | |
| identities={} | |
| for split in ['train','validation']: | |
| rows=[];reject=collections.Counter() | |
| for category in ['static','sound']: | |
| p=Path(cfg['sources'][category])/f'{split}.jsonl';audit['source_hashes'][str(p)]=sha(p) | |
| rs=read(p) | |
| if category=='static':rs=[r for r in rs if r['task']=='HOS' and r.get('source')=='custom'] | |
| groups=collections.defaultdict(list) | |
| for r in rs: | |
| assert r['task'] in TASKS and r['split']==split | |
| groups[r['episode_id']].append(r) | |
| for eid,seq in groups.items(): | |
| seq.sort(key=lambda r:r['step']) | |
| if any(r[k] in held[h][k] for r in seq for h in (['validation','test'] if split=='train' else ['test']) for k in ['scene','clip_id']): | |
| reject[category]+=len(seq);continue | |
| for i,r in enumerate(seq): | |
| hist=seq[max(0,i-2):i+1] | |
| assert all(hist[j+1]['step']==hist[j]['step']+1 for j in range(len(hist)-1)) | |
| # HOS is explicitly visual only. Sound tasks use the full recording before frozen-frame search. | |
| rows.append(dict(id=category+':'+r['id'],task=r['task'],split=split,episode_id=eid,scene=r['scene'],clip_id=r['clip_id'],instruction=r['instruction'],pose=r['pose'],observations=[dict(panorama=x['panorama'],pose=x['pose']) for x in hist],history_actions=[x['answer'] for x in hist[:-1]],audio_path=r.get('audio_path') if category=='sound' else None,audio_end_s=10. if category=='sound' else None,reference=None,dynamic=False,answers=[r['answer']])) | |
| assert set(r['task'] for r in rows)==set(TASKS) | |
| assert len(rows)==len({r['id'] for r in rows}) | |
| identities[split]={k:{r[k] for r in rows} for k in ['scene','clip_id']} | |
| p=out/f'{split}.jsonl';content=''.join(json.dumps(r)+'\n' for r in rows) | |
| if p.exists():assert p.read_text()==content,'Frozen dataset drift' | |
| else:p.write_text(content) | |
| audit['splits'][split]=dict(rows=len(rows),tasks=dict(collections.Counter(r['task'] for r in rows)),scenes=len(identities[split]['scene']),clips=len(identities[split]['clip_id']),excluded=dict(reject),sha256=sha(p),first_submit=dict(collections.Counter(r['task'] for r in rows if 'submit(' in r['answers'][0]))) | |
| for k in identities['train']:assert not identities['train'][k]&identities['validation'][k] | |
| audit['train_validation_test_scene_clip_disjoint']=True | |
| (out/'audit.json').write_text(json.dumps(audit,indent=2));return audit | |
| def load_image(desc): | |
| import cv2 | |
| from PIL import Image | |
| from hvs_core import perspective | |
| if 'image' in desc: | |
| with Image.open(desc['image']) as im:return im.convert('RGB') | |
| if 'video' in desc: | |
| cap=cv2.VideoCapture(desc['video']);assert cap.isOpened();cap.set(cv2.CAP_PROP_POS_FRAMES,desc['frame']);ok,pano=cap.read();cap.release();assert ok,desc | |
| else:pano=cv2.imread(desc['panorama']);assert pano is not None | |
| return Image.fromarray(cv2.cvtColor(perspective(pano,*desc['pose']),cv2.COLOR_BGR2RGB)) | |
| def policy_messages(row): | |
| c=[] | |
| if row['reference']:c.extend([{'type':'text','text':'First-frame target identity reference:'},{'type':'image'}]) | |
| for i,_ in enumerate(row['observations']): | |
| c.extend([{'type':'text','text':'Current observation:' if i==len(row['observations'])-1 else 'Historical observation:'},{'type':'image'}]) | |
| if i<len(row['history_actions']):c.append({'type':'text','text':'Previous action: '+row['history_actions'][i]}) | |
| if row.get('audio_path'):c.append({'type':'text','text':'<|audio_start|>'+'<|audio_pad|>'*41+'<|audio_end|>'+f"Audio ends at {row['audio_end_s']:.1f}s; microphone orientation is fixed, independent of camera rotation."}) | |
| task='Each rotation advances 0.2 seconds. Track the reference. Only rotate: dyaw in [-30,30], dpitch in [-15,15].' if row['dynamic'] else 'Rotate to find the requested object, then submit the CURRENT pose. dyaw in [-180,180], dpitch in [-90,90].' | |
| c.append({'type':'text','text':row['instruction']+f"\nCurrent yaw,pitch={row['pose']}. "+task+' Return exactly one next action in <answer> tags.'}) | |
| return [{'role':'system','content':'Control a camera using only causal observations. Positive yaw right, positive pitch up. Return one action without explanation.'},{'role':'user','content':c}] | |
| class ActionDataset: | |
| def __init__(self,path,proc,max_length):self.rows=read(path);self.proc=proc;self.max_length=max_length | |
| def __len__(self):return len(self.rows) | |
| def __getitem__(self,i): | |
| import torch,numpy as np,soundfile as sf | |
| from PIL import Image | |
| r=self.rows[i];images=[] | |
| if r['reference']: | |
| with Image.open(r['reference']) as im:images.append(im.convert('RGB')) | |
| images.extend(load_image(x) for x in r['observations']) | |
| messages=policy_messages(r) | |
| messages[-1]['content'][-1]['text']=messages[-1]['content'][-1]['text'].replace('Return exactly one next action in <answer> tags.','Return exactly one next action in <answer> tags.') | |
| messages[0]['content']='Control a camera using only causal observations. Positive yaw right, positive pitch up. Return one action without explanation.' | |
| text=self.proc.apply_chat_template(messages,tokenize=False,add_generation_prompt=True) | |
| b=dict(self.proc(text=[text],images=images,return_tensors='pt')) | |
| target=torch.tensor([self.proc.tokenizer.encode(r['answers'][0]+'<|im_end|>',add_special_tokens=False)],dtype=torch.long) | |
| n=b['input_ids'].shape[1] | |
| b['input_ids']=torch.cat([b['input_ids'],target],dim=1) | |
| b['attention_mask']=torch.ones_like(b['input_ids']) | |
| b['labels']=b['input_ids'].clone();b['labels'][:,:n]=-100 | |
| assert b['input_ids'].shape[1]<=self.max_length | |
| if r.get('audio_path'): | |
| from omini.data.staqa_preprocessing import prepare_staqa_waveform | |
| with sf.SoundFile(r['audio_path']) as f:sr=f.samplerate;wave=f.read(frames=int(sr*r['audio_end_s']),dtype='float32',always_2d=True) | |
| assert wave.shape[1]==2 and np.isfinite(wave).all() | |
| b['audio']=prepare_staqa_waveform(wave,sr).unsqueeze(0) | |
| return b | |
| def inverse_messages(): | |
| return [dict(role='system',content='Infer relative camera rotation from overlapping views of a static scene.'),dict(role='user',content=[dict(type='text',text='Before rotation:'),dict(type='image'),dict(type='text',text='After rotation:'),dict(type='image'),dict(type='text',text='Both views have 100-degree horizontal field of view. Positive yaw is right and positive pitch is up. Return exactly <answer>rotate(dyaw,dpitch)</answer> in integer degrees.')])] | |
| def inverse_batch(row,proc,max_length,seed): | |
| import torch | |
| rng=random.Random(seed);before=row['pose'];dy=rng.choice([-45,-30,-15,15,30,45]);dp=rng.choice([-15,0,15]) | |
| after=[(before[0]+dy)%360,max(-75,min(75,before[1]+dp))];dp=after[1]-before[1] | |
| assert abs(dp)<=90 | |
| desc=row['observations'][-1] | |
| pics=[load_image(dict(panorama=desc['panorama'],pose=p)) for p in [before,after]] | |
| text=proc.apply_chat_template(inverse_messages(),tokenize=False,add_generation_prompt=True) | |
| b=dict(proc(text=[text],images=pics,return_tensors='pt'));n=b['input_ids'].shape[1] | |
| target=torch.tensor([proc.tokenizer.encode(f'<answer>rotate({dy},{dp})</answer><|im_end|>',add_special_tokens=False)]) | |
| b['input_ids']=torch.cat([b['input_ids'],target],1);b['attention_mask']=torch.ones_like(b['input_ids']);b['labels']=b['input_ids'].clone();b['labels'][:,:n]=-100 | |
| assert b['input_ids'].shape[1]<=max_length | |
| return b | |