The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Evaluation harness: metrics in Python (uv, pinned), each a small module with tests on tiny fixtures
Claude40e6b3c0a0ea
diff --git a/scripts/eval/lib/metric-info.mjs b/scripts/eval/lib/metric-info.mjsnew file mode 100644index 00000000..9b129df0--- /dev/null+++ b/scripts/eval/lib/metric-info.mjs@@ -0,0 +1,42 @@+// What each score means, which way is better, and how big a difference is noise. The Python side+// (metrics/fuobe_metrics/registry.py) writes the same keys; timing and cost come from the runner.++/** @type {Record<string, { label: string, better: "higher" | "lower" | "none", unit: string, tie: number, digits: number }>} */+export const METRIC_INFO = {+ clip: { label: "CLIP prompt adherence", better: "higher", unit: "CLIPScore 0–100", tie: 0.5, digits: 1 },+ aesthetic: { label: "Aesthetic (LAION v2)", better: "higher", unit: "1–10", tie: 0.05, digits: 2 },+ style: { label: "Style vs references", better: "higher", unit: "cosine", tie: 0.005, digits: 3 },+ styleNearest: { label: "Style, nearest reference", better: "higher", unit: "cosine", tie: 0.005, digits: 3 },+ identity: { label: "Identity vs references", better: "higher", unit: "cosine", tie: 0.01, digits: 3 },+ faceRate: { label: "Frames with a face", better: "higher", unit: "0–1", tie: 0.01, digits: 2 },+ drift: { label: "Frame-to-frame drift", better: "lower", unit: "1 − cosine", tie: 0.002, digits: 4 },+ driftMax: { label: "Worst frame jump", better: "lower", unit: "1 − cosine", tie: 0.005, digits: 4 },+ warp: { label: "Warp error (flicker)", better: "lower", unit: "0–1", tie: 0.001, digits: 4 },+ lipsync: { label: "Lip-sync proxy", better: "higher", unit: "Pearson r", tie: 0.02, digits: 3 },+ lipsyncOffset: { label: "A/V offset", better: "none", unit: "frames", tie: 0, digits: 0 },+ syncnet: { label: "SyncNet confidence", better: "higher", unit: "conf", tie: 0.1, digits: 2 },+ continuity: { label: "Shot continuity", better: "higher", unit: "cosine", tie: 0.005, digits: 3 },+ seconds: { label: "Time", better: "lower", unit: "s (wall clock)", tie: 0.5, digits: 1 },+ costUsd: { label: "Cost", better: "lower", unit: "US$", tie: 0.0005, digits: 4 },+ vramGb: { label: "Peak memory", better: "lower", unit: "GB", tie: 0.1, digits: 2 },+};++/** Keys in the order reports show them. */+export const METRIC_ORDER = Object.keys(METRIC_INFO);++/** b against a: "win" when b is better by more than the metric's tie band, "loss" when worse, else "tie". */+export function verdict(metric, a, b) {+ const info = METRIC_INFO[metric];+ if (!info || info.better === "none" || a == null || b == null || Number.isNaN(a) || Number.isNaN(b)) return null;+ const gain = info.better === "higher" ? b - a : a - b;+ return gain > info.tie ? "win" : gain < -info.tie ? "loss" : "tie";+}++/** b − a, signed so that positive is better. */+export function gain(metric, a, b) {+ const info = METRIC_INFO[metric];+ if (!info || a == null || b == null) return null;+ return info.better === "lower" ? a - b : b - a;+}++export const fmt = (metric, v) => (v == null || Number.isNaN(v) ? "–" : Number(v).toFixed(METRIC_INFO[metric]?.digits ?? 3));diff --git a/scripts/eval/lib/metrics.mjs b/scripts/eval/lib/metrics.mjsnew file mode 100644index 00000000..fb865097--- /dev/null+++ b/scripts/eval/lib/metrics.mjs@@ -0,0 +1,55 @@+// The bridge to the Python metrics (scripts/eval/metrics): find the venv pnpm eval:setup made (or+// uv), run the scorer on a run folder and read metrics.json back. With no Python, a run still gets+// its timing and cost; the scores say they were skipped and why.+import { spawn, spawnSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { METRICS_DIR } from "./paths.mjs";+import { readJson } from "./store.mjs";++const VENV_PY = process.platform === "win32" ? path.join(METRICS_DIR, ".venv", "Scripts", "python.exe") : path.join(METRICS_DIR, ".venv", "bin", "python");++/** How to start the scorer: the venv's Python, else `uv run` with the pinned requirements, else null (with why). */+export function pythonCommand(env = process.env) {+ if (env.FUOBE_EVAL_PYTHON) return { cmd: env.FUOBE_EVAL_PYTHON, args: [], how: "FUOBE_EVAL_PYTHON" };+ if (fs.existsSync(VENV_PY)) return { cmd: VENV_PY, args: [], how: "scripts/eval/metrics/.venv" };+ const uv = spawnSync("uv", ["--version"], { encoding: "utf8" });+ if (uv.status === 0) return { cmd: "uv", args: ["run", "--no-project", "--with-requirements", path.join(METRICS_DIR, "requirements.txt"), "python"], how: "uv run (first use downloads the pinned packages)" };+ return null;+}++/** Score a run folder; resolves with {ok, file, doc, skipped} and streams the scorer's progress to `log`. */+export function scoreRun(dir, { metrics, device, clipModel, identityModel, acceptNoncommercial, force, log = () => {}, env = process.env } = {}) {+ const py = pythonCommand(env);+ if (!py) return Promise.resolve({ ok: false, reason: "No Python for the metrics: run pnpm eval:setup (needs uv), or set FUOBE_EVAL_PYTHON" });+ const args = [+ ...py.args,+ "-m",+ "fuobe_metrics.score",+ dir,+ ...(metrics ? ["--metrics", metrics] : []),+ ...(device ? ["--device", device] : []),+ ...(clipModel ? ["--clip-model", clipModel] : []),+ ...(identityModel ? ["--identity-model", identityModel] : []),+ ...(acceptNoncommercial ? ["--accept-noncommercial"] : []),+ ...(force ? ["--force"] : []),+ ];+ return new Promise((resolve) => {+ const child = spawn(py.cmd, args, { cwd: METRICS_DIR, env: { ...env, PYTHONUNBUFFERED: "1" }, stdio: ["ignore", "pipe", "pipe"] });+ let tail = "";+ const onData = (d) => {+ const text = d.toString();+ tail = (tail + text).slice(-4000);+ for (const line of text.split("\n")) if (line.trim()) log(` ${line.trim()}`);+ };+ child.stdout.on("data", onData);+ child.stderr.on("data", onData);+ child.on("error", (e) => resolve({ ok: false, reason: `Couldn't start ${py.cmd}: ${e.message}` }));+ child.on("close", (code) => {+ const file = path.join(dir, "metrics.json");+ if (code !== 0) return resolve({ ok: false, reason: `the scorer stopped (exit ${code}): ${tail.trim().split("\n").at(-1) ?? ""}` });+ const doc = readJson(file);+ resolve({ ok: !!doc, file, doc, skipped: doc?.skipped ?? {}, how: py.how });+ });+ });+}diff --git a/scripts/eval/metrics/fuobe_metrics/__init__.py b/scripts/eval/metrics/fuobe_metrics/__init__.pynew file mode 100644index 00000000..3f155dca--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/__init__.py@@ -0,0 +1 @@+"""Metrics for Fuobe's evaluation harness (scripts/eval). See scripts/eval/README.md."""diff --git a/scripts/eval/metrics/fuobe_metrics/download.py b/scripts/eval/metrics/fuobe_metrics/download.pynew file mode 100644index 00000000..7ff3df6c--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/download.py@@ -0,0 +1,31 @@+"""Fetch the metric weights at their pinned revisions: python -m fuobe_metrics.download [--identity] [--no-aesthetic].+They go to FUOBE_EVAL_CACHE (default ~/.cache/fuobe-eval); scoring downloads them on first use otherwise."""++from __future__ import annotations++import argparse+import sys++from .models import _download+from .registry import MODELS+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(prog="fuobe_metrics.download")+ ap.add_argument("--identity", action="store_true", help="also AuraFace (Apache-2.0) for identity and the lip-sync face box")+ ap.add_argument("--no-aesthetic", action="store_true", help="skip CLIP ViT-L/14 and the aesthetic head (about 1.7 GB)")+ args = ap.parse_args(argv)+ wanted = [("clip-b32", MODELS["clip-b32"]["file"])]+ if not args.no_aesthetic:+ wanted += [("clip-l14", MODELS["clip-l14"]["file"]), ("aesthetic-v2", MODELS["aesthetic-v2"]["file"])]+ if args.identity:+ wanted += [("auraface", f) for f in MODELS["auraface"]["files"]]+ for key, f in wanted:+ m = MODELS[key]+ print(f"{m['repo']} · {f} @ {m['revision'][:8]} ({m['licence']})", file=sys.stderr)+ print(f" → {_download(key, f)}", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/eval/metrics/fuobe_metrics/maths.py b/scripts/eval/metrics/fuobe_metrics/maths.pynew file mode 100644index 00000000..158eb28c--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/maths.py@@ -0,0 +1,148 @@+"""The metric maths, on plain numpy arrays (embeddings, frames, flows, audio), so it is tested+without any model. The model wrappers in models.py only turn media into these arrays."""++from __future__ import annotations++import numpy as np+++def l2norm(x: np.ndarray, axis: int = -1) -> np.ndarray:+ x = np.asarray(x, dtype=np.float64)+ n = np.linalg.norm(x, axis=axis, keepdims=True)+ return x / np.where(n == 0, 1, n)+++def cosine(a: np.ndarray, b: np.ndarray) -> float:+ """Cosine similarity of two vectors (0 when either is all zeros)."""+ return float(np.dot(l2norm(a), l2norm(b)))+++def clip_score(image_emb: np.ndarray, text_emb: np.ndarray) -> float:+ """CLIPScore as torchmetrics defines it: 100 * max(cos(image, text), 0). Higher follows the prompt better."""+ return 100.0 * max(cosine(image_emb, text_emb), 0.0)+++def mean_clip_score(image_embs: np.ndarray, text_emb: np.ndarray) -> float:+ """A clip's score is the mean over its sampled frames."""+ return float(np.mean([clip_score(e, text_emb) for e in np.atleast_2d(image_embs)]))+++def reference_similarity(emb: np.ndarray, refs: np.ndarray) -> dict:+ """How close an output is to a reference set: to the set's centroid and to its nearest member."""+ refs = l2norm(np.atleast_2d(refs))+ e = l2norm(emb)+ centroid = l2norm(refs.mean(axis=0))+ sims = refs @ e+ return {"centroid": float(centroid @ e), "nearest": float(sims.max()), "n": int(len(refs))}+++def drift(frame_embs: np.ndarray) -> dict:+ """Frame-to-frame embedding drift: 1 - cos between consecutive frames (0 = no change). Lower is steadier."""+ e = l2norm(np.atleast_2d(frame_embs))+ if len(e) < 2:+ return {"mean": 0.0, "max": 0.0, "pairs": 0}+ d = 1.0 - np.sum(e[1:] * e[:-1], axis=1)+ d = np.clip(d, 0.0, 2.0)+ return {"mean": float(d.mean()), "max": float(d.max()), "pairs": int(len(d))}+++def warp_backward(image: np.ndarray, flow: np.ndarray) -> np.ndarray:+ """Sample `image` (H×W×C, float) at x + flow(x) with bilinear interpolation (edges clamped)."""+ h, w = image.shape[:2]+ ys, xs = np.mgrid[0:h, 0:w].astype(np.float64)+ x = np.clip(xs + flow[..., 0], 0, w - 1)+ y = np.clip(ys + flow[..., 1], 0, h - 1)+ x0 = np.floor(x).astype(int)+ y0 = np.floor(y).astype(int)+ x1 = np.minimum(x0 + 1, w - 1)+ y1 = np.minimum(y0 + 1, h - 1)+ wx = (x - x0)[..., None]+ wy = (y - y0)[..., None]+ img = image if image.ndim == 3 else image[..., None]+ top = img[y0, x0] * (1 - wx) + img[y0, x1] * wx+ bottom = img[y1, x0] * (1 - wx) + img[y1, x1] * wx+ out = top * (1 - wy) + bottom * wy+ return out if image.ndim == 3 else out[..., 0]+++def valid_flow_mask(flow_fw: np.ndarray, flow_bw: np.ndarray, alpha: float = 0.01, beta: float = 0.5) -> np.ndarray:+ """Forward-backward consistency (Sundaram et al. 2010): pixels whose flow round trip doesn't come back are occluded."""+ bw_at = warp_backward(flow_bw, flow_fw)+ diff = np.sum((flow_fw + bw_at) ** 2, axis=-1)+ bound = alpha * (np.sum(flow_fw**2, axis=-1) + np.sum(bw_at**2, axis=-1)) + beta+ h, w = flow_fw.shape[:2]+ ys, xs = np.mgrid[0:h, 0:w]+ inside = (xs + flow_fw[..., 0] >= 0) & (xs + flow_fw[..., 0] <= w - 1) & (ys + flow_fw[..., 1] >= 0) & (ys + flow_fw[..., 1] <= h - 1)+ return (diff <= bound) & inside+++def warp_error(frame0: np.ndarray, frame1: np.ndarray, flow: np.ndarray, mask: np.ndarray | None = None) -> float:+ """+ Mean absolute photometric error (0–1) between frame0 and frame1 warped back along the flow+ frame0 → frame1, over the pixels in `mask`. Flicker and texture boiling raise it; real motion+ that the flow follows doesn't.+ """+ a = np.asarray(frame0, dtype=np.float64)+ b = warp_backward(np.asarray(frame1, dtype=np.float64), flow)+ err = np.abs(a - b)+ if err.ndim == 3:+ err = err.mean(axis=-1)+ if a.max() > 1.5:+ err = err / 255.0+ if mask is not None:+ if not mask.any():+ return float("nan")+ return float(err[mask].mean())+ return float(err.mean())+++def frame_envelope(audio: np.ndarray, sr: int, fps: float, frames: int) -> np.ndarray:+ """The audio's RMS loudness for each video frame (frames values)."""+ audio = np.asarray(audio, dtype=np.float64)+ hop = sr / fps+ out = np.zeros(frames)+ for i in range(frames):+ a = int(round(i * hop))+ b = int(round((i + 1) * hop))+ seg = audio[a:b]+ out[i] = float(np.sqrt(np.mean(seg**2))) if len(seg) else 0.0+ return out+++def motion_energy(frames: np.ndarray) -> np.ndarray:+ """Mean absolute change of a region between consecutive frames (len(frames) values; the first copies the second)."""+ f = np.asarray(frames, dtype=np.float64)+ if len(f) < 2:+ return np.zeros(len(f))+ d = np.abs(np.diff(f, axis=0)).reshape(len(f) - 1, -1).mean(axis=1)+ return np.concatenate([[d[0]], d])+++def best_lag_correlation(a: np.ndarray, b: np.ndarray, max_lag: int) -> dict:+ """+ The Pearson correlation of two series at the lag (b shifted by -max_lag..max_lag samples) where it+ is highest. A lip-sync proxy: the mouth region's motion against the voice's loudness, with the+ lag as the audio/video offset in frames.+ """+ a = np.asarray(a, dtype=np.float64)+ b = np.asarray(b, dtype=np.float64)+ n = min(len(a), len(b))+ a, b = a[:n], b[:n]+ best = {"corr": 0.0, "lag": 0, "overlap": 0}+ for lag in range(-max_lag, max_lag + 1):+ x = a[max(0, lag) : n + min(0, lag)]+ y = b[max(0, -lag) : n - max(0, lag)]+ if len(x) < 4 or x.std() == 0 or y.std() == 0:+ continue+ r = float(np.corrcoef(x, y)[0, 1])+ if r > best["corr"]:+ best = {"corr": r, "lag": lag, "overlap": int(len(x))}+ return best+++def consecutive_similarity(embs: np.ndarray) -> float:+ """Mean cosine between consecutive items (the shots of a film): how well a look and its subject carry across cuts."""+ e = l2norm(np.atleast_2d(embs))+ if len(e) < 2:+ return float("nan")+ return float(np.mean(np.sum(e[1:] * e[:-1], axis=1)))diff --git a/scripts/eval/metrics/fuobe_metrics/media.py b/scripts/eval/metrics/fuobe_metrics/media.pynew file mode 100644index 00000000..dc91cea1--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/media.py@@ -0,0 +1,108 @@+"""Reading outputs and references: images (SVG demo art too, through ffmpeg's librsvg), a clip's+frames sampled at a fixed rate, and its sound. ffmpeg and ffprobe do the decoding."""++from __future__ import annotations++import json+import pathlib+import shutil+import subprocess+import tempfile++import numpy as np+from PIL import Image++IMAGE = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".svg"}+VIDEO = {".mp4", ".mov", ".m4v", ".webm", ".mkv"}+AUDIO = {".wav", ".mp3", ".flac", ".ogg", ".m4a"}+++def kind_of(path: str | pathlib.Path) -> str | None:+ ext = pathlib.Path(path).suffix.lower()+ return "image" if ext in IMAGE else "video" if ext in VIDEO else "audio" if ext in AUDIO else None+++def have_ffmpeg() -> bool:+ return bool(shutil.which("ffmpeg") and shutil.which("ffprobe"))+++def load_image(path: str | pathlib.Path, max_side: int = 1024) -> Image.Image:+ """An RGB image; SVG is rasterised by ffmpeg (librsvg). Large images are shrunk to max_side."""+ p = pathlib.Path(path)+ if p.suffix.lower() == ".svg":+ if not have_ffmpeg():+ raise RuntimeError("an SVG output needs ffmpeg (with librsvg) to be read")+ with tempfile.TemporaryDirectory() as tmp:+ out = pathlib.Path(tmp) / "frame.png"+ r = subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(p), "-frames:v", "1", str(out)], capture_output=True)+ if r.returncode != 0 or not out.exists():+ raise RuntimeError(f"ffmpeg couldn't rasterise {p.name}: {r.stderr.decode(errors='replace').strip()[:200]}")+ img = Image.open(out).convert("RGB")+ img.load()+ else:+ img = Image.open(p).convert("RGB")+ if max(img.size) > max_side:+ img.thumbnail((max_side, max_side))+ return img+++def probe(path: str | pathlib.Path) -> dict:+ """{duration, fps, width, height, audio} of a clip."""+ r = subprocess.run(+ ["ffprobe", "-v", "error", "-show_entries", "stream=codec_type,width,height,avg_frame_rate:format=duration", "-of", "json", str(path)],+ capture_output=True,+ text=True,+ )+ if r.returncode != 0:+ raise RuntimeError(f"ffprobe couldn't read {pathlib.Path(path).name}")+ j = json.loads(r.stdout or "{}")+ video = next((s for s in j.get("streams", []) if s.get("codec_type") == "video"), None)+ num, _, den = (video or {}).get("avg_frame_rate", "0/1").partition("/")+ fps = float(num) / float(den or 1) if float(den or 1) else 0.0+ return {+ "duration": float(j.get("format", {}).get("duration") or 0),+ "fps": fps,+ "width": int((video or {}).get("width") or 0),+ "height": int((video or {}).get("height") or 0),+ "audio": any(s.get("codec_type") == "audio" for s in j.get("streams", [])),+ }+++def video_frames(path: str | pathlib.Path, fps: float = 4.0, max_frames: int = 32, width: int = 256) -> tuple[np.ndarray, float]:+ """Frames sampled at `fps` (at most max_frames, spread over the clip), as uint8 N×H×W×3, and the rate they were taken at."""+ info = probe(path)+ rate = fps+ if info["duration"] > 0 and info["duration"] * fps > max_frames:+ rate = max_frames / info["duration"]+ w = width - width % 2+ h = max(2, int(round(info["height"] * w / max(1, info["width"]) / 2)) * 2) if info["width"] else w+ r = subprocess.run(+ ["ffmpeg", "-v", "error", "-i", str(path), "-vf", f"fps={rate},scale={w}:{h}", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"],+ capture_output=True,+ )+ if r.returncode != 0:+ raise RuntimeError(f"ffmpeg couldn't read {pathlib.Path(path).name}: {r.stderr.decode(errors='replace').strip()[:200]}")+ frames = np.frombuffer(r.stdout, dtype=np.uint8)+ n = len(frames) // (w * h * 3)+ return frames[: n * w * h * 3].reshape(n, h, w, 3)[:max_frames], rate+++def audio_track(path: str | pathlib.Path, sr: int = 16000) -> np.ndarray | None:+ """The sound as mono float32 at `sr` Hz, or None when there is none."""+ r = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "1", "-ar", str(sr), "-f", "s16le", "-"], capture_output=True)+ if r.returncode != 0 or not r.stdout:+ return None+ return np.frombuffer(r.stdout, dtype="<i2").astype(np.float32) / 32768.0+++def images_of(path: str | pathlib.Path, frames: int = 4) -> list[Image.Image]:+ """A file as pictures: an image itself, or `frames` frames spread over a clip."""+ k = kind_of(path)+ if k == "image":+ return [load_image(path)]+ if k == "video":+ arr, _ = video_frames(path, fps=frames, max_frames=frames, width=384)+ if len(arr) > frames:+ arr = arr[np.linspace(0, len(arr) - 1, frames).astype(int)]+ return [Image.fromarray(a) for a in arr]+ return []diff --git a/scripts/eval/metrics/fuobe_metrics/models.py b/scripts/eval/metrics/fuobe_metrics/models.pynew file mode 100644index 00000000..bcbb878a--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/models.py@@ -0,0 +1,138 @@+"""The models behind the metrics, loaded once and only when a metric needs them. Weights come from+Hugging Face at the revisions pinned in registry.py, into FUOBE_EVAL_CACHE (default+~/.cache/fuobe-eval). Everything runs on the CPU unless --device says otherwise."""++from __future__ import annotations++import os+import pathlib++import numpy as np++from .registry import MODELS++CACHE = pathlib.Path(os.environ.get("FUOBE_EVAL_CACHE", pathlib.Path.home() / ".cache" / "fuobe-eval"))+++class Missing(RuntimeError):+ """A metric's library or weights aren't installed; the message says how to get them."""+++def _torch():+ try:+ import torch # noqa: PLC0415+ except ImportError as e:+ raise Missing("PyTorch isn't installed: run pnpm eval:setup") from e+ return torch+++def device_of(want: str = "cpu") -> str:+ if want == "auto":+ torch = _torch()+ return "cuda" if torch.cuda.is_available() else "mps" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available() else "cpu"+ return want+++def _download(key: str, filename: str) -> str:+ try:+ from huggingface_hub import hf_hub_download # noqa: PLC0415+ except ImportError as e:+ raise Missing("huggingface_hub isn't installed: run pnpm eval:setup") from e+ m = MODELS[key]+ return hf_hub_download(m["repo"], filename, revision=m["revision"], cache_dir=str(CACHE / "hf"))+++class Clip:+ """open_clip image and text embeddings (L2-normalised numpy)."""++ def __init__(self, key: str = "clip-b32", device: str = "cpu"):+ try:+ import open_clip # noqa: PLC0415+ except ImportError as e:+ raise Missing("open_clip isn't installed: run pnpm eval:setup") from e+ torch = _torch()+ m = MODELS[key]+ weights = _download(key, m["file"])+ self.key = key+ self.device = device+ self.model, _, self.preprocess = open_clip.create_model_and_transforms(m["arch"], pretrained=weights, device=device)+ self.model.eval()+ self.tokenizer = open_clip.get_tokenizer(m["arch"])+ self.torch = torch++ def images(self, pictures) -> np.ndarray:+ if not pictures:+ return np.zeros((0, 1))+ with self.torch.no_grad():+ out = []+ for i in range(0, len(pictures), 16):+ batch = self.torch.stack([self.preprocess(p) for p in pictures[i : i + 16]]).to(self.device)+ e = self.model.encode_image(batch)+ out.append(self.torch.nn.functional.normalize(e, dim=-1).float().cpu().numpy())+ return np.concatenate(out)++ def texts(self, texts: list[str]) -> np.ndarray:+ with self.torch.no_grad():+ tokens = self.tokenizer(texts).to(self.device)+ e = self.model.encode_text(tokens)+ return self.torch.nn.functional.normalize(e, dim=-1).float().cpu().numpy()+++class Aesthetic:+ """The LAION improved aesthetic predictor (v2, sac+logos+ava1 linear MSE) on CLIP ViT-L/14 embeddings: about 1–10."""++ def __init__(self, clip_l14: Clip):+ torch = clip_l14.torch+ nn = torch.nn+ self.clip = clip_l14+ self.head = nn.Sequential(+ nn.Linear(768, 1024),+ nn.Dropout(0.2),+ nn.Linear(1024, 128),+ nn.Dropout(0.2),+ nn.Linear(128, 64),+ nn.Dropout(0.1),+ nn.Linear(64, 16),+ nn.Linear(16, 1),+ )+ state = torch.load(_download("aesthetic-v2", MODELS["aesthetic-v2"]["file"]), map_location="cpu", weights_only=True)+ # The original checkpoint names the Sequential "layers".+ self.head.load_state_dict({k.removeprefix("layers."): v for k, v in state.items()})+ self.head.eval().to(clip_l14.device)++ def scores(self, pictures) -> np.ndarray:+ emb = self.clip.images(pictures)+ with self.clip.torch.no_grad():+ t = self.clip.torch.from_numpy(emb).to(self.clip.device)+ return self.head(t).squeeze(-1).float().cpu().numpy()+++class Faces:+ """Face detection + ArcFace-style embeddings through insightface. AuraFace (Apache-2.0) by default; buffalo_l is opt-in."""++ def __init__(self, name: str = "auraface", device: str = "cpu"):+ try:+ from insightface.app import FaceAnalysis # noqa: PLC0415+ except ImportError as e:+ raise Missing("insightface isn't installed: run pnpm eval:setup --identity") from e+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"] if device == "cuda" else ["CPUExecutionProvider"]+ root = CACHE / "insightface"+ if name == "auraface":+ folder = root / "models" / "auraface"+ folder.mkdir(parents=True, exist_ok=True)+ for f in MODELS["auraface"]["files"]:+ target = folder / f+ if not target.exists():+ target.symlink_to(_download("auraface", f))+ self.name = name+ self.app = FaceAnalysis(name=name, root=str(root), providers=providers, allowed_modules=["detection", "recognition"])+ self.app.prepare(ctx_id=0 if device == "cuda" else -1, det_size=(640, 640))++ def largest(self, picture) -> dict | None:+ """The largest face in a PIL picture: {embedding, box} or None."""+ bgr = np.asarray(picture.convert("RGB"))[:, :, ::-1]+ faces = self.app.get(bgr)+ if not faces:+ return None+ f = max(faces, key=lambda x: float((x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1])))+ return {"embedding": np.asarray(f.normed_embedding, dtype=np.float64), "box": [float(v) for v in f.bbox]}diff --git a/scripts/eval/metrics/fuobe_metrics/registry.py b/scripts/eval/metrics/fuobe_metrics/registry.pynew file mode 100644index 00000000..7c730abc--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/registry.py@@ -0,0 +1,74 @@+"""What each metric means and which model (at which pinned revision, under which licence) makes it.+scripts/eval/lib/metric-info.mjs holds the same directions for compare and the reports."""++# The suite names a metric family; each family writes these keys per job.+FAMILIES = {+ "clip": ["clip"],+ "aesthetic": ["aesthetic"],+ "style": ["style", "styleNearest"],+ "identity": ["identity", "faceRate"],+ "temporal": ["drift", "driftMax", "warp"],+ "lipsync": ["lipsync", "lipsyncOffset"],+ "continuity": ["continuity"],+}++METRICS = {+ "clip": {"label": "CLIP prompt adherence", "better": "higher", "unit": "CLIPScore 0–100"},+ "aesthetic": {"label": "Aesthetic (LAION v2)", "better": "higher", "unit": "1–10"},+ "style": {"label": "Style vs references", "better": "higher", "unit": "cosine to the reference centroid"},+ "styleNearest": {"label": "Style, nearest reference", "better": "higher", "unit": "cosine"},+ "identity": {"label": "Identity vs references", "better": "higher", "unit": "face-embedding cosine"},+ "faceRate": {"label": "Frames with a face", "better": "higher", "unit": "0–1"},+ "drift": {"label": "Frame-to-frame drift", "better": "lower", "unit": "1 − cosine"},+ "driftMax": {"label": "Worst frame jump", "better": "lower", "unit": "1 − cosine"},+ "warp": {"label": "Warp error (flicker)", "better": "lower", "unit": "mean abs error 0–1"},+ "lipsync": {"label": "Lip-sync proxy", "better": "higher", "unit": "Pearson r, mouth motion vs voice"},+ "lipsyncOffset": {"label": "A/V offset", "better": "none", "unit": "frames"},+ "syncnet": {"label": "SyncNet confidence", "better": "higher", "unit": "SyncNet conf"},+ "continuity": {"label": "Shot continuity", "better": "higher", "unit": "cosine between consecutive shots"},+}++# Weights, each pinned to a Hugging Face revision. "commercial" says whether the model itself may be used+# commercially; a metric model only scores outputs, but the licence is recorded with every result.+MODELS = {+ "clip-b32": {+ "arch": "ViT-B-32",+ "repo": "laion/CLIP-ViT-B-32-laion2B-s34B-b79K",+ "file": "open_clip_model.safetensors",+ "revision": "1a25a446712ba5ee05982a381eed697ef9b435cf",+ "licence": "MIT",+ "commercial": True,+ },+ "clip-l14": {+ "arch": "ViT-L-14-quickgelu",+ "repo": "timm/vit_large_patch14_clip_224.openai",+ "file": "open_clip_model.safetensors",+ "revision": "18d0535469bb561bf468d76c1d73aa35156c922b",+ "licence": "MIT (OpenAI CLIP)",+ "commercial": True,+ },+ "aesthetic-v2": {+ "repo": "camenduru/improved-aesthetic-predictor",+ "file": "sac+logos+ava1-l14-linearMSE.pth",+ "revision": "7b2449be1264fcd9a1cf92e3d30dd29af989c836",+ "licence": "Apache-2.0 (christophschuhmann/improved-aesthetic-predictor; a mirror of the original weights)",+ "commercial": True,+ },+ "auraface": {+ "repo": "fal/AuraFace-v1",+ "files": ["glintr100.onnx", "scrfd_10g_bnkps.onnx"],+ "revision": "af6d057c9b0ec4071d4c49c80e3539258798b609",+ "licence": "Apache-2.0 (fal/AuraFace-v1, trained on commercially usable data; ships an SCRFD detector)",+ "commercial": True,+ },+ "buffalo_l": {+ "repo": "insightface model zoo (downloaded by insightface)",+ "licence": "non-commercial research only (insightface model packs)",+ "commercial": False,+ },+ "dinov2-small": {+ "repo": "facebook/dinov2-small",+ "licence": "Apache-2.0",+ "commercial": True,+ },+}diff --git a/scripts/eval/metrics/fuobe_metrics/score.py b/scripts/eval/metrics/fuobe_metrics/score.pynew file mode 100644index 00000000..d9deb909--- /dev/null+++ b/scripts/eval/metrics/fuobe_metrics/score.py@@ -0,0 +1,348 @@+"""Score a run: python -m fuobe_metrics.score <runDir> [options]. Reads run.json and jobs.jsonl,+writes metrics.json next to them: per-job scores, per-group scores (continuity across a film's+shots), which models made them (revision and licence) and why any metric was skipped. A job whose+outputs and settings haven't changed keeps its earlier scores (--force recomputes)."""++from __future__ import annotations++import argparse+import datetime as dt+import hashlib+import json+import math+import os+import pathlib+import sys+import time++import numpy as np++from . import maths+from .media import audio_track, have_ffmpeg, images_of, kind_of, video_frames+from .models import MODELS, Aesthetic, Clip, Faces, Missing, device_of+from .registry import FAMILIES++VERSION = 1+++def read_jobs(run_dir: pathlib.Path) -> list[dict]:+ rows: dict[str, dict] = {}+ path = run_dir / "jobs.jsonl"+ if not path.exists():+ return []+ for line in path.read_text(encoding="utf8").splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ row = json.loads(line)+ except json.JSONDecodeError:+ continue+ rows[row["id"]] = row+ return [r for r in rows.values() if r.get("status") == "succeeded" and r.get("outputs")]+++def media_outputs(run_dir: pathlib.Path, job: dict) -> list[pathlib.Path]:+ """The job's picture or clip outputs (masks, first frames and other helpers left out)."""+ out = []+ for o in job.get("outputs", []):+ if o.get("role") in {"mask", "first-frame", "depth"}:+ continue+ p = run_dir / o["file"]+ if p.exists() and kind_of(p) in {"image", "video"}:+ out.append(p)+ return out+++def fingerprint(run_dir: pathlib.Path, job: dict, config: dict) -> str:+ h = hashlib.sha256(json.dumps(config, sort_keys=True).encode())+ for p in media_outputs(run_dir, job) + [pathlib.Path(r) for r in job.get("references", [])]:+ try:+ st = p.stat()+ h.update(f"{p}|{st.st_size}|{int(st.st_mtime)}".encode())+ except OSError:+ h.update(f"{p}|missing".encode())+ h.update(json.dumps(sorted(job.get("metrics", []))).encode())+ return h.hexdigest()[:16]+++class Scorer:+ def __init__(self, args):+ self.args = args+ self.device = device_of(args.device)+ self._clip = None+ self._clip_l14 = None+ self._aesthetic = None+ self._faces = None+ self.used: dict[str, dict] = {}+ self.skipped: dict[str, str] = {}++ # Models, loaded on first use; a missing one skips its metric for the whole run with the reason.+ def clip(self):+ if self._clip is None:+ self._clip = Clip(self.args.clip_model, self.device)+ self.used["clip"] = {**MODELS[self.args.clip_model], "key": self.args.clip_model}+ return self._clip++ def aesthetic(self):+ if self._aesthetic is None:+ if self._clip_l14 is None:+ self._clip_l14 = self._clip if self.args.clip_model == "clip-l14" and self._clip else Clip("clip-l14", self.device)+ self._aesthetic = Aesthetic(self._clip_l14)+ self.used["aesthetic"] = {"head": MODELS["aesthetic-v2"], "clip": MODELS["clip-l14"]}+ return self._aesthetic++ def faces(self):+ if self._faces is None:+ name = self.args.identity_model+ if name == "buffalo_l" and not self.args.accept_noncommercial:+ raise Missing("buffalo_l is licensed for non-commercial research only: add --accept-noncommercial to use it, or keep the default AuraFace (Apache-2.0)")+ self._faces = Faces(name, self.device)+ self.used["identity"] = {**MODELS[name], "key": name}+ return self._faces++ # Metric families: each returns a dict of keys from registry.FAMILIES plus notes.+ def family(self, name: str, job: dict, outs: list[pathlib.Path]) -> dict:+ return getattr(self, f"m_{name}")(job, outs)++ def m_clip(self, job, outs):+ text = (job.get("prompt") or "").replace("{character}", "a person").strip()+ if not text:+ return {"_note": "no prompt to compare with"}+ pics = [p for o in outs for p in images_of(o, frames=4)]+ if not pics:+ return {"_note": "no picture to score"}+ t = self.clip().texts([text])[0]+ return {"clip": round(maths.mean_clip_score(self.clip().images(pics), t), 3)}++ def m_aesthetic(self, job, outs):+ pics = [p for o in outs for p in images_of(o, frames=4)]+ if not pics:+ return {"_note": "no picture to score"}+ return {"aesthetic": round(float(np.mean(self.aesthetic().scores(pics))), 3)}++ def reference_pictures(self, job) -> list:+ pics = []+ for r in job.get("references", []):+ if kind_of(r) in {"image", "video"} and pathlib.Path(r).exists():+ pics += images_of(r, frames=4)+ return pics++ def m_style(self, job, outs):+ refs = self.reference_pictures(job)+ if not refs:+ return {"_note": "no style references (add your own images to the case's local/references folder)"}+ pics = [p for o in outs for p in images_of(o, frames=4)]+ if not pics:+ return {"_note": "no picture to score"}+ ref_emb = self.clip().images(refs)+ out_emb = maths.l2norm(self.clip().images(pics).mean(axis=0))+ s = maths.reference_similarity(out_emb, ref_emb)+ return {"style": round(s["centroid"], 4), "styleNearest": round(s["nearest"], 4), "_refs": s["n"]}++ def m_identity(self, job, outs):+ refs = self.reference_pictures(job)+ if not refs:+ return {"_note": "no reference photos of the person"}+ faces = self.faces()+ ref = [f["embedding"] for f in (faces.largest(p) for p in refs) if f]+ if not ref:+ return {"_note": "no face found in the reference photos"}+ pics = [p for o in outs for p in images_of(o, frames=8)]+ found = [f for f in (faces.largest(p) for p in pics) if f]+ if not found:+ return {"identity": None, "faceRate": 0.0, "_note": "no face found in the output"}+ centroid = maths.l2norm(np.mean(ref, axis=0))+ sims = [float(maths.l2norm(f["embedding"]) @ centroid) for f in found]+ return {"identity": round(float(np.mean(sims)), 4), "faceRate": round(len(found) / len(pics), 3), "_refs": len(ref)}++ def m_temporal(self, job, outs):+ clips = [o for o in outs if kind_of(o) == "video"]+ if not clips:+ return {"_note": "not a clip"}+ res = {}+ frames, _ = video_frames(clips[0], fps=self.args.fps, max_frames=self.args.frames, width=256)+ if len(frames) < 2:+ return {"_note": "the clip has fewer than two frames"}+ from PIL import Image # noqa: PLC0415++ d = maths.drift(self.clip().images([Image.fromarray(f) for f in frames]))+ res["drift"] = round(d["mean"], 5)+ res["driftMax"] = round(d["max"], 5)+ try:+ import cv2 # noqa: PLC0415+ except ImportError:+ res["_note"] = "warp error needs OpenCV (pnpm eval:setup)"+ return res+ errs = []+ gray = [cv2.cvtColor(f, cv2.COLOR_RGB2GRAY) for f in frames]+ for a, b, ga, gb in zip(frames[:-1], frames[1:], gray[:-1], gray[1:]):+ fw = cv2.calcOpticalFlowFarneback(ga, gb, None, 0.5, 3, 15, 3, 5, 1.2, 0)+ bw = cv2.calcOpticalFlowFarneback(gb, ga, None, 0.5, 3, 15, 3, 5, 1.2, 0)+ e = maths.warp_error(a, b, fw, maths.valid_flow_mask(fw, bw))+ if not math.isnan(e):+ errs.append(e)+ if errs:+ res["warp"] = round(float(np.mean(errs)), 5)+ return res++ def m_lipsync(self, job, outs):+ clips = [o for o in outs if kind_of(o) == "video"]+ if not clips:+ return {"_note": "not a clip"}+ fps = 25.0+ frames, rate = video_frames(clips[0], fps=fps, max_frames=750, width=256)+ audio = audio_track(clips[0])+ source = "the clip's sound"+ if audio is None and job.get("inputs", {}).get("audio") and pathlib.Path(job["inputs"]["audio"]).exists():+ audio, source = audio_track(job["inputs"]["audio"]), "the voice track sent"+ if audio is None or len(frames) < 8:+ return {"_note": "no sound to compare the mouth with"}+ box = None+ try:+ from PIL import Image # noqa: PLC0415++ f = self.faces().largest(Image.fromarray(frames[len(frames) // 2]))+ box = f and f["box"]+ except Missing:+ pass+ h, w = frames.shape[1:3]+ if box:+ x0, y0, x1, y1 = box+ mouth = (int(y0 + 0.62 * (y1 - y0)), int(min(h, y1 + 0.05 * (y1 - y0))), int(x0 + 0.25 * (x1 - x0)), int(x0 + 0.75 * (x1 - x0)))+ else: # no detector: the lower middle of the frame, where a talking head's mouth usually is+ mouth = (int(0.55 * h), int(0.85 * h), int(0.3 * w), int(0.7 * w))+ region = frames[:, mouth[0] : max(mouth[0] + 2, mouth[1]), mouth[2] : max(mouth[2] + 2, mouth[3])].mean(axis=-1)+ motion = maths.motion_energy(region)+ env = maths.frame_envelope(audio, 16000, rate, len(frames))+ best = maths.best_lag_correlation(motion, env, max_lag=int(round(rate * 0.5)))+ res = {"lipsync": round(max(0.0, best["corr"]), 4), "lipsyncOffset": best["lag"], "_note": f"proxy: mouth-region motion vs {source}{' (face box)' if box else ' (fixed region, no face detector)'}"}+ cmd = os.environ.get("FUOBE_EVAL_SYNCNET_CMD")+ if cmd:+ import shlex # noqa: PLC0415+ import subprocess # noqa: PLC0415++ r = subprocess.run([*shlex.split(cmd), str(clips[0])], capture_output=True, text=True, timeout=1800)+ try:+ s = json.loads(r.stdout.strip().splitlines()[-1])+ res["syncnet"] = float(s["confidence"])+ res["syncnetOffset"] = s.get("offset")+ except (ValueError, KeyError, IndexError):+ res["_note"] += f"; SyncNet command gave no JSON ({(r.stderr or '').strip()[:120]})"+ return res+++def group_continuity(scorer: Scorer, run_dir: pathlib.Path, jobs: list[dict]) -> dict:+ """Shot lists: the middle frame of each shot, CLIP-embedded, against the next shot's."""+ groups: dict[str, list[dict]] = {}+ for j in jobs:+ if j.get("shot") and "continuity" in j.get("metrics", []):+ groups.setdefault(f"{j['caseId']}|{j['variant']}|s{j['seed']}", []).append(j)+ out = {}+ for key, members in groups.items():+ members.sort(key=lambda j: j["shot"]["index"])+ pics = []+ for j in members:+ outs = media_outputs(run_dir, j)+ if outs:+ p = images_of(outs[0], frames=3)+ if p:+ pics.append(p[len(p) // 2])+ if len(pics) >= 2:+ out[key] = {"continuity": round(maths.consecutive_similarity(scorer.clip().images(pics)), 4), "shots": len(pics), "jobs": [j["id"] for j in members]}+ return out+++def main(argv=None) -> int:+ ap = argparse.ArgumentParser(prog="fuobe_metrics.score", description="Score an evaluation run's outputs.")+ ap.add_argument("run_dir")+ ap.add_argument("--metrics", help="families to compute (default: each job's own list)")+ ap.add_argument("--device", default="cpu", help="cpu (default), cuda, mps or auto")+ ap.add_argument("--clip-model", default="clip-b32", choices=["clip-b32", "clip-l14"])+ ap.add_argument("--identity-model", default="auraface", choices=["auraface", "buffalo_l"])+ ap.add_argument("--accept-noncommercial", action="store_true", help="allow buffalo_l (non-commercial research licence)")+ ap.add_argument("--frames", type=int, default=24, help="frames sampled per clip for temporal metrics")+ ap.add_argument("--fps", type=float, default=8.0, help="sampling rate for temporal metrics")+ ap.add_argument("--force", action="store_true", help="recompute every job")+ args = ap.parse_args(argv)++ run_dir = pathlib.Path(args.run_dir).resolve()+ if not (run_dir / "run.json").exists():+ print(f"{run_dir} isn't a run folder (no run.json)", file=sys.stderr)+ return 2+ if not have_ffmpeg():+ print("The metrics need ffmpeg and ffprobe on PATH.", file=sys.stderr)+ return 2+ wanted = set(args.metrics.split(",")) if args.metrics else None+ if wanted and wanted - set(FAMILIES):+ print(f"Unknown metric {', '.join(sorted(wanted - set(FAMILIES)))} (have {', '.join(FAMILIES)})", file=sys.stderr)+ return 2++ out_file = run_dir / "metrics.json"+ previous = json.loads(out_file.read_text(encoding="utf8")) if out_file.exists() and not args.force else {}+ config = {"v": VERSION, "clip": args.clip_model, "identity": args.identity_model, "frames": args.frames, "fps": args.fps}+ scorer = Scorer(args)+ jobs = read_jobs(run_dir)+ results: dict[str, dict] = {}+ started = time.time()+ for i, job in enumerate(jobs, 1):+ fams = [f for f in job.get("metrics", []) if f in FAMILIES and f != "continuity" and (not wanted or f in wanted)]+ fp = fingerprint(run_dir, job, {**config, "fams": fams})+ old = previous.get("jobs", {}).get(job["id"])+ if old and old.get("_fp") == fp:+ results[job["id"]] = old+ continue+ outs = media_outputs(run_dir, job)+ row: dict = {"_fp": fp}+ notes = []+ for fam in fams:+ if fam in scorer.skipped:+ continue+ try:+ got = scorer.family(fam, job, outs)+ except Missing as e:+ scorer.skipped[fam] = str(e)+ continue+ except Exception as e: # one bad file shouldn't stop the run's other scores+ notes.append(f"{fam}: {e}")+ continue+ note = got.pop("_note", None)+ refs = got.pop("_refs", None)+ if note:+ notes.append(f"{fam}: {note}")+ if refs is not None:+ row[f"_{fam}Refs"] = refs+ row.update(got)+ if notes:+ row["_notes"] = notes+ results[job["id"]] = row+ print(f"[{i}/{len(jobs)}] {job['id']}: " + ", ".join(f"{k} {v}" for k, v in row.items() if not k.startswith("_")), file=sys.stderr)++ groups = {}+ if not wanted or "continuity" in wanted:+ try:+ groups = group_continuity(scorer, run_dir, jobs)+ except Missing as e:+ scorer.skipped["continuity"] = str(e)+ doc = {+ "version": VERSION,+ "computedAt": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),+ "device": scorer.device,+ "config": config,+ "models": {**previous.get("models", {}), **scorer.used},+ "skipped": scorer.skipped,+ "jobs": results,+ "groups": groups,+ "seconds": round(time.time() - started, 1),+ }+ tmp = out_file.with_suffix(".json.tmp")+ tmp.write_text(json.dumps(doc, indent=2, ensure_ascii=False) + "\n", encoding="utf8")+ tmp.replace(out_file)+ for fam, why in scorer.skipped.items():+ print(f"Skipped {fam}: {why}", file=sys.stderr)+ print(f"Wrote {out_file} ({len(results)} jobs, {len(groups)} groups)", file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/eval/metrics/requirements-identity.in b/scripts/eval/metrics/requirements-identity.innew file mode 100644index 00000000..6bdd9d44--- /dev/null+++ b/scripts/eval/metrics/requirements-identity.in@@ -0,0 +1,5 @@+# Optional: face identity (ArcFace-style embeddings). pnpm eval:setup --identity installs it.+# The default face model is AuraFace v1 (fal/AuraFace-v1, Apache-2.0, trained for commercial use).+# insightface's own buffalo_l pack is non-commercial research only: it is opt-in (--identity-model buffalo_l).+insightface==2.1 # MIT (the library; model packs have their own licences)+onnxruntime==1.31.0 # MITdiff --git a/scripts/eval/metrics/requirements-identity.txt b/scripts/eval/metrics/requirements-identity.txtnew file mode 100644index 00000000..cdf7c4c2--- /dev/null+++ b/scripts/eval/metrics/requirements-identity.txt@@ -0,0 +1,68 @@+# This file was autogenerated by uv via the following command:+# uv pip compile requirements-identity.in --python-version 3.12 -o requirements-identity.txt+certifi==2026.10.23+ # via requests+charset-normalizer==3.5.2+ # via requests+flatbuffers==25.12.19+ # via onnxruntime+idna==3.20+ # via requests+imageio==2.38.1+ # via scikit-image+insightface==2.1+ # via -r requirements-identity.in+lazy-loader==0.6+ # via scikit-image+ml-dtypes==0.6.0+ # via onnx+networkx==3.7+ # via scikit-image+numpy==2.5.4+ # via+ # imageio+ # insightface+ # ml-dtypes+ # onnx+ # onnxruntime+ # opencv-python+ # scikit-image+ # scipy+ # tifffile+onnx==1.23.2+ # via insightface+onnxruntime==1.31.0+ # via+ # -r requirements-identity.in+ # insightface+opencv-python==5.0.0.93+ # via insightface+packaging==26.3+ # via+ # lazy-loader+ # onnxruntime+ # scikit-image+pillow==13.0.0+ # via+ # imageio+ # scikit-image+protobuf==7.36.2+ # via+ # onnx+ # onnxruntime+requests==2.34.2+ # via insightface+scikit-image==0.26.0+ # via insightface+scipy==1.18.1+ # via+ # insightface+ # scikit-image+tifffile==2026.10.15+ # via scikit-image+tqdm==4.70.1+ # via insightface+typing-extensions==4.16.0+ # via onnx+urllib3==2.8.0+ # via requestsdiff --git a/scripts/eval/metrics/requirements-test.txt b/scripts/eval/metrics/requirements-test.txtnew file mode 100644index 00000000..129354fc--- /dev/null+++ b/scripts/eval/metrics/requirements-test.txt@@ -0,0 +1,4 @@+# The metric maths tests need only these (the model tests skip without torch and open_clip).+numpy==2.5.4+pillow==13.0.0+pytest==9.1.1diff --git a/scripts/eval/metrics/requirements.in b/scripts/eval/metrics/requirements.innew file mode 100644index 00000000..1fb96663--- /dev/null+++ b/scripts/eval/metrics/requirements.in@@ -0,0 +1,13 @@+# Metrics for the evaluation harness (scripts/eval). Top-level choices with their licences;+# requirements.txt is the full pinned set, compiled from this file:+# uv pip compile requirements.in --torch-backend cpu --python-version 3.12 -o requirements.txt+# pnpm eval:setup installs it into scripts/eval/metrics/.venv (git-ignored).+numpy==2.5.4 # BSD-3-Clause+pillow==13.0.0 # MIT-CMU (HPND)+torch==2.14.1 # BSD-3-Clause; CPU build by default, --torch-backend auto picks CUDA+torchvision==0.29.1 # BSD-3-Clause+open_clip_torch==3.3.0 # MIT. CLIP score, style and drift: ViT-B-32 laion2b_s34b_b79k (MIT weights)+ # aesthetic: ViT-L-14 openai (MIT weights) + LAION improved aesthetic predictor (Apache-2.0)+huggingface_hub==2.3.0 # Apache-2.0; downloads the weights at pinned revisions+opencv-python-headless==5.0.0.93 # Apache-2.0; optical flow for the warp error+pytest==9.1.1 # MIT; the metric testsdiff --git a/scripts/eval/metrics/requirements.txt b/scripts/eval/metrics/requirements.txtnew file mode 100644index 00000000..ccdf0e2c--- /dev/null+++ b/scripts/eval/metrics/requirements.txt@@ -0,0 +1,109 @@+# This file was autogenerated by uv via the following command:+# uv pip compile requirements.in --torch-backend cpu --python-version 3.12 -o requirements.txt+anyio==4.15.1+ # via httpx2+click==8.5.0+ # via huggingface-hub+filelock==4.2.4+ # via+ # huggingface-hub+ # torch+fsspec==2026.9.0+ # via+ # huggingface-hub+ # torch+ftfy==6.3.1+ # via open-clip-torch+h11==0.16.0+ # via httpcore2+hf-xet==1.7.0+ # via huggingface-hub+httpcore2==2.16.0+ # via httpx2+httpx2==2.16.0+ # via huggingface-hub+huggingface-hub==2.3.0+ # via+ # -r requirements.in+ # open-clip-torch+ # timm+idna==3.20+ # via+ # anyio+ # httpx2+iniconfig==2.3.1+ # via pytest+jinja2==3.1.6+ # via torch+markupsafe==3.0.4+ # via jinja2+mpmath==1.3.0+ # via sympy+networkx==3.7+ # via torch+numpy==2.5.4+ # via+ # -r requirements.in+ # opencv-python-headless+ # torchvision+open-clip-torch==3.3.0+ # via -r requirements.in+opencv-python-headless==5.0.0.93+ # via -r requirements.in+packaging==26.3+ # via+ # huggingface-hub+ # pytest+pillow==13.0.0+ # via+ # -r requirements.in+ # torchvision+pluggy==1.7.0+ # via pytest+pygments==2.21.0+ # via pytest+pytest==9.1.1+ # via -r requirements.in+pyyaml==6.0.3+ # via+ # huggingface-hub+ # timm+regex==2026.9.29+ # via open-clip-torch+safetensors==0.8.0+ # via+ # open-clip-torch+ # timm+setuptools==84.2.1+ # via torch+sympy==1.14.0+ # via torch+timm==1.0.30+ # via open-clip-torch+torch==2.14.1+cpu+ # via+ # -r requirements.in+ # open-clip-torch+ # timm+ # torchvision+torchvision==0.29.1+cpu+ # via+ # -r requirements.in+ # open-clip-torch+ # timm+tqdm==4.70.1+ # via+ # huggingface-hub+ # open-clip-torch+truststore==0.10.5+ # via+ # httpcore2+ # httpx2+typing-extensions==4.16.0+ # via+ # anyio+ # httpx2+ # huggingface-hub+ # torch+wcwidth==0.9.3+ # via ftfydiff --git a/scripts/eval/metrics/tests/conftest.py b/scripts/eval/metrics/tests/conftest.pynew file mode 100644index 00000000..874619ee--- /dev/null+++ b/scripts/eval/metrics/tests/conftest.py@@ -0,0 +1,6 @@+import pathlib+import sys++# The package sits next to the tests (scripts/eval/metrics/fuobe_metrics).+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+FIXTURES = pathlib.Path(__file__).resolve().parents[2] / "fixtures"diff --git a/scripts/eval/metrics/tests/test_maths.py b/scripts/eval/metrics/tests/test_maths.pynew file mode 100644index 00000000..4ec7192b--- /dev/null+++ b/scripts/eval/metrics/tests/test_maths.py@@ -0,0 +1,98 @@+"""The metric maths on tiny synthetic inputs (numpy only, no model)."""++import math++import numpy as np+import pytest++from fuobe_metrics import maths+++def test_cosine_and_clip_score():+ a = np.array([1.0, 0.0, 0.0])+ assert maths.cosine(a, a) == pytest.approx(1.0)+ assert maths.cosine(a, np.array([0.0, 1.0, 0.0])) == pytest.approx(0.0)+ assert maths.cosine(a, np.zeros(3)) == 0.0+ # CLIPScore is 100·cos, and never negative.+ assert maths.clip_score(np.array([3.0, 4.0]), np.array([3.0, 4.0])) == pytest.approx(100.0)+ assert maths.clip_score(np.array([1.0, 0.0]), np.array([-1.0, 0.0])) == 0.0+ frames = np.array([[1.0, 0.0], [0.0, 1.0]])+ assert maths.mean_clip_score(frames, np.array([1.0, 0.0])) == pytest.approx(50.0)+++def test_reference_similarity_centroid_and_nearest():+ refs = np.array([[1.0, 0.0], [0.0, 1.0]])+ s = maths.reference_similarity(np.array([1.0, 1.0]), refs)+ assert s["centroid"] == pytest.approx(1.0)+ assert s["nearest"] == pytest.approx(math.sqrt(0.5))+ assert s["n"] == 2+ far = maths.reference_similarity(np.array([-1.0, -1.0]), refs)+ assert far["centroid"] == pytest.approx(-1.0)+++def test_drift_is_zero_for_a_still_and_grows_with_change():+ still = np.tile([[0.2, 0.9, 0.1]], (6, 1))+ assert maths.drift(still) == {"mean": pytest.approx(0.0), "max": pytest.approx(0.0), "pairs": 5}+ rng = np.random.default_rng(0)+ shaky = rng.normal(size=(6, 32))+ d = maths.drift(shaky)+ assert d["mean"] > 0.5 and d["max"] >= d["mean"]+ assert maths.drift(np.ones((1, 3)))["pairs"] == 0+++def _texture(h=48, w=64, seed=1):+ rng = np.random.default_rng(seed)+ base = rng.random((h // 4, w // 4))+ return np.kron(base, np.ones((4, 4))) # blocky, so a 2-pixel shift is exact to interpolate+++def test_warp_error_is_near_zero_when_the_flow_explains_the_motion():+ f0 = _texture()+ f1 = np.roll(f0, 2, axis=1) # everything moves 2 px right+ flow = np.zeros(f0.shape + (2,))+ flow[..., 0] = 2.0+ inside = np.zeros(f0.shape, bool)+ inside[:, 2:-2] = True+ assert maths.warp_error(f0, f1, flow, inside) == pytest.approx(0.0, abs=1e-9)+ # With no flow, the same motion counts as error; flicker (new noise) counts even with the right flow.+ assert maths.warp_error(f0, f1, np.zeros_like(flow), inside) > 0.1+ flicker = f1 + np.random.default_rng(2).normal(0, 0.2, f1.shape)+ assert maths.warp_error(f0, flicker, flow, inside) > 0.1+ # 0–255 frames are put on the same 0–1 scale.+ assert maths.warp_error(f0 * 255, f1 * 255, np.zeros_like(flow), inside) == pytest.approx(maths.warp_error(f0, f1, np.zeros_like(flow), inside))+ assert math.isnan(maths.warp_error(f0, f1, flow, np.zeros(f0.shape, bool)))+++def test_valid_flow_mask_keeps_consistent_pixels_and_drops_ones_that_leave_the_frame():+ h, w = 20, 30+ fw = np.zeros((h, w, 2))+ fw[..., 0] = 3.0+ bw = -fw+ mask = maths.valid_flow_mask(fw, bw)+ assert mask[:, : w - 3].all()+ assert not mask[:, w - 2 :].any()+ # A backward flow that doesn't undo the forward one marks the pixels occluded.+ assert not maths.valid_flow_mask(fw, np.zeros_like(fw))[:, :10].any()+++def test_lip_sync_proxy_finds_the_offset_between_mouth_motion_and_voice():+ fps, sr, n = 25, 16000, 100+ t = np.arange(n * sr // fps) / sr+ syllables = (np.sin(2 * np.pi * 3 * t) > 0.3).astype(float)+ audio = syllables * np.sin(2 * np.pi * 200 * t)+ env = maths.frame_envelope(audio, sr, fps, n)+ assert env.shape == (n,) and env.max() > 0.5 and env.min() == 0.0+ # A mouth that opens with the voice, two frames late.+ mouth = np.roll(env, 2) + np.random.default_rng(3).normal(0, 0.02, n)+ best = maths.best_lag_correlation(mouth, env, max_lag=5)+ assert best["lag"] == 2 and best["corr"] > 0.9+ unrelated = np.random.default_rng(4).random(n)+ assert maths.best_lag_correlation(unrelated, env, max_lag=5)["corr"] < 0.4+++def test_motion_energy_and_continuity():+ frames = np.zeros((4, 2, 2))+ frames[2] = 1.0+ assert maths.motion_energy(frames).tolist() == [0.0, 0.0, 1.0, 1.0]+ assert maths.consecutive_similarity(np.array([[1.0, 0.0], [1.0, 0.0], [0.0, 1.0]])) == pytest.approx(0.5)+ assert math.isnan(maths.consecutive_similarity(np.array([[1.0, 0.0]])))diff --git a/scripts/eval/metrics/tests/test_media_and_models.py b/scripts/eval/metrics/tests/test_media_and_models.pynew file mode 100644index 00000000..70c50e60--- /dev/null+++ b/scripts/eval/metrics/tests/test_media_and_models.py@@ -0,0 +1,131 @@+"""Decoding (needs ffmpeg) and the model wrappers (need the metrics venv and cached weights)."""++import json+import os+import pathlib+import shutil+import subprocess++import numpy as np+import pytest+from conftest import FIXTURES++from fuobe_metrics import media++needs_ffmpeg = pytest.mark.skipif(not media.have_ffmpeg(), reason="ffmpeg isn't installed")+++def _clip(tmp_path, name="clip.mp4", seconds=2, size="160x96", audio=True):+ out = tmp_path / name+ cmd = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", f"testsrc=size={size}:rate=12:duration={seconds}"]+ if audio:+ cmd += ["-f", "lavfi", "-i", f"sine=frequency=440:duration={seconds}", "-shortest"]+ cmd += ["-pix_fmt", "yuv420p", str(out)]+ subprocess.run(cmd, check=True)+ return out+++def test_kind_of():+ assert media.kind_of("a/b.PNG") == "image"+ assert media.kind_of("x.svg") == "image"+ assert media.kind_of("x.mov") == "video"+ assert media.kind_of("x.wav") == "audio"+ assert media.kind_of("x.glb") is None+++def test_load_image_png():+ img = media.load_image(FIXTURES / "palette.png")+ assert img.mode == "RGB" and img.size == (500, 100)+++@needs_ffmpeg+def test_load_image_rasterises_svg(tmp_path):+ svg = tmp_path / "demo.svg"+ svg.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="64" height="32"><rect width="64" height="32" fill="#ff0000"/></svg>')+ img = media.load_image(svg)+ assert img.size == (64, 32)+ r, g, b = img.getpixel((10, 10))+ assert r > 200 and g < 50 and b < 50+++@needs_ffmpeg+def test_video_frames_audio_and_probe(tmp_path):+ clip = _clip(tmp_path)+ info = media.probe(clip)+ assert info["width"] == 160 and info["audio"] is True and abs(info["duration"] - 2) < 0.2+ frames, rate = media.video_frames(clip, fps=4, max_frames=32, width=64)+ assert frames.shape[1:] == (38, 64, 3) or frames.shape[1:] == (40, 64, 3)+ assert 7 <= len(frames) <= 9 and rate == 4+ few, rate2 = media.video_frames(clip, fps=24, max_frames=6, width=64)+ assert len(few) <= 6 and rate2 == pytest.approx(3.0, rel=0.1)+ sound = media.audio_track(clip)+ assert sound is not None and abs(len(sound) / 16000 - 2) < 0.1 and np.abs(sound).max() > 0.1+ assert media.audio_track(_clip(tmp_path, "silent.mp4", audio=False)) is None+ assert len(media.images_of(clip, frames=3)) == 3+++@needs_ffmpeg+def test_score_cli_on_a_run_without_models(tmp_path):+ """The scorer reads a run folder and writes metrics.json; with no metric asked for it still writes a valid file."""+ run = tmp_path / "run"+ (run / "outputs" / "j1").mkdir(parents=True)+ shutil.copy(FIXTURES / "palette.png", run / "outputs" / "j1" / "1.png")+ (run / "run.json").write_text(json.dumps({"runId": "r", "suite": "s"}))+ (run / "jobs.jsonl").write_text(json.dumps({"id": "j1", "status": "succeeded", "metrics": [], "outputs": [{"file": "outputs/j1/1.png"}]}) + "\n")+ from fuobe_metrics.score import main++ assert main([str(run)]) == 0+ doc = json.loads((run / "metrics.json").read_text())+ assert doc["version"] == 1 and "j1" in doc["jobs"] and doc["groups"] == {}+ assert main([str(run), "--metrics", "smell"]) == 2+++def _weights_cached(key):+ """Model tests run only when the weights are already in the cache (pnpm eval:setup --download), or FUOBE_EVAL_MODEL_TESTS=1."""+ from fuobe_metrics.models import CACHE++ return os.environ.get("FUOBE_EVAL_MODEL_TESTS") == "1" or any((CACHE / "hf").glob(f"models--{key.replace('/', '--')}"))+++@needs_ffmpeg+def test_clip_prefers_the_matching_caption():+ pytest.importorskip("torch")+ pytest.importorskip("open_clip")+ if not _weights_cached("laion/CLIP-ViT-B-32-laion2B-s34B-b79K"):+ pytest.skip("CLIP weights aren't cached (pnpm eval:setup --download)")+ from fuobe_metrics import maths+ from fuobe_metrics.models import Clip++ clip = Clip("clip-b32")+ img = clip.images([media.load_image(FIXTURES / "palette.png")])[0]+ texts = clip.texts(["five coloured stripes side by side", "a dog running on a beach"])+ assert maths.clip_score(img, texts[0]) > maths.clip_score(img, texts[1])+++@needs_ffmpeg+def test_aesthetic_scores_are_on_the_predictor_scale():+ pytest.importorskip("torch")+ pytest.importorskip("open_clip")+ if not _weights_cached("timm/vit_large_patch14_clip_224.openai"):+ pytest.skip("CLIP ViT-L/14 weights aren't cached (pnpm eval:setup --download)")+ from fuobe_metrics.models import Aesthetic, Clip++ a = Aesthetic(Clip("clip-l14"))+ s = a.scores([media.load_image(FIXTURES / "start-frame.png")])+ assert s.shape == (1,) and 0.0 < float(s[0]) < 10.0+++def test_faces_on_drawn_faces_do_not_crash():+ pytest.importorskip("insightface")+ if not _weights_cached("fal/AuraFace-v1"):+ pytest.skip("AuraFace weights aren't cached (pnpm eval:setup --identity --download)")+ from fuobe_metrics.models import Faces++ f = Faces("auraface")+ got = f.largest(media.load_image(FIXTURES / "character" / "drawn-face-1.png"))+ assert got is None or (got["embedding"].shape == (512,) and abs(np.linalg.norm(got["embedding"]) - 1) < 1e-3)+++def test_fixtures_are_where_the_tests_expect():+ assert (FIXTURES / "palette.png").exists()+ assert pathlib.Path(media.__file__).name == "media.py"