Datasets:
Download code/robohome/src/tools/asset_curation/pub9_pose.py from RoboParty/RoboHome: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/tools/asset_curation/pub9_pose.py
- Command line
-
hf download hf://datasets/RoboParty/RoboHome@86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/tools/asset_curation/pub9_pose.py
-
curl -L -o pub9_pose.py https://huggingface.co/datasets/RoboParty/RoboHome/resolve/86ffa4ecc1047bb404fdc283987bd22cbc259a96/code/robohome/src/tools/asset_curation/pub9_pose.py
12.3 kB
| #!/usr/bin/env python3 | |
| """Pose correction for HSSD assets whose authored up axis is -Z (authored csv + real scene placements + producer conflict all agree). | |
| Correct source->canonical rotation M' = diag(1,-1,-1): (x,y,z)->(x,-y,-z) (local -Z becomes canonical +Z). | |
| Publishes a replacement release (identity transform, geometry bounds, pose record, pool status) and a v6 retrieval db.""" | |
| import curation_paths as paths | |
| import copy,csv,glob,hashlib,json,math,os,shutil,sqlite3,sys,time,collections as C | |
| from pathlib import Path | |
| sys.path.insert(0,paths.S); import front_evidence_extension as fee | |
| R=paths.R; W=paths.W; A=paths.A | |
| DRY=len(sys.argv)>1 and sys.argv[1]=='dry'; OUT=Path(os.environ['OUTDIR']); | |
| CSV=paths.B+'/semantics/objects.csv' | |
| PARENT=Path(os.environ['PARENT']) | |
| M_OLD=[1,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,1]; M_NEW=[1,0,0,0,0,-1,0,0,0,0,-1,0,0,0,0,1] | |
| csvrows={r['id']:r for r in csv.DictReader(open(CSV))}; csv_sha=fee.sha256(CSV) | |
| scene=json.load(open(W+'/out/pose_scene_up.json')); sev={s['asset_id']:s for s in scene} | |
| swe={s['asset_id']:s for s in json.load(open(W+'/out/pose_scene_evidence.json'))} | |
| FIX={a for a,s in sev.items() if s['scene_up']=='-Z' and s['consistency']>=.9 and csvrows.get(a.split('/')[-1],{}).get('up')=='0,0,-1' | |
| and s['producer_source_up']==[0,0,-1] and s['producer_current_up']==[0,1,0]} | |
| FALSE={a for a,s in sev.items() if s['scene_up']=='+Y' and s['consistency']>=.9} | |
| DEC=json.load(open(W+'/out/front_decisions.json'))['decisions'] | |
| CSVONLY={a for a,d in DEC.items() if d['source']=='csv' and a not in FIX and a not in FALSE} | |
| ALLSEL=FIX|FALSE|CSVONLY | |
| FR_FRAME='canonical right-handed Z-up; positive axis points outward from access face' | |
| def set_front(row,aid,d,matrix): | |
| ff=row['attributes'].get('functional_front') or {} | |
| if ff.get('status')!='unknown': stats['front_skip_already_'+str(ff.get('status'))]+=1; return False | |
| reg=row['evidence_registry'] | |
| if 'authored_front_certificate' in reg or 'authored_front_table' in reg: stats['front_skip_collision']+=1; return False | |
| c=d['csv']; axis=d['axis'] | |
| cert=dict(schema='rhg.functional_front_evidence.authored.v1',record_id=row['record_id'],asset_id=aid,source_sha256=row['identity']['source']['value']['sha256'], | |
| runtime_sha256=row['identity']['runtime']['value']['sha256'],canonical_transform=[float(x) for x in matrix],canonical_axis=axis,scene_yaw_already_applied=False,geometry_changed=False, | |
| evidence_kind='authored_source_front',review_status='inferred',reviewer='automated:authored_source_front_v1', | |
| authored=dict(table_uri=CSV,table_sha256=csv_sha,row_id=c['row_id'],name=c['name'],up=c['up'],front=c['front']), | |
| rationale='The dataset authors annotated this object with up=%s and front=%s in its source frame; rotated into the canonical frame by the asset transform the front is %s.'%(c['up'],c['front'],axis), | |
| limits='Dataset-authored annotation, re-derived at consumption; not independently verified against geometry or by a human reviewer.', | |
| scope='static_authored_front_not_articulation_clearance_or_dynamics') | |
| ep=OUT/'evidence'/('front_'+hashlib.sha256(row['record_id'].encode()).hexdigest()[:16]+'.json'); fee._write(ep,cert) | |
| reg['authored_front_certificate']=dict(fee._ref(ep),kind='authored_front_certificate_file') | |
| reg['authored_front_table']=dict(uri=CSV,sha256=csv_sha,kind='source_authored_front_table') | |
| row['attributes']['functional_front']=dict(status='inferred',confidence=.9,value=dict(axis=axis,axis_frame=FR_FRAME,certificate='authored_front_certificate',evidence_kind='authored_source_front'), | |
| evidence=['authored_front_certificate','authored_front_table'],provenance=dict(method='authored_source_front',reviewer='automated:authored_source_front_v1', | |
| confidence_basis='pipeline minimum, not a probability',limitations='Dataset-authored front, re-derived at consumption; no geometry or physical qualification changed')) | |
| stats['front_set']+=1; return True | |
| print('FIX',len(FIX),'FALSE_POSITIVE',len(FALSE),'dry' if DRY else 'WRITE',flush=True) | |
| def swapdims(d): return [d[0],d[2],d[1]] | |
| def newbbox(bb): (x0,y0,z0),(x1,y1,z1)=bb; return [[x0,-z1,y0],[x1,-z0,y1]] | |
| def fix_geometry(g,notes): | |
| v=g['value'] | |
| d=swapdims(v['dimensions_xyz_m']); v['dimensions_xyz_m']=d | |
| x0,x1=-d[0]/2,d[0]/2; y0,y1=-d[1]/2,d[1]/2 # importer centres footprint XY and puts min Z on the origin plane | |
| v['world_bbox_m']=[[x0,y0,0.0],[x1,y1,d[2]]]; rect=[[x0,y0],[x1,y0],[x1,y1],[x0,y1]] | |
| if 'visual_footprint_xy_m' in v: v['visual_footprint_xy_m']=rect | |
| if 'obb_m' in v: v['obb_m']=dict(center_xy_m=[0.0,0.0],footprint_polygon_xy_m=rect,size_xy_m=[d[0],d[1]],yaw_deg=0.0) | |
| v['pose']='authored_up_corrected_frame' | |
| notes.add('geometry:'+','.join(sorted(v.keys()))) | |
| def fix_anchor(tr): | |
| ub=tr.get('canonical_uncentered_bbox_m') | |
| if ub: | |
| (x0,y0,z0),(x1,y1,z1)=ub; nb=[[x0,-z1,y0],[x1,-z0,y1]]; tr['canonical_uncentered_bbox_m']=nb | |
| (a0,b0,c0),(a1,b1,c1)=nb; tr['canonical_anchor_xyz_m']=[(a0+a1)/2,(b0+b1)/2,c0] | |
| elif 'canonical_anchor_xyz_m' in tr: | |
| a=tr['canonical_anchor_xyz_m']; tr['canonical_anchor_xyz_m']=[a[0],-a[2],a[1]] | |
| def evidence_file(aid,row): | |
| s=sev[aid]; e=swe.get(aid,{}); c=csvrows[aid.split('/')[-1]] | |
| ev=dict(schema='rhg.pose_correction_evidence.v1',asset_id=aid,record_id=row['record_id'], | |
| authored_csv=dict(uri=CSV,sha256=csv_sha,row=dict(id=c['id'],name=c['name'],up=c['up'],front=c['front'],wnsynsetkey=c['wnsynsetkey'])), | |
| scene_placements=dict(n_instances=s['n'],dominant_local_up=s['scene_up'],consistency=s['consistency'],n_scenes=e.get('scenes'),source='hssd-hab scenes/*.scene_instance.json (168 scenes)'), | |
| producer_record=dict(source_up=s['producer_source_up'],current_canonical_up=s['producer_current_up']), | |
| correction=dict(old_source_to_canonical=M_OLD,new_source_to_canonical=M_NEW,rule='local -Z (authored up) -> canonical +Z; horizontal yaw is arbitrary and left to the front evidence'), | |
| limits='Rotation is the minimal tilt correction; the in-plane yaw is not determined by this evidence. Other measured attributes (support, usage_space, shape) were produced in the old frame and are not recomputed.') | |
| return ev | |
| if not DRY: | |
| if OUT.exists(): shutil.rmtree(OUT) | |
| OUT.mkdir(parents=True); (OUT/'evidence').mkdir() | |
| pset=json.load(open(PARENT)); new=[]; stats=C.Counter(); notes=set(); samples=[] | |
| for ri,ref in enumerate(pset['releases']): | |
| dpath=Path(ref.get('delivery') or ref['delivery_uri']); delivery=json.load(open(dpath)); recs=delivery['artifacts'].get('records.jsonl') | |
| if not recs: new.append(ref); continue | |
| rpath=Path(recs['uri']); changed={} | |
| for line in rpath.open('rb'): | |
| if not line.strip(): continue | |
| row=json.loads(line); aid=row.get('asset_id') | |
| if aid not in ALLSEL: continue | |
| if aid in CSVONLY: | |
| if row['processing']['pool_status']!='prepared': stats['csvonly_skip_not_prepared']+=1; continue | |
| try: | |
| for n in ('source','runtime'): fee._verify(row['identity'][n]['value']) | |
| except Exception: stats['csvonly_skip_source_changed']+=1; continue | |
| if set_front(row,aid,DEC[aid],row['identity']['canonical_transform']['value']['matrix_row_major']): changed[row['record_id']]=row | |
| continue | |
| pq=row['attributes'].get('pose_qualification') or {}; pv=pq.get('value') or {} | |
| if pq.get('status')!='conflict': stats['skip_not_conflict']+=1; continue | |
| reg=row['evidence_registry'] | |
| if any(k.startswith('pose_fix_') for k in reg): stats['skip_collision']+=1; continue | |
| issues=[i for i in row['processing'].get('issues',[]) if i.get('kind')!='source_or_independent_pose_conflict'] | |
| if aid in FIX: | |
| tr=row['identity']['canonical_transform']['value'] | |
| if tr.get('matrix_row_major')!=[float(x) for x in M_OLD]: stats['skip_unexpected_matrix']+=1; continue | |
| ev=evidence_file(aid,row); | |
| if not DRY: | |
| ep=OUT/'evidence'/(hashlib.sha256(row['record_id'].encode()).hexdigest()[:16]+'.pose.json'); fee._write(ep,ev); ref_ev=dict(fee._ref(ep),kind='pose_correction_evidence') | |
| else: ref_ev=dict(uri='dry',sha256='0'*64,kind='pose_correction_evidence') | |
| reg['pose_fix_evidence']=ref_ev; reg['pose_fix_authored_csv']=dict(uri=CSV,sha256=csv_sha,kind='source_authored_up_axis') | |
| old=copy.deepcopy(tr['matrix_row_major']); tr['matrix_row_major']=[float(x) for x in M_NEW] | |
| for k in list(tr.keys()): | |
| if k=='complete_runtime_world_to_canonical_matrix_row_major': tr[k]=[float(x) for x in M_NEW] | |
| elif isinstance(tr[k],list) and len(tr[k])==16 and k!='matrix_row_major': notes.add('transform_16list:'+k) | |
| fix_anchor(tr); notes.add('transform_keys:'+','.join(sorted(tr.keys()))) | |
| tf=row['identity']['canonical_transform']; tf['evidence']=list(tf.get('evidence',[]))+['pose_fix_evidence','pose_fix_authored_csv'] | |
| tf['provenance']=dict(method='authored_up_axis_plus_scene_placement_rotation',previous_matrix_row_major=old,previous_provenance=tf.get('provenance'), | |
| limitations='Tilt corrected from authored up and real scene placements; in-plane yaw undetermined; not an independent re-measurement of geometry') | |
| fix_geometry(row['attributes']['geometry'],notes) | |
| pq['value']=dict(current_pose='upright',source_up_vector=[0.0,0.0,-1.0],current_canonical_up_vector=[0.0,0.0,1.0],intended_up_axis=[0,0,1],geometry_or_transform_modified=True) | |
| pq['status']='measured'; pq['evidence']=list(pq.get('evidence',[]))+['pose_fix_evidence','pose_fix_authored_csv'] | |
| pq['provenance']=dict(method='authored_up_and_scene_placements_agree_with_producer_conflict',limitations='Pose corrected by rotation of the source-to-canonical transform',confidence_basis='three independent sources agree; not a probability') | |
| if aid in DEC and DEC[aid]['source']=='csv': set_front(row,aid,DEC[aid],M_NEW) | |
| stats['fix']+=1 | |
| else: | |
| pq['value']=dict(pv,current_pose='upright',note='producer conflict not supported: real scene placements keep the file +Y axis vertical') | |
| pq['status']='inferred'; pq['provenance']=dict(method='scene_placement_rotation_consistent_with_registered_up',limitations='Producer conflict overridden by 168-scene placement statistics',confidence_basis='not a probability') | |
| stats['false_positive']+=1 | |
| row['processing']['issues']=issues | |
| if not issues and row['processing']['pool_status']=='needs_confirmation': row['processing']['pool_status']='prepared'; stats['now_prepared']+=1 | |
| else: stats['still_needs_confirmation(other issues)']+=1 | |
| changed[row['record_id']]=row | |
| if len(samples)<1: samples.append(row) | |
| if DRY or not changed: | |
| if not changed: new.append(ref) | |
| continue | |
| pub=OUT/('release_%02d'%ri); pub.mkdir(); target=pub/'records.jsonl'; n=0 | |
| with rpath.open('rb') as s, target.open('wb') as dst: | |
| for line in s: | |
| r=json.loads(line) if line.strip() else {} | |
| if r.get('record_id') in changed: dst.write((json.dumps(changed[r['record_id']],ensure_ascii=False,allow_nan=False)+'\n').encode()); n+=1 | |
| else: dst.write(line) | |
| assert n==len(changed) | |
| d=copy.deepcopy(delivery); d.update(release=delivery['release']+'_pose_fix',consumer_contract='rhg.source_geometry_attributes.v1',status='pose_correction_extension_other_fields_preserved',parent_delivery=fee._ref(dpath)) | |
| d['artifacts']['records.jsonl']=fee._ref(target); fee._write(pub/'delivery.json',d) | |
| new.append(dict(delivery=str((pub/'delivery.json').resolve()),sha256=fee.sha256(pub/'delivery.json'))) | |
| print('release stats',dict(stats)); print('notes:'); [print(' ',n) for n in sorted(notes)] | |
| if DRY and samples: print(json.dumps(samples[0]['attributes']['geometry']['value'])[:700]) | |
| if not DRY: | |
| out=copy.deepcopy(pset); out['releases']=new; fee._write(OUT/'attribute_releases.json',out) | |
| json.dump(dict(fix=sorted(FIX),false_positive=sorted(FALSE),stats=dict(stats),built=time.strftime('%F %T')),open(OUT/'publication.json','w')) | |