File size: 25,089 Bytes
4221512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658106a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4221512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658106a
 
 
4221512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658106a
4221512
 
 
 
658106a
4221512
 
 
 
 
658106a
 
4221512
 
 
 
658106a
4221512
 
 
658106a
4221512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658106a
4221512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658106a
4221512
658106a
 
4221512
 
658106a
 
 
4221512
 
658106a
4221512
 
 
 
 
 
 
 
 
 
 
658106a
 
 
 
 
 
 
 
4221512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
// AI Image Check, single-file build of pilresize.js + views.js + main.js (see build.py).
// Port of Pillow's 8-bit resampling (libImaging/Resample.c) for RGB images, so the
// detectors see the same pixels in the browser as in Python: Image.resize(size,
// BICUBIC | LANCZOS) with no box and reducing_gap=None. Separable, horizontal pass first,
// coefficients normalised in double and rounded to 22-bit fixed point, as in C.
const PRECISION_BITS = 22;
const ONE = 1 << PRECISION_BITS;

const FILTERS = {
  bicubic: { support: 2.0, f: (x) => {
    const a = -0.5;
    if (x < 0) x = -x;
    if (x < 1) return ((a + 2) * x - (a + 3)) * x * x + 1;
    if (x < 2) return (((x - 5) * x + 8) * x - 4) * a;
    return 0;
  } },
  lanczos: { support: 3.0, f: (x) => {
    const sinc = (v) => { if (v === 0) return 1; v *= Math.PI; return Math.sin(v) / v; };
    return (x >= -3 && x < 3) ? sinc(x) * sinc(x / 3) : 0;
  } },
};

function coeffs(inSize, outSize, filter) {
  const scale = inSize / outSize;
  const filterscale = scale < 1 ? 1 : scale;
  const support = filter.support * filterscale;
  const ksize = Math.ceil(support) * 2 + 1;
  const kk = new Int32Array(outSize * ksize), bounds = new Int32Array(outSize * 2);
  const pre = new Float64Array(ksize);
  for (let xx = 0; xx < outSize; xx++) {
    const center = (xx + 0.5) * scale, ss = 1 / filterscale;
    let xmin = Math.trunc(center - support + 0.5); if (xmin < 0) xmin = 0;
    let xmax = Math.trunc(center + support + 0.5); if (xmax > inSize) xmax = inSize;
    xmax -= xmin;
    let ww = 0;
    for (let x = 0; x < xmax; x++) { const w = filter.f((x + xmin - center + 0.5) * ss); pre[x] = w; ww += w; }
    for (let x = 0; x < xmax; x++) {
      const v = ww !== 0 ? pre[x] / ww : pre[x];
      kk[xx * ksize + x] = v < 0 ? Math.trunc(-0.5 + v * ONE) : Math.trunc(0.5 + v * ONE);
    }
    bounds[xx * 2] = xmin; bounds[xx * 2 + 1] = xmax;
  }
  return { kk, bounds, ksize };
}

const clip8 = (v) => (v >= (ONE * 256) ? 255 : v <= 0 ? 0 : Math.floor(v / ONE));

// img: { w, h, data: Uint8Array RGB } -> { w, h, data }
function resize(img, outW, outH, kind) {
  if (outW === img.w && outH === img.h) return { w: img.w, h: img.h, data: img.data.slice() };
  const filter = FILTERS[kind];
  const H = coeffs(img.w, outW, filter), V = coeffs(img.h, outH, filter);
  const needH = outW !== img.w, needV = outH !== img.h;
  const yFirst = V.bounds[0], yLast = V.bounds[(outH - 1) * 2] + V.bounds[(outH - 1) * 2 + 1];
  let src = img;
  if (needH) {
    const rows = yLast - yFirst, out = new Uint8Array(outW * rows * 3), d = img.data, W = img.w;
    for (let yy = 0; yy < rows; yy++) {
      const rowOff = (yy + yFirst) * W * 3;
      for (let xx = 0; xx < outW; xx++) {
        const xmin = H.bounds[xx * 2], xmax = H.bounds[xx * 2 + 1], k = xx * H.ksize;
        let s0 = ONE / 2, s1 = ONE / 2, s2 = ONE / 2;
        for (let x = 0; x < xmax; x++) {
          const c = H.kk[k + x], p = rowOff + (x + xmin) * 3;
          s0 += d[p] * c; s1 += d[p + 1] * c; s2 += d[p + 2] * c;
        }
        const o = (yy * outW + xx) * 3;
        out[o] = clip8(s0); out[o + 1] = clip8(s1); out[o + 2] = clip8(s2);
      }
    }
    src = { w: outW, h: rows, data: out };
  }
  if (!needV) return src;
  const shift = needH ? yFirst : 0, W = src.w, d = src.data, out = new Uint8Array(W * outH * 3);
  for (let yy = 0; yy < outH; yy++) {
    const ymin = V.bounds[yy * 2] - shift, ymax = V.bounds[yy * 2 + 1], k = yy * V.ksize;
    for (let xx = 0; xx < W; xx++) {
      let s0 = ONE / 2, s1 = ONE / 2, s2 = ONE / 2;
      for (let y = 0; y < ymax; y++) {
        const c = V.kk[k + y], p = ((y + ymin) * W + xx) * 3;
        s0 += d[p] * c; s1 += d[p + 1] * c; s2 += d[p + 2] * c;
      }
      const o = (yy * W + xx) * 3;
      out[o] = clip8(s0); out[o + 1] = clip8(s1); out[o + 2] = clip8(s2);
    }
  }
  return { w: W, h: outH, data: out };
}

