Download tasks/t23-dance-blob/tests/reference_score.py from refreshdotdev/Refresh-GUI-dataset: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/bbd50c4e8c7e5749a41d52fa58ed3cbddfbcea1d/tasks/t23-dance-blob/tests/reference_score.py
- Command line
-
hf download hf://datasets/refreshdotdev/Refresh-GUI-dataset@bbd50c4e8c7e5749a41d52fa58ed3cbddfbcea1d/tasks/t23-dance-blob/tests/reference_score.py
-
curl -L -o reference_score.py https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/bbd50c4e8c7e5749a41d52fa58ed3cbddfbcea1d/tasks/t23-dance-blob/tests/reference_score.py
15.9 kB
| """t23 v1: reference-conditioned, offline visual checklist (ALE-inspired). | |
| Uses only stdlib + ffmpeg. Twenty equally weighted binary questions; export | |
| requirements and the existing GUI-only rule are gates, not appearance points. | |
| The immutable feature manifest is built from the exact clip shown to the agent. | |
| """ | |
| import argparse | |
| import colorsys | |
| import hashlib | |
| import json | |
| import math | |
| from pathlib import Path | |
| import statistics as st | |
| import legacy_v0 as v0 | |
| VERSION = 't23-reference-v1' | |
| GRID = 64 | |
| REFERENCE = Path(__file__).parent / 'reference' / 'visual-reference.json' | |
| def mean(xs): | |
| return st.mean(xs) if xs else 0.0 | |
| def sha(path): | |
| return hashlib.sha256(Path(path).read_bytes()).hexdigest() | |
| def period_fit(h): | |
| # Fit a repeated height trace over the whole clip. Multi-cycle lags avoid | |
| # rounding a 14.25-frame reference hop to 14 frames and accumulating drift. | |
| if len(h) < 60 or max(h) - min(h) < 2: | |
| return None | |
| best = (float('inf'), None) | |
| for k in range(480, 721): | |
| p = k / 40 # 12..18 frames, 0.4..0.6 seconds | |
| errors = [] | |
| for cycles in (1, 2, 4, 6): | |
| lag = cycles * p | |
| n = int(lag) | |
| frac = lag - n | |
| errors.extend((h[i] - ((1-frac)*h[i+n] + frac*h[i+n+1]))**2 | |
| for i in range(len(h)-n-1)) | |
| cost = mean(errors) | |
| if cost < best[0]: | |
| best = cost, p | |
| # A fit pegged to the search boundary is not evidence of the requested hop. | |
| return best[1] if best[1] not in (12.0, 18.0) else None | |
| def profile(values, period): | |
| sums = [[] for _ in range(12)] | |
| for i, x in enumerate(values): | |
| sums[int((i / period % 1) * 12)].append(x) | |
| return [mean(x) for x in sums] | |
| def rotate(x, n): | |
| return x[n:] + x[:n] | |
| def template(frame, b): | |
| """Canonical body and face masks; no background contribution to overlap.""" | |
| body, face = [], [] | |
| for y in range(GRID): | |
| yy = b['top'] + min(b['h'] - 1, int((y + .5) * b['h'] / GRID)) | |
| for x in range(GRID): | |
| xx = b['x0'] + min(b['w'] - 1, int((x + .5) * b['w'] / GRID)) | |
| p = 3 * (yy * v0.S + xx) | |
| rgb = frame[p:p+3] | |
| dark = max(rgb) < 110 | |
| body.append(int(max(rgb) - min(rgb) > 50 or min(rgb) < 180)) | |
| face.append(int(dark)) | |
| return body, face | |
| def pack(mask): | |
| return hex(sum(x<<i for i,x in enumerate(mask)))[2:] | |
| def unpack(encoded): | |
| n=int(encoded,16) | |
| return [(n>>i)&1 for i in range(GRID*GRID)] | |
| def pose_bank(poses): | |
| # Keep separate observed drawings: averaging masks would erase moving eyes | |
| # and tilted smiles. Uniform samples span the full video, including repeats. | |
| indices=sorted(set(round(i*(len(poses)-1)/31) for i in range(32))) if poses else [] | |
| return [{'body':pack(poses[i][0]),'face':pack(poses[i][1])} for i in indices] | |
| def extract(path): | |
| frames = v0.decode(str(path)) | |
| if not frames: | |
| return {'valid': False, 'reason': 'video did not fully decode'} | |
| analyses = [v0.analyse(f) for f in frames] | |
| full = [[b for b in a['blobs'] if b['full']] for a in analyses] | |
| valid = [i for i, b in enumerate(full) if len(b) >= 2] | |
| if len(valid) < .9 * len(frames): | |
| return {'valid': False, 'reason': 'fewer than two complete coloured blobs on over 10% of frames'} | |
| h = [st.median(b['h'] for b in full[i]) if full[i] else 0 for i in range(len(frames))] | |
| w = [st.median(b['w'] for b in full[i]) if full[i] else 0 for i in range(len(frames))] | |
| bottom = [st.median(b['bot'] for b in full[i]) for i in valid] | |
| spacing = [bs[j+1]['x0'] - bs[j]['x0'] for bs in full for j in range(len(bs)-1)] | |
| p = period_fit(h) | |
| lo, hi = min(x for x in h if x), max(h) | |
| rest, squash = [], [] | |
| hues, saturation, value = [], [], [] | |
| for i, f in enumerate(frames): | |
| hh = [math.radians(b['hue']) for b in full[i] if b['hue'] is not None] | |
| hues.append(math.degrees(math.atan2(mean([math.sin(x) for x in hh]), mean([math.cos(x) for x in hh]))) % 360) | |
| if not full[i]: | |
| continue | |
| # Every full blob, across the entire clip, contributes to the pose masks. | |
| for b in full[i]: | |
| if h[i] >= hi - 2: | |
| rest.append(template(f, b)) | |
| if h[i] <= lo + 2: | |
| squash.append(template(f, b)) | |
| b = min(full[i], key=lambda b: abs((b['x0']+b['x1'])/2-v0.S/2)) | |
| pix = [] | |
| for y in range(b['top'], b['bot']+1, 2): | |
| for x in range(b['x0'], b['x1']+1, 2): | |
| at = 3*(y*v0.S+x) | |
| rgb = f[at:at+3] | |
| if max(rgb)-min(rgb)>50: | |
| pix.append(colorsys.rgb_to_hsv(*(c/255 for c in rgb))) | |
| saturation.append(mean([x[1] for x in pix])) | |
| value.append(mean([x[2] for x in pix])) | |
| # Track row centres modulo a spacing. Centring avoids the directional | |
| # tie bias of overlap-only column correlation as silhouettes change width. | |
| sp = st.median(spacing) | |
| locations = [] | |
| for bs in full: | |
| angles = [2*math.pi*((b['x0']+b['x1'])/2)/sp for b in bs] | |
| locations.append(math.atan2(mean([math.sin(x) for x in angles]), | |
| mean([math.cos(x) for x in angles]))*sp/(2*math.pi)) | |
| shifts = [(b-a+sp/2)%sp-sp/2 for a,b in zip(locations,locations[1:])] | |
| sp = st.median(spacing) | |
| height_profile = profile(h, p) if p else [0]*12 | |
| # Choose one phase from the height only; use it for BOTH height and motion. | |
| phase = height_profile.index(max(height_profile)) | |
| height_profile = rotate(height_profile, phase) | |
| move_profile = rotate(profile(shifts, p), phase) if p else [0]*12 | |
| angular = [(b-a+180)%360-180 for a,b in zip(hues,hues[1:])] | |
| spread = [v0.circ_spread([b['hue'] for b in bs if b['hue'] is not None]) for bs in full] | |
| return dict(valid=True, frames=len(frames), width=st.median(w)*4, | |
| rest_height=hi*4, baseline=st.median(bottom)*4, | |
| baseline_std=st.pstdev(bottom)*4, width_ratio=max(w)/max(1,min(w)), | |
| spacing=sp*4, spacing_cv=st.pstdev(spacing)/sp, | |
| white_fraction=mean([a['white']>225 for a in analyses]), | |
| squash_ratio=lo/hi if hi else 0, period_s=p/30 if p else None, | |
| height_profile=height_profile, | |
| drift=mean(shifts)*30/sp, | |
| move_profile=[x*30/sp for x in move_profile], | |
| saturation=st.median(saturation), value=st.median(value), | |
| hue_cycles_s=mean(angular)*30/360, | |
| hue_bins=len(set(int(x//30) for x in hues)), | |
| shared_fraction=mean([x<20 for x in spread]), | |
| masks={name: pose_bank(poses) for name,poses in [('rest',rest),('squash',squash)]}) | |
| def points(mask): | |
| return {(i%GRID, i//GRID) for i,x in enumerate(mask) if x} | |
| def centroid(p): | |
| return (mean([x for x,y in p]), mean([y for x,y in p])) if p else (0,0) | |
| def compare(a,r): | |
| checks=[] | |
| def check(id, category, question, got, threshold, passed): | |
| checks.append(dict(id=id, category=category, question=question, | |
| measured=got, tolerance=threshold, passed=bool(passed), weight=.05)) | |
| if not a.get('valid'): | |
| return checks | |
| pose_results={} | |
| for pose in ('rest','squash'): | |
| def describe(t): | |
| body=points(unpack(t['body'])) | |
| face=points(unpack(t['face'])) | |
| c=centroid(face) | |
| centred={(x-round(c[0]),y-round(c[1])) for x,y in face} | |
| dilated={(x+dx,y+dy) for x,y in centred for dx in (-1,0,1) for dy in (-1,0,1)} | |
| return body,face,c,centred,dilated | |
| ab=[describe(t) for t in a['masks'][pose]] | |
| rb=[describe(t) for t in r['masks'][pose]] | |
| metrics=[] | |
| for ap,af,ac,asc,ad in ab: | |
| choices=[] | |
| for rp,rf,rc,rsc,rd in rb: | |
| iou=len(ap&rp)/len(ap|rp) if ap|rp else 0 | |
| precision=len(asc&rd)/len(asc) if asc else 0 | |
| recall=len(rsc&ad)/len(rsc) if rsc else 0 | |
| f1=2*precision*recall/(precision+recall) if precision+recall else 0 | |
| dist=math.dist(ac,rc)/GRID if af and rf else 1 | |
| area=abs(len(af)/len(rf)-1) if rf else 1 | |
| # One reference drawing supplies every metric for this pair. | |
| choices.append((iou+.2*f1-.2*dist,iou,f1,dist,area)) | |
| metrics.append(max(choices)[1:]) | |
| vals=[mean([m[i] for m in metrics]) for i in range(4)] | |
| pose_results[pose]=vals | |
| iou,f1,_,_=vals | |
| check('silhouette_'+pose,'appearance','Does the foreground silhouette match at '+pose+'?',iou,'mean paired IoU >= 0.92',iou>=.92) | |
| check('face_drawing_'+pose,'appearance','Do the facial strokes match at '+pose+' after centring?',f1,'mean paired tolerant F1 >= 0.75',f1>=.75) | |
| distance=mean([v[2] for v in pose_results.values()]) | |
| check('face_placement','appearance','Is the face placed at the same relative position within the body?',distance,'mean centroid distance <= 0.04 body units',distance<=.04) | |
| density_error=mean([v[3] for v in pose_results.values()]) | |
| check('face_weight','appearance','Does the amount of dark facial ink match?',density_error,'mean relative area error <= 0.25',density_error<=.25) | |
| for field in ('width','rest_height'): | |
| error=abs(a[field]/r[field]-1) | |
| check(field,'appearance','Does the blob '+field+' match the reference?',error,'relative error <= 0.08',error<=.08) | |
| delta=abs(a['baseline']-r['baseline']) | |
| check('floor','layout','Is the row at the reference floor height?',delta,'difference <= 8 pixels at 800x800',delta<=8) | |
| check('background','layout','Does the plain white background match?',a['white_fraction'],'white border on >= 95% frames',a['white_fraction']>=.95) | |
| error=abs(a['spacing']/r['spacing']-1) | |
| check('spacing','layout','Does the repeated row spacing match?',dict(relative_error=error,cv=a['spacing_cv']),'error <= 0.08 and CV <= 0.08',error<=.08 and a['spacing_cv']<=.08) | |
| error=abs(a['period_s']/r['period_s']-1) if a['period_s'] and r['period_s'] else 1 | |
| check('hop_period','motion','Does the repeating hop cadence match?',error,'relative period error <= 0.10',error<=.10) | |
| error=abs(a['squash_ratio']-r['squash_ratio']) | |
| check('squash_depth','motion','Does the squash reach the reference relative height?',error,'ratio difference <= 0.05',error<=.05) | |
| check('pinned_floor','motion','Do the feet stay pinned as in the reference?',a['baseline_std'],'baseline std <= max(reference + 2, 4) pixels',a['baseline_std']<=max(r['baseline_std']+2,4)) | |
| check('stable_width','motion','Does width remain constant during the squash?',a['width_ratio'],'max/min <= max(reference + 0.02, 1.05)',a['width_ratio']<=max(r['width_ratio']+.02,1.05)) | |
| def norm(h): | |
| span=max(h)-min(h) | |
| return [(x-min(h))/span for x in h] if span else [0]*len(h) | |
| ah,rh=norm(a['height_profile']),norm(r['height_profile']) | |
| # At most one bin correction for quantized rest plateaus; never warp time. | |
| offsets=(-1,0,1) | |
| best=min(offsets,key=lambda o: mean([abs(x-y) for x,y in zip(rotate(ah,o),rh)])) | |
| error=mean([abs(x-y) for x,y in zip(rotate(ah,best),rh)]) | |
| check('squash_easing','motion','Does the normalized squash/spring timing curve match?',error,'12-phase mean absolute error <= 0.08',a['period_s'] is not None and error<=.08) | |
| error=abs(a['drift']/r['drift']-1) if r['drift'] else abs(a['drift']) | |
| check('rightward_travel','motion','Does the row advance right at the reference rate?',dict(relative_error=error,agent=a['drift'],reference=r['drift']),'positive travel; relative error <= 0.15',a['drift']>0 and error<=.15) | |
| amp=max(r['move_profile']) or 1 | |
| error=mean([abs(x-y)/amp for x,y in zip(rotate(a['move_profile'],best),r['move_profile'])]) | |
| check('hop_pulse','motion','Is rightward motion pulsed at the same stage of the squash?',error,'phase velocity error <= 0.15 and positive drift',a['drift']>0.2 and error<=.15) | |
| error=max(abs(a['saturation']-r['saturation']),abs(a['value']-r['value'])) | |
| check('palette','colour','Does the fill have the reference saturation and brightness?',error,'HSV saturation/value difference <= 0.08',error<=.08) | |
| error=abs(a['hue_cycles_s']/r['hue_cycles_s']-1) if r['hue_cycles_s'] else 1 | |
| check('colour_cycle','colour','Does the shared hue cycle follow the reference direction and rate?',dict(rate_error=error,bins=a['hue_bins'],shared=a['shared_fraction']),'rate error <= 0.15; reference hue coverage minus <= 1 bin; shared >= 95%',error<=.15 and a['hue_bins']>=max(6,r['hue_bins']-1) and a['shared_fraction']>=.95) | |
| assert len(checks)==20 | |
| return checks | |
| def evaluate(video, project, terminal_log, reference=REFERENCE): | |
| manifest=json.loads(Path(reference).read_text()) # missing reference is evaluator error | |
| if manifest.get('version')!=VERSION: | |
| raise ValueError('reference manifest version mismatch') | |
| meta=v0.probe(str(video)) | |
| streams=meta.get('streams',[]) if meta else [] | |
| video_stream=next((x for x in streams if x.get('codec_type')=='video'),{}) | |
| gates=dict(decodable=bool(meta),size=v0.video_size(meta)==(800,800) if meta else False, | |
| duration=abs((v0.duration(meta) or 0)-6)<=1 if meta else False, | |
| codec=video_stream.get('codec_name')=='h264', | |
| no_audio=not any(x.get('codec_type')=='audio' for x in streams), | |
| fps=video_stream.get('avg_frame_rate') in ('30/1','60/2'), | |
| project=Path(project).is_file() and Path(project).stat().st_size>=1024, | |
| gui_only=not(Path(terminal_log).exists() and Path(terminal_log).read_text().strip())) | |
| a=extract(video) if meta else {'valid':False} | |
| gates['visible_blobs']=a.get('valid',False) | |
| gates['decoded_duration']=150<=a.get('frames',0)<=210 | |
| checks=compare(a,manifest['features']) | |
| quality=round(sum(x['weight'] for x in checks if x['passed']),4) | |
| result=dict(version=VERSION,method='deterministic reference-conditioned binary checklist', | |
| paper='https://arxiv.org/html/2606.05405v1#A3.SS3.SSS4', | |
| reference_sha256=manifest['source_sha256'], | |
| candidate_sha256=sha(video) if Path(video).exists() else None, | |
| reference_manifest_sha256=sha(reference),scorer_sha256=sha(__file__), | |
| gates=gates,checks=checks,visual_score=quality, | |
| reward=quality if all(gates.values()) else 0., | |
| features=a,reference_features=manifest['features']) | |
| return result | |
| def main(): | |
| p=argparse.ArgumentParser() | |
| p.add_argument('--build-reference',type=Path) | |
| p.add_argument('--video',type=Path) | |
| p.add_argument('--project',type=Path) | |
| p.add_argument('--terminal-log',type=Path,default=Path('/nonexistent-terminal-log')) | |
| p.add_argument('--output',type=Path,required=True) | |
| args=p.parse_args() | |
| if args.build_reference: | |
| features=extract(args.build_reference) | |
| if not features.get('valid'): | |
| raise ValueError('reference extraction failed') | |
| result=dict(version=VERSION,source='Agent-visible environment/media/reference.mp4', | |
| source_sha256=sha(args.build_reference),features=features) | |
| else: | |
| if not args.video or not args.project: | |
| p.error('--video and --project are required to grade') | |
| result=evaluate(args.video,args.project,args.terminal_log) | |
| print(json.dumps({k:v for k,v in result.items() if k not in ('features','reference_features','checks')},indent=2)) | |
| for c in result['checks']: | |
| print(('PASS' if c['passed'] else 'FAIL'),c['id'],c['measured']) | |
| args.output.parent.mkdir(parents=True,exist_ok=True) | |
| args.output.write_text(json.dumps(result,indent=2)+'\n') | |
| if __name__=='__main__': | |
| main() | |