File size: 18,714 Bytes
1cb0c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
"""t19 rubric v0.2 — two-part Friction tutorial (Part One drop, then
Part Two composition on top of it).

v0.2 (2026-09-21): Part One's "Friction project saved" checkpoint is now
REPORTED BUT UNSCORED (weight 0.00) and its 0.10 moved into the two motion
checks -- "falls straight down" 0.15 -> 0.20, "eases in" 0.10 -> 0.15 -- the
same change t18 made the same day (t18-render-v1). Reason: Friction's project
format is binary and it has no headless mode, so it was the one checkpoint the
ffmpeg oracle could never earn, capping the oracle at 0.96 (1 - 0.10 * 0.40).
The check still runs and prints, test.sh still harvests every *.friction, and
task.toml artifacts still pull /root/edit back for human review. Cost, stated
plainly: nothing in Part One's reward now requires the agent to have used
Friction. The proper fix is still a GUI-saved environment/reference/oracle.friction.

Part One (P1_SHARE of the reward) = t18's render rubric applied to
/root/Desktop/scene1.mp4 unchanged: blue drop, taller than wide, straight
eased fall from above the canvas to below it in frames 0-30, solid
background, project saved. Calibrated in t18 (oracle 0.90 of its share,
live runs 1.00 / 0.90).

Part Two (P2_SHARE) v0: proxies on final.mp4 for the composite the tutorial
builds with Sid's asset mapping (particles.mp4 = background, flames.mp4 =
imported-but-unused decoy, drops = Part One's scene linked in). See
part_two()'s docstring. Calibrated only against an ffmpeg approximation
(solution/solve.sh) — recalibrate against the first real Friction renders.
"""
import glob
import json
import os
import subprocess

from _vedit_verifier import Rubric, duration, probe, video_size

# T19_* env overrides exist ONLY for local rubric calibration; in the
# container the defaults are the real paths.
HOME = os.environ.get("T19_HOME", "/root")
SCENE1 = os.environ.get("T19_SCENE1", os.path.join(HOME, "Desktop/scene1.mp4"))
FINAL = os.environ.get("T19_FINAL", os.path.join(HOME, "Desktop/final.mp4"))
MEDIA = os.environ.get("T19_MEDIA", "/root/media")
REWARD_PATH = os.environ.get("T19_REWARD", "/logs/verifier/reward.txt")
WORK = os.environ.get("T19_WORK", "/tmp/t19-grade")

# --- thresholds (rubric v0, calibrated on the ffmpeg oracle 2026-09-03) ------
WANT_SIZE = (1920, 1080)
FPS = 30
N_FRAMES = 60
DUR_TOL = 0.5              # 60 vs 61 frames, container rounding
TW, TH = 192, 108          # 10x downscale; a 5 %-wide drop is still ~10 px
BLUE_MIN, BLUE_R_GAP, BLUE_G_GAP = 90, 40, 20
AREA_MIN, AREA_MAX = 0.002, 0.15
BG_FRAC = 0.98             # solid-background purity
DROP_ASPECT = 1.05         # bbox h/w on fully-visible frames
X_DRIFT = 0.05             # of the width, across the whole fall
EXIT_FRAME = 36            # frame 30 + slack for a slightly long fall
EASE_RATIO = 1.3           # last-third / first-third distance (ease-in)
VISIBLE_MIN_PX = 12        # below this a frame counts as "no drop"


# ------------------------------------------------------------------ helpers

