Spaces:
Running

surfaceguard-ai / app.js
kramit1116's picture
In-browser SurfaceGuard AI demo (b5_iw_a, int8)
61dfa5e verified
Raw History Blame Contribute Delete
6.18 kB
// SurfaceGuard AI, page logic: loads config + ONNX model, reads an uploaded image, runs core.js, draws the result.
import * as core from './core.js';
const ORT_VERSION = '1.31.1';
const COLORS = [[255, 59, 48], [255, 204, 0], [52, 199, 89], [0, 122, 255]]; // defect_a red, b yellow, c green, d blue
const $ = (id) => document.getElementById(id);
let CFG = null, SESSION = null, BACKEND = '', CURRENT = null;
function status(msg, isError = false) {
const el = $('status');
el.textContent = msg;
el.className = isError ? 'status error' : 'status';
}
async function fetchWithProgress(url, onProgress) {
const res = await fetch(url);
if (!res.ok) throw new Error(`could not download ${url} (HTTP ${res.status})`);
const total = Number(res.headers.get('content-length')) || 0;
if (!res.body || !total) return new Uint8Array(await res.arrayBuffer());
const out = new Uint8Array(total);
const reader = res.body.getReader();
let got = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
out.set(value, got);
got += value.length;
onProgress(got, total);
}
return got === total ? out : out.subarray(0, got);
}
async function createSession(bytes) {
ort.env.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VERSION}/dist/`;
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;
if (navigator.gpu) {
try {
const s = await ort.InferenceSession.create(bytes, { executionProviders: ['webgpu', 'wasm'] });
return [s, 'WebGPU'];
} catch (e) {
console.warn('WebGPU session failed, using WebAssembly:', e);
}
}
return [await ort.InferenceSession.create(bytes, { executionProviders: ['wasm'] }), 'WebAssembly (CPU)'];
}
async function init() {
try {
CFG = await (await fetch('config.json')).json();
} catch (e) {
status('config.json could not be loaded: ' + e, true);
return;
}
$('model-info').textContent = `${CFG.model.description} · ${CFG.model.precision} · ${(CFG.model.bytes / 1e6).toFixed(0)} MB`;
$('lb').textContent = CFG.leaderboard.score;
const sel = $('preset');
for (const name of Object.keys(CFG.presets)) {
const o = document.createElement('option');
o.value = name;
o.textContent = name + (name === CFG.default_preset ? ' (leaderboard preset)' : '');
sel.appendChild(o);
}
sel.value = CFG.default_preset;
$('repo-link').href = CFG.full_model_url;
$('file').addEventListener('change', onFile);
$('run').addEventListener('click', run);
sel.addEventListener('change', () => CURRENT && CURRENT.result && render());
try {
status('Downloading the model (once; the browser caches it)...');
const bytes = await fetchWithProgress(CFG.model.file, (got, total) =>
status(`Downloading the model: ${(got / 1e6).toFixed(0)} / ${(total / 1e6).toFixed(0)} MB`));
status('Preparing the model...');
[SESSION, BACKEND] = await createSession(bytes);
$('tta').checked = BACKEND === 'WebGPU';
status(`Model ready (${BACKEND}). Choose an 800x128 steel-surface image.`);
$('file').disabled = false;
} catch (e) {
status('The model could not be loaded: ' + e.message, true);
}
}
async function onFile(ev) {
const file = ev.target.files[0];
if (!file) return;
const bmp = await createImageBitmap(file);
const cv = document.createElement('canvas');
cv.width = core.W;
cv.height = core.H;
const ctx = cv.getContext('2d');
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(bmp, 0, 0, core.W, core.H);
const rgba = ctx.getImageData(0, 0, core.W, core.H).data;
CURRENT = { name: file.name.replace(/\.[^.]+$/, ''), rgba, resized: bmp.width !== core.W || bmp.height !== core.H, result: null };
drawRGBA($('input-canvas'), rgba);
$('overlay-canvas').getContext('2d').clearRect(0, 0, core.W, core.H);
$('report').innerHTML = '';
$('rle').value = '';
$('run').disabled = false;
status(`Loaded ${file.name} (${bmp.width}x${bmp.height}${CURRENT.resized ? ', resized to 800x128' : ''}). Press "Find defects".`);
}
async function run() {
if (!SESSION || !CURRENT) return;
$('run').disabled = true;
const tta = $('tta').checked;
status(`Running${tta ? ' with 4-view test-time augmentation' : ''} on ${BACKEND}...`);
await new Promise((r) => setTimeout(r, 30));
try {
const t0 = performance.now();
CURRENT.result = await core.predict(ort, SESSION, core.rgbaToCHW(CURRENT.rgba), tta);
CURRENT.seconds = (performance.now() - t0) / 1000;
CURRENT.tta = tta;
render();
} catch (e) {
status('Inference failed: ' + e.message, true);
}
$('run').disabled = false;
}
function render() {
const preset = CFG.presets[$('preset').value];
const { probs, cls } = CURRENT.result;
const out = core.postprocess(probs, cls, preset, CFG.gate, CFG.classes);
const ov = new Uint8ClampedArray(CURRENT.rgba);
for (let c = 0; c < 4; c++) {
const m = out.masks[c];
for (let i = 0; i < core.HW; i++) {
if (!m[i]) continue;
for (let k = 0; k < 3; k++) ov[4 * i + k] = 0.55 * ov[4 * i + k] + 0.45 * COLORS[c][k];
}
}
drawRGBA($('overlay-canvas'), ov);
let rows = '<tr><th>Defect type</th><th>Detected</th><th>Pixels</th><th>Coverage</th><th>Gate score</th></tr>';
const lines = [];
CFG.classes.forEach((cl, c) => {
const a = out.areas[c];
rows += `<tr><td><span class="sw" style="background:rgb(${COLORS[c].join(',')})"></span>${cl}</td><td>${a > 0 ? 'yes' : 'no'}</td>` +
`<td>${a}</td><td>${(100 * a / core.HW).toFixed(2)}%</td><td>${out.gates[c].toFixed(3)}</td></tr>`;
lines.push(`${CURRENT.name}_${cl},${CURRENT.name},${cl},${core.rleEncode(out.masks[c]) || ' '}`);
});
$('report').innerHTML = rows;
$('rle').value = 'ID,image_id,defect_type,mask_rle\n' + lines.join('\n');
status(`Done in ${CURRENT.seconds.toFixed(1)} s on ${BACKEND}${CURRENT.tta ? ' (4-view TTA)' : ''}, preset ${$('preset').value}.`);
}
function drawRGBA(canvas, rgba) {
canvas.width = core.W;
canvas.height = core.H;
canvas.getContext('2d').putImageData(new ImageData(new Uint8ClampedArray(rgba), core.W, core.H), 0, 0);
}
init();