function crop(img, x, y, w, h) {
  const out = new Uint8Array(w * h * 3);
  for (let r = 0; r < h; r++) out.set(img.data.subarray(((y + r) * img.w + x) * 3, ((y + r) * img.w + x + w) * 3), r * w * 3);
  return { w, h, data: out };
}

// Python's round(): halves to even.
function pyRound(v) {
  const f = Math.floor(v), d = v - f;
  if (d > 0.5) return f + 1;
  if (d < 0.5) return f;
  return f % 2 === 0 ? f : f + 1;
}

// Detector inputs, ported line by line from the Python originals so the browser feeds the
// models the same pixels: mesmer inference.py (views, rank_normalise, display_p) and
// Smaug smaug_image_detect.py (views). Images are { w, h, data: Uint8Array RGB }.

// ---------------------------------------------------------------- mesmer
const S_PEL = 336, S_PEG = 448, CAP_PEL = 1024;

function capLongSide(px, maxSide) {
  const { w, h } = px;
  if (maxSide <= 0 || Math.max(h, w) <= maxSide) return px;
  const k = maxSide / Math.max(h, w);
  const [nw, nh] = w >= h ? [maxSide, Math.max(1, pyRound(h * k))] : [Math.max(1, pyRound(w * k)), maxSide];
  return resize(px, nw, nh, 'lanczos');
}

function viewResizeCrop(im, S) {
  const s = S / Math.min(im.w, im.h);
  const r = resize(im, Math.max(S, pyRound(im.w * s)), Math.max(S, pyRound(im.h * s)), 'bicubic');
  return crop(r, (r.w - S) >> 1, (r.h - S) >> 1, S, S);
}

function upscaleShort(im, S) {
  if (Math.min(im.w, im.h) >= S) return im;
  const s = S / Math.min(im.w, im.h);
  return resize(im, Math.max(S, pyRound(im.w * s)), Math.max(S, pyRound(im.h * s)), 'bicubic');
}

function nativeCentre(im, S) {
  im = upscaleShort(im, S);
  return crop(im, (im.w - S) >> 1, (im.h - S) >> 1, S, S);
}

function spreadCrops(im, S, ts = [0, 0.25, 1]) {
  im = upscaleShort(im, S);
  return ts.map((t) => (im.w >= im.h
    ? crop(im, pyRound(t * (im.w - S)), (im.h - S) >> 1, S, S)
    : crop(im, (im.w - S) >> 1, pyRound(t * (im.h - S)), S, S)));
}

// uint8 HWC views -> float32 NCHW, (x / 255 - mean) / std
function toTensor(views, S, mean = 0.5, std = 0.5) {
  const plane = S * S, out = new Float32Array(views.length * 3 * plane);
  views.forEach((v, i) => {
    const d = v.data, o = i * 3 * plane;
    for (let p = 0; p < plane; p++)
      for (let c = 0; c < 3; c++) out[o + c * plane + p] = (Math.fround(d[p * 3 + c] / 255) - mean) / std;
  });
  return out;
}

