"""B-name-batch v4: last-five-second ranges, cross dissolves and supplied music. Unknown native structures/action/render evidence remain explicit. No fixed runtime. """ import argparse,json,math,shutil,subprocess from pathlib import Path from verifier_runtime import select_project import numpy as np from deterministic_checks import action_checks,native_dissolve,rendered_assembly,GradingError,require_complete from media_helpers import digest,probe,run,normal,geometry,decoded_frames,video_end,TICKS SOURCES=['coffee-beans-closeup-4k.mp4','pouring-coffee-carafe-4k.mp4','hands-cup-pickup-4k.mp4'] MUSIC='817913__johnmode__1980s-song-fragment-01.mp3' EXPORTS=[('final01-1080p.mp4',1920,1080),('final01-720p.mp4',1280,720)] POINTS=dict(zip(list('acdefghijklmno'),[2,4,4,8,9,12,10,6,8,4,6,12,10,5])) LABELS=dict(zip(POINTS,['Filmcraft use','Three targets available in Filmcraft','Editable assembled sequence','Correct target order only','Last five seconds normal forward speed','Editable and rendered cross dissolves','Both exports contain matching tail assembly','Picture continuity and no black tail','Two H.264 MP4s at 30 fps','Exact names and original output folder','Full-image fit without stretching','Editable native footage, dissolves, music and links','Supplied music audible and trimmed to picture end','Both exports queued together and batch executed'])) assert sum(POINTS.values())==100 def pcm(path): r=run(['ffmpeg','-v','error','-i',str(path),'-vn','-ac','1','-ar','8000','-f','f32le','pipe:1'],180) return np.frombuffer(r.stdout,dtype='covered+1/30:continuity=False covered=max(covered,end) add('i','native-continuity',1,continuity if clips else absent,'Union of contributing video intervals; alternate nested/transition arrangements require review') add('i','native-sequence-export-end',1,bool(selected) and all(t.get('start',0)+t.get('duration',0)<=round(picture_end*TICKS) for t in selected['transitions']) and (selected['seq'].get('mark_out') is None or abs(selected['seq']['mark_out']/TICKS-picture_end)<=1/30),'Sequence picture end and active export range') refs=[decoded_frames(assets/'reference'/n,192,108,'fps=30,scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2') for n in SOURCES] if standard and order==SOURCES else [] exports=[];source_pcm=pcm(assets/'reference'/MUSIC) for filename,W,H in EXPORTS: p=out/filename;present=p.is_file();d={};s={};frames=None;decode_error=None if present: try: d,s=probe(p) if float(d['format'].get('duration',0))>120:raise ValueError('Decode budget exceeded') frames=decoded_frames(p,192,108) except Exception as e:decode_error=str(e) if decode_error:raise GradingError('Export decode/probe failed: '+decode_error) valid=frames is not None and len(frames)>0;duration=float(s.get('duration',d.get('format',{}).get('duration',0))) timestamp=False if valid: r=run(['ffprobe','-v','error','-select_streams','v:0','-show_entries','frame=best_effort_timestamp_time','-of','json',str(p)],180) if not r.returncode: ts=[float(x['best_effort_timestamp_time']) for x in json.loads(r.stdout)['frames'] if 'best_effort_timestamp_time' in x];timestamp=len(ts)>1 and max(abs(b-a-1/30) for a,b in zip(ts,ts[1:]))<.0001 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'))==(W,H) 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)]:add('j',filename+'/'+prop,1,ok if valid else None if present else False,'Actual decoded probe/timestamps') add('k',filename+'/name',1,present,'Exact filename');add('k',filename+'/directory',1,present,'Original final01/output path') assembly=rendered_assembly(frames,clips,selected,refs) if valid and refs else {'full':False,'tails':[False]*3,'joins':[False]*2,'end':False} visual=[] for i,n in enumerate(SOURCES): c=next((c for c in clips if links.get(str(c.get('item')),{}).get('name')==n),None);match=None if valid and c and standard: # Compare an unblended midpoint outside overlap. Dissolve frames are separately reviewed. t=c['start']/TICKS+c['duration']/TICKS/2;overlap=any(x is not c and x['start']/TICKS<=t<(x['start']+x['duration'])/TICKS for x in clips) if not overlap: source_time=c.get('source_in',0)/TICKS+(t-c['start']/TICKS);ref_path=assets/'reference'/n rr=run(['ffmpeg','-v','error','-ss',str(source_time),'-i',str(ref_path),'-frames:v','1','-vf',f'scale={W}:{H}:force_original_aspect_ratio=decrease,pad={W}:{H}:(ow-iw)/2:(oh-ih)/2,scale=192:108','-pix_fmt','rgb24','-f','rawvideo','pipe:1'],120) if len(rr.stdout)==192*108*3 and round(t*30)=-2 and g['y']>=-2 and g['x']+g['w']<=sw+2 and g['y']+g['h']<=sh+2 and abs(max(g['w']/sw,g['h']/sh)-1)<.003) proportional=bool(g and 'sx' in g and abs(g['sx']-g['sy'])<1e-5) add('l',filename+'/'+n+'/'+prop,.5,assembly['tails'][i] and (fit if prop=='full-image-fit' else proportional),'Native sequence transforms with proportional export scaling and all-frame source comparison: '+str(g)) for i in [1,2]:add('g',f'join-{i}/'+filename,1.5,assembly['joins'][i-1],'All transition frames compared with outgoing/incoming source mixtures; monotonic blend and no fade-to-black: '+json.dumps(assembly)) add('i',filename+'/continuity',1,assembly['full'],'Every decoded frame matches source or progressive blend; source-inherent black allowed') add('i',filename+'/picture-end-no-black-tail',1,assembly['end'],'Decoded frame count and final three frames matched to actual source picture end') audio=pcm(p) if valid else np.array([]);audible=len(audio)>0 and float(np.sqrt((audio.astype(float)**2).mean()))>1e-5 correlation=None if audible and len(source_pcm)>len(audio): # Best gain-invariant waveform correlation at coarse source offsets; not a forced start time. stride=8;a=audio[::stride].astype(float);a-=a.mean();best=0 for offset in range(0,len(source_pcm)-len(audio),800): b=source_pcm[offset:offset+len(audio):stride].astype(float);b-=b.mean();den=np.linalg.norm(a)*np.linalg.norm(b) if den:best=max(best,float(np.dot(a,b)/den)) correlation=best add('n',filename+'/audible-matching-music',2,bool(audible and correlation is not None and correlation>.75 and music_clips),'Decoded RMS and native supplied-source waveform correlation '+str(correlation)+'; gain/mixing/codec delay require calibrated review') audio_streams=[x for x in d.get('streams',[]) if x.get('codec_type')=='audio'];audio_end=max((float(x.get('start_time',0))+float(x.get('duration',0)) for x in audio_streams),default=None) add('n',filename+'/audio-end',1,bool(audio_end is not None and picture_end is not None and abs(audio_end-picture_end)<=frame_tolerance+1024/48000),'Audio stream end with one video-frame tolerance for AAC padding '+str(audio_end)+'; picture end '+str(picture_end)+'; inspect final audible samples and calibrate encoder padding') exports.append({'name':filename,'probe':d,'decode_error':decode_error,'frames':len(frames) if valid else 0,'duration':duration,'interior_matches':visual,'music_correlation':correlation}) add('m','name',1,required_project.is_file(),'proj-task-01.fcproj');add('m','directory',1,project.is_file(),'final01/output');add('m','native-load',2,bool(native) if native is not None else absent,'Pinned native reopen') add('m','editable-original-footage',2,True if native and standard and order==SOURCES else absent,'Native loaded editable original-source timeline required; flattened export insufficient') add('m','editable-dissolves',1,bool(native) and all(native_dissolve(selected,clips,i) for i in [1,2]),'Native reopen and enabled source-linked editable cross dissolves') add('m','editable-music-trim',1,True if native and music_clips else absent,'Native editable source-backed audio clip and trim') for n in SOURCES+[MUSIC]:add('m','link/'+n,1,n in imported,'Actual resolving original asset hash') add('o','queued-two-exports-before-start',2,actions['batch'],actions['queue_evidence']) add('o','batch-processes-both-jobs',3,actions['batch'] and all((out/n).is_file() for n,_,_ in EXPORTS),actions['queue_evidence']) review_path=report_dir/'operator-review.json';review=json.loads(review_path.read_text()) if review_path.is_file() else {};reviewed=bool(submission) and review.get('submission_sha256')==submission and review.get('reviewer') and 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-B-name-batch-v4-deterministic-20261016','rubric':rows,'resolved_score':round(earned,6),'unresolved_points':round(unknown,6),'score_range':[round(earned,6),round(earned+unknown,6)],'policy':policy,'exports':exports,'native_picture_end':picture_end,'project_error':error,'submission_sha256':submission,'operator_review_applied':bool(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/'reward.json').write_text(json.dumps({'reward':earned/100,'score_points':earned,'unresolved_points':unknown,'possible_upper_bound':(earned+unknown)/100},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,row in rows.items() for c in row['checks'] if c['state']=='unknown'}},indent=2)+'\n');return result def main(): from verifier_runtime import cli_main cli_main(evaluate,Path(__file__).resolve().parent) if __name__=='__main__':main()