File size: 17,427 Bytes
1daa78e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""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='<f4') if r.returncode==0 else np.array([])

def evaluate(workspace,report_dir,assets,access):
 report_dir.mkdir(parents=True,exist_ok=True);out=workspace/'root/Desktop/final01/output';project=out/'proj-task-01.fcproj';manifest=json.loads((assets/'source-manifest.json').read_text());initial=json.loads((assets/'initial-project.fcproj').read_text())
 required_project=project;project=select_project(project)
 rows={k:{'requirement':LABELS[k],'possible':v,'checks':[]} for k,v 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={};error=None
 if project.is_file():
  try:
   doc=json.loads(project.read_text())
   if doc.get('format')!='filmcraft.project':raise ValueError('Unrecognized native format')
  except Exception as e:error=str(e);doc={}
 items=doc.get('project',{}).get('items',{});links={};submission={str(p.relative_to(workspace)):digest(p) for p in out.iterdir() if p.is_file()} if out.is_dir() else {}
 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;n=next((n for n,r in manifest.items() if r['sha256']==sha),None)
  links[id]={'name':n,'valid':bool(n) and not m.get('offline'), 'media':m,'path':path}
  if p.is_file():submission[str(p.relative_to(workspace))]=sha
 imported={l['name'] for l in links.values() if l['valid']}
 trace_path=assets/'operator-trajectory.json'
 if not trace_path.is_file():raise GradingError('Missing operator-supplied trajectory for app and batch checks')
 actions=action_checks(json.loads(trace_path.read_text()),workspace,SOURCES,assets)
 add('a','recorded-use',2,actions['app_use'],actions['app_steps'])
 for n in SOURCES:add('c',n,4/3,n in imported,'Actual source hash compared with initial distractor-only bin')
 native=None
 if project.is_file() and doc and shutil.which('filmcraft-cli'):
  r=run(['filmcraft-cli','--project',str(project),'inspect'],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 Exception:pass
 seqs=[]
 for id,item in items.items():
  s=item.get('kind',{}).get('Sequence')
  if not s:continue
  video=[];audio=[];trans=[]
  for kind,bag in [('video_tracks',video),('audio_tracks',audio)]:
   tracks=s.get(kind,[]);solo=any(t.get('solo') for t in tracks)
   for t in tracks:
    if not t.get('enabled',True) or t.get('muted',False) or solo and not t.get('solo'):continue
    bag.extend(c for c in t.get('items',[]) if c.get('enabled',True));
    if kind=='video_tracks':trans.extend(t.get('transitions',[]))
  video.sort(key=lambda c:c.get('start',0));seqs.append({'id':id,'seq':s,'video':video,'audio':audio,'transitions':trans})
 active=str(doc.get('view',{}).get('active_sequence',''));selected=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') in SOURCES for c in s['video']),default=None)
 clips=selected['video'] if selected else [];order=[links.get(str(c.get('item')),{}).get('name') for c in clips];standard=bool(selected) and all(str(c.get('item')) in links for c in clips);absent=None if project.is_file() else False
 add('d','source-backed-new-sequence',4,bool(native) and bool(clips) if native is not None else absent,'No sequences in initial fixture; successful native reopen still required')
 for i,n in enumerate(SOURCES):add('e',f'position-{i}',2,(i<len(order) and order[i]==n) if standard else absent,order)
 add('e','only-targets',2,order==SOURCES if standard else absent,'Distractors may stay in bins')
 for n in SOURCES:
  cs=[c for c in clips if links.get(str(c.get('item')),{}).get('name')==n]
  for prop in ['tail-start','five-second-range','normal-speed']:
   values=[]
   for c in cs:
    m=links[str(c['item'])]['media'];duration=video_end(assets/'reference'/n)
    values.append(abs(c.get('source_in',0)/TICKS-(duration-5))<=1/30 if prop=='tail-start' else abs(c.get('duration',0)/TICKS-5)<=1/30 and abs((c.get('source_in',0)+c.get('duration',0))/TICKS-duration)<=1/30 if prop=='five-second-range' else normal(c,m))
   ok=(None if None in values else all(values)) if values else False if standard or not project.is_file() else None
   add('f',n+'/'+prop,1,ok,'Native contribution/edge handles: '+str(values)+'; alternate transition-range representations need review')
 for i in [1,2]:
  add('g',f'join-{i}/native-editable',3,bool(native_dissolve(selected,clips,i)),'Enabled source-linked native dissolve at actual join: '+json.dumps(selected['transitions'] if selected else []))
 picture_end=max((c.get('start',0)+c.get('duration',0))/TICKS for c in clips) if clips else None
 rate=(selected['seq']['settings'].get('frame_rate') or {'num':30,'den':1}) if selected else {'num':30,'den':1}
 frame_tolerance=max(1/30,rate['den']/rate['num'])+1e-6
 music_clips=[c for c in selected['audio'] if links.get(str(c.get('item')),{}).get('name')==MUSIC and normal(c,links[str(c['item'])]['media']) is not False] if selected else []
 add('n','linked-sound-in-timeline',2,bool(music_clips) if selected else absent,'Supplied music SHA256 must resolve from an active audio contribution')
 add('n','native-music-picture-end',2,all(abs((c['start']+c['duration'])/TICKS-picture_end)<=frame_tolerance for c in music_clips) if music_clips and picture_end else absent,'Actual music end compared with video end; '+str(picture_end))
 intervals=sorted((c.get('start',0)/TICKS,(c.get('start',0)+c.get('duration',0))/TICKS) for c in clips)
 continuity=None
 if standard and intervals:
  covered=0;continuity=True
  for start,end in intervals:
   if start>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)<len(frames):match=float(np.abs(np.frombuffer(rr.stdout,dtype=np.uint8).reshape(108,192,3).astype(float)-frames[round(t*30)].astype(float)).mean())<15
   add('h',filename+'/'+n+'/interior',.5,bool(match),'Interior time-mapped sample; full source range requires separate evidence');visual.append(match)
   add('h',filename+'/'+n+'/full-tail-range',7/6,assembly['tails'][i],'All decoded tail frames including paired source contributions: '+json.dumps(assembly))
   for prop in ['full-image-fit','proportional-scale']:
    g=geometry(c,links[str(c['item'])]['media'],selected['seq']['settings']['width'],selected['seq']['settings']['height']) if c and standard else None
    sw,sh=(selected['seq']['settings']['width'],selected['seq']['settings']['height']) if selected else (W,H)
    fit=bool(g and 'sx' in g and g['x']>=-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()