File size: 13,361 Bytes
d7786d9 | 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | #!/usr/bin/env python3
"""Deterministic final-video grader for the Friction tutorial tasks t44–t48.
It reads exported pixels and timing, not editor state. Every check includes its
measurements in score.json, so a partial export remains reviewable at timeout.
"""
import json
from pathlib import Path
import subprocess
ROOT = Path('/tests')
DESKTOP = Path('/root/Desktop')
PROJECT = Path('/root/edit/project.friction')
OUT = Path('/logs/verifier')
def command(args):
return subprocess.run(args, check=True, capture_output=True).stdout
def video(path, w, h):
if not path.exists() or not path.stat().st_size:
return None, []
try:
data = json.loads(command(['ffprobe', '-v', 'error', '-show_streams',
'-show_format', '-of', 'json', str(path)]))
stream = next(x for x in data['streams'] if x.get('codec_type') == 'video')
a, b = stream['avg_frame_rate'].split('/')
meta = {'width': stream['width'], 'height': stream['height'],
'fps': float(a) / float(b),
'duration': float(data['format']['duration'])}
raw = command(['ffmpeg', '-v', 'error', '-i', str(path), '-vf',
f'fps=8,scale={w}:{h}', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'])
size = w*h*3
frames = [raw[i:i+size] for i in range(0, len(raw), size)]
if not frames or len(raw) % size:
return None, []
return meta, frames
except (subprocess.CalledProcessError, KeyError, StopIteration, ValueError):
return None, []
def bounds(points):
if not points:
return None
xs, ys = zip(*points)
return [min(xs), min(ys), max(xs), max(ys)]
def frame_stats(frame, w, h):
masks = {name: [] for name in ('white', 'offwhite', 'dark', 'navy', 'blue',
'yellow', 'orange', 'red', 'pink')}
for i in range(w*h):
r, g, b = frame[3*i:3*i+3]
p = (i % w, i // w)
if min(r,g,b) > 210: masks['white'].append(p)
if min(r,g,b) > 170: masks['offwhite'].append(p)
if max(r,g,b) < 45: masks['dark'].append(p)
if r < 70 and g < 95 and b < 130 and b >= r*1.05:
masks['navy'].append(p)
if b > 85 and b > r*1.20 and b > g*0.85: masks['blue'].append(p)
if r > 165 and g > 130 and b < 135 and r > b*1.5: masks['yellow'].append(p)
if r > 150 and 45 < g < 175 and b < 100: masks['orange'].append(p)
if r > 145 and g < 115 and b < 140 and r > g*1.5: masks['red'].append(p)
if r > 145 and b > 105 and r > g*1.15: masks['pink'].append(p)
result = {k: {'count': len(v), 'fraction': len(v)/(w*h), 'bbox': bounds(v),
'cx': sum(x for x,y in v)/len(v) if v else None,
'cy': sum(y for x,y in v)/len(v) if v else None}
for k,v in masks.items()}
blue_rows = {}
for x,y in masks['blue']:
blue_rows.setdefault(y, []).append(x)
left_edges = [min(xs) for xs in blue_rows.values() if len(xs) >= 3]
result['blue']['left_edge_variation'] = motion(left_edges)
return result
def span(box, axis):
return box[axis+2]-box[axis]+1 if box else 0
def add(checks, name, points, passed, evidence):
checks.append({'name': name, 'points': points,
'earned': points if passed else 0,
'status': 'pass' if passed else 'fail', 'evidence': evidence})
def common(checks, path, meta, frames, spec, weight_video=10, weight_format=15,
actual_path=None):
exists = bool(meta and frames)
# A playable export elsewhere still supplies evidence for visual grading,
# while the requested delivery location earns its own points.
delivered = exists and (actual_path is None or actual_path == path)
add(checks, f'{path.name} delivered', weight_video, delivered,
{'media': meta, 'actual_path': str(actual_path or path) if exists else None})
fmt = bool(exists and meta['width'] == spec['output_size'][0]
and meta['height'] == spec['output_size'][1]
and abs(meta['fps']-spec['output_fps']) < 0.05
and abs(meta['duration']-spec['output_duration_sec']) <= 0.09)
add(checks, f'{path.name} source composition format', weight_format, fmt,
{'expected': [spec['output_size'], spec['output_fps'],
spec['output_duration_sec']], 'actual': meta})
def motion(series):
values = [x for x in series if x is not None]
return max(values)-min(values) if values else 0
def grade_one(kind, stats, checks):
n = len(stats)
if not n:
for label, points in [('Tutorial palette', 20), ('Subject design', 20),
('Tutorial motion', 25), ('Fine details', 15),
('Final hold', 5)]:
add(checks, label, points, False, 'No decodable frames')
return
start = stats[:max(1,n//5)]; middle = stats[n//3:2*n//3]
end = stats[-max(1,n//5):]
peak = lambda key: max(s[key]['count'] for s in stats)
endavg = lambda key: sum(s[key]['fraction'] for s in end)/len(end)
if kind == 't44':
# Tutorial construction frames show yellow fill over charcoal base on
# pale blue. The opening polished blue sample is a separate example.
palette = peak('yellow') > 20 and endavg('offwhite') > .55
# Shape and motion are independent of the palette checkpoint. A
# different-colored ring still has measurable circular motion.
subject = 'yellow' if peak('yellow') > 20 else 'blue'
boxes = [s[subject]['bbox'] for s in stats if s[subject]['count'] > 20]
design = any(span(b,0) > 12 and span(b,1) > 8 and
abs(span(b,0)-span(b,1)) <= .30*max(span(b,0),span(b,1))
for b in boxes)
sizes = [s[subject]['count'] for s in stats]
anim = motion(sizes) > 25 and sum(b>=a for a,b in zip(sizes,sizes[1:])) > .6*(n-1)
details = peak('dark') > 100 and any(s['dark']['count'] > 5 for s in end)
# A full colored ring is the tutorial's completed pose. A blue arc
# that stops at a partial percentage does not pass this check.
hold = end[-1]['yellow']['count'] > 20 if subject == 'yellow' else end[-1]['blue']['count'] > 600
elif kind == 't45':
palette = endavg('white') > .7 and peak('orange') > 20
boxes = [s['orange']['bbox'] for s in stats if s['orange']['count'] > 20]
design = any(6 <= span(b,0) <= 35 and 6 <= span(b,1) <= 35 for b in boxes)
ys = [s['orange']['cy'] for s in stats]
changes = [b-a for a,b in zip(ys,ys[1:]) if a is not None and b is not None]
reversals = sum(a*b < 0 for a,b in zip(changes,changes[1:]))
xs = [s['orange']['cx'] for s in stats]
# The tutorial is a vertical bounce in place. A ball that traverses
# the whole canvas while bouncing does not match its motion path.
anim = (motion(ys) > 15 and reversals >= 2 and
motion(xs) < max(12, motion(ys)*.45))
ratios = [span(b,0)/max(1,span(b,1)) for b in boxes]
details = bool(ratios and max(ratios) > 1.15 and min(ratios) < 1.1)
hold = end[-1]['orange']['count'] > 15
elif kind == 't46':
palette = endavg('offwhite') > .65 and peak('blue') > 30
boxes = [s['blue']['bbox'] for s in stats if s['blue']['count'] > 25]
design = any(span(b,0) > 3*span(b,1) and span(b,0) > 35 for b in boxes)
# The outlined track spans the full width even before the fill grows.
# Measure blue area change rather than the outline's bounding box.
counts = [s['blue']['count'] for s in stats]
anim = (motion(counts) > 120 and
sum(s['blue']['count'] for s in end)/len(end) >
sum(s['blue']['count'] for s in start)/len(start) + 100)
# A black background must not earn rim/arrow-detail credit. The
# tutorial's left chevron changes the blue left edge across rows.
details = (max(s['blue']['left_edge_variation'] for s in middle) > 3
and peak('blue') > 60)
hold = end[-1]['blue']['count'] > 25
elif kind == 't48':
palette = endavg('dark') > .60 and peak('red') > 20 and peak('white') > 15
boxes = [s['red']['bbox'] for s in stats if s['red']['count'] > 20]
design = any(span(b,0) > 2*span(b,1) and span(b,0) > 15 for b in boxes)
widths = [span(s['red']['bbox'],0) for s in stats]
anim = motion(widths) > 8 or motion([s['red']['cx'] for s in stats]) > 8
details = peak('white') > 20 and peak('red') > 35
# The demonstrated subscribed state can fade the red play icon while
# retaining the blue/white button.
hold = (end[-1]['red']['count'] > 20 or
(end[-1]['white']['count'] > 70 and
end[-1]['blue']['count'] > 40 and
end[-1]['dark']['fraction'] > .60))
else:
raise ValueError(kind)
add(checks, 'Tutorial palette', 20, palette,
{'peak_subject_pixels': {k:peak(k) for k in ('blue','yellow','orange','red')},
'end_white': endavg('white'), 'end_dark': endavg('dark')})
add(checks, 'Subject design and placement', 20, design,
{'sample_boxes': boxes[:10] if boxes else []})
add(checks, 'Tutorial motion', 25, anim,
{'samples': n, 'start': start[0], 'end': end[-1]})
detail_evidence = {'subject_boxes': len(boxes)}
if kind == 't46':
detail_evidence['blue_left_edge_variation_peak'] = max(
s['blue']['left_edge_variation'] for s in middle)
add(checks, 'Tutorial details', 15, details, detail_evidence)
add(checks, 'Final composition and hold', 5, hold, end[-1])
def grade_t47(a, b, checks):
def one(stats, method):
n=len(stats)
if not n:
for name,points in [('palette',10),('bubble and text',15),('animation',10)]:
add(checks,f'Method {method} {name}',points,False,'No decodable frames')
return
blues=[s['blue']['count'] for s in stats]
whites=[s['white']['count'] for s in stats]
pinks=[s['pink']['count'] for s in stats]
if method==1:
palette=max(blues)>100 and max(s['navy']['fraction'] for s in stats)>.35
design=max(blues)>150 and max(whites)>40
anim=motion(blues)>40
else:
palette=max(pinks)>35 and max(blues)>35
design=max(pinks)>65 and max(whites)>50
anim=motion(pinks)>30 or motion([s['pink']['cx'] for s in stats])>8
add(checks,f'Method {method} tutorial palette',10,palette,
{'peak_blue':max(blues),'peak_pink':max(pinks)})
add(checks,f'Method {method} bubble and text design',15,design,
{'peak_white':max(whites),'samples':n})
add(checks,f'Method {method} animated entrance',10,anim,
{'blue_range':motion(blues),'pink_range':motion(pinks)})
one(a,1);one(b,2)
distinct=bool(a and b and abs(max(s['pink']['count'] for s in a)-
max(s['pink']['count'] for s in b))>30)
add(checks,'Distinct tutorial methods',5,distinct,
{'method1_frames':len(a),'method2_frames':len(b)})
def main():
spec=json.loads((ROOT/'rubric.json').read_text())
task=spec['task_id'];w,h=(160,140) if task=='t45' else ((160,90) if spec['output_size'][0]>spec['output_size'][1] else (90,160))
paths=[DESKTOP/name for name in (['method1.mp4','method2.mp4'] if task=='t47' else ['final.mp4'])]
checks=[];analyzed=[]
for path in paths:
actual_path=path
meta,frames=video(path,w,h)
if not meta and task!='t47':
for candidate in [*sorted(DESKTOP.glob('*.mp4')),
*sorted(PROJECT.parent.glob('*.mp4'))]:
if candidate == path:
continue
meta,frames=video(candidate,w,h)
if meta:
actual_path=candidate
break
common(checks,path,meta,frames,spec,5,5,actual_path)
analyzed.append([frame_stats(f,w,h) for f in frames])
saved=PROJECT.exists() and PROJECT.stat().st_size>=1024
add(checks,'Native editable Friction project',5,saved,
{'bytes': PROJECT.stat().st_size if PROJECT.exists() else 0})
if task=='t47':
grade_t47(*analyzed,checks)
else:
grade_one(task,analyzed[0],checks)
total=sum(x['points'] for x in checks)
if total != 100:
raise RuntimeError(f'Rubric weights sum to {total}, expected 100')
reward=sum(x['earned'] for x in checks)/total
OUT.mkdir(parents=True,exist_ok=True)
report={'task':task,'rubric_version':'video-v1',
'reference_video_sha256':spec.get('reference_video_sha256'),
'reference_frames':spec.get('reference_frames'), 'checks':checks,
'possible_points':total,'earned_points':sum(x['earned'] for x in checks),
'reward':reward,'outputs':[str(p) for p in paths],
'actual_outputs':[str(actual_path) if task!='t47' else str(p)
for p in paths]}
(OUT/'score.json').write_text(json.dumps(report,indent=2)+'\n')
(OUT/'reward.txt').write_text(f'{reward:.6f}\n')
if __name__=='__main__':
main()
|