File size: 12,624 Bytes
d7786d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# GENERATED by suite refresh from packages/verifier/vedit_verifier.py
# — do not edit here; edit the source and re-run ./suite/suite.sh refresh
"""
Shared verifier library for the video-editing task suite.

Single source of truth for the grading primitives every task verifier uses.
Task verifiers own their rubric (weights, checkpoints, calibrated thresholds);
this module owns the mechanics. `suite refresh` copies this file into each
task's tests/ dir as `_vedit_verifier.py` (a generated file — edit it HERE,
never in a task dir), so the tests/ dir stays self-contained the way Harbor
expects.

Grading philosophy (see fcpx.md and the task READMEs):
  - FRACTIONAL, artifact-only (exported MP4 + saved project, never UI state).
  - reward.txt gets the weighted fraction; pytest pass/fail means "fully
    solved" and is only the trajectory-readable signal of which dimension
    fell short.

GRADER CHANGE 2026-08-21 (deliberate, affects score comparability):
extract_project_edl previously graded the single best MLT playlist, so a
same-track mix or a V1/V2-overlap dissolve split the clips across playlists
and dropped project_structure points (the t07 opus5 run lost 0.19 to this —
the on-screen timeline held both clips; the save was correct; the parser
was not). It now also considers per-tractor merges (Kdenlive models one
timeline track as TWO sub-playlists so same-track mixes can overlap) and a
merge of all non-audio playlists ordered by timeline position (for
cross-track dissolves). Scores from before this date under-grade multi-clip
projects that used a mix; do not compare across the boundary.
"""

import json
import os
import subprocess
import tempfile
import xml.etree.ElementTree as ET


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

class Section:
    """One named sub-verifier: its own checks, weights, and fraction."""

    def __init__(self, name):
        self.name = name
        self.earned = 0.0
        self.total = 0.0
        self.lines = []

    def check(self, weight, label, ok):
        self.total += weight
        try:
            ok = bool(ok)
        except Exception:
            ok = False
        if ok:
            self.earned += weight
        self.lines.append("  [%s] %.3f  %s" % ("x" if ok else " ", weight, label))
        return ok

    def fraction(self):
        return (self.earned / self.total) if self.total else 1.0


class Rubric(Section):
    """Single-section variant for simple tasks: report() writes reward.txt."""

    def __init__(self, name, reward_path="/logs/verifier/reward.txt"):
        super().__init__(name)
        self.reward_path = reward_path

    def report(self):
        score = self.fraction() if self.total else 0.0
        print("\n%s -- rubric" % self.name)
        print("\n".join(self.lines))
        print("  score: %.4f (%.2f / %.2f)" % (score, self.earned, self.total))
        write_reward(score, self.reward_path)
        return score


def write_reward(score, reward_path="/logs/verifier/reward.txt"):
    os.makedirs(os.path.dirname(reward_path), exist_ok=True)
    with open(reward_path, "w") as fh:
        fh.write("%.4f\n" % score)


def write_breakdown(breakdown, breakdown_path):
    os.makedirs(os.path.dirname(breakdown_path), exist_ok=True)
    with open(breakdown_path, "w") as fh:
        json.dump(breakdown, fh, indent=2)


# ----------------------------------------------------------------- ffprobe

def probe(path):
    """ffprobe the file; None if it does not exist or is unreadable."""
    if not os.path.isfile(path):
        return None
    try:
        out = subprocess.run(
            ["ffprobe", "-v", "error", "-print_format", "json",
             "-show_format", "-show_streams", path],
            capture_output=True, check=True).stdout
        return json.loads(out)
    except Exception:
        return None


def duration(meta):
    try:
        return float(meta["format"]["duration"])
    except Exception:
        return None


def has_audio(meta):
    return meta and any(s.get("codec_type") == "audio" for s in meta.get("streams", []))


