// MiniGPT-4's vision side in the browser: EVA ViT-g -> Q-Former -> linear projection, as one ONNX graph (8-bit weights) on ONNX Runtime Web. import { resize } from './pilresize.js'; const MEAN = [0.48145466, 0.4578275, 0.40821073], STD = [0.26862954, 0.26130258, 0.27577711]; // bitmap -> Float32 [1,3,224,224]: PIL-exact bicubic squash to 224x224 (no crop), then normalise, like blip2_image_eval. export function preprocess(bitmap) { const c = new OffscreenCanvas(bitmap.width, bitmap.height), g = c.getContext('2d', { willReadFrequently: true }); g.fillStyle = '#fff'; g.fillRect(0, 0, c.width, c.height); g.drawImage(bitmap, 0, 0); // flatten transparency like PIL's convert('RGB') on white-less data const px = g.getImageData(0, 0, c.width, c.height).data, rgb = new Uint8Array(c.width * c.height * 3); for (let i = 0, j = 0; i < px.length; i += 4, j += 3) { rgb[j] = px[i]; rgb[j + 1] = px[i + 1]; rgb[j + 2] = px[i + 2]; } const r = resize({ w: c.width, h: c.height, data: rgb }, 224, 224, 'bicubic'), out = new Float32Array(3 * 224 * 224); for (let i = 0; i < 224 * 224; i++) for (let k = 0; k < 3; k++) out[k * 224 * 224 + i] = (r.data[i * 3 + k] / 255 - MEAN[k]) / STD[k]; return out; } async function runOnce(ort, files, input, ep) { const [model, data] = await Promise.all([files.model.arrayBuffer(), files.data.arrayBuffer()]); const sess = await ort.InferenceSession.create(new Uint8Array(model), { executionProviders: [ep], logSeverityLevel: 3, externalData: [{ path: files.dataName, data: new Uint8Array(data) }] }); try { return Float32Array.from((await sess.run({ image: new ort.Tensor('float32', input, [1, 3, 224, 224]) })).embeds.data); } // copied out before release finally { await sess.release(); } } const sane = (e) => { let s = 0, s2 = 0; for (const v of e) { if (!Number.isFinite(v)) return false; s += v; s2 += v * v; } const n = e.length; return Math.sqrt(s2 / n - (s / n) ** 2) > 0.05; }; // 32 x 4096 image embeddings. If the GPU run fails or returns junk (a driver or kernel problem), redo it on the CPU provider. export async function encodeImage(ort, files, bitmap, ep, onFallback) { const input = preprocess(bitmap); if (ep === 'webgpu') { try { const e = await runOnce(ort, files, input, 'webgpu'); if (sane(e)) return e; console.warn('WebGPU vision output looks wrong'); } catch (err) { console.warn('WebGPU vision run failed', err); } onFallback?.(); } return runOnce(ort, files, input, 'wasm'); }