sidrefresh's picture
Add files using upload-large-folder tool
e33425b verified
Raw History Blame
14.9 kB
#!/usr/bin/env python3
"""Deterministic t49 artifact scorer, using the tutorial's visible shape poses.
No model call, downloaded asset, or GUI state is needed for visual scoring.
An evaluator error exits nonzero without writing a reward. Missing agent
artifacts are valid partial-work evidence and receive no unsupported points.
"""
import argparse
from collections import deque
import json
from pathlib import Path
import subprocess
W, H = 160, 90
PIXELS = W * H
REF = Path(__file__).parent / "reference" / "tutorial-shapes-30s.png"
def run(cmd):
return subprocess.run(cmd, check=True, capture_output=True).stdout
def decode(path, single=False):
args = ["ffmpeg", "-v", "error", "-i", str(path), "-vf", f"scale={W}:{H}"]
if single:
args += ["-frames:v", "1"]
args += ["-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
raw = run(args)
frame_size = PIXELS * 3
if not raw or len(raw) % frame_size:
raise RuntimeError(f"Decode produced an incomplete frame: {path}")
return [raw[i:i + frame_size] for i in range(0, len(raw), frame_size)]
def probe(path):
data = json.loads(run(["ffprobe", "-v", "error", "-show_streams", "-show_format",
"-of", "json", str(path)]))
stream = next((s for s in data.get("streams", []) if s.get("codec_type") == "video"), None)
if stream is None:
return None
return {"width": stream.get("width"), "height": stream.get("height"),
"fps": fraction(stream.get("avg_frame_rate", "0/1")),
"duration": float(data.get("format", {}).get("duration", 0))}
def fraction(value):
a, b = value.split("/")
return float(a) / float(b) if float(b) else 0.0
def yellow_mask(frame):
out = bytearray(PIXELS)
for p in range(PIXELS):
i = p * 3
r, g, b = frame[i], frame[i + 1], frame[i + 2]
out[p] = int(r >= 145 and g >= 75 and b <= 130 and r - g >= 20 and g - b >= 35)
return out
def components(mask):
seen = bytearray(PIXELS)
found = []
for seed in range(PIXELS):
if not mask[seed] or seen[seed]:
continue
q = deque([seed]); seen[seed] = 1; points = []
while q:
p = q.popleft(); points.append(p)
x, y = p % W, p // W
for near 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 near >= 0 and mask[near] and not seen[near]:
seen[near] = 1; q.append(near)
if len(points) >= 2:
xs = [p % W for p in points]; ys = [p // W for p in points]
found.append({"area": len(points), "cx": sum(xs) / len(xs),
"cy": sum(ys) / len(ys),
"bbox": [min(xs), min(ys), max(xs), max(ys)],
"points": points})
return sorted(found, key=lambda c: c["area"], reverse=True)
def stats(frame):
mask = yellow_mask(frame)
comp = components(mask)
return {"mask": mask, "components": comp, "main": comp[0] if comp else None}
def iou(a, b):
intersection = sum(bool(x and y) for x, y in zip(a, b))
union = sum(bool(x or y) for x, y in zip(a, b))
return intersection / union if union else 0.0
def reference_masks():
frame = decode(REF, single=True)[0]
mask = yellow_mask(frame)
triangle = bytearray(mask)
square = bytearray(mask)
for p in range(PIXELS):
if p % W >= W // 2:
triangle[p] = 0
else:
square[p] = 0
tc = components(triangle); sc = components(square)
if not tc or not sc or tc[0]["area"] < 100 or sc[0]["area"] < 100:
raise RuntimeError("Tutorial pose reference is invalid")
return triangle, square, tc[0], sc[0], frame
def check(report, name, points, status, detail):
report["checks"].append({"name": name, "points": points, "status": status,
"earned": points if status == "pass" else 0,
"detail": detail})
def grade(video, project, terminal_log):
report = {"rubric_version": "t49-video-v1", "reference": str(REF),
"checks": [], "termination": "agent-artifacts"}
if terminal_log.exists() and terminal_log.stat().st_size:
report["terminal_attempts"] = terminal_log.read_text(errors="replace").splitlines()
else:
report["terminal_attempts"] = []
meta = None
frames = []
if video.exists() and video.stat().st_size:
try:
meta = probe(video)
if meta:
frames = decode(video)
except subprocess.CalledProcessError:
# A corrupt candidate file is an observed artifact failure.
meta = None
check(report, "Readable exported video", 5, "pass" if meta and frames else
("fail" if video.exists() else "missing"), meta)
good_format = bool(meta and meta["width"] == 1920 and meta["height"] == 1080
and abs(meta["fps"] - 25) < 0.05
and abs(meta["duration"] - 5.0) <= 0.08
and 123 <= len(frames) <= 127)
check(report, "Tutorial composition format (1920x1080, 25 fps, 5 s)", 10,
"pass" if good_format else ("fail" if meta else "missing"),
{"probe": meta, "decoded_frames": len(frames)})
saved = project.exists() and project.stat().st_size >= 1024
check(report, "Native Friction project file delivered", 5,
"pass" if saved else "missing", {"path": str(project),
"bytes": project.stat().st_size if project.exists() else 0})
if not frames:
for name, points in (("Black and yellow tutorial palette", 10),
("Initial triangle pose", 15), ("Final square pose", 15),
("Anticipation, dash and overshoot", 15),
("Stretched morph and continuous handoff", 10),
("Fly-off blob", 10), ("Interior texture", 5)):
check(report, name, points, "missing", "No decodable candidate frames")
else:
tri, sq, tc, sc, ref_frame = reference_masks()
analyzed = [stats(frame) for frame in frames]
mains = [s["main"] for s in analyzed]
# The clean tutorial composition is black with one golden shape.
sample_ids = sorted({0, min(5, len(frames)-1), len(frames)//2,
max(0, len(frames)-6), len(frames)-1})
black_fracs = []; yellow_colors = []; stray_fracs = []
for fi in sample_ids:
frame = frames[fi]; mask = analyzed[fi]["mask"]
black = bright_other = 0; colors = []
for p in range(PIXELS):
i = 3*p; r,g,b = frame[i:i+3]
if max(r,g,b) < 35: black += 1
if mask[p]: colors.append((r,g,b))
elif max(r,g,b) > 80: bright_other += 1
black_fracs.append(black / PIXELS)
stray_fracs.append(bright_other / PIXELS)
if colors:
yellow_colors.append(tuple(sum(c[k] for c in colors)/len(colors) for k in range(3)))
# Tutorial yellow sample is derived from the same RGB thresholded pose.
ref_mask = yellow_mask(ref_frame)
ref_colors = [tuple(ref_frame[i:i+3]) for i in range(0,len(ref_frame),3)
if ref_mask[i//3]]
ref_color = tuple(sum(c[k] for c in ref_colors)/len(ref_colors) for k in range(3))
color_error = max((sum(abs(c[k]-ref_color[k]) for k in range(3))/3
for c in yellow_colors), default=255)
palette_ok = min(black_fracs) >= 0.86 and max(stray_fracs) <= 0.04 and color_error <= 45
check(report, "Black and yellow tutorial palette", 10,
"pass" if palette_ok else "fail",
{"black_fractions": black_fracs, "stray_fractions": stray_fracs,
"reference_rgb": ref_color, "max_channel_error": color_error})
first = analyzed[:min(12, len(frames))]
last = analyzed[max(0, len(frames)-12):]
tri_matches = [iou(s["mask"], tri) for s in first]
sq_matches = [iou(s["mask"], sq) for s in last]
def one_primary_shape(s, frame):
comps = s["components"]
# Pale rectangles and stars are separate visible shapes even when
# the yellow-only segmentation sees a single component.
other_bright = sum(max(frame[3*p:3*p+3]) > 80 and not s['mask'][p]
for p in range(PIXELS))
return bool(comps and
sum(c["area"] >= comps[0]["area"]*0.2 for c in comps) == 1
and other_bright / PIXELS <= .04)
tri_qualified = sum(v >= 0.55 and one_primary_shape(s, frame)
for v,s,frame in zip(tri_matches,first,frames[:len(first)]))
sq_qualified = sum(v >= 0.55 and one_primary_shape(s, frame)
for v,s,frame in zip(sq_matches,last,frames[-len(last):]))
tri_pass = tri_qualified >= 3
sq_pass = sq_qualified >= 3
check(report, "Initial triangle pose", 15, "pass" if tri_pass else "fail",
{"tutorial_frame_sec": 30, "best_mask_iou": max(tri_matches, default=0),
"matching_start_frames": tri_qualified})
check(report, "Final square pose", 15, "pass" if sq_pass else "fail",
{"tutorial_frame_sec": 30, "best_mask_iou": max(sq_matches, default=0),
"matching_end_frames": sq_qualified})
valid = [(i,m) for i,m in enumerate(mains) if m and m["area"] >= 35]
xs = [m["cx"] if m else None for m in mains]
start_x = tc["cx"]; end_x = sc["cx"]
left = [(i,x) for i,x in enumerate(xs[:len(xs)//2]) if x is not None and x < start_x - 1.2]
past = [(i,x) for i,x in enumerate(xs) if x is not None and x > end_x + 1.2]
return_home = bool(past and any(i > past[0][0] and x is not None and
abs(x-end_x) <= 5 for i,x in enumerate(xs)))
crossing = [(i,x) for i,x in enumerate(xs) if x is not None and
start_x + 12 < x < end_x - 12]
ordered = bool(left and crossing and past and left[0][0] < crossing[0][0] < past[-1][0])
# A fast center movement relative to the early anticipation.
speeds = [abs(xs[i]-xs[i-1]) for i in range(1,len(xs))
if xs[i] is not None and xs[i-1] is not None]
fast = max(speeds, default=0) >= 1.5
motion_ok = ordered and return_home and fast
check(report, "Anticipation, dash and overshoot", 15,
"pass" if motion_ok else "fail",
{"reference_start_x": start_x, "reference_end_x": end_x,
"left_frames": [i for i,_ in left], "crossing_frames": [i for i,_ in crossing],
"past_frames": [i for i,_ in past], "return_home": return_home,
"max_step_px_at_160w": max(speeds, default=0)})
normal_width = max(tc["bbox"][2]-tc["bbox"][0]+1,
sc["bbox"][2]-sc["bbox"][0]+1)
stretched = [i for i,m in valid if start_x+8 < m["cx"] < end_x-8 and
(m["bbox"][2]-m["bbox"][0]+1) >= normal_width*1.2]
transit = [i for i,m in valid if start_x+5 < m["cx"] < end_x-5]
gap = any(mains[i] is None for i in range(min(transit,default=0),
max(transit,default=0)+1)) if transit else True
handoff_ok = len(stretched) >= 2 and len(transit) >= 3 and not gap
check(report, "Stretched morph and continuous handoff", 10,
"pass" if handoff_ok else "fail",
{"stretched_frames": stretched, "transit_frames": transit,
"blank_gap": gap, "reference_normal_width": normal_width})
blob_events = []
for i,s in enumerate(analyzed):
if not s["main"] or s["main"]["cx"] < end_x-10: continue
for c in s["components"][1:]:
if (2 <= c["area"] <= max(3, s["main"]["area"]*0.15) and
c["cx"] > s["main"]["bbox"][2] + 1):
blob_events.append((i,c["cx"],c["area"]))
break
consecutive = any(b[0] == a[0]+1 for a,b in zip(blob_events,blob_events[1:]))
moves_right = bool(blob_events and max(e[1] for e in blob_events)-min(e[1] for e in blob_events)>=2)
shrinks = bool(blob_events and blob_events[-1][2] < blob_events[0][2])
check(report, "Fly-off blob", 10,
"pass" if consecutive and moves_right and shrinks else "fail",
{"events": blob_events[:30], "consecutive": consecutive,
"moves_right": moves_right, "shrinks": shrinks})
# Look for visible line/shading pixels inside the square's central
# region in settled poses. Dark or colored squiggles both count. This
# is intentionally low weight;
# exact aesthetics remain available for human review of the export.
textured = []
for fi in range(max(0,len(frames)-25),len(frames)):
m=mains[fi]
if not m or m["area"] < 50: continue
x0,y0,x1,y1=m["bbox"]; n=0
inset_x = max(2,(x1-x0)//5); inset_y = max(2,(y1-y0)//5)
for y in range(y0+inset_y,y1-inset_y):
for x in range(x0+inset_x,x1-inset_x):
p=y*W+x
if not analyzed[fi]["mask"][p]:n+=1
if n>=3:textured.append((fi,n))
check(report, "Interior texture", 5,
"pass" if len(textured)>=2 else "fail", {"textured_frames": textured})
report["trace"] = [{"frame":i,"main":{k:v for k,v in m.items() if k!="points"}
if m else None} for i,m in enumerate(mains)]
earned = sum(c["earned"] for c in report["checks"])
report["ungated_points"] = earned
report["score"] = 0 if report["terminal_attempts"] else earned/100
report["code_access_gate"] = "terminal-attempt" if report["terminal_attempts"] else "clear"
return report
def main():
p = argparse.ArgumentParser()
p.add_argument("--video", default="/root/Desktop/final.mp4")
p.add_argument("--project", default="/root/edit/project.friction")
p.add_argument("--terminal-log", default="/logs/artifacts/terminal-attempts.log")
p.add_argument("--reward", default="/logs/verifier/reward.txt")
p.add_argument("--report", default="/logs/verifier/score.json")
a = p.parse_args()
result = grade(Path(a.video), Path(a.project), Path(a.terminal_log))
Path(a.report).parent.mkdir(parents=True, exist_ok=True)
Path(a.report).write_text(json.dumps(result, indent=2)+"\n")
Path(a.reward).write_text(f"{result['score']:.4f}\n")
print(json.dumps({"score":result["score"], "checks":result["checks"]}, indent=2))
if __name__ == "__main__":
main()