sidrefresh's picture
Add files using upload-large-folder tool
09c6e66 verified
Raw History Blame Contribute Delete
24.5 kB
#!/usr/bin/env python3
"""Deterministic video verifier for the t50–t53 Friction tutorial tasks.
The source composition and measured visual gates are in rubric.json. This
script only scores rendered pixels and harvested artifacts; it does not infer
success from the agent's narration or editor state.
"""
import argparse
from collections import deque
import json
import math
import os
from pathlib import Path
import shutil
import signal
import subprocess
import time
SPEC = json.loads((Path(__file__).parent / 'rubric.json').read_text())
TASK = SPEC['task_id']
W, H = SPEC['analysis_size']
N = W * H
def command(args):
return subprocess.run(args, capture_output=True, check=True).stdout
def probe(path):
data = json.loads(command(['ffprobe', '-v', 'error', '-show_streams',
'-show_format', '-of', 'json', str(path)]))
stream = next(s for s in data['streams'] if s.get('codec_type') == 'video')
a, b = stream['avg_frame_rate'].split('/')
return {'width': stream['width'], 'height': stream['height'],
'fps': float(a) / float(b),
'duration': float(data['format']['duration'])}
def decode(path):
raw = command(['ffmpeg', '-v', 'error', '-i', str(path), '-vf',
f'fps=8,scale={W}:{H}:flags=area', '-f', 'rawvideo',
'-pix_fmt', 'rgb24', '-'])
size = N * 3
if not raw or len(raw) % size:
raise RuntimeError(f'Incomplete decode: {path}')
return [raw[i:i+size] for i in range(0, len(raw), size)]
def mask(frame, color):
result = bytearray(N)
for p in range(N):
r, g, b = frame[p*3:p*3+3]
if color == 'blue':
hit = b > 95 and b > r*1.25 and b >= g*.83
elif color == 'green':
hit = g > 95 and g > r*1.35 and g > b*1.03
elif color == 'teal':
hit = g > 85 and b > 85 and g > r*1.17 and b > r*1.17
elif color == 'white':
hit = min(r, g, b) > 180
elif color == 'light':
hit = min(r, g, b) > 55
else:
raise ValueError(color)
result[p] = int(hit)
return result
def components(bitmap, min_area=3):
seen = bytearray(N)
found = []
for seed in range(N):
if not bitmap[seed] or seen[seed]:
continue
q = deque([seed]); seen[seed] = 1
count = sx = sy = 0
x0 = W; y0 = H; x1 = y1 = 0
while q:
p = q.popleft(); x = p % W; y = p // W
count += 1; sx += x; sy += y
x0 = min(x0, x); x1 = max(x1, x)
y0 = min(y0, y); y1 = max(y1, y)
for other in (p-1 if x else -1, p+1 if x<W-1 else -1,
p-W if y else -1, p+W if y<H-1 else -1):
if other >= 0 and bitmap[other] and not seen[other]:
seen[other] = 1; q.append(other)
if count >= min_area:
found.append({'area': count, 'cx': sx/count, 'cy': sy/count,
'bbox': [x0, y0, x1, y1]})
return sorted(found, key=lambda c: c['area'], reverse=True)
def dark_fraction(frame):
return sum(max(frame[p*3:p*3+3]) < 45 for p in range(N)) / N
def range_of(values):
return max(values)-min(values) if values else 0
def native_project(path):
if not path.exists() or path.stat().st_size < 1024:
return False, 'Missing or undersized project'
if not shutil.which('friction') or not shutil.which('Xvfb'):
return False, 'Friction or Xvfb unavailable; native reopen not verified'
display = f':{100 + os.getpid() % 10000}'
server = subprocess.Popen(['Xvfb', display, '-screen', '0', '1280x800x24',
'-nolisten', 'tcp'], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
time.sleep(.5)
if server.poll() is not None:
return False, 'Could not start isolated X display'
env = os.environ.copy()
env['DISPLAY'] = display
process = subprocess.Popen(['friction', str(path)], env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
start_new_session=True)
try:
time.sleep(4)
running = process.poll() is None
if running:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
running = False
try:
output = process.communicate(timeout=5)[0].decode(errors='replace')
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
output = process.communicate()[0].decode(errors='replace')
try:
os.killpg(server.pid, signal.SIGTERM)
except ProcessLookupError:
pass
server.wait(timeout=5)
opened = (running and 'Friction 1.' in output and
'Error while reading' not in output and
'Incompatible or incomplete data' not in output and
'No such file' not in output)
return opened, output[-1000:]
def contour_profile(bitmap):
columns = []
for x in range(W):
rows = [y for y in range(H) if bitmap[y*W+x]]
if rows:
columns.append((x, sum(rows)/len(rows)))
if len(columns) < 4:
return [], None
start, end = columns[0][0], columns[-1][0]
low = min(y for _, y in columns)
height = max(y for _, y in columns)-low
if not height or end == start:
return [], None
profile = []
for fraction in (0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1):
target = start + fraction*(end-start)
nearest = min(columns, key=lambda item: abs(item[0]-target))
profile.append((nearest[1]-low)/height)
return profile, len(columns)/(end-start+1)
def add(report, name, points, passed, detail, missing=False):
status = 'missing' if missing else ('pass' if passed else 'fail')
report['checks'].append({'name': name, 'points': points, 'status': status,
'earned': points if passed else 0, 'detail': detail})
def media(report, path, points_video=5, points_format=10):
if not path.exists() or not path.stat().st_size:
meta, frames = None, []
else:
try:
meta, frames = probe(path), decode(path)
except (subprocess.CalledProcessError, KeyError, StopIteration, ValueError,
RuntimeError):
meta, frames = None, []
add(report, f'{path.name}: readable export', points_video, bool(meta and frames),
meta, missing=not path.exists())
fmt = bool(meta and meta['width'] == SPEC['output_size'][0]
and meta['height'] == SPEC['output_size'][1]
and abs(meta['fps']-SPEC['output_fps']) < .05
and abs(meta['duration']-SPEC['output_duration_sec'])
<= max(.09, 2/SPEC['output_fps']))
add(report, f'{path.name}: source composition format', points_format, fmt,
{'expected': [SPEC['output_size'], SPEC['output_fps'],
SPEC['output_duration_sec']], 'actual': meta}, missing=not meta)
return frames
def grade_t50(report, frames):
if not frames:
for name, pts in [('Blue center, green satellites on black',20),
('Orbital motion',25),('Satellite count and phase',15),
('Depth and occlusion',10),('Loop seam',10)]:
add(report,name,pts,False,'No decoded frames',True)
return
rows=[]
for frame in frames:
blue=components(mask(frame,'blue'),20)
green=components(mask(frame,'green'),4)
rows.append({'blue':blue[0] if blue else None,'green':green[:6],
'dark':dark_fraction(frame)})
centers=[r['blue'] for r in rows if r['blue']]
center=centers[len(centers)//2] if centers else None
comp=bool(center and center['area']>100 and abs(center['cx']-W/2)<W*.2
and abs(center['cy']-H/2)<H*.2 and
sum(r['dark']>.72 and len(r['green'])>=2 for r in rows)>=len(rows)*.45)
add(report,'Blue center, green satellites on black',20,comp,
{'center':center,'dark_range':[min(r['dark'] for r in rows),
max(r['dark'] for r in rows)],
'frames_with_two_satellites':sum(len(r['green'])>=2 for r in rows)})
angles=[]; distances=[]; green_x=[];green_y=[]; phase=[];near=far=0
if center:
for row in rows:
satellites=row['green']
for c in satellites:
dx=c['cx']-center['cx'];dy=c['cy']-center['cy']
dist=math.hypot(dx,dy)
if dist<4:continue
angles.append(math.atan2(dy,dx));distances.append(dist)
green_x.append(c['cx']);green_y.append(c['cy'])
radius=math.sqrt(center['area']/math.pi)
near+=dist<radius*1.4;far+=dist>radius*1.7
if len(satellites)>=2:
a=math.atan2(satellites[0]['cy']-center['cy'],satellites[0]['cx']-center['cx'])
b=math.atan2(satellites[1]['cy']-center['cy'],satellites[1]['cx']-center['cx'])
phase.append(abs((a-b+math.pi)%(2*math.pi)-math.pi))
bins={int((a+math.pi)/(2*math.pi)*8)%8 for a in angles}
orbital=len(bins)>=6 and range_of(green_x)>W*.20 and range_of(green_y)>H*.20
add(report,'Orbital motion',25,orbital,
{'occupied_angle_bins':sorted(bins),'x_range':range_of(green_x),
'y_range':range_of(green_y),'satellite_samples':len(angles)})
phase_ok=bool(orbital and len(phase)>=len(rows)*.45 and
sum(.35<p<math.pi-.15 for p in phase)/len(phase)>.65)
add(report,'Satellite count and phase',15,phase_ok,
{'two_satellite_frames':len(phase),'phase_range':
[min(phase),max(phase)] if phase else None})
depth=orbital and near>=2 and far>=2
add(report,'Depth and occlusion',10,depth,
{'near_center_samples':near,'far_samples':far,
'reference_note':'satellite passes beside/behind the blue center'})
a=frames[0];b=frames[-1]
mismatch=sum(abs(a[i]-b[i])>45 for i in range(0,len(a),3))/N
add(report,'Loop seam',10,mismatch<.08,
{'first_last_changed_pixel_fraction':mismatch})
report['trace']=[{'frame':i,'blue':r['blue'],'green':r['green']}
for i,r in enumerate(rows)]
def grade_t51(report, frames):
if not frames:
for name,pts in [('Black and teal line design',20),('Final path contour',20),
('Sequential path reveal',25),('Moving tip',10),
('Final hold',5)]:
add(report,name,pts,False,'No decoded frames',True)
return
masks=[mask(f,'teal') for f in frames]
areas=[sum(m) for m in masks]
boxes=[]
for m in masks:
pts=[p for p,v in enumerate(m) if v]
boxes.append([min(p%W for p in pts),min(p//W for p in pts),
max(p%W for p in pts),max(p//W for p in pts)] if pts else None)
peak=max(areas); end=areas[-1];dark=sum(dark_fraction(f) for f in frames[-5:])/min(5,len(frames))
design=peak>70 and dark>.8 and end>peak*.6
add(report,'Black and teal line design',20,design,
{'peak_line_pixels':peak,'end_pixels':end,'end_dark_fraction':dark})
final=masks[-1]
profile, coverage=contour_profile(final)
reference=[1,.73,.46,.19,.15,.47,.81,.9,.54,.45,.7]
error=sum(abs(actual-expected) for actual,expected in zip(profile,reference))/len(reference) if profile else None
contour=bool(boxes[-1] and boxes[-1][2]-boxes[-1][0]>W*.38 and
boxes[-1][3]-boxes[-1][1]>H*.18 and coverage>.85 and
error<.18 and profile[0]>profile[3]+.4 and
profile[6]>profile[4]+.35 and
profile[6]>min(profile[8:10])+.2 and
profile[10]>min(profile[8:10])+.1)
add(report,'Final path contour',20,contour,
{'final_bbox':boxes[-1],'normalized_profile':profile,
'reference_error':error,'column_coverage':coverage})
first=min(areas[:max(1,len(areas)//5)]);last=sum(areas[-5:])/min(5,len(areas))
rises=sum(b>=a-peak*.08 for a,b in zip(areas,areas[1:]))
line_overlap=[]
for current,area in zip(masks,areas):
if area>peak*.1:
matches=sum(current[p] and any(final[q] for q in
(p, p-1 if p%W else p, p+1 if p%W<W-1 else p,
p-W if p>=W else p, p+W if p<N-W else p))
for p in range(N))
line_overlap.append(matches/area)
reveal=(contour and peak>70 and first<peak*.3 and last>peak*.7 and
rises>=.7*(len(areas)-1) and
bool(line_overlap) and min(line_overlap)>.65)
add(report,'Sequential path reveal',25,reveal,
{'first_min':first,'peak':peak,'last_mean':last,
'nondecreasing_steps':rises,'min_final_path_overlap':
min(line_overlap) if line_overlap else None})
left=[b[0] if b else None for b in boxes];right=[b[2] if b else None for b in boxes]
active=[i for i,a in enumerate(areas) if a>peak*.10]
tip=bool(active and range_of([right[i] for i in active if right[i] is not None])>W*.3
and range_of([left[i] for i in active if left[i] is not None])<W*.12)
add(report,'Moving tip',10,tip,
{'left_range':range_of([left[i] for i in active if left[i] is not None]),
'right_range':range_of([right[i] for i in active if right[i] is not None])})
hold=peak>70 and min(areas[-max(2,len(areas)//8):])>peak*.72
add(report,'Final hold',5,hold,{'last_areas':areas[-10:]})
report['trace']=[{'frame':i,'line_pixels':areas[i],'bbox':boxes[i]}
for i in range(len(frames))]
def t52_bins(frame):
bins=[0]*8
cx=W/2;cy=H/2
for p in range(N):
x=p%W-cx;y=p//W-cy;d=math.hypot(x,y)
if not 5<d<26:continue
r,g,b=frame[p*3:p*3+3]
light=max(0,min(r,g,b)-35)
angle=(math.atan2(y,x)+math.pi)/(2*math.pi)
bins[int(angle*8)%8]+=light
return bins
def grade_t52(report, frames):
if not frames:
for name,pts in [('Eight-dot loader design',20),('Rotating phase order',25),
('Repeated cycle',20),('Staggered brightness',10),
('Loop seam',5)]:
add(report,name,pts,False,'No decoded frames',True)
return
comps=[];bins=[];darks=[]
for frame in frames:
# Dim dots remain present while the highlighted dot travels.
comps.append(components(mask(frame,'light'),3))
bins.append(t52_bins(frame));darks.append(dark_fraction(frame))
ring=[]
for cs in comps:
good=[c for c in cs if 5<math.hypot(c['cx']-W/2,c['cy']-H/2)<26
and 3<=c['area']<=180]
ring.append(good)
design=max(len(x) for x in ring)>=6 and sum(d>.83 for d in darks)>=len(darks)*.7
add(report,'Eight-dot loader design',20,design,
{'max_ring_dots':max(len(x) for x in ring),
'frames_with_six_or_more':sum(len(x)>=6 for x in ring),
'dark_range':[min(darks),max(darks)]})
brightest=[max(range(8),key=lambda j:row[j]) for row in bins]
unique=len(set(brightest))
steps=[(b-a)%8 for a,b in zip(brightest,brightest[1:])]
forward=sum(1<=s<=3 for s in steps);reverse=sum(5<=s<=7 for s in steps)
phase=unique>=5 and max(forward,reverse)>=max(4,len(steps)*.18)
add(report,'Rotating phase order',25,phase,
{'visited_bins':sorted(set(brightest)),'forward_steps':forward,
'reverse_steps':reverse,'sequence':brightest})
# Compare brightness patterns at lags: a repeated phase cycle should
# produce several near matches separated by a stable nonzero interval.
period=None;score=1e9
for lag in range(max(4,len(bins)//10),max(5,len(bins)//2)):
pairs=[(bins[i],bins[i+lag]) for i in range(len(bins)-lag)]
errors=[sum(abs(a-b) for a,b in zip(x,y))/max(1,sum(x)+sum(y)) for x,y in pairs]
mean=sum(errors)/len(errors)
if mean<score:score=mean;period=lag
cycle=period is not None and score<.32 and unique>=5
add(report,'Repeated cycle',20,cycle,
{'best_lag_samples':period,'relative_brightness_error':score})
contrast=[(max(x)-min(x))/max(1,max(x)) for x in bins]
stagger=sum(v>.35 for v in contrast)>=len(contrast)*.55
add(report,'Staggered brightness',10,stagger,
{'contrast_mean':sum(contrast)/len(contrast)})
a=frames[0];b=frames[-1]
mismatch=sum(abs(a[i]-b[i])>55 for i in range(0,len(a),3))/N
add(report,'Loop seam',5,mismatch<.055,
{'first_last_changed_pixel_fraction':mismatch})
report['trace']=[{'frame':i,'ring_dots':len(ring[i]),'bins':bins[i]}
for i in range(len(frames))]
def boundary_uneven(bitmap,orientation):
positions=[]
if orientation=='top':
for x in range(2,W-2,3):
rows=[y for y in range(H) if bitmap[y*W+x]]
if rows:positions.append(max(rows))
elif orientation=='left':
for y in range(2,H-2,3):
cols=[x for x in range(W) if bitmap[y*W+x]]
if cols:positions.append(max(cols))
else:
for sector in range(24):
angle=2*math.pi*sector/24
radii=[];furthest_inside=0
for r in range(1,round(math.hypot(W/2,H/2))+1):
x=round(W/2+math.cos(angle)*r);y=round(H/2+math.sin(angle)*r)
if not (0<=x<W and 0<=y<H):break
furthest_inside=r
if bitmap[y*W+x]:radii.append(r)
# Ignore rays clipped by the rectangular canvas. A perfectly
# circular edge must not appear liquid only because it hits a side.
if radii and max(radii)<furthest_inside-1:
positions.append(max(radii))
return range_of(positions),positions
def grade_t53_method(report,frames,method):
label=method.replace('_',' ')
if not frames:
for name,points in (('Black and white scenes',3),('Wipe progression',3),
('Liquid boundary',10),('Full transition and settle',4)):
add(report,f'{label}: {name}',points,False,'No decoded frames',True)
return None
bitmaps=[mask(f,'white') for f in frames]
coverage=[sum(m)/N for m in bitmaps]
scenes=min(coverage)<.08 and max(coverage)>.90
add(report,f'{label}: Black and white scenes',3,scenes,
{'min_white':min(coverage),'max_white':max(coverage)})
peak=max(range(len(coverage)),key=lambda i:coverage[i])
rise=sum(b>=a-.08 for a,b in zip(coverage[:peak],coverage[1:peak+1]))
fall=sum(b<=a+.08 for a,b in zip(coverage[peak:],coverage[peak+1:]))
progressing=(peak>=2 and peak<len(coverage)-2 and
rise>=peak*.65 and fall>=(len(coverage)-peak-1)*.65 and
min(coverage[peak:])<.12)
add(report,f'{label}: Wipe progression',3,progressing,
{'peak_frame':peak,'rise_steps':rise,'fall_steps':fall,
'coverage':coverage})
candidates=[i for i in range(peak+1) if .22<coverage[i]<.78]
mid=min(candidates,key=lambda i:abs(coverage[i]-.5)) if candidates else None
if mid is None:
oriented=False;uneven=0;profile=[]
else:
m=bitmaps[mid]
if method=='top_to_bottom':
top=sum(m[y*W+x] for y in range(H//3) for x in range(W))/(N/3)
bottom=sum(m[y*W+x] for y in range(2*H//3,H) for x in range(W))/(N/3)
oriented=top>bottom+.25
uneven,profile=boundary_uneven(m,'top')
elif method=='left_to_right':
left=sum(m[y*W+x] for y in range(H) for x in range(W//3))/(N/3)
right=sum(m[y*W+x] for y in range(H) for x in range(2*W//3,W))/(N/3)
oriented=left>right+.25
uneven,profile=boundary_uneven(m,'left')
else:
center=sum(m[y*W+x] for y in range(H//3,2*H//3)
for x in range(W//3,2*W//3))/max(1,(H//3)*(W//3))
corners=sum(m[y*W+x] for y in list(range(H//5))+list(range(4*H//5,H))
for x in list(range(W//5))+list(range(4*W//5,W)))
corners/=max(1,(2*(H//5))*(2*(W//5)))
oriented=center>corners+.22
uneven,profile=boundary_uneven(m,'center')
liquid=oriented and uneven>=3
add(report,f'{label}: Liquid boundary',10,liquid,
{'mid_frame':mid,'oriented':oriented,'boundary_range':uneven,
'sampled_boundary':profile[:40]})
settled=coverage[0]<.12 and coverage[-1]<.12 and max(coverage)>.9
add(report,f'{label}: Full transition and settle',4,settled,
{'first':coverage[0],'last':coverage[-1],'peak':max(coverage)})
report.setdefault('trace',{})[method]=[{'frame':i,'white_fraction':v}
for i,v in enumerate(coverage)]
return bitmaps[mid] if mid is not None else None
def grade(desktop,project,terminal_log):
report={'task':TASK,'rubric_version':SPEC['rubric_version'],
'source_video_sha256':SPEC['source_video_sha256'],
'checks':[],'outputs':{},'terminal_attempts':[]}
if terminal_log.exists() and terminal_log.stat().st_size:
report['terminal_attempts']=terminal_log.read_text(errors='replace').splitlines()
clips={}
for filename in SPEC['outputs']:
path=desktop/filename
clips[filename]=media(report,path,5,5 if TASK=='t53' else 10)
report['outputs'][filename]=str(path)
saved, reopen_detail=native_project(project) if TASK=='t51' else (
project.exists() and project.stat().st_size>=1024, 'Size check only')
add(report,'Native editable Friction project',5,saved,
{'path':str(project),'bytes':project.stat().st_size if project.exists() else 0,
'reopen':reopen_detail},
missing=not project.exists())
if TASK=='t50':grade_t50(report,clips['final.mp4'])
elif TASK=='t51':grade_t51(report,clips['final.mp4'])
elif TASK=='t52':grade_t52(report,clips['final.mp4'])
elif TASK=='t53':
mids={}
for method in ('top_to_bottom','left_to_right','center'):
mids[method]=grade_t53_method(report,clips[method+'.mp4'],method)
pairs=[(a,b) for a,b in (('top_to_bottom','left_to_right'),
('top_to_bottom','center'),
('left_to_right','center'))
if mids[a] is not None and mids[b] is not None]
ious=[]
for a,b in pairs:
x,y=mids[a],mids[b]
inter=sum(bool(u and v) for u,v in zip(x,y))
union=sum(bool(u or v) for u,v in zip(x,y))
ious.append(inter/union if union else 1)
distinct=len(ious)==3 and max(ious)<.80
add(report,'Three distinct transition methods',5,distinct,
{'pairwise_midframe_iou':ious},missing=len(ious)<3)
else:raise ValueError(TASK)
possible=sum(c['points'] for c in report['checks'])
if possible!=100:
raise RuntimeError(f'Rubric totals {possible}, expected 100')
earned=sum(c['earned'] for c in report['checks'])
report['earned_points']=earned
report['raw_score']=earned/100
report['native_project_gate']=(('clear' if saved else 'capped-at-0.5')
if TASK=='t51' else 'not-applicable')
report['ungated_score']=min(earned/100,.5) if TASK=='t51' and not saved else earned/100
report['code_access_gate']='terminal-attempt' if report['terminal_attempts'] else 'clear'
report['score']=0 if report['terminal_attempts'] else report['ungated_score']
return report
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--desktop',default='/root/Desktop')
parser.add_argument('--project',default='/root/edit/project.friction')
parser.add_argument('--terminal-log',default='/logs/artifacts/terminal-attempts.log')
parser.add_argument('--reward',default='/logs/verifier/reward.txt')
parser.add_argument('--report',default='/logs/verifier/score.json')
args=parser.parse_args()
result=grade(Path(args.desktop),Path(args.project),Path(args.terminal_log))
report=Path(args.report);reward=Path(args.reward)
report.parent.mkdir(parents=True,exist_ok=True)
reward.parent.mkdir(parents=True,exist_ok=True)
report.write_text(json.dumps(result,indent=2)+'\n')
reward.write_text(f"{result['score']:.6f}\n")
print(json.dumps({'score':result['score'],'checks':result['checks']},indent=2))
if __name__=='__main__':main()