"""Private, renderer-backed FilmCraft masking verifier. Never mount /tests for the agent.""" import argparse,copy,hashlib,json,math,subprocess,sys,os,shutil from pathlib import Path from functools import lru_cache import numpy as np import cv2 TICKS=254016000000 RUBRIC=[('files','Correct supplied video and audio files',10),('imports','Files imported into FilmCraft',10),('dimensions','1920×1080 sequence at 24 fps',10),('rectangles','Perfectly rectangular masks',20),('planes','Flyover 01:39–01:58; planes always visible',15),('mug_range','Mug before 00:03; handle always visible',15),('basketball_start','Basketball starts from source beginning',5),('borders','No black borders at top or bottom',10),('beats','Sequential entrances on beats; earlier clips stay',5)] class GradingError(RuntimeError):pass def run(args): p=subprocess.run(args,capture_output=True,timeout=900) if p.returncode:raise GradingError('Command failed '+str(p.returncode)+' '+str(args[:3])+': '+p.stderr.decode(errors='replace')[-1500:]) return p.stdout @lru_cache(maxsize=128) def digest(p): h=hashlib.sha256() with open(p,'rb') as f: for b in iter(lambda:f.read(1048576),b''):h.update(b) return h.hexdigest() def val(p,default=None): if p.get('keyframes'):raise GradingError('Animated parameter requires an extended renderer adapter') v=p.get('value',{}) return next(iter(v.values()),default) def frame(p,t,w,h): cache=os.environ.get('MASKING_FRAME_CACHE') key=hashlib.sha256(f'{digest(p)}:{max(0,t):.9f}:{w}:{h}'.encode()).hexdigest() f=Path(cache)/(key+'.npy') if cache else None if f and f.exists():return np.load(f) raw=run(['ffmpeg','-v','error','-ss',str(max(0,t)),'-i',str(p),'-frames:v','1','-vf',f'scale={w}:{h}','-pix_fmt','rgb24','-f','rawvideo','pipe:1']) if len(raw)!=w*h*3:raise GradingError('Unreadable source frame') im=np.frombuffer(raw,np.uint8).reshape(h,w,3) if f: f.parent.mkdir(parents=True,exist_ok=True);np.save(f,im) return im def geom(c,m,W,H): motion=next((e for e in c['effects'] if e['effect']=='motion' and e.get('enabled',True)),None) if motion is None:raise GradingError('Missing motion data') ps=motion['params'];g=lambda k,d:val(ps.get(k,{}),d) sw,sh=m['info']['video']['width'],m['info']['video']['height'] if m.get('interpret',{}).get('par') or m.get('interpret',{}).get('frame_rate'):raise GradingError('Unsupported media reinterpretation') base=min(W/sw,H/sh) if c.get('scale_to_frame') else 1 sy=base*g('scale',100)/100;sx=sy if g('uniform_scale',True) else base*g('scale_width',100)/100 angle=math.radians(g('rotation',0));A=np.array([[sx*math.cos(angle),-sy*math.sin(angle)],[sx*math.sin(angle),sy*math.cos(angle)]]) a=g('anchor',{'x':sw/2,'y':sh/2});p=g('position',{'x':W/2,'y':H/2});b=np.array([p['x'],p['y']])-A@np.array([a['x'],a['y']]) return np.column_stack([A,b]),sw,sh def rect(c,M): masks=[m for e in c.get('effects',[]) if e.get('enabled',True) and e['effect']=='opacity' for m in e.get('masks',[])] if len(masks)!=1:return False,None m=masks[0];p=val(m.get('path',{})); if not p or not p.get('closed') or len(p.get('vertices',[]))!=4:return False,None if any(any(k!='p' for k in v) for v in p['vertices']):return False,None pts=np.array([[v['p']['x'],v['p']['y']] for v in p['vertices']]);q=pts@M[:,:2].T+M[:,2];edge=np.roll(q,-1,axis=0)-q lengths=np.linalg.norm(edge,axis=1) perpendicular=all(abs(float(edge[i]@edge[(i+1)%4]))/(lengths[i]*lengths[(i+1)%4]+1e-12)<1e-6 for i in range(4)) axis=all(min(abs(v[0]),abs(v[1]))<.01 for v in edge) hard=val(m.get('feather',{}),0)==0 and val(m.get('opacity',{}),100)==100 and val(m.get('expansion',{}),0)==0 and not m.get('inverted') and m.get('mode','Add')=='Add' op=next(e for e in c['effects'] if e['effect']=='opacity');hard &= val(op['params'].get('opacity',{}),100)==100 and val(op['params'].get('blend',{}),0)==0 return bool(perpendicular and hard and min(lengths)>1),[float(q[:,0].min()),float(q[:,1].min()),float(q[:,0].max()),float(q[:,1].max())] def audio_beats(p): raw=run(['ffmpeg','-v','error','-i',str(p),'-t','20','-ar','22050','-ac','1','-f','f32le','pipe:1']);x=np.frombuffer(raw,np.float32) hop=220;N=1024;spec=np.abs(np.fft.rfft(np.array([x[i:i+N]*np.hanning(N) for i in range(0,len(x)-N,hop)]))) # Bass kick energy and positive spectral flux; local maxima with minimum 180ms separation. bass=(spec[:,1:9]**2).sum(1);flux=np.maximum(np.diff(spec,axis=0,prepend=spec[:1]),0).sum(1) def peaks(v): smooth=np.convolve(v,np.ones(3)/3,'same');inds=[i for i in range(1,len(v)-1) if smooth[i]>=smooth[i-1] and smooth[i]>smooth[i+1] and smooth[i]>np.quantile(smooth,.65)] selected=[] for i in sorted(inds,key=lambda i:smooth[i],reverse=True): if all(abs(i-j)>18 for j in selected):selected.append(i) return [(i*hop+N/2)/22050 for i in selected] return sorted(set([0.]+peaks(flux))) def grade(project,e,out): for tool in ['ffmpeg','filmcraft-cli']: if not shutil.which(tool):raise GradingError('Missing grading tool: '+tool) d=json.loads(Path(project).read_text()); if d.get('format')!='filmcraft.project':raise GradingError('Unreadable/unsupported project format') sid=str(d.get('view',{}).get('active_sequence','')) if sid not in d['project']['items']: ids=[k for k,v in d['project']['items'].items() if 'Sequence' in v['kind']] if len(ids)!=1:raise GradingError('Select one active sequence') sid=ids[0] s=d['project']['items'][sid]['kind'].get('Sequence') if not s:raise GradingError('Active item is not a sequence') W,H=s['settings']['width'],s['settings']['height'];fps=s['settings']['frame_rate']['num']/s['settings']['frame_rate']['den'] result={k:False for k,_,_ in RUBRIC};details={};result['dimensions']=(W,H)==(1920,1080) and abs(fps-24)<1e-9 for v in e['sources'].values(): if not Path(v['path']).is_file() or digest(v['path'])!=v['sha256']:raise GradingError('Private source evidence missing or changed') imported=set() for item in d['project']['items'].values(): m=item.get('kind',{}).get('Media');f=m.get('media',{}).get('File',{}).get('path') if m else None if f and Path(f).is_file():imported.add(digest(f)) result['files']=all(v['sha256'] in imported for v in e['sources'].values()) result['imports']=result['files'] and all(item.get('kind',{}).get('Media',{}).get('offline',False)==False for item in d['project']['items'].values()) cs=[c for t in s['video_tracks'] if t.get('enabled',True) and not t.get('muted') for c in t['items'] if c.get('enabled',True)] by={};roles={v['sha256']:k for k,v in e['sources'].items()} for c in cs: m=d['project']['items'][str(c['item'])]['kind'].get('Media') if m is None:raise GradingError('Nested sequences require adapter') f=m['media'].get('File',{}).get('path');role=roles.get(digest(f)) if f and Path(f).is_file() else None if role in ['basketball','flyover','cup'] and role not in by:by[role]=(c,m) sources_ok=len(cs)==3 and len(by)==3 if not sources_ok:return result,{'reason':'Expected three distinct supplied source clips'},None boxes={};maps={};rectangle=[] for role,(c,m) in by.items(): if c.get('reverse') or c.get('frame_hold') is not None or c.get('speed',1)!=1:raise GradingError('Retime adapter required') for fx in c['effects']: if fx.get('enabled',True) and fx['effect'] not in ['motion','opacity','time_remap']:raise GradingError('Unsupported effect: '+fx['effect']) if fx['effect']=='time_remap' and val(fx['params'].get('speed',{}),100)!=100:raise GradingError('Time remap adapter required') M,sw,sh=geom(c,m,W,H);maps[role]=(M,sw,sh);ok,b=rect(c,M);rectangle.append(ok);boxes[role]=b result['rectangles']=all(rectangle) and all(boxes[r] is not None for r in by) and boxes['basketball'][0]2*W/3 and boxes['basketball'][2]<=boxes['flyover'][0]+1 and boxes['flyover'][2]<=boxes['cup'][0]+1 if any(b is None for b in boxes.values()):return result,{'reason':'Missing four-point closed opacity mask'},None result['basketball_start']=by['basketball'][0]['source_in']==0 ranges={} for role in ['flyover','cup']: c=by[role][0];ranges[role]=[c['source_in']/TICKS,(c['source_in']+c['duration'])/TICKS] plane_range=ranges['flyover'][0]>=99 and ranges['flyover'][1]<=118 mug_range=ranges['cup'][0]>=0 and ranges['cup'][1]<=3 end=max((c['start']+c['duration'])/TICKS for c,_ in by.values());start=[by[r][0]['start']/TICKS for r in ['basketball','flyover','cup']] if end>30 or fps<=0 or fps>120:raise GradingError('Unsupported duration/frame rate for current adapter') music=[c for t in s['audio_tracks'] if t.get('enabled',True) and not t.get('muted') for c in t['items'] if c.get('enabled',True) and str(c['item']) in d['project']['items'] and d['project']['items'][str(c['item'])].get('kind',{}).get('Media',{}).get('media',{}).get('File',{}).get('path') and digest(d['project']['items'][str(c['item'])]['kind']['Media']['media']['File']['path'])==e['sources']['music']['sha256']] beats=audio_beats(e['sources']['music']['path']);beatdist=[] if len(music)==1: a=music[0];offset=(a['start']-a['source_in'])/TICKS beatdist=[min(abs(t-(b+offset)) for b in beats) for t in start] ordered=sorted(by.values(),key=lambda cm:cm[0]['start']);ordered_start=[cm[0]['start']/TICKS for cm in ordered] result['beats']=ordered_start[0]ordered_start[i+1] for i in range(2)) and a['start']/TICKS<=min(start) and (a['start']+a['duration'])/TICKS>=end-1/fps # Render every frame with the actual FilmCraft renderer. Remove only audio from verifier copy. nd=copy.deepcopy(d);nd['project']['items'][sid]['kind']['Sequence']['audio_tracks']=[] if abs(fps-24)>1e-9: nd['project']['items'][sid]['kind']['Sequence']['settings']['frame_rate']={'num':24,'den':1};fps=24 p=out/'render-input.fcproj';p.write_text(json.dumps(nd));video=out/'native-render.mp4' run(['filmcraft-cli','--data-dir',str(out/'filmcraft-data'),'--project',str(p),'export',str(video),'--format','h264','--start','0','--end',str(end),'--gpu-rendering','off','--no-audio','--scale','0.25']) w,h=round(W*.25),round(H*.25);raw=run(['ffmpeg','-v','error','-i',str(video),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);frames=np.frombuffer(raw,np.uint8).reshape(-1,h,w,3) if abs(len(frames)-end*fps)>2:raise GradingError('Native frame count disagrees with timeline') errors=[];border=True;plane_count=0;handle_count=0;sample_count={};visible={};subject_total={};subject_pass={} for role,(c,m) in by.items(): M,sw,sh=maps[role];b=np.array(boxes[role]);x0,y0,x1,y1=b corners=np.array([[0,0],[sw,0],[sw,sh],[0,sh]])@M[:,:2].T+M[:,2] border &= y0<=.5 and y1>=H-.5 and corners[:,1].min()<=.5 and corners[:,1].max()>=H-.5 j0=max(0,int(math.ceil(c['start']/TICKS*fps-1e-6)));j1=min(len(frames),int(round((c['start']+c['duration'])/TICKS*fps))) l=max(0,int(math.ceil(x0/4))+2);r=min(w,int(math.floor(x1/4))-2);sample_count[role]=0;visible[role]=[];subject_total[role]=0;subject_pass[role]=0 if r<=l:border=False;continue for j in range(j0,j1): im=frames[j]; if np.mean(im[:2,l:r].max(axis=2)<12)>.98 or np.mean(im[-2:,l:r].max(axis=2)<12)>.98:border=False t=c['source_in']/TICKS+j/fps-c['start']/TICKS;src=frame(e['sources'][role]['path'],t,round(sw/4),round(sh/4));A=M.copy();A[:,2]/=4 ref=cv2.warpAffine(src,A,(w,h));op=next(e for e in c['effects'] if e['effect']=='opacity');ref=255*np.power(np.power(ref.astype(float)/255,2.2)*val(op['params'].get('opacity',{}),100)/100,1/2.2);mae=float(np.abs(ref[:,l:r].astype(float)-im[:,l:r].astype(float)).mean());errors.append(mae);sample_count[role]+=1 if role=='flyover': subject_total[role]+=1 gray=cv2.cvtColor(src,cv2.COLOR_RGB2GRAY);mask=(gray<40).astype(np.uint8);mask[int(mask.shape[0]*.83):]=0 n,labels,stats,_=cv2.connectedComponentsWithStats(mask) objs=[] for a in stats[1:]: x,y,bw,bh,area=map(int,a) if area>=8 and 8<=bw<=160 and 2<=bh<=40 and bw>bh*1.5 and 20=l+1 and q[1,0]<=r-1 and q[0,1]>=1 and q[1,1]<=h-1] if len(contained)>=1:plane_count+=1;subject_pass[role]+=1;visible[role].append(round(t,3)) if role=='cup': subject_total[role]+=1 bx=e['handle']['box'];q=np.array([[bx[0]/4,bx[1]/4],[bx[2]/4,bx[3]/4]])@A[:,:2].T+A[:,2] if q[0,0]>=l+1 and q[1,0]<=r-1 and q[0,1]>=1 and q[1,1]<=h-1:handle_count+=1;subject_pass[role]+=1;visible[role].append(round(t,3)) # Pixel agreement binds geometry/subject evidence to what the native renderer actually displays. if not errors or max(errors)>24 or np.quantile(errors,.95)>15:raise GradingError('Source-to-render mapping not validated: '+str(max(errors) if errors else None)) result['planes']=plane_range and subject_total['flyover']>0 and subject_pass['flyover']==subject_total['flyover'] result['mug_range']=mug_range and subject_total['cup']>0 and subject_pass['cup']==subject_total['cup'] result['borders']=bool(border) details={'source_ranges_seconds':ranges,'subject_frames_total':subject_total,'subject_frames_pass':subject_pass,'panel_boxes':boxes,'starts_seconds':start,'end_seconds':end,'beat_distances_seconds':beatdist,'music_beats_seconds':beats,'native_frames':len(frames),'max_mapping_mae':max(errors),'samples':sample_count,'subject_visible_source_seconds':visible,'limitations':['Flyover selected source range must be contained in 99–118 seconds; cup before 3 seconds; subject containment is checked in every active frame. File finding/import are verified as saved imported media outcomes, not inferred GUI actions.','Static mask/motion adapter; unsupported curves/effects yield verifier error, never a numeric score.','No export requirement: native render is operator grading evidence, not an agent deliverable.']} return result,details,video def main(): a=argparse.ArgumentParser();a.add_argument('--project',required=True);a.add_argument('--evidence',required=True);a.add_argument('--report-dir',required=True);args=a.parse_args();out=Path(args.report_dir);out.mkdir(parents=True,exist_ok=True) for f in ['reward.txt','reward.json']:(out/f).unlink(missing_ok=True) try: e=json.loads(Path(args.evidence).read_text());r,details,video=grade(args.project,e,out);criteria=[{'id':k,'name':label,'weight':weight,'verdict':'pass' if r[k] else 'fail','score':weight if r[k] else 0,'explanation':label+(' passed' if r[k] else ' failed')} for k,label,weight in RUBRIC];score=sum(x['score'] for x in criteria)/100 report={'status':'graded','score':score,'criteria':criteria,'details':details,'project_sha256':digest(args.project)};(out/'reward.txt').write_text(str(score)+'\n');code=0 except Exception as ex: report={'status':'verifier_error','error':type(ex).__name__+': '+str(ex),'criteria':[],'score':None};code=2 (out/'rubric_report.json').write_text(json.dumps(report,indent=2));print(json.dumps({'status':report['status'],'score':report['score'],'error':report.get('error')}));return code if __name__=='__main__':sys.exit(main())