function mesmerViews(px) {
  const capped = capLongSide(px, CAP_PEL);
  const peg = viewResizeCrop(px, S_PEG);   // PE-G: from the image as is (capping only applies to PE-L)
  const pel = [viewResizeCrop(capped, S_PEL), nativeCentre(capped, S_PEL), ...spreadCrops(capped, S_PEL)];
  return { peg: toTensor([peg], S_PEG), pel: toTensor(pel, S_PEL), pegView: peg, pelViews: pel };
}

// rank_normalise: logit of the mid-rank ECDF of the sorted real reference scores + 1e-3 x robust z
function makeRanker(ref) {
  const r = Float64Array.from(ref).sort(), n = r.length;
  const pct = (q) => { const i = q / 100 * (n - 1), lo = Math.floor(i), hi = Math.ceil(i); return r[lo] + (r[hi] - r[lo]) * (i - lo); };
  const med = n % 2 ? r[(n - 1) / 2] : (r[n / 2 - 1] + r[n / 2]) / 2;
  const iqr = Math.max(pct(75) - pct(25), 1e-12);
  const left = (x) => { let a = 0, b = n; while (a < b) { const m = (a + b) >> 1; if (r[m] < x) a = m + 1; else b = m; } return a; };
  const right = (x) => { let a = 0, b = n; while (a < b) { const m = (a + b) >> 1; if (r[m] <= x) a = m + 1; else b = m; } return a; };
  return (x) => {
    let u = (left(x) + right(x)) / 2;
    u = Math.min(Math.max((u + 0.5) / (n + 1), 0.5 / (n + 1)), 1 - 0.5 / (n + 1));
    return Math.log(u / (1 - u)) + 1e-3 * (x - med) / iqr;
  };
}

// Round a float32 value to the nearest binary16 value (ties to even), as torch's .half() does.
function f16round(x) {
  if (!Number.isFinite(x) || x === 0) return x;
  const a = Math.abs(x);
  if (a >= 65520) return Math.sign(x) * Infinity;
  let e = Math.floor(Math.log2(a));
  if (2 ** e > a) e--; else if (2 ** (e + 1) <= a) e++;
  const q = 2 ** (Math.max(e, -14) - 10);          // spacing of binary16 values near a (subnormals below 2^-14)
  const v = a / q, f = Math.floor(v), d = v - f;
  const r = (d > 0.5 || (d === 0.5 && f % 2 === 1) ? f + 1 : f) * q;
  return x < 0 ? -r : r;
}

// Detector.score_peg's head: [mean, std] of blocks 25 / 38 / 50 + the pooled output, each clamped to
// +-65000 and rounded to fp16, NaN -> 0, L2-normalised per block, standardised, then a dot product.
// head: Float32Array mu | sd | w (n each) | b, dims: block widths summing to n.
function pegLogit(s25, s38, s50, pooled, head, dims) {
  const h = (s) => [s.subarray(0, s.length / 2), s.subarray(s.length / 2)];
  const blocks = [...h(s25), ...h(s38), ...h(s50), pooled];
  const n = dims.reduce((a, b) => a + b, 0), mu = head.subarray(0, n), sd = head.subarray(n, 2 * n), w = head.subarray(2 * n, 3 * n);
  let logit = head[3 * n], o = 0;
  blocks.forEach((blk, i) => {
    if (blk.length !== dims[i]) throw new Error(`PE-G block ${i}: ${blk.length} values, expected ${dims[i]}`);
    const x = Array.from(blk, (v) => { const r = f16round(Math.min(65000, Math.max(-65000, v))); return Number.isNaN(r) ? 0 : r; });
    const norm = Math.max(Math.fround(Math.sqrt(x.reduce((a, v) => a + v * v, 0))), 1e-12);
    for (let k = 0; k < x.length; k++, o++) {
      const z = Math.fround(Math.fround(Math.fround(x[k] / norm) - mu[o]) / sd[o]);
      logit += z * w[o];
    }
  });
  return logit;
}

function mesmerVerdict(pelLogit, pegLogit, fusion) {
  const zp = fusion.rank.pel(pelLogit), zg = fusion.rank.peg(pegLogit), w = fusion.weights;
  const z = (w.pel * zp + w.peg * zg) / (w.pel + w.peg);
  const { ai, unc } = fusion.thresholds;
  const verdict = z >= ai ? 'likely_ai' : z >= unc ? 'uncertain' : 'likely_real';
  const p = 1 / (1 + Math.exp(-Math.max(-60, Math.min(60, Math.log(9) * (z - unc) / (ai - unc)))));
  return { verdict, score: z, p_ai: p, zp, zg };
}

