"""Content-single v4. Grading only in the isolated verifier / external operator workspace.""" import argparse,json,math,shutil from pathlib import Path from verifier_runtime import select_project import numpy as np from deterministic_checks import action_checks,GradingError,require_complete from media_helpers import digest,run,probe,normal,geometry,decoded_frames,reference_frames,TICKS SOURCES=['k2wwwwt2y.mp4','7876094154.mp4','edhbasbnr.mp4'] POINTS=dict(zip(['a','c','d']+list('efghijklmn'),[2,4,4,8,8,9,15,8,8,5,7,12,10])) LABELS=dict(zip(POINTS,['Filmcraft use','Correct targets imported','Editable sequence created','Visual identification of three targets','Three targets in order','First five seconds normal forward speed','Decoded MP4 source ranges','Straight cuts and 15 seconds without gaps','1080p H.264 MP4 at 30 fps','Filename and coffee-ad output path','Proportional full-image fit','Native editable project with source links','Five distractors absent from contributing footage'])) assert sum(POINTS.values())==100 def evaluate(workspace,report_dir,assets,access): report_dir.mkdir(parents=True,exist_ok=True);out=workspace/'root/Desktop/coffee-ad/output';project=out/'proj-task-01.fcproj';video=out/'final01.mp4' required_project=project;project=select_project(project) manifest=json.loads((assets/'source-manifest.json').read_text());distractors=[n for n in manifest if n not in SOURCES] rows={k:{'requirement':LABELS[k],'possible':pts,'checks':[]} for k,pts in POINTS.items()} def add(k,id,pts,state,evidence):rows[k]['checks'].append({'id':id,'possible':pts,'state':'unknown' if state is None else 'met' if state else 'unmet','evidence':str(evidence)}) 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(): m=item.get('kind',{}).get('Media',{});path=m.get('media',{}).get('File',{}).get('path') if not path:continue p=workspace/path.lstrip('/') if Path(path).is_absolute() else project.parent/path sha=digest(p) if p.is_file() else None name=next((n for n,r in manifest.items() if r['sha256']==sha),None) links[id]={'name':name,'valid':bool(name) and not m.get('offline',False),'path':path,'media':m} imported={l['name'] for l in links.values() if l['valid']} trace=assets/'operator-trajectory.json' if not trace.is_file():raise GradingError('Missing private operator trajectory for app/visual observation checks') actions=action_checks(json.loads(trace.read_text()),workspace,SOURCES,assets) add('a','action-evidence',2,actions['app_use'],actions['app_steps']) for n in SOURCES: add('c',n,4/3,n in imported,'Actual resolved source hashes, initial empty project; distractor imports allowed') add('e',n,8/3,actions['source_view'][n],{'source':n,'preview_steps':actions['preview_steps'],'pixel_evidence':actions.get('source_view_evidence',{})}) native=None;native_error=None if project.is_file() and doc and shutil.which('filmcraft-cli'): r=run(['filmcraft-cli','--project',str(project),'inspect'],timeout=180) (report_dir/'native-inspection.stdout').write_bytes(r.stdout);(report_dir/'native-inspection.stderr').write_bytes(r.stderr) if r.returncode==0: try:native=json.loads(r.stdout) except ValueError:native_error='Invalid native inspector JSON' else:native_error='Native inspector failed; review project error versus missing runtime dependency' seqs=[] for id,item in items.items(): s=item.get('kind',{}).get('Sequence') if not s:continue cs=[];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',[]) cs += [c for c in t.get('items',[]) if c.get('enabled',True)] cs.sort(key=lambda c:c.get('start',0));seqs.append({'id':id,'seq':s,'clips':cs,'trans':trans}) active=str(doc.get('view',{}).get('active_sequence','')) chosen=next((s for s in seqs if s['id']==active),None) or max(seqs,key=lambda s:sum(links.get(str(c.get('item')),{}).get('name')==n for c,n in zip(s['clips'],SOURCES)),default=None) cs=chosen['clips'] if chosen else [];order=[links.get(str(c.get('item')),{}).get('name') for c in cs] standard=bool(chosen) and all(str(c.get('item')) in links for c in cs) # Unknown/nested or corrupt project structure requires native review, not a guessed failure. unavailable=None if project.is_file() else False for i,n in enumerate(SOURCES):add('f',f'position-{i}',2,(ii and abs(cs[i]['start']/TICKS-i*5)<=1/30 and not trans) if standard else unavailable,'Native contributing timeline') gap=standard and len(cs)==3 and not 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('i','native-duration-gapfree',1,gap if standard else unavailable,'No gaps/overlaps and 15-second duration') add('m','filename',1,required_project.is_file(),'Exact filename');add('m','directory',1,project.is_file(),'Original workspace path /root/Desktop/coffee-ad/output') add('m','native-load',3,bool(native) if native is not None else unavailable,native_error or 'Linux native reopen unverified' if native is None else 'Native inspect success') add('m','editable-three-source-timeline',4,editable if native is not None else unavailable,'Source-backed clips; flattened/nested projects require native evidence') for n in SOURCES:add('m','link/'+n,1,n in imported,'Hash verified working source link independent of filename') add('k','filename',2,video.is_file(),'final01.mp4');add('k','directory',3,video.is_file(),'Original workspace path /root/Desktop/coffee-ad/output') d={};s={};frames=None;decode_error=None;errors=[];matches=[False]*3;timestamp_ok=False if video.is_file(): try: d,s=probe(video) # Avoid unbounded decoding of malicious or accidentally enormous submissions. duration=float(d.get('format',{}).get('duration',0)) if duration>120:raise ValueError('Export exceeds verifier decode budget') frames=decoded_frames(video,192,108) except Exception as e:decode_error=str(e) if decode_error:raise GradingError('Unable to decode submitted export: '+decode_error) valid=frames is not None and len(frames)>0 if valid: for i,n in enumerate(SOURCES): ref=reference_frames(assets/'reference'/n,1920,1080);segment=frames[i*150:(i+1)*150] if len(segment)!=150 or len(ref)!=150:errors.append('Missing/short segment');continue delta=np.abs(segment.astype(np.float32)-ref.astype(np.float32)).mean(axis=(1,2,3)) for shift in [-1,1]: alt=np.roll(ref,shift,axis=0);dd=np.abs(segment.astype(np.float32)-alt.astype(np.float32)).mean(axis=(1,2,3));dd[:2]=delta[:2];dd[-2:]=delta[-2:];delta=np.minimum(delta,dd) matches[i]=bool(np.quantile(delta,.99)<=12 and delta.max()<=22) errors.append({'mean':float(delta.mean()),'p99':float(np.quantile(delta,.99)),'max':float(delta.max())}) r=run(['ffprobe','-v','error','-select_streams','v:0','-show_entries','frame=best_effort_timestamp_time','-of','json',str(video)],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 i,n in enumerate(SOURCES):add('h',n,5,bool(valid and matches[i]),errors) for i in [1,2]:add('i',f'export-cut-{i}',1.5,bool(valid and matches[i-1] and matches[i]),'Source mapping through decoded cut boundary') add('i','export-duration-gapfree',1,(len(frames)==450 and abs(float(d['format'].get('duration',0))-15)<=1/30) if valid and all(matches) else False,'All decoded frames correspond to source mapping; 450 frames') fps=s.get('avg_frame_rate','0/1').split('/');rate=float(fps[0])/max(1,float(fps[1])) 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'))==(1920,1080) and s.get('sample_aspect_ratio','1:1') in ['1:1','N/A'] and not any(x.get('rotation',0)%360 for x in s.get('side_data_list',[]))),('fps',abs(rate-30)<.001 and timestamp_ok)]:add('j',prop,2,valid and ok if not decode_error else None,'Actual decoded probe/timestamps') geoms=[];clipped=[] for i,n in enumerate(SOURCES): gs=[geometry(c,links[str(c['item'])]['media'],1920,1080) for c in cs if links.get(str(c.get('item')),{}).get('name')==n] 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) fit=understood and all(abs(max(g['w']/1920,g['h']/1080)-1)<.003 for g in gs) contained=understood and all(g['x']>=-2 and g['y']>=-2 and g['x']+g['w']<=1922 and g['y']+g['h']<=1082 for g in gs) geoms.append(gs);clipped.append(contained) add('l',n+'/full-image',1,bool(fit and contained),gs) add('l',n+'/proportional',1,bool(proportional),gs) add('l','placement-unclipped',1,bool(all(clipped)),geoms) for n in distractors: present=n in order # Correct full-duration target mapping plus native contributing state proves absence. absent=standard and not present and all(l['valid'] for l in links.values() if l['name'] in order) add('n',n,2,False if present else bool(absent) if standard else None if project.is_file() else False,'Hash-verified contributing timeline; source-range/export conformity is scored separately; distractor bin imports allowed') submission={str(p.relative_to(workspace)):digest(p) for p in out.iterdir() if p.is_file()} if out.is_dir() else {} # Bind operator evidence to actual linked media too, so replaced dependencies invalidate it. for l in links.values(): p=workspace/l['path'].lstrip('/') if Path(l['path']).is_absolute() else project.parent/l['path'] if p.is_file():submission[str(p.relative_to(workspace))]=digest(p) rp=report_dir/'operator-review.json';review=json.loads(rp.read_text()) if rp.is_file() else {} reviewed=bool(submission) and 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='pass' if access=='terminal' else review.get('policy','unknown') if reviewed else 'unknown' if policy not in ['pass','fail','unknown']:policy='unknown' result={'rubric_version':'01-A-content-single-v4','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','project_error':project_error,'native_error':native_error,'export':{'probe':d,'decoded_frames':len(frames) if valid else 0,'error':decode_error,'segment_matches':matches,'comparison_errors':errors},'submission_sha256':submission,'operator_review_applied':reviewed,'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') (report_dir/'reward.json').write_text(json.dumps({'reward':earned/100,'score_points':earned,'unresolved_points':unknown,'possible_upper_bound':(earned+unknown)/100},indent=2)+'\n') return result def main(): from verifier_runtime import cli_main cli_main(evaluate,Path(__file__).resolve().parent) if __name__=='__main__':main()