Spaces:
Running

File size: 9,026 Bytes
10709fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
(function () {
  "use strict";
  Demo.chrome({ repo: "https://github.com/rigel08/polyp-segmentation",
    footer: 'Training data: Jha et al., Kvasir-SEG (MMM 2020, research use). Example images: Wikimedia Commons, <a href="https://github.com/rigel08/portfolio-site/blob/main/demos/polyp/examples/ATTRIBUTION.md">credits</a>.',
    privacy: "Your image stays in your browser: the model runs on this device and nothing you choose or upload is sent anywhere. Even so, do not use images that could identify a patient." });

  var SIZE = 256, MEAN = [0.485, 0.456, 0.406], STD = [0.229, 0.224, 0.225], MAX_SIDE = 1024;
  var EXAMPLES = ["example_1.jpg", "example_2.jpg", "example_3.jpg"];
  var st = Demo.status(document.getElementById("load"));
  var thr = document.getElementById("thr"), tta = document.getElementById("tta");
  var sessP = null, current = null, busy = Promise.resolve();

  function session() {
    if (!sessP) sessP = Demo.loadSession("models/polyp_unet_fp16.onnx", function (f, got) {
      st.set("Downloading the model (49 MB, once)… " + Math.round(f * 100) + "%", f);
    });
    return sessP;
  }

  /* RGB uint8 (256*256*4 RGBA) -> NCHW float tensor data */
  function toTensor(rgba) {
    var n = SIZE * SIZE, x = new Float32Array(3 * n);
    for (var i = 0; i < n; i++) for (var c = 0; c < 3; c++) x[c * n + i] = (rgba[i * 4 + c] / 255 - MEAN[c]) / STD[c];
    return x;
  }
  function flip(x, h, v) { // flip each channel horizontally and/or vertically
    if (!h && !v) return x;
    var out = new Float32Array(x.length), n = SIZE * SIZE;
    for (var c = 0; c < x.length / n; c++)
      for (var r = 0; r < SIZE; r++) for (var q = 0; q < SIZE; q++)
        out[c * n + r * SIZE + q] = x[c * n + (v ? SIZE - 1 - r : r) * SIZE + (h ? SIZE - 1 - q : q)];
    return out;
  }

  async function probMap(rgba256, useTTA) {
    var sess = await session(), x = toTensor(rgba256), n = SIZE * SIZE, total = new Float32Array(n);
    var flips = useTTA ? [[0, 0], [1, 0], [0, 1], [1, 1]] : [[0, 0]];
    for (var f of flips) {
      var out = await sess.run({ image: new ort.Tensor("float32", flip(x, f[0], f[1]), [1, 3, SIZE, SIZE]) });
      var lg = flip(out.logits.data, f[0], f[1]);
      for (var i = 0; i < n; i++) total[i] += 1 / (1 + Math.exp(-lg[i]));
    }
    for (i = 0; i < n; i++) total[i] /= flips.length;
    return total;
  }

  function resized(img, w, h) {
    var c = document.createElement("canvas"); c.width = w; c.height = h;
    var ctx = c.getContext("2d", { willReadFrequently: true });
    ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high";
    ctx.drawImage(img, 0, 0, w, h);
    return { canvas: c, data: ctx.getImageData(0, 0, w, h).data };
  }

  function render() {
    if (!current) return;
    var t = +thr.value, img = current.img, prob = current.prob;
    document.getElementById("thr-val").textContent = t.toFixed(2);
    var s = Math.min(1, MAX_SIDE / Math.max(img.naturalWidth, img.naturalHeight));
    var W = Math.round(img.naturalWidth * s), H = Math.round(img.naturalHeight * s);
    var out = document.getElementById("out"); out.width = W; out.height = H;
    var ctx = out.getContext("2d"); ctx.drawImage(img, 0, 0, W, H);
    var im = ctx.getImageData(0, 0, W, H), d = im.data, mask = new Uint8Array(W * H), area = 0;
    for (var y = 0; y < H; y++) {  // bilinear upsampling of the 256x256 probability map
      var fy = Math.max(0, Math.min(SIZE - 1, (y + 0.5) * SIZE / H - 0.5)), y0 = Math.floor(fy), y1 = Math.min(y0 + 1, SIZE - 1), wy = fy - y0;
      for (var x = 0; x < W; x++) {
        var fx = Math.max(0, Math.min(SIZE - 1, (x + 0.5) * SIZE / W - 0.5)), x0 = Math.floor(fx), x1 = Math.min(x0 + 1, SIZE - 1), wx = fx - x0;
        var p = (prob[y0 * SIZE + x0] * (1 - wx) + prob[y0 * SIZE + x1] * wx) * (1 - wy) + (prob[y1 * SIZE + x0] * (1 - wx) + prob[y1 * SIZE + x1] * wx) * wy;
        if (p > t) { mask[y * W + x] = 1; area++; }
      }
    }
    var lw = Math.max(2, Math.round(Math.max(W, H) / 200));
    for (y = 0; y < H; y++) for (x = 0; x < W; x++) {
      var k = y * W + x; if (!mask[k]) continue;
      var edge = false;
      for (var dy = -lw; dy <= lw && !edge; dy += lw) for (var dx = -lw; dx <= lw; dx += lw) {
        var yy = y + dy, xx = x + dx;
        if (yy < 0 || xx < 0 || yy >= H || xx >= W || !mask[yy * W + xx]) { edge = true; break; }
      }
      var j = k * 4;
      if (edge) { d[j] = 40; d[j + 1] = 90; d[j + 2] = 255; }
      else { d[j] = 0.65 * d[j] + 0.35 * 40; d[j + 1] = 0.65 * d[j + 1] + 0.35 * 90; d[j + 2] = 0.65 * d[j + 2] + 0.35 * 255; }
    }
    ctx.putImageData(im, 0, 0);
    var heat = document.getElementById("heat").getContext("2d"), hm = heat.createImageData(SIZE, SIZE);
    for (var i = 0; i < SIZE * SIZE; i++) { var v = prob[i]; hm.data[i * 4] = 255 * v; hm.data[i * 4 + 1] = 120 * v; hm.data[i * 4 + 2] = 255 * (1 - v) * 0.35; hm.data[i * 4 + 3] = 255; }
    heat.putImageData(hm, 0, 0);
    var pct = 100 * area / (W * H), v = document.getElementById("verdict");
    v.className = "verdict" + (area ? " alert" : "");
    v.innerHTML = area ? "<b>Predicted polyp area: " + pct.toFixed(1) + "% of the image</b>" + current.label
                       : "<b>No polyp pixels above the threshold</b>This does not rule out a polyp." + current.label;
  }

  function analyse(src, label) {
    busy = busy.then(async function () {
      try {
        var img = await Demo.loadImage(src);
        var small = resized(img, SIZE, SIZE);
        st.set(sessP ? "Running the model…" : "Downloading the model…", null);
        await session(); st.set("Running the model…", null);
        var t0 = performance.now();
        var prob = await probMap(small.data, tta.checked);
        current = { img: img, prob: prob, label: "<br><span class='cap'>" + label + "</span>" };
        render();
        st.set("Segmented on this device in " + Math.round(performance.now() - t0) + " ms" + (tta.checked ? " (4 flipped passes)." : "."), null);
      } catch (e) { console.error(e); st.set(e.message, null, true); }
    });
    return busy;
  }

  var exBox = document.getElementById("examples"), lastSrc = null, lastLabel = "";
  EXAMPLES.forEach(function (name, i) {
    var b = document.createElement("button");
    b.className = "btn small"; b.type = "button"; b.textContent = "Example " + (i + 1);
    b.addEventListener("click", function () {
      exBox.querySelectorAll("button").forEach(function (o) { o.setAttribute("aria-pressed", o === b); });
      lastSrc = "examples/" + name; lastLabel = "Example " + (i + 1) + " (Wikimedia Commons)"; analyse(lastSrc, lastLabel);
    });
    exBox.append(b);
  });
  document.getElementById("file").addEventListener("change", function (e) {
    var f = e.target.files[0]; if (!f) return;
    if (f.size > 20 * 1048576) { st.set("That file is larger than 20 MB.", null, true); return; }
    exBox.querySelectorAll("button").forEach(function (o) { o.setAttribute("aria-pressed", false); });
    lastSrc = f; lastLabel = "Your image (stays on this device)"; analyse(f, lastLabel);
  });
  thr.addEventListener("input", render);
  tta.addEventListener("change", function () { if (lastSrc) analyse(lastSrc, lastLabel); });
  exBox.querySelector("button").click();

  // Parity hook (demos/VERIFY.md): feed the exact 256x256 pixels Python used, compare probability maps.
  window.__demo = {
    parity: async function () {
      await busy; var out = {};
      for (var k = 1; k <= 3; k++) {
        var img = await Demo.loadImage("https://rigel08.github.io/portfolio-site/demos/parity/polyp/example_" + k + "_256.png");
        var rgba = resized(img, SIZE, SIZE).data, p = await probMap(rgba, true);
        var res = { };
        for (var ref of ["fp32", "fp16"]) {
          var u = new Uint16Array(await (await fetch("https://rigel08.github.io/portfolio-site/demos/parity/polyp/example_" + k + "_prob_" + ref + ".u16")).arrayBuffer());
          var mx = 0, inter = 0, a = 0, b = 0;
          for (var i = 0; i < u.length; i++) {
            var q = u[i] / 65535; mx = Math.max(mx, Math.abs(q - p[i]));
            var m1 = p[i] > 0.4, m2 = q > 0.4; inter += m1 && m2; a += m1; b += m2;
          }
          res[ref] = { maxAbs: mx, dice: 2 * inter / Math.max(a + b, 1) };
        }
        // full browser pipeline: canvas resize of the original JPEG instead of OpenCV INTER_AREA
        var full = await probMap(resized(await Demo.loadImage("examples/example_" + k + ".jpg"), SIZE, SIZE).data, true);
        u = new Uint16Array(await (await fetch("https://rigel08.github.io/portfolio-site/demos/parity/polyp/example_" + k + "_prob_fp32.u16")).arrayBuffer());
        inter = a = b = 0; mx = 0;
        for (i = 0; i < u.length; i++) { q = u[i] / 65535; mx = Math.max(mx, Math.abs(q - full[i])); m1 = full[i] > 0.4; m2 = q > 0.4; inter += m1 && m2; a += m1; b += m2; }
        res.browserResize_vs_fp32 = { maxAbs: mx, dice: 2 * inter / Math.max(a + b, 1) };
        out["example_" + k] = res;
      }
      return out;
    },
  };
})();