All files / lib images.js

62.06% Statements 270/435
100% Branches 42/42
47.36% Functions 9/19
62.06% Lines 270/435

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 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 4831x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 1x   1x 1x 1x 1x 1x 1x 1x 40x 40x   1x 1x 1x 1x 1x 4x 4x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 13x 13x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 3x 3x 3x 3x 3x   1x 1x 1x 1x 1x 1x 1x 5x   5x 2x 2x 2x 5x 5x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x                 1x 1x 1x 1x             1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x                                                                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                           1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x   1x       1x 1x 1x 1x 1x 1x 1x                                                                             1x 1x 1x 1x 1x 1x 1x 3x 3x   1x 1x 1x   1x 1x 1x   1x   1x 1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 5x 1x 1x   4x 4x 4x 4x 5x 5x 5x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x                                                                               1x 1x 1x 1x 1x 1x                      
import { uiState } from '$lib/state.svelte';
import { ulid } from 'ulid';
import { coordsScaler, toTopLeftCoords } from './BoundingBoxes.svelte';
import { errorMessage, humanFormatName } from './i18n';
import * as db from './idb.svelte';
import { tables } from './idb.svelte';
import { imageLimits } from './inference_utils';
import { clamp, unique } from './utils';
 
/**
 * @import { Image, Protocol } from './database.js';
 * @import { IDBTransactionWithAtLeast } from './idb.svelte';
 */
 
/**
 * Used for tests
 * @param {string} id
 * @param {string} fileId
 * @returns {Image}
 */
const sampleImage = (id, fileId) => ({
	id,
	fileId,
	addedAt: new Date(667),
	dimensions: { width: 100, height: 100, aspectRatio: 1 },
	filename: 'gurt: syubau.jpeg',
	boundingBoxesAnalyzed: false,
	contentType: 'image/jpeg',
	metadata: {}
});
 
/**
 * Retourne un id d'image
 * @example "01ARZ3NDEKTSV4RRFFQ69G5FAV_000001"
 * @param {string} fileId
 * @param {number} subindex
 */
export function imageId(fileId, subindex = 0) {
	return `${fileId}_${subindex.toString().padStart(6, '0')}`;
}
 
/**
 * Retourne un id d'un ImageFile
 * @example "01ARZ3NDEKTSV4RRFFQ69G5FAV"
 */
export function imageFileId() {
	return ulid();
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('imageId', () => {
		const id = imageFileId();
		expect(imageId(id)).toBe(id + '_000000');
		expect(imageId(id, 2)).toBe(id + '_000002');
		expect(imageId(id, 1234567)).toBe(id + '_1234567');
	});
}
 
/**
 * @param {string} id
 */
export function isValidImageId(id) {
	return /^[0-9A-Z]{26}_\d+$/.test(id);
}
 
if (import.meta.vitest) {
	const { test, expect, describe } = import.meta.vitest;
	describe('isValidImageId', () => {
		test('imageId() generates a valid ID', () => {
			expect(isValidImageId(imageId(imageFileId(), 0))).toBe(true);
		});
		test('imageFileId() is not a valid image ID by itself', () => {
			expect(isValidImageId(imageFileId())).toBe(false);
		});
	});
}
 
/**
 * @param {string} id
 */
function invalidImageIdError(id) {
	return new Error(
		`Identifiant d'image invalide (le format correct est aaaaaaaaaaaaaaaaaaaaaaaaaa_nnnnnn) : ${id}`
	);
}
 
/**
 * Retourne l'id d'un objet ImageFile associé à l'objet Image
 * @template {string|undefined} T
 * @param {T} id
 * @returns {T}
 */
export function imageIdToFileId(id) {
	if (id === undefined) return id;
 
	if (!isValidImageId(id)) {
		throw invalidImageIdError(id);
	}
	// @ts-expect-error
	return id?.replace(/(_\d+)+$/, '');
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('imageIdToFileId', () => {
		const id = '0001KVE9TGKVKZ3GG307YQ70CZ';
		expect(imageIdToFileId(`${id}_000000`)).toBe(id);
		expect(imageIdToFileId(`${id}_1234567`)).toBe(id);
		expect(() => imageIdToFileId(`${id}_${id}_123456`)).toThrowErrorMatchingInlineSnapshot(
			`[Error: Identifiant d'image invalide (le format correct est aaaaaaaaaaaaaaaaaaaaaaaaaa_nnnnnn) : 0001KVE9TGKVKZ3GG307YQ70CZ_0001KVE9TGKVKZ3GG307YQ70CZ_123456]`
		);
		expect(imageIdToFileId(undefined)).toBeUndefined();
		expect(() => imageIdToFileId('000001')).toThrowErrorMatchingInlineSnapshot(
			`[Error: Identifiant d'image invalide (le format correct est aaaaaaaaaaaaaaaaaaaaaaaaaa_nnnnnn) : 000001]`
		);
	});
}
 
