import json,cv2,numpy as np,hashlib,os from pathlib import Path ROOT=Path('/root/autodl-tmp/kimi_realcase_20261109') INV=json.loads((ROOT/'inventory_sources.json').read_text()) CONFIG=json.loads((ROOT/os.environ.get('BATCH_CONFIG','first_batch_config.json')).read_text()) W,H=1280,704 def cover(fr,nearest=False): h,w=fr.shape[:2];scale=max(W/w,H/h);nw,nh=round(w*scale),round(h*scale) interp=cv2.INTER_NEAREST if nearest else cv2.INTER_AREA fr=cv2.resize(fr,(nw,nh),interpolation=interp);x=(nw-W)//2;y=(nh-H)//2 return fr[y:y+H,x:x+W],{'source_wh':[w,h],'scale':scale,'resized_wh':[nw,nh],'crop_xy':[x,y],'output_wh':[W,H]} def mask_score(r): best=None for m in r['mask_videos']: vals=[s['nonzero_px'] or 0 for s in m['samples']];score=float(np.median(vals)) if best is None or score>best[0]:best=(score,m['file']) if not best:raise RuntimeError('no dataset mask prompt candidate') return best[1] manifest=[] for cfg in CONFIG: r=INV['records'][cfg['inventory_index']] assert r['source_sha256'] and r['probe']['frames_metadata']>=49 case=cfg['case_id'];cd=ROOT/'cases'/case;sd=ROOT/'samples'/case if cd.exists(): existing=json.loads((cd/'case.json').read_text());manifest.append(existing) print(json.dumps({'case':case,'status':'already_preserved'}),flush=True) continue for sub in ['frames','segmentation/lamp0']:(cd/sub).mkdir(parents=True,exist_ok=False) sd.mkdir(parents=True) src=r['source_path'];mask_file=mask_score(r);mask_src=str(Path(r['raw_dir'])/mask_file) cap=cv2.VideoCapture(src);mcap=cv2.VideoCapture(mask_src) fps=float(cap.get(5));n=int(cap.get(7));mfps=float(mcap.get(5));mn=int(mcap.get(7)) frame_map=[];transform=None for i in range(49): si=min(int(round(i*fps/10.0)),n-1);mi=min(int(round(i*mfps/10.0)),mn-1) cap.set(cv2.CAP_PROP_POS_FRAMES,si);ok,fr=cap.read() mcap.set(cv2.CAP_PROP_POS_FRAMES,mi);mok,mfr=mcap.read() if not ok or not mok:raise RuntimeError(f'decode failed {case} frame {i} source {si} mask {mi}') fr,transform=cover(fr);mfr,_=cover(mfr,nearest=True) mask=(mfr.mean(axis=2)>127).astype(np.uint8)*255 cv2.imwrite(str(cd/'frames'/f'{i:03}.png'),fr) cv2.imwrite(str(cd/'segmentation/lamp0'/f'{i:03}.png'),mask) frame_map.append({'output_frame':i,'source_frame':si,'mask_source_frame':mi,'source_time_seconds':si/fps,'mask_time_seconds':mi/mfps}) cap.release();mcap.release() cfg2=dict(cfg);cfg2.update({'source_path':src,'source_sha256':r['source_sha256'],'source_size':r['source_size'],'raw_dir':r['raw_dir'],'mask_prompt_video':mask_src,'mask_prompt_semantics':'dataset-derived candidate prompt only; completeness and identity require visual review','source_probe':r['probe'],'frame_map':frame_map,'cover_transform':transform,'status':'prepared'}) (cd/'case.json').write_text(json.dumps(cfg2,ensure_ascii=False,indent=2)) manifest.append(cfg2) print(json.dumps({'case':case,'frames':49,'mask_prompt':mask_file,'source_sha256':r['source_sha256']}),flush=True) (ROOT/os.environ.get('BATCH_OUTPUT','first_batch_prepared.json')).write_text(json.dumps(manifest,ensure_ascii=False,indent=2))