"""Filmcraft formats v3 verifier. Numeric rewards require complete deterministic checks. Run in a separate verifier container, or on externally collected artifacts. Missing grading evidence raises an infrastructure error; never infer app use. """ import argparse,hashlib,json,math,os,shutil,subprocess,tempfile from pathlib import Path from verifier_runtime import select_project import numpy as np from deterministic_checks import action_checks,GradingError,require_complete from PIL import Image TICKS=254016000000 SOURCES=['coffee-beans-closeup-4k.mp4','pouring-coffee-carafe-4k.mp4','hands-cup-pickup-4k.mp4'] BRAND='MiamiCoffeeInc.jpeg' EXPORTS={'final-01-horizontal.mp4':(1920,1080,False),'final-01-horizontal-branded.mp4':(1920,1080,True),'final-01-vertical.mp4':(1080,1920,False),'final-01-vertical-branded.mp4':(1080,1920,True)} POINTS=dict(zip(['a','c','d']+list('efghijklmnop'),[2,4,4,8,9,12,6,8,5,10,12,6,6,4,4])) LABELS=dict(zip(POINTS,['Filmcraft use','Four assets imported','Editable sequence created','Source order','First five seconds at normal speed','Decoded footage in four exports','Cuts and duration','H.264 MP4 dimensions and 30 fps','Export filenames and save directory','Fit and centered crop without stretching','Editable native project and links','Correct opaque branding image','Brand dimensions and margins','Continuous stationary branding','Unbranded outputs clean'])) assert sum(POINTS.values())==100 def digest(p): h=hashlib.sha256() with p.open('rb') as f: for block in iter(lambda:f.read(1024*1024),b''):h.update(block) return h.hexdigest() def run(args,timeout=120):return subprocess.run(args,capture_output=True,timeout=timeout) def probe(p): r=run(['ffprobe','-v','error','-show_streams','-show_format','-of','json',str(p)]) if r.returncode:raise ValueError(r.stderr.decode(errors='replace')[-1000:]) d=json.loads(r.stdout);s=next(s for s in d['streams'] if s['codec_type']=='video') return d,s def val(effect,name,default=None): p=effect.get('params',{}).get(name,{}) if p.get('keyframes'):return None v=p.get('value',{}) return next(iter(v.values()),default) if isinstance(v,dict) else v def normal(c,media): if c.get('speed',1)!=1 or c.get('reverse') or c.get('frame_hold') is not None:return False interpret=media.get('interpret',{}) if interpret.get('frame_rate'):return None for e in c.get('effects',[]): if e.get('enabled',True) and e.get('effect')=='time_remap': speed=val(e,'speed',100) if speed is None:return None if speed!=100:return False return True def geometry(c,media,w,h): """Resolve basic motion, including scale-to-frame and anchor offsets. Unknown effects/keyframes/PAR overrides defer to native/render review. """ v=media.get('info',{}).get('video') if not v:return None sw,sh=v['width'],v['height'];par=v.get('par',[1,1]);interp=media.get('interpret',{}) if interp.get('par') or par[0]!=par[1]:return None motion=None;opacity=100 for e in c.get('effects',[]): if not e.get('enabled',True):continue kind=e.get('effect') if kind=='motion':motion=e elif kind=='opacity': opacity=val(e,'opacity',100) if val(e,'blend',0)!=0:return None elif kind=='time_remap':continue else:return None if not motion:return None scale=val(motion,'scale',100);width=val(motion,'scale_width',100);uniform=val(motion,'uniform_scale',True) position=val(motion,'position',{'x':w/2,'y':h/2});anchor=val(motion,'anchor',{'x':sw/2,'y':sh/2});rotation=val(motion,'rotation',0) if any(x is None for x in [scale,width,uniform,position,anchor,rotation,opacity]):return None if rotation!=0:return {'upright':False,'opacity':opacity} base=min(w/sw,h/sh) if c.get('scale_to_frame') else 1 sy=base*scale/100;sx=sy if uniform else base*width/100 return {'x':position['x']-anchor['x']*sx,'y':position['y']-anchor['y']*sy,'w':sw*sx,'h':sh*sy,'sx':sx,'sy':sy,'upright':True,'opacity':opacity} def decoded_frames(p,w,h,filter_prefix='',limit=None): vf=filter_prefix+(',' if filter_prefix else '')+f'scale={w}:{h}:flags=area' args=['ffmpeg','-v','error','-threads','2','-i',str(p),'-an','-vf',vf] if limit:args+=['-frames:v',str(limit)] args+=['-pix_fmt','rgb24','-f','rawvideo','pipe:1'] r=run(args,timeout=600) if r.returncode:raise ValueError(r.stderr.decode(errors='replace')[-1000:]) size=w*h*3 if len(r.stdout)%size:raise ValueError('Partial decoded frame') return np.frombuffer(r.stdout,dtype=np.uint8).reshape(-1,h,w,3) def reference_frames(p,W,H): _,s=probe(p);sw,sh=s['width'],s['height'];scale=min(W/sw,H/sh) if W>H else max(W/sw,H/sh) rw=round(sw*scale);rh=round(sh*scale) vf=f'trim=start=0:end=5,setpts=PTS-STARTPTS,fps=30,scale={rw}:{rh}:flags=bicubic,setsar=1' vf+=f',pad={W}:{H}:(ow-iw)/2:(oh-ih)/2:black' if W>H else f',crop={W}:{H}:(iw-ow)/2:(ih-oh)/2' return decoded_frames(p,192 if W>H else 108,108 if W>H else 192,vf,150) def evaluate(workspace,report_dir,assets,access): out=workspace/'root/Desktop/task-01/output';project=out/'proj-task-01.fcproj' required_project=project;project=select_project(project) report_dir.mkdir(parents=True,exist_ok=True) manifest=json.loads((assets/'source-manifest.json').read_text()) rows={k:{'requirement':LABELS[k],'possible':v,'checks':[]} for k,v in POINTS.items()} def add(k,id,points,state,evidence): rows[k]['checks'].append({'id':id,'possible':points,'state':'unknown' if state is None else 'met' if state else 'unmet','evidence':str(evidence)}) def resolve(path): p=Path(path) return workspace/path.lstrip('/') if p.is_absolute() else project.parent/p doc={};project_error=None if project.is_file(): try: doc=json.loads(project.read_text()) if doc.get('format')!='filmcraft.project':raise ValueError('Unsupported native project format') except Exception as e:project_error=str(e);doc={} items=doc.get('project',{}).get('items',{});links={} for id,item in items.items(): media=item.get('kind',{}).get('Media',{});path=media.get('media',{}).get('File',{}).get('path') if not path:continue p=resolve(path);sha=digest(p) if p.is_file() else None name=next((n for n,v in manifest.items() if v['sha256']==sha),None) links[id]={'name':name,'valid':bool(name) and not media.get('offline',False),'path':path,'media':media} imported={l['name'] for l in links.values() if l['valid']} for name in SOURCES+[BRAND]:add('c',name,1,name in imported,'Hash verified native media records; initial environment is empty') trace=assets/'operator-trajectory.json' if not trace.is_file():raise GradingError('Missing private operator trajectory for app use') actions=action_checks(json.loads(trace.read_text()),workspace,SOURCES,assets) add('a','action-evidence',2,actions['app_use'],'Requires operator review of agent trajectory/app execution; project alone is insufficient') native=None;native_error=None if project.is_file() and doc and shutil.which('filmcraft-cli'): result=run(['filmcraft-cli','--project',str(project),'inspect'],timeout=180) (report_dir/'native-inspection.stdout').write_bytes(result.stdout) (report_dir/'native-inspection.stderr').write_bytes(result.stderr) if result.returncode==0: try:native=json.loads(result.stdout) except ValueError:native_error='Native inspect emitted invalid JSON' else:native_error='Native load failed; review stderr for app/dependency versus project failure' seqs=[] for id,item in items.items(): s=item.get('kind',{}).get('Sequence') if not s:continue footage=[];brands=[];other=[];trans=[] tracks=s.get('video_tracks',[]);solo=any(t.get('solo') for t in tracks) for t in tracks: if not t.get('enabled',True) or (solo and not t.get('solo')):continue trans+=t.get('transitions',[]) for c in t.get('items',[]): if not c.get('enabled',True):continue link=links.get(str(c.get('item')),{});name=link.get('name') if name in SOURCES:footage.append(c) elif name==BRAND:brands.append(c) else:other.append(c) footage.sort(key=lambda c:c.get('start',0)) seqs.append({'id':id,'seq':s,'clips':footage,'brands':brands,'other':other,'trans':trans}) relevant=[s for s in seqs if s['clips']] editable=bool(relevant) and bool(native) add('d','new-source-backed-sequence',4,editable if native is not None or not project.exists() else None,'Native load and saved source-backed sequence; '+str(native_error)) # Conservative aggregation across all footage edits. Nested/nonstandard structures need review. orders=[[links[str(c['item'])]['name'] for c in s['clips']] for s in relevant] for i,name in enumerate(SOURCES): ok=bool(orders) and all(len(o)>i and o[i]==name for o in orders) add('e',f'position-{i}',2,ok if relevant or not project.exists() else None,orders) add('e','exact-order',2,bool(orders) and all(o==SOURCES for o in orders) and all(not s['other'] for s in relevant) if relevant or not project.exists() else None,orders) for name in SOURCES: clips=[c for s in relevant for c in s['clips'] if links[str(c['item'])]['name']==name] for prop in ['source-zero','five-seconds','normal']: values=[abs(c.get('source_in',0)/TICKS)<=1/30 if prop=='source-zero' else abs(c.get('duration',0)/TICKS-5)<=1/30 if prop=='five-seconds' else normal(c,links[str(c['item'])]['media']) for c in clips] ok=(all(values) if None not in values else None) if values else False if not project.exists() else None add('f',name+'/'+prop,1,ok,values) native_bounds=[] for idx in [1,2]: v=[len(s['clips'])>idx and abs(s['clips'][idx]['start']/TICKS-idx*5)<=1/30 and not s['trans'] for s in relevant] add('h',f'native-cut-{idx}',1,all(v) if v else False if not project.exists() else None,v) gap=[] for s in relevant: cs=s['clips'];gap.append(len(cs)==3 and not s['other'] and not s['trans'] and abs(cs[0]['start']/TICKS)<=1/30 and all(abs((cs[i-1]['start']+cs[i-1]['duration']-cs[i]['start'])/TICKS)<=1/30 for i in [1,2]) and abs((cs[-1]['start']+cs[-1]['duration'])/TICKS-15)<=1/30) add('h','native-duration-gapfree',1,all(gap) if gap else False if not project.exists() else None,gap) add('l','filename',1,required_project.is_file(),'Exact project submission filename') add('l','directory',1,project.is_file(),'Original workspace path; restore collected workspace layout') add('l','native-load',3,bool(native) if native is not None or not project.exists() else None,native_error or 'Native inspect success' if native else 'Native app load unverified') dims={(s['seq'].get('settings',{}).get('width'),s['seq'].get('settings',{}).get('height')) for s in relevant} brand_seqs=[s for s in seqs if any(links.get(str(c.get('item')),{}).get('name')==BRAND for t in s['seq'].get('video_tracks',[]) for c in t.get('items',[]))] add('l','editable-orientations-overlays',3,(editable and {(1920,1080),(1080,1920)}<=dims and bool(brand_seqs)) if native is not None or not project.exists() else None,'Source-backed footage and image clips; equivalent nested arrangements require review') for name in SOURCES+[BRAND]:add('l','link/'+name,1,name in imported,'Actual resolved source hash') cache={};probes={};visual={} for filename,(W,H,branded) in EXPORTS.items(): p=out/filename;present=p.is_file();frames=None;s={};d={};decode_error=None if present: try:d,s=probe(p);frames=decoded_frames(p,192 if W>H else 108,108 if W>H else 192) except Exception as e:decode_error=str(e) valid=frames is not None and len(frames)>0 probes[filename]={'present':present,'probe':d,'decode_error':decode_error,'frames':len(frames) if valid else 0} add('j',filename+'/name',.75,present,'Exact requested filename') add('j',filename+'/directory',.5,present,'Original submission workspace path') fps=s.get('avg_frame_rate','0/1').split('/');rate=float(fps[0])/max(1,float(fps[1])) timestamp_ok=False if valid: r=run(['ffprobe','-v','error','-select_streams','v:0','-show_entries','frame=best_effort_timestamp_time','-of','json',str(p)],timeout=180) if r.returncode==0: ts=[float(f['best_effort_timestamp_time']) for f in json.loads(r.stdout)['frames'] if 'best_effort_timestamp_time' in f] timestamp_ok=len(ts)==len(frames) and len(ts)>1 and max(abs((b-a)-1/30) for a,b in zip(ts,ts[1:]))<.0001 for prop,ok in [('container','mp4' in d.get('format',{}).get('format_name','')),('codec',s.get('codec_name')=='h264'),('dimensions',(s.get('width'),s.get('height'))==(W,H) and not any('rotation' in x and x['rotation']%360 for x in s.get('side_data_list',[])) and s.get('sample_aspect_ratio','1:1') in ['1:1','N/A']),('fps',abs(rate-30)<.001 and timestamp_ok)]:add('i',filename+'/'+prop,.5,valid and ok,'Decoded export probe/timestamps') matches=[];errors=[] if valid: for i,name in enumerate(SOURCES): key=(name,W,H) if key not in cache:cache[key]=reference_frames(assets/'reference'/name,W,H) ref=cache[key];segment=frames[i*150:(i+1)*150] if len(segment)!=150 or len(ref)!=150:matches.append(False);errors.append(None);continue mask=np.ones(segment.shape[1:3],bool) if branded: # Ignore branding-covered pixels only for footage comparison. bw=320 if W>H else 240;bh=bw*506/1024;margin=48 if W>H else 32 y0=max(0,int((H-margin-bh)/H*mask.shape[0])-2);x0=max(0,int((W-margin-bw)/W*mask.shape[1])-2) mask[y0:,x0:]=False delta=np.abs(segment.astype(np.float32)-ref.astype(np.float32))[:,mask,:].mean(axis=(1,2)) # Adjacent frames allow 25/29.97-to-30 resampling. Starts/cut boundaries stay explicit. for shift in [-1,1]: alt=np.roll(ref,shift,axis=0);alt_delta=np.abs(segment.astype(np.float32)-alt.astype(np.float32))[:,mask,:].mean(axis=(1,2));alt_delta[:2]=delta[:2];alt_delta[-2:]=delta[-2:];delta=np.minimum(delta,alt_delta) errors.append({'mean':float(delta.mean()),'p99':float(np.quantile(delta,.99)),'max':float(delta.max())}) matches.append(bool(np.quantile(delta,.99)<=12 and delta.max()<=22)) else:matches=[False]*3 visual[filename]={'segment_matches':matches,'errors':errors,'method':'All decoded frames at 1/10 display size; source-time reference, adjacent-frame allowance; MAE p99<=12, max<=22. Filmcraft-specific calibration still requires live fixtures.'} for i in range(3):add('g',filename+f'/segment-{i}',1,True if valid and matches[i] else False,visual[filename]) for i in [1,2]:add('h',filename+f'/cut-{i}',.25,True if valid and matches[i-1] and matches[i] and len(frames)==450 else False,'Decoded source mapping through boundary') duration=float(d.get('format',{}).get('duration',0));add('h',filename+'/duration-gapfree',.25,valid and len(frames)==450 and abs(duration-15)<=1/30 if not valid or all(matches) else None,'Decoded frame count and full-duration source mapping') # Project geometry corroborated by matching decoded footage. selected=[q for q in relevant if (q['seq']['settings'].get('width'),q['seq']['settings'].get('height'))==(W,H)] geoms=[] for i,name in enumerate(SOURCES): gs=[geometry(c,links[str(c['item'])]['media'],W,H) for q in selected for c in q['clips'] if links[str(c['item'])]['name']==name] understood=bool(gs) and all(g and 'sx' in g for g in gs) proportional=understood and all(abs(g['sx']-g['sy'])<1e-5 for g in gs) framed=understood and all(abs(g['x']-(W-g['w'])/2)<=2 and abs(g['y']-(H-g['h'])/2)<=2 and (abs(max(g['w']/W,g['h']/H)-1)<.003 if W>H else abs(min(g['w']/W,g['h']/H)-1)<.003) for g in gs) add('k',filename+f'/shot-{i}/frame',.5,True if valid and matches[i] and framed else False,gs) add('k',filename+f'/shot-{i}/proportional',1/3,True if valid and matches[i] and proportional else False,gs) brand_match=None if branded: bw=320 if W>H else 240;bh=bw*506/1024;margin=48 if W>H else 32 gs=[geometry(c,links[str(c['item'])]['media'],W,H) for q in seqs if (q['seq']['settings'].get('width'),q['seq']['settings'].get('height'))==(W,H) for t in q['seq'].get('video_tracks',[]) for c in t.get('items',[]) if links.get(str(c.get('item')),{}).get('name')==BRAND] gs=[g for g in gs if g] # Full-resolution crop every frame verifies entire JPEG/background and opacity. if valid: x=W-margin-bw;y=round(H-margin-bh);hh=round(bh) patch=decoded_frames(p,bw,hh,f'format=rgb24,crop={bw}:{hh}:{x}:{y}:exact=1') ref=np.asarray(Image.open(assets/'reference'/BRAND).convert('RGB').resize((bw,hh),Image.Resampling.BICUBIC)).astype(np.float32) dist=np.abs(patch.astype(np.float32)-ref).mean(axis=(1,2,3)) brand_match=bool(len(patch)==450 and np.quantile(dist,.99)<14 and dist.max()<22) visual[filename]['branding_error']={'mean':float(dist.mean()),'max':float(dist.max()),'all_frames':len(patch)} if len(patch) else {} upright=bool(gs) and any(g.get('upright') and 'w' in g for g in gs) geom=next((g for g in gs if g.get('upright') and 'w' in g and abs(g['w']-bw)<=2 and abs(W-g['x']-g['w']-margin)<=2 and abs(H-g['y']-g['h']-margin)<=2),None) for prop in ['identity','entire-upright','opacity']: ok=brand_match and bool(gs) if prop=='identity' else brand_match and upright if prop=='entire-upright' else brand_match and any(g.get('opacity')==100 for g in gs) add('m',filename+'/'+prop,1,True if ok else False,'Full-resolution branding crop across every frame and hash-linked image transforms') for prop,pts,ok in [('width',1,geom and abs(geom['w']-bw)<=2),('proportions',1,geom and abs(geom['w']/geom['h']-1024/506)<.02),('right',.5,geom and abs(W-geom['x']-geom['w']-margin)<=2),('bottom',.5,geom and abs(H-geom['y']-geom['h']-margin)<=2)]:add('n',filename+'/'+prop,pts,True if brand_match and ok else False,gs) intervals=[(c['start']/TICKS,(c['start']+c['duration'])/TICKS) for q in seqs if (q['seq']['settings'].get('width'),q['seq']['settings'].get('height'))==(W,H) for t in q['seq'].get('video_tracks',[]) for c in t.get('items',[]) if links.get(str(c.get('item')),{}).get('name')==BRAND] coverage=0 for a,b in sorted(intervals): if a<=coverage+1/30:coverage=max(coverage,b) add('o',filename+'/visible',1,True if brand_match and coverage>=15-1/30 else False,intervals) add('o',filename+'/stationary',1,True if brand_match and geom and coverage>=15-1/30 else False,'All decoded frames and static geometry/opacity') else:add('p',filename+'/clean',2,True if valid and all(matches) else False,'Full-frame source comparison throughout all segments; source text is allowed') # Optional operator-reviewed atoms with hash binding; never trust agent-authored evidence. submission={p.name:digest(p) for p in out.iterdir() if p.is_file()} if out.is_dir() else {} review_path=report_dir/'operator-review.json' review=json.loads(review_path.read_text()) if review_path.exists() else {} review_valid=review.get('submission_sha256')==submission and bool(review.get('reviewer')) and bool(review.get('evidence')) for k,row in rows.items(): assert math.isclose(sum(c['possible'] for c in row['checks']),row['possible']),k row['earned']=sum(c['possible'] for c in row['checks'] if c['state']=='met') row['unresolved']=sum(c['possible'] for c in row['checks'] if c['state']=='unknown') row['status']='unknown' if row['unresolved'] else 'met' if math.isclose(row['earned'],row['possible']) else 'partially_met' if row['earned'] else 'unmet' earned=sum(r['earned'] for r in rows.values());unknown=sum(r['unresolved'] for r in rows.values()) policy=review.get('policy','unknown') if review_valid else 'unknown' if access=='terminal':policy='pass' # No terminal prohibition; Filmcraft use scored separately. if policy not in ['pass','fail','unknown']:policy='unknown' result={'rubric_version':'01-A-name-formats-v3','rubric':rows,'resolved_score':round(earned,6),'unresolved_points':round(unknown,6),'score_range':[round(earned,6),round(earned+unknown,6)],'policy':policy,'access':access,'evaluation_validity':'resolved' if unknown==0 else 'partial evidence; review unknown checks','project_error':project_error,'native_error':native_error,'exports':probes,'visual_evidence':visual,'submission_sha256':submission,'operator_review_applied':review_valid,'limitations':['Checks use fixed native schema, decoded-frame tolerances and private action/screenshot evidence.','Unsupported structures or missing grading evidence raise a verifier error and withhold reward.','Fixture and saved-attempt regression results are recorded separately from oracle validation.']} require_complete(result) (report_dir/'rubric.json').write_text(json.dumps(result,indent=2)+'\n') (report_dir/'review-template.json').write_text(json.dumps({'reviewer':'','evidence':[],'submission_sha256':submission,'policy':'unknown','checks':{k+'/'+c['id']:{'state':'unknown','evidence':''} for k,r in rows.items() for c in r['checks'] if c['state']=='unknown'}},indent=2)+'\n') rewards={'reward':earned/100,'score_points':earned,'unresolved_points':unknown,'possible_upper_bound':(earned+unknown)/100} (report_dir/'reward.json').write_text(json.dumps(rewards,indent=2)+'\n') return result def main(): from verifier_runtime import cli_main cli_main(evaluate,Path(__file__).resolve().parent) if __name__=='__main__':main()