/**
 * @param {Protocol|undefined} protocol
 * @param {string|null} imageFileId
 */
export function imageIsAnalyzed(protocol, imageFileId) {
	if (!protocol) return false;
	if (!imageFileId) return false;
	if (uiState.erroredImages.has(imageFileId)) return true;
	return tables.Image.state.some(
		(img) => img.fileId === imageFileId && img.boundingBoxesAnalyzed
	);
}
 
/**
 * @param {Image} image
 */
export function imageIsClassified(image) {
	return Boolean(
		(uiState.classificationMetadataId && image.metadata[uiState.classificationMetadataId]) ||
			uiState.erroredImages.has(image.id)
	);
}
 
/**
 * @param {Image} image
 */
export function imageBufferWasSaved(image) {
	return Boolean(image.fileId || uiState.erroredImages.has(image.id));
}
 
/**
 *
 * @param {string} id ImageFile ID
 * @param {IDBTransactionWithAtLeast<["Image", "ImageFile", "ImagePreviewFile"]>} [tx]
 * @param {boolean} [notFoundOk=true]
 */
export async function deleteImageFile(id, tx, notFoundOk = true) {
	await db.openTransaction(
		['Image', 'ImageFile', 'ImagePreviewFile', 'Observation'],
		{ tx },
		async (tx) => {
			const observations = await tx.objectStore('Observation').getAll();
			// Store there cuz imagesOfImageFile() reads from reactive state.
			const imagesOfFile = imagesOfImageFile(id);
			try {
				tx.objectStore('ImageFile').delete(id);
				tx.objectStore('ImagePreviewFile').delete(id);
 
				for (const image of imagesOfFile) {
					tx.objectStore('Image').delete(image.id);
 
					for (const observation of observations) {
						const remainingImages = observation.images.filter(
							(imageId) => imageId !== image.id
						);
 
						if (remainingImages.length === 0) {
							tx.objectStore('Observation').delete(observation.id);
						} else if (remainingImages.length < observation.images.length) {
							tx.objectStore('Observation').put({
								...observation,
								images: remainingImages
							});
						}
					}
				}
			} catch (error) {
				if (!notFoundOk) return Promise.reject(error);
			}
		}
	);
 
	uiState.erroredImages.delete(id);
	uiState.loadingImages.delete(id);
	uiState.queuedImages.delete(id);
	if (uiState.imageOpenedInCropper === id) {
		uiState.imageOpenedInCropper = '';
	}
 
	const previewURL = uiState.previewURLs.get(id);
	if (previewURL) {
		URL.revokeObjectURL(previewURL);
		uiState.previewURLs.delete(id);
	}
}
 
/**
 *
 * @param {object} param0
 * @param {string} param0.id id of the ImageFile to create
 * @param {ArrayBuffer} param0.originalBytes the image data
 * @param {ArrayBuffer} param0.resizedBytes resized image data
 * @param {string} param0.contentType the content type of the image
 * @param {string} param0.filename the filename of the image
 * @param {number} param0.width the width of the image
 * @param {number} param0.height the height of the image
 * @param {IDBTransactionWithAtLeast<['Image', 'ImageFile', 'ImagePreviewFile']>} [param0.tx] transaction to use
 */
export async function storeImageBytes({
	id,
	originalBytes,
	resizedBytes,
	contentType,
	filename,
	width,
	height,
	tx
}) {
	await db.openTransaction(['ImageFile', 'ImagePreviewFile'], { tx }, async (tx) => {
		tx.objectStore('ImageFile').put({
			id,
			bytes: originalBytes,
			contentType,
			filename,
			dimensions: { width, height }
		});
		tx.objectStore('ImagePreviewFile').put({
			id,
			bytes: resizedBytes,
			contentType,
			filename,
			dimensions: { width, height }
		});
		const preview = new Blob([resizedBytes], { type: contentType });
		uiState.setPreviewURL(id, URL.createObjectURL(preview));
	});
}
 
// ATTENTION: Changer aussi dans la validation des définitions de protocoles (Ctrl-F pour 1024 dans tout le projet pour être sûr·e de rien louper) si jamais on change ça
const MAXWIDTH = 1024;
/**
 * @param {object} param0
 * @param {number} param0.width
 * @param {number} param0.height
 */
