File size: 4,207 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
"""Whole-selection conversion utilities. Never reads previous pilot outputs."""
from pilot_build import *
import hashlib

RELEASE='shared-sequence-v1.1'

class View:
 def __init__(self,dataset,seq,cam,ids,size,source,kind='video',sampling='dense',split='unknown'):
  self.root=ROOT/dataset/RELEASE;self.p=self.root/'data'/seq/cam
  self.p.mkdir(parents=True,exist_ok=True);self.T=len(ids);self.source=source;self.checks=[]
  self.m={'schema_version':'hand-warehouse/1.1','dataset_id':dataset,'release_id':RELEASE,'sequence_id':seq,'camera_id':cam,'sample_type':kind,'num_frames':self.T,'hand_slots':['left','right'],'sampling':{'type':'single' if kind=='image' else sampling,'source_fps':None,'frames_ref':'camera/frames.jsonl'},'camera':{'model':'unknown','schema_id':None,'image_size':size},'components':{},'split':split}
  self.frames=[{'frame_index':i,'source_frame_id':str(fid),'timestamp_ns':None,'clock_domain':None,'source_locator':{**source,'source_frame_id':str(fid)}} for i,fid in enumerate(ids)]
 def add(self,name,path,schema,axes,valid,method='source values retained',**kw):
  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':'format_conversion','method':method},'source_locator':self.source,**kw}
 def array(self,name,path,schema,a,valid,axes,**kw):
  a=np.asarray(a,np.float32).copy();valid=np.asarray(valid,bool)
  assert a.shape[:valid.ndim]==valid.shape and a.shape[0]==self.T
  assert np.isfinite(a[valid]).all(),name
  a[~valid]=np.nan;tensor(self.p/path,a);self.add(name,path,schema,axes,valid,**kw)
  restored=torch.load(self.p/path,map_location='cpu',weights_only=True).numpy()
  for index in range(self.T):assert np.array_equal(restored[index],a[index],equal_nan=True)
  self.checks.append({'test':'tensor_serialization_exact','file':path,'shape':list(a.shape),'valid_count':int(valid.sum())})
 def video(self,name,path,iterator,mask=False,**kw):
  w,h=self.m['camera']['image_size'];pix='gray16le' if mask else 'rgb24';dtype='<u2' if mask else 'uint8'
  dst=self.p/path;dst.parent.mkdir(parents=True,exist_ok=True);hashes=[]
  proc=subprocess.Popen([FF,'-v','error','-y','-f','rawvideo','-pixel_format',pix,'-video_size',f'{w}x{h}','-framerate','1','-i','pipe:0','-c:v','ffv1','-level','3','-g','1',str(dst)],stdin=subprocess.PIPE)
  try:
   for frame in iterator:
    a=np.asarray(frame,dtype=dtype);assert a.shape==((h,w) if mask else (h,w,3));b=a.tobytes();hashes.append(hashlib.sha256(b).hexdigest());proc.stdin.write(b)
  finally:proc.stdin.close()
  assert proc.wait()==0 and len(hashes)==self.T
  proc=subprocess.Popen([FF,'-v','error','-i',str(dst),'-f','rawvideo','-pix_fmt',pix,'pipe:1'],stdout=subprocess.PIPE)
  nbytes=w*h*(2 if mask else 3)
  for digest in hashes:
   b=proc.stdout.read(nbytes);assert len(b)==nbytes and hashlib.sha256(b).hexdigest()==digest,'video roundtrip'
  assert not proc.stdout.read(1);assert proc.wait()==0
  self.checks.append({'test':'all_frames_pixel_exact_roundtrip','file':path,'frames':self.T})
  self.add(name,path,'segment/uint16_labels/v1' if mask else 'rgb/uint8/v1',['T','height','width'] if mask else ['T','height','width','channel'],np.ones(self.T,bool),storage_fps=1,timebase_role='index_only',**kw)
 def intrinsic(self,K):
  self.m['camera'].update(model='pinhole',schema_id='camera/pinhole/v1')
  self.array('intrinsic','camera/intrinsic.pt','camera/pinhole/v1',np.broadcast_to(K,(self.T,3,3)),np.ones(self.T,bool),['T','row','column'])
 def finish(self):
  lines(self.p/'camera/frames.jsonl',self.frames);save(self.p/'metainfo.json',self.m)
  save(self.root/'doc'/f'{self.m["sequence_id"]}__{self.m["camera_id"]}.checks.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 snapshot(dataset,scripts):
 # Retained for old callers. The organized bundle must not be repopulated at runtime.
 (ROOT/dataset/RELEASE/'script').mkdir(parents=True,exist_ok=True)