102 lines
4.7 KiB
Python
102 lines
4.7 KiB
Python
"""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]"""
|
|
import asyncio
|
|
import base64
|
|
import collections
|
|
import itertools
|
|
import json
|
|
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
|
|
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
|
|
|
|
|
|
async def main():
|
|
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
|
|
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)
|
|
ts = trials(n)
|
|
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4})})")
|
|
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]))
|
|
await b.close()
|
|
finally:
|
|
server.terminate()
|
|
|
|
|
|
asyncio.run(main())
|