Spaces:
Running

surfaceguard-ai / core.js
kramit1116's picture
In-browser SurfaceGuard AI demo (b5_iw_a, int8)
61dfa5e verified
Raw History Blame Contribute Delete
5.11 kB
// SurfaceGuard AI, browser inference core (pure functions, no DOM). Mirrors deploy/inference.py of the 0.75203 bundle:
// preprocessing and the 2x upsample / sigmoid / 2x2 pooling are inside the ONNX graph; this file does test-time flips,
// the presence gate, the per-class hysteresis rule, the 8-connected blob filter and run-length encoding.
export const H = 128;
export const W = 800;
export const HW = H * W;
export const VIEWS = [[false, false], [true, false], [false, true], [true, true]];
// RGBA bytes (from canvas getImageData, 800x128) -> Float32Array CHW with RGB values 0..255
export function rgbaToCHW(rgba) {
const out = new Float32Array(3 * HW);
for (let i = 0; i < HW; i++) {
out[i] = rgba[4 * i];
out[HW + i] = rgba[4 * i + 1];
out[2 * HW + i] = rgba[4 * i + 2];
}
return out;
}
// flip a (C, H, W) array horizontally and/or vertically (its own inverse)
export function flipCHW(src, C, h, v) {
if (!h && !v) return src;
const out = new Float32Array(src.length);
for (let c = 0; c < C; c++) {
const base = c * HW;
for (let y = 0; y < H; y++) {
const sy = v ? H - 1 - y : y;
for (let x = 0; x < W; x++) {
out[base + y * W + x] = src[base + sy * W + (h ? W - 1 - x : x)];
}
}
}
return out;
}
// one forward pass per view; probabilities are un-flipped and averaged, presence probabilities averaged
export async function predict(ort, session, chw, tta) {
const views = tta ? VIEWS : VIEWS.slice(0, 1);
const probs = new Float32Array(4 * HW);
const cls = new Float32Array(4);
for (const [h, v] of views) {
const input = new ort.Tensor('float32', flipCHW(chw, 3, h, v), [1, 3, H, W]);
const out = await session.run({ image: input });
const p = flipCHW(out.probs.data, 4, h, v);
for (let i = 0; i < p.length; i++) probs[i] = probs[i] + p[i];
for (let c = 0; c < 4; c++) cls[c] = cls[c] + out.cls.data[c];
}
for (let i = 0; i < probs.length; i++) probs[i] = probs[i] / views.length;
for (let c = 0; c < 4; c++) cls[c] = cls[c] / views.length;
return { probs, cls };
}
// gate = w_cls * class prob + w_top * mean(top-k pixel probs) + w_max * max pixel prob, per class
export function gateScores(probs, cls, g) {
const out = new Array(4);
for (let c = 0; c < 4; c++) {
const ch = Float32Array.from(probs.subarray(c * HW, (c + 1) * HW)).sort();
let s = 0;
for (let i = HW - g.top_k; i < HW; i++) s += ch[i];
out[c] = g.cls_weight * cls[c] + g.topk_weight * (s / g.top_k) + g.max_weight * ch[HW - 1];
}
return out;
}
// keep 8-connected components with at least minArea pixels (same as cv2.connectedComponentsWithStats + area filter)
export function removeSmallBlobs(mask, minArea) {
if (minArea <= 0) return mask;
let any = false;
for (let i = 0; i < HW; i++) if (mask[i]) { any = true; break; }
if (!any) return mask;
const seen = new Uint8Array(HW);
const stack = new Int32Array(HW);
const comp = new Int32Array(HW);
const out = new Uint8Array(HW);
for (let s = 0; s < HW; s++) {
if (!mask[s] || seen[s]) continue;
let top = 0, n = 0;
stack[top++] = s;
seen[s] = 1;
while (top > 0) {
const i = stack[--top];
comp[n++] = i;
const y = (i / W) | 0, x = i - y * W;
for (let dy = -1; dy <= 1; dy++) {
const yy = y + dy;
if (yy < 0 || yy >= H) continue;
for (let dx = -1; dx <= 1; dx++) {
const xx = x + dx;
if (xx < 0 || xx >= W || (dx === 0 && dy === 0)) continue;
const j = yy * W + xx;
if (mask[j] && !seen[j]) { seen[j] = 1; stack[top++] = j; }
}
}
}
if (n >= minArea) for (let k = 0; k < n; k++) out[comp[k]] = 1;
}
return out;
}
// per-class rule of the bundle: gate, support area above high_thr, hysteresis mask above low_thr, blob filter
export function applyRule(p, gate, prm) {
const empty = new Uint8Array(HW);
if (gate < prm.cls_thr) return empty;
let n = 0;
for (let i = 0; i < HW; i++) if (p[i] > prm.high_thr) n++;
if (n < prm.min_area) return empty;
const m = new Uint8Array(HW);
for (let i = 0; i < HW; i++) m[i] = p[i] > prm.low_thr ? 1 : 0;
return removeSmallBlobs(m, prm.min_cc_area);
}
// competition format: column-major, 1-indexed "start length" pairs; '' for an empty mask
export function rleEncode(mask) {
const runs = [];
let start = -1, k = 0;
for (let x = 0; x < W; x++) {
for (let y = 0; y < H; y++, k++) {
const on = mask[y * W + x] === 1;
if (on && start < 0) start = k;
if (!on && start >= 0) { runs.push(start + 1, k - start); start = -1; }
}
}
if (start >= 0) runs.push(start + 1, HW - start);
return runs.join(' ');
}
export function postprocess(probs, cls, preset, gateCfg, classes) {
const gates = gateScores(probs, cls, gateCfg);
const masks = [], areas = [];
for (let c = 0; c < 4; c++) {
const m = applyRule(probs.subarray(c * HW, (c + 1) * HW), gates[c], preset[classes[c]]);
let a = 0;
for (let i = 0; i < HW; i++) a += m[i];
masks.push(m);
areas.push(a);
}
return { masks, areas, gates };
}