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: faces found by YuNet (MIT); the SCRFD detector AuraFace ships is recorded apart and opt-in
Claude9f1e430cde0b
diff --git a/scripts/eval/README.md b/scripts/eval/README.mdindex 2478deab..cfcee0bc 100644--- a/scripts/eval/README.md+++ b/scripts/eval/README.md@@ -305,15 +305,16 @@ still has its timing and cost, and the report says why the scores are missing.| Prompt adherence | `clip` | higher | CLIPScore (100·cos) between the output and the case's own words. Clips are sampled at 4 frames | open_clip ViT-B/32 laion2B, **MIT** (`--clip-model clip-l14`: OpenAI ViT-L/14, MIT) || Aesthetic | `aesthetic` | higher | LAION improved aesthetic predictor v2 on CLIP ViT-L/14 embeddings, about 1–10 | head **Apache-2.0** (christophschuhmann/improved-aesthetic-predictor), CLIP MIT || Style vs references | `style`, `styleNearest` | higher | cosine of the output's embedding to the centroid of the look's reference set, and to the nearest reference | CLIP (default), or `--style-model dinov2`: DINOv2 ViT-S/14 via timm, **Apache-2.0** |-| Identity | `identity`, `faceRate` | higher | ArcFace-style face embeddings of the output against the person's photos; the share of frames with a face | **AuraFace v1** (fal, **Apache-2.0**, trained for commercial use) by default. insightface's `buffalo_l` is **non-commercial research only**: opt in with `--identity-model buffalo_l --accept-noncommercial` |+| Identity | `identity`, `faceRate` | higher | ArcFace-style face embeddings of the output against the person's photos; the share of frames with a face | **AuraFace v1**'s recognition model (fal, **Apache-2.0**, trained for commercial use), with faces found and aligned by **YuNet** (OpenCV Zoo, **MIT**). The SCRFD detector AuraFace's repo ships comes from insightface's model zoo (released for non-commercial research; the licence is unclear), so it runs only with `--face-detector scrfd`. insightface's `buffalo_l` is **non-commercial research only**: opt in with `--identity-model buffalo_l --accept-noncommercial` || Temporal consistency | `drift`, `driftMax`, `warp` | lower | frame-to-frame CLIP embedding drift (mean and worst jump), and a warp error: Farneback optical flow with a forward-backward occlusion mask | CLIP, OpenCV (Apache-2.0) |-| Lip-sync | `lipsync`, `lipsyncOffset` | higher | a proxy: mouth-region motion against the voice's loudness, with the best lag as the A/V offset | AuraFace's detector for the face box when identity is installed, else a fixed lower-centre region |+| Lip-sync | `lipsync`, `lipsyncOffset` | higher | a proxy: mouth-region motion against the voice's loudness, with the best lag as the A/V offset | the identity metric's face detector for the face box when identity is installed, else a fixed lower-centre region || SyncNet (optional) | `syncnet` | higher | runs only when `FUOBE_EVAL_SYNCNET_CMD` points at your own SyncNet. It isn't bundled because its weights' licence isn't stated | yours || Shot continuity | `continuity` | higher | CLIP similarity between consecutive shots of a film | CLIP || Time, cost, memory | `seconds`, `costUsd`, `vramGb` | lower | from the runner | — |Identity needs `pnpm eval:setup --identity`, which installs insightface and onnxruntime (MIT-libraries). Re-scoring is incremental: a job whose outputs and settings haven't changed keeps its+libraries). `metrics.json` records the face detector apart from the recognition model, each with its+licence, and compare warns when two runs used different detectors. Re-scoring is incremental: a job whose outputs and settings haven't changed keeps itsscores. `--metrics clip,style` re-scores only those families and keeps the others. `--force`re-scores everything.diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjsindex f88621d7..c97642b3 100644--- a/scripts/eval/eval.mjs+++ b/scripts/eval/eval.mjs@@ -29,7 +29,7 @@ const num = (v, name) => {class Usage extends Error {}const COMMON = { url: { type: "string" }, token: { type: "string" }, out: { type: "string" }, json: { type: "boolean" }, help: { type: "boolean", short: "h" } };-const SCORE = { "no-metrics": { type: "boolean" }, metrics: { type: "string" }, device: { type: "string" }, "clip-model": { type: "string" }, "style-model": { type: "string" }, "identity-model": { type: "string" }, "accept-noncommercial": { type: "boolean" }, force: { type: "boolean" } };+const SCORE = { "no-metrics": { type: "boolean" }, metrics: { type: "string" }, device: { type: "string" }, "clip-model": { type: "string" }, "style-model": { type: "string" }, "identity-model": { type: "string" }, "face-detector": { type: "string" }, "accept-noncommercial": { type: "boolean" }, force: { type: "boolean" } };const HELP = {run: `pnpm eval:run --suite <name> --engine demo|open|cloud [options]@@ -52,7 +52,7 @@ const HELP = {--comfy-url <url> ComfyUI's address, for memory and its own timings (open engine; default COMFYUI_URL)--label <text> a note for this run--no-metrics don't score afterwards · --no-report: don't write the report either`,- report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--style-model clip|dinov2] [--force]",+ report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--style-model clip|dinov2] [--face-detector yunet|scrfd] [--force]",review: "pnpm eval:review <runId|latest> [--against variants|references|<otherRunId>] [--port 4173] [--no-serve] [--limit n]",compare: "pnpm eval:compare <runA[:variant]> <runB[:variant]> [--fail-on clip,aesthetic] [--threshold 1|5%] [--per-case]",promote: `pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain] [--record [--apply-strengths] [--research file]]@@ -68,7 +68,7 @@ const HELP = {history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",trash: "pnpm eval:trash <runId> [--dry-run] moves the run's generations to that Fuobe's Trash (its results here stay)",- setup: "pnpm eval:setup [--identity] [--download [--dinov2]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",+ setup: "pnpm eval:setup [--identity] [--download [--dinov2] [--scrfd]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",};function usage() {@@ -128,7 +128,7 @@ const root = (values, env) => resultsDir(env, values.out);async function score(dir, v, ctx) {if (v["no-metrics"]) return null;ctx.note("Scoring the outputs…");- const r = await scoreRun(dir, { metrics: v.metrics, device: v.device, clipModel: v["clip-model"], styleModel: v["style-model"], identityModel: v["identity-model"], acceptNoncommercial: v["accept-noncommercial"], force: v.force, log: ctx.note, env: ctx.env });+ const r = await scoreRun(dir, { metrics: v.metrics, device: v.device, clipModel: v["clip-model"], styleModel: v["style-model"], identityModel: v["identity-model"], faceDetector: v["face-detector"], acceptNoncommercial: v["accept-noncommercial"], force: v.force, log: ctx.note, env: ctx.env });if (!r.ok) ctx.note(`Not scored: ${r.reason}. Timing and cost are in the report; pnpm eval:report ${path.basename(dir)} scores it later.`);return r;}@@ -417,7 +417,7 @@ async function covers(args, ctx) {}async function setup(args, ctx) {- const { values: v } = parse(args, { identity: { type: "boolean" }, dinov2: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });+ const { values: v } = parse(args, { identity: { type: "boolean" }, dinov2: { type: "boolean" }, scrfd: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });if (v.help) return ctx.print(HELP.setup), 0;const step = (cmd, a, opts = {}) => {ctx.note(`$ ${cmd} ${a.join(" ")}`);@@ -429,7 +429,7 @@ async function setup(args, ctx) {if (!fs.existsSync(path.join(METRICS_DIR, py))) step("uv", ["venv", ".venv", "--python", ">=3.11"]);step("uv", ["pip", "install", "--python", py, "-r", "requirements.txt", "--torch-backend", v["torch-backend"] ?? "cpu"]);if (v.identity) step("uv", ["pip", "install", "--python", py, "-r", "requirements-identity.txt"]);- if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : []), ...(v.dinov2 ? ["--dinov2"] : [])]);+ if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : []), ...(v.dinov2 ? ["--dinov2"] : []), ...(v.scrfd ? ["--scrfd"] : [])]);ctx.print(`Metrics ready in ${path.join(METRICS_DIR, ".venv")}${v.download ? "" : " (weights download on first use, or run pnpm eval:setup --download)"}.`);return 0;}diff --git a/scripts/eval/lib/compare.mjs b/scripts/eval/lib/compare.mjsindex b6be5800..63090cc6 100644--- a/scripts/eval/lib/compare.mjs+++ b/scripts/eval/lib/compare.mjs@@ -95,10 +95,12 @@ export function compareRuns(a, b, opts = {}) {const warnings = [];const ca = A.metrics?.config ?? {};const cb = B.metrics?.config ?? {};- for (const [k, label] of [["clip", "CLIP model"], ["style", "style model"], ["identity", "face model"]]) {+ for (const [k, label] of [["clip", "CLIP model"], ["style", "style model"], ["identity", "face model"], ["faceDetector", "face detector"]]) {// metrics.json from before --style-model scored style with CLIP.- const x = ca[k] ?? (k === "style" && A.metrics ? "clip" : null);- const y = cb[k] ?? (k === "style" && B.metrics ? "clip" : null);+ // metrics.json from before --face-detector found AuraFace's faces with its own SCRFD.+ const was = (c, doc) => c[k] ?? (k === "style" && doc ? "clip" : k === "faceDetector" && c.identity === "auraface" ? "scrfd" : null);+ const x = was(ca, A.metrics);+ const y = was(cb, B.metrics);if (x != null && y != null && x !== y) warnings.push(`the runs were scored with a different ${label} (${x} vs ${y}): rescore one with pnpm eval:report --force and the same options`);}return {diff --git a/scripts/eval/lib/metrics.mjs b/scripts/eval/lib/metrics.mjsindex 07e328ec..a8dfa713 100644--- a/scripts/eval/lib/metrics.mjs+++ b/scripts/eval/lib/metrics.mjs@@ -19,7 +19,7 @@ export function pythonCommand(env = process.env) {}/** 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, styleModel, identityModel, acceptNoncommercial, force, log = () => {}, env = process.env } = {}) {+export function scoreRun(dir, { metrics, device, clipModel, styleModel, identityModel, faceDetector, 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 = [@@ -32,6 +32,7 @@ export function scoreRun(dir, { metrics, device, clipModel, styleModel, identity...(clipModel ? ["--clip-model", clipModel] : []),...(styleModel ? ["--style-model", styleModel] : []),...(identityModel ? ["--identity-model", identityModel] : []),+ ...(faceDetector ? ["--face-detector", faceDetector] : []),...(acceptNoncommercial ? ["--accept-noncommercial"] : []),...(force ? ["--force"] : []),];diff --git a/scripts/eval/metrics/fuobe_metrics/download.py b/scripts/eval/metrics/fuobe_metrics/download.pyindex e8fe20ed..0abbf6b9 100644--- a/scripts/eval/metrics/fuobe_metrics/download.py+++ b/scripts/eval/metrics/fuobe_metrics/download.py@@ -12,7 +12,8 @@ from .registry import MODELSdef 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("--identity", action="store_true", help="also AuraFace (Apache-2.0) and YuNet (MIT) for identity and the lip-sync face box")+ ap.add_argument("--scrfd", action="store_true", help="also the SCRFD detector AuraFace ships (licence unclear), for --face-detector scrfd")ap.add_argument("--no-aesthetic", action="store_true", help="skip CLIP ViT-L/14 and the aesthetic head (about 1.7 GB)")ap.add_argument("--dinov2", action="store_true", help="also DINOv2 ViT-S/14 (Apache-2.0, 88 MB) for --style-model dinov2")args = ap.parse_args(argv)@@ -22,7 +23,9 @@ def main(argv=None) -> int:if args.dinov2:wanted += [("dinov2-small", MODELS["dinov2-small"]["file"])]if args.identity:- wanted += [("auraface", f) for f in MODELS["auraface"]["files"]]+ wanted += [("auraface", MODELS["auraface"]["recognition"]), ("yunet", MODELS["yunet"]["file"])]+ if args.scrfd:+ wanted += [("scrfd", MODELS["scrfd"]["file"])]for key, f in wanted:m = MODELS[key]print(f"{m['repo']} · {f} @ {m['revision'][:8]} ({m['licence']})", file=sys.stderr)diff --git a/scripts/eval/metrics/fuobe_metrics/maths.py b/scripts/eval/metrics/fuobe_metrics/maths.pyindex 158eb28c..f67ef345 100644--- a/scripts/eval/metrics/fuobe_metrics/maths.py+++ b/scripts/eval/metrics/fuobe_metrics/maths.py@@ -146,3 +146,13 @@ def consecutive_similarity(embs: np.ndarray) -> float:if len(e) < 2:return float("nan")return float(np.mean(np.sum(e[1:] * e[:-1], axis=1)))+++def yunet_face(row, scale: float = 1.0) -> dict:+ """One row of OpenCV's FaceDetectorYN (x, y, w, h, 5 landmarks, score) found on a picture resized by `scale`,+ in the original picture's pixels: {box: [x0, y0, x1, y1], kps: 5×2, score}. YuNet lists the subject's right+ eye, left eye, nose tip, right and left mouth corners: in the picture, left to right as ArcFace's template+ (and insightface's kps) expects them."""+ r = np.asarray(row, dtype=np.float64)+ x, y, w, h = r[:4] / scale+ return {"box": [float(x), float(y), float(x + w), float(y + h)], "kps": (r[4:14] / scale).reshape(5, 2), "score": float(r[14])}diff --git a/scripts/eval/metrics/fuobe_metrics/models.py b/scripts/eval/metrics/fuobe_metrics/models.pyindex e4663f6a..c19d3738 100644--- a/scripts/eval/metrics/fuobe_metrics/models.py+++ b/scripts/eval/metrics/fuobe_metrics/models.py@@ -139,14 +139,27 @@ class Aesthetic:class Faces:- """Face detection + ArcFace-style embeddings through insightface. AuraFace (Apache-2.0) by default; buffalo_l is opt-in."""+ """ArcFace-style face embeddings. AuraFace's recognition model (Apache-2.0) by default, with YuNet (MIT) finding+ and aligning the faces; --face-detector scrfd uses the SCRFD detector AuraFace ships instead (its licence is+ unclear). buffalo_l (non-commercial research) is opt-in and brings its own detector."""- def __init__(self, name: str = "auraface", device: str = "cpu"):+ def __init__(self, name: str = "auraface", device: str = "cpu", detector: str = "yunet"):try:from insightface.app import FaceAnalysis # noqa: PLC0415except ImportError as e:raise Missing("insightface isn't installed: run pnpm eval:setup --identity") from eproviders = ["CUDAExecutionProvider", "CPUExecutionProvider"] if device == "cuda" else ["CPUExecutionProvider"]+ self.name = name+ self.detector = detector if name == "auraface" else "own"+ self.app = None+ if self.detector == "yunet":+ import cv2 # noqa: PLC0415+ from insightface.model_zoo import get_model # noqa: PLC0415++ self.rec = get_model(_download("auraface", MODELS["auraface"]["recognition"]), providers=providers)+ self.rec.prepare(ctx_id=0 if device == "cuda" else -1)+ self.yunet = cv2.FaceDetectorYN.create(_download("yunet", MODELS["yunet"]["file"]), "", (320, 320), 0.6, 0.3, 5000)+ returnroot = CACHE / "insightface"if name == "auraface":folder = root / "models" / "auraface"@@ -155,13 +168,38 @@ class Faces:target = folder / fif not target.exists():target.symlink_to(_download("auraface", f))- self.name = nameself.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 _yunet_faces(self, bgr) -> list[dict]:+ """YuNet finds faces of about 10–300 px: try the picture at 640 px on its longest side, then at 320."""+ import cv2 # noqa: PLC0415++ from .maths import yunet_face # noqa: PLC0415++ h, w = bgr.shape[:2]+ for side in (640, 320):+ scale = min(1.0, side / max(h, w))+ img = cv2.resize(bgr, (max(1, round(w * scale)), max(1, round(h * scale))), interpolation=cv2.INTER_AREA) if scale < 1 else bgr+ self.yunet.setInputSize((img.shape[1], img.shape[0]))+ _, rows = self.yunet.detect(img)+ if rows is not None and len(rows):+ return [yunet_face(r, scale) for r in rows]+ return []+def largest(self, picture) -> dict | None:"""The largest face in a PIL picture: {embedding, box} or None."""- bgr = np.asarray(picture.convert("RGB"))[:, :, ::-1]+ bgr = np.ascontiguousarray(np.asarray(picture.convert("RGB"))[:, :, ::-1])+ if self.app is None:+ from insightface.utils import face_align # noqa: PLC0415++ faces = self._yunet_faces(bgr)+ if not faces:+ return None+ f = max(faces, key=lambda x: (x["box"][2] - x["box"][0]) * (x["box"][3] - x["box"][1]))+ crop = face_align.norm_crop(bgr, landmark=f["kps"], image_size=self.rec.input_size[0])+ emb = np.asarray(self.rec.get_feat(crop), dtype=np.float64).ravel()+ return {"embedding": emb / (np.linalg.norm(emb) or 1.0), "box": f["box"]}faces = self.app.get(bgr)if not faces:return Nonediff --git a/scripts/eval/metrics/fuobe_metrics/registry.py b/scripts/eval/metrics/fuobe_metrics/registry.pyindex 76c3217c..b7c0bfd5 100644--- a/scripts/eval/metrics/fuobe_metrics/registry.py+++ b/scripts/eval/metrics/fuobe_metrics/registry.py@@ -54,13 +54,32 @@ MODELS = {"licence": "Apache-2.0 (christophschuhmann/improved-aesthetic-predictor; a mirror of the original weights)","commercial": True,},+ # AuraFace's recognition model. Its card covers that model only: the SCRFD detector the repo also ships is+ # recorded on its own ("scrfd") and isn't used unless --face-detector scrfd asks for it."auraface": {"repo": "fal/AuraFace-v1","files": ["glintr100.onnx", "scrfd_10g_bnkps.onnx"],+ "recognition": "glintr100.onnx","revision": "af6d057c9b0ec4071d4c49c80e3539258798b609",- "licence": "Apache-2.0 (fal/AuraFace-v1, trained on commercially usable data; ships an SCRFD detector)",+ "licence": "Apache-2.0 (fal/AuraFace-v1's recognition model glintr100.onnx, trained on commercially usable data)","commercial": True,},+ # Face detectors for AuraFace. YuNet (default) has a clear permissive licence; SCRFD is what AuraFace's own+ # example uses, but the weights come from insightface's model zoo, released for non-commercial research.+ "yunet": {+ "repo": "opencv/face_detection_yunet",+ "file": "face_detection_yunet_2023mar.onnx",+ "revision": "3cc26e7f1014a5ee5d74a42acee58bafc9d0a310",+ "licence": "MIT (Shiqi Yu's YuNet, libfacedetection; OpenCV Zoo)",+ "commercial": True,+ },+ "scrfd": {+ "repo": "fal/AuraFace-v1",+ "file": "scrfd_10g_bnkps.onnx",+ "revision": "af6d057c9b0ec4071d4c49c80e3539258798b609",+ "licence": "unclear: SCRFD-10G from insightface's model zoo, whose pretrained models insightface releases for non-commercial research (AuraFace's card covers only its recognition model)",+ "commercial": None,+ },"buffalo_l": {"repo": "insightface model zoo (downloaded by insightface)","licence": "non-commercial research only (insightface model packs)",diff --git a/scripts/eval/metrics/fuobe_metrics/score.py b/scripts/eval/metrics/fuobe_metrics/score.pyindex 11b8ee7a..81d21b42 100644--- a/scripts/eval/metrics/fuobe_metrics/score.py+++ b/scripts/eval/metrics/fuobe_metrics/score.py@@ -108,8 +108,11 @@ class Scorer:name = self.args.identity_modelif 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}+ detector = getattr(self.args, "face_detector", "yunet")+ self._faces = Faces(name, self.device, detector)+ # The detector is recorded on its own: its licence isn't the recognition model's.+ found = {"detector": {**MODELS[detector], "key": detector}} if name == "auraface" else {}+ self.used["identity"] = {**MODELS[name], "key": name, **found}return self._faces# Metric families: each returns a dict of keys from registry.FAMILIES plus notes.@@ -274,6 +277,7 @@ def main(argv=None) -> int:ap.add_argument("--style-model", default="clip", choices=["clip", "dinov2"], help="image embeddings for style similarity")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("--face-detector", default="yunet", choices=["yunet", "scrfd"], help="finds faces for AuraFace: YuNet (MIT, default) or the SCRFD AuraFace ships (licence unclear)")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")@@ -293,7 +297,7 @@ def main(argv=None) -> int: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, "style": args.style_model, "identity": args.identity_model, "frames": args.frames, "fps": args.fps}+ config = {"v": VERSION, "clip": args.clip_model, "style": args.style_model, "identity": args.identity_model, "faceDetector": args.face_detector if args.identity_model == "auraface" else "buffalo_l", "frames": args.frames, "fps": args.fps}scorer = Scorer(args)jobs = read_jobs(run_dir)results: dict[str, dict] = {}diff --git a/scripts/eval/metrics/tests/test_maths.py b/scripts/eval/metrics/tests/test_maths.pyindex 4ec7192b..16f63d3b 100644--- a/scripts/eval/metrics/tests/test_maths.py+++ b/scripts/eval/metrics/tests/test_maths.py@@ -96,3 +96,15 @@ def test_motion_energy_and_continuity():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]])))+++def test_yunet_rows_come_back_in_the_pictures_pixels_with_the_eyes_left_to_right():+ # A face found on the picture at half size: box x, y, w, h, then right eye, left eye, nose, right and left mouth corners.+ row = [10, 20, 30, 40, 15, 30, 32, 30, 24, 40, 17, 50, 31, 50, 0.9]+ f = maths.yunet_face(row, scale=0.5)+ assert f["box"] == [20.0, 40.0, 80.0, 120.0]+ assert f["kps"].shape == (5, 2)+ # The subject's right eye is on the picture's left: ArcFace's template wants that one first.+ assert f["kps"][0][0] < f["kps"][1][0] and f["kps"][3][0] < f["kps"][4][0]+ assert f["kps"][2].tolist() == [48.0, 80.0]+ assert f["score"] == 0.9diff --git a/scripts/eval/metrics/tests/test_media_and_models.py b/scripts/eval/metrics/tests/test_media_and_models.pyindex 8ce9ae2c..451bd718 100644--- a/scripts/eval/metrics/tests/test_media_and_models.py+++ b/scripts/eval/metrics/tests/test_media_and_models.py@@ -123,15 +123,35 @@ def test_aesthetic_scores_are_on_the_predictor_scale():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)")+ if not _weights_cached("fal/AuraFace-v1") or not _weights_cached("opencv/face_detection_yunet"):+ pytest.skip("AuraFace and YuNet weights aren't cached (pnpm eval:setup --identity --download)")from fuobe_metrics.models import Facesf = Faces("auraface")+ assert f.detector == "yunet"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_yunet_aligns_faces_as_auraface_expects():+ """The same face found by YuNet (MIT, the default) and by the SCRFD AuraFace ships embeds alike: the landmarks are in+ the order ArcFace's alignment wants. Uses the group photo insightface ships as test data (not in this repo)."""+ insightface = pytest.importorskip("insightface")+ photo = pathlib.Path(insightface.__file__).parent / "data" / "images" / "t1.jpg"+ if not photo.exists():+ pytest.skip("insightface's sample photo isn't installed")+ if not _weights_cached("fal/AuraFace-v1") or not _weights_cached("opencv/face_detection_yunet"):+ pytest.skip("AuraFace and YuNet weights aren't cached (pnpm eval:setup --identity --download --scrfd)")+ from fuobe_metrics.models import Faces++ picture = media.load_image(photo)+ yunet = Faces("auraface", detector="yunet").largest(picture)+ scrfd = Faces("auraface", detector="scrfd").largest(picture)+ assert yunet["embedding"].shape == (512,) and abs(np.linalg.norm(yunet["embedding"]) - 1) < 1e-6+ assert all(abs(a - b) < 12 for a, b in zip(yunet["box"], scrfd["box"]))+ assert float(yunet["embedding"] @ scrfd["embedding"]) > 0.9++def test_fixtures_are_where_the_tests_expect():assert (FIXTURES / "palette.png").exists()assert pathlib.Path(media.__file__).name == "media.py"