All files / lib inference_utils.js

6.5% Statements 8/123
0% Branches 0/19
4.76% Functions 1/21
7.07% Lines 8/113

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  5x                                   3x 3x 3x 3x   3x 3x   3x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
import { match } from 'arktype';
import { Jimp } from 'jimp';
import * as ort from 'onnxruntime-web';
 
import { coordsScaler, toTopLeftCoords } from './BoundingBoxes.svelte.js';
 
/**
 * @satisfies {import('@jimp/js-jpeg').DecodeJpegOptions}
 */
export const imageLimits = /** @type {const} */ ({
	maxMemoryUsageInMB: 1024,
	maxResolutionInMP: 100
});
 
/**
 * @typedef {import('onnxruntime-web')} ort
 */
 
/**
 *
 * @param {number[]} bb1
 * @param {number[]} bb2
 * @returns
 */
function IoU(bb1, bb2) {
	// Intersection over Union
	// bb1 et bb2 sont des bounding boxes de la forme : [x, y, w, h]
	let x1 = Math.max(bb1[0], bb2[0]);
	let y1 = Math.max(bb1[1], bb2[1]);
	let x2 = Math.min(bb1[0] + bb1[2], bb2[0] + bb2[2]);
	let y2 = Math.min(bb1[1] + bb1[3], bb2[1] + bb2[3]);
 
	let intersection = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
	let union = bb1[2] * bb1[3] + bb2[2] * bb2[3] - intersection;
 
	return intersection / union;
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('IoU', () => {
		expect(IoU([0, 0, 10, 10], [5, 5, 10, 10])).toBe(0.14285714285714285);
		expect(IoU([0, 0, 10, 10], [15, 15, 10, 10])).toBe(0);
		expect(IoU([0, 0, 10, 10], [5, 5, 5, 5])).toBe(0.25);
	});
}
/**
 *
 * @param {NonNullable<typeof import('$lib/schemas/metadata.js').MetadataInferOptionsNeural.infer['neural']>[number] } settings
 * @param {ort.Tensor} tensor
 * @param {number[]} mean
 * @param {number[]} std
 * @param {AbortSignal} [abortSignal]
 * @returns {Promise<ort.Tensor>}
 */
export async function preprocessTensor(settings, tensor, mean, std, abortSignal) {
	const { width, height, normalized } = settings.input;
	let c = tensor;
	c = await normalizeTensor(c, mean, std, !normalized, abortSignal);
	c = await resizeTensor(c, width, height, abortSignal);
 
	return c;
}
 
/**
 * _If you need to get back the actual image the model ran on, see commit 682e3fb8849ac3f96005f71a486eefa3c932753a_
 * @param {ArrayBuffer[]} buffers
 * @param {object} settings
 * @param {number} settings.height
 * @param {number} settings.width
 * @param {import('./BoundingBoxes.svelte.js').CenteredBoundingBox} [settings.crop]
 * @param {boolean} [settings.normalized] normalize pixel channel values to [0, 1] instead of [0, 255]
 * @param {AbortSignal} [settings.abortSignal] signal to abort the operation
 * @returns {Promise<import('onnxruntime-web').TypedTensor<'float32'>>}
 */