// ---------------------------------------------------------------- smaug
const CROP = 528, SIDE = 576;

function smaugCrops(px) {
  let im = px;
  const m = Math.min(im.w, im.h);
  if (m > SIDE) {
    const s = SIDE / m;
    im = resize(im, pyRound(im.w * s), pyRound(im.h * s), 'lanczos');
  } else if (m < CROP) {
    const s = CROP / m;
    im = resize(im, Math.ceil(im.w * s), Math.ceil(im.h * s), 'bicubic');
  }
  const cx = (im.w - CROP) >> 1, cy = (im.h - CROP) >> 1;
  const spots = im.w >= im.h ? [[0, cy], [cx, cy], [im.w - CROP, cy]] : [[cx, 0], [cx, cy], [cx, im.h - CROP]];
  const views = spots.map(([x, y]) => crop(im, x, y, CROP, CROP));
  return { tensor: toTensor(views, CROP, 0, 1), views };
}

const sigmoid = (v) => 1 / (1 + Math.exp(-v));


const q = new URLSearchParams(location.search);
// Test hooks: same-origin paths only, so a crafted link cannot load someone else's code or weights.
const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null);
const MESMER_REPO = 'WeReCooking/Mesmer-AI-Image-Detector-ONNX-WebGPU';
const MESMER = local(q.get('mesmer')) || `https://huggingface.co/${MESMER_REPO}/resolve/main`;
const SMAUG = local(q.get('smaug')) || 'https://huggingface.co/21amd21/smaug-ai-image-detector-web/resolve/1f7d2da952f86543c6c878450ee8fc82750bd14d/model.onnx';
const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs';
const CACHE = 'ai-image-check-v1';
const EXAMPLES = [
  ['photo-real-1.jpg', 'Real photo: a puppy, by Andrew Sterling on Unsplash', 'https://unsplash.com/photos/xelC-x_Uvh0'],
  ['photo-real-2.jpg', 'Real photo: a couple at sunrise, by Andrey Câmara on Unsplash', 'https://unsplash.com/photos/80_6jJ97c-U'],
  ['photo-real-3.jpg', 'Real photo: a vintage car, by Ross Sneddon on Unsplash', 'https://unsplash.com/photos/65SjWi7gTao'],
  ['ai-midjourney-7.png', 'AI image: Midjourney 7, from the OpenFake dataset', 'https://huggingface.co/datasets/ComplexDataLab/OpenFake'],
  ['ai-gpt-image-2.png', 'AI image: GPT-Image-2, from the OpenFake dataset', 'https://huggingface.co/datasets/ComplexDataLab/OpenFake'],
  ['ai-dflow2.png', 'AI image: DFlow2 2B with the 4-step LoRA, made in our DFlow2 WebGPU Space', 'https://huggingface.co/spaces/WeReCooking/DFlow2-WebGPU'],
];

const $ = (id) => document.getElementById(id);
const ui = { drop: $('drop'), photo: $('photo'), file: $('file'), thumbs: $('thumbs'), store: $('store'), wipe: $('wipe') };
const rows = { smaug: $('smaug'), mesmer: $('mesmer') };
const mb = (b) => `${Math.round(b / 1e6)} MB`;
const tick = () => new Promise((r) => setTimeout(r, 0));

function show(name, cls, frac, html) {
  const r = rows[name];
  r.className = `res ${cls}`;
  r.querySelector('.meter i').style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;
  r.querySelector('.val').innerHTML = html;
}

// ---------------------------------------------------------------- downloads (Cache API, once)
async function openCache() { try { return await caches.open(CACHE); } catch { return null; } }

async function fetchBytes(url, onBytes) {
  const cache = await openCache();
  const hit = cache && await cache.match(url);
  if (hit) return new Uint8Array(await hit.arrayBuffer());
  const resp = await fetch(url);
  if (!resp.ok) throw new Error(`HTTP ${resp.status} for ${url.split('/').pop()}`);
  const total = Number(resp.headers.get('content-length')) || 0, reader = resp.body.getReader();
  let bytes = new Uint8Array(total || 1 << 20), got = 0;
  for (;;) {     // one preallocated buffer: no Blob, no second copy
    const { done, value } = await reader.read();
    if (done) break;
    if (got + value.length > bytes.length) { const g = new Uint8Array(Math.max(bytes.length * 2, got + value.length)); g.set(bytes.subarray(0, got)); bytes = g; }
    bytes.set(value, got); got += value.length;
    onBytes?.(got);
  }
  if (got !== bytes.length) bytes = bytes.slice(0, got);
  if (cache) { try { await cache.put(url, new Response(bytes)); } catch (e) { console.warn(`not stored (${e.name}): ${url}`); } }
  return bytes;
}

