sidrefresh's picture
Add files using upload-large-folder tool
2e7de11 verified
Raw History Blame Contribute Delete
20.5 kB
"""t16 rubric v2 — golf shot tracers graded against an APPROVED REFERENCE run.
Flow (instruction.md): /root/media/shot_01..04.mp4 → Friction: import each
clip, Add Path along the flight frame by frame, Sub-Path keyframed so the line
grows with the ball, save *.friction under /root/edit, render each clip to
/root/edit/traced/shot_0N.mp4, export each scene to /root/edit/svg/shot_0N.svg
→ Shotcut: the 4 renders in order → /root/edit/project.mlt + /root/Desktop/final.mp4.
Reference (tests/reference/tracer-reference.json, built by
tools/build-reference.py from the approved renders + SVG paths): per frame the
drawn-pixel count and the TIP of the reference line, the final drawn mask,
and the path polyline. Sid (2026-09-04): Friction's output is the heaviest
part of the score.
Friction ........................................................ 0.76
A *.friction mentions each clip (binary; QStrings are UTF-16) 4 x 0.01
B traced render exists, portrait, source length ±0.5 s 4 x 0.04
C tracer vs reference (per clip 0.11):
timestamp interval: annotated onset ±3 frames, sustained
visibility and no early line; replaces clean+onset of the
reference's first line frame 0.02
tracking: on ≥ 70 % of the flight frames the agent's tip is
within 100 px of the reference tip (frame by frame) 0.05
footprint: at the end of the shot ≥ 80 % of the agent's line
lies within 40 px of the reference line AND vice versa 0.03
clean: nothing drawn 0.5 s / 0.2 s before impact 0.01
D SVG export: parses to ≥ 1 path (0.01); its polyline lies within
60 px of the reference path both ways for ≥ 80 % of points (0.02) 4 x 0.03
Shotcut assembly ................................................. 0.12
E project.mlt references the 4 traced renders (4 x 0.01); exactly 4
clips (0.02); each clip frame-matches the final in order (4 x 0.015)
Final export ..................................................... 0.12
F 1080x1920 / 30 fps / H.264 (0.04); duration = sum ± 1 s (0.02);
tracer visible in the final on each shot (4 x 0.015)
GUI-only gate: any logged terminal attempt → reward 0.
Tracer pixels = max RGB channel delta > 80 between the render and the source
frame AND its two neighbours (footage motion matches one of them, a tracer
matches none). The per-frame masks for a whole clip come from ONE ffmpeg
filter graph (difference vs S[f-1], S[f], S[f+1] → per-channel max → min over
the three → threshold) so frame-by-frame tracking costs seconds, not minutes.
Ceilings: do-nothing 0.00; the oracle (reference renders + SVGs + the
reference .friction baked at /opt/t16-reference) = 1.00.
"""
from tracer_intervals import score_intervals
import glob
import json
import math
import os
import re
import subprocess
from _vedit_verifier import (Rubric, duration, extract_project_edl,
gray_thumb, mad, probe, video_size, write_reward)
HERE = os.path.dirname(os.path.abspath(__file__))
MEDIA = os.environ.get("T16_MEDIA", "/root/media")
HOME = os.environ.get("T16_HOME", "/root")
FINAL = os.environ.get("T16_FINAL", os.path.join(HOME, "Desktop/final.mp4"))
TRACED = os.environ.get("T16_TRACED", os.path.join(HOME, "edit/traced"))
SVGDIR = os.environ.get("T16_SVG", os.path.join(HOME, "edit/svg"))
REWARD_PATH = os.environ.get("T16_REWARD", "/logs/verifier/reward.txt")
TERMINAL_LOG = os.environ.get("T16_TERMINAL_LOG", "/logs/artifacts/terminal-attempts.log")
WORK = "/tmp/t16-grade"
SHOTS = json.load(open(os.path.join(HERE, "shots.json")))["shots"]
REF = json.load(open(os.path.join(HERE, "reference/tracer-reference.json")))
NAMES = [s["id"] + ".mp4" for s in SHOTS]
FRAME_W, FRAME_H = 1080, 1920
# --- matching -------------------------------------------------------------
MW, MH = 54, 96
MATCH_MAD = 22.0
TRACED_ALIGN = 0.5
FINAL_ALIGN = 1.0
DUR_TOL = 0.5
FINAL_DUR_TOL = 1.0
# --- tracer detection / reference tolerances ------------------------------
TW, TH = REF["thumb"]
SCALE = FRAME_W / TW
DIFF_THR = 80
MIN_TRACER_PX = 100
MAX_TRACER_FRAC = 0.12
CLEAN_MAX_PX = 120
ONSET_TOL_FRAMES = 3
TIP_TOL_PX = 100
TIP_FRAC = 0.70
FOOT_TOL_PX = 40
FOOT_FRAC = 0.80
SVG_TOL_PX = 60
SVG_FRAC = 0.80
END_MARGIN = 0.15
MAX_PTS = 700 # subsample for the chamfer checks
# ------------------------------------------------------------------ helpers
def rgb_thumb(path, t):
try:
raw = subprocess.run(
["ffmpeg", "-nostdin", "-v", "error", "-ss", "%.3f" % max(0.0, t), "-i", path,
"-frames:v", "1", "-vf", "scale=%d:%d" % (TW, TH), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
capture_output=True, check=True).stdout
return raw[:TW * TH * 3] if len(raw) >= TW * TH * 3 else None
except Exception:
return None
def source_neighbourhood(src, t):
thumbs = [rgb_thumb(src, t + k / 30.0) for k in (-1, 0, 1)]
thumbs = [x for x in thumbs if x]
return thumbs if len(thumbs) == 3 else None
def changed_px(a, srcs):
n = 0
for i in range(0, len(a), 3):
r, g, b = a[i], a[i + 1], a[i + 2]
if all(abs(r - s[i]) > DIFF_THR or abs(g - s[i + 1]) > DIFF_THR
or abs(b - s[i + 2]) > DIFF_THR for s in srcs):
n += 1
return n
def align(vid, ref, t_ref, t_vid_guess, rng):
b = gray_thumb(ref, t_ref, MW, MH)
if not b:
return 255.0, 0.0
cache = {}
def probe_d(d):
key = round(d, 3)
if key not in cache:
t = t_vid_guess + d
a = gray_thumb(vid, t, MW, MH) if t >= 0 else None
cache[key] = mad(a, b, MW, MH) if a else 255.0
return cache[key]
coarse = [k / 10.0 for k in range(-int(rng * 10), int(rng * 10) + 1)]
d0 = min(coarse, key=probe_d)
fine = [d0 + k / 30.0 for k in range(-3, 4)]
best = min(fine, key=probe_d)
return probe_d(best), best
def tracer_masks(traced, src, shift_frames):
"""Per-frame drawn masks (bytes, TW*TH, 255 = drawn) for the whole clip
from one ffmpeg graph: |T-S[f-1]|, |T-S[f]|, |T-S[f+1]| per channel → max
over channels → min over the three → > DIFF_THR. shift_frames > 0 means
the render runs LATE by that many frames (trimmed off its start)."""
tsrc = "[0:v]scale=%d:%d,format=rgb24" % (TW, TH)
if shift_frames > 0:
tsrc += ",trim=start_frame=%d,setpts=PTS-STARTPTS" % shift_frames
elif shift_frames < 0:
tsrc += ",tpad=start=%d:start_mode=clone" % (-shift_frames)
g = [tsrc + "[t]",
"[1:v]scale=%d:%d,format=rgb24,split=3[s0][s1][s2]" % (TW, TH),
"[s1]tpad=start=1:start_mode=clone[sm]", # S[f-1]
"[s2]trim=start_frame=1,setpts=PTS-STARTPTS[sp]", # S[f+1]
"[t]split=3[t0][t1][t2]"]
outs = []
for k, s in enumerate(("s0", "sm", "sp")):
g += ["[t%d][%s]blend=all_mode=difference,format=rgb24,extractplanes=r+g+b[r%d][g%d][b%d]" % (k, s, k, k, k),
"[r%d][g%d]blend=all_mode=lighten[rg%d]" % (k, k, k),
"[rg%d][b%d]blend=all_mode=lighten[d%d]" % (k, k, k)]
outs.append("[d%d]" % k)
g += ["[d0][d1]blend=all_mode=darken[d01]", "[d01][d2]blend=all_mode=darken[dm]",
"[dm]format=gray,geq=lum='if(gt(lum(X,Y),%d),255,0)'[out]" % DIFF_THR]
try:
raw = subprocess.run(
["ffmpeg", "-nostdin", "-v", "error", "-i", traced, "-i", src, "-filter_complex", ";".join(g),
"-map", "[out]", "-f", "rawvideo", "-pix_fmt", "gray", "-"],
capture_output=True, check=True, timeout=600).stdout
except Exception:
return []
n = len(raw) // (TW * TH)
return [raw[i * TW * TH:(i + 1) * TW * TH] for i in range(n)]
_RUN = re.compile(rb"\xff+")
def mask_points(mask, limit=None):
"""Thumb (x, y) of drawn pixels; count is exact, points may be subsampled."""
pts = []
for m in _RUN.finditer(mask):
for i in range(m.start(), m.end()):
pts.append((i % TW, i // TW))
if limit and len(pts) > limit:
step = len(pts) / float(limit)
pts = [pts[int(k * step)] for k in range(limit)]
return pts
def mask_count(mask):
return sum(m.end() - m.start() for m in _RUN.finditer(mask))
def tip_of(mask, bx, by):
best, bd = None, -1.0
for x, y in mask_points(mask):
d = (x * SCALE - bx) ** 2 + (y * SCALE - by) ** 2
if d > bd:
bd, best = d, (x * SCALE, y * SCALE)
return best
def coverage(pts_a, pts_b, tol):
"""Fraction of pts_a within tol of some point of pts_b (both in 1080 px)."""
if not pts_a or not pts_b:
return 0.0
tol2 = tol * tol; hit = 0
for ax, ay in pts_a:
for bx_, by_ in pts_b:
if (ax - bx_) ** 2 + (ay - by_) ** 2 <= tol2:
hit += 1; break
return hit / float(len(pts_a))
def sub(pts, limit=MAX_PTS):
if len(pts) <= limit:
return pts
step = len(pts) / float(limit)
return [pts[int(k * step)] for k in range(limit)]
def rle_points(runs):
pts = []
for start, length in runs:
for i in range(start, start + length):
pts.append(((i % TW) * SCALE, (i // TW) * SCALE))
return pts
def find_files(pattern, extra_dirs=()):
hits = glob.glob(os.path.join(HOME, "edit", pattern))
hits += glob.glob(os.path.join(HOME, "**", pattern), recursive=True)
for d in extra_dirs:
hits += glob.glob(os.path.join(d, pattern))
return sorted(set(hits), key=lambda p: os.path.getmtime(p), reverse=True)
def mentions(path, needle):
try:
data = open(path, "rb").read()
except OSError:
return False
return (needle.encode() in data or needle.encode("utf-16-le") in data
or needle.encode("utf-16-be") in data)
def best_mlt():
cands = find_files("*.mlt", extra_dirs=(os.path.join(HOME, ".local/share/Meltytech/Shotcut/autosave"),))
for p in cands:
if any(mentions(p, s["id"]) for s in SHOTS):
return p
return None
def fps_of(meta):
try:
for s in meta.get("streams", []):
if s.get("codec_type") == "video":
n, d = s.get("r_frame_rate", "0/1").split("/")
return float(n) / float(d)
except Exception:
pass
return None
def vcodec_of(meta):
for s in (meta or {}).get("streams", []):
if s.get("codec_type") == "video":
return s.get("codec_name")
return None
def svg_points(path):
try:
from svgpath import svg_polylines
polys = svg_polylines(open(path, errors="ignore").read())
except Exception:
return None
pts = [(x, y) for poly in polys for x, y in poly]
return pts or None
# ------------------------------------------------------------------- rubric
def test_rubric():
os.makedirs(WORK, exist_ok=True)
r = Rubric("t16-shottracer-effects", reward_path=REWARD_PATH)
samples = {}
# -- A. Friction project mentions each clip -----------------------------
frictions = [p for p in find_files("*.friction") if os.path.getsize(p) >= 1024]
for s in SHOTS:
hit = next((p for p in frictions if mentions(p, s["id"])), None)
r.check(0.01, "A %s: a Friction project mentions it (%s)" % (s["id"], hit), bool(hit))
traced_ok = {}
for s in SHOTS:
sid, impact, (bx, by) = s["id"], s["impact_t"], s["ball_xy"]
ref = REF["shots"][sid]
src = os.path.join(MEDIA, sid + ".mp4")
trc = os.path.join(TRACED, sid + ".mp4")
src_dur = duration(probe(src)) if os.path.isfile(src) else s["duration"]
meta = probe(trc)
dur = duration(meta) if meta else None
size = video_size(meta) if meta else None
portrait = bool(size) and size[0] and size[1] and size[1] > size[0]
exported = bool(dur) and portrait and abs(dur - src_dur) <= DUR_TOL
r.check(0.04, "B %s: traced render exists, portrait, %.2fs vs source %.2fs"
% (sid, dur or -1, src_dur), exported)
traced_ok[sid] = exported
m, d = 255.0, 0.0
if exported and os.path.isfile(src):
t_ref = max(0.2, impact - 0.6)
m, d = align(trc, src, t_ref, t_ref, TRACED_ALIGN)
footage = exported and m <= MATCH_MAD
shift = int(round(d * 30)) if footage else 0
masks = tracer_masks(trc, src, shift) if footage else []
info = {"align_mad": round(m, 1), "offset_frames": shift, "footage": footage, "n_masks": len(masks)}
imp_f = ref["impact_frame"]
n = min(len(masks), ref["n_frames"])
def cnt(f):
return mask_count(masks[f]) if 0 <= f < len(masks) else None
annotation = s['tracer_intervals']
imp_f = annotation['intervals'][0]['start_frame']
ref_first = imp_f
expected_count = ref['n_frames']
timing_rows = [{'source_reference_frame': f,
'actual_pixels': cnt(f) or 0,
'missing_candidate_frame': f >= len(masks)}
for f in range(expected_count)]
timing = score_intervals(timing_rows, annotation, expected_count - 1,
min_pixels=MIN_TRACER_PX - 1)
# Fractional credit with the existing 0.03 clean/onset allocation.
r.check(0.03, 'C %s: annotated timestamp interval %.4f' %
(sid, timing['score']), False)
r.earned += 0.03 * timing['score']
pre = []
first = next((f for f in range(n) if cnt(f) >= MIN_TRACER_PX), None)
info['timestamp_interval'] = timing
# tracking: tip vs reference tip, frame by frame over the flight
good = total = 0
dists = []
if masks and ref_first is not None:
for row in ref["frames"]:
f = row["f"]
if f < ref_first or "tip" not in row:
continue
total += 1
tip = tip_of(masks[f], bx, by) if cnt(f) is not None and cnt(f) >= 20 else None
if tip is None:
dists.append(None); continue
dist = math.hypot(tip[0] - row["tip"][0], tip[1] - row["tip"][1])
dists.append(round(dist))
if dist <= TIP_TOL_PX:
good += 1
frac = good / float(total) if total else 0.0
r.check(0.05, "C %s: tip within %d px of the reference tip on %.0f%% of %d flight frames (need %.0f%%)"
% (sid, TIP_TOL_PX, frac * 100, total, TIP_FRAC * 100), total > 0 and frac >= TIP_FRAC)
# footprint at the end of the shot (chamfer both ways)
end_f = min(n - 1, int(round((src_dur - END_MARGIN) * 30))) if n else -1
cov_a = cov_b = 0.0
end_px = cnt(end_f) if end_f >= 0 else None
if end_f >= 0 and end_px and MIN_TRACER_PX <= end_px <= MAX_TRACER_FRAC * TW * TH:
agent_pts = [(x * SCALE, y * SCALE) for x, y in mask_points(masks[end_f], MAX_PTS)]
ref_pts = sub(rle_points(ref["final_mask_rle"]))
cov_a = coverage(agent_pts, ref_pts, FOOT_TOL_PX)
cov_b = coverage(ref_pts, agent_pts, FOOT_TOL_PX)
foot_ok = cov_a >= FOOT_FRAC and cov_b >= FOOT_FRAC
r.check(0.03, "C %s: end-of-shot line matches the reference footprint (%d px; %.0f%% of agent within %d px "
"of reference, %.0f%% of reference covered)" % (sid, end_px or 0, cov_a * 100, FOOT_TOL_PX, cov_b * 100),
foot_ok)
# D. SVG export
svgp = os.path.join(SVGDIR, sid + ".svg")
pts = svg_points(svgp) if os.path.isfile(svgp) else None
r.check(0.01, "D %s: SVG export parses to a path (%s, %s points)" % (sid, svgp, len(pts) if pts else 0), bool(pts))
s_a = s_b = 0.0
if pts and ref.get("svg_polyline"):
a, b = sub(pts), sub([tuple(p) for p in ref["svg_polyline"]])
s_a, s_b = coverage(a, b, SVG_TOL_PX), coverage(b, a, SVG_TOL_PX)
r.check(0.02, "D %s: SVG path within %d px of the reference path (%.0f%% / %.0f%%)"
% (sid, SVG_TOL_PX, s_a * 100, s_b * 100), s_a >= SVG_FRAC and s_b >= SVG_FRAC)
info.update(pre_counts=pre, first_line_frame=first, ref_first=ref_first, tip_frames=total,
tip_good=good, tip_dists=dists, end_px=end_px, foot_cov=[round(cov_a, 2), round(cov_b, 2)],
svg_cov=[round(s_a, 2), round(s_b, 2)])
samples[sid] = info
# -- E. Shotcut ----------------------------------------------------------
project = best_mlt()
text = ""
if project:
try:
text = open(project, errors="ignore").read()
except OSError:
text = ""
for s in SHOTS:
ref_ok = ("traced/%s.mp4" % s["id"]) in text
r.check(0.01, "E Shotcut project references the traced render of %s" % s["id"], ref_ok)
xml_ok, referenced, seq = (extract_project_edl(project, set(NAMES)) if project else (False, set(), []))
r.check(0.02, "E Shotcut project has exactly %d clips (found %d in %s)" % (len(SHOTS), len(seq), project),
xml_ok and len(seq) == len(SHOTS))
# -- F. final --------------------------------------------------------------
fmeta = probe(FINAL)
fdur = duration(fmeta) if fmeta else None
fsize = video_size(fmeta) if fmeta else None
ffps = fps_of(fmeta) if fmeta else None
fcodec = vcodec_of(fmeta)
fmt_ok = (bool(fdur) and fsize == (FRAME_W, FRAME_H) and ffps is not None
and abs(ffps - 30.0) <= 0.1 and fcodec == "h264")
r.check(0.04, "F final.mp4 exists, %s, %s fps, %s" % (fsize, ffps, fcodec), fmt_ok)
total_dur = sum(duration(probe(os.path.join(MEDIA, n_))) or s["duration"] for n_, s in zip(NAMES, SHOTS))
r.check(0.02, "F final duration %.2fs = the four clips %.2fs ± %.1fs" % (fdur or -1, total_dur, FINAL_DUR_TOL),
bool(fdur) and abs(fdur - total_dur) <= FINAL_DUR_TOL)
pos = 0.0
fsamples = {}
for s in SHOTS:
sid, impact = s["id"], s["impact_t"]
src = os.path.join(MEDIA, sid + ".mp4")
trc = os.path.join(TRACED, sid + ".mp4")
src_dur = duration(probe(src)) if os.path.isfile(src) else s["duration"]
ref_vid = trc if traced_ok.get(sid) else src
m, d = 255.0, 0.0
if fdur and os.path.isfile(ref_vid):
t_ref = max(0.2, impact - 0.6)
m, d = align(FINAL, ref_vid, t_ref, pos + t_ref, FINAL_ALIGN)
seg_ok = fdur is not None and m <= MATCH_MAD
r.check(0.015, "E final: %s in position %d (expected @ %.2fs; mad %.1f, offset %+.2fs)"
% (sid, SHOTS.index(s) + 1, pos, m, d), seg_ok)
n_end = None
if seg_ok and os.path.isfile(src):
t_end = src_dur - END_MARGIN
a = rgb_thumb(FINAL, pos + t_end + d)
srcs = source_neighbourhood(src, t_end)
n_end = changed_px(a, srcs) if a and srcs else None
r.check(0.015, "F final: tracer visible on %s (%s changed px at the end of the shot)" % (sid, n_end),
n_end is not None and MIN_TRACER_PX <= n_end <= MAX_TRACER_FRAC * TW * TH)
fsamples[sid] = {"expected_in": round(pos, 3), "mad": round(m, 1), "offset": round(d, 3), "end_px": n_end}
pos += src_dur
with open(os.path.join(WORK, "tracer-samples.json"), "w") as f:
json.dump({"traced": samples, "final": fsamples}, f, indent=2)
os.makedirs(os.path.dirname(REWARD_PATH), exist_ok=True)
with open(os.path.join(os.path.dirname(REWARD_PATH), 'timestamp-intervals.json'), 'w') as f:
json.dump({'grading_revision': 'source-frame-intervals-v1',
'shots': {sid: info['timestamp_interval'] for sid, info in samples.items()}}, f, indent=2)
score = r.report()
# GUI-only gate (Sid, 2026-09-04): the image has no terminal; every attempt
# to open one is logged by the stub. Any attempt → 0 regardless of artifacts.
if os.path.isfile(TERMINAL_LOG) and os.path.getsize(TERMINAL_LOG) > 0:
with open(TERMINAL_LOG, errors="ignore") as f:
lines = f.read().strip().splitlines()
print(" GUI-ONLY GATE: %d terminal attempt(s) logged -> reward 0 (first: %s)" % (len(lines), lines[0][:120]))
write_reward(0.0, REWARD_PATH)
score = 0.0
assert score == 1.0, "scored %.4f -- see rubric above" % score