export async function loadToTensor(
	buffers,
	{ width: targetWidth, height: targetHeight, crop, normalized, abortSignal }
) {
	/*
    charge les images et les resize
    -------input------- :
        files : liste de fichiers
        targetWidth : largeur cible
        targetHeight : hauteur cible
    
    -------output------- :
        tensor : tenseur contenant les images
            forme : [files.length, 3, targetHeight, targetWidth]
    */
 
	var float32Data = new Float32Array(targetHeight * targetWidth * 3 * buffers.length);
	for (let f = 0; f < buffers.length; f++) {
		abortSignal?.throwIfAborted();
 
		let buffer = buffers[f];
 
		const imageTensor = await Jimp.fromBuffer(buffer, {
			'image/jpeg': imageLimits
		});
 
		if (crop) {
			const scaler = coordsScaler({ x: imageTensor.width, y: imageTensor.height });
			const { x, y, height: h, width: w } = toTopLeftCoords(scaler(crop));
			abortSignal?.throwIfAborted();
			imageTensor.crop({ x, y, w, h });
		}
 
		abortSignal?.throwIfAborted();
		imageTensor.resize({ w: targetWidth, h: targetHeight });
 
		var imageBufferData = imageTensor.bitmap.data;
 
		const [redArray, greenArray, blueArray] = new Array(new Array(), new Array(), new Array());
		for (let i = 0; i < imageBufferData.length; i += 4) {
			abortSignal?.throwIfAborted();
			redArray.push(imageBufferData[i]);
			greenArray.push(imageBufferData[i + 1]);
			blueArray.push(imageBufferData[i + 2]);
		}
 
		const transposedData = redArray.concat(greenArray).concat(blueArray);
		let i,
			l = transposedData.length;
 
		if (normalized) {
			for (i = 0; i < l; i++) {
				abortSignal?.throwIfAborted();
				float32Data[f * l + i] = transposedData[i] / 255.0; // convert to float
			}
		}
	}
 
	abortSignal?.throwIfAborted();
	var tensor = new ort.Tensor('float32', float32Data, [
		buffers.length,
		3,
		targetHeight,
		targetWidth
	]);
 
	float32Data = new Float32Array(0);
	return tensor;
}
/**
 *
 * @param {ort.Tensor} tensor
 * @param {number[]} mean
 * @param {number[]} std
 * @param {boolean} [denormalize=false] denormalize the pixel values from [0, 1] to [0, 255]
 * @param {AbortSignal} [abortSignal]
 * @returns {Promise<ort.Tensor>}
 */
async function normalizeTensor(tensor, mean, std, denormalize = false, abortSignal) {
	abortSignal?.throwIfAborted();
	const data = await tensor.getData();
	const dims = tensor.dims;
 
	for (let x = 0; x < dims[2]; x++) {
		for (let y = 0; y < dims[3]; y++) {
			for (let c = 0; c < dims[1]; c++) {
				abortSignal?.throwIfAborted();
				let i = c * dims[2] * dims[3] + x * dims[3] + y;
				// @ts-ignore
				data[i] = (data[i] - mean[c]) / std[c];
				if (denormalize) {
					// @ts-ignore
					data[i] = Math.min(data[i] * 255, 255);
				}
			}
		}
	}
 
	abortSignal?.throwIfAborted();
	const newTensor = new ort.Tensor(tensor.type, data, dims);
	tensor.dispose();
 
	return newTensor;
}
 
/**
 *
 * @param {import('./database.js').ModelDetectionOutputShape} outputShape
 * @param {Float32Array} output
 * @param {number} numImages
 * @param {number} minConfidence
 * @param {AbortSignal} [abortSignal]
 * @returns {[import('./inference.js').BB[][], number[][]]}
 */
