Spaces:
Running

File size: 9,495 Bytes
d193e00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55abd6b
 
 
d193e00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// DefectGen static page: loads assets/data.json, runs both detectors with ONNX Runtime Web.
import { letterboxTensor, maskAt, postprocess } from "./detect.js";

const ORT_DIST = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";
const MODELS = ["real_only", "genai"];
// Categorical slots 1-5 (validated palette); every mask also carries a text label.
const CLASS_COLORS = ["#257de0", "#f47230", "#00b894", "#f2a600", "#ee7fac"];
const $ = (id) => document.getElementById(id);

let data;
let sessions = null;
let busy = false;

function titles(d) {
  return {
    real_only: `Trained on ${d.k} real defects per type`,
    genai: `Same ${d.k} real defects + ${d.n_synthetic} GenAI defects per type`,
  };
}

function setupTabs() {
  const buttons = document.querySelectorAll(".tabs button");
  buttons.forEach((b) =>
    b.addEventListener("click", () => {
      buttons.forEach((x) => x.setAttribute("aria-selected", String(x === b)));
      document.querySelectorAll(".tab").forEach((t) => {
        t.hidden = t.id !== `tab-${b.dataset.tab}`;
      });
    }),
  );
}

function renderStatic(d) {
  const t = titles(d);
  $("headline").textContent = d.headline.split(/(?<=\.) (?=[A-Z])/)[0]; // first sentence
  $("headline-full").textContent = d.headline;
  $("link-github").href = d.links.github;
  $("link-lora").href = d.links.lora;
  for (const m of MODELS) $(`cap-${m}`).textContent = t[m];
  $("models-note").textContent =
    "Each model is the training seed with the best validation score; the test set never " +
    "picks anything. One model's test score varies a lot with so few test images, so the " +
    "Results tab reports means over 3 seeds.";
  const rows = MODELS.map((m) => {
    const r = d.models[m];
    return `<tr><td>${t[m]}</td><td>seed ${r.seed}</td><td>${(+r.val_mask_map50).toFixed(3)}</td><td>${(+r.test_mask_map50).toFixed(3)}</td></tr>`;
  }).join("");
  $("models-table").innerHTML =
    "<table><thead><tr><th>Model</th><th>Run</th><th>Val mask mAP50</th><th>Test mask mAP50</th></tr></thead>" +
    `<tbody>${rows}</tbody></table>`;
  for (const key of ["main", "per_class", "grid", "generation"]) $(`t-${key}`).innerHTML = d.tables[key];
  $("plots").innerHTML = d.plots
    .map((p) => `<img src="assets/${p}" alt="results plot" loading="lazy" />`)
    .join("");
  $("grids").innerHTML = d.grids
    .map((g) => {
      const name = g.split("/").pop().replace(".jpg", "").replace("_", " · ").replace("kall", "K all").replace(/^k(\d)/, "K $1");
      return `<a href="assets/${g}" target="_blank" rel="noopener"><img src="assets/${g}" alt="sample grid ${name}" loading="lazy" />${name}</a>`;
    })
    .join("");
  const byK = {};
  for (const e of d.gallery) (byK[e.k] ||= []).push(e);
  $("gallery").innerHTML = Object.entries(byK)
    .map(([k, items]) => {
      const head = k === "all" ? "LoRAs trained on all real defects (8–10 per type)" : `LoRAs trained on only ${k} real defects per type`;
      const figs = items
        .map((e) => `<figure><img src="assets/${e.file}" alt="${e.caption}" loading="lazy" /><figcaption>${e.defect}</figcaption></figure>`)
        .join("");
      return `<div class="gallery-k"><h3>${head}</h3><div class="gallery-grid">${figs}</div></div>`;
    })
    .join("");
  $("examples").innerHTML = d.examples
    .map((src) => {
      const label = src.split("/").pop().split("_")[0];
      return `<button type="button" aria-pressed="false" data-src="assets/${src}"><img src="assets/${src}" alt="test image: ${label}" />${label}</button>`;
    })
    .join("");
  $("examples").querySelectorAll("button").forEach((b) =>
    b.addEventListener("click", () => {
      $("examples").querySelectorAll("button").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
      loadAndDetect(b.dataset.src);
    }),
  );
}

async function loadSessions() {
  ort.env.wasm.wasmPaths = ORT_DIST;
  ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;
  const out = {};
  for (const m of MODELS) out[m] = await ort.InferenceSession.create(`assets/models/${m}.onnx`, { executionProviders: ["wasm"] });
  return out;
}

function loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    // Hub serves large files from a CDN on another origin (CORS: *); ask for them anonymously so
    // the canvas stays readable (otherwise getImageData fails on a "tainted" canvas).
    img.crossOrigin = "anonymous";
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error("could not read that image"));
    img.src = src;
  });
}

const MAX_SIDE = 2048; // very large uploads are scaled down first (memory), then letterboxed

