File size: 8,161 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python3
"""Publish articulation-transfer operation-side fronts as ONE replacement of the parent release.

Only records that are (a) prepared, (b) currently functional_front=unknown, (c) HSSD-standard canonical transform,
(d) matched by point-cloud geometry to articulated URDF models whose horizontal joint motions all agree.
The front is an inference (status 'inferred', reviewer 'automated:articulation_transfer_v1'); it is NOT a visual review.
"""
import curation_paths as paths
import copy,hashlib,json,sqlite3,sys,time,os
from pathlib import Path
sys.path.insert(0,paths.S)
import front_evidence_extension as fee

PARENT_SET=Path(os.environ['PARENT'])
EVID=Path(paths.A+'/static_front_from_urdf.json')
DB=paths.L+'/full_matrix_reviewed_compatibility_v4.sqlite3'
OUT=Path(sys.argv[1]); REVIEWER='automated:articulation_transfer_v1'; CONF=.9
FRAME='canonical right-handed Z-up; positive axis points outward from access face'
HSSD_MATRIX=[1,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,1]
def sha(p): return fee.sha256(p)

def main():
    OUT.mkdir(parents=True,exist_ok=False); (OUT/'certs').mkdir()
    evid={e['static']:e for e in json.load(open(EVID))}
    DEC=json.load(open(paths.W+'/out/front_decisions.json'))['decisions']
    eligible={a:e for a,e in evid.items() if DEC.get(a,{}).get('source')=='art'}
    db=sqlite3.connect('file:'+DB+'?mode=ro',uri=True)
    upath={a:json.loads(rj).get('canonical_path') for a,rj in db.execute("select asset_id,record_json from assets where asset_id like 'hssd:urdf/%'")}
    uhash={}
    def urdf_ref(a):
        if a not in uhash:
            p=Path(upath[a]); uhash[a]=dict(uri=str(p.resolve()),sha256=sha(p),meshes={m.name:sha(m) for m in sorted(p.parent.glob('*.glb'))})
        return uhash[a]
    pset=json.load(open(PARENT_SET)); stats=dict(eligible_assets=len(eligible),skipped={}); 
    def skip(why): stats['skipped'][why]=stats['skipped'].get(why,0)+1
    new_releases=[]; summary=[]
    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_releases.append(ref); continue
        rpath=Path(recs['uri']); changed={}
        with rpath.open('rb') as f:
            for line in f:
                if not line.strip(): continue
                row=json.loads(line); aid=row.get('asset_id')
                if aid not in eligible: continue
                if row['processing']['pool_status']!='prepared': skip('not_prepared'); continue
                ff=row['attributes'].get('functional_front') or {}
                if ff.get('status')!='unknown': skip('front_already_%s'%ff.get('status')); continue
                tr=row['identity']['canonical_transform']['value']
                if tr.get('matrix_row_major')!=HSSD_MATRIX or (tr.get('units'),tr.get('up_axis'),tr.get('handedness'))!=('m','Z','right'): skip('non_standard_transform'); continue
                try:
                    for n in ('source','runtime'): fee._verify(row['identity'][n]['value'])
                except Exception: skip('source_bytes_changed'); continue
                e=eligible[aid]; axis=e['front_axis']; rid=row['record_id']
                matches=[]; reg=row['evidence_registry']
                if any(k.startswith('articulation_') for k in reg): skip('key_collision'); continue
                for i,s in enumerate(e['support']):
                    u=urdf_ref(s['urdf']); share=s['share']
                    matches.append(dict(urdf_asset_id=s['urdf'],urdf_uri=u['uri'],urdf_sha256=u['sha256'],mesh_sha256=u['meshes'],chamfer_over_bbox_diag=s['chamfer'],
                                        axis=s['axis'],vote_share=share,votes=s['votes'],joint_counts=s['n']))
                cert=dict(schema='rhg.functional_front_evidence.articulation.v1',record_id=rid,asset_id=aid,source_sha256=row['identity']['source']['value']['sha256'],
                    runtime_sha256=row['identity']['runtime']['value']['sha256'],canonical_transform=tr['matrix_row_major'],canonical_axis=axis,
                    scene_yaw_already_applied=False,geometry_changed=False,evidence_kind='articulation_kinematic_transfer',review_status='inferred',reviewer=REVIEWER,
                    rationale='The matched articulated model opens its horizontal doors/drawers toward %s in this static mesh\'s canonical frame; the operation side is the front.'%axis,
                    transfer=dict(method='point_cloud_chamfer_match_then_urdf_joint_motion_direction',front_axis=axis,agreement=e['agree'],n_models=e['n_urdf'],
                                  min_vote_share=e['min_share'],matches=matches,frame='HSSD registry transform: glTF Y-up to canonical Z-up',
                                  limits='Static mesh identity is established by geometry match, not byte identity; operation side defines the front; no clearance or dynamics claim.'),
                    scope='static_operation_side_not_articulation_clearance_or_dynamics')
                cp=OUT/'certs'/(hashlib.sha256(rid.encode()).hexdigest()[:16]+'.articulation.json'); fee._write(cp,cert)
                reg['articulation_front_certificate']=dict(fee._ref(cp),kind='articulation_kinematics_certificate')
                keys=['articulation_front_certificate']
                for i,m in enumerate(matches):
                    reg['articulation_urdf_%d'%i]=dict(uri=m['urdf_uri'],sha256=m['urdf_sha256'],kind='source_articulation_urdf'); keys.append('articulation_urdf_%d'%i)
                row['attributes']['functional_front']=dict(status='inferred',confidence=CONF,
                    value=dict(axis=axis,axis_frame=FRAME,certificate='articulation_front_certificate',evidence_kind='articulation_kinematic_transfer'),
                    evidence=keys,provenance=dict(method='articulation_kinematic_transfer',reviewer=REVIEWER,
                        confidence_basis='pipeline evidence grade at the accepted minimum, not a probability',
                        limitations='Operation side inferred from a geometry-matched articulated model; not a visual review; no geometry or physical qualification changed'))
                changed[rid]=row
        if not changed: new_releases.append(ref); continue
        pub=OUT/('release_%02d'%ri); pub.mkdir(); target=pub/'records.jsonl'; n=0
        with rpath.open('rb') as src, target.open('wb') as dst:
            for line in src:
                row=json.loads(line) if line.strip() else {}
                if row.get('record_id') in changed:
                    dst.write((json.dumps(changed[row['record_id']],ensure_ascii=False,allow_nan=False)+'\n').encode()); n+=1
                else: dst.write(line)
        assert n==len(changed),'replacement count mismatch'
        d=copy.deepcopy(delivery); d.update(release=delivery['release']+'_articulation_front_'+OUT.name,consumer_contract='rhg.source_geometry_attributes.v1',
            status='articulation_front_extension_other_fields_preserved',parent_delivery=fee._ref(dpath))
        d['artifacts']['records.jsonl']=fee._ref(target); fee._write(pub/'delivery.json',d)
        new_releases.append(dict(delivery=str((pub/'delivery.json').resolve()),sha256=sha(pub/'delivery.json')))
        summary.append(dict(release_index=ri,records_changed=len(changed),by_axis={a:sum(1 for r in changed.values() if r['attributes']['functional_front']['value']['axis']==a) for a in ('-Y','+Y','-X','+X')},
                            assets=len({r['asset_id'] for r in changed.values()})))
    out=copy.deepcopy(pset); out['releases']=new_releases
    fee._write(OUT/'attribute_releases.json',out)
    result=dict(status='PUBLISHED-ARTICULATION-FRONT',release_set=str((OUT/'attribute_releases.json').resolve()),release_set_sha256=sha(OUT/'attribute_releases.json'),
                parent_set=str(PARENT_SET),reviewer=REVIEWER,confidence=CONF,stats=stats,releases=summary,built=time.strftime('%F %T'),
                qualification='front_only_native_preparation_and_final_admission_still_required')
    fee._write(OUT/'publication.json',result); print(json.dumps(result,indent=1))
if __name__=='__main__': main()