const MAXHEIGHT = ({ width, height }) => Math.round((MAXWIDTH * height) / width);
 
const RAW_IMAGE_MEDIA_TYPES = [
	'image/CR2',
	'image/x-canon-cr2',
	'image/x-dcraw',
	'image/x-canon-crw',
	'image/x-kodak-dcr',
	'image/x-adobe-dng',
	'image/x-epson-erf',
	'image/x-kodak-k25',
	'image/x-kodak-kdc',
	'image/x-minolta-mrw',
	'image/x-nikon-nef',
	'image/x-olympus-orf',
	'image/x-pentax-pef',
	'image/x-fuji-raf',
	'image/x-panasonic-raw',
	'image/x-sony-sr2',
	'image/x-sony-srf',
	'image/x-sigma-x3f'
];
 
const ALWAYS_SUPPORTED_TYPES = ['image/jpeg', 'image/png'];
const SUPPORT_PLANNED_TYPES = [...RAW_IMAGE_MEDIA_TYPES];
 
export function errorMessageImageTooLarge() {
	return `L'image est trop grande pour être traitée. Elle doit faire moins de ${imageLimits.maxResolutionInMP} Megapixels et ${imageLimits.maxMemoryUsageInMB} Mo`;
}
 
/**
 * Resize an image to fit within MAXWIDTH and MAXHEIGHT
 * @param {object} param0
 * @param {Blob} param0.source
 * @returns {Promise<[[number, number], ArrayBuffer]>} [[original width, original height], resized image data]
 */
export async function resizeToMaxSize({ source }) {
	// For some reason top-level import fails
	const { resize } = await import('pica-gpu');
	const originalImage = await createImageBitmap(source).catch((error) => {
		throw new Error(
			ALWAYS_SUPPORTED_TYPES.includes(source.type)
				? errorMessage(error)
				: SUPPORT_PLANNED_TYPES.includes(source.type)
					? `Les fichiers ${humanFormatName(source.type)} ne sont pas encore supportés`
					: `Le format de fichier ${humanFormatName(source.type)} n'est pas supporté`
		);
	});
	const { width, height } = originalImage;
 
	if (width * height > imageLimits.maxResolutionInMP * 1e6) {
		throw new Error(errorMessageImageTooLarge());
	}
 
	const originalCanvas = document.createElement('canvas');
	originalCanvas.width = width;
	originalCanvas.height = height;
	originalCanvas.getContext('2d')?.drawImage(originalImage, 0, 0);
 
	const resizedCanvas = document.createElement('canvas');
	resizedCanvas.width = MAXWIDTH;
	resizedCanvas.height = MAXHEIGHT(originalImage);
	resize(originalCanvas, resizedCanvas, {
		targetWidth: MAXWIDTH,
		targetHeight: MAXHEIGHT(originalImage),
		filter: 'mks2013'
	});
	return new Promise((resolve) => {
		resizedCanvas.toBlob((blob) => {
			if (!blob) throw new Error('Failed to resize image');
			blob.arrayBuffer().then((buf) => resolve([[width, height], buf]));
		}, source.type);
	});
}
 
/**
 *
 * @param {string} imageFileId
 * @param {Image[]} [images] look for images in this array instead of the database
 * @returns {Image[]}
 */
export function imagesOfImageFile(imageFileId, images = undefined) {
	return (images ?? tables.Image.state).filter((img) => img.fileId === imageFileId);
}
 
if (import.meta.vitest) {
	const { _tablesState } = await import('./idb.svelte');
	const { test, expect } = import.meta.vitest;
 
	test('imagesOfImageFile', () => {
		const images = [sampleImage('1', '1'), sampleImage('2', '1'), sampleImage('3', '2')];
		const [img1, img2] = images;
 
		expect(imagesOfImageFile('1', images)).toEqual([img1, img2]);
 
		_tablesState.Image = [];
		expect(imagesOfImageFile('1')).toEqual([]);
 
		_tablesState.Image = images;
		expect(imagesOfImageFile('1')).toEqual([img1, img2]);
	});
}
 
/**
 *
 * @param {Image[]} images
 * @returns {string[]}
 */
export function imageFileIds(images) {
	return unique(images.map((image) => image.fileId).filter((id) => id !== null));
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('imageFileIds', () => {
		const images = [sampleImage('1', '1'), sampleImage('2', '1'), sampleImage('3', '2')];
		expect(imageFileIds(images)).toEqual(['1', '2']);
	});
}
 