async function cachedAll(urls) {
  const cache = await openCache();
  if (!cache) return false;
  for (const u of urls) if (!(await cache.match(u))) return false;
  return true;
}

// ---------------------------------------------------------------- models
let ortP = null;
const getOrt = () => (ortP ||= (async () => {
  if (!navigator.gpu || !(await navigator.gpu.requestAdapter())) throw new Error('needs WebGPU: Chrome or Edge 121+, Android 12+ or Safari 26');
  const ort = await import(ORT_URL);
  ort.env.logLevel = 'error';
  return ort;
})());
// One ONNX Runtime call at a time: creating one session while another runs corrupts its memory.
let gpuQ = Promise.resolve();
const gpu = (fn) => { const p = gpuQ.then(fn); gpuQ = p.catch(() => {}); return p; };

async function download(name, files, total) {   // files: [[url, bytes]], sequential, progress in the row
  let done = 0;
  const out = [];
  const fresh = !(await cachedAll(files.map(([u]) => u)));
  for (const [url, size] of files) {
    out.push(await fetchBytes(url, (got) => {
      show(name, 'busy', (done + got) / total, `downloading ${mb(done + got)} of ${mb(total)}, first time only`);
    }));
    done += size;
  }
  if (fresh) show(name, 'busy', 1, 'starting on your GPU…');
  return out;
}

let smaugP = null, mesmerP = null, manifestP = null;
const getManifest = () => (manifestP ||= fetch(`${MESMER}/manifest.json`).then((r) => {
  if (!r.ok) throw new Error(`model list: HTTP ${r.status}`);
  return r.json();
}));

const getSmaug = () => (smaugP ||= (async () => {
  const ort = await getOrt();
  const [bytes] = await download('smaug', [[SMAUG, 181210404]], 181210404);
  show('smaug', 'busy', 1, 'starting on your GPU…');
  return gpu(() => ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], graphOptimizationLevel: 'disabled', logSeverityLevel: 3 }));
})());

const getMesmer = () => (mesmerP ||= (async () => {
  const ort = await getOrt();
  await getSmaug().catch(() => {});    // Smaug's download first, so its answer comes quickly
  const man = await getManifest();
  const parts = ['pel', ...man.peg];
  const files = parts.map((p) => [`${MESMER}/${man.files[p].path}`, man.files[p].bytes]);
  const total = files.reduce((a, [, b]) => a + b, 0);
  const [fusion, policy] = await Promise.all(['fusion.json', 'policy.json'].map((f) => fetchBytes(`${MESMER}/${f}`).then((b) => JSON.parse(new TextDecoder().decode(b)))));
  const hb = await fetchBytes(`${MESMER}/${man.peg_head.path}`);
  const head = new Float32Array(hb.buffer, hb.byteOffset, hb.byteLength / 4);
  const bytes = await download('mesmer', files, total);
  const sessions = {};
  for (const [i, p] of parts.entries()) {
    show('mesmer', 'busy', 1, `starting on your GPU (${i + 1} of ${parts.length})…`);
    sessions[p] = await gpu(() => ort.InferenceSession.create(bytes[i], { executionProviders: ['webgpu'], logSeverityLevel: 3 }));
    bytes[i] = null;
  }
  const th = policy.thresholds;
  return { ort, man, sessions, head, fusion: { weights: fusion.weights, thresholds: { ai: th.likely_ai_at_or_above, unc: th.uncertain_at_or_above },
    rank: { pel: makeRanker(fusion.reference.pel), peg: makeRanker(fusion.reference.peg) } } };
})());

