File size: 12,960 Bytes
b4b45bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""Helpers for the fresh ARCTIC/HOT3D whole-sequence v1.0 pilots.



Original archives are read only. Temporary extraction is outside raw.

Licensed MANO weights stay in the local model directory and are never published.

"""
from sequence_pilot_world import camera_mano, Mano
from pilot_build import *
from scipy.spatial.transform import Rotation
import hashlib
import re
import time
import trimesh
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
from contextlib import contextmanager

DATA_ROOT = Path('E:/hand-datasets')
RELEASE = 'shared-v1.0'
RUN = 'fresh-sequence-pilot-20260920'
VRS = WORK/'scripts/tools/vrs_env/Library/bin/vrs.exe'
MEDIA_POOL=None
MEDIA_PENDING=[]
MEDIA_WORKERS=1
MEDIA_POLICY='legacy_full_pixels'
OUTPUT_OVERRIDE=None
TMP_OVERRIDE=None

@contextmanager
def media_pipeline(workers=1,policy='jpeg-packets-all-rgb-sample16/v1'):
    global MEDIA_POOL,MEDIA_PENDING,MEDIA_WORKERS,MEDIA_POLICY
    assert MEDIA_POOL is None and not MEDIA_PENDING
    MEDIA_WORKERS=workers;MEDIA_POLICY=policy
    MEDIA_POOL=ThreadPoolExecutor(max_workers=workers)
    try:
        yield
        for future in MEDIA_PENDING:future.result()
    finally:
        MEDIA_POOL.shutdown(wait=True,cancel_futures=True)
        MEDIA_POOL=None;MEDIA_PENDING=[];MEDIA_POLICY='legacy_full_pixels'

def submit_media(view,members_factory):
    global MEDIA_PENDING
    def execute():
        jpeg_video(view,members_factory());view.m['pilot_complete']=True;view.finish()
    if MEDIA_POOL is None:execute();return
    # Bound pending views and source/video spools, not only running FFmpeg tasks.
    while len(MEDIA_PENDING)>=MEDIA_WORKERS:
        finished,_=wait(MEDIA_PENDING,return_when=FIRST_COMPLETED)
        for future in finished:future.result()
        MEDIA_PENDING=[f for f in MEDIA_PENDING if f not in finished]
    MEDIA_PENDING.append(MEDIA_POOL.submit(execute))

def digest(p):
    h=hashlib.sha256()
    with Path(p).open('rb') as f:
        for b in iter(lambda:f.read(4*1024*1024),b''): h.update(b)
    return h.hexdigest()

def native_npy_bytes(data):
    f=io.BytesIO(data);version=np.lib.format.read_magic(f)
    shape,order,dtype=np.lib.format._read_array_header(f,version)
    if dtype.hasobject:return Restricted(f,encoding='latin1').load().item()
    return np.frombuffer(f.read(),dtype=dtype).reshape(shape,order='F' if order else 'C').copy()

def command(args):
    r=subprocess.run([str(x) for x in args],capture_output=True)
    if r.returncode:raise RuntimeError(r.stderr.decode(errors='replace')[-3000:])
    return r.stdout

def framehash(args,copy=False):
    output=command([FF,'-v','error','-threads','2','-noautorotate',*args,'-map','0:v:0',
        *(['-c:v','copy'] if copy else ['-pix_fmt','rgb24','-threads','2']),
        '-f','framehash','-hash','sha256','-fps_mode','passthrough','pipe:1']).decode()
    return [(int(r.split(',')[-2]),r.split(',')[-1].strip()) for r in output.splitlines() if r and not r.startswith('#')]

def jpeg_video(view, members):
    """members is a fresh iterator of (locator, JPEG bytes). Verify every packet/frame."""
    if MEDIA_POLICY!='legacy_full_pixels':
        from accelerated_media import write_video
        return write_video(view,members)
    temporary=view.tmp/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.mjpeg'
    temporary.parent.mkdir(parents=True,exist_ok=True)
    hashes=[]
    with temporary.open('wb') as out:
        for locator,b in members:
            assert b[:2]==b'\xff\xd8',locator
            hashes.append((len(b),hashlib.sha256(b).hexdigest()));out.write(b)
    assert len(hashes)==view.T
    dst=view.p/'observation/rgb.mkv';dst.parent.mkdir(parents=True,exist_ok=True)
    source=['-f','image2pipe','-framerate','1','-c:v','mjpeg','-i',str(temporary)]
    command([FF,'-v','error','-y',*source,'-map','0:v:0','-c:v','copy',dst])
    packet=framehash(['-i',str(dst)],True)
    assert packet==hashes,'source JPEG packets changed in MKV'
    before=framehash(source);after=framehash(['-i',str(dst)])
    assert before==after and len(before)==view.T,'RGB decoding differs'
    w,h=view.m['camera']['image_size'];assert all(n==w*h*3 for n,_ in after)
    info=subprocess.run([FF,'-hide_banner','-i',str(dst)],capture_output=True).stderr.decode(errors='replace')
    line=next(s.strip() for s in info.splitlines() if 'Video: mjpeg' in s)
    pixel=re.search(r'Video: mjpeg[^,]*,\s*(\w+)',line).group(1)
    version=command([FF,'-version']).decode().splitlines()[0]
    view.component('rgb','observation/rgb.mkv','rgb/uint8/v1',['T','height','width','channel'],np.ones(view.T,bool),
        source=view.source,method='Original JPEG packets copied from raw into MKV; no recompression or rotation',
        storage={'profile':'mkv/mjpeg_copy/v1','codec':'mjpeg','pixel_format':pixel,'encoded_size':[w,h],
          'source_lossy':True,'decoder':{'name':'ffmpeg','version':version,'output_pixel_format':'rgb24','autorotate':False,'source_color_declaration':'unknown','actual_stream_description':line},
          'encoder_parameters':{'mode':'stream_copy','version':version}},storage_fps=1,timebase_role='index_only')
    view.checks.append({'test':'all_source_JPEG_packets_and_RGB_pixels_exact','passed':True,'frames':view.T,
        'packet_manifest_sha256':hashlib.sha256(json.dumps(hashes).encode()).hexdigest(),
        'pixel_manifest_sha256':hashlib.sha256(json.dumps(after).encode()).hexdigest(),'output_bytes':dst.stat().st_size})
    save(view.tmp/'media_checks'/f'{view.m["sequence_id"]}__{view.m["camera_id"]}.json',{'packets':hashes,'pixels':after})
    # This precise file was created by this call within the current run's temporary directory.
    assert temporary.resolve().is_relative_to(view.tmp.resolve());temporary.unlink()

class FreshView:
    def __init__(self,dataset,seq,cam,ids,size,source):
        self.root=(OUTPUT_OVERRIDE/dataset/RELEASE if OUTPUT_OVERRIDE else DATA_ROOT/dataset/RELEASE);self.p=self.root/'data'/seq/cam
        self.tmp=(TMP_OVERRIDE/dataset/RUN if TMP_OVERRIDE else DATA_ROOT/dataset/'tmp'/RUN);self.p.mkdir(parents=True,exist_ok=True)
        self.T=len(ids);self.source=source;self.checks=[]
        self.m={'schema_version':'hand-warehouse/1.0','storage_revision':'lossless-video-2026-09-18',
            'dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,
            'sample_type':'video','num_frames':self.T,'hand_slots':['left','right'],
            'sampling':{'type':'dense','source_fps':None,'frames_ref':'camera/frames.jsonl','selection':'all released images in selected complete source sequence'},
            'camera':{'model':'unknown','schema_id':None,'image_size':size},'split':'unknown','components':{},'pilot':True}
        self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,
            'source_locator':dict(source,source_frame_id=str(fid))} for i,fid in enumerate(ids)]
    def component(self,name,path,schema,axes,valid,source=None,method='source values retained',kind='format_conversion',**kw):
        valid=np.asarray(valid,bool);vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/vp,valid)
        self.m['components'][name]={'available':True,'schema_id':schema,'data_ref':path,'axes':axes,
            'valid_ref':vp,'valid_axes':axes[:valid.ndim],'provenance':{'kind':kind,'method':method},
            'source_locator':source or self.source,**kw}
    def array(self,name,path,schema,data,valid,axes,**kw):
        a=np.asarray(data,np.float32).copy();valid=np.asarray(valid,bool)
        assert a.shape[0]==self.T and a.shape[:valid.ndim]==valid.shape
        assert np.isfinite(a[valid]).all(),name
        a[~valid]=np.nan;tensor(self.p/path,a)
        self.component(name,path,schema,axes,valid,**kw)
        restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
        assert np.array_equal(a,restored,equal_nan=True)
        self.checks.append({'test':'tensor_exact_roundtrip','file':path,'shape':list(a.shape),'valid_count':int(valid.sum()),'passed':True})
    def attribute(self,parent,path,data,axes,source,meaning):
        data=np.asarray(data,np.float32);valid=np.isfinite(data)
        assert ((data[valid]>=0)&(data[valid]<=1)).all()
        vp=Path(path).with_name(Path(path).stem+'_valid.pt').as_posix();tensor(self.p/path,data);tensor(self.p/vp,valid)
        self.m['components'][parent].setdefault('attributes',{})['visibility']={'data_ref':path,'valid_ref':vp,
            'axes':axes,'valid_axes':axes,'dtype':'float32','visibility_type':'ratio','meaning':meaning,
            'provenance':{'kind':'source','method':'native HOT3D visibility ratio retained in [0,1]; misleading [%] header is not a percentage scale'},'source_locator':source}
    def mesh(self,oid,path,source):
        self.component('object_'+oid+'_mesh',path,'mesh/obj/v1',['vertex','coordinate'],np.array(True),source=source,
            method='Object vertices in metres; topology, material and texture dependencies retained',static=True,unit='m',coordinate_frame='object')
    def finish(self):
        lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
        save(self.tmp/'checks'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.json',{'checks':self.checks,'frames':self.T,'input':self.source})
        print('CONVERTED',self.m['dataset_id'],self.m['sequence_id'],self.m['camera_id'],self.T,flush=True)

def assert_se3(a):
    a=np.asarray(a);assert a.shape[-2:]==(4,4)
    # A component may exist while QA leaves no usable poses in this view.
    if a.size==0:return
    assert np.isfinite(a).all() and np.allclose(a[...,3,:],[0,0,0,1],atol=1e-6)
    r=a[...,:3,:3];assert np.max(np.abs(r@np.swapaxes(r,-1,-2)-np.eye(3)))<2e-5
    assert np.max(np.abs(np.linalg.det(r)-1))<2e-5

def setup(dataset,seq):
    base=DATA_ROOT/dataset;out=base/RELEASE
    for folder in ['doc','script','doc/validation']: (out/folder).mkdir(parents=True,exist_ok=True)
    for f in ['CONTRACT.md','schema.json']:shutil.copyfile(WORK/'distribution/hand-warehouse-1.0'/f,out/'doc'/f)
    save(out/'doc/validation/status.json',{'stage':'building_sequence_pilot','human_review':'pending','sequence_id':seq,'full_preprocessing_authorized':False,'upload_authorized':False})
    # The organized script bundle is already self-contained; runtime work must not repopulate its root.
    (base/'tmp'/RUN).mkdir(parents=True,exist_ok=True)

def object_textured_assets(z,prefix,target):
    target.mkdir(parents=True,exist_ok=True)
    for name in z.namelist():
        if not name.startswith(prefix) or name.endswith('/'):continue
        rel=Path(name[len(prefix):]);dest=target/rel
        assert dest.resolve().is_relative_to(target.resolve());dest.parent.mkdir(parents=True,exist_ok=True)
        if dest.suffix.lower() in ('.obj','.mtl','.jpg','.jpeg','.png'):
            b=z.read(name)
            if dest.suffix=='.obj':
                rows=b.decode().splitlines()
                for i,row in enumerate(rows):
                    if row.startswith('v '):
                        v=row.split();v[1:4]=[format(float(x)/1000,'.17g') for x in v[1:4]];rows[i]=' '.join(v)
                b=('\n'.join(rows)+'\n').encode()
            dest.write_bytes(b)
    repair_arctic_material_refs(target)

def repair_arctic_material_refs(target):
    """Repair a source filename mismatch only when material identifiers agree."""
    material=target/'material.mtl'
    if not material.exists():return
    ids={x.split(maxsplit=1)[1] for x in material.read_text().splitlines() if x.startswith('newmtl ')}
    for obj in target.glob('*.obj'):
        text=obj.read_text();rows=text.splitlines();used={x.split(maxsplit=1)[1] for x in rows if x.startswith('usemtl ')}
        if 'mtllib material_0.mtl' in rows and not (target/'material_0.mtl').exists():
            assert used and used.issubset(ids),(obj,used,ids)
            obj.write_text(text.replace('mtllib material_0.mtl','mtllib material.mtl'))

def project_points(xyz,camera,params):
    xyz=np.asarray(xyz,float);uv=np.full((len(xyz),2),np.nan);good=np.isfinite(xyz).all(1)&(xyz[:,2]>1e-6)
    if camera=='fisheye624':
        p=np.asarray(params);xy=xyz[good,:2]/xyz[good,2,None];r=np.linalg.norm(xy,axis=1);th=np.arctan(r)
        radial=th*(1+sum(p[3+i]*th**(2*i+2) for i in range(6)))
        xy=xy*np.divide(radial,r,out=np.ones_like(r),where=r>1e-12)[:,None]
        x,y=xy.T;rr=x*x+y*y
        xd=x+(2*x*x+rr)*p[9]+2*x*y*p[10]+p[11]*rr+p[12]*rr*rr
        yd=y+(2*y*y+rr)*p[10]+2*x*y*p[9]+p[13]*rr+p[14]*rr*rr
        uv[good]=p[0]*np.stack([xd,yd],1)+p[1:3]
    else:
        K,D=params;uv[good]=cv2.projectPoints(xyz[good],np.zeros(3),np.zeros(3),K,D)[0].reshape(-1,2)
    return uv