#!/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(W+'/release_pose'); CSV=paths.B+'/semantics/objects.csv' PARENT=Path(R+'/bed_front_20261104/front_probe/published/review_1793770727314953958/attribute_releases.json') 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} 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 FIX and aid not in FALSE: 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') 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'))