Smaug + Mesmer AI image check, WebGPU
Browse filesFiles changed (17)
- .gitattributes+6
- README.md+31-5
- app.jsAdded+464
- examples/ai-dflow2.pngAdded
- examples/ai-gpt-image-2.pngAdded
- examples/ai-midjourney-7.pngAdded
- examples/photo-real-1.jpgAdded
- examples/photo-real-2.jpgAdded
- examples/photo-real-3.jpgAdded
- examples/thumb/ai-dflow2.jpgAdded
- examples/thumb/ai-gpt-image-2.jpgAdded
- examples/thumb/ai-midjourney-7.jpgAdded
- examples/thumb/photo-real-1.jpgAdded
- examples/thumb/photo-real-2.jpgAdded
- examples/thumb/photo-real-3.jpgAdded
- index.html+52-17
- style.css+68-22
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404132 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/ai-dflow2.png filter=lfs diff=lfs merge=lfs -textexamples/ai-gpt-image-2.png filter=lfs diff=lfs merge=lfs -textexamples/ai-midjourney-7.png filter=lfs diff=lfs merge=lfs -textexamples/photo-real-1.jpg filter=lfs diff=lfs merge=lfs -textexamples/photo-real-2.jpg filter=lfs diff=lfs merge=lfs -textexamples/photo-real-3.jpg filter=lfs diff=lfs merge=lfs -text
12345678910---title: AI Image Detector WebGPUemoji: 📊colorFrom: yellowcolorTo: greensdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536---title: AI Image Checkemoji: 🔍colorFrom: graycolorTo: redsdk: staticapp_file: index.htmlpinned: falselicense: cc-by-nc-sa-4.0short_description: Two AI image detectors in your browser, WebGPUmodels:- abacusai/Smaug-AI-Image-Detector- 21amd21/smaug-ai-image-detector-web- mesmertech/mesmer-ai-image-detector- WeReCooking/Mesmer-AI-Image-Detector-ONNX-WebGPUtags:- webgpu- onnxruntime-web- ai-image-detection---Drop, paste or pick a photo and two detectors check it on your own GPU with ONNX Runtime Web. Nothing is uploaded.- **Smaug** ([abacusai/Smaug-AI-Image-Detector](https://huggingface.co/abacusai/Smaug-AI-Image-Detector), Apache-2.0),run from the 181 MB web build [21amd21/smaug-ai-image-detector-web](https://huggingface.co/21amd21/smaug-ai-image-detector-web).- **Mesmer** ([mesmertech/mesmer-ai-image-detector](https://huggingface.co/mesmertech/mesmer-ai-image-detector), CC-BY-NC-SA-4.0),converted for the browser in [WeReCooking/Mesmer-AI-Image-Detector-ONNX-WebGPU](https://huggingface.co/WeReCooking/Mesmer-AI-Image-Detector-ONNX-WebGPU).The crops and resizes are a JavaScript port of the Pillow code both models were trained with, and give the same pixelsas Python. A score is a likelihood, not proof.Examples: Unsplash photos by Andrew Sterling, Andrey Câmara and Ross Sneddon (Unsplash License); Midjourney 7 andGPT-Image-2 images from [OpenFake](https://huggingface.co/datasets/ComplexDataLab/OpenFake) (CC BY-NC 4.0); a DFlow2 imagemade in [DFlow2 WebGPU](https://huggingface.co/spaces/WeReCooking/DFlow2-WebGPU).Non-commercial: the Mesmer weights are CC-BY-NC-SA-4.0, so this Space is too.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464// 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 }.
// ---------------------------------------------------------------- mesmerconst 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) / stdfunction 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 zfunction 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; };}
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 };}
// ---------------------------------------------------------------- smaugconst 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;}
// ---------------------------------------------------------------- modelslet 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;})());
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 ort.InferenceSession.create(bytes, { executionProviders: ['webgpu'], graphOptimizationLevel: 'disabled', logSeverityLevel: 3 });})());
const getMesmer = () => (mesmerP ||= (async () => { const ort = await getOrt(); 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 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 ort.InferenceSession.create(bytes[i], { executionProviders: ['webgpu'], logSeverityLevel: 3 }); bytes[i] = null; } const th = policy.thresholds; return { ort, man, sessions, 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 };}
// ---------------------------------------------------------------- scanlet 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 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 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]), s25 = null, s38 = null, peg = null; for (const [i, part] of m.man.peg.entries()) { show('mesmer', 'busy', (i + 1) / (m.man.peg.length + 1), 'scanning…'); const sess = S[part], feed = {}; for (const n of sess.inputNames) feed[n] = n === 's25' ? s25 : n === 's38' ? s38 : x; const o = await sess.run(feed); if (o.logit) { peg = o.logit.data[0]; break; } x = o.y || o.x; if (o.s25) s25 = o.s25; if (o.s38) s38 = o.s38; } 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();}
// ---------------------------------------------------------------- inputui.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(() => {});12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>AI Image Check</title><meta name="description" content="Two AI image detectors, Smaug and Mesmer, running on your own GPU with ONNX Runtime Web. Your photo never leaves this tab."><link rel="icon" href="data:,"><link rel="stylesheet" href="style.css"></head><body><main><p id="line"><b>Is it AI?</b> <a href="https://huggingface.co/abacusai/Smaug-AI-Image-Detector" target="_blank" rel="noopener">Smaug</a>and <a href="https://huggingface.co/mesmertech/mesmer-ai-image-detector" target="_blank" rel="noopener">Mesmer</a> check your photo on your own GPU. It never leaves this tab.</p><label id="drop" for="file"><img id="photo" alt=""><span id="ask">Drop, paste or <u>pick a photo</u></span><input id="file" type="file" accept="image/*" class="sr"></label><section id="results" aria-live="polite"><div class="res" id="smaug"><a class="name" href="https://huggingface.co/abacusai/Smaug-AI-Image-Detector" target="_blank" rel="noopener">Smaug</a><span class="meter"><i></i></span><span class="val">waiting for a photo</span></div><div class="res" id="mesmer"><a class="name" href="https://huggingface.co/mesmertech/mesmer-ai-image-detector" target="_blank" rel="noopener">Mesmer</a><span class="meter"><i></i></span><span class="val">waiting for a photo</span></div></section><section id="examples"><p>Or try one: <span class="k">real photos</span> then <span class="k">AI images</span></p><div id="thumbs"></div></section><details id="more"><summary>About, storage and credits</summary><p>Both models download once into this browser (about <span id="sizes">1.3 GB</span>), then work offline. They need WebGPU(Chrome or Edge 121+, Android 12+, Safari 26). Smaug answers first; Mesmer is bigger and follows.</p><p>A score is a likelihood, not proof. Detectors miss images from new generators, and heavy edits, screenshots orrecompression can fool them. Do not use them as the only evidence about a person.</p><p><b>Smaug</b>: <a href="https://huggingface.co/abacusai/Smaug-AI-Image-Detector" target="_blank" rel="noopener">abacusai/Smaug-AI-Image-Detector</a>(Apache-2.0), run from the 4-bit web build <a href="https://huggingface.co/21amd21/smaug-ai-image-detector-web" target="_blank" rel="noopener">21amd21/smaug-ai-image-detector-web</a>.The bar is sigmoid of the mean logit of three 528 px crops.</p><p><b>Mesmer</b>: <a href="https://huggingface.co/mesmertech/mesmer-ai-image-detector" target="_blank" rel="noopener">mesmertech/mesmer-ai-image-detector</a>(CC-BY-NC-SA-4.0, non-commercial), on Meta's Perception Encoder backbones (Apache-2.0). ONNX conversion:<a id="repo" target="_blank" rel="noopener">model repo</a>. Verdict lines and the bar come from the model's policy: 50% at "uncertain", 90% at "likely AI";it is a display score, not a calibrated probability.</p><p id="store"></p><button id="wipe" type="button">Delete downloaded models</button><p id="credits"></p></details></main><script type="module" src="app.js"></script></body></html>
12345678910111213141516171819202122232425262728body {padding: 2rem;font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;}h1 {font-size: 16px;margin-top: 0;}p {color: rgb(107, 114, 128);font-size: 15px;margin-bottom: 10px;margin-top: 5px;}.card {max-width: 620px;margin: 0 auto;padding: 16px;border: 1px solid lightgray;border-radius: 16px;}.card p:last-child {margin-bottom: 0;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374:root {--bg: #f4f2ee; --panel: #ffffff; --ink: #1d1c1a; --muted: #6b6760; --line: #d8d4cc;--accent: #b4441b; --accent-ink: #ffffff; --bad: #a3261b;--real: #2f6f4f; --unsure: #a8741a; --ai: #b4441b;color-scheme: light dark;}@media (prefers-color-scheme: dark) {:root { --bg: #151413; --panel: #1f1d1b; --ink: #ece8e1; --muted: #a29d94; --line: #3a3732;--accent: #e0703f; --accent-ink: #151413; --bad: #ff8a7a;--real: #6cc097; --unsure: #e2b04f; --ai: #e0703f; }}* { box-sizing: border-box; }html, body { margin: 0; background: var(--bg); color: var(--ink);font: 15px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }main {display: grid; gap: 10px; padding: 8px 12px 16px; max-width: 1100px; margin: 0 auto;grid-template-columns: minmax(0, 1fr);grid-template-areas: "line" "drop" "results" "examples" "more";}@media (min-width: 760px) {main { grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); align-items: start;grid-template-rows: auto auto auto 1fr;grid-template-areas: "line line" "drop results" "drop examples" "drop more"; }}#line { grid-area: line; margin: 0; font-size: 14px; color: var(--muted); }#line b { color: var(--ink); font-weight: 600; font-size: 15px; }#drop {grid-area: drop; position: relative; display: grid; place-items: center; cursor: pointer;min-height: 240px; background: var(--panel); border: 1.5px dashed var(--line); border-radius: 6px; overflow: hidden;}#drop.over { border-color: var(--accent); }#drop img { display: none; max-width: 100%; max-height: 70vh; object-fit: contain; }#drop.has img { display: block; }#drop.has { border-style: solid; }#ask { color: var(--muted); padding: 24px; text-align: center; }#ask u { color: var(--accent); }#drop.has #ask { position: absolute; bottom: 6px; right: 8px; padding: 2px 8px; font-size: 12px;background: var(--panel); border-radius: 4px; opacity: .9; }#results { grid-area: results; display: grid; gap: 8px; }.res { display: grid; grid-template-columns: 4.8em minmax(0, 1fr); grid-template-areas: "name meter" "name val";gap: 3px 10px; align-items: center; padding: 8px 10px; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; }.res .name { grid-area: name; font-weight: 600; color: var(--ink); text-decoration: none; align-self: start; padding-top: 1px; }.res .name:hover { text-decoration: underline; }.meter { grid-area: meter; height: 8px; background: var(--line); border-radius: 4px; overflow: hidden; }.meter i { display: block; height: 100%; width: 0; background: var(--muted); transition: width .3s; }.val { grid-area: val; font-size: 14px; color: var(--muted); font-variant-numeric: tabular-nums; min-height: 1.4em; }.val b { font-weight: 600; }.res.real .meter i { background: var(--real); } .res.real .val b { color: var(--real); }.res.unsure .meter i { background: var(--unsure); } .res.unsure .val b { color: var(--unsure); }.res.ai .meter i { background: var(--ai); } .res.ai .val b { color: var(--ai); }.res.busy .meter i { background: var(--muted); opacity: .6; }.res.bad .val { color: var(--bad); }#examples { grid-area: examples; }#examples p { margin: 0 0 6px; font-size: 13px; color: var(--muted); }#thumbs { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; }@media (max-width: 420px) { #thumbs { grid-template-columns: repeat(3, minmax(0, 1fr)); } }#thumbs button { padding: 0; border: 2px solid transparent; border-radius: 5px; background: none; cursor: pointer; aspect-ratio: 1; overflow: hidden; }#thumbs button.on { border-color: var(--accent); }#thumbs img { width: 100%; height: 100%; object-fit: cover; display: block; border-radius: 3px; }.k { color: var(--ink); }#more { grid-area: more; color: var(--muted); font-size: 13px; }#more p { margin: 6px 0; }summary { cursor: pointer; }#wipe { font: inherit; min-height: 30px; padding: 0 12px; cursor: pointer; color: var(--ink); background: transparent;border: 1px solid var(--line); border-radius: 4px; }a { color: var(--accent); }.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }:where(button, input, summary, a, label, [tabindex]):focus-visible { outline: 2px solid var(--accent) !important; outline-offset: 2px; }#drop:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; }@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition-duration: 0.01ms !important; } }
.gitattributes+6
README.md+31-5
app.jsAdded+464
examples/ai-dflow2.pngAdded

Large File Pointer Details
- SHA256: e5dd690034888edafe2c7e28145a2964f3d078d22cac1faa8060cd5b6a89270f
- Pointer size: 132 Bytes
- Size of remote file: 3.52 MB
examples/ai-gpt-image-2.pngAdded

Large File Pointer Details
- SHA256: dd0cb6298de3484a7ef0a22aa3ba0b960744ec93e4875fbdd70b4a03d38b9365
- Pointer size: 132 Bytes
- Size of remote file: 3.54 MB
examples/ai-midjourney-7.pngAdded

Large File Pointer Details
- SHA256: 5586fd23b4dc294e76eb884fc5237e77057ac6dc78aef2dc71a4d2ae51c7db61
- Pointer size: 132 Bytes
- Size of remote file: 1.34 MB
examples/photo-real-1.jpgAdded

Large File Pointer Details
- SHA256: 855d8d353b7d3048a09cd782192793c1a82428a6e395383dc6d896c2aab1de61
- Pointer size: 132 Bytes
- Size of remote file: 7.76 MB
examples/photo-real-2.jpgAdded

Large File Pointer Details
- SHA256: 25ab5125943b5b9f8c8023acc97e784babf79d0a0cb17bdd8d522324b2675ed8
- Pointer size: 132 Bytes
- Size of remote file: 1.03 MB
examples/photo-real-3.jpgAdded

Large File Pointer Details
- SHA256: 150d00488b62434ce6106ff24ca8cb7907915cdb015f0065cefe6362ddfcd339
- Pointer size: 132 Bytes
- Size of remote file: 1.87 MB
examples/thumb/ai-dflow2.jpgAdded
examples/thumb/ai-gpt-image-2.jpgAdded
examples/thumb/ai-midjourney-7.jpgAdded
examples/thumb/photo-real-1.jpgAdded
examples/thumb/photo-real-2.jpgAdded
examples/thumb/photo-real-3.jpgAdded
index.html+52-17
style.css+68-22