All files / lib/metadata merging.ts

48.51% Statements 49/101
50% Branches 16/32
41.37% Functions 24/58
52.32% Lines 45/86

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            8x                                                                               1x 2x       1x         1x   1x   1x 3x 3x     1x                           2x       2x   2x   2x 42x 8x 4x 4x     4x 8x 64x 8x     4x   8x 3x   6x       2x               4x       3x   6x                 4x           3x   6x 6x 3x       4x   3x         6x                                                                 1x                                                                         3x         1x 1x 1x                                                                                                                   2x               2x                                                  
import type * as DB from '$lib/database';
import { type RuntimeValue } from '$lib/schemas/metadata.js';
import { avg, mapValues, nonnull } from '$lib/utils.js';
 
import { switchOnMetadataType, type RuntimeValuesPerType } from './types.js';
 
export const MERGEABLE_METADATA_TYPES: Set<DB.MetadataType> = new Set([
	'boolean',
	'integer',
	'float',
	'date',
	'location',
	'boundingbox',
	'enum'
]);
 
/**
 * Merge metadata values from images and observations. For every metadata key, the value is taken from the merged values of observation overrides if there exists at least one, otherwise from the merged values of the images.
 */
export function mergeMetadataFromImagesAndObservations({
	definitions,
	images,
	observations
}: {
	definitions: DB.Metadata[];
	images: DB.Image[];
	observations: DB.Observation[];
}) {
	// TODO improve performance by passing a cache
	// const options = await Promise.all(
	// 	definitions.map(async (def) => {
	// 		if (def.type !== 'enum') return [def.id, []] as const;
	// 		const parsedId = splitMetadataId(def.id);
	// 		if (!parsedId.namespace) {
	// 			throw new Error(`Cannot get options for non-namespaced metadata ID ${def.id}`);
	// 		}
 
	// 		const opts = await db.getAll(
	// 			'MetadataOption',
	// 			metadataOptionsKeyRange(parsedId.namespace, parsedId.id)
	// 		);
 
	// 		return [def.id, opts] as const;
	// 	})
	// ).then((entries) => Object.fromEntries(entries));
 
	const mergedValues = mergeMetadataValues(
		images.map((img) => img.metadata),
		{ definitions }
	);
 
	const mergedOverrides = mergeMetadataValues(
		observations.map((obs) => obs.metadataOverrides),
		{ definitions }
	);
 
	const keys = new Set([...Object.keys(mergedValues), ...Object.keys(mergedOverrides)]);
 
	const output: Record<string, DB.MetadataValue & { merged: boolean }> = {};
 
	for (const key of keys) {
		const value = mergedOverrides[key] ?? mergedValues[key];
		Eif (value) output[key] = value;
	}
 
	return output;
}
 
export function mergeMetadataValues(
	values: Array<DB.MetadataValues>,
	{
		definitions,
		options = {}
	}: {
		definitions: DB.Metadata[];
		/** Key is id of the metadata */
		options?: Record<string, DB.MetadataEnumVariant[]>;
	}
): Record<string, DB.MetadataValue & { merged: boolean }> {
	Iif (values.length === 1) {
		return mapValues(values[0], (v) => ({ ...v, merged: false }));
	}
 
	const output: Record<string, DB.MetadataValue & { merged: boolean }> = {};
 
	const keys = new Set(values.flatMap((singleSubjectValues) => Object.keys(singleSubjectValues)));
 
	for (const key of keys) {
		const definition = definitions.find((def) => def.id === key);
		if (!definition) {
			console.warn(`Cannot merge metadata values for unknown key ${key}`);
			continue;
		}
 
		const valuesOfKey = values.flatMap((singleSubjectValues) =>
			Object.entries(singleSubjectValues)
				.filter(([k]) => k === key)
				.map(([, v]) => v)
		);
 
		const merged = mergeMetadata(definition, valuesOfKey, options[key] ?? []);
 
		if (merged !== null && merged !== undefined)
			output[key] = {
				...merged,
				merged: new Set(valuesOfKey.map((v) => JSON.stringify(v.value))).size > 1
			};
	}
 
	return output;
}
 
