File size: 14,000 Bytes
dbaccc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os,sys,json,ast,hashlib,importlib.util,shutil
from pathlib import Path
import numpy as np,cv2
from PIL import Image
ROOT=Path('/root/autodl-tmp/kimi_realcase_20261109')
PROD=Path('/root/autodl-tmp/real_video_condition_repro_20261105_v1')
CORE=PROD/'tools/old671';LOADER=Path('/root/autodl-tmp/codex_user8_20261108/bbox_dataset_original.py')
sys.path.insert(0,str(CORE))
from bbox import OrientedBoundingBox,render_bbox_conditions
W,H=1280,704
COLORS={'purple':[.72,.02,1.],'green':[.02,1.,.03],'blue':[.02,.08,1.],'warm':[1.,.75,.42]}
LEVELS={'low':1000,'medium':4000,'high':12000}
PALETTE=np.array([[0,0,0],[255,0,0],[0,0,255],[255,255,0]],np.uint8)

def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(4*1024*1024),b''):h.update(b)
 return h.hexdigest()
def srgb(lin):return np.where(lin<=.0031308,12.92*lin,1.055*np.power(np.maximum(lin,0),1/2.4)-.055)
def angle(R):return float(np.degrees(np.arccos(np.clip((np.trace(R)-1)/2,-1,1))))
def load_joint():
 class Native704(ast.NodeTransformer):
  def visit_Constant(self,node):
   if type(node.value) is int and node.value in (352,640):return ast.copy_location(ast.Constant(value={352:704,640:1280}[node.value]),node)
   return node
 tree=Native704().visit(ast.parse(LOADER.read_text()));ast.fix_missing_locations(tree);ns={'__name__':'native704_loader'};exec(compile(tree,str(LOADER),'exec'),ns);return ns['joint_frames']
def project_mesh(vertices,faces,K,w2c):
 cam=vertices@w2c[:3,:3].T+w2c[:3,3];pr=cam@K.T
 with np.errstate(divide='ignore',invalid='ignore'):uv=pr[:,:2]/pr[:,2,None]
 good=np.isfinite(uv).all(1)&(cam[:,2]>0);tri=faces[good[faces].all(1)];points=np.rint(np.clip(uv,-32760,32760)).astype(np.int32);mask=np.zeros((H,W),np.uint8)
 for t in tri:
  p=points[t]
  if p[:,0].max()<0 or p[:,0].min()>=W or p[:,1].max()<0 or p[:,1].min()>=H:continue
  cv2.fillConvexPoly(mask,p,255,lineType=cv2.LINE_8)
 return mask