def decode_thumbs(path, w, h):
    """All frames as rgb24 thumbs (list of bytes), or []."""
    try:
        out = subprocess.run(
            ["ffmpeg", "-v", "error", "-i", path, "-vf", "scale=%d:%d" % (w, h),
             "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
            capture_output=True, check=True).stdout
    except Exception:
        return []
    n = w * h * 3
    return [out[i:i + n] for i in range(0, len(out) - n + 1, n)]


def analyse(frame, w, h):
    """Blue-pixel statistics of one thumb."""
    xs = ys = cnt = 0
    r_sum = g_sum = b_sum = 0
    minx, maxx, miny, maxy = w, -1, h, -1
    for i in range(0, len(frame), 3):
        r, g, b = frame[i], frame[i + 1], frame[i + 2]
        if b > BLUE_MIN and b - r > BLUE_R_GAP and b - g > BLUE_G_GAP:
            p = i // 3
            x, y = p % w, p // w
            cnt += 1
            xs += x
            ys += y
            r_sum += r
            g_sum += g
            b_sum += b
            minx, maxx = min(minx, x), max(maxx, x)
            miny, maxy = min(miny, y), max(maxy, y)
    if cnt < VISIBLE_MIN_PX:
        return {"visible": False, "count": cnt}
    return {"visible": True, "count": cnt, "area": cnt / (w * h),
            "cx": xs / cnt, "cy": ys / cnt,
            "bbox": (minx, miny, maxx, maxy),
            "mean": (r_sum / cnt, g_sum / cnt, b_sum / cnt),
            "touch_top": miny == 0, "touch_bottom": maxy == h - 1}


def background_purity(frame):
    """Fraction of pixels equal (±6 per channel) to the modal colour."""
    hist = {}
    px = [(frame[i] >> 3, frame[i + 1] >> 3, frame[i + 2] >> 3)
          for i in range(0, len(frame), 3)]
    for p in px:
        hist[p] = hist.get(p, 0) + 1
    mode = max(hist, key=hist.get)
    near = sum(v for k, v in hist.items()
               if all(abs(k[c] - mode[c]) <= 1 for c in range(3)))
    return near / len(px)


def find_projects(pattern):
    hits = glob.glob(os.path.join(HOME, "edit", pattern))
    hits += glob.glob(os.path.join(HOME, "**", pattern), recursive=True)
    return sorted(set(hits), key=lambda p: os.path.getmtime(p), reverse=True)


# ------------------------------------------------------------------- rubric

def part_one(r, W):
    """t18's checks on scene1.mp4, every weight scaled by W (Part One share)."""
    FINAL = SCENE1
    def chk(w, label, ok):
        r.check(round(w * W, 4), "P1 " + label, ok)

    meta = probe(FINAL)
    dur = duration(meta) if meta else None
    size = video_size(meta) if meta else None
    want_dur = N_FRAMES / FPS

    chk(0.05, "final.mp4 exists, readable, video stream (%s)" % (size,),
            bool(meta) and bool(dur) and bool(size) and all(size))
    chk(0.05, "final is %dx%d" % WANT_SIZE, bool(size) and tuple(size) == WANT_SIZE)
    # t19: the instruction fixes 1920x1080/30 fps but NOT Part One's length (the
    # tutorial's own scene is 250 frames and the drop falls in frames 0-30), so
    # any sane scene length passes; the timing check below still wants the
    # drop gone by frame 36. (opus a1 rendered 8.33 s and lost this 0.04.)
    chk(0.10, "scene1 duration %.2fs in %.1f-%.1f s" % (dur or -1, P1_DUR_MIN, P1_DUR_MAX),
        bool(dur) and P1_DUR_MIN <= dur <= P1_DUR_MAX)

    frictions = [p for p in find_projects("*.friction") if os.path.getsize(p) >= 1024]
    chk(0.00, "[unscored] Friction project saved (%s)" % (frictions[0] if frictions else "none"),
            bool(frictions))

    frames = decode_thumbs(FINAL, TW, TH) if meta else []
    stats = [analyse(f, TW, TH) for f in frames]
    vis = [i for i, s in enumerate(stats) if s["visible"]]
    n = len(frames)

    # background: the last frame (drop long gone) must be one flat colour
    purity = background_purity(frames[-1]) if frames else 0.0
    chk(0.05, "solid background (%.1f%% of the last frame is one colour)" % (100 * purity),
            bool(frames) and purity >= BG_FRAC and not stats[-1]["visible"])

    mid = [stats[i] for i in vis if AREA_MIN <= stats[i]["area"] <= AREA_MAX]
    chk(0.10, "blue blob present mid-fall (%d visible frames, %d within the area band)"
            % (len(vis), len(mid)), len(mid) >= 3)

    means = [stats[i]["mean"] for i in vis]
    blue = bool(means) and all(m[2] - m[0] >= 40 and m[2] - m[1] >= 20 for m in means)
    chk(0.10, "blob is blue (mean rgb %s)" % ((tuple(round(v) for v in means[0]) if means else None),),
            blue)

    full = [stats[i] for i in vis if not stats[i]["touch_top"] and not stats[i]["touch_bottom"]]
    aspects = [(b[3] - b[1] + 1) / max(1, b[2] - b[0] + 1) for b in (s["bbox"] for s in full)]
    chk(0.10, "drop shape: bbox taller than wide on %d fully-visible frames (h/w %s)"
            % (len(full), [round(a, 2) for a in aspects[:4]]),
            bool(aspects) and min(aspects) >= DROP_ASPECT)

    cys = [stats[i]["cy"] for i in vis]
    cxs = [stats[i]["cx"] for i in vis]
    descends = len(cys) >= 3 and all(b >= a - 0.5 for a, b in zip(cys, cys[1:])) and cys[-1] > cys[0] + TH * 0.3
    straight = bool(cxs) and (max(cxs) - min(cxs)) <= X_DRIFT * TW
    chk(0.20, "falls straight down (centroid y %s..%s, x drift %.1f px)"
            % (round(cys[0]) if cys else None, round(cys[-1]) if cys else None,
               (max(cxs) - min(cxs)) if cxs else -1), descends and straight)

    first_touch = next((i for i in vis if stats[i]["touch_top"]), None)
    last_touch = next((i for i in reversed(vis) if stats[i]["touch_bottom"]), None)
    timing = (n > 0 and not stats[0]["visible"] and bool(vis)
              and first_touch is not None and first_touch == vis[0]
              and last_touch is not None and last_touch == vis[-1]
              and vis[-1] < EXIT_FRAME)
    chk(0.10, "timing: invisible at frame 0, enters from the top (frame %s), leaves at the "
            "bottom (frame %s), gone before frame %d" % (vis[0] if vis else None,
                                                        vis[-1] if vis else None, EXIT_FRAME),
            timing)

    ease = None
    if len(cys) >= 6:
        k = len(cys) // 3
        first = cys[k - 1] - cys[0]
        last = cys[-1] - cys[-k]
        ease = last / first if first > 0 else float("inf")
    chk(0.15, "eases in: last-third distance / first-third = %s (need ≥ %.1f)"
            % (round(ease, 2) if ease is not None else None, EASE_RATIO),
            ease is not None and ease >= EASE_RATIO)

    with open(os.path.join(WORK, "samples.json"), "w") as f:
        json.dump({"frames": n, "visible": vis, "purity": purity, "ease": ease,
                   "track": [{"frame": i, "cx": stats[i]["cx"], "cy": stats[i]["cy"],
                              "area": stats[i]["area"], "bbox": stats[i]["bbox"]} for i in vis]},
                  f, indent=1)



def warm_frac(frame):
    """Fraction of fire-hued pixels (r > g >= b, red at least 10 over blue),
    brightness-independent: the flames clip measures 0.51-0.90, a composite
    with it dimmed as the background 0.14-0.25 (opus a1), the particles clip
    and the oracle 0.000 (2026-09-03)."""
    n = len(frame) // 3
    return sum(1 for i in range(0, len(frame), 3)
               if frame[i] >= 15 and frame[i] > frame[i + 1] >= frame[i + 2]
               and frame[i] - frame[i + 2] >= 10) / n


def teal_frac(frame):
    """Fraction of dark-teal pixels (the particles clip's signature: g and b
    at least 8 over r, not bright): particles clip / oracle 0.64-0.68 peak,
    opus a1 with particles only inside the text 0.20 peak."""
    n = len(frame) // 3
    return sum(1 for i in range(0, len(frame), 3)
               if frame[i + 2] >= frame[i] + 8 and frame[i + 1] >= frame[i] + 8
               and frame[i] + frame[i + 1] + frame[i + 2] < 270) / n


def drop_components(frame, w, h):
    """Connected components of true-blue pixels that are drop-sized (4 px to
    2 % of the thumb) and not wider than tall — the blue SPLASH text forms
    much larger components and is excluded, which is why the drop checks
    cannot be satisfied by blue text alone (opus a1 was). Returns a list of
    (cx, cy, area)."""
    blue = bytearray(w * h)
    for i in range(0, len(frame), 3):
        r, g, b = frame[i], frame[i + 1], frame[i + 2]
        if b > BLUE_MIN and b - r > BLUE_R_GAP and b - g > BLUE_G_GAP:
            blue[i // 3] = 1
    seen = bytearray(w * h)
    comps = []
    cap = 0.02 * w * h
    for start in range(w * h):
        if not blue[start] or seen[start]:
            continue
        stack = [start]; seen[start] = 1
        px = []
        while stack:
            p = stack.pop(); px.append(p)
            x, y = p % w, p // w
            for q in ((p - 1) if x > 0 else -1, (p + 1) if x < w - 1 else -1,
                      (p - w) if y > 0 else -1, (p + w) if y < h - 1 else -1):
                if q >= 0 and blue[q] and not seen[q]:
                    seen[q] = 1; stack.append(q)
        a = len(px)
        if 4 <= a <= cap:
            xs = [q % w for q in px]; ys = [q // w for q in px]
            bw, bh = max(xs) - min(xs) + 1, max(ys) - min(ys) + 1
            if bh >= 0.9 * bw:
                comps.append((sum(xs) / a, sum(ys) / a, a))
    return comps


def median_rgb(frame):
    ch = [sorted(frame[c::3]) for c in range(3)]
    return tuple(c[len(c) // 2] for c in ch)


def ocr_text(path, t, thr, width, psm):
    """Tesseract on a binarised, downscaled frame. Video-filled letters (the
    DstIn clip) defeat OCR on the raw frame; thresholding the luma turns them
    into solid glyphs, the median filter eats the particle speckle, and 640 px
    wide keeps 300-px-tall letters inside tesseract's comfort zone (calibrated
    on the ffmpeg oracle 2026-09-03: only thr .35 / 640 / psm 6 read SPLASH)."""
    import tempfile
    try:
        with tempfile.TemporaryDirectory() as td:
            png = os.path.join(td, "f.png")
            subprocess.run(["ffmpeg", "-v", "error", "-ss", "%.3f" % t, "-i", path, "-frames:v", "1",
                            "-vf", "format=gray,scale=%d:-1,median=radius=2,"
                                   "geq=lum='if(gt(lum(X,Y),255*%.2f),0,255)'" % (width, thr), png],
                           capture_output=True, check=True)
            out = subprocess.run(["tesseract", png, "stdout", "--psm", str(psm)],
                                 capture_output=True, check=True).stdout
            return out.decode("utf-8", errors="replace").upper()
    except Exception:
        return ""


def ocr_has_splash(path, times):
    """Best fuzzy match of any OCR'd word against SPLASH over a small grid of
    frames x binarisation settings (each tesseract call ~0.3 s)."""
    import difflib
    best = 0.0
    for t in times:
        for thr in (0.15, 0.22, 0.30, 0.35, 0.45):   # 0.15/0.22 added for dim fire-filled letters on black (fable c-a1 read 0.00 at >= 0.30)
            for width in (640, 960):
                for psm in (6, 11):
                    txt = ocr_text(path, t, thr, width, psm)
                    for w in txt.split():
                        w2 = "".join(ch for ch in w if ch.isalpha())
                        if len(w2) >= 4:
                            best = max(best, difflib.SequenceMatcher(None, w2, "SPLASH").ratio())
                    if best >= 0.99:
                        return best
    return best


def part_two(r, W):
    """Part Two composite (final.mp4), v0 proxies — designed 2026-09-03 against
    the shipped assets, calibrated on an ffmpeg approximation only (no real
    Friction render yet). The tutorial's composite = particle background,
    "SPLASH" text with video clipped inside (DstIn), the Part One drop scene
    LINKED in and looped, several offset drop copies; the fire clip is imported
    but never used.
      0.10 exists + 1920x1080
      0.10 duration 2.5-60 s (the scene length is the agent's; background is 8 s)
      0.10 motion (frames change over time)
      0.15 background clip used: teal (particles) pixels >= TEAL_MIN of the frame on >= 60 % of frames
      0.15 "SPLASH" text legible by OCR on at least one sampled frame (fuzzy >= 0.6)
      0.15 blue drops present: drop-sized true-blue connected components (not the text) on >= 3 frames
      0.15 drops keep coming: seen over >= 50 % of the video at heights spanning >= 40 % of the frame
      0.10 decoy unused: fire-hue pixels < WARM_MAX on every sampled frame
    v0.1 (after opus a1, 0.78): hue fractions replaced the median/brightness
    tests (a dimmed fire background scored 0.000 on the old warm test), and
    connected components replaced whole-frame blue centroids (blue SPLASH text
    satisfied both drop checks by itself)."""
    def chk(w, label, ok):
        r.check(round(w * W, 4), "P2 " + label, ok)
    meta = probe(FINAL)
    dur = duration(meta) if meta else None
    size = video_size(meta) if meta else None
    chk(0.10, "final.mp4 exists, 1920x1080 (%s)" % (size,),
        bool(meta) and bool(size) and tuple(size) == WANT_SIZE)
    chk(0.10, "final duration %.2fs in 2.5-60 s" % (dur or -1), bool(dur) and 2.5 <= dur <= 60)
    frames = decode_thumbs(FINAL, TW, TH) if meta and dur and dur <= 60 else []
    n = len(frames)
    step = max(1, n // 24)
    idx = list(range(0, n, step))
    samp = [frames[i] for i in idx]
    moving = sum(1 for a, b in zip(samp, samp[1:])
                 if sum(abs(x - y) for x, y in zip(a[::3], b[::3])) / (TW * TH) > 1.0)
    chk(0.10, "motion on %d/%d sample pairs" % (moving, max(0, len(samp) - 1)),
        len(samp) > 2 and moving >= 0.6 * (len(samp) - 1))
    teal = [teal_frac(f) for f in samp]
    teal_ok = sum(1 for t in teal if t >= TEAL_MIN)
    chk(0.15, "background clip used: teal (particles) fraction >= %.2f on %d/%d frames (max %.2f)"
        % (TEAL_MIN, teal_ok, len(teal), max(teal) if teal else 0),
        bool(teal) and teal_ok >= 0.6 * len(teal))
    ocr_times = [dur * f for f in (0.15, 0.4, 0.65, 0.9)] if dur and n else []
    score = ocr_has_splash(FINAL, ocr_times) if ocr_times else 0.0
    chk(0.15, "SPLASH text legible (best OCR match %.2f)" % score, score >= 0.6)
    comps = [drop_components(f, TW, TH) for f in samp]
    with_drop = [i for i, c in enumerate(comps) if c]
    chk(0.15, "blue drops present (drop-sized blue components) on %d/%d frames"
        % (len(with_drop), len(comps)), len(with_drop) >= 3)
    ys = [c[1] for cs in comps for c in cs]
    span_t = (with_drop[-1] - with_drop[0]) / max(1, len(comps) - 1) if with_drop else 0
    span_y = (max(ys) - min(ys)) / TH if ys else 0
    chk(0.15, "drops keep coming: seen over %.0f%% of the video at heights spanning %.0f%% of the frame"
        % (100 * span_t, 100 * span_y), span_t >= 0.5 and span_y >= 0.4)
    warm = [warm_frac(f) for f in samp]
    chk(0.10, "decoy (fire clip) unused: max fire-hue fraction %.3f (limit %.2f)" % (max(warm) if warm else 1.0, WARM_MAX),
        bool(warm) and max(warm) < WARM_MAX)
    with open(os.path.join(WORK, "part2-samples.json"), "w") as f:
        json.dump({"idx": idx, "teal": teal, "warm": warm, "ocr": score,
                   "drops": [[list(c) for c in cs] for cs in comps]}, f, indent=1)


P1_SHARE, P2_SHARE = 0.40, 0.60
P1_DUR_MIN, P1_DUR_MAX = 1.5, 12.0
TEAL_MIN = 0.20            # per-frame teal fraction that says 'the particles clip fills the background'
WARM_MAX = 0.03            # fire-hue fraction above this = the flames clip is in the composite


def test_rubric():
    os.makedirs(WORK, exist_ok=True)
    r = Rubric("t19-friction-tutorial-part2", reward_path=REWARD_PATH)
    part_one(r, P1_SHARE)
    part_two(r, P2_SHARE)
    score = r.report()
    assert score == 1.0, "scored %.4f -- see rubric above" % score


if __name__ == "__main__":
    try:
        test_rubric()
    except AssertionError as e:
        print(e)