Ring code v2: logo disc locator, projective rectification, animated dashes, lab pages, bench tool
This commit is contained in:
+183
@@ -0,0 +1,183 @@
|
||||
"""tiny chrome devtools protocol client: headless chrome, pages, eval, screencast"""
|
||||
import asyncio
|
||||
import base64
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
import websockets
|
||||
|
||||
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
|
||||
|
||||
|
||||
class Browser:
|
||||
def __init__(self, port=9333):
|
||||
self.port = port
|
||||
self.ids = itertools.count(1)
|
||||
self.pending = {}
|
||||
self.listeners = {}
|
||||
|
||||
async def start(self):
|
||||
self.profile = tempfile.mkdtemp(prefix="rv-chrome-")
|
||||
self.proc = subprocess.Popen([
|
||||
CHROME, "--headless=new", f"--remote-debugging-port={self.port}", f"--user-data-dir={self.profile}",
|
||||
"--no-first-run", "--no-default-browser-check", "--hide-scrollbars", "--mute-audio",
|
||||
"--disable-background-timer-throttling", "--disable-renderer-backgrounding",
|
||||
"--disable-backgrounding-occluded-windows", "--use-fake-ui-for-media-stream",
|
||||
"--force-color-profile=srgb", "--window-size=1920,1080", "about:blank",
|
||||
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
for _ in range(100):
|
||||
try:
|
||||
info = json.load(urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/version"))
|
||||
break
|
||||
except OSError:
|
||||
await asyncio.sleep(0.1)
|
||||
self.ws = await websockets.connect(info["webSocketDebuggerUrl"], max_size=None)
|
||||
self.reader = asyncio.create_task(self._read())
|
||||
|
||||
async def _read(self):
|
||||
async for raw in self.ws:
|
||||
m = json.loads(raw)
|
||||
if "id" in m:
|
||||
fut = self.pending.pop(m["id"], None)
|
||||
if fut and not fut.done():
|
||||
if "error" in m:
|
||||
fut.set_exception(RuntimeError(m["error"]))
|
||||
else:
|
||||
fut.set_result(m.get("result", {}))
|
||||
else:
|
||||
cb = self.listeners.get(m.get("sessionId"))
|
||||
if cb:
|
||||
cb(m["method"], m.get("params", {}))
|
||||
|
||||
async def send(self, method, params=None, session=None):
|
||||
i = next(self.ids)
|
||||
fut = asyncio.get_running_loop().create_future()
|
||||
self.pending[i] = fut
|
||||
msg = {"id": i, "method": method, "params": params or {}}
|
||||
if session:
|
||||
msg["sessionId"] = session
|
||||
await self.ws.send(json.dumps(msg))
|
||||
return await asyncio.wait_for(fut, 60)
|
||||
|
||||
async def page(self, width, height, dsf=1, mobile=False):
|
||||
tid = (await self.send("Target.createTarget", {"url": "about:blank", "newWindow": True}))["targetId"]
|
||||
sid = (await self.send("Target.attachToTarget", {"targetId": tid, "flatten": True}))["sessionId"]
|
||||
p = Page(self, sid, width, height, dsf)
|
||||
self.listeners[sid] = p._event
|
||||
for m in ("Page.enable", "Runtime.enable"):
|
||||
await p.send(m)
|
||||
await p.send("Page.setBypassCSP", {"enabled": True})
|
||||
await p.send("Emulation.setFocusEmulationEnabled", {"enabled": True})
|
||||
await p.send("Emulation.setDeviceMetricsOverride",
|
||||
{"width": width, "height": height, "deviceScaleFactor": dsf, "mobile": mobile})
|
||||
if mobile:
|
||||
await p.send("Emulation.setTouchEmulationEnabled", {"enabled": True, "maxTouchPoints": 5})
|
||||
return p
|
||||
|
||||
async def close(self):
|
||||
try:
|
||||
await asyncio.wait_for(self.send("Browser.close"), 5)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.proc.wait(5)
|
||||
except Exception:
|
||||
self.proc.kill()
|
||||
shutil.rmtree(self.profile, ignore_errors=True)
|
||||
|
||||
|
||||
class Page:
|
||||
def __init__(self, browser, sid, w, h, dsf):
|
||||
self.b, self.sid, self.w, self.h, self.dsf = browser, sid, w, h, dsf
|
||||
self.load = None
|
||||
self.frames = None
|
||||
|
||||
def send(self, method, params=None):
|
||||
return self.b.send(method, params, self.sid)
|
||||
|
||||
def _event(self, method, params):
|
||||
if method == "Page.loadEventFired" and self.load and not self.load.done():
|
||||
self.load.set_result(True)
|
||||
elif method == "Page.screencastFrame":
|
||||
if self.frames is not None:
|
||||
ts = params["metadata"].get("timestamp", time.time())
|
||||
path = os.path.join(self.frame_dir, f"{len(self.frames):06d}.jpg")
|
||||
with open(path, "wb") as f:
|
||||
f.write(base64.b64decode(params["data"]))
|
||||
self.frames.append((ts, path))
|
||||
asyncio.get_running_loop().create_task(
|
||||
self.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]}))
|
||||
|
||||
async def goto(self, url):
|
||||
self.load = asyncio.get_running_loop().create_future()
|
||||
await self.send("Page.navigate", {"url": url})
|
||||
await asyncio.wait_for(self.load, 20)
|
||||
|
||||
async def js(self, expr):
|
||||
r = await self.send("Runtime.evaluate", {"expression": expr, "awaitPromise": True, "returnByValue": True})
|
||||
if "exceptionDetails" in r:
|
||||
raise RuntimeError(r["exceptionDetails"].get("exception", {}).get("description", r["exceptionDetails"]))
|
||||
return r.get("result", {}).get("value")
|
||||
|
||||
async def on_new_document(self, source):
|
||||
await self.send("Page.addScriptToEvaluateOnNewDocument", {"source": source})
|
||||
|
||||
async def record(self, frame_dir):
|
||||
os.makedirs(frame_dir, exist_ok=True)
|
||||
self.frame_dir = frame_dir
|
||||
self.frames = []
|
||||
await self.send("Page.startScreencast", {"format": "jpeg", "quality": 90,
|
||||
"maxWidth": int(self.w * self.dsf), "maxHeight": int(self.h * self.dsf)})
|
||||
|
||||
async def stop(self):
|
||||
if getattr(self, "shooter", None):
|
||||
self.shooting = False
|
||||
try:
|
||||
await asyncio.wait_for(self.shooter, 3)
|
||||
except Exception:
|
||||
self.shooter.cancel()
|
||||
else:
|
||||
try:
|
||||
await asyncio.wait_for(self.send("Page.stopScreencast"), 3)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def record_shots(self, frame_dir, fps=24):
|
||||
"""screenshot polling: slower than screencast but honours deviceScaleFactor"""
|
||||
os.makedirs(frame_dir, exist_ok=True)
|
||||
self.frames, self.shooting = [], True
|
||||
|
||||
async def loop():
|
||||
while self.shooting:
|
||||
t = time.time()
|
||||
r = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": 90})
|
||||
path = os.path.join(frame_dir, f"{len(self.frames):06d}.jpg")
|
||||
with open(path, "wb") as f:
|
||||
f.write(base64.b64decode(r["data"]))
|
||||
self.frames.append((t, path))
|
||||
await asyncio.sleep(max(0, 1 / fps - (time.time() - t)))
|
||||
self.shooter = asyncio.get_running_loop().create_task(loop())
|
||||
|
||||
async def png(self, path, transparent=False):
|
||||
if transparent:
|
||||
await self.send("Emulation.setDefaultBackgroundColorOverride", {"color": {"r": 0, "g": 0, "b": 0, "a": 0}})
|
||||
r = await self.send("Page.captureScreenshot", {"format": "png"})
|
||||
with open(path, "wb") as f:
|
||||
f.write(base64.b64decode(r["data"]))
|
||||
|
||||
async def mouse(self, kind, x, y, button="left", clicks=1):
|
||||
await self.send("Input.dispatchMouseEvent",
|
||||
{"type": kind, "x": x, "y": y, "button": button, "clickCount": clicks})
|
||||
|
||||
async def type(self, text, rng, target="document.activeElement"):
|
||||
# write into the field directly: focus can drift between headless targets while screenshotting
|
||||
await self.js(f"window.__tt = {target}; __tt.focus()")
|
||||
for ch in text:
|
||||
await self.js("__tt.value += " + json.dumps(ch) + "; __tt.dispatchEvent(new Event('input', {bubbles: true}))")
|
||||
await asyncio.sleep(rng.uniform(0.05, 0.14) + (0.18 if ch == " " and rng.random() < 0.2 else 0))
|
||||
@@ -0,0 +1,96 @@
|
||||
"""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)
|
||||
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)
|
||||
print(f"codes read {ok}/{len(codes)} ({100 * ok / len(codes):.0f} %), median {sorted(r['ms'] for r in codes)[len(codes) // 2]} ms/frame")
|
||||
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())
|
||||
Reference in New Issue
Block a user