function mergeMetadata(
	definition: DB.Metadata,
	values: DB.MetadataValue[],
	options: DB.MetadataEnumVariant[] = []
) {
	const mergeAlternatives = (
		merger: (probabilities: number[]) => number,
		values: DB.MetadataValue[]
	) =>
		Object.fromEntries(
			values
				.flatMap((v) => Object.keys(v.alternatives))
				.map((valueAsString) => [
					valueAsString,
					merger(
						values.flatMap((v) => v.alternatives[valueAsString] ?? null).filter(Boolean)
					)
				])
		);
 
	const mergeFullValue = ({
		value,
		confidences
	}: {
		value: RuntimeValue;
		confidences: (probabilities: number[]) => number;
	}): DB.MetadataValue => ({
		value,
		manuallyModified: values.some((v) => v.manuallyModified),
		confidence: confidences(values.map((v) => v.confidence)),
		confirmed: values.every((v) => v.confirmed),
		alternatives: mergeAlternatives(confidences, values)
	});
 
	switch (definition.mergeMethod) {
		case 'average':
			return mergeFullValue({
				confidences: avg,
				value: mergeByAggregate({
					aggregate: avg,
					type: definition.type,
					values: values.map((v) => v.value),
					options
				})
			});
		case 'max':
		case 'min':
			return mergeFullValue({
				confidences: max,
				value: mergeByMajority(
					definition.type,
					values,
					definition.mergeMethod === 'max' ? max : min
				)
			});
		case 'median':
			return mergeFullValue({
				confidences: median,
				value: mergeByAggregate({
					aggregate: median,
					type: definition.type,
					values: values.map((v) => v.value),
					options
				})
			});
		case 'union':
			return mergeFullValue({
				confidences: avg,
				value: mergeByUnion(
					definition.type,
					values.map((v) => v.value)
				)
			});
		case 'none':
			return null;
	}
}
 
/**
 * Merge values by best confidence. If multiple values have the same confidence, use `strategy` to break the tie. If `strategy` throws, use first value as a fallback.
 */
function mergeByMajority<Type extends DB.MetadataType, Value extends RuntimeValue<Type>>(
	_type: Type,
	values: Array<{ value: Value; confidence: number }>,
	strategy: (values: Value[]) => Value
): Value {
	const bestConfidence = Math.max(...values.map((v) => v.confidence));
	const bestValues = values.filter((v) => v.confidence === bestConfidence);
	try {
		return strategy(bestValues.map((v) => v.value));
	} catch (error) {
		console.error(error);
		return bestValues[0].value;
	}
}
 
/**
 * Merge values by a numerical aggregation function, such as average or median.
 */
function mergeByAggregate<Type extends DB.MetadataType, Value extends RuntimeValue<Type>>({
	type,
	values,
	options,
	aggregate
}: {
	type: Type;
	values: Value[];
	options: DB.MetadataEnumVariant[];
	aggregate: (vals: number[]) => number;
}) {
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	return switchOnMetadataType<any, RuntimeValuesPerType>(
		type,
		values,
		{
			boolean: (...vals) => aggregate(toNumber('boolean', vals)) > 0.5,
			integer: (...vals) => Math.ceil(aggregate(vals)),
			float: (...vals) => aggregate(vals),
			date: (...vals) => new Date(aggregate(toNumber('date', vals))),
			location: (...vals) => ({
				latitude: aggregate(vals.map((v) => v.latitude)),
				longitude: aggregate(vals.map((v) => v.longitude))
			}),
			enum: (...vals) => {
				// Get average index of values, and return closest option
 
				const targetIndex = Math.round(
					aggregate(
						vals.map((v) => options.find((opt) => opt.key === v)?.index).filter(nonnull)
					)
				);
 
				return options.find((opt) => opt.index === targetIndex)?.key ?? vals[0];
			}
		},
		() => {
			throw new Error(`Impossible de fusionner des valeurs de type ${type}`);
		}
	);
}
 
/**
 * Merge values by union.
 */
function mergeByUnion(type: DB.MetadataType, values: Array<RuntimeValue>) {
	return switchOnMetadataType<RuntimeValue<'boundingbox'>>(
		type,
		values,
		{
			boundingbox: (...vals) => {
				const xStart = Math.min(...vals.map((v) => v.x));
				const yStart = Math.min(...vals.map((v) => v.y));
				const xEnd = Math.max(...vals.map((v) => v.x + v.w));
				const yEnd = Math.max(...vals.map((v) => v.y + v.h));
 
				return {
					x: xStart,
					y: yStart,
					w: xEnd - xStart,
					h: yEnd - yStart
				};
			}
		},
		() => {
			throw new Error(`Impossible de fusionner des valeurs de type ${type} par union`);
		}
	);
}
 
/**
 * Convert series of values to an output number
 */
function toNumber(
	type: DB.MetadataType & ('integer' | 'float' | 'boolean' | 'date'),
	values: Array<RuntimeValue<typeof type>>
) {
	return values.map((value) =>
		switchOnMetadataType<number>(
			type,
			value,
			{
				integer: (v) => v,
				float: (v) => v,
				boolean: (v) => (v ? 1 : 0),
				date: (v) => new Date(v).getTime()
			},
			() => {
				throw new Error(`Impossible de convertir des valeurs de type ${type} en nombre`);
			}
		)
	);
}
 
function median(values: number[]) {
	const sorted = values.sort((a, b) => a - b);
	const middle = Math.floor(sorted.length / 2);
	if (sorted.length % 2 === 0) {
		return (sorted[middle - 1] + sorted[middle]) / 2;
	}
	return sorted[middle];
}
 
function max(values: number[]) {
	return Math.max(...values);
}
 
function min(values: number[]) {
	return Math.min(...values);
}