/**
 * @param {string} imageId
 * @returns {{ fileId: string; subindex: number|null }}
 */
export function parseImageId(imageId) {
	if (!isValidImageId(imageId) && !isValidImageId(`${imageId}_000000`)) {
		throw invalidImageIdError(imageId);
	}
 
	const [fileId, subindex] = imageId.split('_', 2);
	const subindexNumber = Number.parseInt(subindex, 10);
	return {
		fileId,
		subindex: Number.isNaN(subindexNumber) ? null : subindexNumber
	};
}
 
if (import.meta.vitest) {
	const { test, expect, describe } = import.meta.vitest;
	describe('parseImageId', () => {
		test('parses regular IDs', () => {
			const id = '0001KVE9TGKVKZ3GG307YQ70CZ';
			expect(parseImageId(`${id}_000000`)).toEqual({ fileId: id, subindex: 0 });
			expect(parseImageId(`${id}_1234567`)).toEqual({ fileId: id, subindex: 1234567 });
		});
		test('parses ImageFile IDs', () => {
			const id = '0001KVE9TGKVKZ3GG307YQ70CZ';
			expect(parseImageId(id)).toEqual({ fileId: id, subindex: null });
		});
		test('throws on malformed IDs', () => {
			expect(() => parseImageId('coming in hot!!!')).toThrowErrorMatchingInlineSnapshot(
				`[Error: Identifiant d'image invalide (le format correct est aaaaaaaaaaaaaaaaaaaaaaaaaa_nnnnnn) : coming in hot!!!]`
			);
		});
 
		test('roundtrip', () => {
			const id = imageFileId();
			expect(parseImageId(imageId(id, 1234567))).toStrictEqual({
				fileId: id,
				subindex: 1234567
			});
		});
	});
}
 
/**
 * @param {ArrayBuffer} bytes image bytes
 * @param {string} contentType content type of the image
 * @param {import('./metadata').RuntimeValue<'boundingbox'>} centeredBoundingBox
 * @param {string} [padding] padding to add around the bounding box when cropping images. string of the form "npx" or "n%"
 * @returns {Promise<{ cropped: ArrayBuffer, original: ArrayBuffer }>}
 */
export async function cropImage(bytes, contentType, centeredBoundingBox, padding = '0px') {
	const bitmap = await createImageBitmap(new Blob([bytes], { type: contentType }));
	const boundingBox = coordsScaler({ x: bitmap.width, y: bitmap.height })(
		toTopLeftCoords(centeredBoundingBox)
	);
 
	const { inPixels } = parseCropPadding(padding);
	const paddingPixels = { x: inPixels(bitmap.width), y: inPixels(bitmap.height) };
 
	try {
		const croppedBitmap = await createImageBitmap(
			bitmap,
			clamp(boundingBox.x - paddingPixels.x, 0, bitmap.width),
			clamp(boundingBox.y - paddingPixels.y, 0, bitmap.height),
			clamp(boundingBox.width + 2 * paddingPixels.x, 1, bitmap.width),
			clamp(boundingBox.height + 2 * paddingPixels.y, 1, bitmap.height)
		);
 
		const canvas = new OffscreenCanvas(croppedBitmap.width, croppedBitmap.height);
		canvas.getContext('2d')?.drawImage(croppedBitmap, 0, 0);
		const croppedBytes = await canvas
			.convertToBlob({
				type: ['image/png', 'image/jpeg'].includes(contentType) ? contentType : 'image/png'
			})
			.then((blob) => blob.arrayBuffer());
 
		// @ts-ignore
		return { cropped: croppedBytes, original: bytes };
	} catch (error) {
		throw new Error(
			`Couldn't crop with ${JSON.stringify({ boundingBox, padding })}: ${error}`,
			{
				cause: error
			}
		);
	} finally {
		bitmap.close();
	}
}
 
/**
 *
 * @param {string} padding
 * @returns {{ withUnit: string, unitless: number, unit: 'px' | '%', inPixels: (basis: number) => number }}
 */
export function parseCropPadding(padding) {
	const match = padding.match(/(\d+)(px|%)/);
	if (!match) throw new Error(`Invalid crop padding: ${padding}`);
	const [value, unit] = [Number.parseInt(match[1], 10), /** @type {'%'|'px'} */ (match[2])];
	return {
		withUnit: padding,
		unitless: value,
		unit,
		inPixels: (axis) => (unit === 'px' ? value : Math.round((axis * value) / 100))
	};
}