function inputTensor(img, size) {
  const f = Math.min(1, MAX_SIDE / Math.max(img.naturalWidth, img.naturalHeight));
  const w = Math.round(img.naturalWidth * f);
  const h = Math.round(img.naturalHeight * f);
  const c = document.createElement("canvas");
  c.width = w;
  c.height = h;
  const ctx = c.getContext("2d");
  ctx.drawImage(img, 0, 0, w, h);
  const { tensor, lb } = letterboxTensor(ctx.getImageData(0, 0, w, h).data, w, h, size);
  return { tensor: new ort.Tensor("float32", tensor, [1, 3, size, size]), lb };
}

function hexToRgb(hex) {
  const v = parseInt(hex.slice(1), 16);
  return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
}

function draw(canvas, img, dets, lb, size, classes) {
  const scale = Math.min(1, 1024 / Math.max(img.naturalWidth, img.naturalHeight));
  canvas.width = Math.round(img.naturalWidth * scale);
  canvas.height = Math.round(img.naturalHeight * scale);
  const ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  const overlay = document.createElement("canvas");
  overlay.width = overlay.height = size;
  const octx = overlay.getContext("2d");
  const paint = octx.createImageData(size, size);
  for (const d of dets) {
    const [r, g, b] = hexToRgb(CLASS_COLORS[d.cls % CLASS_COLORS.length]);
    const m = maskAt(d, size);
    for (let p = 0; p < m.length; p++) {
      if (!m[p]) continue;
      paint.data.set([r, g, b, 120], 4 * p);
    }
  }
  octx.putImageData(paint, 0, 0);
  ctx.drawImage(overlay, lb.left, lb.top, lb.nw, lb.nh, 0, 0, canvas.width, canvas.height);
  const k = canvas.width / lb.nw;
  const px = Math.max(12, Math.round(canvas.width / 30)); // labels stay readable when scaled down
  ctx.lineWidth = Math.max(2, Math.round(px / 8));
  ctx.font = `600 ${px}px ui-sans-serif, system-ui, sans-serif`;
  for (const d of dets) {
    const color = CLASS_COLORS[d.cls % CLASS_COLORS.length];
    const x = (d.box[0] - lb.left) * k;
    const y = (d.box[1] - lb.top) * k;
    ctx.strokeStyle = color;
    ctx.strokeRect(x, y, (d.box[2] - d.box[0]) * k, (d.box[3] - d.box[1]) * k);
    const text = `${classes[d.cls]} ${d.score.toFixed(2)}`;
    const w = ctx.measureText(text).width + px * 0.6;
    const bh = Math.round(px * 1.45);
    const ty = Math.max(0, y - bh);
    ctx.fillStyle = "rgba(25,25,25,0.85)";
    ctx.fillRect(x, ty, w, bh);
    ctx.fillStyle = "#ffffff";
    ctx.fillText(text, x + px * 0.3, ty + px * 1.08);
  }
}

async function loadAndDetect(src) {
  if (busy) return;
  busy = true;
  try {
    $("status").textContent = sessions ? "Running both detectors…" : "Still loading the detectors…";
    const img = await loadImage(src);
    sessions = sessions || (await sessionsPromise);
    const size = data.detect.imgsz;
    const { tensor, lb } = inputTensor(img, size);
    const times = [];
    for (const m of MODELS) {
      const t0 = performance.now();
      const out = await sessions[m].run({ [sessions[m].inputNames[0]]: tensor });
      const [o0, o1] = sessions[m].outputNames.map((n) => out[n]);
      const [, ch, n] = o0.dims;
      const [, nm, mh, mw] = o1.dims;
      const dets = postprocess(o0.data, o1.data, {
        nc: ch - 4 - nm, nm, n, mh, mw, conf: data.detect.conf, iouThr: data.detect.iou,
      });
      times.push(performance.now() - t0);
      draw($(`out-${m}`), img, dets, lb, size, data.classes);
      $(`found-${m}`).textContent = dets.length
        ? dets.map((d) => `${data.classes[d.cls]} (${d.score.toFixed(2)})`).join(", ")
        : "No defect found.";
    }
    $("status").textContent = `Done in ${Math.round(times[0] + times[1])} ms on your device.`;
  } catch (err) {
    $("status").textContent = `Error: ${err.message}`;
  } finally {
    busy = false;
  }
}

function setupUpload() {
  const drop = $("drop");
  const use = (file) => file && loadAndDetect(URL.createObjectURL(file));
  $("file").addEventListener("change", (e) => use(e.target.files[0]));
  drop.addEventListener("dragover", (e) => {
    e.preventDefault();
    drop.classList.add("over");
  });
  drop.addEventListener("dragleave", () => drop.classList.remove("over"));
  drop.addEventListener("drop", (e) => {
    e.preventDefault();
    drop.classList.remove("over");
    use(e.dataTransfer.files[0]);
  });
}

let sessionsPromise;

async function start() {
  setupTabs();
  setupUpload();
  data = await (await fetch("assets/data.json")).json();
  renderStatic(data);
  sessionsPromise = loadSessions();
  try {
    sessions = await sessionsPromise;
    $("status").textContent = "Detectors ready. Click an example or drop an image.";
    const first = $("examples").querySelector("button");
    if (first) first.click();
  } catch (err) {
    $("status").textContent = `Could not load the detectors: ${err.message}`;
  }
}

start();