"""ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome, runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell] env: SUITE=legacy,far,seq,neg (default all) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300 IV=700 FADE_K=0.3 (sequence code interval and wipe share) CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)""" import asyncio import base64 import collections import itertools import json import math import os import random import subprocess import sys from pathlib import Path import httpx ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tools")) from cdp import Browser # noqa: E402 from rotatyvote import ringcode # noqa: E402 PORT = 8200 V1 = bool(os.environ.get("V1")) rng = random.Random(11) def trials(n): out = [] grid = itertools.product([560, 420, 320, 250, 200], [0, 20, 35], [0, 1.2, 2.2], [(1.0, 1.0), (0.55, 1.12)]) for d, tilt, blur, (contrast, bright) in grid: for _ in range(n): secret, slot = rng.randbytes(32), rng.randrange(1 << 36) out.append({"d": d, "tilt": tilt, "axis": rng.uniform(0, 360), "blur": blur, "contrast": contrast, "bright": bright, "noise": 7, "dx": rng.uniform(-80, 80), "dy": rng.uniform(-50, 50), "theta": rng.uniform(0, 6.283), "anim": rng.uniform(0, 100), "bits": ringcode.render_bits(secret, "abcdefgh", 1000, slot), "token": ringcode.token(secret, "abcdefgh", 1000, slot)}) # harsh perspective (phone very close to the screen), for information for _ in range(n * 6): secret, slot = rng.randbytes(32), rng.randrange(1 << 36) out.append({"d": 420, "tilt": 25, "axis": rng.uniform(0, 360), "blur": 0.6, "contrast": 1, "bright": 1, "noise": 7, "dx": 0, "dy": 0, "theta": rng.uniform(0, 6.283), "anim": rng.uniform(0, 100), "dist": 1.6, "harsh": True, "bits": ringcode.render_bits(secret, "abcdefgh", 1000, slot), "token": ringcode.token(secret, "abcdefgh", 1000, slot)}) for _ in range(40): out.append({"nocode": True, "d": 0, "tilt": 0, "blur": rng.choice([0, 1.2]), "contrast": 1, "bright": 1, "noise": 7}) return out def code(r): secret, slot = r.randbytes(32), r.randrange(1 << 36) return {"bits": ringcode.render_bits(secret, "abcdefgh", 500, slot), "token": ringcode.token(secret, "abcdefgh", 500, slot)} # washed projector: (black level, white level) of the screen as the camera sees it WASH = {0.45: (80, 195), 0.3: (105, 181)} SENSORS = {1280: (1280, 720), 1920: (1920, 1080)} def camera(r, d, contrast, blur, sensor): """one phone looking at a projected code d px wide in a 1280 px frame, plus what a real room adds""" W, H = SENSORS[sensor] return {"W": W, "H": H, "d": d, "frac": d / 1280, "contrast": contrast, "wash": WASH[contrast], "blur": blur, "sensor": sensor, # optical blur is angular, pixel softness (demosaic, video codec) is per sensor pixel "oblur": blur, "pblur": 0.6 + 0.2 * blur, "cast": [r.uniform(0.9, 1.0), 1.0, r.uniform(0.95, 1.1)], "gain": r.uniform(0.85, 1.2), "room": r.choice(["dark", "dark", "bright"]), "band": r.choice([0, 0, 0.06, 0.1]), "bandPeriod": r.uniform(40, 200), "noise": r.uniform(4, 8), "axis": r.uniform(0, 360), "dx": r.uniform(-250, 250) * W / 1280, "dy": r.uniform(-120, 120) * W / 1280, "theta": r.uniform(0, 6.283), "anim": r.uniform(0, 100), "qseed": r.randrange(1 << 20)} def far_trials(n): r = random.Random(23) out = [] sizes = [int(x) for x in os.environ.get("FAR_D", "80,100,120,150,180").split(",")] for d, contrast, blur, tilt, sensor in itertools.product(sizes, [0.45, 0.3], [0.7, 1.5], [0, 20], [1280, 1920]): for _ in range(n): t = camera(r, d, contrast, blur, sensor) m = r.uniform(0, 1.5), r.uniform(0, 6.283) t.update(code(r), tilt=tilt, motion=[m[0] * math.cos(m[1]), m[0] * math.sin(m[1])], jpeg=r.choice([0, 0, 0.6])) out.append(t) return out def neg_trials(n): """nothing to read: no code on the screen, bare dark discs, discs with pie-like arcs around""" r = random.Random(31) out = [] for i in range(n): t = camera(r, r.choice([80, 120, 180, 300]), r.choice([0.45, 0.3]), r.choice([0.7, 1.5]), r.choice([1280, 1920])) t.update(tilt=r.choice([0, 20]), nocode=True, decoy=i % 3) out.append(t) return out def seqs(n): r = random.Random(47) out = [] for d, contrast, fps in itertools.product([60, 70, 80, 100, 120, 150], [0.45, 0.3], [15, 7]): for _ in range(n): s = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920) iv = int(os.environ.get("IV", "500")) s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=iv, shake=r.uniform(0.3, 1.2), fadeK=float(os.environ.get("FADE_K", "0.25")), tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * iv + r.uniform(0, iv * 0.8)) out.append(s) return out def table(rows, keys, pipes): for key in keys: vals = sorted({r[key] for r in rows}) for p in pipes: cells = [] for v in vals: sub = [r for r in rows if r[key] == v] cells.append(f"{v}: {100 * sum(r[p]['ok'] for r in sub) / len(sub):3.0f}%") print(f" {key:9s}{p:7s}", " ".join(cells)) async def chunks(p, fn, key, items, cfg, size): # cdp calls time out after 60 s out = [] for i in range(0, len(items), size): out += await p.js(f"{fn}({json.dumps({**cfg, key: items[i:i + size], 'seed': 1000 + i, 'v1': V1})})") return out async def run_legacy(p, n): ts = trials(n) res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4, 'v1': V1})})") harsh = [r for r in res if r.get("harsh")] print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}") codes = [r for r in res if not r.get("nocode") and not r.get("harsh")] for key in ("d", "tilt", "blur", "contrast"): agg = collections.defaultdict(lambda: [0, 0, 0]) for r in codes: a = agg[r[key]] a[0] += 1; a[1] += (r["found"] or 0) > 0; a[2] += r["ok"] print(f"{key:8s}", " ".join(f"{k}: ok {v[2]}/{v[0]}" for k, v in sorted(agg.items()))) ok = sum(r["ok"] for r in codes) ms = sorted(r['ms'] for r in res) print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), decode ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}") fails = [r for r in codes if not r["ok"]] print("failures (d, tilt, blur, contrast, found, score, errs):", [(r["d"], r["tilt"], r["blur"], r["contrast"], r["found"], r["score"], r.get("errs")) for r in fails[:16]]) wrong = [r for r in res if r["token"] and not r["ok"]] print("false tokens:", len(wrong), "(no-code frames:", sum(1 for r in res if r.get("nocode")), ")") out = ROOT / "tools" / "bench_out" out.mkdir(exist_ok=True) for i, r in enumerate(res[:4]): if r.get("png"): (out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1])) async def run_far(p, n, pipes, diag): ts = far_trials(n) res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes, "diag": diag, "keep": 3}, 10) print(f"\n== far + washed projector, single frames ({len(res)} frames), d = code diameter in a 1280 px wide frame ==") table(res, ("d", "contrast", "blur", "tilt", "sensor", "room"), pipes) for pn in pipes: ms = sorted(r[pn]["ms"] for r in res) wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"]) print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}, false tokens {wrong}") if diag: print(f" where {diag} resolution frames break (truth substituted stage by stage):") for d in sorted({r["d"] for r in res}): sub = [r["diag"] for r in res if r["d"] == d] good = [x for x in sub if x["rank"] in range(4) and x.get("candOk")] st = collections.Counter(x["stage"] + ("/" + x["loc"] if x["stage"] == "locate" else "") for x in sub if x not in good) print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}" f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})" f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels") print(" bit errors with true geometry per decision rule, and bleed model (own, ring neighbours, adjacent rings, residual):") for d in sorted({r["d"] for r in res}): labs = [r["diag"]["lab"] for r in res if r["d"] == d and "isi" in r["diag"]["lab"]] keys = [k for k in labs[0] if k != "isi"] isi = [sum(x["isi"][i] for x in labs) / len(labs) for i in range(5)] print(f" d {d}: " + " ".join(f"{k} {sum(x.get(k, 0) for x in labs) / len(labs):.1f}" for k in keys) + f" | own {isi[1]:.2f} ang {isi[2]:.2f} rad {isi[3]:.2f} resid {isi[4]:.2f}") out = ROOT / "tools" / "bench_out" out.mkdir(exist_ok=True) for i, r in enumerate(res[:3]): if r.get("png"): (out / f"far_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1])) return res async def run_neg(p, n, pipes): ts = neg_trials(n) res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes}, 10) print(f"\n== negatives ({len(res)} frames without a code) ==") for pn in pipes: print(f" {pn}: false tokens {sum(1 for r in res if r[pn]['token'])}") async def run_seq(p, n, pipes): ss = seqs(n) res = await chunks(p, "runSeq", "seqs", ss, {"pipes": pipes}, 1) print(f"\n== far sequences: 6 s = 12 tokens shown, 1920x1080 sensor, hand shake ({len(res)} sequences) ==") for key in ("d", "contrast", "fps"): for pn in pipes: cells = [] for v in sorted({r[key] for r in res}): sub = [r[pn] for r in res if r[key] == v] done = sorted(x["first5"] for x in sub if x["first5"] is not None) med = f"{done[len(done) // 2]:.1f}s" if done else "-" cells.append(f"{v}: {sum(x['got'] for x in sub) / len(sub):4.1f} tok, 5 in 6s {100 * len(done) / len(sub):3.0f}% ({med})") print(f" {key:9s}{pn:7s}", " ".join(cells)) for pn in pipes: print(f" {pn}: false tokens {sum(r[pn]['false'] for r in res)}, ms/frame {sum(r[pn]['ms'] for r in res) / len(res):.1f}") async def main(): n = int(sys.argv[1]) if len(sys.argv) > 1 else 3 suites = os.environ.get("SUITE", "legacy,far,seq,neg").split(",") pipes = os.environ.get("PIPES", "legacy" if V1 else "scan").split(",") env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"} server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: for _ in range(100): try: httpx.get(f"http://127.0.0.1:{PORT}/api/config", timeout=0.5) break except httpx.HTTPError: await asyncio.sleep(0.1) b = Browser(9336) await b.start() p = await b.page(960, 720) throttle = float(os.environ.get("CPU", "1")) if throttle > 1: # rough low-end phone: chrome devtools cpu slowdown factor await p.send("Emulation.setCPUThrottlingRate", {"rate": throttle}) await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html") for _ in range(50): if await p.js("!!window.benchReady"): break await asyncio.sleep(0.1) if "legacy" in suites: await run_legacy(p, n) if "far" in suites: await run_far(p, n, pipes, os.environ.get("DIAG")) if "seq" in suites: await run_seq(p, max(1, n // 2), pipes) if "neg" in suites: await run_neg(p, int(os.environ.get("NEG", "300")), pipes) await b.close() finally: server.terminate() if __name__ == "__main__": asyncio.run(main())