// ---------------------------------------------------------------- decode
// Strips of at most 4 MP: phone browsers cap canvas area (16 MP on iOS), photos are often bigger.
// sRGB: EXIF orientation, ICC -> sRGB, alpha over white (mesmer's to_srgb).
// raw: EXIF orientation, colours as stored (Smaug's PIL .convert('RGB') does no colour management).
async function decode(blob, srgb) {
  const bmp = await createImageBitmap(blob, { imageOrientation: 'from-image', colorSpaceConversion: srgb ? 'default' : 'none',
    premultiplyAlpha: srgb ? 'default' : 'none' });
  const w = bmp.width, h = bmp.height, step = Math.max(1, Math.min(h, Math.floor(4194304 / w)));
  const cv = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(w, step) : Object.assign(document.createElement('canvas'), { width: w, height: step });
  const ctx = cv.getContext('2d', { willReadFrequently: true });
  ctx.imageSmoothingEnabled = false;
  const out = new Uint8Array(w * h * 3);
  for (let y = 0; y < h; y += step) {
    const n = Math.min(step, h - y);
    if (srgb) { ctx.globalCompositeOperation = 'source-over'; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, w, step); }
    else { ctx.globalCompositeOperation = 'copy'; }
    ctx.drawImage(bmp, 0, y, w, n, 0, 0, w, n);
    const d = ctx.getImageData(0, 0, w, n).data;
    for (let i = 0, o = y * w * 3; i < w * n * 4; i += 4, o += 3) { out[o] = d[i]; out[o + 1] = d[i + 1]; out[o + 2] = d[i + 2]; }
    await tick();
  }
  bmp.close();
  return { w, h, data: out };
}

// ---------------------------------------------------------------- scan
let latest = 0, chain = Promise.resolve();

