"""Content formats v4: artifact grading with unresolved genuine action/native evidence.""" import argparse,json,math,tempfile,shutil,subprocess from pathlib import Path from verifier_runtime import select_project import numpy as np from PIL import Image from deterministic_checks import GradingError,require_complete import footage_backend as backend from media_helpers import digest,decoded_frames,geometry,val,TICKS EXPORTS=[('final01horizontal-sample.mp4',1920,1080,True),('final01-vertical-sample.mp4',1080,1920,True),('final01horizontal.mp4',1920,1080,False),('final01-vertical.mp4',1080,1920,False)] POINTS=dict(zip(['a','c','d']+list('efghijklmnopqr'),[2,4,4,6,6,9,12,6,8,4,8,12,3,4,4,3,5])) LABELS=dict(zip(POINTS,['Filmcraft use','Correct imports','Editable footage sequences','Visual identification','Native target order and no extra footage','First five seconds normal speed','Four exports source ranges','Cuts and duration','H.264 MP4 dimensions and 30 fps','Four names and output directory','Horizontal fit and centered portrait crop','Editable footage/text and source links','Clean exports without watermark','Exact white DejaVu Sans wording','50 percent effective text opacity','Fully visible legible wording','Continuous watermark visibility'])) assert sum(POINTS.values())==100 TEXT='FOR SAMPLE VIEW ONLY' def evaluate(workspace,report_dir,assets,access): report_dir.mkdir(parents=True,exist_ok=True);out=workspace/'root/Desktop/output';results=[] for filename,W,H,sample in EXPORTS: with tempfile.TemporaryDirectory() as temp: r=backend.evaluate(workspace,Path(temp),assets,access,filename,W,H,sample) dest=report_dir/filename;dest.mkdir(exist_ok=True) for p in Path(temp).glob('native-inspection.*'):shutil.copy2(p,dest/p.name) results.append(r) 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':state,'evidence':str(evidence)}) def copyrow(k,source,index=0,factor=1,prefix=''): for c in results[index]['rubric'][source]['checks']:add(k,prefix+c['id'],c['possible']*factor,c['state'],c['evidence']) for k in ['a','c','d']:copyrow(k,k) copyrow('e','e',factor=.75) for index,c in enumerate(results[0]['rubric']['f']['checks']): states=[r['rubric']['f']['checks'][index]['state'] for r in results] pts=1 if c['id'].startswith('position') else 3 add('f',c['id'],pts,'unmet' if 'unmet' in states else 'unknown' if 'unknown' in states else 'met',states) for index,c in enumerate(results[0]['rubric']['g']['checks']): states=[r['rubric']['g']['checks'][index]['state'] for r in results] add('g',c['id'],c['possible'],'unmet' if 'unmet' in states else 'unknown' if 'unknown' in states else 'met',states) for c in results[0]['rubric']['i']['checks']: if c['id'].startswith('native'):add('i',c['id'],1,c['state'],c['evidence']) project=out/'proj-task-01.fcproj';doc={} required_project=project;project=select_project(project) try:doc=json.loads(project.read_text()) except Exception:pass items=doc.get('project',{}).get('items',{});seqs=[it['kind']['Sequence'] for it in items.values() if 'Sequence' in it.get('kind',{})] graphs=[] for s in seqs: tracks=s.get('video_tracks',[]);solo=any(t.get('solo') for t in tracks) for track in tracks: if not track.get('enabled',True) or solo and not track.get('solo'):continue for c in track.get('items',[]): if not c.get('enabled',True):continue for e in c.get('effects',[]): if e.get('effect')=='graphic_text' and e.get('enabled',True):graphs.append({'clip':c,'effect':e,'width':s.get('settings',{}).get('width'),'height':s.get('settings',{}).get('height')}) media={} manifest=json.loads((assets/'source-manifest.json').read_text()) for id,item in items.items(): m=item.get('kind',{}).get('Media',{});path=m.get('media',{}).get('File',{}).get('path') if path: p=workspace/path.lstrip('/') if Path(path).is_absolute() else project.parent/path if p.is_file() and digest(p) in [v['sha256'] for v in manifest.values()]:media[id]=m def state(ok,present):return 'met' if ok else 'unmet' for ix,((filename,W,H,sample),r) in enumerate(zip(EXPORTS,results)): prefix=filename+'/';present=(out/filename).is_file();export=r['export'];matched=export['segment_matches'] copyrow('h','h',ix,.2,prefix) for c in r['rubric']['i']['checks']: if c['id'].startswith('export'):add('i',prefix+c['id'],.25,c['state'],c['evidence']) copyrow('j','j',ix,.25,prefix) add('k',prefix+'name',.5,'met' if present else 'unmet','Exact filename');add('k',prefix+'directory',.5,'met' if present else 'unmet','Original Desktop/output path') selected=[s for s in seqs if (s.get('settings',{}).get('width'),s.get('settings',{}).get('height'))==(W,H)] for si,name in enumerate(backend.SOURCES): geoms=[] for s in selected: for track in s.get('video_tracks',[]): if not track.get('enabled',True):continue for c in track.get('items',[]): if not c.get('enabled',True):continue id=str(c.get('item'));m=media.get(id) if not m:continue path=m.get('media',{}).get('File',{}).get('path','');p=workspace/path.lstrip('/') if Path(path).is_absolute() else project.parent/path if digest(p)==manifest[name]['sha256']:geoms.append(geometry(c,m,W,H)) known=bool(geoms) and all(g and 'sx' in g for g in geoms) proportional=known and all(abs(g['sx']-g['sy'])<1e-5 for g in geoms) centered=known and all(abs(g['x']-(W-g['w'])/2)<=2 and abs(g['y']-(H-g['h'])/2)<=2 for g in geoms) framed=known and all(abs((max if W>H else min)(g['w']/W,g['h']/H)-1)<.003 for g in geoms) if W>H: contained=known and all(g['x']>=-2 and g['y']>=-2 and g['x']+g['w']<=W+2 and g['y']+g['h']<=H+2 for g in geoms) add('l',prefix+name+'/full-image',1/3,state(matched[si] and framed and contained,present),geoms) add('l',prefix+name+'/proportional',1/3,state(matched[si] and proportional and contained,present),geoms) else: add('l',prefix+name+'/fill',1/6,state(matched[si] and framed,present),geoms) add('l',prefix+name+'/center',1/6,state(matched[si] and centered,present),geoms) add('l',prefix+name+'/proportional',1/3,state(matched[si] and proportional,present),geoms) if not sample:add('n',filename,1.5,state(all(matched) and export['decoded_frames']==450,present),'All-frame clean/source comparison') # Native project components distinct from rendered watermark quality. for c in results[0]['rubric']['m']['checks']: pts=2 if c['id']=='native-load' else 3 if c['id']=='editable-three-source-timeline' else c['possible'] states=[next(x for x in r['rubric']['m']['checks'] if x['id']==c['id'])['state'] for r in results] add('m',c['id'],pts,'unmet' if 'unmet' in states else 'unknown' if 'unknown' in states else 'met',states) add('m','editable-watermark-text',2,'met' if project.is_file() and len(graphs)>=2 and all(any(x['state']=='met' for x in r['rubric']['m']['checks'] if x['id']=='native-load') for r in results) else 'unmet','Successful native reopen and editable graphic_text effects in both orientations') watermark_evidence={} for ix in [0,1]: filename,W,H,sample=EXPORTS[ix];p=out/filename;clean=out/EXPORTS[ix+2][0];present=p.is_file();prefix=filename+'/' native_graphs=[g for g in graphs if (g['width'],g['height'])==(W,H)] metadata=[{'text':val(g['effect'],'text'),'font':val(g['effect'],'font'),'color':val(g['effect'],'fill_color'),'opacity':val(g['effect'],'opacity'),'start':g['clip'].get('start',0)/TICKS,'duration':g['clip'].get('duration',0)/TICKS} for g in native_graphs] exact_native=any(m['text']==TEXT for m in metadata);font_native=any(m['font']=='DejaVu Sans' for m in metadata) evidence={'native_text_effects':metadata,'ocr':[],'glyph_masks':[]};ocr_ok=False;continuous=False;white_ok=False;opacity_ok=False if present and clean.is_file() and results[ix]['export']['decoded_frames']==450 and results[ix+2]['export']['decoded_frames']==450: sample_frames=decoded_frames(p,384 if W>H else 216,216 if W>H else 384);clean_frames=decoded_frames(clean,384 if W>H else 216,216 if W>H else 384) if sample_frames.shape==clean_frames.shape: diff=sample_frames.astype(float)-clean_frames.astype(float);active=(diff.mean(axis=3)>5)&(diff.max(axis=3)-diff.min(axis=3)<100) counts=active.sum(axis=(1,2));continuous=bool((counts>30).all());evidence['all_frame_changed_pixels']={'min':int(counts.min()),'max':int(counts.max()),'frames':len(counts)} # Positive white-overlay residual across channels; opacity estimate includes antialiasing. linear=lambda v:np.where(v<=.04045,v/12.92,((v+.055)/1.055)**2.4) clean_linear=linear(clean_frames.astype(float)/255);sample_linear=linear(sample_frames.astype(float)/255) denom=1-clean_linear;alpha=(sample_linear-clean_linear)/np.maximum(denom,.001);mask=active & (denom.min(axis=3)>.15) estimates=alpha.mean(axis=3)[mask];channel_residual=alpha.std(axis=3)[mask] if len(estimates): estimate=float(np.quantile(estimates,.90));residual=float(np.median(channel_residual));evidence['white_alpha_estimate']={'p95':estimate,'median_channel_residual':residual} white_ok=residual<.10;opacity_ok=.40<=estimate<=.60 and white_ok if shutil.which('tesseract'): reference_mask=None for frame in [0,149,150,299,300,449]: img=report_dir/(filename+f'-frame-{frame}.png') # Decode the original frame at full resolution; subtraction removes the busy moving background before OCR. aa=decoded_frames(p,W,H,fr'select=eq(n\,{frame})',1)[0].astype(float);bb=decoded_frames(clean,W,H,fr'select=eq(n\,{frame})',1)[0].astype(float) residual=np.clip((aa-bb).mean(axis=2)*5,0,255);Image.fromarray(np.uint8(255-residual)).save(img) la=linear(aa/255);lb=linear(bb/255);glyph_alpha=np.clip(((la-lb)/np.maximum(1-lb,.04)).mean(axis=2),0,1);glyph_mask=glyph_alpha>.15 if reference_mask is None:reference_mask=glyph_mask mask_iou=float((glyph_mask&reference_mask).sum()/max(1,(glyph_mask|reference_mask).sum()));retained=float((glyph_mask&reference_mask).sum()/max(1,reference_mask.sum()));evidence['glyph_masks'].append({'frame':frame,'reference_iou':mask_iou,'reference_retained':retained}) rr=subprocess.run(['tesseract',str(img),'stdout','--psm','11'],capture_output=True,timeout=30);recognized=' '.join(rr.stdout.decode(errors='replace').split()) if TEXT not in recognized: # Fixed threshold removes codec noise; exact text is still required with native corroboration. thresholded=report_dir/(filename+f'-frame-{frame}-threshold.png');Image.open(img).point(lambda v:0 if v<220 else 255).save(thresholded) rr=subprocess.run(['tesseract',str(thresholded),'stdout','--psm','11'],capture_output=True,timeout=30);alternative=' '.join(rr.stdout.decode(errors='replace').split()) if TEXT in alternative:recognized=alternative evidence['ocr'].append({'frame':frame,'text':recognized}) ocr_ok=bool(evidence['ocr']) and TEXT in evidence['ocr'][0]['text'] and all(x['reference_retained']>=.95 and x['reference_iou']>=.70 for x in evidence['glyph_masks']) # Exact first-frame OCR plus stable independently decoded glyph masks avoids false deductions from background-dependent OCR errors. watermark_evidence[filename]=evidence add('o',prefix+'wording',1,state(exact_native and ocr_ok,present),evidence) add('o',prefix+'font',.5,'met' if font_native and ocr_ok else 'unmet','Native DejaVu Sans setting and exact rendered wording; '+str(metadata)) add('o',prefix+'white',.5,state(white_ok and exact_native,present),evidence) add('p',filename,2,state(opacity_ok and exact_native,present),evidence) add('q',prefix+'fully-visible',.75,state(ocr_ok,present),evidence) add('q',prefix+'legible',.75,state(ocr_ok,present),evidence) intervals=[(m['start'],m['start']+m['duration']) for m in metadata if m['text']==TEXT];coverage=0 for a,b in sorted(intervals): if a<=coverage+1/30:coverage=max(coverage,b) add('r',filename,2.5,state(continuous and ocr_ok and coverage>=15-1/30,present),evidence) submission=results[0]['submission_sha256'];rp=report_dir/'operator-review.json';review=json.loads(rp.read_text()) if rp.exists() 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-formats-v4','rubric':rows,'resolved_score':round(earned,6),'unresolved_points':round(unknown,6),'score_range':[round(earned,6),round(earned+unknown,6)],'policy':policy,'export_checks':[r['export'] for r in results],'watermark_evidence':watermark_evidence,'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/'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()