"""Evaluate the Vision Hands / HandPortal package headlessly (no webcam). Reproduces every number on the Hugging Face model card for Noor-Khan/vision-hands. Run from the repo root with a Python that has OpenCV + MediaPipe (e.g. the vh venv): python evaluate.py Writes metrics.json and samples/ next to this file. """ import json import subprocess import sys import time from pathlib import Path import cv2 import numpy as np ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT)) import portal_app # noqa: E402 from handportal import EFFECT_NAMES, EFFECTS, PinchTrigger # noqa: E402 from handportal.model import MODEL_SHA256, ensure_model, file_sha256 # noqa: E402 METRICS = {} def note(key, value): METRICS[key] = value print(f"{key}: {value}") def _photo(name): """Palm photos live in samples/ in the published repo (repo root in work/).""" for cand in (ROOT / "samples" / name, ROOT / name): if cand.exists(): return cand return ROOT / "samples" / name def make_test_frame(w=1280, h=720, seed=7): """Deterministic photo-like frame: gradient sky, shapes, seeded noise.""" rng = np.random.default_rng(seed) frame = np.zeros((h, w, 3), dtype=np.uint8) for y in range(h): frame[y, :, 0] = np.clip(200 - y * 0.18, 0, 255) # B gradient frame[y, :, 1] = np.clip(60 + y * 0.12, 0, 255) # G gradient frame[y, :, 2] = np.clip(30 + y * 0.2, 0, 255) # R gradient cv2.circle(frame, (w // 3, h // 2), 130, (40, 200, 240), -1) cv2.rectangle(frame, (w // 2, h // 4), (w * 3 // 4, h * 3 // 4), (220, 90, 60), -1) cv2.putText(frame, "HandPortal", (w // 4, h // 6), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 3, cv2.LINE_AA) noise = rng.integers(0, 28, size=(h, w, 3), dtype=np.uint8) return cv2.add(frame, noise) class FakeLandmark: def __init__(self, x, y): self.x, self.y = x, y def fake_hand(tip_x, tip_y): """21 fake landmarks; only index tip (8) and thumb tip (4) matter here.""" hand = [FakeLandmark(0.5, 0.5) for _ in range(21)] hand[8] = FakeLandmark(tip_x, tip_y) hand[4] = FakeLandmark(tip_x - 0.05, tip_y + 0.02) return hand def main(): import cv2 as _cv2 import mediapipe import PIL note("environment", { "python": sys.version.split()[0], "opencv": _cv2.__version__, "mediapipe": mediapipe.__version__, "numpy": np.__version__, "pillow": PIL.__version__, }) frame = make_test_frame() cv2.imwrite(str(ROOT / "test_frame.jpg"), frame) # --- 1. All 8 effects: shape/dtype preserved, change magnitude, timing effects = {} for name, fn in zip(EFFECT_NAMES, EFFECTS): for _ in range(3): fn(frame) # warmup times = [] for _ in range(10): t0 = time.perf_counter() out = fn(frame) times.append((time.perf_counter() - t0) * 1000) assert out.shape == frame.shape and out.dtype == np.uint8 diff = float(np.mean(np.abs(out.astype(np.float32) - frame.astype(np.float32)))) changed = float(np.mean(np.any(out != frame, axis=2))) effects[name] = { "mean_abs_diff": round(diff, 3), "pixels_changed_fraction": round(changed, 4), "ms_per_frame_mean": round(float(np.mean(times)), 2), } print(f" effect {name}: diff {diff:.3f}, changed {changed:.4f}, " f"{float(np.mean(times)):.2f} ms/frame") note("effects_1280x720", effects) # --- 2. Portal geometry: quad from two index fingertips hand_a = fake_hand(0.30, 0.30) hand_b = fake_hand(0.70, 0.65) quad = portal_app.build_quad_from_index_fingers(hand_a, hand_b, 1280, 720) assert quad is not None and quad.shape == (4, 2) note("quad_from_fingertips_px", [[round(float(v), 1) for v in pt] for pt in quad]) # NaN fingertip drops the frame instead of rendering garbage bad = fake_hand(float("nan"), 0.30) assert portal_app.build_quad_from_index_fingers(bad, hand_b, 1280, 720) is None note("quad_nan_fingertip_returns_none", True) # --- 3. Portal composite: effect only inside the quad thermal = EFFECTS[0] before = frame.copy() portal_app.render_portal_into_quad(frame, thermal, quad) changed = np.any(frame != before, axis=2) ys, xs = np.mgrid[0:720, 0:1280] inside = cv2.fillPoly(np.zeros((720, 1280), np.uint8), [quad.astype(np.int32)], 1).astype(bool) inside_changed = float(changed[inside].mean()) outside_changed = float(changed[~inside].mean()) note("portal_composite", { "inside_quad_changed_fraction": round(inside_changed, 4), "outside_quad_changed_fraction": round(outside_changed, 6), }) # alpha=0 hides the portal entirely; crossfade blends two effects frame2 = before.copy() portal_app.render_portal_into_quad(frame2, thermal, quad, alpha=0.0) assert np.array_equal(frame2, before) note("portal_alpha_0_unchanged", True) frame3 = before.copy() portal_app.render_portal_into_quad(frame3, thermal, quad, prev_effect_fn=EFFECTS[1], blend=0.5) cross_diff = float(np.mean(np.abs(frame3.astype(np.float32) - frame.astype(np.float32)))) note("portal_crossfade_blend_0.5_mean_abs_diff_vs_full_thermal", round(cross_diff, 3)) # glow + corner accents run and only touch the neighbourhood of the quad frame4 = before.copy() portal_app.draw_portal_glow(frame4, quad, portal_app.ACCENT, 0.8) portal_app.draw_corner_accents(frame4, quad, portal_app.ACCENT, t=1.0) glow_changed = float(np.mean(np.any(frame4 != before, axis=2))) note("portal_glow_and_corners_changed_fraction", round(glow_changed, 4)) # vignette: corners darker than centre vig = portal_app.make_vignette_layer(640, 360) assert vig.shape == (360, 640, 3) and vig.dtype == np.uint8 note("vignette", { "corner_mean": round(float(vig[0, 0].mean()), 1), "centre_mean": round(float(vig[180, 320].mean()), 1), }) # --- 4. QuadSmoother: EMA + NaN frame dropped, last good quad kept smoother = portal_app.QuadSmoother(alpha=0.5) q0 = np.zeros((4, 2), dtype=np.float32) q1 = np.full((4, 2), 10, dtype=np.float32) smoother.update(q0) smoothed = smoother.update(q1) assert np.allclose(smoothed, 5) kept = smoother.update(np.full((4, 2), np.nan, dtype=np.float32)) assert np.allclose(kept, 5) note("quad_smoother", {"ema_0_then_10_alpha_0.5": 5.0, "nan_frame_keeps_last_good": True}) # --- 5. PinchTrigger hysteresis (defaults 0.055 enter / 0.070 release) trigger = PinchTrigger() seq = [0.10, 0.04, 0.04, 0.04, 0.08, 0.04, float("nan"), 0.04, 0.10, 0.04] fired = [i for i, d in enumerate(seq) if trigger.update([d])] note("pinch_trigger", { "sequence": seq, "fired_at_indices": fired, "expected": "fires once per pinch; holding the pinch does not " "re-fire; a NaN reading is dropped and treated like a " "missing hand, so it re-arms a disarmed trigger and a " "pinch on the next good frame fires again", }) assert fired == [1, 5, 7, 9], fired trigger.adjust(0.01) assert abs(trigger.enter_threshold - 0.065) < 1e-9 trigger.reset() assert trigger.enter_threshold == 0.055 and trigger.armed note("pinch_trigger_adjust_reset", True) # --- 6. Hand detection on real photos (CC BY-SA 4.0 Wikimedia palms) import mediapipe as mp from mediapipe.tasks import python as mp_python from mediapipe.tasks.python import vision as mp_vision model_path = ensure_model(str(ROOT / "hand_landmarker.task")) note("model_checksum_matches", file_sha256(model_path) == MODEL_SHA256) base = mp_python.BaseOptions(model_asset_path=str(model_path)) options = mp_vision.HandLandmarkerOptions( base_options=base, num_hands=2, min_hand_detection_confidence=0.5) hands = {} for label, fname in [("palm_left", "palm_left.jpg"), ("palm_right", "palm_right.png")]: img = cv2.imread(str(_photo(fname))) assert img is not None, fname rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb) t0 = time.perf_counter() with mp_vision.HandLandmarker.create_from_options(options) as landmarker: result = landmarker.detect(mp_image) dt = (time.perf_counter() - t0) * 1000 n = len(result.hand_landmarks) assert n >= 1 hand = result.hand_landmarks[0] handed = result.handedness[0][0] score = float(handed.score) hands[label] = { "hands_detected": n, "landmarks": len(hand), "handedness": handed.category_name, "score": round(score, 3), "detect_ms": round(dt, 1), } print(f" {label}: {n} hand(s), {handed.category_name} {score:.3f}, " f"{len(hand)} landmarks, {dt:.1f} ms") # annotated sample ann = img.copy() for lm in hand: cv2.circle(ann, (int(lm.x * img.shape[1]), int(lm.y * img.shape[0])), 4, (0, 255, 255), -1) cv2.imwrite(str(ROOT / "samples" / f"{label}_annotated.jpg"), ann) note("hand_detection_palm_photos", hands) # controls: blank and random-noise images find no hands for label, img in [("blank", np.zeros((480, 640, 3), np.uint8)), ("noise", np.random.default_rng(3).integers( 0, 256, size=(480, 640, 3), dtype=np.uint8))]: rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb) with mp_vision.HandLandmarker.create_from_options(options) as landmarker: result = landmarker.detect(mp_image) note(f"hand_detection_{label}_image_hands", len(result.hand_landmarks)) assert len(result.hand_landmarks) == 0 # missing model file -> clear error, no silent download attempt here try: ensure_model(str(ROOT / "does_not_exist.task"), url="http://invalid.invalid/hand_landmarker.task") note("missing_model_raises", False) except RuntimeError as exc: note("missing_model_raises", str(exc)[:120]) # --- 7. Repo's own test suite (webcam-independent). The version test # only passes when the package is installed (it compares # handportal.__version__ against pyproject.toml), so install the # local copy first, exactly as CI does, then uninstall it again. subprocess.run([sys.executable, "-m", "pip", "install", "-e", ".", "--no-deps", "-q"], cwd=str(ROOT), capture_output=True, text=True, timeout=300) try: proc = subprocess.run( [sys.executable, "-m", "pytest", "-q", "tests"], cwd=str(ROOT), capture_output=True, text=True, timeout=600) finally: subprocess.run([sys.executable, "-m", "pip", "uninstall", "-y", "handportal"], cwd=str(ROOT), capture_output=True, text=True, timeout=120) tail = (proc.stdout + proc.stderr).strip().splitlines()[-3:] note("repo_test_suite", {"exit_code": proc.returncode, "tail": tail}) print("\n".join(tail)) # --- 8. Samples: 8-effect grid + portal before/after on a real photo samples = ROOT / "samples" samples.mkdir(exist_ok=True) photo = cv2.imread(str(_photo("palm_left.jpg"))) photo = cv2.resize(photo, (640, 360)) tiles = [photo] + [fn(photo) for fn in EFFECTS] labels = ["Original"] + EFFECT_NAMES grid = np.zeros((3 * 360, 3 * 640, 3), dtype=np.uint8) for i, tile in enumerate(tiles): r, c = divmod(i, 3) grid[r * 360:(r + 1) * 360, c * 640:(c + 1) * 640] = tile cv2.putText(grid, labels[i], (c * 640 + 14, r * 360 + 36), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 3, cv2.LINE_AA) cv2.putText(grid, labels[i], (c * 640 + 12, r * 360 + 34), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA) cv2.imwrite(str(samples / "effects_grid.jpg"), grid) # portal before/after on the same photo demo = photo.copy() quad_demo = portal_app.build_quad_from_index_fingers( fake_hand(0.25, 0.25), fake_hand(0.75, 0.80), 640, 360) after = photo.copy() portal_app.render_portal_into_quad(after, thermal, quad_demo) portal_app.draw_portal_glow(after, quad_demo, portal_app.ACCENT, 0.8) portal_app.draw_corner_accents(after, quad_demo, portal_app.ACCENT, t=1.0) pair = np.hstack([photo, after]) for txt, x in [("Before", 12), ("Portal: Thermal", 652)]: cv2.putText(pair, txt, (x + 2, 36), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 3, cv2.LINE_AA) cv2.putText(pair, txt, (x, 34), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 2, cv2.LINE_AA) cv2.imwrite(str(samples / "portal_before_after.jpg"), pair) for f in ["palm_left.jpg", "palm_right.png"]: src = _photo(f) if src.exists() and src.resolve() != (samples / f).resolve(): import shutil shutil.copy(src, samples / f) note("samples", ["effects_grid.jpg", "portal_before_after.jpg", "palm_left.jpg", "palm_right.png", "palm_left_annotated.jpg", "palm_right_annotated.jpg"]) with open(ROOT / "metrics.json", "w") as fh: json.dump(METRICS, fh, indent=2) print("\nmetrics.json written") if __name__ == "__main__": main()