function onImage(blob, from = null) {
  if (!blob || !/^image\//.test(blob.type || 'image/')) return;
  const id = ++latest;
  ui.photo.src = URL.createObjectURL(blob);
  ui.photo.onload = () => URL.revokeObjectURL(ui.photo.src);
  ui.drop.classList.add('has');
  for (const b of ui.thumbs.children) b.classList.toggle('on', b === from);
  for (const n of Object.keys(rows)) show(n, 'busy', 0, 'reading the photo…');
  chain = chain.then(() => scan(blob, id)).catch((e) => console.error(e));
}

async function scan(blob, id) {
  const stale = () => id !== latest;
  if (stale()) return;
  let smaugIn, mesmerIn;
  try {
    await tick();
    smaugIn = smaugCrops(await decode(blob, false));
    if (stale()) return;
    mesmerIn = mesmerViews(await decode(blob, true));
  } catch (e) {
    for (const n of Object.keys(rows)) show(n, 'bad', 0, `cannot read this image (${e.message || e.name})`);
    return;
  }
  if (stale()) return;
  for (const n of Object.keys(rows)) show(n, 'busy', 0, 'waiting…');
  getMesmer().catch(() => {});        // Mesmer downloads while Smaug runs: separate promise, starts once

  try {
    const s = await getSmaug();
    if (stale()) return;
    show('smaug', 'busy', 0, 'scanning…');
    const t0 = performance.now(), { ort } = { ort: await getOrt() };
    const r = await gpu(() => s.run({ pixels: new ort.Tensor('float32', smaugIn.tensor, [3, 3, 528, 528]) }));
    const lg = Array.from(r.logits.data), p = sigmoid(lg.reduce((a, b) => a + b, 0) / lg.length);
    Object.values(r).forEach((t) => t.dispose?.());
    if (!stale()) {
      const ai = p >= 0.5;
      show('smaug', ai ? 'ai' : 'real', p, `<b>${ai ? 'Looks AI-made' : 'Looks real'}</b> · ${(100 * p).toFixed(p > 0.995 || p < 0.005 ? 1 : 0)}% AI · ${((performance.now() - t0) / 1000).toFixed(1)} s`);
      rows.smaug.title = `crop logits ${lg.map((v) => v.toFixed(2)).join(', ')}`;
    }
  } catch (e) { show('smaug', 'bad', 0, e.message || String(e)); }

  if (stale()) return;
  try {
    const m = await getMesmer();
    if (stale()) return;
    show('mesmer', 'busy', 0, 'scanning…');
    const { ort, sessions: S, fusion } = m, t0 = performance.now();
    const pr = await gpu(() => S.pel.run({ pixels: new ort.Tensor('float32', mesmerIn.pel, [5, 3, 336, 336]) }));
    const pv = Array.from(pr.logit.data), pel = pv.reduce((a, b) => a + b, 0) / pv.length;
    let x = new ort.Tensor('float32', mesmerIn.peg, [1, 3, 448, 448]);
    const st = {};
    for (const [i, part] of m.man.peg.entries()) {
      show('mesmer', 'busy', (i + 1) / (m.man.peg.length + 1), 'scanning…');
      const sess = S[part];
      const o = await gpu(() => sess.run({ [sess.inputNames[0]]: x }));
      for (const k of ['s25', 's38', 's50', 'pooled']) if (o[k]) st[k] = o[k].data;
      x = o.y || o.x;
    }
    const peg = pegLogit(st.s25, st.s38, st.s50, st.pooled, m.head, m.man.peg_head.dims);
    const v = mesmerVerdict(pel, peg, fusion);
    if (!stale()) {
      const label = { likely_ai: ['ai', 'Likely AI'], uncertain: ['unsure', 'Uncertain'], likely_real: ['real', 'Likely real'] }[v.verdict];
      show('mesmer', label[0], v.p_ai, `<b>${label[1]}</b> · ${(100 * v.p_ai).toFixed(v.p_ai > 0.995 || v.p_ai < 0.005 ? 1 : 0)}% · ${((performance.now() - t0) / 1000).toFixed(1)} s`);
      rows.mesmer.title = `score ${v.score.toFixed(3)} (uncertain from ${fusion.thresholds.unc.toFixed(2)}, likely AI from ${fusion.thresholds.ai.toFixed(2)}); PE-L logit ${pel.toFixed(3)}, PE-G logit ${peg.toFixed(3)}`;
    }
  } catch (e) { show('mesmer', 'bad', 0, e.message || String(e)); }
  storage();
}

// ---------------------------------------------------------------- input
// An error thrown inside ONNX Runtime can escape its promise; say so instead of spinning forever.
const fail = (e) => {
  const msg = (e?.reason ?? e?.error ?? e)?.message || String(e?.reason ?? e?.message ?? e);
  for (const n of Object.keys(rows)) if (rows[n].classList.contains('busy')) show(n, 'bad', 0, `stopped: ${msg}. Reload the page to try again.`);
};
addEventListener('error', fail);
addEventListener('unhandledrejection', fail);

ui.file.addEventListener('change', () => { onImage(ui.file.files[0]); ui.file.value = ''; });
addEventListener('paste', (e) => {
  const f = [...(e.clipboardData?.files || [])].find((x) => x.type.startsWith('image/'));
  if (f) { e.preventDefault(); onImage(f); }
});
addEventListener('dragover', (e) => { e.preventDefault(); ui.drop.classList.add('over'); });
addEventListener('dragleave', (e) => { if (!e.relatedTarget) ui.drop.classList.remove('over'); });
addEventListener('drop', (e) => {
  e.preventDefault(); ui.drop.classList.remove('over');
  onImage([...(e.dataTransfer?.files || [])].find((x) => x.type.startsWith('image/')));
});

for (const [file, alt, link] of EXAMPLES) {
  const b = document.createElement('button');
  b.type = 'button'; b.title = alt;
  b.innerHTML = `<img src="examples/thumb/${file.replace(/\.\w+$/, '.jpg')}" alt="${alt}" loading="lazy">`;
  b.addEventListener('click', async () => {
    try {
      const r = await fetch(`examples/${file}`);
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      onImage(new Blob([await r.arrayBuffer()], { type: file.endsWith('.png') ? 'image/png' : 'image/jpeg' }), b);
    } catch (e) { show('smaug', 'bad', 0, `example: ${e.message}`); }
  });
  ui.thumbs.append(b);
}
$('credits').innerHTML = 'Examples: ' + EXAMPLES.map(([, alt, link]) => `<a href="${link}" target="_blank" rel="noopener">${alt.split(': ')[1]}</a>`).join('; ') +
  '. Unsplash photos under the Unsplash License; OpenFake images under CC BY-NC 4.0.';
$('repo').href = `https://huggingface.co/${MESMER_REPO}`; $('repo').textContent = MESMER_REPO;

async function storage() {
  try {
    const e = await navigator.storage.estimate();
    ui.store.textContent = `This site stores ${mb(e.usage || 0)} in this browser.`;
  } catch { ui.store.textContent = ''; }
}
ui.wipe.addEventListener('click', async () => {
  await caches.delete(CACHE).catch(() => {});
  smaugP = mesmerP = null;
  ui.store.textContent = 'Deleted. The models download again on the next photo.';
});
storage();
getManifest().then((m) => { $('sizes').textContent = `${((181210404 + Object.values(m.files).reduce((a, f) => a + f.bytes, 0)) / 1e9).toFixed(1)} GB`; }).catch(() => {});