File size: 16,455 Bytes
e33425b | 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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | """Offline Harbor scorer. Geometry is rasterized from each authoritative SVG.
Candidate animation is judged from decoded renders, never inferred from a
binary project or an SVG tag alone. The Friction render is evaluated.
"""
import argparse
import hashlib
import json
import math
import bisect
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
import cv2
import numpy as np
import sys
if len(Path(__file__).resolve().parents)>2 and (Path(__file__).resolve().parents[2]/'tasks/golf-tracer-batch/golf-01-akshay-bhatia-driver/tests').exists():sys.path.append(str(Path(__file__).resolve().parents[2]/'tasks/golf-tracer-batch/golf-01-akshay-bhatia-driver/tests'))
from svgpath import path_polylines, _parse_transform, _mat_mul, svg_polylines
from tracer_intervals import active_interval, score_intervals
# Avoid excessive OpenCV thread overhead on small CPU Daytona sandboxes.
cv2.setNumThreads(1)
def probe(p):
return json.loads(subprocess.check_output([
'ffprobe', '-v', 'error', '-count_frames', '-show_streams', '-show_format',
'-of', 'json', str(p)], timeout=120))
def reference_mask(p, w, h):
root = ET.parse(p).getroot()
out = np.zeros((h, w), np.uint8)
def walk(el, parent, opacity):
matrix = _mat_mul(parent, _parse_transform(el.get('transform')))
opacity *= float(el.get('opacity', 1))
if el.tag.split('}')[-1] == 'path' and opacity > 0:
width = float(el.get('stroke-width', 6)) * math.hypot(matrix[0], matrix[3])
for poly in path_polylines(el.get('d', '')):
pts = np.array(poly, dtype=float)
if len(pts) < 2:
continue
distances = np.r_[0, np.cumsum(np.linalg.norm(np.diff(pts, axis=0), axis=1))]
# These exported references use one on-dash followed by one off-dash.
dash = el.get('stroke-dasharray')
if dash:
length = float(dash.replace(',', ' ').split()[0])
revealed = max(0, length - float(el.get('stroke-dashoffset', 0)))
if revealed <= 0:
continue
idx = min(int(np.searchsorted(distances, revealed, side='right')), len(pts)-1)
clipped = pts[:idx].tolist()
if idx > 0:
a = (revealed-distances[idx-1]) / max(1e-9, distances[idx]-distances[idx-1])
clipped.append((pts[idx-1]+np.clip(a, 0, 1)*(pts[idx]-pts[idx-1])).tolist())
pts = np.array(clipped)
if len(pts) < 2:
continue
m = np.array([[matrix[0], matrix[1], matrix[2]], [matrix[3], matrix[4], matrix[5]]])
screen = np.c_[pts, np.ones(len(pts))] @ m.T
q = np.round(screen*16).astype(np.int32)
cv2.polylines(out, [q], False, 255, max(1, round(width)), cv2.LINE_AA, shift=4)
for point in [q[0], q[-1]]:
cv2.circle(out, tuple(point), round(width*8), 255, -1, cv2.LINE_AA, shift=4)
for ch in el:
walk(ch, matrix, opacity)
walk(root, (1, 0, 0, 0, 1, 0), 1)
return out > 80
def red_mask(source, candidate):
delta = np.max(np.abs(source.astype(np.int16)-candidate.astype(np.int16)), axis=2)
b, g, r = cv2.split(candidate)
return ((r > 105) & (r.astype(float) > g+40.) & (r.astype(float) > b+40.) & (delta > 28))
def coverage(a, b, tolerance):
if not np.any(a):
return 1.0 if not np.any(b) else 0.0
if not np.any(b):
return 0.0
# Exact dilation by a Euclidean disk equals the requested pixel corridor.
radius=int(math.ceil(tolerance)); yy,xx=np.ogrid[-radius:radius+1,-radius:radius+1]
kernel=((xx*xx+yy*yy)<=tolerance*tolerance).astype(np.uint8)
allowed=cv2.dilate(b.astype(np.uint8),kernel)>0
return float(np.mean(allowed[a]))
def audio_score(a, b):
def pcm(p):
if not any(s['codec_type']=='audio' for s in probe(p)['streams']):
return np.array([], dtype=float)
raw = subprocess.check_output(['ffmpeg','-v','error','-i',str(p),'-vn','-ac','1',
'-ar','8000','-f','f32le','-'], timeout=120)
return np.frombuffer(raw, '<f4').astype(float)
x, y = pcm(a), pcm(b)
if len(x) == 0:
return float(len(y) == 0)
if abs(len(x)-len(y)) > 1600 or len(y) == 0:
return 0.0
n = min(len(x),len(y)); x=x[:n];y=y[:n]
if np.std(x) < 1e-5:
return float(np.std(y)<1e-4)
# Audio codecs may introduce a short priming offset.
scores=[]
for lag in range(-800,801,40):
xx=x[max(lag,0):n+min(lag,0)]; yy=y[max(-lag,0):n+min(-lag,0)]
corr=float(np.dot(xx,yy)/max(1e-10,np.linalg.norm(xx)*np.linalg.norm(yy)))
gain=np.linalg.norm(yy)/max(1e-10,np.linalg.norm(xx))
scores.append(max(0,corr)*max(0,1-abs(gain-1)))
return max(scores)
def find_render(outputs):
required=outputs/'edit/traced/shot_01.mp4'
if required.is_file():
try:probe(required);return required
except Exception:pass
candidates=list((outputs/'edit').rglob('*.mp4'))
playable=[]
for path in candidates:
try:
info=probe(path);v=next(x for x in info['streams'] if x['codec_type']=='video')
playable.append((int(v.get('nb_read_frames',0)),path))
except Exception:pass
return max(playable,key=lambda x:x[0])[1] if playable else required
def evaluate_video(source, candidate, refdir, data, config):
w,h=data['width'],data['height']; output=config['output']; n=output['frame_count']; fps=output['fps']
# Work in output pixels so a margin has the exact advertised meaning.
ow,oh=output['width'],output['height']; scale=ow/w
timestamps=[r['time_seconds'] for r in data['frames']]
if not candidate.is_file():
return {'valid':False,'reason':'missing render'}
try:
streams=probe(candidate)['streams']; v=next(s for s in streams if s['codec_type']=='video')
count=int(v.get('nb_read_frames',0)); rate=eval_fraction(v['avg_frame_rate'])
if count<=0 or rate<=0:raise ValueError('No decodable video frames')
duration=count/rate
compliance={'dimensions':v['width']==ow and v['height']==oh,'fps':abs(rate-fps)<0.015,'codec':v['codec_name']=='h264','audio':not any(s['codec_type']=='audio' for s in streams),'duration':min(duration,n/fps)/max(duration,n/fps)}
except Exception as e:
return {'valid':False,'reason':str(e)}
a=cv2.VideoCapture(str(source));b=cv2.VideoCapture(str(candidate));rows=[]
source_index=-1;src=None;expected=None
candidate_index=-1;img=None
for f in range(n):
index=min(len(timestamps)-1,max(0,bisect.bisect_right(timestamps,f/fps+1e-6)-1))
state=data['frames'][index]
ok1=True
while source_index<index:
ok1,src=a.read();source_index+=1
if not ok1:break
target_index=int(f/fps*rate+1e-6);ok2=True
while candidate_index<target_index:
ok2,img=b.read();candidate_index+=1
if not ok2:break
if target_index>=count:
rows.append({'frame':f,'source_reference_frame':index,'position_tolerance_px':10,'phase':state['phase'],'confidence':state['confidence'],'weight':1,'geometry':0,'presence':0,'growth':0,'tip':0,'style':0,'preservation':0,'expected_pixels':1,'actual_pixels':0,'missing_candidate_frame':True});continue
if ok2 and img is not None and img.shape[:2]!=(oh,ow):img=cv2.resize(img,(ow,oh),interpolation=cv2.INTER_LANCZOS4)
if not(ok1 and ok2):
a.release();b.release();return {'valid':False,'reason':'decode failure'}
expected_native=reference_mask(refdir/'svg_frames'/f'{index:06d}.svg',w,h)
expected=cv2.resize(expected_native.astype(np.uint8),(ow,oh),interpolation=cv2.INTER_NEAREST)>0
scaled_source=cv2.resize(src,(ow,oh),interpolation=cv2.INTER_LANCZOS4)
actual=red_mask(scaled_source,img); uncertain=state['confidence'] in ['low','unobserved']
tolerance=config['spatial_tolerance_output_px']['low_or_unobserved' if uncertain else 'medium']
recall=coverage(expected,actual,tolerance); precision=coverage(actual,expected,tolerance)
geometry=2*recall*precision/max(1e-9,recall+precision)
e=int(expected.sum());c=int(actual.sum())
# Very short first segments still count; codecs can lose a few pixels.
presence=float((c>3)==(e>3))
growth=1.0 if e<=3 and c<=3 else max(0,1-abs(c-e)/max(40,e))
tip=state.get('tip_xy');tipscore=None
if tip is not None and state['phase'] not in ['holding','offscreen_gap']:
x,y=np.array(tip)*scale
if 0<=x<ow and 0<=y<oh:
yy,xx=np.where(actual)
dist=float(np.min(np.hypot(xx-x,yy-y))) if len(xx) else 1e6
tipscore=1.0 if dist<=tolerance else max(0,1-(dist-tolerance)/tolerance)
# Exclude the complete accepted-position corridor plus codec edge margin.
radius=tolerance+6
zone=cv2.dilate(expected.astype(np.uint8),np.ones((2*radius+1,2*radius+1),np.uint8))>0
annotation = config.get('tracer_intervals')
if annotation:
interval = active_interval(index, annotation, data['frames'][-1]['frame'])
permitted_extension = interval and interval.get('allow_growth_after_end') and index > interval['growth_end_frame']
permitted_early = any(i.get('allow_early_start') and index < i['start_frame'] for i in annotation['intervals'])
if permitted_extension or permitted_early:
zone |= cv2.dilate(actual.astype(np.uint8), np.ones((13,13), np.uint8)) > 0
diff=np.abs(scaled_source.astype(float)-img.astype(float))
preservation=max(0,1-float(diff[~zone].mean())/12) if np.any(~zone) else 1
colour=0.0
if c:
values=img[actual][:,::-1].astype(float)
colour=max(0,1-float(np.mean(np.linalg.norm(values-[255,0,0],axis=1)))/200)
area= min(c,e)/max(1,c,e) if e else float(c<=3)
rows.append({'frame':f,'source_reference_frame':index,'position_tolerance_px':tolerance,'phase':state['phase'],'confidence':state['confidence'],
'weight':0.35 if uncertain else 1,'geometry':geometry,'presence':presence,'growth':growth,
'tip':tipscore,'style':(colour+area)/2 if e else float(c<=3),
'preservation':preservation,'expected_pixels':e,'actual_pixels':c})
a.release();b.release()
annotation = config.get('tracer_intervals')
interval_report = None
if annotation:
last_frame = data['frames'][-1]['frame']
interval_report = score_intervals(rows, annotation, last_frame)
for row in rows:
f = row['source_reference_frame']
interval = active_interval(f, annotation, last_frame)
optional_early = any((i.get('allow_early_start') or i['start_frame'] - annotation.get('onset_tolerance_frames', 3) <= f) and f < i['start_frame']
for i in annotation['intervals'])
relaxed_hold = interval and interval.get('growth_end_frame') is not None and f > interval['growth_end_frame']
if optional_early or relaxed_hold:
for key in ['geometry', 'growth', 'tip', 'style']:
row[key] = None
if optional_early:
row['presence'] = None
else:
row['presence'] = float(row['actual_pixels'] > 3)
elif not row.get('missing_candidate_frame'):
expected_visible = interval is not None
row['presence'] = float((row['actual_pixels'] > 3) == expected_visible)
# An obsolete reference onset must not impose a conflicting
# growth/position requirement on newly annotated frames.
if not expected_visible or expected_visible != (row['expected_pixels'] > 3):
for key in ['geometry', 'growth', 'tip', 'style']:
row[key] = None
def avg(key,active=False):
rr=[r for r in rows if r[key] is not None and (not active or r['expected_pixels']>3)]
return sum(r[key]*r['weight'] for r in rr)/max(1e-9,sum(r['weight'] for r in rr))
audio=audio_score(source,candidate)
return {'valid':True,'compliance':compliance,'candidate_duration_seconds':duration,'comparison':'original timestamps; no duration stretching; missing frames receive zero; excess duration affects export compliance','geometry':avg('geometry',True),
'timing':0.5*avg('presence')+0.5*avg('growth'), 'tip':avg('tip'),
'timestamp_interval':interval_report['score'] if interval_report else 0,
'tracer_intervals':interval_report,
'style':avg('style',True),'preservation':0.7*avg('preservation')+0.3*audio,
'audio':audio,'frames':rows}
def eval_fraction(x):
a,*b=x.split('/');return float(a)/(float(b[0]) if b else 1)
def grade(task, outputs, log):
log.mkdir(parents=True,exist_ok=True)
ref=task/'tests/reference';d=json.loads((ref/'trajectory.json').read_text())
source=task/'environment/media/source.mp4'
if not source.exists(): source=Path('/root/media/source.mp4')
source_valid=hashlib.sha256(source.read_bytes()).hexdigest()==d['source_sha256']
config=json.loads((task/'tests/rubric.json').read_text())
candidate=find_render(outputs)
render=evaluate_video(source,candidate,ref,d,config)
scores={k:render.get(k,0) for k in ['geometry','timing','timestamp_interval','tip','style','preservation']}
svg=outputs/'edit/svg/shot_01.svg';svg_score=0
if svg.exists():
try:
text=svg.read_text();root=ET.fromstring(text)
no_media=not any(e.tag.split('}')[-1] in ['image','foreignObject','script'] for e in root.iter())
# SVG is an editable vector-deliverable check. Renders supply animation truth.
svg_score=float(no_media and any(len(p)>1 for p in svg_polylines(text)))
except Exception: pass
scores['svg']=svg_score
checks=render.get('compliance',{})
checks['filename']=candidate==outputs/'edit/traced/shot_01.mp4'
scores['export']=sum(float(x) for x in checks.values())/6 if render['valid'] else 0
weights=config.get('weights', {'svg':8,'geometry':38,'timing':8,'timestamp_interval':10,'tip':12,'style':8,'preservation':8,'export':8})
gates=[]
if not source_valid:gates.append('source hash changed')
audit=outputs/'terminal-attempts.log'
if not audit.exists():audit=Path('/logs/artifacts/terminal-attempts.log')
if audit.exists() and audit.stat().st_size:
gates.append('terminal use')
if not render['valid']:gates.append('missing or nonconforming render')
# Normalize raster/codec artefacts against the supplied reference itself.
baseline=json.loads((task/'tests/calibration.json').read_text())
for key in ['geometry','timing','tip','style','preservation']:
scores[key]=min(1.0,scores[key]/max(1e-9,baseline[key]))
reward=0 if gates else sum(weights[k]*v for k,v in scores.items())/100
report={'reward':reward,'gates':gates,'weights':weights,'scores':scores,
'render':render,'candidate_path':str(candidate),'grading_revision':'source-frame-intervals-v1',
'limitations':['Reference SVG geometry is compared to decoded render pixels; no native project is inspected.',
'Artifact checks do not prove GUI provenance. The launch adapter and trajectory audit enforce application-only work; Friction expressions are allowed.',
'Style measures colour and footprint; cap/join/taper/glow are assessed through SVG-reference geometry, not independently classified.',
'Low-confidence reference positions are guide estimates, not physical ball-location ground truth.']}
(log/'score.json').write_text(json.dumps(report,indent=2)+'\n')
(log/'reward.txt').write_text(f'{reward:.6f}\n')
print(json.dumps({'reward':reward,'scores':scores,'gates':gates}))
return report
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--task',type=Path,default=Path('/'))
p.add_argument('--outputs',type=Path,default=Path('/root'));p.add_argument('--log',type=Path,default=Path('/logs/verifier'))
a=p.parse_args();grade(a.task,a.outputs,a.log)
|