Download tasks/t07-remake-reference/tests/remake_verifier.py from refreshdotdev/Refresh-GUI-dataset: direct link, hf CLI and curl.
- Browser
- Download file 22.5 kB
-
https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/main/tasks/t07-remake-reference/tests/remake_verifier.py
- Command line
-
hf download hf://datasets/refreshdotdev/Refresh-GUI-dataset/tasks/t07-remake-reference/tests/remake_verifier.py
-
curl -L -o remake_verifier.py https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/main/tasks/t07-remake-reference/tests/remake_verifier.py
22.5 kB
| """Artifact-based 14-point remake verifier. All subprocesses are bounded. | |
| Shotcut MLT is the supported native project format. Dissolve and audio are | |
| measured from decoded output, independently of effect names or XML labels. | |
| Ground truth stays in /tests and must only be uploaded after agent execution. | |
| """ | |
| from functools import lru_cache | |
| import json | |
| import math | |
| import os | |
| from pathlib import Path | |
| import shutil | |
| import subprocess | |
| import xml.etree.ElementTree as ET | |
| import numpy as np | |
| POINTS = {"find_clips": 1, "import_clips": 1, "clip_order_and_trims": 3, | |
| "transition_timing": 3, "dissolve_behavior": 3, "original_audio": 1, | |
| "export_valid": 1, "export_path": 1} | |
| FPS = 10 | |
| WIDTH, HEIGHT = 96, 54 | |
| FRAME_MAD = 22.0 | |
| BLEND_MAD = 18.0 | |
| TIME_TOL = 0.5 | |
| DURATION_TOL = 0.5 | |
| class VerifierError(RuntimeError): | |
| """Infrastructure/answer failure, not a scored agent failure.""" | |
| def run(args, timeout=60): | |
| try: | |
| return subprocess.run(args, capture_output=True, timeout=timeout, check=True).stdout | |
| except subprocess.TimeoutExpired as exc: | |
| raise VerifierError(f"Grading subprocess timed out: {args[0]}") from exc | |
| def probe(path): | |
| if not Path(path).is_file(): | |
| return None | |
| try: | |
| return json.loads(run(["ffprobe", "-v", "error", "-show_streams", | |
| "-show_format", "-of", "json", str(path)], 20)) | |
| except (subprocess.CalledProcessError, ValueError): | |
| return None | |
| def frames(path): | |
| # Bound decode/memory for malformed or arbitrarily long submissions. | |
| data = run(["ffmpeg", "-v", "error", "-i", str(path), "-t", "60", | |
| "-map", "0:v:0", "-vf", f"fps={FPS},scale={WIDTH}:{HEIGHT}", | |
| "-an", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], 90) | |
| unit = WIDTH * HEIGHT * 3 | |
| if len(data) < unit or len(data) % unit: | |
| raise ValueError("Video has no complete decoded frames") | |
| return np.frombuffer(data, np.uint8).reshape(-1, HEIGHT, WIDTH, 3).astype(np.float32) | |
| def frame_at(video, t): | |
| i = int(round(t * FPS)) | |
| return video[i] if 0 <= i < len(video) else None | |
| def pixels(frame): | |
| # Mask only the central watermark band; retain RGB and both outer regions. | |
| return np.concatenate((frame[:20].ravel(), frame[34:].ravel())) | |
| def mad(a, b): | |
| return float(np.mean(np.abs(a - b))) | |
| def matching_samples(export_frames, reference_frames, edl): | |
| results = [] | |
| transition = edl["transitions"][0] | |
| for segment in edl["segments"]: | |
| start = segment["timeline_at"] + 0.7 | |
| end = segment["timeline_at"] + segment["duration"] - 0.7 | |
| candidates = [float(t) for t in np.linspace(start, end, 9) | |
| if not transition["timeline_at"]-0.5 <= t <= | |
| transition["timeline_at"]+transition["duration"]+0.5] | |
| def motion(t): | |
| a, b = frame_at(reference_frames, t-.1), frame_at(reference_frames, t+.1) | |
| return mad(pixels(a), pixels(b)) if a is not None and b is not None else 255 | |
| selected = sorted(candidates, key=motion)[:2] | |
| scores = [] | |
| for t in selected: | |
| actual = frame_at(export_frames, t) | |
| if actual is None: | |
| scores.append(255.) | |
| continue | |
| refs = [frame_at(reference_frames, t+d) for d in np.arange(-.5, .51, .1)] | |
| scores.append(min((mad(pixels(actual), pixels(r)) for r in refs | |
| if r is not None), default=255.)) | |
| results.append({"clip": segment["clip"], "times": selected, "mads": scores, | |
| "matches": len(scores) == 2 and max(scores) <= FRAME_MAD}) | |
| return results | |
| def clock(value, fps): | |
| if value is None: | |
| return 0. | |
| if ":" in value: | |
| parts = [float(x) for x in value.split(":")] | |
| return sum(v*60**i for i, v in enumerate(reversed(parts))) | |
| return float(value)/fps if value.lstrip("-").isdigit() else float(value) | |
| def properties(node): | |
| return {p.get("name"): p.text or "" for p in node.findall("property")} | |
| def read_project(path, media_dir): | |
| """Walk only the active root tractor, including nested Shotcut overlaps. | |
| Bin membership is separate from active usage. Preserve unknown/distractor | |
| resources; never pick whichever playlist best matches the answer. | |
| """ | |
| empty = {"valid": False, "imported": [], "clips": [], "transitions": [], | |
| "reference_used": False, "error": "No readable Shotcut project"} | |
| try: | |
| root = ET.parse(path).getroot() | |
| profile = root.find("profile") | |
| fps = float(profile.get("frame_rate_num"))/float(profile.get("frame_rate_den")) | |
| nodes = {n.get("id"): n for n in root if n.get("id")} | |
| tractors = root.findall("tractor") | |
| if root.tag != "mlt" or not tractors: | |
| return empty | |
| main = tractors[-1] | |
| clips, transitions = [], [] | |
| def source_name(resource): | |
| if resource.startswith("file://"): | |
| from urllib.parse import unquote, urlparse | |
| resource = unquote(urlparse(resource).path) | |
| # Verify content identity rather than trusting a source basename. | |
| candidate = Path(resource) | |
| if not candidate.is_absolute(): | |
| candidate = Path(path).parent / candidate | |
| expected = Path(media_dir) / candidate.name | |
| if not candidate.is_file() or not expected.is_file(): | |
| return "unknown:" + candidate.name | |
| import hashlib | |
| def digest(p): | |
| with p.open("rb") as f: | |
| return hashlib.file_digest(f, "sha256").hexdigest() | |
| return candidate.name if digest(candidate) == digest(expected) else "unknown:"+candidate.name | |
| def walk(identifier, at, source_in, length, stack=()): | |
| if identifier in stack or len(stack)>20: | |
| raise ValueError("Cyclic/overdeep project graph") | |
| node = nodes.get(identifier) | |
| if node is None: | |
| raise ValueError("Missing active producer") | |
| props = properties(node) | |
| stack = (*stack, identifier) | |
| if node.tag in ("chain", "producer"): | |
| resource = props.get("resource", "") | |
| if props.get("mlt_service") in ("color", "colour") or resource == "0": | |
| return | |
| name = source_name(resource) | |
| clips.append({"clip": name, "timeline_at": at, "src_in": source_in, | |
| "duration": length}) | |
| elif node.tag == "playlist": | |
| pos = 0. | |
| for entry in node: | |
| if entry.tag == "blank": | |
| pos += clock(entry.get("length"), fps) | |
| elif entry.tag == "entry": | |
| begin = clock(entry.get("in"), fps) | |
| duration = clock(entry.get("out"), fps)-begin+1/fps | |
| lo, hi = max(pos, source_in), min(pos+duration, source_in+length) | |
| if hi > lo: | |
| walk(entry.get("producer"), at+lo-source_in, | |
| begin+lo-pos, hi-lo, stack) | |
| pos += duration | |
| elif node.tag == "tractor": | |
| tracks = [t for t in node.findall("track") if t.get("hide") != "video"] | |
| for track in tracks: | |
| child = nodes.get(track.get("producer")) | |
| if child is not None and properties(child).get("shotcut:audio") == "1": | |
| continue | |
| begin = clock(track.get("in"), fps) | |
| walk(track.get("producer"), at, source_in+begin, length, stack) | |
| # Only connected, active video transitions qualify as timing evidence. | |
| for effect in node.findall("transition"): | |
| p = properties(effect) | |
| if p.get("mlt_service") not in ("luma", "dissolve", "frei0r.luma", "frei0r.wipe"): | |
| continue | |
| try: | |
| a, b = int(p["a_track"]), int(p["b_track"]) | |
| if a == b or not 0 <= a < len(node.findall("track")) or not 0 <= b < len(node.findall("track")): | |
| continue | |
| except (KeyError, ValueError): | |
| continue | |
| start = clock(effect.get("in", node.get("in")), fps) | |
| finish = clock(effect.get("out", node.get("out")), fps)+1/fps | |
| lo, hi = max(start, source_in), min(finish, source_in+length) | |
| if hi > lo: | |
| transitions.append({"start": at+lo-source_in, "duration": hi-lo, | |
| "service": p.get("mlt_service")}) | |
| length = clock(main.get("out"), fps)-clock(main.get("in"), fps)+1/fps | |
| walk(main.get("id"), 0., clock(main.get("in"), fps), length) | |
| # Merge split portions of the same source in Shotcut overlap tractors. | |
| merged = [] | |
| for clip in sorted(clips, key=lambda c: (c["timeline_at"], c["clip"])): | |
| previous = next((c for c in reversed(merged) if c["clip"] == clip["clip"] | |
| and abs(c["timeline_at"]+c["duration"]-clip["timeline_at"]) < .08 | |
| and abs(c["src_in"]+c["duration"]-clip["src_in"]) < .08), None) | |
| if previous: | |
| previous["duration"] += clip["duration"] | |
| elif clip not in merged: | |
| merged.append(clip.copy()) | |
| bin_node = nodes.get("main_bin") | |
| imported = [] | |
| if bin_node is not None: | |
| for entry in bin_node.findall("entry"): | |
| node = nodes.get(entry.get("producer")) | |
| if node is not None: | |
| imported.append(source_name(properties(node).get("resource", ""))) | |
| # An actively used source is imported even if it was removed from the bin. | |
| imported += [c["clip"] for c in merged] | |
| reference_used = any("reference.mp4" in c["clip"] for c in merged) | |
| return {"valid": True, "imported": sorted(set(imported)), "clips": merged, | |
| "transitions": transitions, "reference_used": reference_used, "error": None} | |
| except (OSError, ET.ParseError, ValueError, TypeError, AttributeError, ZeroDivisionError) as exc: | |
| return {**empty, "error": str(exc)} | |
| def measure_dissolve(output, sources, edl): | |
| """Fit RGB blends over a search interval, rejecting poor footage matches. | |
| Frame-time offsets accommodate VFR/encoder differences. Only fits that | |
| improve over BOTH pure-shot hypotheses count as intermediate blends. | |
| The fit permits timing credit independent of the chosen effect name. | |
| """ | |
| a, b = edl["segments"] | |
| expected = edl["transitions"][0] | |
| start, end = expected["timeline_at"], expected["timeline_at"]+expected["duration"] | |
| rows = [] | |
| for t in np.arange(max(0, start-1), min(len(output)/FPS, end+1), .1): | |
| out = frame_at(output, t) | |
| if out is None: | |
| continue | |
| y = pixels(out) | |
| best = None | |
| for offset in [-.2, -.1, 0., .1, .2]: | |
| fa = frame_at(sources[a["clip"]], a["src_in"]+t-a["timeline_at"]+offset) | |
| fb = frame_at(sources[b["clip"]], b["src_in"]+t-b["timeline_at"]+offset) | |
| if fa is None or fb is None: | |
| continue | |
| x, z = pixels(fa), pixels(fb) | |
| delta = z-x | |
| if float(np.mean(np.abs(delta))) < 12: | |
| continue | |
| alpha = float(np.clip(np.dot(y-x, delta)/(np.dot(delta, delta)+1e-6), 0, 1)) | |
| residual = mad(y, x+alpha*delta) | |
| pure = min(mad(y, x), mad(y, z)) | |
| candidate = {"time": round(float(t), 3), "alpha": round(alpha, 4), | |
| "mad": round(residual, 3), "improvement": round(pure-residual, 3)} | |
| if best is None or residual < best["mad"]: | |
| best = candidate | |
| if best is not None: | |
| rows.append(best) | |
| middle = [r for r in rows if .12 <= r["alpha"] <= .88 | |
| and r["mad"] <= BLEND_MAD and r["improvement"] >= 2.5] | |
| result = {"matches": False, "interval": None, "samples": rows, | |
| "reason": "No reliable intermediate blend of the required footage"} | |
| if len(middle) < 4: | |
| return result | |
| ts = np.array([r["time"] for r in middle]); alphas = np.array([r["alpha"] for r in middle]) | |
| slope, intercept = np.polyfit(ts, alphas, 1) | |
| fit_error = float(np.mean(np.abs(alphas-(slope*ts+intercept)))) | |
| progression = float(np.mean(np.diff(alphas) >= -.10)) | |
| if slope <= 0 or np.ptp(alphas)<.4 or fit_error>.12 or progression<.75: | |
| return {**result, "reason": "Blend does not progress smoothly from outgoing to incoming"} | |
| detected_start, detected_end = -intercept/slope, (1-intercept)/slope | |
| if not .3 <= detected_end-detected_start <= 2.5: | |
| return result | |
| return {**result, "matches": True, | |
| "interval": {"start": round(float(detected_start), 3), | |
| "duration": round(float(detected_end-detected_start), 3)}, | |
| "fit_error": fit_error, "progression": progression, "reason": "Required shots blend progressively"} | |
| def audio(path): | |
| meta = probe(path) | |
| streams = [s for s in (meta or {}).get("streams", []) | |
| if s.get("codec_type") == "audio" and s.get("codec_name")] | |
| if not streams: | |
| return np.array([], np.float32) | |
| data = run(["ffmpeg", "-v", "error", "-i", str(path), "-t", "60", | |
| "-map", f"0:{streams[0]['index']}", "-vn", "-ac", "1", "-ar", "8000", | |
| "-f", "f32le", "-"], 90) | |
| return np.frombuffer(data, "<f4") | |
| def measure_audio(export, reference, edl): | |
| actual, expected = audio(export), audio(reference) | |
| checks = [] | |
| if not len(actual) or not len(expected): | |
| return {"matches": False, "windows": [], "reason": "Missing decodable audio"} | |
| transition = edl["transitions"][0] | |
| regions = [] | |
| for segment in edl["segments"]: | |
| lo = max(segment["timeline_at"]+.6, 0) | |
| hi = segment["timeline_at"]+segment["duration"]-.6 | |
| for t in np.linspace(lo, max(lo, hi-.75), 3): | |
| if t <= transition["timeline_at"]+transition["duration"] and t+.75 >= transition["timeline_at"]: | |
| continue | |
| regions.append((segment["clip"], float(t))) | |
| # Also require the original audio through the joined region. | |
| regions.append(("transition", transition["timeline_at"] + transition["duration"]/2 - .375)) | |
| for clip, t in regions: | |
| ref = expected[int(t*8000):int(t*8000)+6000] | |
| ref = ref-ref.mean() | |
| best = 0. | |
| # FFT correlation searches every sample within the cut tolerance. | |
| base = max(0, int((t-.5)*8000)) | |
| region = actual[base:int((t+.5)*8000)+6000] | |
| if len(ref)==6000 and len(region)>=6000 and np.sqrt(np.mean(ref**2))>1e-5: | |
| n = 1 << (len(region)+len(ref)-1).bit_length() | |
| corr = np.fft.irfft(np.fft.rfft(region, n)*np.fft.rfft(ref[::-1], n), n) | |
| dot = corr[len(ref)-1:len(region)] | |
| sums = np.concatenate(([0.], np.cumsum(region, dtype=np.float64))) | |
| sq = np.concatenate(([0.], np.cumsum(region.astype(np.float64)**2))) | |
| count = len(ref) | |
| variance = (sq[count:]-sq[:-count])-(sums[count:]-sums[:-count])**2/count | |
| norm = np.sqrt(np.maximum(variance, 0)*np.sum(ref**2)) | |
| best = float(np.max(np.divide(dot, norm, out=np.zeros_like(dot), where=norm>1e-10))) | |
| checks.append({"clip": clip, "time": round(float(t), 3), | |
| "correlation": round(best, 4), "matches": best>=.45}) | |
| return {"matches": bool(checks) and all(c["matches"] for c in checks) | |
| and all(any(c["clip"]==s["clip"] for c in checks) for s in edl["segments"]), | |
| "windows": checks, "reason": "Original sound must match every sampled region of both shots"} | |
| def choose_export(expected, roots): | |
| if Path(expected).is_file(): | |
| return Path(expected) | |
| candidates = sorted({p for root in roots for p in Path(root).rglob("*.mp4") | |
| if p.name != "reference.mp4"})[:100] | |
| valid = [p for p in candidates if probe(p)] | |
| # Never select the highest-scoring candidate by consulting ground truth. | |
| return valid[0] if len(valid)==1 else None | |
| def grade(export_path, project_path, reference, media_dir, edl_path, search_roots=None): | |
| for tool in ["ffmpeg", "ffprobe"]: | |
| if not shutil.which(tool): | |
| raise VerifierError(f"Missing grading dependency: {tool}") | |
| try: | |
| edl = json.loads(Path(edl_path).read_text()) | |
| if len(edl["segments"])!=2 or len(edl["transitions"])!=1: | |
| raise ValueError("This verifier instance requires two segments and one transition") | |
| for s in edl["segments"]: | |
| if s["duration"]<=0 or s["src_in"]<0: | |
| raise ValueError("Invalid grading source range") | |
| reference_frames = frames(str(reference)) | |
| sources = {s["clip"]: frames(str(Path(media_dir)/s["clip"])) for s in edl["segments"]} | |
| if not len(audio(str(reference))): | |
| raise ValueError("Reference audio is missing") | |
| except (OSError, KeyError, ValueError, subprocess.CalledProcessError) as exc: | |
| raise VerifierError(f"Unreadable reference or grading inputs: {exc}") from exc | |
| selected = choose_export(export_path, search_roots or [Path(export_path).parent, Path(project_path).parent]) | |
| project = read_project(project_path, media_dir) | |
| known = {s["clip"] for s in edl["segments"]} | |
| active = {s["clip"] for s in project["clips"]} | |
| details = {"project": project, "selected_export": str(selected) if selected else None} | |
| awarded = dict.fromkeys(POINTS, 0.) | |
| awarded["import_clips"] = float(known <= set(project["imported"])) | |
| awarded["find_clips"] = float(project["valid"] and active == known) | |
| meta = probe(selected) if selected else None | |
| output = None | |
| if meta: | |
| try: | |
| duration = float(meta["format"]["duration"]) | |
| video = next(s for s in meta["streams"] if s.get("codec_type")=="video") | |
| if not 0 < duration <= 60: | |
| raise ValueError("Export duration out of bounds") | |
| output = frames(str(selected)) | |
| # Full decode catches corruption beyond sparse scored samples. | |
| run(["ffmpeg", "-v", "error", "-xerror", "-i", str(selected), | |
| "-map", "0:v:0", "-f", "null", "-"], 90) | |
| valid = video.get("codec_name")=="h264" and (video.get("width"), video.get("height"))==(1920,1080) | |
| awarded["export_valid"] = float(valid) | |
| awarded["export_path"] = float(valid and selected.resolve()==Path(export_path).resolve()) | |
| details["duration"] = duration | |
| except (ValueError, KeyError, StopIteration, subprocess.CalledProcessError): | |
| output = None | |
| if output is not None: | |
| matches = matching_samples(output, reference_frames, edl) | |
| details["visual_samples"] = matches | |
| seq = sorted(project["clips"], key=lambda c:c["timeline_at"]) | |
| order_ok = [c["clip"] for c in seq]==[s["clip"] for s in edl["segments"]] | |
| awarded["clip_order_and_trims"] += float(order_ok and all(m["matches"] for m in matches)) | |
| # Source mapping, rather than overlap handle lengths, is invariant | |
| # across built-in dissolve and keyframed two-track implementations. | |
| mapping_ok = order_ok and all(abs((c["src_in"]-c["timeline_at"])- | |
| (s["src_in"]-s["timeline_at"]))<=TIME_TOL for c,s in zip(seq,edl["segments"])) | |
| awarded["clip_order_and_trims"] += float(mapping_ok and all(m["matches"] for m in matches)) | |
| coverage_ok = order_ok and abs(seq[0]["timeline_at"]) <= TIME_TOL and all( | |
| c["timeline_at"] <= s["timeline_at"]+TIME_TOL and | |
| c["timeline_at"]+c["duration"] >= s["timeline_at"]+s["duration"]-TIME_TOL | |
| for c,s in zip(seq,edl["segments"])) | |
| awarded["clip_order_and_trims"] += float(mapping_ok and | |
| coverage_ok and | |
| abs(details["duration"]-edl["sequence_duration"])<=.6 and | |
| all(m["matches"] for m in matches)) | |
| dissolve = measure_dissolve(output, sources, edl) | |
| details["dissolve"] = dissolve | |
| if dissolve["matches"]: | |
| awarded["dissolve_behavior"] = 3. | |
| interval = dissolve["interval"] | |
| # No timing credit from unused XML. An active connected transition | |
| # can establish timing even when the footage/type is wrong. | |
| if interval is None and project["transitions"]: | |
| interval = project["transitions"][0] | |
| if interval: | |
| expected = edl["transitions"][0] | |
| start_ok = abs(interval["start"]-expected["timeline_at"])<=TIME_TOL | |
| dur_ok = abs(interval["duration"]-expected["duration"])<=DURATION_TOL | |
| end_ok = abs(interval["start"]+interval["duration"]- | |
| expected["timeline_at"]-expected["duration"])<=TIME_TOL | |
| awarded["transition_timing"] = float(start_ok)+float(dur_ok)+float(end_ok) | |
| try: | |
| details["audio"] = measure_audio(str(selected), str(reference), edl) | |
| awarded["original_audio"] = float(details["audio"]["matches"]) | |
| except subprocess.CalledProcessError: | |
| details["audio"] = {"matches": False, "reason": "Submitted audio cannot decode"} | |
| # Preserve calibrated watermark-band identity gate without OCR dependency. | |
| bands=[] | |
| for match in matches: | |
| for t in match["times"]: | |
| actual = frame_at(output,t) | |
| if actual is not None: | |
| options=[frame_at(reference_frames,t+d) for d in np.arange(-.5,.51,.1)] | |
| bands.append(min((mad(actual[20:34],r[20:34]) for r in options if r is not None),default=255.)) | |
| details["reference_band_mads"] = bands | |
| gated = project["reference_used"] or bool(bands and sum(b<=4 for b in bands)>len(bands)/2) | |
| else: | |
| gated = project["reference_used"] | |
| earned = sum(awarded.values()) | |
| return {"status": "ok", "points": awarded, "possible_points": POINTS, | |
| "earned_points": earned, "total_points": 14, "anti_cheat": not gated, | |
| "reward": 0. if gated else round(earned/14,6), "details": details} | |