def video_size(meta):
    if not meta:
        return None
    for s in meta.get("streams", []):
        if s.get("codec_type") == "video":
            return (s.get("width"), s.get("height"))
    return None


# ---------------------------------------------------------- frame sampling

def frame_rgb(path, t):
    """Mean (r, g, b) of the frame at time t; None if extraction fails.

    The synthetic seed footage is solid colors with burned-in slates, so
    "is this the right segment" is a mean-RGB classification — deterministic,
    no reference render needed."""
    try:
        out = subprocess.run(
            ["ffmpeg", "-v", "error", "-ss", str(t), "-i", path,
             "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
            capture_output=True, check=True).stdout
        n = len(out) // 3
        if n == 0:
            return None
        return (sum(out[0::3]) / n, sum(out[1::3]) / n, sum(out[2::3]) / n)
    except Exception:
        return None


def gray_thumb(path, t, w, h):
    """Grayscale w*h pixel bytes at time t; None on failure."""
    try:
        out = subprocess.run(
            ["ffmpeg", "-v", "error", "-ss", str(t), "-i", path,
             "-frames:v", "1", "-vf", "scale=%d:%d" % (w, h),
             "-f", "rawvideo", "-pix_fmt", "gray", "-"],
            capture_output=True, check=True).stdout
        if len(out) < w * h:
            return None
        return out[:w * h]
    except Exception:
        return None


def mad(a, b, w, h, rows=None, skip_rows=None):
    """Mean abs diff of two thumbs over `rows` (or all rows minus
    `skip_rows`). rows/skip_rows are (lo, hi) half-open row ranges."""
    total = n = 0
    for row in range(h):
        if skip_rows and skip_rows[0] <= row < skip_rows[1]:
            continue
        if rows and not (rows[0] <= row < rows[1]):
            continue
        base = row * w
        for i in range(base, base + w):
            total += abs(a[i] - b[i])
            n += 1
    return total / n if n else 255.0


def ocr_frame(path, t):
    """Uppercased tesseract OCR of the frame at t; '' on any failure."""
    try:
        with tempfile.TemporaryDirectory() as td:
            png = os.path.join(td, "frame.png")
            subprocess.run(
                ["ffmpeg", "-v", "error", "-ss", str(t), "-i", path,
                 "-frames:v", "1", png],
                capture_output=True, check=True)
            out = subprocess.run(
                ["tesseract", png, "stdout"],
                capture_output=True, check=True).stdout
            return out.decode("utf-8", errors="replace").upper()
    except Exception:
        return ""


# --------------------------------------------------- project (MLT XML) EDL

def project_references(path, needle):
    """Saved project parses as XML and references the source clip."""
    if not os.path.isfile(path):
        return False
    try:
        ET.parse(path)
    except Exception:
        return False
    with open(path, "r", errors="replace") as fh:
        return needle in fh.read()


def parse_clock(v, fps):
    """MLT in/out value -> seconds. Frames int, float seconds, or hh:mm:ss.ms."""
    if v is None:
        return None
    v = v.strip()
    try:
        return int(v) / fps
    except ValueError:
        pass
    if ":" in v:
        parts = v.split(":")
        try:
            sec = float(parts[-1])
            for i, p in enumerate(reversed(parts[:-1]), 1):
                sec += int(p) * (60 ** i)
            return sec
        except ValueError:
            return None
    try:
        return float(v)
    except ValueError:
        return None


def extract_project_edl(path, known_clips):
    """
    Parse a .kdenlive (MLT XML) file into candidate clip sequences.

    Returns (xml_ok, referenced_clips, best_seq) where best_seq is the
    per-playlist entry sequence [(clip, src_in, src_dur), ...] that
    references the most known clips (real projects duplicate entries across
    audio/video tracks; we grade the best-matching track).

    See the module docstring for the known V1/V2-dissolve limitation.
    """
    if not os.path.isfile(path):
        return False, set(), []
    try:
        root = ET.parse(path).getroot()
    except Exception:
        return False, set(), []

    prof = root.find("profile")
    fps = 30.0
    if prof is not None:
        try:
            fps = float(prof.get("frame_rate_num", 30)) / float(prof.get("frame_rate_den", 1))
        except Exception:
            pass

    resources = {}
    for tag in ("producer", "chain"):
        for p in root.iter(tag):
            res = None
            for prop in p.findall("property"):
                if prop.get("name") in ("resource", "kdenlive:originalurl"):
                    res = os.path.basename((prop.text or "").strip())
                    if res in known_clips:
                        break
            if res:
                resources[p.get("id")] = res

    referenced = set(r for r in resources.values() if r in known_clips)

    def playlist_entries(pl):
        """[(timeline_pos, clip, src_in, dur)] for one playlist, blanks walked."""
        pos = 0.0
        out = []
        for node in pl:
            if node.tag == "blank":
                pos += parse_clock(node.get("length"), fps) or 0.0
            elif node.tag == "entry":
                src_in = parse_clock(node.get("in"), fps) or 0.0
                src_out = parse_clock(node.get("out"), fps)
                dur = (src_out - src_in + 1.0 / fps) if src_out is not None else None
                clip = resources.get(node.get("producer"))
                if clip in known_clips:
                    out.append((pos, clip, src_in, dur))
                pos += dur or 0.0
        return out

    def is_audio(pl):
        return any(
            prop.get("name") == "kdenlive:audio_track"
            for prop in pl.findall("property")
        )

    playlists = {}
    for pl in root.iter("playlist"):
        if pl.get("id") == "main_bin":
            continue
        playlists[pl.get("id")] = pl

    # Candidate sequences, most-specific first:
    #  a) each playlist alone (flat saves, and the pre-2026-08-21 behaviour);
    #  b) each tractor's sub-playlists merged by timeline position — Kdenlive
    #     stores one timeline track as two playlists so same-track mixes can
    #     overlap, which is how a two-clip track reads as one clip per list;
    #  c) all non-audio playlists merged by timeline position, for dissolves
    #     that overlap clips across two video tracks.
    candidates = []
    for pl in playlists.values():
        candidates.append(sorted(playlist_entries(pl)))
    for tractor in root.iter("tractor"):
        merged = []
        for track in tractor.findall("track"):
            pl = playlists.get(track.get("producer"))
            if pl is not None and not is_audio(pl):
                merged.extend(playlist_entries(pl))
        if merged:
            candidates.append(sorted(merged))
    video_merge = []
    for pl in playlists.values():
        if not is_audio(pl):
            video_merge.extend(playlist_entries(pl))
    if video_merge:
        candidates.append(sorted(video_merge))

    # Best = covers the most DISTINCT known clips; ties broken by fewer
    # entries (less cross-track duplication), then by earlier candidate
    # (single playlists first, preserving legacy behaviour on flat saves).
    best = []
    best_score = None
    for seq in candidates:
        score = (len(set(c for _, c, _, _ in seq)), -len(seq))
        if best_score is None or score > best_score:
            best, best_score = seq, score
    return True, referenced, [(clip, src_in, dur) for _, clip, src_in, dur in best]


def project_has_transition(path):
    """A deliberate video dissolve in the project.

    luma/dissolve only: real Kdenlive saves ALWAYS contain internal "mix"
    (audio) and "composite"/"frei0r.cairoblend" (track compositing)
    transitions, so counting those passes a project with no dissolve at all.
    Kdenlive's same-track video mix and the oracle both use "luma"."""
    if not os.path.isfile(path):
        return False
    try:
        root = ET.parse(path).getroot()
    except Exception:
        return False
    services = set()
    for t in root.iter("transition"):
        for prop in t.findall("property"):
            if prop.get("name") == "mlt_service":
                services.add((prop.text or "").strip())
    return bool(services & {"luma", "dissolve"})