def run(cfg,only_version=None):
 case=cfg['case_id'];num=cfg['number'];rev=os.environ.get('REVISION',cfg.get('revision','move_replace_mesh_v1'));cd=ROOT/'cases'/case;sd=ROOT/'samples'/case;base=ROOT/'outputs'/str(num)/rev;mask_stage=cfg.get('mask_stage',os.environ.get('MASK_STAGE','step8_sam2_candidate'))
 joint_frames=load_joint();pcfpath=PROD/'tools/code_user_specified/render_pcf.py';spec=importlib.util.spec_from_file_location('prod_pcf',pcfpath);mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod);renderer=mod.Renderer(W,H)
 versions=only_version or ['small_4deg','orbit_10deg'];summary={}
 for version in versions:
  out=base/version
  if out.exists():raise FileExistsError(out)
  for sub in ['pcf','geometry/P/mask','geometry/P/wire','geometry/Q/mask','geometry/Q/wire','move_replace/labels','move_replace/joint','move_replace/target_lamp_mask','source_visible_mask_B_estimated','source_frames','source_visible_mask']:(out/sub).mkdir(parents=True,exist_ok=True)
  for c in COLORS:(out/'move_replace/lighting'/c/'color').mkdir(parents=True)
  for level in LEVELS:(out/'move_replace/intensity'/level).mkdir(parents=True)
  data=np.load(base/f'cameras_and_boxes_{version}.npz');A=data['w2c_A'];B=data['w2c_B'];K=data['K'];P=data['P'];Q=data['Q'];psize=data['P_size'];qsize=data['Q_size'];prot=data['P_rotation'];qrot=data['Q_rotation'];local=data['asset_vertices_local'];faces=data['asset_faces'];world=local@qrot.T+Q
  shutil.copy2(base/f'cameras_and_boxes_{version}.npz',out/'cameras_and_boxes.npz')
  for i in range(49):
   f=f'{i:06}.png';(out/'source_frames'/f).symlink_to(cd/'frames'/f'{i:03}.png');(out/'source_visible_mask'/f).symlink_to(sd/mask_stage/'mask49'/f)
  plan=json.loads((base/'geometry_plan.json').read_text());(out/'source_amodal_estimate.json').write_text(json.dumps({'P_amodal':plan['P']['amodal_estimate'],'visibility':'visible mask contains observed pixels only; estimated hidden geometry is separate'},indent=2))
  vggt=np.load(sd/'step3_worldpoints/vggt_raw.npz');wp=vggt['world_points'];gh,gw=wp.shape[1:3]
  records=[];target_border_frames=[];source_outside_max=0;target_outside_max=0
  for i in range(49):
   f=f'{i:06}.png';Kp=K[i]
   rgb,_=renderer.frame(np.linalg.inv(B[i]@np.linalg.inv(A[0])),Kp,.5);rgb=rgb.astype(np.uint8);cv2.imwrite(str(out/'pcf'/f),cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR))
   masks={};wires={}
   for name,center,size,rot in [('P',P,psize,prot),('Q',Q,qsize,qrot)]:
    obb=OrientedBoundingBox(name,center,size,rot,np.array([255,255,255],np.uint8));lines,_,mask,_=render_bbox_conditions([obb],Kp,B[i],H,W,edge_width=3,fill_alpha=.28);wire=((lines.max(-1)>100)&(mask>0)).astype(np.uint8)*255;masks[name]=mask>0;wires[name]=wire>0;cv2.imwrite(str(out/'geometry'/name/'mask'/f),mask);cv2.imwrite(str(out/'geometry'/name/'wire'/f),wire)
   labels=masks['P'].astype(np.uint8)+2*masks['Q'].astype(np.uint8);cv2.imwrite(str(out/'move_replace/labels'/f),labels)
   recipe={'schema':'pcf_bbox_factored.v003','background':'bbox_v3/pcf','labels':'bbox_v3/move_replace/labels','source_wire':'bbox_v3/geometry/P/wire','target_wire':'bbox_v3/geometry/Q/wire','palette_rgb':PALETTE.tolist(),'fill_alpha':.58,'background_alpha':.42}
   (out/'move_replace/RENDER.json').write_text(json.dumps(recipe,indent=2))
   # joint_frames is called below once all 49 label/PCF frames exist.
   target=project_mesh(world,faces,Kp,B[i]);cv2.imwrite(str(out/'move_replace/target_lamp_mask'/f),target);sel=target>0
   outside=int(np.count_nonzero(sel&~masks['Q']));target_outside_max=max(target_outside_max,outside)
   border=bool(sel.any() and (sel[0].any() or sel[-1].any() or sel[:,0].any() or sel[:,-1].any()))
   if border:target_border_frames.append(i)
   # Approximate source visible mask in B solely for geometric self-consistency checking.
   sm=cv2.imread(str(sd/mask_stage/'mask49'/f),0)
   if i in cfg.get('allow_fully_occluded_frames',[]) and not np.any(sm>0):
    sw=np.zeros((H,W),np.uint8);cv2.imwrite(str(out/'source_visible_mask_B_estimated'/f),sw);source_outside=0
   else:
    ys,xs=np.where(sm>0);yy=np.minimum((ys*gh/H).astype(int),gh-1);xx=np.minimum((xs*gw/W).astype(int),gw-1);pw=wp[i,yy,xx];cam=pw@A[i,:3,:3].T+A[i,:3,3];z=cam[:,2];z=z[np.isfinite(z)&(z>0)];depth=float(np.median(z));corners=np.array([[0,0],[W-1,0],[W-1,H-1],[0,H-1]],np.float32);zz=np.full(4,depth);cp=np.stack([(corners[:,0]-Kp[0,2])*zz/Kp[0,0],(corners[:,1]-Kp[1,2])*zz/Kp[1,1],zz],1);cw=(cp-A[i,:3,3])@A[i,:3,:3];bc=cw@B[i,:3,:3].T+B[i,:3,3];bp=bc@Kp.T;uv=bp[:,:2]/bp[:,2,None];M=cv2.getPerspectiveTransform(corners,uv.astype(np.float32));sw=cv2.warpPerspective(sm,M,(W,H),flags=cv2.INTER_NEAREST);cv2.imwrite(str(out/'source_visible_mask_B_estimated'/f),sw);source_outside=int(np.count_nonzero((sw>0)&~masks['P']));source_outside_max=max(source_outside_max,source_outside)
   ys,xs=np.where(sel);left,right=(int(xs.min()),int(xs.max()+1)) if len(xs) else (0,1);top,bottom=(int(ys.min()),int(ys.max()+1)) if len(ys) else (0,1)
   for typ,vals in [('color',COLORS),('intensity',{k:float(np.log1p(v/100)/np.log1p(100000/100)) for k,v in LEVELS.items()})]:
    for name,value in vals.items():
     rgbv=np.asarray(value if typ=='color' else [value]*3,np.float32);roi=np.zeros((bottom-top,right-left,3),np.float32);roi[sel[top:bottom,left:right]]=rgbv;folder=out/'move_replace'/(Path('lighting')/name/'color' if typ=='color' else Path('intensity')/name);np.savez_compressed(folder/f'{i:06}.npz',**{typ:roi},origin_xy=np.array([left,top]),full_shape_hwc=np.array([H,W,3]));full=np.zeros((H,W,3),np.uint8);show=srgb(roi) if typ=='color' else roi;full[top:bottom,left:right]=np.rint(np.clip(show,0,1)*255).astype(np.uint8);cv2.imwrite(str(folder/f),cv2.cvtColor(full,cv2.COLOR_RGB2BGR))
   records.append({'frame':i,'target_pixels':int(sel.sum()),'target_outside_Q':outside,'source_estimated_outside_P':source_outside,'target_touches_border':border})
   if i%12==0:print(num,version,i,flush=True)
  frames=joint_frames(str(out/'move_replace'),str(out),str(out));assert frames.shape==(49,H,W,3)
  for i,fr in enumerate(frames):Image.fromarray(fr).save(out/'move_replace/joint'/f'{i:06}.png',compress_level=1)
  # Camera evidence measures the perturbation itself, separately from natural A motion.
  angles=[];step=[];disp=[];centers=[]
  for i in range(49):
   angles.append(angle(B[i,:3,:3]@A[i,:3,:3].T));centers.append(np.linalg.inv(B[i])[:3,3]);disp.append(float(np.linalg.norm(centers[-1]-np.linalg.inv(A[i])[:3,3])))
   if i:
    d0=B[i-1]@np.linalg.inv(A[i-1]);d1=B[i]@np.linalg.inv(A[i]);step.append(angle(d1[:3,:3]@d0[:3,:3].T))
  # Preview: A source+SAM | A geometry placement | B joint / target | color | intensity.
  for i in (0,24,48):
   f=f'{i:06}.png';src=cv2.imread(str(cd/'frames'/f'{i:03}.png'));sm=cv2.imread(str(sd/mask_stage/'mask49'/f),0)>0;src[sm]=np.rint(.55*src[sm]+.45*np.array([0,255,0])).astype(np.uint8)
   place=cv2.imread(str(cd/'frames'/f'{i:03}.png'))
   for center,size,rot,color in [(P,psize,prot,(0,0,255)),(Q,qsize,qrot,(255,0,0))]:
    obb=OrientedBoundingBox('box',center,size,rot,np.array([255,255,255],np.uint8));lines,_,bm,_=render_bbox_conditions([obb],K[i],A[i],H,W,edge_width=3,fill_alpha=.28);wire=(lines.max(-1)>100)&(bm>0);place[wire]=color
   am=project_mesh(world,faces,K[i],A[i])>0;place[am]=np.rint(.45*place[am]+.55*np.array([255,0,255])).astype(np.uint8)
   imgs=[src,place,cv2.imread(str(out/'move_replace/joint'/f)),cv2.imread(str(out/'move_replace/target_lamp_mask'/f)),cv2.imread(str(out/'move_replace/lighting/purple/color'/f)),cv2.imread(str(out/'move_replace/intensity/medium'/f))]
   labels_img=['A source + visible SAM','A P/Q + replacement geometry (not edited RGB)','B original PCF + 3D boxes','B actual GLB silhouette','B purple linear-control sRGB preview','B medium experimental intensity']
   sheet=np.zeros((704,1920,3),np.uint8)
   for j,(im,text) in enumerate(zip(imgs,labels_img)):
    x=(j%3)*640;y=(j//3)*352;sheet[y:y+352,x:x+640]=cv2.resize(im,(640,352));cv2.rectangle(sheet,(x,y),(x+640,y+24),(0,0,0),-1);cv2.putText(sheet,f'{text} f{i}',(x+5,y+17),cv2.FONT_HERSHEY_SIMPLEX,.43,(255,255,255),1,cv2.LINE_AA)
   cv2.imwrite(str(out/f'preview_{i:06}.jpg'),sheet,[cv2.IMWRITE_JPEG_QUALITY,91])
  # Independent whole-frame file and support checks.
  failures=[]
  for sub in ['pcf','geometry/P/mask','geometry/P/wire','geometry/Q/mask','geometry/Q/wire','move_replace/labels','move_replace/joint','move_replace/target_lamp_mask','source_visible_mask_B_estimated']:
   paths=sorted((out/sub).glob('*.png'))
   if len(paths)!=49:failures.append(f'{sub}: {len(paths)} files')
   for p in paths:
    im=cv2.imread(str(p),cv2.IMREAD_UNCHANGED)
    if im is None or im.shape[:2]!=(H,W):failures.append(f'{p.name} unreadable/wrong size in {sub}')
  support_mismatches=0
  for i in range(49):
   f=f'{i:06}.png';sel=cv2.imread(str(out/'move_replace/target_lamp_mask'/f),0)>0
   for typ,names in [('color',COLORS),('intensity',LEVELS)]:
    for name in names:
     folder=out/'move_replace'/(Path('lighting')/name/'color' if typ=='color' else Path('intensity')/name);z=np.load(folder/f'{i:06}.npz');a=z[typ];x,y=map(int,z['origin_xy']);full=np.zeros((H,W),bool);full[y:y+a.shape[0],x:x+a.shape[1]]=np.any(a!=0,axis=2)
     if not np.array_equal(full,sel):support_mismatches+=1
  if support_mismatches:failures.append(f'{support_mismatches} color/intensity support mismatches')
  if target_outside_max:failures.append(f'target outside Q max {target_outside_max}')
  if source_outside_max:failures.append(f'estimated source warp outside P max {source_outside_max}')
  if target_border_frames:failures.append(f'target touches border frames {target_border_frames}')
  validation={'frames':49,'resolution':[W,H],'records':records,'max_target_outside_Q':target_outside_max,'max_source_estimated_outside_P':source_outside_max,'target_border_frames':target_border_frames,'color_intensity_support_mismatches':support_mismatches,'camera':{'relative_angle_min':min(angles),'relative_angle_max':max(angles),'max_relative_perturbation_step_deg':max(step),'displacement_min':min(disp),'displacement_max':max(disp),'A_B_identical':bool(np.array_equal(A,B))},'failures':failures,'numeric_state':'pass' if not failures else 'fail','visual_state':'pending','loader_state':'original joint_frames executed; full legacy load_row conflicts with silhouette support because it asserts support == target bbox; not called as acceptance','model_inference':'not_run','target_mesh_occlusion':'all GLB triangles projected; scene occlusion and dynamic foreground not resolved'}
  (out/'validation.json').write_text(json.dumps(validation,indent=2))
  manifest={'case_id':case,'number':num,'revision':rev,'camera_version':version,'operation':'move_replace','source_sha256':json.loads((cd/'case.json').read_text())['source_sha256'],'asset_sha256':sha(Path('/root/autodl-tmp/codex_user8_move_replace_20261109/realcase_new_models')/f"{cfg['asset_number']}.glb"),'pcf_sha256':sha(pcfpath),'bbox_sha256':sha(CORE/'bbox.py'),'joint_loader_sha256':sha(LOADER),'frames':49,'resolution':[W,H],'color_linear_controls':COLORS,'intensity_legacy_log_controls_not_measured':LEVELS,'intensity_encoding':'log1p(L/100)/log1p(100000/100), experimental legacy adapter; not HF v2 raw gamma and not measured lumens','status':'experimental_not_quality_accepted','geometry_plan':'../geometry_plan.json','validation':'validation.json','target_B_RGB':'not_observed_not_supplied','uncertainty':plan['uncertainty']}
  (out/'manifest.json').write_text(json.dumps(manifest,indent=2));summary[version]={'numeric_state':validation['numeric_state'],'failures':failures,'camera':validation['camera']}
 (base/'batch_summary.json').write_text(json.dumps({'case_id':case,'versions':summary,'status':'experimental_not_quality_accepted'},indent=2))
 print(json.dumps({'case':case,'versions':summary}),flush=True)

if __name__=='__main__':
 configs=json.loads((ROOT/os.environ.get('PRODUCTION_CONFIG','production_config.json')).read_text());wanted=sys.argv[1:]
 for cfg in configs:
  if wanted and str(cfg['number']) not in wanted:continue
  run(cfg)