export function output2BB(outputShape, output, numImages, minConfidence, abortSignal) {
	/*reshape les bounding boxes obtenues par le modèle d'inférence
    -------input------- :
        output : liste de bounding boxes obtenues par le modèle d'inférence
        numfiles : nombre d'images sur lesquelles on a fait l'inférence*
        minConfidence : seuil de confiance minimum pour considérer une bounding box
        nms : booléen, si True, alors on applique le fait que la sortie d'un modèle 
            ultralytics avec des nms est différente que quand yen a pas
            
 
    -------output------- :
        bestBoxes : liste de bounding boxes après suppression des doublons
            forme : [each img [each box [x, y, w, h]]]
        bestScore : liste des meilleurs scores pour chaque image
            forme : [each img [each box score]]
    */
 
	/** @type {import('./inference.js').BB[][]}  */
	let bestBoxes = [];
	/** @type {number[][]}  */
	let bestScores = [];
 
	const suboutputSize = outputShape.length;
	let boundingBoxesCount = output.length / suboutputSize;
 
	for (let k = 0; k < numImages; k++) {
		/** @type {import('./inference.js').BB[]}  */
		let bestPerImageBoxes = [];
		/** @type {number[]} */
		let bbScores = [];
 
		let suboutput = output.slice(
			k * boundingBoxesCount * suboutputSize,
			(k + 1) * boundingBoxesCount * suboutputSize
		);
 
		for (let i = 0; i < suboutput.length; i += suboutputSize) {
			abortSignal?.throwIfAborted();
			/**
			 * Get a data point ("atom") for this bounding box for this model.
			 * If the protocol's inference detection output shape does not include the atom, return undefined.
			 * Otherwise, grab the data point from the suboutput using the index of the atom in the output shape.
			 * For example, if the output shape is `['sx', '_', '_', 'sy']`, we can get the 'sy' atom using `suboutput[i + 3]`.
			 * @param {import('./database').ModelDetectionOutputShape[number]} atom
			 */
			const atom = (atom) =>
				outputShape.includes(atom) ? suboutput[i + outputShape.indexOf(atom)] : undefined;
 
			// All possible data points ("atoms") for this bounding box
			const atoms = {
				sx: atom('sx'),
				sy: atom('sy'),
				ex: atom('ex'),
				ey: atom('ey'),
				cx: atom('cx'),
				cy: atom('cy'),
				w: atom('w'),
				h: atom('h'),
				score: atom('score')
			};
 
			// Get center point x coord and width
			const [x, w] = match
				.case({ cx: 'number', ex: 'number' }, ({ cx, ex }) => [cx, 2 * (ex - cx)])
				.case({ cx: 'number', sx: 'number' }, ({ sx, cx }) => [cx, 2 * (cx - sx)])
				.case({ cx: 'number', w: 'number' }, ({ cx, w }) => [cx, w])
				.case({ ex: 'number', sx: 'number' }, ({ sx, ex }) => [(sx + ex) / 2, ex - sx])
				.case({ ex: 'number', w: 'number' }, ({ ex, w }) => [ex - w / 2, w])
				.case({ sx: 'number', w: 'number' }, ({ sx, w }) => [sx + w / 2, w])
				.default(() => {
					throw new Error(
						`Could not get center point x coord and width. Check your protocol's inference.detection.output.shape. Available atoms: ${JSON.stringify(atoms)}`
					);
				})(atoms);
 
			const [y, h] = match
				.case({ cy: 'number', ey: 'number' }, ({ cy, ey }) => [cy, 2 * (ey - cy)])
				.case({ cy: 'number', sy: 'number' }, ({ sy, cy }) => [cy, 2 * (cy - sy)])
				.case({ cy: 'number', h: 'number' }, ({ cy, h }) => [cy, h])
				.case({ ey: 'number', sy: 'number' }, ({ sy, ey }) => [(sy + ey) / 2, ey - sy])
				.case({ ey: 'number', h: 'number' }, ({ ey, h }) => [ey - h / 2, h])
				.case({ sy: 'number', h: 'number' }, ({ sy, h }) => [sy + h / 2, h])
				.default(() => {
					throw new Error(
						`Could not get center point y coord and height. Check your protocol's inference.detection.output.shape. Available atoms: ${JSON.stringify(atoms)}`
					);
				})(atoms);
 
			if (x == 0 && y == 0 && w == 0 && h == 0) {
				break;
			}
 
			if (atoms.score === undefined) {
				throw new Error(
					"Could not get score. Check your protocol's inference.detection.output.shape."
				);
			}
 
			if (atoms.score > minConfidence) {
				bestPerImageBoxes.push([x, y, w, h]);
				bbScores.push(atoms.score);
			}
		}
 
		bestBoxes.push(bestPerImageBoxes);
		bestScores.push(bbScores);
	}
	return [bestBoxes, bestScores];
}
 
/**
 *
 * @param {ort.Tensor} tensor
 * @param {number} targetWidth
 * @param {number} targetHeight
 * @param {AbortSignal} [abortSignal]
 * @returns {Promise<ort.Tensor>}
 */
async function resizeTensor(tensor, targetWidth, targetHeight, abortSignal) {
	// resize using nearest neighbor interpolation
	abortSignal?.throwIfAborted();
	const data = await tensor.getData();
	const dims = tensor.dims;
 
	const resizedData = new Float32Array(targetHeight * targetWidth * 3);
	const resizedDims = [1, 3, targetHeight, targetWidth];
 
	const widthRatio = dims[3] / targetWidth;
	const heightRatio = dims[2] / targetHeight;
 
	for (let x = 0; x < targetWidth; x++) {
		for (let y = 0; y < targetHeight; y++) {
			for (let c = 0; c < 3; c++) {
				abortSignal?.throwIfAborted();
 
				const i = c * targetHeight * targetWidth + y * targetWidth + x;
 
				const j =
					c * dims[2] * dims[3] +
					Math.floor(y * heightRatio) * dims[3] +
					Math.floor(x * widthRatio);
				// @ts-ignore
				resizedData[i] = data[j];
			}
		}
	}
 
	abortSignal?.throwIfAborted();
	const resizedTensor = new ort.Tensor(tensor.type, resizedData, resizedDims);
	return resizedTensor;
}