From 7a0c1b9e378d3c5a012e2b9572ba2ada057b56fb Mon Sep 17 00:00:00 2001 From: Avi Shor Date: Tue, 1 Dec 2026 19:45:27 +0200 Subject: [PATCH] Python port: add photo reader, library docs, examples, pyproject --- ports/python/.gitignore | 5 + ports/python/README.md | 67 +- ports/python/examples/encode_decode.py | 21 + ports/python/examples/read_photo.py | 13 + ports/python/pyproject.toml | 19 + ports/python/reader/prism_chain.py | 859 +++++++ ports/python/reader/prism_reader.py | 3100 ++++++++++++++++++++++++ ports/python/reader/read.py | 64 + 8 files changed, 4145 insertions(+), 3 deletions(-) create mode 100644 ports/python/.gitignore create mode 100644 ports/python/examples/encode_decode.py create mode 100644 ports/python/examples/read_photo.py create mode 100644 ports/python/pyproject.toml create mode 100644 ports/python/reader/prism_chain.py create mode 100644 ports/python/reader/prism_reader.py create mode 100644 ports/python/reader/read.py diff --git a/ports/python/.gitignore b/ports/python/.gitignore new file mode 100644 index 0000000..18d151d --- /dev/null +++ b/ports/python/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.pyc +build/ +*.egg-info/ +hello.png diff --git a/ports/python/README.md b/ports/python/README.md index e64d28e..f1b6e76 100644 --- a/ports/python/README.md +++ b/ports/python/README.md @@ -16,8 +16,8 @@ Comb Code by Avi Shor. Free to use, with or without credit. See LICENSE.md in th filled-corner gap pattern, fixed ring and pilot cells — exactly as the live site. - **Decoder**: reads a clean/perfect PNG produced by any conforming encoder (this port, the Java port, or the live site's creator) and returns the payload - bytes with header CRC-4 and payload CRC-32 verification. This is not the full - robust camera pipeline (no perspective/glare/blur recovery). + bytes with header CRC-4 and payload CRC-32 verification. `decodePNG` is for clean + images; photos go through the reader (see Photo reader). - **CLI** for both. ## Usage @@ -57,7 +57,7 @@ As a library: `import prism` → `prism.encode(payload, size=-1, ecc=1, mode=0)` ## Known limits (honest) - The decoder expects a clean, axis-aligned PNG straight from an encoder. Photos - of codes need the site's full reader. + of codes need the reader in `reader/`. - The live site's own readers currently fail on the largest multi-block clean codes (e.g. ~1 KB+ at size 4-5) **even on PNGs the site's own creator made**; this decoder reads those fine. That is a live-reader limitation, not a port @@ -98,3 +98,64 @@ Key files accept this port's JSON and the live site's `{"publicKey":{...},"priva Python; Python-sealed (128 MiB/t=3) opens in JS. - AES-GCM matches NIST vectors; Argon2id matches hash-wasm byte for byte; `strength()` matches the JS heuristic exactly on the tested set. + +## Install + +The encoder, decoder and Comb Code Secure need only the standard library +(Python 3.8+). Copy the modules, or from this directory: + +```bash +pip install . +``` + +The photo reader also needs numpy and Pillow: `pip install ".[reader]"`. + +## Example + +`examples/encode_decode.py`: + +```python +import prism + +png, _ = prism.encodePNG("Hello from Comb Code".encode("utf-8"), r=12) +payload, info = prism.decodePNG(png) +print(payload.decode("utf-8")) +``` + +## API reference (`prism`) + +- `prism.encode(payload, size=-1, ecc=1, mode=0, type_=0, logo=0)` returns a code + object. `size` -1 is automatic, 0..5 fixed; `ecc` 0..3 is 10/20/30/40% repair + data; `mode` 0 color, 1 black-and-white; `type_` 0 text, 1 binary. +- `prism.encodePNG(payload, r=12, **kw)` returns `(png_bytes, code)`; `r` is pixels + per cell unit. +- `prism.decodePNG(png_bytes)` returns `(payload, info)`. The payload is only + returned when the header CRC-4 and payload CRC-32 pass. +- `prism.capacity(size, ecc, mode)` returns the payload capacity. + +## Photo reader + +`reader/` reads codes from photos: detection, hypothesis search, Reed-Solomon +recovery, palette-mix and distance-fit recovery, and the page retry chain. It is a +port of the live reader (`fast-reader.html`). + +```python +import sys; sys.path.insert(0, "reader") +from PIL import Image +import read + +result = read.read(Image.open("photo.jpg").convert("RGBA")) +print(bytes(result["bytes"]).decode("utf-8")) +``` + +`examples/read_photo.py photo.jpg` does the same from the command line. It raises +when no code is read. + +Limits: canvas resizes in the retry chain are approximated with Pillow, time budgets +are not enforced, and the reader is slow on hard photos (blurred scenes can take +minutes). Synthetic bench scenes only, no physical-camera tests. + +## License + +Comb Code, Copyright (c) 2026 Avi Shor. Free to use, with or without credit. +No warranty. diff --git a/ports/python/examples/encode_decode.py b/ports/python/examples/encode_decode.py new file mode 100644 index 0000000..56d1c5d --- /dev/null +++ b/ports/python/examples/encode_decode.py @@ -0,0 +1,21 @@ +# Comb Code Python example: encode a text payload to a PNG, decode it back. +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) +import prism + +text = 'Hello from Comb Code' + +# Encode: automatic size, 20% repair data, color mode, 12 px per cell unit. +png, _ = prism.encodePNG(text.encode('utf-8'), r=12) +with open('hello.png', 'wb') as f: + f.write(png) +print('encoded', len(text), 'bytes -> hello.png') + +# Decode it back. The payload is only returned when its CRC-32 passes. +payload, info = prism.decodePNG(png) +decoded = payload.decode('utf-8') +print('decoded', len(decoded), 'bytes:', decoded) +print('round-trip', 'OK' if decoded == text else 'MISMATCH') +sys.exit(0 if decoded == text else 1) diff --git a/ports/python/examples/read_photo.py b/ports/python/examples/read_photo.py new file mode 100644 index 0000000..b573e1d --- /dev/null +++ b/ports/python/examples/read_photo.py @@ -0,0 +1,13 @@ +# Comb Code Python example: read a code from a photo. +# usage: python3 examples/read_photo.py photo.jpg +# Needs numpy and Pillow (pip install numpy pillow). +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'reader')) +from PIL import Image +import read + +img = Image.open(sys.argv[1]).convert('RGBA') +result = read.read(img) +print(bytes(result['bytes']).decode('utf-8', 'replace')) diff --git a/ports/python/pyproject.toml b/ports/python/pyproject.toml new file mode 100644 index 0000000..c01706b --- /dev/null +++ b/ports/python/pyproject.toml @@ -0,0 +1,19 @@ +[build-system] +requires = ["setuptools>=61"] +build-backend = "setuptools.build_meta" + +[project] +name = "comb-code" +version = "1.0.0" +description = "Comb Code encoder, decoder, Comb Code Secure and photo reader." +readme = "README.md" +requires-python = ">=3.8" +authors = [{ name = "Avi Shor" }] +license = { text = "Free to use, with or without credit" } +urls = { Homepage = "https://getcombcode.github.io/" } + +[project.optional-dependencies] +reader = ["numpy", "pillow"] + +[tool.setuptools] +py-modules = ["prism", "prism_secure", "prism_secure_cli"] diff --git a/ports/python/reader/prism_chain.py b/ports/python/reader/prism_chain.py new file mode 100644 index 0000000..9063576 --- /dev/null +++ b/ports/python/reader/prism_chain.py @@ -0,0 +1,859 @@ +# Page retry chain of the live reader (27 filters), Python port. Needs numpy and Pillow. +# Pixel filters are exact (Uint8ClampedArray = clamp + round-half-even). +# Canvas drawImage resizes are approximated with Pillow: smoothingQuality 'high' -> +# LANCZOS, smoothingEnabled false -> NEAREST. Browsers use their own resampling, so +# the zoomcrop / zoomauto / zooman outputs are not pixel-identical to the page. +import numpy as np +from PIL import Image + +def _u8c(a): + # Uint8ClampedArray store: clamp 0..255, round half to even + return np.clip(np.rint(a), 0, 255).astype(np.uint8) + +def _to_rgba(img): + return img.convert('RGBA') if isinstance(img, Image.Image) else img + +def _arr(img): + if isinstance(img, Img): + return img.a + if isinstance(img, np.ndarray): + return img + return np.frombuffer(img.tobytes(), dtype=np.uint8).reshape(img.height, img.width, 4).copy() + +class Img: + __slots__ = ('a',) + def __init__(self, a): + self.a = a # HxWx4 uint8 + @property + def width(self): return self.a.shape[1] + @property + def height(self): return self.a.shape[0] + def to_pil(self): return Image.fromarray(self.a, 'RGBA') + +def lift(img): + a = _arr(img); h, w = a.shape[:2] + d = a.reshape(-1, 4).astype(np.float64) + hist = np.bincount(((d[:, 0]*299 + d[:, 1]*587 + d[:, 2]*114) / 1000).astype(np.int64), minlength=256) + acc = 0; hi = 255; th = w*h*0.98 + for v in range(256): + acc += int(hist[v]) + if acc >= th: hi = v; break + g = 255 / max(30, hi) + o = a.copy().reshape(-1, 4) + o[:, :3] = _u8c(np.minimum(255, a.reshape(-1, 4)[:, :3].astype(np.float64) * g)) + o[:, 3] = 255 + return Img(o.reshape(h, w, 4)) + +def liftdn(img): + a = _arr(lift(img)) + h, w = a.shape[:2] + d = a[:, :, :3].astype(np.float64) + wt = np.array([1, 4, 6, 4, 1], dtype=np.float64) + tmp = np.zeros((h, w, 3)) + for dx in range(-2, 3): + xs = np.clip(np.arange(w) + dx, 0, w-1) + tmp += d[:, xs, :] * wt[dx+2] + tmp = (tmp / wt.sum()).astype(np.float32).astype(np.float64) # Float32Array store + o = np.zeros((h, w, 3)) + for dy in range(-2, 3): + ys = np.clip(np.arange(h) + dy, 0, h-1) + o += tmp[ys, :, :] * wt[dy+2] + o /= wt.sum() + out = np.dstack([_u8c(o), np.full((h, w), 255, np.uint8)]) + return Img(out) + +def _zoomcrop(img, frac, scale): + # canvas drawImage(smoothing 'high') approximation: LANCZOS + a = _arr(img); h, w = a.shape[:2] + s = round(min(w, h) * frac) + x0 = round((w - s) / 2); y0 = round((h - s) / 2) + S = round(s * scale) + pil = Image.fromarray(a[y0:y0+s, x0:x0+s], 'RGBA') + return Img(np.array(pil.resize((S, S), Image.LANCZOS))) + +def zoom(img): + return _zoomcrop(img, 0.45, 3) + +def _unsharp(img, amt): + a = _arr(img).astype(np.float64); h, w = a.shape[:2] + d = a[:, :, :3] + blur = np.zeros_like(d); n = np.zeros((h, w, 1)) + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + ys = slice(max(0, dy), h + min(0, dy)); xs = slice(max(0, dx), w + min(0, dx)) + yt = slice(max(0, -dy), h - max(0, dy)); xt = slice(max(0, -dx), w - max(0, dx)) + blur[yt, xt] += d[ys, xs]; n[yt, xt] += 1 + blur /= n + o = _u8c(d + amt * (d - blur)) + return Img(np.dstack([o, np.full((h, w), 255, np.uint8)])) + +def _edge_grid(a): + h, w = a.shape[:2] + gw = max(32, round(w / 8)); gh = max(32, round(h / 8)) + G = np.zeros((gh, gw)) + d = a.astype(np.float64) + for gy in range(gh): + for gx in range(gw): + x = min(w-2, round(gx*w/gw)); y = min(h-2, round(gy*h/gh)) + l1 = .299*d[y, x, 0]+.587*d[y, x, 1]+.114*d[y, x, 2] + lx = .299*d[y, x+1, 0]+.587*d[y, x+1, 1]+.114*d[y, x+1, 2] + ly = .299*d[y+1, x, 0]+.587*d[y+1, x, 1]+.114*d[y+1, x, 2] + G[gy, gx] = np.float32(abs(l1-lx)+abs(l1-ly)) + return G, gw, gh + +def _zoomscan(img, cap, mult, smooth): + a = _arr(img); h, w = a.shape[:2] + G, gw, gh = _edge_grid(a) + best = None + for sOrig in (50, 80, 120, 170): + sg = max(3, round(sOrig/w*gw)) + for gy in range(0, gh-sg+1, 2): + for gx in range(0, gw-sg+1, 2): + s = G[gy:gy+sg, gx:gx+sg].sum() + norm = s/(sg*sg) + if best is None or norm > best[0]: + best = (norm, gx, gy, sg) + _, gx, gy, sg = best + px = gx/gw*w; py = gy/gh*h; ps = sg/gw*w + m = ps*0.8 + x0 = max(0, round(px-m)); y0 = max(0, round(py-m)) + side = min(min(w-x0, h-y0), round(ps+2*m)) + S = min(cap, round(side*mult)) + pil = Image.fromarray(a[y0:y0+side, x0:x0+side], 'RGBA') + return pil.resize((S, S), Image.LANCZOS if smooth else Image.NEAREST) + +def zoomauto(img): + # canvas smoothing 'high' approximation: LANCZOS + return Img(np.array(_unsharp(Img(np.array(_zoomscan(img, 1200, 5, True))), 1.0).a)) + +def zooman(img): + # canvas smoothing off: NEAREST (exact) + return Img(np.array(_zoomscan(img, 1400, 6, False))) + +def crplain(img): + a = _arr(img); h, w = a.shape[:2] + d = a[:, :, :3].astype(np.float64) + lum = (d.sum(axis=2) / 3).astype(np.float32).astype(np.float64) + amp = (d.max(axis=2) - d.min(axis=2)).astype(np.float32).astype(np.float64) + R = max(4, round(min(w, h)/12)) + bl = np.zeros((h, w)) + for y in range(h): + s = 0.0 + for x in range(w): + if x+R < w: s += amp[y, x+R] + if x-R-1 >= 0: s -= amp[y, x-R-1] + bl[y, x] = np.float32(s / (min(w-1, x+R) - max(0, x-R-1))) + tmp = np.zeros((h, w)) + for x in range(w): + s = 0.0 + for y in range(h): + if y+R < h: s += bl[y+R, x] + if y-R-1 >= 0: s -= bl[y-R-1, x] + tmp[y, x] = np.float32(s / (min(h-1, y+R) - max(0, y-R-1))) + k = np.minimum(6, np.maximum(1, 90/np.maximum(18, tmp))) + k = np.where(lum < 190, 1.0, k) + o = lum[..., None] + (d - lum[..., None]) * k[..., None] + m2 = o.max(axis=2) + over = m2 > 255 + o[over] *= (255/m2[over])[..., None] + return Img(np.dstack([_u8c(o), np.full((h, w), 255, np.uint8)])) + +# ===== shared convolution helpers (Float32Array stores, f64 accumulate) ===== + +def gk(sig): + r = min(16, int(np.ceil(sig * 3))) + k = np.zeros(2 * r + 1) + s = 0.0 + for i in range(-r, r + 1): + v = float(np.exp(-i * i / (2 * sig * sig))) + k[i + r] = v + s += v + k /= s + return k.astype(np.float32), r + +def cv1(src, W, H, k, r, horiz): + # src: (H*W*3) float64 view of the f32 array values; JS accumulates f64, stores f32 + out = np.zeros(W * H * 3) + s3 = src.reshape(H, W, 3) + o3 = out.reshape(H, W, 3) + for i in range(-r, r + 1): + w = float(k[i + r]) + if horiz: + xs = np.clip(np.arange(W) + i, 0, W - 1) + o3 += s3[:, xs, :] * w + else: + ys = np.clip(np.arange(H) + i, 0, H - 1) + o3 += s3[ys, :, :] * w + return out.astype(np.float32) + +def gconv(src, W, H, sig): + k, r = gk(sig) + return cv1(cv1(src, W, H, k, r, True), W, H, k, r, False) + +def toF(img): + a = _arr(img) + return a[:, :, :3].reshape(-1).astype(np.float32) + +def toImg(f, W, H): + o = np.clip(f, 0, 255) # JS: manual clamp, then Uint8ClampedArray rounds half-even + o = np.rint(o).astype(np.uint8).reshape(H, W, 3) + return Img(np.dstack([o, np.full((H, W), 255, np.uint8)])) + +def unsharpG(img, sig, amt): + a = _arr(img); H, W = a.shape[:2] + f = toF(a).astype(np.float64) + bl = gconv(f, W, H, sig) + f = f + amt * (f - bl) + return toImg(f, W, H) + +def gs3a2(img): return unsharpG(img, 3, 2) +def deblkS(img): return unsharpG(img, 1.2, 1.5) + +def zoomw(img): + # canvas smoothing 'high' approximation: LANCZOS + a = _arr(img); h, w = a.shape[:2] + s = round(min(w, h) * 0.6) + x0 = round((w - s) / 2); y0 = round((h - s) / 2) + S = round(s * 2.5) + pil = Image.fromarray(a[y0:y0+s, x0:x0+s], 'RGBA') + return Img(np.array(pil.resize((S, S), Image.LANCZOS))) + +def saliencyCrop(img, marginFrac): + a = _arr(img); H, W = a.shape[:2] + d = a.reshape(-1, 4) + g = max(1, int(max(W, H) // 200)) + gw = int(np.ceil(W / g)); gh = int(np.ceil(H / g)) + px = np.zeros((gh, gw, 3)) + for y in range(gh): + for x in range(gw): + px[y, x] = d[(y * g) * W + x * g][:3] + med = [np.sort(px[:, :, c].reshape(-1))[len(px.reshape(-1, 3)) >> 1] for c in range(3)] + out = (np.abs(px - np.array(med)).sum(axis=2) > 90).astype(np.uint8) + den = np.zeros((gh, gw), np.uint8) + for y in range(gh): + for x in range(gw): + if not out[y, x]: continue + n = 0 + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + yy, xx = y + dy, x + dx + if 0 <= yy < gh and 0 <= xx < gw and out[yy, xx]: n += 1 + if n >= 3: den[y, x] = 1 + lab = np.full((gh, gw), -1, np.int64) + sizes = [] + for y in range(gh): + for x in range(gw): + if not den[y, x] or lab[y, x] >= 0: continue + id_ = len(sizes); sz = 0 + st = [(x, y)]; lab[y, x] = id_ + while st: + cx, cy = st.pop(); sz += 1 + for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)): + xx, yy = cx + dx, cy + dy + if 0 <= xx < gw and 0 <= yy < gh and den[yy, xx] and lab[yy, xx] < 0: + lab[yy, xx] = id_; st.append((xx, yy)) + sizes.append(sz) + if not sizes: return None + best = int(np.argmax(sizes)) + if sizes[best] < 16: return None + ys, xs = np.where(lab == best) + x0, x1, y0, y1 = xs.min(), xs.max(), ys.min(), ys.max() + w = (x1 - x0 + 1) * g; h = (y1 - y0 + 1) * g + mg = round(max(w, h) * marginFrac) + cx = x0 * g + w / 2; cy = y0 * g + h / 2 + s = max(w, h) + 2 * mg + sx = max(0, round(cx - s / 2)); sy = max(0, round(cy - s / 2)) + ex = min(W, round(cx + s / 2)); ey = min(H, round(cy + s / 2)) + if (ex - sx) * (ey - sy) > 0.6 * W * H: return None + return Img(a[sy:ey, sx:ex].copy()) + +def lrG(img, sig, iters): + a = _arr(img); H, W = a.shape[:2] + y = toF(a).astype(np.float64) + k, r = gk(sig) + def blur(e): + return cv1(cv1(e.astype(np.float64), W, H, k, r, True), W, H, k, r, False).astype(np.float64) + est = y.copy() + for _ in range(iters): + c = blur(est) + ratio = (y / np.maximum(8, c)).astype(np.float32).astype(np.float64) + cr = blur(ratio) + est = np.clip(est * cr, 0, 255).astype(np.float32).astype(np.float64) + return toImg(est, W, H) + +def lrLine(img, L, angDeg, iters): + a = _arr(img); H, W = a.shape[:2] + y = toF(a).astype(np.float64) + ang = angDeg * np.pi / 180 + dx, dy = np.cos(ang), np.sin(ang) + offs = [] + for t in np.arange(-(L - 1) / 2, (L - 1) / 2 + 1): + ox, oy = round(float(dx * t)), round(float(dy * t)) + if (ox, oy) not in offs: offs.append((ox, oy)) + kw = 1 / len(offs) + def conv(e): + e3 = e.reshape(H, W, 3) + o = np.zeros((H, W, 3)) + for ox, oy in offs: + xs = np.clip(np.arange(W) + ox, 0, W - 1) + ys = np.clip(np.arange(H) + oy, 0, H - 1) + o += e3[np.ix_(ys, xs)] + return (o * kw).reshape(-1).astype(np.float32).astype(np.float64) + est = y.copy() + for _ in range(iters): + c = conv(est) + ratio = (y / np.maximum(8, c)).astype(np.float32).astype(np.float64) + cr = conv(ratio) + est = np.clip(est * cr, 0, 255).astype(np.float32).astype(np.float64) + return toImg(est, W, H) + +def lr2(img): + c = saliencyCrop(img, .15) or img + return lrG(c, 2, 6) + +def _ml(img, ang): + c = saliencyCrop(img, .15) or img + return lrLine(c, 19, ang, 8) + +def ml45(img): return _ml(img, 45) +def ml0(img): return _ml(img, 0) +def ml90(img): return _ml(img, 90) +def ml135(img): return _ml(img, 135) +def ml22(img): return _ml(img, 22) +def ml68(img): return _ml(img, 68) +def ml112(img): return _ml(img, 112) +def ml158(img): return _ml(img, 158) + +def estMotionAngle(img): + a = _arr(img); H, W = a.shape[:2] + d = a.astype(np.float64) + g = .299 * d[:, :, 0] + .587 * d[:, :, 1] + .114 * d[:, :, 2] + E = [] + step = 3; dist = 3 + for t in range(0, 180, step): + aa = t * np.pi / 180 + fx, fy = np.cos(aa) * dist, np.sin(aa) * dist + ix, iy = int(np.floor(fx)), int(np.floor(fy)) + ax, ay = fx - ix, fy - iy + w00 = (1 - ax) * (1 - ay); w10 = ax * (1 - ay); w01 = (1 - ax) * ay; w11 = ax * ay + y0, y1 = max(0, -iy), min(H - 1, H - 1 - iy) + x0, x1 = max(0, -ix), min(W - 1, W - 1 - ix) + base = g[y0:y1, x0:x1] + qy = y0 + iy; qx = x0 + ix + q0 = g[qy:qy + (y1 - y0), qx:qx + (x1 - x0)] + q1 = g[qy:qy + (y1 - y0), qx + 1:qx + 1 + (x1 - x0)] + q2 = g[qy + 1:qy + 1 + (y1 - y0), qx:qx + (x1 - x0)] + q3 = g[qy + 1:qy + 1 + (y1 - y0), qx + 1:qx + 1 + (x1 - x0)] + s = np.abs(base - (q0 * w00 + q1 * w10 + q2 * w01 + q3 * w11)).sum() + n = (y1 - y0) * (x1 - x0) + E.append(s / max(1, n)) + h_ = 90 // step + best = 0; bv = 1e9 + for i in range(len(E)): + r_ = E[i] / E[(i + h_) % len(E)] + if r_ < bv: bv = r_; best = i + global _lastRatio + _lastRatio = bv + return best * step + +_lastRatio = None + +_FFT_CACHE = {} + +def _fft_setup(n, inv): + key = (n, inv) + if key in _FFT_CACHE: return _FFT_CACHE[key] + perm = list(range(n)) + j = 0 + for i in range(1, n): + bit = n >> 1 + while j & bit: + j ^= bit; bit >>= 1 + j ^= bit + if i < j: + perm[i], perm[j] = perm[j], perm[i] + stages = [] + len_ = 2 + while len_ <= n: + ang = 2 * np.pi / len_ * (1 if inv else -1) + wr, wi = np.cos(ang), np.sin(ang) + half = len_ // 2 + crs = np.empty(half); cis = np.empty(half) + cr, ci = 1.0, 0.0 + for jj in range(half): + crs[jj] = cr; cis[jj] = ci + cr, ci = cr * wr - ci * wi, cr * wi + ci * wr + stages.append((len_, half, crs, cis)) + len_ <<= 1 + _FFT_CACHE[key] = (np.array(perm), stages) + return _FFT_CACHE[key] + +def fft1(re, im, inv): + n = len(re) + perm, stages = _fft_setup(n, inv) + re[:] = re[perm]; im[:] = im[perm] + for len_, half, crs, cis in stages: + re2 = re.reshape(-1, len_); im2 = im.reshape(-1, len_) + a_re = re2[:, :half]; a_im = im2[:, :half] + b_re = re2[:, half:]; b_im = im2[:, half:] + xr = b_re * crs - b_im * cis + xi = b_re * cis + b_im * crs + b_re[:] = a_re - xr; b_im[:] = a_im - xi + a_re += xr; a_im += xi + if inv: + re /= n; im /= n + +def fft2(re, im, N, inv): + rr = np.empty(N); ri = np.empty(N) + for y in range(N): + rr[:] = re[y*N:y*N+N]; ri[:] = im[y*N:y*N+N] + fft1(rr, ri, inv) + re[y*N:y*N+N] = rr; im[y*N:y*N+N] = ri + for x in range(N): + rr[:] = re[x::N]; ri[:] = im[x::N] + fft1(rr, ri, inv) + re[x::N] = rr; im[x::N] = ri + +def wienerLine(img, L, angDeg, nsr): + a = _arr(img); H, W = a.shape[:2] + N = 1 + while N < max(W, H): N <<= 1 + ang = angDeg * np.pi / 180 + dx, dy = np.cos(ang), np.sin(ang) + kr = np.zeros(N * N); ki = np.zeros(N * N) + tot = 0.0 + t = -(L - 1) / 2 + while t <= (L - 1) / 2 + 1e-9: + fx, fy = dx * t, dy * t + x0, y0 = int(np.floor(fx)), int(np.floor(fy)) + ax, ay = fx - x0, fy - y0 + for ux, uy, w in ((0, 0, (1-ax)*(1-ay)), (1, 0, ax*(1-ay)), (0, 1, (1-ax)*ay), (1, 1, ax*ay)): + kr[(((y0 + uy) % N + N) % N) * N + (((x0 + ux) % N + N) % N)] += w + tot += w + t += .25 + kr /= tot + fft2(kr, ki, N, False) + out = np.zeros((H, W, 4), np.uint8) + d = a.astype(np.float64) + for c in range(3): + re = np.zeros(N * N); im = np.zeros(N * N) + for y in range(N): + xs = np.minimum(W - 1, np.arange(N)) + re[y*N:(y+1)*N] = d[min(H - 1, y), xs, c] + fft2(re, im, N, False) + k2 = kr * kr + ki * ki + nsr + r = re * kr + im * ki + m = im * kr - re * ki + re = r / k2; im = m / k2 + fft2(re, im, N, True) + out[:, :, c] = _u8c(np.clip(re.reshape(N, N)[:H, :W], 0, 255)) + out[:, :, 3] = 255 + return Img(out) + +def mlb(img, L, it): + c = saliencyCrop(img, .15) or img + return lrLine(c, L, estMotionAngle(c), it) + +def mlw(img, L, nsr): + c = saliencyCrop(img, .15) or img + return wienerLine(c, L, estMotionAngle(c), nsr) + +def mlw19(img): return mlw(img, 19, .003) +def mlw31(img): return mlw(img, 31, .003) +def mlw9(img): return mlw(img, 9, .003) +def mlf19(img): return wienerLine(img, 19, estMotionAngle(img), .003) +def mlf31(img): return wienerLine(img, 31, estMotionAngle(img), .003) +def mlb19(img): return mlb(img, 19, 8) +def mlb31(img): return mlb(img, 31, 8) +def mlb9(img): return mlb(img, 9, 8) +def mlb19b(img): return mlb(img, 19, 16) +def mlb31b(img): return mlb(img, 31, 16) + +_mlgState = {} + +def mlg(img, L, flags): + c = saliencyCrop(img, .15) or img + key = id(img) + if _mlgState.get('img_key') == key: + ang = _mlgState['ang']; rt = _mlgState['rt'] + else: + ang = estMotionAngle(c); rt = _lastRatio + _mlgState.update(img_key=key, ang=ang, rt=rt) + if not (rt < 0.72): return None + flags['calmed10'] = True + return wienerLine(c, L, ang, .003) + +def mlg19(img, flags): return mlg(img, 19, flags) +def mlg31(img, flags): return mlg(img, 31, flags) + +def glNorm(img): + a = _arr(img); H, W = a.shape[:2] + d = a.astype(np.float64) + hw = W >> 1; hh = H >> 1; n = hw * hh; K = 10 + ch = [] + for c in range(3): + ac = np.zeros((hh, hw)) + for y in range(hh): + for x in range(hw): + ac[y, x] = (d[2*y, 2*x, c] + d[2*y, 2*x+1, c] + d[2*y+1, 2*x, c] + d[2*y+1, 2*x+1, c]) / 4 + ch.append(ac) + def sep(ac, op): + t = np.zeros((hh, hw)) + for y in range(hh): + for x in range(hw): + j0, j1 = max(0, x - K), min(hw - 1, x + K) + t[y, x] = op(ac[y, j0:j1+1]) + r = np.zeros((hh, hw)) + for y in range(hh): + for x in range(hw): + j0, j1 = max(0, y - K), min(hh - 1, y + K) + r[y, x] = op(t[j0:j1+1, x]) + return r + def blur(ac, sg): + R = int(np.ceil(sg * 2)) + k = np.array([np.exp(-i*i/(2*sg*sg)) for i in range(-R, R+1)]) + t = np.zeros((hh, hw)) + for y in range(hh): + for x in range(hw): + v = 0.0; wt = 0.0 + for j in range(-R, R+1): + xx = x + j + if 0 <= xx < hw: + v += ac[y, xx] * k[j+R]; wt += k[j+R] + t[y, x] = np.float32(v / wt) + r = np.zeros((hh, hw)) + for y in range(hh): + for x in range(hw): + v = 0.0; wt = 0.0 + for j in range(-R, R+1): + yy = y + j + if 0 <= yy < hh: + v += t[yy, x] * k[j+R]; wt += k[j+R] + r[y, x] = np.float32(v / wt) + return r + lo = [blur(sep(ac, np.min), 7) for ac in ch] + hi = [blur(sep(ac, np.max), 7) for ac in ch] + out = np.zeros((H, W, 4), np.uint8) + for y in range(H): + fy = min(hh - 1.001, max(0, (y - .5) / 2)); y0 = int(fy); ty = fy - y0 + for x in range(W): + fx = min(hw - 1.001, max(0, (x - .5) / 2)); x0 = int(fx); tx = fx - x0 + for c in range(3): + Lc, Hc = lo[c], hi[c] + l = (Lc[y0, x0]*(1-tx)+Lc[y0, x0+1]*tx)*(1-ty)+(Lc[y0+1, x0]*(1-tx)+Lc[y0+1, x0+1]*tx)*ty + hg = (Hc[y0, x0]*(1-tx)+Hc[y0, x0+1]*tx)*(1-ty)+(Hc[y0+1, x0]*(1-tx)+Hc[y0+1, x0+1]*tx)*ty + v = (d[y, x, c] - l) / max(hg - l, 25) * 255 + out[y, x, c] = min(255, max(0, int(np.rint(v)))) + out[y, x, 3] = 255 + return Img(out) + +def gln(img): return glNorm(img) + +def _glmk(blk, sm, gam): + def f(img): + a = _arr(img); H, W = a.shape[:2] + d = a.astype(np.float64) + mn = d[:, :, :3].min(axis=2) + gw = int(np.ceil(W / blk)); gh = int(np.ceil(H / blk)) + bm = np.full((gh, gw), 255.0) + for y in range(H): + ky = y // blk + for x in range(W): + k = ky * gw + x // blk + if mn[y, x] < bm.flat[k]: bm.flat[k] = mn[y, x] + g = bm + for _ in range(2): + t = np.zeros((gh, gw)) + for y in range(gh): + for x in range(gw): + y0, y1 = max(0, y-sm), min(gh-1, y+sm) + x0, x1 = max(0, x-sm), min(gw-1, x+sm) + t[y, x] = np.float32(g[y0:y1+1, x0:x1+1].mean()) + g = t + o = np.zeros((H, W, 4), np.uint8) + for y in range(H): + fy = min(gh - 1, max(0, y / blk - .5)); y0 = int(np.floor(fy)) + y1 = min(gh - 1, y0 + 1); ty = fy - y0 + for x in range(W): + fx = min(gw - 1, max(0, x / blk - .5)); x0 = int(np.floor(fx)) + x1 = min(gw - 1, x0 + 1); tx = fx - x0 + B = (g[y0, x0]*(1-tx)+g[y0, x1]*tx)*(1-ty)+(g[y1, x0]*(1-tx)+g[y1, x1]*tx)*ty + Bc = max(0, B - gam); sc = 255 / max(40, 255 - Bc) + v = (d[y, x, :3] - Bc) * sc + o[y, x, :3] = _u8c(v) + o[y, x, 3] = 255 + return Img(o) + return f + +gl1 = _glmk(12, 1, 0) +gl2 = _glmk(8, 1, 8) +gl3 = _glmk(16, 2, 10) +gl4 = _glmk(16, 2, 14) +gl5 = _glmk(20, 2, 10) +gl6 = _glmk(12, 3, 10) +gl7 = _glmk(8, 1, 20) + +def llBoost(img): + a = _arr(img); H, W = a.shape[:2] + d = a.astype(np.float64); n = W * H + flat = d.reshape(-1, 4) + idx = np.arange(0, n, 7) + s = flat[idx, :3].sum() + if s / (int(np.ceil(n / 7)) * 3) > 45: return None + r = int(np.ceil(4.5)) + k = np.array([np.exp(-i*i/(2*1.5*1.5)) for i in range(-r, r+1)]) + k /= k.sum() + aa = d[:, :, :3].reshape(-1, 3) + b = np.zeros_like(aa) + a3 = aa.reshape(H, W, 3); b3 = b.reshape(H, W, 3) + for i in range(-r, r+1): + xs = np.clip(np.arange(W) + i, 0, W - 1) + b3 += a3[:, xs, :] * k[i + r] + b3 = b3.astype(np.float32).astype(np.float64) # Float32Array store + out3 = np.zeros_like(a3) + for i in range(-r, r+1): + ys = np.clip(np.arange(H) + i, 0, H - 1) + out3 += b3[ys, :, :] * k[i + r] + out3 = out3.astype(np.float32).astype(np.float64) # Float32Array store + av = np.clip(np.floor(out3.reshape(-1) + 0.5), 0, 255).astype(np.int64) # Math.round + hist = np.bincount(av, minlength=256) + acc = 0; lo = 0; hi = 255 + tot = n * 3; pl = tot * .02 + for v in range(256): + acc += int(hist[v]) + if acc >= pl: lo = v; break + acc = 0 + for v in range(255, -1, -1): + acc += int(hist[v]) + if acc >= pl: hi = v; break + if hi - lo < 4: return None + lut = np.zeros(256) + for v in range(256): + t = (v - lo) / (hi - lo) + t = min(1, max(0, t)) + lut[v] = np.power(t, .6) * 255 + o = np.zeros((H, W, 4), np.uint8) + ai = np.clip(np.floor(out3 + 0.5), 0, 255).astype(np.int64) # Math.round + o[:, :, :3] = _u8c(lut[ai]) + o[:, :, 3] = 255 + return Img(o) + +def llb(img): return llBoost(img) + +# ===== PrismRoi (exact port) ===== + +def roi_bbox(img): + a = _arr(img); H, W = a.shape[:2] + d = a.reshape(-1, 4) + g = max(1, int(max(W, H) // 200)) + gw = int(np.ceil(W / g)); gh = int(np.ceil(H / g)) + N = gw * gh + P = np.zeros((N, 3), np.uint8) + h0 = np.zeros(256, np.int64); h1 = np.zeros(256, np.int64); h2 = np.zeros(256, np.int64) + k = 0 + for y in range(gh): + for x in range(gw): + i = (y * g) * W + x * g + av, bv, cv = int(d[i, 0]), int(d[i, 1]), int(d[i, 2]) + P[k] = (av, bv, cv) + h0[av] += 1; h1[bv] += 1; h2[cv] += 1 + k += 1 + half = N >> 1 + def med(h): + s = 0 + for v in range(256): + s += int(h[v]) + if s > half: return v + return 255 + m0, m1, m2 = med(h0), med(h1), med(h2) + out = np.zeros(N, np.uint8) + for kk in range(N): + if abs(int(P[kk, 0]) - m0) + abs(int(P[kk, 1]) - m1) + abs(int(P[kk, 2]) - m2) > 90: + out[kk] = 1 + out2 = out.reshape(gh, gw) + den = np.zeros((gh, gw), np.uint8) + for y in range(gh): + for x in range(gw): + if not out2[y, x]: continue + n = 0 + for dy in (-1, 0, 1): + yy = y + dy + if yy < 0 or yy >= gh: continue + for dx in (-1, 0, 1): + xx = x + dx + if 0 <= xx < gw and out2[yy, xx]: n += 1 + if n >= 3: den[y, x] = 1 + lab = np.full((gh, gw), -1, np.int64) + sizes = [] + for y in range(gh): + for x in range(gw): + if not den[y, x] or lab[y, x] >= 0: continue + id_ = len(sizes); sz = 0 + stk = [y * gw + x]; lab[y, x] = id_ + while stk: + p = stk.pop() + cx, cy = p % gw, p // gw + sz += 1 + if cx + 1 < gw and den[cy, cx + 1] and lab[cy, cx + 1] < 0: + lab[cy, cx + 1] = id_; stk.append(p + 1) + if cx - 1 >= 0 and den[cy, cx - 1] and lab[cy, cx - 1] < 0: + lab[cy, cx - 1] = id_; stk.append(p - 1) + if cy + 1 < gh and den[cy + 1, cx] and lab[cy + 1, cx] < 0: + lab[cy + 1, cx] = id_; stk.append(p + gw) + if cy - 1 >= 0 and den[cy - 1, cx] and lab[cy - 1, cx] < 0: + lab[cy - 1, cx] = id_; stk.append(p - gw) + sizes.append(sz) + if not sizes: return None + best = int(np.argmax(sizes)) + if sizes[best] < 16: return None + ys, xs = np.where(lab == best) + x0, x1, y0, y1 = int(xs.min()), int(xs.max()), int(ys.min()), int(ys.max()) + w = (x1 - x0 + 1) * g; h = (y1 - y0 + 1) * g + mg = round(max(w, h) * .25) + cx = x0 * g + w / 2; cy = y0 * g + h / 2 + s = max(w, h) + 2 * mg + sx = max(0, round(cx - s / 2)); sy = max(0, round(cy - s / 2)) + ex = min(W, round(cx + s / 2)); ey = min(H, round(cy + s / 2)) + if (ex - sx) * (ey - sy) > 0.4 * W * H: return None + return (sx, sy, ex - sx, ey - sy) + +def crop(img, b): + a = _arr(img) + sx, sy, w, h = b + return Img(a[sy:sy+h, sx:sx+w].copy()) + +def upNN(img, s): + a = _arr(img); h, w = a.shape[:2] + W2 = round(w * s); H2 = round(h * s) + ys = np.minimum(h - 1, (np.arange(H2) / s).astype(np.int64)) + xs = np.minimum(w - 1, (np.arange(W2) / s).astype(np.int64)) + o = a[np.ix_(ys, xs)].copy() + o[:, :, 3] = 255 + return Img(o) + +# ===== orchestrator (AsyncPrismReader.read) ===== + +CHAIN0 = ['cenon','llb','zoom','mlg19','mlg31','gl5','gl3','liftdn','crplain','zoomauto', + 'zooman','gl6','gl7','gln','calmedon','gs3a2','deblkS','zoomw','mlw19','mlw31', + 'lr2','veil','ml112','ml45','ml0','ml90','ml135'] + +def _front_list(a): + H, W = a.shape[:2] + D = a.reshape(-1, 4).astype(np.int64) + hh = np.zeros(256, np.int64); hn = np.zeros(1100, np.int64) + sm = 0; gxs = 0; gys = 0; sts = 0 + rowL = np.zeros(W * 3, np.int64) + for y in range(H): + s_row = D[y*W:(y+1)*W, :3].sum(axis=1) + rowL[(y % 3) * W:(y % 3) * W + W] = s_row + hh += np.bincount(np.rint(s_row / 3).astype(np.int64), minlength=256) + sts += int((D[y*W:(y+1)*W, :3].max(axis=1) - D[y*W:(y+1)*W, :3].min(axis=1)).sum()) + sm += int(s_row.sum()) + if y > 0: + gxs += int(np.abs(s_row[1:] - rowL[(y % 3) * W:(y % 3) * W + W - 1]).sum()) + gys += int(np.abs(s_row - rowL[((y + 2) % 3) * W:((y + 2) % 3) * W + W]).sum()) + if y > 1: + c = rowL[((y + 2) % 3) * W:((y + 2) % 3) * W + W] + l = np.abs(4 * c[1:W-1] - c[0:W-2] - c[2:W] + - rowL[((y + 1) % 3) * W + 1:((y + 1) % 3) * W + W - 1] + - rowL[(y % 3) * W + 1:(y % 3) * W + W - 1]) + hn += np.bincount(np.minimum(1099, l), minlength=1100) + N = W * H + mean = sm / N / 3 + gx = gxs / ((W - 1) * H) / 3 + gy = gys / (W * (H - 1)) / 3 + grad = (gx + gy) / 2 + aniso = max(gx, gy) / (min(gx, gy) + 1e-6) + c = 0; p98 = 255 + for i in range(256): + c += int(hh[i]) + if c >= .98 * N: p98 = i; break + tot = int(hn.sum()); c = 0; nz = 0 + for i in range(1100): + c += int(hn[i]) + if c >= tot / 2: nz = i / 3; break + front = [] + if mean < 30 and p98 < 45: + front = ['llb', 'liftdn'] if nz < 15.2 else ['liftdn', 'llb'] + elif nz > 15: + front = ['liftdn'] + elif sts / N >= 44 and 228 <= p98 <= 240 and 3 <= nz <= 3.6: + front = ['calmedon', 'gs3a2', 'lr2'] + elif grad < 1.6 and nz < 3.5: + front = ['mlg19', 'mlg31', 'gs3a2'] if aniso >= 1.4 else ['calmedon', 'gs3a2', 'mlg31'] + return front + +def _flags(): + return {'calmed10': False, 'dd': False, 'pq': False, 'veil': False} + +def async_prism_read(img, reader): + """Port of AsyncPrismReader.read. reader(img_dict, flags) -> result dict or raises. + Time budgets are not enforced; order and flags are exact. + cenon sets dd+pq, veil sets veil+pq, calmedon sets calmed10, mlg sets calmed10 on pass.""" + flags = _flags() + # mix-mode first attempt, budgets not enforced. + try: + return reader(img, {'mix': True}) + except Exception as e: + if 'stopped' in str(e): + raise + try: + return reader(img, flags) + except Exception as e: + err = e + _mlgState.clear() + a = _arr(img) + try: + front = _front_list(a) + except Exception: + front = [] + chain = front + [n for n in CHAIN0 if n not in front] + ok_list = [] + flag_transforms = { + 'calmedon': lambda im, fl: (fl.__setitem__('calmed10', True), im)[1], + 'cenon': lambda im, fl: (fl.__setitem__('dd', True), fl.__setitem__('pq', True), im)[2], + 'veil': lambda im, fl: (fl.__setitem__('veil', True), fl.__setitem__('pq', True), im)[2], + } + simple = {'llb': llb, 'zoom': zoom, 'gl5': gl5, 'gl3': gl3, 'liftdn': liftdn, + 'crplain': crplain, 'zoomauto': zoomauto, 'zooman': zooman, 'gl6': gl6, + 'gl7': gl7, 'gln': gln, 'gs3a2': gs3a2, 'deblkS': deblkS, 'zoomw': zoomw, + 'mlw19': mlw19, 'mlw31': mlw31, 'lr2': lr2, 'ml112': ml112, 'ml45': ml45, + 'ml0': ml0, 'ml90': ml90, 'ml135': ml135} + for nm in chain: + im2 = None + try: + if nm in flag_transforms: + im2 = flag_transforms[nm](img, flags) + elif nm in ('mlg19', 'mlg31'): + im2 = mlg(img, 19 if nm == 'mlg19' else 31, flags) + else: + im2 = simple[nm](img) + except Exception: + im2 = None + if im2 is None: + continue + if nm not in ('cenon', 'veil'): + ok_list.append(nm) + try: + return reader(im2, flags) + except Exception: + if nm == 'cenon': + flags['dd'] = False; flags['pq'] = False + if nm == 'veil': + flags['veil'] = False; flags['pq'] = False + for nm in ok_list: + im3 = None + try: + if nm in ('mlg19', 'mlg31'): + im3 = mlg(img, 19 if nm == 'mlg19' else 31, flags) + else: + im3 = simple[nm](img) + except Exception: + im3 = None + if im3 is None: + continue + try: + return reader(im3, flags) + except Exception: + pass + raise err diff --git a/ports/python/reader/prism_reader.py b/ports/python/reader/prism_reader.py new file mode 100644 index 0000000..71c12eb --- /dev/null +++ b/ports/python/reader/prism_reader.py @@ -0,0 +1,3100 @@ +"""Comb Code photo reader - Python port of the live reader (fast-reader.html). +Needs numpy. Detection, hypothesis search, Reed-Solomon recovery, palette-mix and +distance-fit recovery; the page retry chain is in prism_chain.py. +Fidelity notes: JS doubles everywhere except Float32Array stores (frame pixels, +smoothFilter); Uint8ClampedArray = clamp+round-half-even; Math.round=floor(x+0.5). +""" +import math +import struct +from fractions import Fraction +import numpy as np + +S3 = math.sqrt(3.0) +Q = 3 * S3 +SIZES = [[21, 24], [29, 33], [41, 47], [57, 66], [81, 94], [113, 130]] +HEX = ['#1B1B1B', '#2E5BFF', '#00B8D9', '#2DB35A', '#F5C518', '#F77F00', '#D7263D', '#B5179E', '#FFFFFF'] +CFG = dict(detectionWidth=320, saturation=.25, darkness=.55, minScore=.5, + refineStop=.03, meshRadius=.6, sigmaFloor=6, llrClamp=12, minRadius=4, + glareThreshold=.90) + +def clamp(x, a=0.0, b=1.0): + return max(a, min(b, x)) + +def _u8(v): + # Uint8ClampedArray store: clamp [0,255] then round-half-even + return int(np.rint(min(255.0, max(0.0, v)))) + +def rng(seed): + # Exact port of the JS mulberry-style rng (verified in ports/python/prism.py). + state = [seed & 0xFFFFFFFF] + def r(): + s = state[0] = (state[0] + 0x6D2B79F5) & 0xFFFFFFFF + t = ((s ^ (s >> 15)) * (1 | s)) & 0xFFFFFFFF + t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t + return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296.0 + return r + +def median(a): + a = sorted(a) + return a[len(a) >> 1] + +# GF(256) 0x11D +EXP = [0] * 512 +LOG = [0] * 256 +z = 1 +for i in range(255): + EXP[i] = z + LOG[z] = i + z <<= 1 + if z & 256: + z ^= 0x11d +for i in range(255, 512): + EXP[i] = EXP[i - 255] + +def gf_mul(a, b): + return EXP[LOG[a] + LOG[b]] if a and b else 0 + +def gf_div(a, b): + if not b: + raise ZeroDivisionError('GF division by zero') + return EXP[(LOG[a] + 255 - LOG[b]) % 255] if a else 0 + +def peval(p, x): + y = 0 + for i in range(len(p) - 1, -1, -1): + y = gf_mul(y, x) ^ p[i] + return y + +def pmul(a, b): + _, mul = _gf_tables() + A = np.array(a, dtype=np.uint8) + B = np.array(b, dtype=np.uint8) + full = mul[A[:, None], B[None, :]] + o = np.zeros(len(a) + len(b) - 1, dtype=np.uint8) + for i in range(len(a)): + o[i:i + len(b)] ^= full[i] + return o.tolist() + +_GF_EXP = None +_GF_MUL = None + +def _gf_tables(): + global _GF_EXP, _GF_MUL + if _GF_MUL is None: + _GF_EXP = np.array(EXP, dtype=np.uint8) + log = np.array(LOG, dtype=np.uint16) + m = np.zeros((256, 256), dtype=np.uint8) + m[1:, 1:] = _GF_EXP[(log[1:, None] + log[None, 1:]).astype(np.uint16)] + _GF_MUL = m + return _GF_EXP, _GF_MUL + +def syndromes(r, n): + exparr, mul = _gf_tables() + s = np.zeros(n, dtype=np.uint8) + x = exparr[:n] + for c in r: + s = mul[s, x] ^ c + return s.tolist() + +def bm(s): + _, mul = _gf_tables() + S = np.array(s, dtype=np.uint8) + c = np.zeros(len(s) + 1, dtype=np.uint8) + b = np.zeros(len(s) + 1, dtype=np.uint8) + c[0] = b[0] = 1 + L = 0 + m = 1 + bb = 1 + for n in range(len(s)): + if L: + d = int(S[n]) ^ int(np.bitwise_xor.reduce(mul[c[1:L + 1], S[n - L:n][::-1]])) + else: + d = int(S[n]) + if not d: + m += 1 + continue + t = c.copy() + v = gf_div(d, bb) + c[m:] ^= mul[b[:len(c) - m], v] + if 2 * L <= n: + L = n + 1 - L + b = t + bb = d + m = 1 + else: + m += 1 + return c[:L + 1].tolist() + +def rsDecode(input_, nsym, erasures=(), _s=None): + r = list(input_) + s = _s if _s is not None else syndromes(r, nsym) + if not any(s): + return {'bytes': r, 'corrected': 0} + if len(erasures) > nsym: + raise ValueError('Too many erasures') + _, mul = _gf_tables() + G = np.ones(1, dtype=np.uint8) + T = np.array(s, dtype=np.uint8) + for p in erasures: + if p < 0 or p >= len(r): + raise ValueError('Erasure index') + X = EXP[len(r) - 1 - p] + Gn = np.zeros(len(G) + 1, dtype=np.uint8) + Gn[:-1] ^= G + Gn[1:] ^= mul[G, X] + G = Gn + T = mul[T[:-1], X] ^ T[1:] + G = G.tolist() + T = T.tolist() + E = bm(T) + if 2 * (len(E) - 1) + len(erasures) > nsym: + raise ValueError('RS correction limit') + loc = pmul(G, E) + exparr, mul = _gf_tables() + npos = len(r) + xv = exparr[(255 - np.arange(npos - 1, -1, -1)) % 255] + yv = np.zeros(npos, dtype=np.uint8) + for c in reversed(loc): + yv = mul[yv, xv] ^ c + pos = np.nonzero(yv == 0)[0].tolist() + if len(pos) != len(loc) - 1: + raise ValueError('RS roots') + omega = pmul(s, loc)[:nsym] + der = [0] * max(1, len(loc) - 1) + for i in range(1, len(loc), 2): + der[i - 1] = loc[i] + exparr2, mul2 = _gf_tables() + POS = np.array(pos, dtype=np.int64) + EV = len(r) - 1 - POS + XV = exparr2[EV] + XI = exparr2[(255 - EV) % 255] + Y1 = np.zeros(len(pos), dtype=np.uint8) + for c in reversed(omega): + Y1 = mul2[Y1, XI] ^ c + Y2 = np.zeros(len(pos), dtype=np.uint8) + for c in reversed(der): + Y2 = mul2[Y2, XI] ^ c + if int((Y2 == 0).sum()): + raise ZeroDivisionError() + for k in range(len(pos)): + num = gf_mul(int(XV[k]), int(Y1[k])) + den = int(Y2[k]) + r[int(POS[k])] ^= EXP[(LOG[num] - LOG[den]) % 255] if num else 0 + if not all(x == 0 for x in syndromes(r, nsym)): + raise ValueError('RS syndrome check') + return {'bytes': r, 'corrected': len(pos)} + +_crcTable = [] +for n in range(256): + c = n + for _ in range(8): + c = (0xEDB88320 ^ (c >> 1)) if c & 1 else (c >> 1) + _crcTable.append(c & 0xFFFFFFFF) + +def crc32(bytes_): + c = 0xFFFFFFFF + for b in bytes_: + c = _crcTable[(c ^ b) & 255] ^ (c >> 8) + return (c ^ 0xFFFFFFFF) & 0xFFFFFFFF + +def crc4(bits): + r = 0 + for b in bits: + f = ((r >> 3) & 1) ^ b + r = (r << 1) & 15 + if f: + r ^= 3 + return r + +_layout_cache = {} + +def layout(size): + if size in _layout_cache: + return _layout_cache[size] + if size < 0 or size >= len(SIZES): + raise ValueError('Unknown size') + C, R = SIZES[size] + cells = [] + M = [] + known = [] + for j in range(R): + for i in range(C): + role = 'data' + symbol = -1 + pi = (i - 2) / 5 + pj = (j - 2) / 5 + if j <= 2 and i <= 2: + role = 'gap' + symbol = 8 + elif j == 0 or j == R - 1 or i == 0 or i == C - 1: + role = 'ring' + symbol = (j * 5 + i * 3) % 8 + elif i % 5 == 2 and j % 5 == 2: + role = 'pilot' + symbol = (pi * 2 + pj * 3) % 9 + c = {'i': i, 'j': j, 'x': S3 * (i + .5 + .5 * (j & 1)), 'y': 1 + 1.5 * j, + 'role': role, 'symbol': symbol, 'pi': pi, 'pj': pj, 'index': len(cells)} + cells.append(c) + if role == 'data': + M.append(c) + elif role != 'gap': + known.append(c) + headers = [] + for n in range(72): + c = M[int((n + .5) * len(M) / 72)] + c['role'] = 'header' + c['header'] = n + headers.append(c) + data = [c for c in cells if c['role'] == 'data'] + rand = rng(0x5EED ^ size) + for i in range(len(data) - 1, 0, -1): + j = int(rand() * (i + 1)) + data[i], data[j] = data[j], data[i] + l = {'size': size, 'C': C, 'R': R, 'W': S3 * (C + .5), 'H': 2 + 1.5 * (R - 1), + 'cells': cells, 'headers': headers, 'data': data, 'known': known} + _layout_cache[size] = l + return l + +def knownSymbol(c, mode): + if mode: + if c['role'] == 'ring': + return 0 + return 0 if (c['pi'] + c['pj']) % 2 == 0 else 8 + return c['symbol'] + +_B1 = 715094163 # (682+0.03306235651)*2**23 +_B2 = 696219795 # (664-0.03306235651)*2**23 +_CBRT_C = 5.42857142857142815906e-01 +_CBRT_D = -7.05306122448979611050e-01 +_CBRT_E = 1.41428571428571436819e+00 +_CBRT_F = 1.60714285714285720630e+00 +_CBRT_G = 3.57142857142857150787e-01 + +def _bits(x): + return struct.unpack('> 32) & 0xFFFFFFFF + low = bits & 0xFFFFFFFF + sign = hx & 0x80000000 + hx ^= sign + if hx >= 0x7FF00000: + return x + x + if hx < 0x00100000: + if (hx | low) == 0: + return x + t = _frombits(0x43500000 << 32) * x + high = (_bits(t) >> 32) & 0xFFFFFFFF + t = _frombits(((sign | ((high & 0x7FFFFFFF) // 3 + 696219795)) << 32)) + else: + t = _frombits(((sign | (hx // 3 + 715094163)) << 32)) + r = (t * t) * (t / x) + t = t * ((_CBRT_P0 + r * (_CBRT_P1 + r * _CBRT_P2)) + ((r * r) * r) * (_CBRT_P3 + r * _CBRT_P4)) + t = _frombits((_bits(t) + 0x80000000) & 0xFFFFFFFFC0000000) + s = t * t + r = x / s + w = t + t + r = (r - t) / (w + r) + return t + t * r + +def lin(x): + return x / 12.92 if x <= .04045 else ((x + .055) / 1.055) ** 2.4 + +def srgb(x): + return 12.92 * x if x <= .0031308 else 1.055 * x ** (1 / 2.4) - .055 + +LUT = np.array([lin(i / 255) for i in range(256)], dtype=np.float32) +# Exact JS doubles (V8 pow differs from glibc pow by 1 ulp; hardcoded from the live reader) +PAL = [ + [float.fromhex('0x1.6723eea8d3709p-7'), float.fromhex('0x1.6723eea8d3709p-7'), float.fromhex('0x1.6723eea8d3709p-7')], + [float.fromhex('0x1.bfa0200597bdap-6'), float.fromhex('0x1.ac82559cb3644p-4'), float.fromhex('0x1.0000000000000p+0')], + [float.fromhex('0x0.0p+0'), float.fromhex('0x1.ead2e8faec526p-2'), float.fromhex('0x1.634328d4bbe97p-1')], + [float.fromhex('0x1.adefa9761c020p-6'), float.fromhex('0x1.cd9ac9cb2aef2p-2'), float.fromhex('0x1.a2c83a3e6566cp-4')], + [float.fromhex('0x1.d381aa9ef2e82p-1'), float.fromhex('0x1.1ddecaa307b85p-1'), float.fromhex('0x1.2b4e09b3f0ae3p-7')], + [float.fromhex('0x1.dc377d8cc0fd5p-1'), float.fromhex('0x1.b2a60a1263b0ap-3'), float.fromhex('0x0.0p+0')], + [float.fromhex('0x1.5becfd96a2698p-1'), float.fromhex('0x1.3d8f839b79c0bp-6'), float.fromhex('0x1.7e47c775d2428p-5')], + [float.fromhex('0x1.d92ab686ff782p-2'), float.fromhex('0x1.18c2a5a8a8044p-7'), float.fromhex('0x1.5e1ed0a40daacp-2')], + [float.fromhex('0x1.0000000000000p+0'), float.fromhex('0x1.0000000000000p+0'), float.fromhex('0x1.0000000000000p+0')], +] + +def lab(c): + x = (.4124564 * c[0] + .3575761 * c[1] + .1804375 * c[2]) / .95047 + y = .2126729 * c[0] + .7151522 * c[1] + .072175 * c[2] + z_ = (.0193339 * c[0] + .119192 * c[1] + .9503041 * c[2]) / 1.08883 + def f(v): + return cbrt_exact(v) if v > .008856 else 7.787 * v + 16 / 116 + a = f(x) + b = f(y) + d = f(z_) + return [116 * b - 16, 500 * (a - b), 200 * (b - d)] + +LAB = [ + [float.fromhex('0x1.388abb756f4ecp+3'), float.fromhex('-0x1.f0e4c11d40000p-19'), float.fromhex('0x1.8d83cd9800000p-20')], + [float.fromhex('0x1.701fff75d39efp+5'), float.fromhex('0x1.5ef317ac27601p+5'), float.fromhex('-0x1.544c9f90db45cp+6')], + [float.fromhex('0x1.13d57192abe16p+6'), float.fromhex('-0x1.b0f9e39eca274p+4'), float.fromhex('-0x1.b7b360bee678ap+4')], + [float.fromhex('0x1.025d357027ea8p+6'), float.fromhex('-0x1.b64762c21c7cap+5'), float.fromhex('0x1.1ab1016fd7203p+5')], + [float.fromhex('0x1.461393c5e005ep+6'), float.fromhex('0x1.9fab821148ad2p+1'), float.fromhex('0x1.4060baa61786bp+6')], + [float.fromhex('0x1.06ddaae2901f5p+6'), float.fromhex('0x1.419a38eeff187p+5'), float.fromhex('0x1.228a962cc0506p+6')], + [float.fromhex('0x1.79a02ad399a36p+5'), float.fromhex('0x1.0960f5d9e62fdp+6'), float.fromhex('0x1.079ae1cc6d591p+5')], + [float.fromhex('0x1.54fd74a5d8299p+5'), float.fromhex('0x1.17bfea572e3b4p+6'), float.fromhex('-0x1.0f68a1fb2d32bp+5')], + [float.fromhex('0x1.900001037cd35p+6'), float.fromhex('-0x1.179ec93cc0000p-16'), float.fromhex('0x1.bf64752e00000p-18')], +] + +# runtime lab() recomputed per sample; PAL/LAB above are the JS-exact constants + +def dist(a, b): + return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2 + +def solve(a, b): + n = len(b) + m = [list(a[i]) + [b[i]] for i in range(n)] + for j in range(n): + p = j + for k in range(j + 1, n): + if abs(m[k][j]) > abs(m[p][j]): + p = k + if abs(m[p][j]) < 1e-10: + raise ValueError('Singular geometry') + m[j], m[p] = m[p], m[j] + v = m[j][j] + for k in range(j, n + 1): + m[j][k] /= v + for i in range(n): + if i != j: + v = m[i][j] + for k in range(j, n + 1): + m[i][k] -= v * m[j][k] + return [r[n] for r in m] + +def homography(src, dst): + a = [] + b = [] + for i in range(4): + x, y = src[i] + u, v = dst[i] + a.append([x, y, 1, 0, 0, 0, -u * x, -u * y]) + a.append([0, 0, 0, x, y, 1, -v * x, -v * y]) + b.append(u) + b.append(v) + return H(solve(a, b)) + +class H(list): + """Homography vector with optional warp attribute (JS h.warp).""" + warp = None + +def map_h(h, x, y): + w = getattr(h, 'warp', None) + if w: + W = w['W'] + H_ = w['H'] + p = w['p'] + u = 2 * x / W - 1 + v = 2 * y / H_ - 1 + p6 = p[6] if len(p) > 6 else 0 + p7 = p[7] if len(p) > 7 else 0 + p8 = p[8] if len(p) > 8 else 0 + p9 = p[9] if len(p) > 9 else 0 + x += (1 - u * u) * (p[0] + p[1] * v) + p[2] * (1 - v * v) + p6 * u * (1 - u * u) + p8 * u * (1 - v * v) + y += (1 - v * v) * (p[3] + p[4] * u) + p[5] * (1 - u * u) + p7 * v * (1 - u * u) + p9 * v * (1 - v * v) + d = h[6] * x + h[7] * y + 1 + return [(h[0] * x + h[1] * y + h[2]) / d, (h[3] * x + h[4] * y + h[5]) / d] + +def corners(l): + return [[0, 0], [l['W'], 0], [l['W'], l['H']], [0, l['H']]] + +class Frame: + __slots__ = ('w', 'h', 'p', 'image') + def __init__(self, image): + w = image['width'] + h = image['height'] + data = image['data'] # bytes/np.uint8 RGBA + arr = np.frombuffer(data, dtype=np.uint8) if not isinstance(data, np.ndarray) else data + rgb = arr[0:w * h * 4].reshape(-1, 4)[:, :3] + self.p = LUT[rgb].astype(np.float32).reshape(-1) # Float32Array semantics + self.w = w + self.h = h + self.image = image + +def frame(image): + return Frame(image) + +def pixel(f, x, y): + if x < 0 or y < 0 or x >= f.w - 1 or y >= f.h - 1: + return [1.0, 1.0, 1.0] + i = math.floor(x) + j = math.floor(y) + a = x - i + b = y - j + k = (j * f.w + i) * 3 + p = f.p + o = [0.0, 0.0, 0.0] + for c in range(3): + o[c] = (float(p[k + c]) * (1 - a) + float(p[k + 3 + c]) * a) * (1 - b) + \ + (float(p[k + f.w * 3 + c]) * (1 - a) + float(p[k + f.w * 3 + 3 + c]) * a) * b + return o + +OFF = [[0, 0]] + [[.45 * math.cos(k * math.pi / 3), .45 * math.sin(k * math.pi / 3)] for k in range(6)] + +def meshAt(mesh, x, y): + if not mesh or not len(mesh): + return [0.0, 0.0] + lst = [] + for m in mesh: + d = (m['x'] - x) ** 2 + (m['y'] - y) ** 2 + if len(lst) < 4 or d < lst[3][0]: + lst.append((d, m)) + lst.sort(key=lambda t: t[0]) + del lst[4:] + sx = sy = sw = 0.0 + for d, m in lst: + w = 1 / (d + .05) + sx += m['dx'] * w + sy += m['dy'] * w + sw += w + return [sx / sw, sy / sw] + +def sample(f, h, c, white=[1, 1, 1], mesh=None, fast=False): + of = meshAt(mesh, c['x'], c['y']) + a = [[], [], []] + for o in (OFF[:1] if fast else OFF): + q = map_h(h, c['x'] + o[0], c['y'] + o[1]) + v = pixel(f, q[0] + of[0], q[1] + of[1]) + for k in range(3): + a[k].append(v[k] / white[k]) + return [median(ch) for ch in a] + +def whiteBalance(f, h, l): + a = [[], [], []] + for t in range(24): + u = (t + .5) / 24 + for x, y in ([u * l['W'], -2.5], [u * l['W'], l['H'] + 2.5], [-2.5, u * l['H']], [l['W'] + 2.5, u * l['H']]): + q = map_h(h, x, y) + if q[0] < 0 or q[1] < 0 or q[0] >= f.w - 1 or q[1] >= f.h - 1: + continue + v = pixel(f, q[0], q[1]) + for k in range(3): + a[k].append(v[k]) + return [max(.08, median(ch) if ch else 1) for ch in a] + +def nearest(c, mode=0): + v = lab(c) + best = -1 + d = math.inf + for i in range(9): + if mode and i != 0 and i != 8: + continue + q = dist(v, LAB[i]) + if q < d: + d = q + best = i + return {'symbol': best, 'd': math.sqrt(d)} + +def hypothesisScore(f, h, l, mode, white, fast=True): + cost = 0.0 + n = 0 + match = 0 + known = l['known'] + stride = max(1, len(known) // 120) + for z_ in range(0, len(known), stride): + c = known[z_] + if mode and c['role'] == 'ring': + continue + v = sample(f, h, c, white, None, fast) + expect = knownSymbol(c, mode) + near = nearest(v, mode) + d = math.sqrt(dist(lab(v), LAB[int(expect)])) + cost += min(d / 30, 1) + match += 1 if near['symbol'] == expect else 0 + n += 1 + return {'cost': cost / n, 'score': match / n} + +def refine(f, h, l, mode, quad, white): + q = [p[:] for p in quad] + radius = math.hypot(q[1][0] - q[0][0], q[1][1] - q[0][1]) / l['W'] + step = radius * .5 + best = hypothesisScore(f, h, l, mode, white, False)['cost'] + while step > radius * CFG['refineStop']: + for pass_ in range(2): + changed = False + for i in range(4): + for j in range(2): + v = q[i][j] + win = v + for s in (-1, 1): + q[i][j] = v + s * step + hh = homography(corners(l), q) + cost = hypothesisScore(f, hh, l, mode, white, False)['cost'] + if cost < best: + best = cost + win = q[i][j] + h = hh + changed = True + q[i][j] = win + if not changed: + break + step *= .5 + return {'h': h, 'quad': q, 'cost': best} + +def cross(a, b, c): + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + +def hull(points): + points = sorted(points, key=lambda p: (p[0], p[1])) + a = [] + b = [] + for p in points: + while len(a) > 1 and cross(a[-2], a[-1], p) <= 0: + a.pop() + a.append(p) + for i in range(len(points) - 1, -1, -1): + p = points[i] + while len(b) > 1 and cross(b[-2], b[-1], p) <= 0: + b.pop() + b.append(p) + a.pop() + b.pop() + return a + b + +def area(q): + return abs(sum(p[0] * q[(i + 1) % len(q)][1] - p[1] * q[(i + 1) % len(q)][0] for i, p in enumerate(q))) / 2 + +def morph(a, w, h, r, max_): + tmp = np.zeros(len(a), dtype=np.uint8) + out = np.zeros(len(a), dtype=np.uint8) + for y in range(h): + for x in range(w): + v = 0 if max_ else 1 + for d in range(-r, r + 1): + xx = min(max(x + d, 0), w - 1) + if max_: + v |= int(a[y * w + xx]) + else: + v &= int(a[y * w + xx]) + tmp[y * w + x] = v + for y in range(h): + for x in range(w): + v = 0 if max_ else 1 + for d in range(-r, r + 1): + yy = min(max(y + d, 0), h - 1) + if max_: + v |= int(tmp[yy * w + x]) + else: + v &= int(tmp[yy * w + x]) + out[y * w + x] = v + return out + +def smoothFilter(a, w, h, r, isMax): + # a: sequence; JS uses Float32Array for tmp/out + a = np.asarray(a, dtype=np.float32) + tmp = np.zeros(len(a), dtype=np.float32) + out = np.zeros(len(a), dtype=np.float32) + for y in range(h): + dq = [] + head = 0 + sum_ = 0.0 + for x in range(-r, w + r): + v = float(a[y * w + min(max(x, 0), w - 1)]) + if isMax: + while len(dq) > head and dq[-1][1] <= v: + dq.pop() + dq.append((x, v)) + while dq[head][0] < x - 2 * r: + head += 1 + else: + sum_ += v + if x > r: + sum_ -= float(a[y * w + min(max(x - 2 * r - 1, 0), w - 1)]) + if x >= r: + tmp[y * w + x - r] = np.float32(dq[head][1] if isMax else sum_ / (2 * r + 1)) + for x in range(w): + dq = [] + head = 0 + sum_ = 0.0 + for y in range(-r, h + r): + v = float(tmp[min(max(y, 0), h - 1) * w + x]) + if isMax: + while len(dq) > head and dq[-1][1] <= v: + dq.pop() + dq.append((y, v)) + while dq[head][0] < y - 2 * r: + head += 1 + else: + sum_ += v + if y > r: + sum_ -= float(tmp[min(max(y - 2 * r - 1, 0), h - 1) * w + x]) + if y >= r: + out[(y - r) * w + x] = np.float32(dq[head][1] if isMax else sum_ / (2 * r + 1)) + return out + +def _jsround(x): + return math.floor(x + 0.5) + +def fitLine(points): + x = y = 0.0 + for p in points: + x += p[0] + y += p[1] + x /= len(points) + y /= len(points) + xx = xy = yy = 0.0 + for p in points: + a = p[0] - x + b = p[1] - y + xx += a * a + xy += a * b + yy += b * b + t = .5 * math.atan2(2 * xy, xx - yy) + nx = -math.sin(t) + ny = math.cos(t) + return [nx, ny, nx * x + ny * y] + +def intersect(a, b): + d = a[0] * b[1] - a[1] * b[0] + if abs(d) < 1e-6: + raise ValueError('Parallel edges') + return [(a[2] * b[1] - a[1] * b[2]) / d, (a[0] * b[2] - a[2] * b[0]) / d] + +def detect(f): + scale = min(1, CFG['detectionWidth'] / max(f.w, f.h)) + w = _jsround(f.w * scale) + h = _jsround(f.h * scale) + V = np.zeros(w * h, dtype=np.float32) + sat = np.zeros(w * h, dtype=np.float32) + for y in range(h): + for x in range(w): + pv = pixel(f, x / scale, y / scale) + p = [srgb(v) for v in pv] + mx = max(p) + mn = min(p) + V[y * w + x] = np.float32(mx) + sat[y * w + x] = np.float32((mx - mn) / mx if mx else 0) + paper = smoothFilter(smoothFilter(V, w, h, 7, True), w, h, 15, False) + mask = np.zeros(w * h, dtype=np.uint8) + for k in range(w * h): + s_ = float(sat[k]) + v_ = float(V[k]) + mask[k] = 1 if (s_ > CFG['saturation'] and v_ > .15) or v_ < CFG['darkness'] * max(float(paper[k]), .4) else 0 + mask = morph(morph(mask, w, h, 2, True), w, h, 2, False) + seen = np.zeros(len(mask), dtype=np.uint8) + queue = np.zeros(len(mask), dtype=np.int32) + candidates = [] + for k in range(len(mask)): + if not mask[k] or seen[k]: + continue + head = 0 + tail = 1 + boundary = [] + queue[0] = k + seen[k] = 1 + while head < tail: + p = int(queue[head]) + head += 1 + x = p % w + y = p // w + edge = False + for q in (p - 1 if x > 0 else -1, p + 1 if x < w - 1 else -1, p - w if y > 0 else -1, p + w if y < h - 1 else -1): + if q < 0 or not mask[q]: + edge = True + continue + if not seen[q]: + seen[q] = 1 + queue[tail] = q + tail += 1 + if edge: + boundary.append([x, y]) + if tail < 100: + continue + hu = hull(boundary) + ar = area(hu) + xs = [p[0] for p in hu] + ys = [p[1] for p in hu] + aspect = (max(xs) - min(xs)) / (max(ys) - min(ys)) + if tail / ar < .04 or aspect < .4 or aspect > 2.5: + continue + candidates.append({'hu': hu, 'tail': tail, 'boundary': boundary, 'ar': ar}) + candidates.sort(key=lambda c: -c['ar']) + if not candidates: + raise ValueError("stageError detect: No code found. Use a plain background with a wide white margin.") + out = [] + for cc in candidates[:3]: + poly = [p[:] for p in cc['hu']] + while len(poly) > 4: + min_ = math.inf + at = 0 + for i in range(len(poly)): + a = poly[(i + len(poly) - 1) % len(poly)] + b = poly[(i + 1) % len(poly)] + v = abs(cross(a, poly[i], b)) / math.hypot(b[0] - a[0], b[1] - a[1]) + if v < min_: + min_ = v + at = i + if min_ > .7: + break + poly.pop(at) + edges = sorted(({'a': p, 'b': poly[(i + 1) % len(poly)], 'i': i, + 'len': math.hypot(p[0] - poly[(i + 1) % len(poly)][0], p[1] - poly[(i + 1) % len(poly)][1])} + for i, p in enumerate(poly)), key=lambda e: -e['len'])[:4] + edges.sort(key=lambda e: e['i']) + lines = [] + for i in range(4): + a = edges[i]['a'] + b = edges[i]['b'] + dx = b[0] - a[0] + dy = b[1] - a[1] + ln = math.hypot(dx, dy) + pts = [p for p in cc['boundary'] if abs(cross(a, b, p)) / ln < 2] + lines.append(fitLine(pts) if len(pts) >= 2 else fitLine([a, b])) + try: + quad = [intersect(lines[(i + 3) % 4], lines[i]) for i in range(4)] + quad = [[(v + .5) / scale for v in p] for p in quad] + out.append(quad) + except ValueError: + pass + if not out: + raise ValueError('stageError detect: Could not fit four edges') + return out + +decodeDeadline = math.inf # mirrors JS decodeDeadline; ports run unbudgeted + +def _f32(x): + return float(np.float32(x)) + +def capacity(size, ecc=1, mode=0): + l = layout(size) + n = int(l['data'].__len__() * (1 if mode else 3) / 8) + B = -(-n // 255) + blocks = [] + for i in range(B): + ln = n // B + (1 if i < n % B else 0) + nsym = max(4, 2 * _jsround(ln * [.1, .2, .3, .4][ecc] / 2)) + blocks.append({'n': ln, 'nsym': nsym, 'k': ln - nsym}) + return {'n': n, 'blocks': blocks, 'k': sum(b['k'] for b in blocks), + 'payload': max(0, sum(b['k'] for b in blocks) - 4)} + +def calibrate(f, h, l, mode, white, mesh): + refs = [] + for c in l['known']: + sym = knownSymbol(c, mode) + o = sample(f, h, c, white, mesh) + refs.append({'c': c, 'o': o, 'E': PAL[int(sym)], 'sym': sym}) + refs = [v for v in refs if v['sym'] == 8 or not all(x > CFG['glareThreshold'] for x in v['o'])] + A = [[0.0] * 4 for _ in range(4)] + b = [[0.0] * 4 for _ in range(3)] + for v in refs: + o = [v['o'][0], v['o'][1], v['o'][2], 1.0] + for i in range(4): + for j in range(4): + A[i][j] += o[i] * o[j] + for k in range(3): + b[k][i] += o[i] * v['E'][k] + for i in range(4): + A[i][i] += .001 + M = [solve(A, v) for v in b] + def apply(o): + return [row[0] * o[0] + row[1] * o[1] + row[2] * o[2] + row[3] for row in M] + for v in refs: + a = apply(v['o']) + v['res'] = [x - a[k] for k, x in enumerate(v['E'])] + def correction(o, c): + a = apply(o) + if PRISM_CALMED: + near = sorted(((((v['c']['x'] - c['x']) ** 2 + (v['c']['y'] - c['y']) ** 2), j, v) + for j, v in enumerate(refs)), key=lambda t: (t[0], t[1]))[:10] + rr = [t[2]['res'] for t in near] + return [clamp(x + median([r[k] for r in rr])) for k, x in enumerate(a)] + near = sorted(((((v['c']['x'] - c['x']) ** 2 + (v['c']['y'] - c['y']) ** 2), j, v) + for j, v in enumerate(refs)), key=lambda t: (t[0], t[1]))[:6] + sw = 0.0 + res = [0.0, 0.0, 0.0] + for d, j, v in near: + w = 1 / (d + .05) + sw += w + for k in range(3): + res[k] += w * v['res'][k] + return [clamp(x + res[k] / sw) for k, x in enumerate(a)] + errors = [math.sqrt(dist(lab(correction(v['o'], v['c'])), lab(v['E']))) for v in refs if v['c']['role'] == 'pilot'] + return {'correction': correction, + 'sigma': max(CFG['sigmaFloor'], 1.4 * median(errors if errors else [6])), + 'refs': refs, 'M': M} + +def buildMesh(f, h, l, mode, white, previous): + pilots = [c for c in l['known'] if c['role'] == 'pilot'] + d = mapDelta(h, l['W'] / 2, l['H'] / 2, 1, 0) + scale = math.hypot(d[0], d[1]) + offsets = [] + for c in pilots: + base = map_h(h, c['x'], c['y']) + prior = meshAt(previous, c['x'], c['y']) + best = math.inf + win = None + expect = knownSymbol(c, mode) + for iy in range(-2, 3): + for ix in range(-2, 3): + dx = prior[0] + ix * .3 * scale + dy = prior[1] + iy * .3 * scale + pv = pixel(f, base[0] + dx, base[1] + dy) + v = [pv[k] / white[k] for k in range(3)] + dd = dist(lab(v), LAB[int(expect)]) + reg = .2 * (dx * dx + dy * dy) / (scale * scale) + if dd + reg < best: + best = dd + reg + win = {'x': c['x'], 'y': c['y'], 'dx': dx, 'dy': dy} + offsets.append(win) + return _meshFilter(offsets, .3 * scale) + +def buildDenseMesh(f, h, l, mode, white, previous): + pilots = l['known'] + d = mapDelta(h, l['W'] / 2, l['H'] / 2, 1, 0) + scale = math.hypot(d[0], d[1]) + offsets = [] + for c in pilots: + base = map_h(h, c['x'], c['y']) + prior = meshAt(previous, c['x'], c['y']) + best = math.inf + win = None + expect = knownSymbol(c, mode) + for iy in range(-2, 3): + for ix in range(-2, 3): + dx = prior[0] + ix * .3 * scale + dy = prior[1] + iy * .3 * scale + pv = pixel(f, base[0] + dx, base[1] + dy) + v = [pv[k] / white[k] for k in range(3)] + dd = dist(lab(v), LAB[int(expect)]) + reg = .2 * (dx * dx + dy * dy) / (scale * scale) + if dd + reg < best: + best = dd + reg + win = {'x': c['x'], 'y': c['y'], 'dx': dx, 'dy': dy} + offsets.append(win) + return _meshFilter(offsets, .8 * scale) + +def _meshFilter(offsets, lim): + out = [] + for idx, m in enumerate(offsets): + near = sorted(((((n['x'] - m['x']) ** 2 + (n['y'] - m['y']) ** 2), j, n) + for j, n in enumerate(offsets) if j != idx), + key=lambda t: (t[0], t[1]))[:8] + if not near: + out.append(m) + continue + dx = median([t[2]['dx'] for t in near]) + dy = median([t[2]['dy'] for t in near]) + if math.hypot(m['dx'] - dx, m['dy'] - dy) <= lim: + out.append(m) + return out + +def mapDelta(h, x, y, dx, dy): + a = map_h(h, x, y) + b = map_h(h, x + dx, y + dy) + return [b[0] - a[0], b[1] - a[1]] + +def llr(c, mode, sigma, glare=False): + if glare: + return [0] if mode else [0, 0, 0] + v = lab(c) + classes = [0, 8] if mode else [0, 1, 2, 3, 4, 5, 6, 7] + logp = [-dist(v, LAB[k]) / (2 * sigma * sigma) for k in classes] + mx = max(logp) + p = [math.exp(x - mx) for x in logp] + out = [] + for b_ in range(1 if mode else 3): + a = 1e-6 + z_ = 1e-6 + for i in range(len(classes)): + sym = classes[i] + bit = (1 if sym == 0 else 0) if mode else ((sym ^ (sym >> 1)) >> (2 - b_)) & 1 + if bit: + a += p[i] + else: + z_ += p[i] + out.append(clamp(math.log(z_ / a), -CFG['llrClamp'], CFG['llrClamp'])) + return out + +def parseHeader(hb): + bits = [1 if x < 0 else 0 for x in hb] + at = [0] + def read(n): + v = 0 + for _ in range(n): + v = (v << 1) | bits[at[0]] + at[0] += 1 + return v + size = read(3) + ecc = read(2) + mode = read(1) + type_ = read(1) + length = read(13) + crc = read(4) + if crc4(bits[:20]) != crc or size > 5: + raise ValueError('stageError header: Header checksum did not pass') + if length > capacity(size, ecc, mode)['payload']: + raise ValueError('stageError header: Invalid length') + return {'size': size, 'ecc': ecc, 'mode': mode, 'type': type_, 'length': length} + +def headerCandidates(hb, size, mode): + soft = np.array(hb, dtype=np.float32) + for k in range(3): + soft[k] = np.float32(-36 if ((size >> (2 - k)) & 1) else 36) + soft[5] = np.float32(-36 if mode else 36) + uncertain = [i for i in range(24) if i not in (0, 1, 2, 5)] + uncertain.sort(key=lambda i: abs(float(hb[i]))) + uncertain = uncertain[:12] + out = [] + def test(flips): + b = np.array(soft, dtype=np.float32) + cost = 0.0 + for i in flips: + b[i] = np.float32(-b[i]) + cost += abs(float(hb[i])) + try: + h = parseHeader(b) + if h['size'] == size and h['mode'] == mode: + out.append({'h': h, 'cost': cost}) + except ValueError: + pass + test([]) + for i in range(len(uncertain)): + test([uncertain[i]]) + for j in range(i + 1, len(uncertain)): + test([uncertain[i], uncertain[j]]) + for k in range(j + 1, len(uncertain)): + test([uncertain[i], uncertain[j], uncertain[k]]) + out.sort(key=lambda o: o['cost']) + seen = set() + res = [] + for o in out: + key = (o['h']['size'], o['h']['ecc'], o['h']['mode'], o['h']['type'], o['h']['length']) + if key in seen: + continue + seen.add(key) + res.append(o['h']) + if len(res) >= 12: + break + return res + +def decodeClass(cls): + if cls.get('mixDecoded') is not None: + return cls['mixDecoded'] + last = None + for header in (cls.get('headers') or [cls['header']]): + for variant in (0, 1): + stream = cls['stream'] + if variant: + random = rng(0xC0DE) + stream = np.array([np.float32(-v if random() < .5 else v) for v in cls['stream']], dtype=np.float32) + try: + decoded = decodeStream(header, stream) + decoded['variant'] = 'generator-whitened' if variant else 'original' + return decoded + except Exception as e: + last = e + raise last if last else ValueError('stageError header: Header checksum did not pass') + +def classify(f, h, l, mode, white, mesh): + if PRISM_MIX and not mode: + # palette-mixing recovery before the normal path. + # (JS also extends PrismFastDeadline here; budgets are not enforced in the port.) + try: + z = mixRecover(f, mixFit(f, h, l), l) + if z is not None: + return {'mixDecoded': z, 'header': z['header'], 'headers': [z['header']], + 'stream': np.zeros(0, dtype=np.float32), 'knownMatch': 1, 'sigma': 6} + except Exception: + pass + cal = calibrate(f, h, l, mode, white, mesh) + hb = np.zeros(24, dtype=np.float32) + for c in l['headers']: + v = sample(f, h, c, white, mesh) + corrected = cal['correction'](v, c) + idx = c['header'] % 24 + hb[idx] = np.float32(float(hb[idx]) + llr(corrected, 1, cal['sigma'], False)[0]) + headers = [hd for hd in headerCandidates(hb, l['size'], mode) + if hd['length'] != 0 or _headerMatchesDirect(hb, hd)] + header = headers[0] if headers else None + if not header: + raise ValueError('stageError header: Header checksum did not pass') + if header['size'] != l['size'] or header['mode'] != mode: + raise ValueError('stageError header: Header conflicts with geometry') + stream = np.zeros(l['data'].__len__() * (1 if mode else 3), dtype=np.float32) + points = [] + ext_glare = None + glare_samples = None + at = 0 + for c in l['data']: + v = sample(f, h, c, white, mesh) + cv = cal['correction'](v, c) + glare = (not mode) and all(x > CFG['glareThreshold'] for x in v) + soft = llr(cv, mode, cal['sigma'], glare) + if (not mode) and l['size'] <= 1 and (not glare) and all(x > .7 for x in v): + if ext_glare is None: + ext_glare = [] + ext_glare.append(at) + if glare and l['size'] <= 1: + if glare_samples is None: + glare_samples = [] + glare_samples.append({'at': at, 'cv': cv}) + for q in soft: + stream[at] = np.float32(q) + at += 1 + points.append({'x': c['x'], 'y': c['y'], + 'confidence': min(abs(s) for s in soft) / 12}) + if PRISM_VEIL and not mode: + try: + _veil(f, h, l, white, mesh, stream, points) + except Exception: + pass + if PRISM_DD and not mode: + _dd(f, h, l, white, mesh, cal, stream, points) + matched = 0 + for v in cal['refs']: + if nearest(cal['correction'](v['o'], v['c']), mode)['symbol'] == knownSymbol(v['c'], mode): + matched += 1 + return {'header': header, 'headers': headers, 'stream': stream, 'hb': hb, + 'sigma': cal['sigma'], 'points': points, + 'extendedGlare': ext_glare, 'glareSamples': glare_samples, + 'knownMatch': matched / len(cal['refs'])} + +def _headerMatchesDirect(hb, hd): + try: + direct = parseHeader(hb) + return all(direct[k] == hd[k] for k in ('size', 'ecc', 'mode', 'type', 'length')) + except ValueError: + return False + +def PADK(o): + x = _imul32((o + 0x9E3779B9) & 0xFFFFFFFF, 0x85EBCA6B) + x ^= x >> 13 + x = _imul32(x, 0xC2B2AE35) + x ^= x >> 16 + return x & 255 + +def _imul32(a, b): + return (a & 0xFFFFFFFF) * (b & 0xFFFFFFFF) & 0xFFFFFFFF + +def padVote(h, st): + if not (h['length'] > 0): + return True + c = capacity(h['size'], h['ecc'], h['mode']) + by = [0] * c['n'] + bl = c['blocks'] + for i in range(c['n']): + v = 0 + for k in range(8): + v = (v << 1) | (1 if st[8 * i + k] < 0 else 0) + by[i] = v + offs = [] + a = 0 + for b in bl: + offs.append(a) + a += b['k'] + at = 0 + z = 0 + q = 0 + maxn = max(b['n'] for b in bl) + for p in range(maxn): + for j in range(len(bl)): + b = bl[j] + if p < b['n']: + if p < b['k'] and offs[j] + p >= h['length'] + 4: + v = by[at] + if v == 0: + z += 1 + if v == PADK(offs[j] + p): + q += 1 + at += 1 + return q >= z + +def PLcd(l): + if 'cd' in l: + return l['cd'] + cx = l['W'] / 2 + cy = l['H'] / 2 + a = [] + for k, c in enumerate(l['data']): + dx = c['x'] - cx + dy = c['y'] - cy + a.append({'c': c, 'k': k, 'b': int(math.sqrt(dx * dx + dy * dy) / 3)}) + a.sort(key=lambda o: (-o['b'], o['k'])) + l['cd'] = [o['c'] for o in a] + return l['cd'] + +def PLfb(h, st, DEC, LAY): + l = LAY(h['size']) + cd = PLcd(l) + N = len(l['data']) + m = 1 if h['mode'] else 3 + if len(st) < N * m: + raise ValueError() + if 'pos' not in l: + l['pos'] = {c['index']: k for k, c in enumerate(l['data'])} + s2 = np.zeros(N * m, dtype=np.float32) + for k in range(N): + p = l['pos'][cd[k]['index']] + for j in range(m): + s2[k * m + j] = np.float32(st[p * m + j]) + n1 = int(N * .12) + ga = gb = gc = gd = 0 + for k in range(N): + v = 0.0 + for j in range(m): + v += abs(float(s2[k * m + j])) + if k >= N - n1: + ga += v + gb += 1 + elif k < N / 2: + gc += v + gd += 1 + if ga / gb > 0.9 * gc / gd: + raise ValueError() + err = None + for f_ in (.1, .18, .26, .34): + s3 = np.array(s2, dtype=np.float32) + for k in range(int(N * (1 - f_)), N): + for j in range(m): + s3[k * m + j] = np.float32(0) + try: + return DEC(h, s3) + except Exception as e: + err = e + raise err + +PRISM_NOLOGO = False +PRISM_CALMED = False # globalThis.PrismCalmed (calmedon chain entry) +PRISM_PQ = False # globalThis.PrismPQ (cenon/veil chain entries) +PRISM_DD = False # globalThis.PrismDD (cenon chain entry) - NOT YET PORTED +PRISM_VEIL = False # globalThis.PrismVeil (veil chain entry) - NOT YET PORTED +PRISM_MIX = False # globalThis.PrismMixMode (palette-mix first attempt) +MIX_SYMBOLS = None # globalThis.__mixSymbols + +def decodeStream(h, st): + try: + return decodeStream0(h, st) + except Exception as e: + if not PRISM_NOLOGO: + try: + return PLfb(h, st, decodeStream0, layout) + except Exception: + pass + raise e + +def decodeStream0(header, stream): + t = padVote(header, stream) + try: + return decodeStreamP(header, stream, t) + except Exception as e: + try: + return decodeStreamP(header, stream, not t) + except Exception: + raise e + +def decodeStreamP(header, stream, PK): + cap = capacity(header['size'], header['ecc'], header['mode']) + n = cap['n'] + bytes_ = [0] * n + conf = np.zeros(n, dtype=np.float32) + for i in range(n): + v = 0 + q = 12.0 + for k in range(8): + s = stream[8 * i + k] + v = (v << 1) | (1 if s < 0 else 0) + q = min(q, abs(float(s))) + bytes_[i] = v + conf[i] = np.float32(q) + blocks = [] + for b in cap['blocks']: + blocks.append({'bytes': [0] * b['n'], 'conf': [0.0] * b['n'], + 'candidates': [], 'tried': set(), + 'n': b['n'], 'nsym': b['nsym'], 'k': b['k']}) + at = 0 + maxn = max(b['n'] for b in blocks) + for p in range(maxn): + for b in blocks: + if p < b['n']: + b['bytes'][p] = bytes_[at] + b['conf'][p] = float(conf[at]) + at += 1 + messageOffset = 0 + for b in blocks: + b['offset'] = messageOffset + for p in range(b['k']): + if header['length'] > 0 and messageOffset + p >= header['length'] + 4: + b['bytes'][p] = PADK(messageOffset + p) if PK else 0 + b['conf'][p] = 12.0 + messageOffset += b['k'] + b['order'] = sorted(range(b['n']), key=lambda i: b['conf'][i]) + + def attempt(b, m): + if m in b['tried']: + return + b['tried'].add(m) + if 'syn' not in b: + b['syn'] = syndromes(b['bytes'], b['nsym']) + try: + ok = rsDecode(b['bytes'], b['nsym'], b['order'][:m], b['syn']) + except Exception: + return + for p in range(b['k']): + if b['offset'] + p >= header['length'] + 4 and ok['bytes'][p] != (PADK(b['offset'] + p) if PK else 0): + return + data = ok['bytes'][:b['k']] + if any(all(x == data[i] for i, x in enumerate(v['data'])) for v in b['candidates']): + return + score = 0.0 + for p in range(b['n']): + if ok['bytes'][p] != b['bytes'][p]: + score += .02 + b['conf'][p] + b['candidates'].append({'data': data, 'corrected': ok['corrected'], 'erasures': m, 'score': score}) + b['candidates'].sort(key=lambda c: c['score']) + del b['candidates'][8:] + + def assemble(): + combinations = [0] + found = [None] + def visit(i, msg, corrected, erasures): + if found[0] or combinations[0] >= 1024: + return + if i == len(blocks): + combinations[0] += 1 + payload = bytes(msg[:header['length']]) + crc = 0 + for v in msg[header['length']:header['length'] + 4]: + crc = (crc << 8) | v + if crc32(payload) == (crc & 0xFFFFFFFF): + if not header['type']: + try: + text = payload.decode('utf-8', 'strict') + except UnicodeDecodeError: + return + else: + text = None + found[0] = {'bytes': payload, 'text': text, 'header': header, + 'corrected': corrected, 'erasures': erasures} + return + for c in blocks[i]['candidates']: + d = c['data'] + msg.extend(d) + visit(i + 1, msg, corrected + c['corrected'], erasures + c['erasures']) + del msg[len(msg) - len(d):] + visit(0, [], 0, 0) + return found[0] + + for b in blocks: + seen_q = [] + for q in (0, .25, .5, .75, 1): + m = _jsround(b['nsym'] * q) + if m not in seen_q: + seen_q.append(m) + for m in seen_q: + attempt(b, m) + if b['candidates']: + break + result = assemble() + if result: + return result + for b in blocks: + for m in range(0, b['nsym'] + 1, 2): + attempt(b, m) + result = assemble() + if result: + return result + if any(not b['candidates'] for b in blocks): + raise ValueError("stageError RS: Error correction could not recover this image") + raise ValueError("stageError CRC: Payload checksum did not pass") + +class StageError(Exception): + def __init__(self, stage, message): + super().__init__(message) + self.stage = stage + +def _stage(e): + s = getattr(e, 'stage', None) + if s: + return s + m = str(e) + if m.startswith('stageError '): + return m.split(':', 1)[0].split(' ', 1)[1] + return None + +def decodeWithGlare(cls): + # Port of minified mA: decodeClass with glare-sample dampening retries. + try: + try: + return decodeClass(cls) + except Exception as t: + if not cls.get('glareSamples') or cls['knownMatch'] < .85: + raise + r = np.array(cls['stream'], dtype=np.float32) + for e in cls['glareSamples']: + tt = llr(e['cv'], 0, cls['sigma'], False) + for k in range(len(tt)): + r[e['at'] + k] = np.float32(.001 * tt[k]) + c2 = dict(cls) + c2['stream'] = r + c2['glareSamples'] = None + return decodeClass(c2) + except Exception: + if not cls.get('extendedGlare') or cls['knownMatch'] < .85: + raise + r = np.array(cls['stream'], dtype=np.float32) + for e in cls['extendedGlare']: + for k in range(3): + r[e + k] = np.float32(0) + c2 = dict(cls) + c2['stream'] = r + c2['glareSamples'] = None + return decodeClass(c2) + +_STAGE_RANK = {'detect': 0, 'hypothesis': 1, 'too small': 1, 'header': 2, 'RS': 3, 'CRC': 4} + +def readNormal(image, known=None, mesh_opt=True, fusion=None, debug=False): + # Port of the anonymous readNormal inside minified readImage. + I = frame(image) + hs = [] + if known: + A = layout(known['size']) + t = homography(corners(A), known['quad']) + r = whiteBalance(I, t, A) + d = dict(h=t, l=A, mode=known['mode'], quad=[p[:] for p in known['quad']], white=r) + d.update(hypothesisScore(I, t, A, known['mode'], r, False)) + hs = [d] + else: + if PRISM_PQ: + try: + cands = detectPQ(I) + except Exception: + cands = [] + try: + cands = cands + [{'quad': q, 'sz': None, 'r0': False} for q in detect(I)] + except Exception: + if not cands: + raise + else: + cands = [{'quad': q, 'sz': None, 'r0': False} for q in detect(I)] + for e in cands: + sizes = [e['sz']] if e['sz'] is not None else range(6) + rots = 1 if e['r0'] else 4 + for sz in sizes: + r_ = layout(sz) + for o in range(rots): + i_ = [e['quad'][(t + o) % 4] for t in range(4)] + try: + a = homography(corners(r_), i_) + except Exception: + continue + g_ = whiteBalance(I, a, r_) + for mode in range(2): + l_ = hypothesisScore(I, a, r_, mode, g_, True) + d = dict(h=a, l=r_, mode=mode, quad=i_, white=g_, rot=o, + pp=bool(e['r0'])) + d.update(l_) + hs.append(d) + hs.sort(key=lambda x: (-x['score'], x['cost'])) + if PRISM_PQ: + hs = [h for h in hs if not h.get('pp')][:4] + [h for h in hs if h.get('pp')][:4] + else: + hs = hs[:4] + attempts = [] + best_err = None + Q_err = StageError('hypothesis', 'Code pattern not recognized. Try better light or a closer photo.') + for hyp in hs: + try: + h = hyp['h'] + n = hyp['l'] + s = hyp['mode'] + Cq = hyp['quad'] + E = hyp['white'] + if not known and hyp['score'] > .92: + if not s and n['size'] < 4: + try: + cls = classify(I, h, n, s, E, None) + dec = decodeWithGlare(cls) + return dict(dec, quality=hyp['score'], quad=Cq, h=h, layout=n, + sigma=cls['sigma'], + radius=math.hypot(Cq[1][0] - Cq[0][0], Cq[1][1] - Cq[0][1]) / n['W']) + except Exception: + pass + if not known: + rr = refine(I, h, n, s, Cq, E) + h = rr['h'] + Cq = rr['quad'] + E = whiteBalance(I, h, n) + B = hypothesisScore(I, h, n, s, E, False)['score'] + if B < (.75 if s else CFG['minScore']): + raise StageError('hypothesis', 'Known cells do not match') + frad = min(math.hypot(*mapDelta(h, n['W'] / 2, n['H'] / 2, 1, 0)), + math.hypot(*mapDelta(h, n['W'] / 2, n['H'] / 2, 0, 1))) + if frad < (2 if n['size'] >= 4 else CFG['minRadius']): + raise StageError('too small', 'Too small. Move closer or use a larger image.') + c = None + m = None + try: + c = classify(I, h, n, s, E, None) + except Exception as ex: + if not mesh_opt: + raise + Q_err = ex + w = None + try: + if c: + w = decodeWithGlare(c) + except Exception as ex: + Q_err = ex + if not w and mesh_opt: + m = buildMesh(I, h, n, s, E, None) + m = buildMesh(I, h, n, s, E, m) + c = classify(I, h, n, s, E, m) + try: + w = decodeWithGlare(c) + except Exception as ex: + Q_err = ex + if fusion is not None and c: + st = fusion.add(c['header'], c['stream'], B) + if not w: + try: + c2 = dict(c) + c2['stream'] = st + w = decodeWithGlare(c2) + except Exception as ex: + Q_err = ex + if w: + return dict(w, quality=B, radius=frad, quad=Cq, h=h, layout=n, + points=c['points'] if debug else None, sigma=c['sigma']) + raise Q_err + except Exception as ex: + if best_err is None or _STAGE_RANK.get(_stage(ex), 0) > _STAGE_RANK.get(_stage(best_err), 0): + best_err = ex + attempts.append({'size': hyp['l']['size'], 'mode': hyp['mode'], + 'score': hyp.get('score'), 'cost': hyp.get('cost'), + 'stage': _stage(ex), 'message': str(ex)}) + if not (Q_err is not None and _stage(ex) not in ('RS', 'CRC') + and _stage(Q_err) in ('RS', 'CRC')): + Q_err = ex + err = best_err if best_err is not None else Q_err + err.attempts = attempts + raise err + +def readImage(image, known=None, debug=False, exportFallback=True, mesh=True, + fusion=None): + # Port of minified Prism.readImage with exportFallback unsupported (the live + # worker calls it with exportFallback:false; generator-export is out of scope). + try: + r = readNormal(image, known=known, mesh_opt=mesh, fusion=fusion, debug=debug) + if not r['bytes'] and r['quality'] < .8: + raise StageError('hypothesis', 'Empty result lacks a strong code-pattern match') + return r + except Exception as ex: + err = ex + raise err + +# ===== PrismLocal.normalize (worker JS fallback; WASM differential-tested) ===== + +def _sliding_max_rows(A, w, h, r): + # exact port of the JS monotonic-deque pass with clamped indices + o = np.zeros(A.shape, dtype=np.float32) + i_size = max(w, h) + 2 * r + 1 + g = [0] * i_size + l = [0.0] * i_size + for y in range(h): + t = 0 + i = 0 + I = y * w + for a in range(-r, w + r): + idx = I + max(0, min(w - 1, a)) + hv = float(A[idx]) + while i > t and l[i - 1] <= hv: + i -= 1 + g[i] = a + l[i] = hv + i += 1 + while g[t] < a - 2 * r: + t += 1 + if a >= r: + o[I + a - r] = np.float32(l[t]) + return o + +def _sliding_max_cols(inp, w, h, r): + out = np.zeros(inp.shape, dtype=np.float32) + i_size = max(w, h) + 2 * r + 1 + g = [0] * i_size + l = [0.0] * i_size + for x in range(w): + t = 0 + i = 0 + for hh in range(-r, h + r): + idx = max(0, min(h - 1, hh)) * w + x + nv = float(inp[idx]) + while i > t and l[i - 1] <= nv: + i -= 1 + g[i] = hh + l[i] = nv + i += 1 + while g[t] < hh - 2 * r: + t += 1 + if hh >= r: + out[(hh - r) * w + x] = np.float32(l[t]) + return out + +def localNormalize(image): + # PrismLocal.normalize (JS fallback path, differential-tested vs WASM) + w = image['width'] + h = image['height'] + data = image['data'] + arr = np.frombuffer(data, dtype=np.uint8) if not isinstance(data, np.ndarray) else data + hist = [np.zeros(256, dtype=np.uint32) for _ in range(3)] + a = [np.zeros(w * h, dtype=np.float32) for _ in range(3)] + px = arr[:w * h * 4].reshape(-1, 4) + for c in range(3): + col = px[:, c] + hist[c] = np.bincount(col, minlength=256).astype(np.uint32) + a[c] = col.astype(np.float32) + black = [] + for c in range(3): + r = 0 + v = 0 + for o in range(256): + r += int(hist[c][o]) + if r > w * h * .02: + v = o + break + black.append(v) + r2 = _jsround(.035 * min(w, h)) + out = np.zeros(w * h * 4, dtype=np.uint8) + for c in range(3): + gmap = _sliding_max_cols(_sliding_max_rows(a[c], w, h, r2), w, h, r2) + for i in range(w * h): + v = 255 * (float(a[c][i]) - black[c]) / max(30, float(gmap[i]) - black[c]) + out[4 * i + c] = _u8(v) + for i in range(w * h): + out[4 * i + 3] = 255 + return {'width': w, 'height': h, 'data': out} + +# ===== PrismDistance.fields (JS fallback; WASM differential-tested) ===== + +class DistanceFields: + __slots__ = ('maps', 'scale', 'w', 'h') + def __init__(self, maps, scale, w, h): + self.maps = maps + self.scale = scale + self.w = w + self.h = h + def at(self, sym, x, y): + y *= self.scale + x *= self.scale + if x < 0 or y < 0 or x >= self.w - 1 or y >= self.h - 1: + return 12 + i = math.floor(x) + l = math.floor(y) + I = x - i + hh = y - l + n = self.maps[sym] + s = l * self.w + i + return ((float(n[s]) * (1 - I) + float(n[s + 1]) * I) * (1 - hh) + + (float(n[s + self.w]) * (1 - I) + float(n[s + self.w + 1]) * I) * hh) + +def _chamfer(A, w, h): + for y in range(h): + for x in range(w): + o = y * w + x + a = float(A[o]) + if x: + a = min(a, float(A[o - 1]) + 1) + if y: + a = min(a, float(A[o - w]) + 1) + if x and y: + a = min(a, float(A[o - w - 1]) + 1.414) + if x < w - 1 and y: + a = min(a, float(A[o - w + 1]) + 1.414) + A[o] = np.float32(a) + for y in range(h - 1, -1, -1): + for x in range(w - 1, -1, -1): + o = y * w + x + a = float(A[o]) + if x < w - 1: + a = min(a, float(A[o + 1]) + 1) + if y < h - 1: + a = min(a, float(A[o + w]) + 1) + if x < w - 1 and y < h - 1: + a = min(a, float(A[o + w + 1]) + 1.414) + if x and y < h - 1: + a = min(a, float(A[o + w - 1]) + 1.414) + A[o] = np.float32(a) + +def distFields(image): + w0 = image['width'] + h0 = image['height'] + data = image['data'] + arr = np.frombuffer(data, dtype=np.uint8) if not isinstance(data, np.ndarray) else data + e = min(1, 240 / max(w0, h0)) + t = _jsround(w0 * e) + r = _jsround(h0 * e) + hist = [np.zeros(256, dtype=np.uint32) for _ in range(3)] + d = arr[:w0 * h0 * 4] + for off in range(0, w0 * h0 * 4, 16): + for c in range(3): + hist[c][d[off + c]] += 1 + a_count = -(-(w0 * h0 * 4) // 16) + levels = [] + for c in range(3): + lo = 0 + hi = 255 + acc = 0 + for v in range(256): + acc += int(hist[c][v]) + if acc >= .02 * a_count: + lo = v + break + acc = 0 + for v in range(256): + acc += int(hist[c][v]) + if acc >= .98 * a_count: + hi = v + break + levels.append((lo, hi)) + maps = [np.full(t * r, 1e3, dtype=np.float32) for _ in range(9)] + cache = {} + for oy in range(r): + for ox in range(t): + off = 4 * (int(oy / e) * w0 + int(ox / e)) + I = [max(0.0, min(1.0, (int(d[off + c]) - levels[c][0]) / max(20, levels[c][1] - levels[c][0]))) + for c in range(3)] + key = 32 * (32 * _jsround(31 * I[0]) + _jsround(31 * I[1])) + _jsround(31 * I[2]) + sym = cache.get(key) + if sym is None: + sym = nearest([lin(v) for v in I], 0)['symbol'] + cache[key] = sym + maps[sym][oy * t + ox] = np.float32(0) + for A in maps: + _chamfer(A, t, r) + for A in maps: + einv = np.array([np.float32(1e3 if v == 0 else 0) for v in A], dtype=np.float32) + _chamfer(einv, t, r) + for i in range(len(A)): + A[i] = np.float32(float(A[i]) / .6 + .7 * max(0.0, 1.7 - float(einv[i]) / .6)) + return DistanceFields(maps, e, t, r) + +# ===== detectTexture (minified, caches omitted) ===== + +def detectTexture(f): + edge = TEXTURE_CONFIG.get('edge', .13) if TEXTURE_CONFIG else .13 + t = min(1, 320 / max(f.w, f.h)) + i = _jsround(f.w * t) + g = _jsround(f.h * t) + l = np.zeros(i * g * 3, dtype=np.float32) + for yy in range(g): + for xx in range(i): + a = xx / t + gg = yy / t + I = 3 * (yy * i + xx) + if a < 0 or gg < 0 or a >= f.w - 1 or gg >= f.h - 1: + v = srgb(1) + l[I] = l[I + 1] = l[I + 2] = np.float32(v) + continue + hx = math.floor(a) + ny = math.floor(gg) + s = a - hx + C = gg - ny + Q = 3 * (ny * f.w + hx) + for c in range(3): + v = ((float(f.p[Q + c]) * (1 - s) + float(f.p[Q + 3 + c]) * s) * (1 - C) + + (float(f.p[Q + 3 * f.w + c]) * (1 - s) + float(f.p[Q + 3 * f.w + 3 + c]) * s) * C) + l[I + c] = np.float32(srgb(v)) + edgeMap = np.zeros(i * g, dtype=np.float32) + for yy in range(1, g - 1): + for xx in range(1, i - 1): + tt = 3 * (yy * i + xx) + best = 0.0 + for A in range(2): + off = tt + (3 * i if A else 3) + o = 0.0 + for c in range(3): + o += (float(l[tt + c]) - float(l[off + c])) ** 2 + best = max(best, math.sqrt(o)) + edgeMap[yy * i + xx] = np.float32(1 if best > edge else 0) + integ = np.zeros((i + 1) * (g + 1), dtype=np.float32) + for yy in range(g): + acc = 0.0 + for xx in range(i): + acc += float(edgeMap[yy * i + xx]) + integ[(yy + 1) * (i + 1) + xx + 1] = np.float32(integ[yy * (i + 1) + xx + 1] + acc) + thresh = TEXTURE_CONFIG.get('threshold', .33) if TEXTURE_CONFIG else .33 + radius = TEXTURE_CONFIG.get('radius', 4) if TEXTURE_CONFIG else 4 + h = np.zeros(i * g, dtype=np.uint8) + for yy in range(g): + for xx in range(i): + t0 = max(0, xx - radius) + r0 = min(i, xx + radius + 1) + o0 = max(0, yy - radius) + a0 = min(g, yy + radius + 1) + cnt = (float(integ[a0 * (i + 1) + r0]) - float(integ[o0 * (i + 1) + r0]) + - float(integ[a0 * (i + 1) + t0]) + float(integ[o0 * (i + 1) + t0])) + h[yy * i + xx] = 1 if cnt / ((r0 - t0) * (a0 - o0)) > thresh else 0 + h = np.asarray(morph(h, i, g, 1, True), dtype=np.uint8) + h = np.asarray(morph(h, i, g, 1, False), dtype=np.uint8) + seen = np.zeros(len(h), dtype=np.uint8) + Qlist = [] + Cqueue = [0] * len(h) + for start in range(len(h)): + if not h[start] or seen[start]: + continue + e_ = 0 + t_ = 1 + boundary = [] + Cqueue[0] = start + seen[start] = 1 + while e_ < t_: + cur = Cqueue[e_] + e_ += 1 + ox = cur % i + oy = cur // i + is_b = False + for d4 in range(4): + if d4 == 0: + nb = cur - 1 if ox > 0 else -1 + elif d4 == 1: + nb = cur + 1 if ox < i - 1 else -1 + elif d4 == 2: + nb = cur - i if oy > 0 else -1 + else: + nb = cur + i if oy < g - 1 else -1 + if nb < 0 or not h[nb]: + is_b = True + elif not seen[nb]: + seen[nb] = 1 + Cqueue[t_] = nb + t_ += 1 + if is_b: + boundary.append([ox, oy]) + if t_ < 100: + continue + hu = hull(boundary) + ar = area(hu) + xs = [p[0] for p in hu] + ys = [p[1] for p in hu] + aspect = (max(xs) - min(xs)) / (max(ys) - min(ys)) + if t_ / ar < .04 or aspect < .4 or aspect > 2.5: + continue + Qlist.append({'hu': hu, 'tail': t_, 'boundary': boundary, 'ar': ar}) + Qlist.sort(key=lambda q: -q['ar']) + if not Qlist: + raise StageError('detect', 'No code found. Use a plain background with a wide white margin.') + E = [] + for cand in Qlist[:3]: + hu = cand['hu'] + bestRect = None + bestArea = math.inf + for rr in range(len(hu)): + p0 = hu[rr] + p1 = hu[(rr + 1) % len(hu)] + gx = p1[0] - p0[0] + gy = p1[1] - p0[1] + L = math.hypot(gx, gy) + gx /= L + gy /= L + hs = [p[0] * gx + p[1] * gy for p in hu] + ns = [-p[0] * gy + p[1] * gx for p in hu] + s0 = min(hs) + C0 = max(hs) + q0 = min(ns) + E0 = max(ns) + B = (C0 - s0) * (E0 - q0) + if B < bestArea: + bestArea = B + bestRect = [[(A * gx - b * gy + .5) / t, (A * gy + b * gx + .5) / t] + for A, b in ([s0, q0], [C0, q0], [C0, E0], [s0, E0])] + if bestRect: + E.append(bestRect) + r = [p[:] for p in hu] + while len(r) > 4: + mn = math.inf + at = 0 + for k in range(len(r)): + pa = r[(k + len(r) - 1) % len(r)] + pb = r[(k + 1) % len(r)] + v = abs(cross(pa, r[k], pb)) / max(.1, math.hypot(pb[0] - pa[0], pb[1] - pa[1])) + if v < mn: + mn = v + at = k + r.pop(at) + if len(r) == 4: + E.append([[ (v + .5) / t for v in p] for p in r]) + lines = [] + for k in range(4): + p0 = r[k] + p1 = r[(k + 1) % 4] + i0 = next((ix for ix, p in enumerate(hu) if p[0] == p0[0] and p[1] == p0[1]), -1) + g0 = next((ix for ix, p in enumerate(hu) if p[0] == p1[0] and p[1] == p1[1]), -1) + longest = None + longestLen = 0.0 + kk = i0 + while kk != g0: + pa = hu[kk] + pb = hu[(kk + 1) % len(hu)] + dd = math.hypot(pa[0] - pb[0], pa[1] - pb[1]) + if dd > longestLen: + longestLen = dd + longest = [pa, pb] + kk = (kk + 1) % len(hu) + hp, hn = longest if longest else (p0, p1) + pts = [p for p in cand['boundary'] + if abs(cross(hp, hn, p)) / max(1, longestLen) < 2] + lines.append(fitLine(pts if len(pts) > 2 else [hp, hn])) + try: + quad = [intersect(lines[(k + 3) % 4], lines[k]) for k in range(4)] + ar2 = area(quad) + if .6 * cand['ar'] < ar2 < 1.5 * cand['ar']: + E.append([[ (v + .5) / t for v in p] for p in quad]) + except Exception: + pass + o = [p[:] for p in hu] + while len(o) > 4: + mn = math.inf + at = 0 + for k in range(len(o)): + pa = o[(k + len(o) - 1) % len(o)] + pb = o[(k + 1) % len(o)] + v = abs(cross(pa, o[k], pb)) / math.hypot(pb[0] - pa[0], pb[1] - pa[1]) + if v < mn: + mn = v + at = k + if mn > .7: + break + o.pop(at) + edges = sorted(({'a': p, 'b': o[(k + 1) % len(o)], 'i': k, + 'len': math.hypot(p[0] - o[(k + 1) % len(o)][0], p[1] - o[(k + 1) % len(o)][1])} + for k, p in enumerate(o)), key=lambda ed: -ed['len'])[:4] + edges.sort(key=lambda ed: ed['i']) + lines2 = [] + for k in range(4): + pa = edges[k]['a'] + pb = edges[k]['b'] + dx = pb[0] - pa[0] + dy = pb[1] - pa[1] + L = math.hypot(dx, dy) + pts = [p for p in cand['boundary'] if abs(cross(pa, pb, p)) / L < 2] + lines2.append(fitLine(pts) if len(pts) >= 2 else fitLine([pa, pb])) + try: + quad = [intersect(lines2[(k + 3) % 4], lines2[k]) for k in range(4)] + E.append([[ (v + .5) / t for v in p] for p in quad]) + except Exception: + pass + if not E: + raise StageError('detect', 'Could not fit four edges') + return E + +TEXTURE_CONFIG = None + +# ===== PrismDistFit.read (minified) ===== + + +def _map_h_vec(h, xs, ys): + # Bit-identical to [map_h(h, x, y) for x, y in zip(xs, ys)]. + w = getattr(h, 'warp', None) + x = xs.astype(np.float64).copy() + y = ys.astype(np.float64).copy() + if w: + W = w['W'] + H_ = w['H'] + p = w['p'] + u = 2 * x / W - 1 + v = 2 * y / H_ - 1 + p6 = p[6] if len(p) > 6 else 0 + p7 = p[7] if len(p) > 7 else 0 + p8 = p[8] if len(p) > 8 else 0 + p9 = p[9] if len(p) > 9 else 0 + x += (1 - u * u) * (p[0] + p[1] * v) + p[2] * (1 - v * v) + p6 * u * (1 - u * u) + p8 * u * (1 - v * v) + y += (1 - v * v) * (p[3] + p[4] * u) + p[5] * (1 - u * u) + p7 * v * (1 - u * u) + p9 * v * (1 - v * v) + d = h[6] * x + h[7] * y + 1 + return (h[0] * x + h[1] * y + h[2]) / d, (h[3] * x + h[4] * y + h[5]) / d + +def _fields_at_vec(fields, syms, xs, ys): + # Bit-identical to [fields.at(sym, x, y) per element]; syms int array or scalar. + y = ys * fields.scale + x = xs * fields.scale + out = np.full(len(xs), 12.0, dtype=np.float64) + ok = (x >= 0) & (y >= 0) & (x < fields.w - 1) & (y < fields.h - 1) + if not ok.any(): + return out + xo = x[ok] + yo = y[ok] + i = np.floor(xo).astype(np.int64) + l = np.floor(yo).astype(np.int64) + I = xo - i + hh = yo - l + s_ = l * fields.w + i + w_ = fields.w + + def _gather(nmap, ss, I2, hh2): + return ((nmap[ss].astype(np.float64) * (1 - I2) + nmap[ss + 1].astype(np.float64) * I2) * (1 - hh2) + + (nmap[ss + w_].astype(np.float64) * (1 - I2) + nmap[ss + w_ + 1].astype(np.float64) * I2) * hh2) + + if np.isscalar(syms): + out[ok] = _gather(fields.maps[syms], s_, I, hh) + return out + r = np.empty(len(xo), dtype=np.float64) + sok = syms[ok] + for sym in np.unique(sok): + m2 = sok == sym + r[m2] = _gather(fields.maps[int(sym)], s_[m2], I[m2], hh[m2]) + out[ok] = r + return out + +def _warpCostInit(h, l, fields): + # lowercase i() in DistFit.read: 48-subsample known-cell cost (JS fallback) + known = l['known'] + step = max(1, len(known) // 48) + cells = known[::step] + xs = np.array([c['x'] for c in cells], dtype=np.float64) + ys = np.array([c['y'] for c in cells], dtype=np.float64) + sy = np.array([int(knownSymbol(c, 0)) for c in cells], dtype=np.int64) + gx, gy = _map_h_vec(h, xs, ys) + D = _fields_at_vec(fields, sy, gx, gy) + r = 0.0 + o = 0 + for lv in D: + r += min(25, lv * lv) + o += 1 + return {'cost': r / o, 'score': 1 / (1 + r / o)} + +def distFitRead(image): + # PrismDistFit.read: marker-free normalized detect + nonlinear internal fit + fields = distFields(image) + f = frame(image) + cands = [] + try: + cands.extend(detectTexture(f)) + except Exception: + pass + try: + for cfg in ({'threshold': .5, 'edge': .13}, {'threshold': .4, 'edge': .2}): + global TEXTURE_CONFIG + TEXTURE_CONFIG = cfg + cands.extend(detectTexture(f)) + TEXTURE_CONFIG = None + except Exception: + TEXTURE_CONFIG = None + # dedupe quads: any rotation with corner squared-distance sum < 100 + kept = [] + for qd in cands: + dup = False + for prev in kept: + for rot in range(4): + s = sum((qd[k][0] - prev[(k + rot) % 4][0]) ** 2 + + (qd[k][1] - prev[(k + rot) % 4][1]) ** 2 for k in range(4)) + if s < 100: + dup = True + break + if dup: + break + if not dup: + kept.append(qd) + cands = kept + scaled = [] + for qd in cands: + for sc in (1, 1.04, 1.08): + cx = sum(p[0] for p in qd) / 4 + cy = sum(p[1] for p in qd) / 4 + scaled.append([[cx + (p[0] - cx) * sc, cy + (p[1] - cy) * sc] for p in qd]) + o = [] + for C in scaled: + for Q in range(6): + E = layout(Q) + for B in range(4): + fq = [C[(k + B) % 4][:] for k in range(4)] + c = homography(corners(E), fq) + w = _warpCostInit(c, E, fields) + u = [0.0] * 10 + for d6 in (-6, 0, 6): + for y6 in (-6, 0, 6): + for M in (0, 6): + for D in (0, 3): + c.warp = {'W': E['W'], 'H': E['H'], + 'p': [d6, 0, 0, 0, 0, y6, M, D, 0, 0]} + p = _warpCostInit(c, E, fields) + if p['score'] > w['score'] or (p['score'] == w['score'] and p['cost'] < w['cost']): + w = p + u = c.warp['p'][:] + for F in (-6, 0, 6): + for k6 in (-6, 0, 6): + for G in (0, -3): + c.warp = {'W': E['W'], 'H': E['H'], + 'p': [0, 0, F, k6, 0, 0, 0, 0, G, G]} + b = _warpCostInit(c, E, fields) + if b['score'] > w['score']: + w = b + u = c.warp['p'][:] + c.warp = {'W': E['W'], 'H': E['H'], 'p': u} + d = dict(h=c, l=E, white=None, quad=fq) + d.update(w) + o.append(d) + o.sort(key=lambda x: (-x['score'], x['cost'])) + kept2 = [] + for L in o: + dup = False + for prev in kept2: + if L['l']['size'] != prev['l']['size']: + continue + s = sum((L['quad'][k][0] - prev['quad'][k][0]) ** 2 + + (L['quad'][k][1] - prev['quad'][k][1]) ** 2 for k in range(4)) + if s < 2 and all(abs(a - b) < .1 for a, b in zip(L['h'].warp['p'], prev['h'].warp['p'])): + dup = True + break + if not dup: + kept2.append(L) + o = kept2 + g_err = Exception('Nonlinear geometry did not decode') + warp_debug = [] + for L in o[:20]: + R = L['h'] + S = L['l'] + N = L['quad'] + U = R.warp + R.warp = U + q = whiteBalance(f, R, S) + J = [c for k, c in enumerate(S['known']) + if k % max(1, len(S['known']) // 160) == 0] + H = [[c for c in S['headers'] if c['header'] % 24 == e_] for e_ in range(24)] + + _Jx = np.array([c['x'] for c in J], dtype=np.float64) + _Jy = np.array([c['y'] for c in J], dtype=np.float64) + _Js = np.array([int(knownSymbol(c, 0)) for c in J], dtype=np.int64) + _Hcells = [(c, g) for g in range(24) for c in H[g]] + _Hx = np.array([c['x'] for c, g in _Hcells], dtype=np.float64) + _Hy = np.array([c['y'] for c, g in _Hcells], dtype=np.float64) + _Hcounts = [len(H[g]) for g in range(24)] + + def costFn(): + gx, gy = _map_h_vec(R, _Jx, _Jy) + D = _fields_at_vec(fields, _Js, gx, gy) + A = [min(64, d_ * d_) for d_ in D] + A.sort() + t85 = int(.85 * len(A)) + r85 = sum(A[:t85]) / t85 + hx, hy = _map_h_vec(R, _Hx, _Hy) + Da = _fields_at_vec(fields, 8, hx, hy) + Di = _fields_at_vec(fields, 0, hx, hy) + o24 = 0.0 + cur = 0 + for A24 in range(24): + cnt = _Hcounts[A24] + t_ = 0.0 + r_ = 0.0 + for k in range(cur, cur + cnt): + t_ += min(36, Da[k] * Da[k]) + r_ += min(36, Di[k] * Di[k]) + cur += cnt + o24 += min(t_, r_) + return r85 + o24 / 72 * .35 + + W = costFn() + K = R.warp['p'] + P = K[:] + for Xv in (-8, -4, 0, 4, 8): + for Ov in (-2, 0, 3, 6, 9): + V = abs(K[2]) + abs(K[3]) > abs(K[0]) + abs(K[5]) + j = 8 if V else 6 + K[2 if V else 0] = Xv + K[j] = -Ov if V else Ov + sc = costFn() + if sc < W: + W = sc + P = K[:] + K[:] = P + for step in (2, 1, .5, .25, .125): + for _it in range(3): + improved = False + for oA in range(10): + aA = K[oA] + iA = aA + for gA in (-1, 1): + K[oA] = aA + gA * step + if abs(K[oA]) > 12: + continue + sc = costFn() + if sc < W: + W = sc + iA = K[oA] + improved = True + K[oA] = iA + tA = R.warp + rA = math.hypot(N[1][0] - N[0][0], N[1][1] - N[0][1]) / S['W'] + for IA in range(4): + for hA in range(2): + nA = N[IA][hA] + sA_ = nA + for CA_ in (-1, 1): + N[IA][hA] = nA + CA_ * step * rA * .35 + QA = H_(corners(S), N) + QA.warp = tA + prevR = R + R = QA + sc = costFn() + if sc < W: + W = sc + sA_ = N[IA][hA] + improved = True + else: + R = prevR + N[IA][hA] = sA_ + R = H_(corners(S), N) + R.warp = tA + if not improved: + break + warp_debug.append({'size': S['size'], 'score': L['score'], 'cost': W, 'warp': K[:]}) + q = whiteBalance(f, R, S) + try: + try: + cA = classify(f, R, S, 0, q, None) + if cA['knownMatch'] < .65: + raise Exception('Weak known-cell support') + cA2 = dict(cA) + cA2['headers'] = cA['headers'][:3] + fA = decodeWithGlare(cA2) + except Exception as mA_err: + if cA['knownMatch'] < .5 or W > 3.5: + raise mA_err + wA = buildDenseMesh(f, R, S, 0, q, None) + wA = buildDenseMesh(f, R, S, 0, q, wA) + cA = classify(f, R, S, 0, q, wA) + if cA['knownMatch'] < .7: + raise Exception('Weak mesh known-cell support') + cA2 = dict(cA) + cA2['headers'] = cA['headers'][:3] + fA = decodeWithGlare(cA2) + if not len(fA['bytes']): + raise Exception('Nonlinear recovery does not accept empty payload hypotheses') + return dict(fA, quality=cA['knownMatch'], quad=N, h=R, layout=S, + sigma=cA['sigma'], + radius=math.hypot(N[1][0] - N[0][0], N[1][1] - N[0][1]) / S['W'], + warp=K[:], reader='original cells + fitted nonlinear surface') + except Exception as uA_err: + g_err = uA_err + g_err.warpDebug = warp_debug + raise g_err + +def H_(src, dst): + return homography(src, dst) + +# ===== PrismFastReader.read (budgets removed; ports run unbudgeted) ===== + +def fastReaderRead(image, fb=None): + CFG['minRadius'] = .55 if PRISM_MIX else 4 # worker onmessage sets CFG.minRadius from the mix flag + if PRISM_MIX: + z = mixDirect(image) + if z is not None: + return z + err = None + try: + return readImage(image, exportFallback=False) + except Exception as e: + err = e + try: + n = localNormalize(image) + return distFitRead(n) + except Exception as e: + err = e + raise err + +# ===== lApq: PQ-mode quad detector (PrismPQ retry path) ===== + +def _pq_box(a, w, h, r): + # Float32Array box blur, truncated windows, rows then cols + t = np.zeros(w * h, dtype=np.float32) + o = np.zeros(w * h, dtype=np.float32) + a3 = a.reshape(h, w) + t3 = t.reshape(h, w) + o3 = o.reshape(h, w) + for d in range(-r, r + 1): + xs = np.clip(np.arange(w) + d, 0, w - 1) + # truncated window: weight only valid; accumulate sums and counts + valid = (np.arange(w) + d >= 0) & (np.arange(w) + d < w) + t3 += np.where(valid[None, :], a3[:, xs], 0.0).astype(np.float32) + # JS sums then divides by count; do sums/counts exactly + ts = np.zeros((h, w)); tc = np.zeros((h, w)) + for d in range(-r, r + 1): + xs = np.arange(w) + d + valid = (xs >= 0) & (xs < w) + xs_c = np.clip(xs, 0, w - 1) + ts += np.where(valid[None, :], a3[:, xs_c].astype(np.float64), 0.0) + tc += valid[None, :].astype(np.float64) + t3[:, :] = (ts / tc).astype(np.float32) + os_ = np.zeros((h, w)); oc = np.zeros((h, w)) + for d in range(-r, r + 1): + ys = np.arange(h) + d + valid = (ys >= 0) & (ys < h) + ys_c = np.clip(ys, 0, h - 1) + os_ += np.where(valid[:, None], t3[ys_c, :].astype(np.float64), 0.0) + oc += valid[:, None].astype(np.float64) + o3[:, :] = (os_ / oc).astype(np.float32) + return o + +def detectPQ(f): + sc = max(1, round(max(f.w, f.h) / 360)) + w = f.w // sc + h = f.h // sc + n = w * h + S = np.zeros(n, dtype=np.float32) + for y in range(h): + for x in range(w): + i = ((y * sc + (sc >> 1)) * f.w + x * sc + (sc >> 1)) * 3 + S[y * w + x] = np.float32(min(f.p[i], f.p[i + 1], f.p[i + 2]) ** .4545) + S = _pq_box(S, w, h, 2) + hist = np.zeros(256) + sv = np.clip(np.rint(S.astype(np.float64) * 255), 0, 255).astype(np.int64) + hist = np.bincount(sv, minlength=256).astype(np.float64) + sum_ = float((np.arange(256) * hist).sum()) + wb = 0.0; sb = 0.0; bt = 0.0; th0 = 128 + for i in range(256): + wb += hist[i] + if not wb: continue + wf = n - wb + if not wf: break + sb += i * hist[i] + mb = sb / wb + mf = (sum_ - sb) / wf + v = wb * wf * (mb - mf) * (mb - mf) + if v > bt: + bt = v; th0 = i + mg = 5.196 + out = [] + for dth in (0, 14, 28, -14): + th = th0 + dth + m = (S.astype(np.float64) * 255 > th).astype(np.float32) + m = _pq_box(m, w, h, 2) + m2 = (m.astype(np.float64) > .01).astype(np.float32) + m2 = _pq_box(m2, w, h, 2) + mk = (m2.astype(np.float64) > .99).astype(np.uint8) + seen = np.zeros(n, np.uint8) + qu = np.zeros(n, np.int64) + best = None; bestA = 0; bestBd = None + mk2 = mk.reshape(h, w) + for k in range(n): + if not mk[k] or seen[k]: continue + hd = 0; tl = 1; bd = [] + qu[0] = k; seen[k] = 1 + while hd < tl: + p = qu[hd]; hd += 1 + x = p % w; y = p // w + ed = False + for q in ((p - 1) if x > 0 else -1, (p + 1) if x < w - 1 else -1, + (p - w) if y > 0 else -1, (p + w) if y < h - 1 else -1): + if q < 0 or not mk[q]: + ed = True + continue + if not seen[q]: + seen[q] = 1 + qu[tl] = q; tl += 1 + if ed: bd.append([x, y]) + if tl < .03 * n or tl > .9 * n: continue + bd.sort(key=lambda p: (p[0], p[1])) + lo = [] + for p in bd: + while len(lo) >= 2 and _pq_cr(lo[-2], lo[-1], p) <= 0: lo.pop() + lo.append(p) + up = [] + for p in reversed(bd): + while len(up) >= 2 and _pq_cr(up[-2], up[-1], p) <= 0: up.pop() + up.append(p) + lo.pop(); up.pop() + hl = lo + up + if len(hl) < 4: continue + ar = 0.0 + for i in range(len(hl)): + a = hl[i]; b = hl[(i + 1) % len(hl)] + ar += a[0] * b[1] - b[0] * a[1] + ar = abs(ar) / 2 + if ar > bestA: + bestA = ar; best = hl; bestBd = bd + if not best: continue + po = [p[:] for p in best] + while len(po) > 4: + mn = 1e18; at = 0 + for i in range(len(po)): + a = po[(i + len(po) - 1) % len(po)] + b = po[(i + 1) % len(po)] + c = po[i] + v = abs((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) + if v < mn: + mn = v; at = i + po.pop(at) + sa = 0.0 + for i in range(4): + a = po[i]; b = po[(i + 1) % 4] + sa += a[0] * b[1] - b[0] * a[1] + if sa < 0: po.reverse() + po = [[(p[0] + .5) * sc, (p[1] + .5) * sc] for p in po] + po = _pq_refine_edges(f, po, sc) + for sz in range(6): + l = layout(sz) + PW = l['W'] + 2 * mg + PH = l['H'] + 2 * mg + for r in range(4): + q = [po[(i + r) % 4] for i in range(4)] + try: + hh = homography([[0, 0], [PW, 0], [PW, PH], [0, PH]], q) + except Exception: + continue + c = [map_h(hh, mg, mg), map_h(hh, l['W'] + mg, mg), + map_h(hh, l['W'] + mg, l['H'] + mg), map_h(hh, mg, l['H'] + mg)] + out.append({'quad': c, 'sz': sz, 'r0': True}) + return out + +def _pq_cr(o, a, b): + return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) + +def _pq_refine_edges(f, po, sc): + def gx(x, y): + if x < 0 or y < 0 or x > f.w - 1.001 or y > f.h - 1.001: return -1 + x0 = int(x); y0 = int(y) + tx = x - x0; ty = y - y0 + i = (y0 * f.w + x0) * 3 + j = i + f.w * 3 + def mn(k): return min(f.p[k], f.p[k + 1], f.p[k + 2]) + return max(0.0, (mn(i) * (1 - tx) + mn(i + 3) * tx) * (1 - ty) + + (mn(j) * (1 - tx) + mn(j + 3) * tx) * ty) ** .4545 + ln = [] + for i in range(4): + a = po[i]; b = po[(i + 1) % 4] + dx = b[0] - a[0]; dy = b[1] - a[1] + L = math.hypot(dx, dy) + nx = dy / L; ny = -dx / L + pts = [] + t = .15 + while t <= .851: + px = a[0] + t * dx; py = a[1] + t * dy + vi = 0.0; vo = 0.0; ci = 0; co = 0; bad = False + d = -3 * sc - 2 + while d <= -2 * sc: + v = gx(px + nx * d, py + ny * d) + if v < 0: bad = True; break + vi += v; ci += 1 + d += 1 + if not bad: + d = 2 * sc + while d <= 3 * sc + 2: + v = gx(px + nx * d, py + ny * d) + if v < 0: bad = True; break + vo += v; co += 1 + d += 1 + if not bad: + vi /= ci; vo /= co + if vi - vo >= .06: + mid = (vi + vo) / 2 + prev = gx(px - nx * 5 * sc, py - ny * 5 * sc) + pd = -5 * sc + hit = None + if prev >= 0: + d = -5 * sc + .5 + while d <= 5 * sc: + v = gx(px + nx * d, py + ny * d) + if v < 0: break + if prev >= mid and v < mid: + hit = pd + (prev - mid) / (prev - v) * (d - pd) + break + prev = v; pd = d + d += .5 + if hit is not None: + pts.append([px + nx * hit, py + ny * hit]) + t += .035 + if len(pts) < 6: + ln.append(None) + continue + fl = None + for it in range(3): + mx = sum(p[0] for p in pts) / len(pts) + my = sum(p[1] for p in pts) / len(pts) + sxx = sxy = syy = 0.0 + for p in pts: + u = p[0] - mx; v = p[1] - my + sxx += u * u; sxy += u * v; syy += v * v + tt = .5 * math.atan2(2 * sxy, sxx - syy) + cx = math.cos(tt); cy = math.sin(tt) + fl = [mx, my, cx, cy] + kept = [p for p in pts if abs((p[0] - mx) * cy - (p[1] - my) * cx) < 2] + if len(kept) < 6 or len(kept) == len(pts): break + pts = kept + ln.append(fl) + np_ = [] + for i in range(4): + l1 = ln[(i + 3) % 4]; l2 = ln[i] + if not l1 or not l2: + np_.append(po[i]); continue + det = l1[2] * l2[3] - l1[3] * l2[2] + if abs(det) < .1: + np_.append(po[i]); continue + t = ((l2[0] - l1[0]) * l2[3] - (l2[1] - l1[1]) * l2[2]) / det + x = l1[0] + t * l1[2]; y = l1[1] + t * l1[3] + np_.append([x, y] if math.hypot(x - po[i][0], y - po[i][1]) < 14 * sc else po[i]) + return np_ + +def _veil(f, h, l, white, mesh, C, B): + # PrismVeil: per-channel spatial scale+offset field fit, re-classify data cells + def vG(x): + return min(1.0, max(0.0, x)) ** .4545 + vP = [[vG(v) for v in PAL[si]] for si in range(8)] + def vB(x, y): + u = 2 * x / l['W'] - 1 + w = 2 * y / l['H'] - 1 + q = [] + for d in range(7): + for k in range(d + 1): + q.append(u ** (d - k) * w ** k) + return q + vN = 28 + vM = 2 * vN + vA = [] + for t in l['known']: + s_ = int(knownSymbol(t, 0)) + if not (0 <= s_ < 8): + continue + vA.append({'b': vB(t['x'], t['y']), + 'o': [vG(v) for v in sample(f, h, t, white, mesh)], 's': s_, 'w': 1}) + vX = [{'b': vB(t['x'], t['y']), + 'o': [vG(v) for v in sample(f, h, t, white, mesh)]} for t in l['data']] + if len(vA) < 40: + return + + def vS(Mx, y): + n2 = len(y) + for c in range(n2): + p = c + for k in range(c + 1, n2): + if abs(Mx[k][c]) > abs(Mx[p][c]): + p = k + Mx[c], Mx[p] = Mx[p], Mx[c] + y[c], y[p] = y[p], y[c] + dv = Mx[c][c] if Mx[c][c] else 1e-12 + for k in range(c + 1, n2): + f_ = Mx[k][c] / dv + if f_: + for j in range(c, n2): + Mx[k][j] -= f_ * Mx[c][j] + y[k] -= f_ * y[c] + z = [0.0] * n2 + for c in range(n2 - 1, -1, -1): + sm = y[c] + for j in range(c + 1, n2): + sm -= Mx[c][j] * z[j] + z[c] = sm / (Mx[c][c] if Mx[c][c] else 1e-12) + return z + + def vF(pts): + cf = [] + for c in range(3): + Mx = np.zeros((vM, vM)) + y = [0.0] * vM + for p in pts: + if not (p['w'] > 0): + continue + pc = vP[p['s']][c] + fv = [p['b'][k] * pc for k in range(vN)] + list(p['b']) + fa = np.array(fv) + Mx += p['w'] * np.outer(fa, fa) + for k in range(vM): + y[k] += p['w'] * fv[k] * p['o'][c] + for k in range(vM): + Mx[k][k] += 1e-6 + cf.append(vS([list(row) for row in Mx], y)) + return cf + + def vC(cf, p): + out = [] + for s_ in range(8): + d = 0.0 + for c in range(3): + av = 0.0 + bv = 0.0 + cc = cf[c] + bk = p['b'] + for k in range(vN): + av += cc[k] * bk[k] + bv += cc[vN + k] * bk[k] + df = vP[s_][c] * av + bv - p['o'][c] + d += df * df + out.append(math.sqrt(d)) + return out + + vCf = vF(vA) + vDs = None + vNn = len(vX) + vPr = [0] * vNn + vMg = [0.0] * vNn + + def vCl(): + nonlocal vDs + vDs = [vC(vCf, p) for p in vX] + for k in range(vNn): + d = vDs[k] + b0 = 0 + b1 = -1 + for s_ in range(1, 8): + if d[s_] < d[b0]: + b1 = b0 + b0 = s_ + elif b1 < 0 or d[s_] < d[b1]: + b1 = s_ + vPr[k] = b0 + vMg[k] = d[b1] - d[b0] + + vCl() + for it in range(3): + pts = list(vA) + for k in range(vNn): + pts.append({'b': vX[k]['b'], 'o': vX[k]['o'], 's': vPr[k], + 'w': min(1, vMg[k] / .078)}) + vCf = vF(pts) + vCl() + vBest = sorted(vDs[k][vPr[k]] for k in range(vNn)) + vSg = max(.015, 1.3 * vBest[len(vBest) >> 1] / 1.54) + vCm = CFG['llrClamp'] + for k in range(vNn): + d = vDs[k] + mn = min(d) + pp = [math.exp(-(z * z - mn * mn) / (2 * vSg * vSg)) for z in d] + for b_ in range(3): + n0 = 1e-9 + n1 = 1e-9 + for s_ in range(8): + if ((s_ ^ (s_ >> 1)) >> (2 - b_)) & 1: + n1 += pp[s_] + else: + n0 += pp[s_] + C[k * 3 + b_] = np.float32(max(-vCm, min(vCm, math.log(n0 / n1)))) + B[k]['confidence'] = min(abs(float(C[k * 3])), abs(float(C[k * 3 + 1])), + abs(float(C[k * 3 + 2]))) / 12 + + +def _dd(f, h, l, white, mesh, cal, C, B): + # PrismDD: per-symbol 3D Gaussian mixture over gamma'd raw colors; re-scores + # data cells whose LLR triple is all zero + def G(x): + return min(1.0, max(0.0, x)) ** .4545 + def I3(m): + p0, p1, p2, p3, p4, p5, p6, p7, p8 = m + A1 = p4 * p8 - p5 * p7 + B1 = -(p3 * p8 - p5 * p6) + C1 = p3 * p7 - p4 * p6 + dt = p0 * A1 + p1 * B1 + p2 * C1 + return {'dt': dt, 'v': [A1 / dt, -(p1 * p8 - p2 * p7) / dt, (p1 * p5 - p2 * p4) / dt, + B1 / dt, (p0 * p8 - p2 * p6) / dt, -(p0 * p5 - p2 * p3) / dt, + C1 / dt, -(p0 * p7 - p1 * p6) / dt, (p0 * p4 - p1 * p3) / dt]} + def est(P, W): + sw = 0.0 + m = [0.0, 0.0, 0.0] + for u, wj in zip(P, W): + sw += wj + for k in range(3): + m[k] += wj * u[k] + for k in range(3): + m[k] /= sw + cm = [0.0] * 9 + for u, wj in zip(P, W): + for x in range(3): + for y in range(3): + cm[x * 3 + y] += wj * (u[x] - m[x]) * (u[y] - m[y]) + for k in range(9): + cm[k] = cm[k] / sw + (3e-4 if k % 4 == 0 else 0) + r = I3(cm) + r['m'] = m + return r + K = [[] for _ in range(8)] + for q in cal['refs']: + s_ = int(knownSymbol(q['c'], 0)) + if not (0 <= s_ <= 7): + continue + K[s_].append([G(v) for v in q['o']]) + if not (all(len(z) >= 6 for z in K) and math.isfinite(K[0][0][0])): + return + M = [est(z, [1] * len(z)) for z in K] + DU = [] + DK = [] + ddf = 0 + for ddk, ddc in enumerate(l['data']): + if not (C[ddf] == 0 and C[ddf + 1] == 0 and C[ddf + 2] == 0): + DU.append([G(v) for v in sample(f, h, ddc, white, mesh)]) + DK.append(ddk) + ddf += 3 + + def PO(u): + ll = [] + for P in M: + d0 = u[0] - P['m'][0] + d1 = u[1] - P['m'][1] + d2 = u[2] - P['m'][2] + v = P['v'] + ll.append(-.5 * (d0 * (v[0] * d0 + v[1] * d1 + v[2] * d2) + + d1 * (v[3] * d0 + v[4] * d1 + v[5] * d2) + + d2 * (v[6] * d0 + v[7] * d1 + v[8] * d2)) + - .5 * math.log(max(1e-12, P['dt']))) + mx = max(ll) + pp = [math.exp(x - mx) for x in ll] + sm = sum(pp) + return [x / sm for x in pp] + + for it in range(3): + PS = [PO(u) for u in DU] + M = [est(DU + K[s_], [z[s_] + 1e-9 for z in PS] + [1] * len(K[s_])) + for s_ in range(8)] + for j, u in enumerate(DU): + pp = PO(u) + f2 = DK[j] * 3 + for b_ in range(3): + n0 = 1e-6 + n1 = 1e-6 + for s_ in range(8): + if ((s_ ^ (s_ >> 1)) >> (2 - b_)) & 1: + n1 += pp[s_] + else: + n0 += pp[s_] + C[f2 + b_] = np.float32(max(-CFG['llrClamp'], + min(CFG['llrClamp'], math.log(n0 / n1)))) + B[DK[j]]['confidence'] = min(abs(float(C[DK[j] * 3])), abs(float(C[DK[j] * 3 + 1])), + abs(float(C[DK[j] * 3 + 2]))) / 12 + + +# ===== palette-constrained cell mixing (PrismMixMode) ===== + +def _pal_ycc(): + out = [] + for hx in HEX: + r = int(hx[1:3], 16); g = int(hx[3:5], 16); b = int(hx[5:7], 16) + out.append([.299 * r + .587 * g + .114 * b, + 128 - .168736 * r - .331264 * g + .5 * b, + 128 + .5 * r - .418688 * g - .081312 * b]) + return out + +_PAL = _pal_ycc() +_PAL_LUM = [p[0] for p in _PAL] + + +def mixFit(A, H, l): + # 6-param homography refinement against palette luminance over ring/pilot cells. + d = A.image['data']; W = A.w; Ht = A.h + base = list(H) + known = [c for c in l['known'] if c['role'] in ('ring', 'pilot')] + + def candidate(p): + h = base[:] + h[2] += p[0]; h[5] += p[1]; h[0] *= 1 + p[2]; h[4] *= 1 + p[3]; h[1] += p[4]; h[3] += p[5] + return h + + def lum(x, y): + xx = math.floor(x); yy = math.floor(y); fx = x - xx; fy = y - yy + if xx < 0 or yy < 0 or xx >= W - 1 or yy >= Ht - 1: + return 255 + val = 0.0 + for dy in range(2): + for dx in range(2): + q = ((yy + dy) * W + xx + dx) * 4 + val += (.299 * d[q] + .587 * d[q + 1] + .114 * d[q + 2]) * (fx if dx else 1 - fx) * (fy if dy else 1 - fy) + return val + + def loss(p): + h = candidate(p); total = 0.0 + for c in known: + for off in OFF: + q = map_h(h, c['x'] + off[0], c['y'] + off[1]) + err = lum(q[0], q[1]) - _PAL_LUM[c['symbol']] + total += min(2500, err * err) + return total + + p = [0.0] * 6 + sc = [1, 1, 1 / l['W'], 1 / l['H'], 1 / l['H'], 1 / l['W']] + best = loss(p) + for step in (.8, .4, .2, .1, .05): + for _ in range(4): + changed = False + for k in range(6): + bk = p[k] + for sign in (-1, 1): + q = p[:]; q[k] += sign * step * sc[k] + ls = loss(q) + if ls < best: + best = ls; bk = q[k]; changed = True + p[k] = bk + if not changed: + break + return candidate(p) + + +def mixRecover(A, h, l): + # Palette-constrained JPEG cell mixing model. Returns only CRC-verified decodes. + global MIX_SYMBOLS + image = A.image + if image is None or (getattr(h, 'warp', None) and any(abs(v) > 0.001 for v in h.warp['p'])): + return None + pitch = math.hypot(h[0], h[3]) * math.sqrt(3) + if pitch < 1 or pitch > 4.5: + return None + W = image['width']; H = image['height'] + cells = l['cells']; N = len(cells); d = image['data'] + SQ3 = math.sqrt(3) + pts = [map_h(h, c['x'], c['y']) for c in cells] + x0 = max(0, math.floor(min(p[0] for p in pts) - 6)); y0 = max(0, math.floor(min(p[1] for p in pts) - 6)) + x1 = min(W, math.ceil(max(p[0] for p in pts) + 8)); y1 = min(H, math.ceil(max(p[1] for p in pts) + 8)) + x0 -= x0 % 2; y0 -= y0 % 2; x1 -= x1 % 2; y1 -= y1 % 2 + w = x1 - x0; ht = y1 - y0; M = w * ht + if M <= 0 or M > 50000: + return None + a, b, c_, dd, ee, f_, g, hh = h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] + inv = [ee - f_ * hh, c_ * hh - b, b * f_ - c_ * ee, + f_ * g - dd, a - c_ * g, c_ * dd - a * f_, + dd * hh - ee * g, b * dd - a * hh, a * ee - b * dd] + rows = [] + obs = [np.zeros(M), np.zeros(M), np.zeros(M)] + for y in range(ht): + for x in range(w): + ix = x + x0; iy = y + y0; k = y * w + x; q = (iy * W + ix) * 4 + r = d[q]; gg = d[q + 1]; bb = d[q + 2] + obs[0][k] = .299 * r + .587 * gg + .114 * bb + obs[1][k] = 128 - .168736 * r - .331264 * gg + .5 * bb + obs[2][k] = 128 + .5 * r - .418688 * gg - .081312 * bb + z = inv[6] * ix + inv[7] * iy + inv[8] + u = (inv[0] * ix + inv[1] * iy + inv[2]) / z + v = (inv[3] * ix + inv[4] * iy + inv[5]) / z + tx = (u + 3 * SQ3) * 10; ty = (v + 3 * SQ3) * 10 + ux = math.floor(tx); vy = math.floor(ty); fx = tx - ux; fy = ty - vy + row = {} + for dx, dy, wt in ((0, 0, (1 - fx) * (1 - fy)), (1, 0, fx * (1 - fy)), + (0, 1, (1 - fx) * fy), (1, 1, fx * fy)): + for sy in range(4): + for sx in range(4): + uu = (ux + dx + (sx + .5) / 4) / 10 - 3 * SQ3 + vv = (vy + dy + (sy + .5) / 4) / 10 - 3 * SQ3 + jr = _jsround((vv - 1) / 1.5) + n = N + for j in range(jr - 1, jr + 2): + ii = _jsround(uu / SQ3 - .5 - .5 * (j & 1)) + if ii < 0 or ii >= l['C'] or j < 0 or j >= l['R']: + continue + hx = abs(uu - SQ3 * (ii + .5 + .5 * (j & 1))) + hy = abs(vv - 1 - 1.5 * j) + if hx <= 1.03 * SQ3 / 2 and hy <= 1.03 - hx / SQ3: + n = max(-1 if n == N else n, j * l['C'] + ii) + row[n] = row.get(n, 0.0) + wt / 16 + rows.append(row) + chrom = [] + hw = w >> 1; ht2 = ht >> 1 + for y in range(ht): + for x in range(w): + row = {} + ky0 = y >> 1; ky1 = max(0, min(ht2 - 1, ky0 + (1 if y % 2 else -1))) + kx0 = x >> 1; kx1 = max(0, min(hw - 1, kx0 + (1 if x % 2 else -1))) + for ky, wy in ((ky0, .75), (ky1, .25)): + for kx, wx in ((kx0, .75), (kx1, .25)): + for oy in range(2): + for ox in range(2): + for n, wt in rows[(ky * 2 + oy) * w + kx * 2 + ox].items(): + row[n] = row.get(n, 0.0) + wt * wy * wx * .25 + chrom.append(row) + known = [c['role'] in ('ring', 'pilot', 'gap') for c in cells]; known.append(True) + symbols = [c['symbol'] if known[c['index']] else 0 for c in cells]; symbols.append(8) + unknown = [k for k in range(N) if not known[k]] + X = [_PAL[symbols[k]][:] for k in range(N + 1)] + mats = [rows, chrom, chrom] + res = []; links = [] + for ch in range(3): + mat = mats[ch] + col = [[] for _ in range(N + 1)] + rhs = obs[ch].copy() + for r in range(M): + for n, wt in mat[r].items(): + col[n].append((r, wt)) + if known[n]: + rhs[r] -= wt * X[n][ch] + + def mul(vec): + out = np.zeros(N + 1) + for r in range(M): + v = 0.0 + for n, wt in mat[r].items(): + if not known[n]: + v += wt * vec[n] + for n, wt in mat[r].items(): + if not known[n]: + out[n] += wt * v + for n in unknown: + out[n] += .0625 * vec[n] + return out + + rr = np.zeros(N + 1) + for n in unknown: + for r, wt in col[n]: + rr[n] += wt * rhs[r] + p = rr.copy(); sol = np.zeros(N + 1) + rs = 0.0 + for n in unknown: + rs += rr[n] ** 2 + it = 0 + while it < 150 and rs > 1e-8: + ap = mul(p) + den = 0.0 + for n in unknown: + den += p[n] * ap[n] + if den <= 0: + break + alpha = rs / den + for n in unknown: + sol[n] += alpha * p[n]; rr[n] -= alpha * ap[n] + ns = 0.0 + for n in unknown: + ns += rr[n] ** 2 + beta = ns / rs + for n in unknown: + p[n] = rr[n] + beta * p[n] + rs = ns; it += 1 + for n in unknown: + X[n][ch] = sol[n] + links.append(col) + for n in unknown: + bs = 0; bc = float('inf') + for sy_ in range(9): + if (cells[n]['role'] == 'data' and sy_ == 8) or (cells[n]['role'] == 'header' and 0 < sy_ < 8): + continue + cost = 0.0 + for ch in range(3): + cost += (8 if ch == 0 else 1) * (X[n][ch] - _PAL[sy_][ch]) ** 2 + if cost < bc: + bc = cost; bs = sy_ + symbols[n] = bs; X[n] = _PAL[bs][:] + for ch in range(3): + mat = mats[ch] + r_ = np.zeros(M) + for r in range(M): + acc = 0.0 + for n, wt in mat[r].items(): + acc += wt * X[n][ch] + r_[r] = obs[ch][r] - acc + res.append(r_) + + def costs(n): + out = [0.0] * 9 + for ch in range(3): + sq = 0.0; rv = 0.0 + for r, wt in links[ch][n]: + sq += wt * wt; rv += wt * res[ch][r] + for sy_ in range(9): + delta = _PAL[sy_][ch] - X[n][ch] + out[sy_] += (8 if ch == 0 else 1) * (sq * delta * delta - 2 * rv * delta) + if cells[n]['role'] == 'data': + out[8] = 1e20 + elif cells[n]['role'] == 'header': + for sy_ in range(1, 8): + out[sy_] = 1e20 + return out + + for _ in range(12): + changed = 0 + for n in unknown: + cs = costs(n) + bs = cs.index(min(cs)) + if bs == symbols[n]: + continue + changed += 1 + for ch in range(3): + delta = _PAL[bs][ch] - X[n][ch] + for r, wt in links[ch][n]: + res[ch][r] -= wt * delta + symbols[n] = bs; X[n] = _PAL[bs][:] + if not changed: + break + MIX_SYMBOLS = symbols + cs = [None if known[n] else costs(n) for n in range(N)] + hb = np.zeros(24, dtype=np.float32) + for c in l['headers']: + idx = c['header'] % 24 + hb[idx] = np.float32(float(hb[idx]) + (cs[c['index']][0] - cs[c['index']][8])) + try: + header = parseHeader(hb) + except Exception: + return None + if header['size'] != l['size'] or header['mode']: + return None + for temp in (80, 300, 1200): + stream = [] + for c in l['data']: + dd_ = cs[c['index']] + mn = min(dd_) + pp = [math.exp(-(x - mn) / temp) for x in dd_] + for b in range(3): + n0 = 1e-12; n1 = 1e-12 + for sy_ in range(8): + if ((sy_ ^ (sy_ >> 1)) >> (2 - b)) & 1: + n1 += pp[sy_] + else: + n0 += pp[sy_] + stream.append(max(-12, min(12, math.log(n0 / n1)))) + try: + dec = decodeStream(header, np.array(stream, dtype=np.float32)) + dec['variant'] = 'palette mixing' + return dec + except Exception: + pass + return None + + +def mixDirect(image): + # White-region hypothesis + palette-mixing recovery for small codes . + W = image['width']; H = image['height']; d = image['data'] + if W * H > 800000: + return None + seen = np.zeros(W * H, dtype=np.uint8) + best = [] + for k in range(W * H): + if seen[k] or min(int(d[k * 4]), int(d[k * 4 + 1]), int(d[k * 4 + 2])) < 232: + continue + q = [k]; seen[k] = 1 + x0 = W; y0 = H; x1 = 0; y1 = 0 + j = 0 + while j < len(q): + p = q[j]; j += 1 + x = p % W; y = p // W + if x < x0: x0 = x + if x > x1: x1 = x + if y < y0: y0 = y + if y > y1: y1 = y + for n in (p - 1, p + 1, p - W, p + W): + if n < 0 or n >= W * H or seen[n] or abs(n % W - x) > 1: + continue + seen[n] = 1 + if min(int(d[n * 4]), int(d[n * 4 + 1]), int(d[n * 4 + 2])) >= 232: + q.append(n) + w = x1 - x0 + 1; h = y1 - y0 + 1 + if 30 <= w < 200 and 30 <= h < 200 and .85 < w / h < 1.15 and len(q) > w * h * .12: + best.append({'x0': x0, 'y0': y0, 'w': w, 'h': h, 'n': len(q)}) + best.sort(key=lambda b: -b['n']) + A = frame(image) + candidates = [] + for b in best[:2]: + for size in range(4): + L = layout(size) + qq = 3 * math.sqrt(3) + sx = b['w'] / (L['W'] + 2 * qq); sy = b['h'] / (L['H'] + 2 * qq) + h = [sx, 0, b['x0'] + sx * qq, 0, sy, b['y0'] + sy * qq, 0, 0] + fit = mixFit(A, h, L) + score = 0.0; count = 0 + for c in L['known']: + if c['role'] not in ('ring', 'pilot'): + continue + v = sample(A, fit, c, [1, 1, 1], None, True) + gamma = [255 * (12.92 * q if q <= .0031308 else 1.055 * q ** (1 / 2.4) - .055) for q in v] + rgb = HEX[c['symbol']] + r = int(rgb[1:3], 16); g = int(rgb[3:5], 16); bb = int(rgb[5:7], 16) + yy = .299 * gamma[0] + .587 * gamma[1] + .114 * gamma[2] + ey = .299 * r + .587 * g + .114 * bb + score += min(2500, (yy - ey) ** 2); count += 1 + candidates.append({'fit': fit, 'L': L, 'score': score / count}) + candidates.sort(key=lambda c: c['score']) + for c in candidates[:3]: + if c['score'] > 700: + continue + r = mixRecover(A, c['fit'], c['L']) + hh = c['fit'] + it = 0 + while r is None and MIX_SYMBOLS and it < 3: + hh = mixAlternate(A, hh, c['L'], MIX_SYMBOLS) + r = mixRecover(A, hh, c['L']) + it += 1 + if r is not None: + r = dict(r) + r['quality'] = 1; r['h'] = c['fit'] + r['radius'] = math.hypot(c['fit'][0], c['fit'][3]); r['sigma'] = 6 + return r + return None + + +def mixAlternate(A, H, L, symbols): + # OffscreenCanvas hex re-render + refit. The canvas fill/downscale is a + # approximation: own supersampled rasterizer + box average. + Q = 3 * math.sqrt(3) + W = math.ceil((L['W'] + 2 * Q) * 10); Ht = math.ceil((L['H'] + 2 * Q) * 10) + scale = 4 + BW, BH = W * scale, Ht * scale + big = np.full(BW * BH, 255.0, dtype=np.float64) + for c in L['cells']: + sy_ = symbols[c['index']] + if sy_ == 8: + continue + cx = (c['x'] + Q) * 10 * scale; cy = (c['y'] + Q) * 10 * scale + R_ = 1.03 * 10 * scale + verts = [(cx + R_ * math.cos((30 + 60 * k) * math.pi / 180), + cy + R_ * math.sin((30 + 60 * k) * math.pi / 180)) for k in range(6)] + xs = [v[0] for v in verts]; ys = [v[1] for v in verts] + xa = max(0, int(math.floor(min(xs)))); xb = min(BW - 1, int(math.ceil(max(xs)))) + ya = max(0, int(math.floor(min(ys)))); yb = min(BH - 1, int(math.ceil(max(ys)))) + for py in range(ya, yb + 1): + for px in range(xa, xb + 1): + X_ = px + .5; Y_ = py + .5 + sgn = 0; inside = True + for k in range(6): + x1_, y1_ = verts[k]; x2_, y2_ = verts[(k + 1) % 6] + cr = (x2_ - x1_) * (Y_ - y1_) - (y2_ - y1_) * (X_ - x1_) + if cr != 0: + if sgn == 0: + sgn = 1 if cr > 0 else -1 + elif (cr > 0) != (sgn > 0): + inside = False; break + if inside: + big[py * BW + px] = _PAL_LUM[sy_] + yy = big.reshape(BH, BW).reshape(Ht, scale, W, scale).mean(axis=(1, 3)) + yy = yy.astype(np.float32) + d = A.image['data']; AW = A.w; AH = A.h + base = list(H) + points = [map_h(base, c['x'], c['y']) for c in L['cells']] + x0 = max(0, math.floor(min(p[0] for p in points))); x1 = min(AW - 1, math.ceil(max(p[0] for p in points))) + y0 = max(0, math.floor(min(p[1] for p in points))); y1 = min(AH - 1, math.ceil(max(p[1] for p in points))) + + def cand(p): + h = base[:] + h[2] += p[0]; h[5] += p[1]; h[0] *= 1 + p[2]; h[4] *= 1 + p[3] + return h + + def loss(p): + h = cand(p) + a, b, c_, d0, e, f_, g, hh = h + iv = [e - f_ * hh, c_ * hh - b, b * f_ - c_ * e, + f_ * g - d0, a - c_ * g, c_ * d0 - a * f_, + d0 * hh - e * g, b * d0 - a * hh, a * e - b * d0] + total = 0.0; n = 0 + for y in range(y0, y1 + 1): + for x in range(x0, x1 + 1): + z = iv[6] * x + iv[7] * y + iv[8] + u = ((iv[0] * x + iv[1] * y + iv[2]) / z + Q) * 10 + v = ((iv[3] * x + iv[4] * y + iv[5]) / z + Q) * 10 + ux = math.floor(u); vy = math.floor(v); fx = u - ux; fy = v - vy + if ux < 0 or vy < 0 or ux >= W - 1 or vy >= Ht - 1: + continue + j = vy * W + ux + pred = (yy[j] * (1 - fx) + yy[j + 1] * fx) * (1 - fy) + (yy[j + W] * (1 - fx) + yy[j + W + 1] * fx) * fy + k = (y * AW + x) * 4 + ob = .299 * d[k] + .587 * d[k + 1] + .114 * d[k + 2] + total += min(2000, (ob - pred) ** 2); n += 1 + return total / max(1, n) + + p = [0.0, 0.0, 0.0, 0.0] + sc = [1, 1, 1 / L['W'], 1 / L['H']] + best = loss(p) + for step in (.15, .075, .035, .015): + for _ in range(3): + for k in range(4): + bk = p[k] + for sign in (-1, 1): + q = p[:]; q[k] += sign * step * sc[k] + ls = loss(q) + if ls < best: + best = ls; bk = q[k] + p[k] = bk + return cand(p) diff --git a/ports/python/reader/read.py b/ports/python/reader/read.py new file mode 100644 index 0000000..ec1a198 --- /dev/null +++ b/ports/python/reader/read.py @@ -0,0 +1,64 @@ +# Comb Code photo reader entry point: page retry chain (prism_chain) driving the +# reader (prism_reader). Needs numpy and Pillow. +# Flags: calmed10 -> PRISM_CALMED, dd -> PRISM_DD, pq -> PRISM_PQ, veil -> PRISM_VEIL, +# mix -> PRISM_MIX. +import os +import sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import numpy as np +import prism_reader as pr +import prism_chain as pc + +def make_reader(): + def reader(img, flags): + pr.PRISM_CALMED = bool(flags.get('calmed10')) + pr.PRISM_DD = bool(flags.get('dd')) + pr.PRISM_PQ = bool(flags.get('pq')) + pr.PRISM_VEIL = bool(flags.get('veil')) + pr.PRISM_MIX = bool(flags.get('mix')) + try: + a = pc._arr(img) + h, w = a.shape[:2] + image = {'width': w, 'height': h, 'data': np.frombuffer(a.tobytes(), dtype=np.uint8)} + return pr.fastReaderRead(image) + finally: + pr.PRISM_CALMED = False + pr.PRISM_DD = False + pr.PRISM_PQ = False + pr.PRISM_VEIL = False + pr.PRISM_MIX = False + return reader + +def roi_read(img, reader): + # roiRead: bbox/crop/upNN then worker read; fall back to full frame + b = None + try: + b = pc.roi_bbox(img) + except Exception: + pass + if b: + try: + mix = bool(_current_flags[0] and _current_flags[0].get('mix')) + if mix: + sx, sy, w, h = b + dx = sx % 2; dy = sy % 2 + b = (sx - dx, sy - dy, w + dx, h + dy) + c = pc.crop(img, b) + m = max(c.width, c.height) + if m < 400 and not mix: + c = pc.upNN(c, min(6, 400 / m)) + return reader(c, _current_flags[0]) + except Exception as e: + if 'stopped' in str(e): + raise + return reader(img, _current_flags[0]) + +_current_flags = [None] + +def read(img): + """Read a Pillow RGBA image or numpy array; returns the result dict or raises.""" + base = make_reader() + def reader(im2, flags): + _current_flags[0] = flags + return roi_read(im2, base) + return pc.async_prism_read(img, reader)