diff --git a/src/assets/messages/ui.da.json b/src/assets/messages/ui.da.json index 8cf43a628..1132157b9 100644 --- a/src/assets/messages/ui.da.json +++ b/src/assets/messages/ui.da.json @@ -124,6 +124,10 @@ "content.validation.percentage": "Nøjagtighed", "content.validation.accuracy": "Accuracy", "content.validation.clearValidations": "Ryd valideringssæt", + "content.validation.downloadValidations": "Download valideringssæt", + "content.validation.uploadValidations": "Upload valideringssæt", + "content.validation.upload.skipped": "Nogle valideringssæt matchede ingen gestus og blev sprunget over: {names}", + "content.validation.upload.error": "Filen kunne ikke indlæses som valideringssæt.", "content.validation.infobox.classesContent": "Her kan du se de klasser, du har defineret på datasiden.", "content.validation.noGestures.title": "Ingen klasser...", "content.validation.noGestures.description": "Du har endnu ikke tilføjet nogen klasser. Gå til datatrinnet i menuen til venstre og tilføj nogle.", diff --git a/src/assets/messages/ui.de.json b/src/assets/messages/ui.de.json index d82d57054..233334f83 100644 --- a/src/assets/messages/ui.de.json +++ b/src/assets/messages/ui.de.json @@ -124,6 +124,10 @@ "content.validation.percentage": "Prozentsatz", "content.validation.accuracy": "Genauigkeit", "content.validation.clearValidations": "Validierungssätze löschen", + "content.validation.downloadValidations": "Validierungssätze herunterladen", + "content.validation.uploadValidations": "Validierungssätze hochladen", + "content.validation.upload.skipped": "Einige Validierungssätze passten zu keiner Geste und wurden übersprungen: {names}", + "content.validation.upload.error": "Die Datei konnte nicht als Validierungssätze gelesen werden.", "content.validation.infobox.classesContent": "Hier siehst du die Klassen, die du auf der Datenseite definiert hast.", "content.validation.noGestures.title": "Keine Gesten...", "content.validation.noGestures.description": "Du hast noch keine Gesten hinzugefügt. Gehe zum Schritt „Daten“ im Menü auf der linken Seite und füge welche hinzu.", diff --git a/src/assets/messages/ui.en.json b/src/assets/messages/ui.en.json index af66d416c..fae5ef922 100644 --- a/src/assets/messages/ui.en.json +++ b/src/assets/messages/ui.en.json @@ -124,6 +124,10 @@ "content.validation.percentage": "Percentage", "content.validation.accuracy": "Accuracy", "content.validation.clearValidations": "Clear validation sets", + "content.validation.downloadValidations": "Download validation sets", + "content.validation.uploadValidations": "Upload validation sets", + "content.validation.upload.skipped": "Some validation sets did not match any gesture and were skipped: {names}", + "content.validation.upload.error": "The file could not be read as validation sets.", "content.validation.infobox.classesContent": "Here you see the classes that you have defined on the data page.", "content.validation.noGestures.title": "No gestures...", "content.validation.noGestures.description": "You haven't added any gestures yet. Go to the data step in the menu to the left and add some.", diff --git a/src/core/utils/Math.ts b/src/core/utils/Math.ts index 7f39a9dba..dceee094d 100644 --- a/src/core/utils/Math.ts +++ b/src/core/utils/Math.ts @@ -16,12 +16,19 @@ export const distanceBetween = (p1: Vector, p2: Vector): number => { } // Calculate the distance using the Euclidean formula - const squaredDifferences = p1.getValue().map((coord, index) => { - const difference = coord - p2.getValue()[index]; - return difference ** 2; - }); + const point1 = p1.getValue(); + const point2 = p2.getValue(); - const sumOfSquares = squaredDifferences.reduce((sum, value) => sum + value, 0); + // Step 1: For each feature, find the difference between the two points, + // square it (multiply it by itself), and add it to a running total. + let sumOfSquares = 0; + for (let i = 0; i < point1.length; i++) { + const difference = point1[i] - point2[i]; + const squaredDifference = difference * difference; + sumOfSquares = sumOfSquares + squaredDifference; + } - return Math.sqrt(sumOfSquares); + // Step 2: The distance is the square root of that total. + const distance = Math.sqrt(sumOfSquares); + return distance; }; diff --git a/src/lib/domain/stores/ValidationSets.ts b/src/lib/domain/stores/ValidationSets.ts index f417150b3..ccfa1b719 100644 --- a/src/lib/domain/stores/ValidationSets.ts +++ b/src/lib/domain/stores/ValidationSets.ts @@ -19,6 +19,22 @@ import PersistantWritable from '../../repository/PersistantWritable'; import type Gestures from './gesture/Gestures'; import type { GestureID } from '../../../core/entities/Gesture'; +/** + * File format for downloaded/uploaded validation sets. + * Mirrors the shape of the training dataset (ID, name, recordings), so + * a training dataset file can also be imported as validation sets. + */ +export type PersistedValidationSet = { + ID: GestureID; + name: string; + recordings: RecordingData[]; +}; + +export type ValidationSetImportResult = { + importedSets: number; + skippedSets: string[]; +}; + class ValidationSets implements Readable { private validationSets: Writable; @@ -90,6 +106,65 @@ class ValidationSets implements Readable { this.validationSets.set([]); } + /** + * Returns the validation sets alongside gesture names, in gesture order, for downloading. + */ + public exportSets(): PersistedValidationSet[] { + const sets = get(this); + return get(this.gestures).map((gesture, idx) => ({ + ID: gesture.ID, + name: gesture.name, + recordings: sets[idx]?.recordings ?? [], + })); + } + + /** + * Replaces the current validation sets with the imported ones. + * Each imported set is matched to an existing gesture by ID, falling back to the + * gesture name (case-insensitive). Sets matching no gesture are skipped. + */ + public importFrom(data: PersistedValidationSet[]): ValidationSetImportResult { + if (!Array.isArray(data)) { + throw new Error('Invalid validation set file: expected an array'); + } + const gestures = get(this.gestures); + const merged = new Map(); + const skippedSets: string[] = []; + + data.forEach(entry => { + if (!entry || !Array.isArray(entry.recordings)) { + return; + } + const gesture = + gestures.find(g => g.ID === entry.ID) ?? + gestures.find( + g => + typeof entry.name === 'string' && + g.name.trim().toLowerCase() === entry.name.trim().toLowerCase(), + ); + if (!gesture) { + skippedSets.push(entry.name ?? String(entry.ID)); + return; + } + merged.set(gesture.ID, [...(merged.get(gesture.ID) ?? []), ...entry.recordings]); + }); + + // Reassign recording IDs, to avoid collisions between imported recordings + let nextId = Date.now(); + const newSets: ValidationSet[] = gestures + .filter(gesture => merged.has(gesture.ID)) + .map(gesture => ({ + gestureId: gesture.ID, + recordings: merged.get(gesture.ID)!.map(recording => ({ + ...recording, + ID: nextId++, + })), + })); + + this.validationSets.set(newSets); + return { importedSets: newSets.length, skippedSets }; + } + public subscribe( run: Subscriber, invalidate?: Invalidator | undefined, diff --git a/src/lib/utils/FileUtility.ts b/src/lib/utils/FileUtility.ts index 8f9fdc621..529a22b40 100644 --- a/src/lib/utils/FileUtility.ts +++ b/src/lib/utils/FileUtility.ts @@ -6,6 +6,10 @@ import { type GestureData } from '../domain/stores/gesture/GestureState'; import { type PersistedGestureData } from '../domain/stores/gesture/Gestures'; import { stores } from '../stores/Stores'; +import type { + PersistedValidationSet, + ValidationSetImportResult, +} from '../domain/stores/ValidationSets'; class FileUtility { public static loadDatasetFromFile(file: File) { @@ -22,14 +26,45 @@ class FileUtility { reader.readAsText(file as Blob); } + public static loadValidationSetsFromFile( + file: File, + onLoaded?: (result: ValidationSetImportResult) => void, + onError?: (error: unknown) => void, + ) { + const reader = new FileReader(); + reader.onload = function (e: ProgressEvent) { + const contents = e.target?.result; + if (typeof contents !== 'string') { + return; + } + try { + const result = stores + .getValidationSets() + .importFrom(JSON.parse(contents) as PersistedValidationSet[]); + onLoaded?.(result); + } catch (error) { + onError?.(error); + } + }; + reader.readAsText(file as Blob); + } + + public static downloadValidationSets(validationSets: PersistedValidationSet[]) { + FileUtility.downloadJson(validationSets, 'validation-sets'); + } + public static downloadDataset(gestureData: GestureData[]) { + FileUtility.downloadJson(gestureData, 'dataset'); + } + + private static downloadJson(data: unknown, filename: string) { const element = document.createElement('a'); element.setAttribute( 'href', 'data:application/json;charset=utf-8,' + - encodeURIComponent(JSON.stringify(gestureData, null, 2)), + encodeURIComponent(JSON.stringify(data, null, 2)), ); - element.setAttribute('download', 'dataset'); + element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); diff --git a/src/lib/utils/graphUtils.ts b/src/lib/utils/graphUtils.ts index 3cbbf47af..ab5729913 100644 --- a/src/lib/utils/graphUtils.ts +++ b/src/lib/utils/graphUtils.ts @@ -160,12 +160,19 @@ export const distanceBetween = (p1: Vector, p2: Vector): number => { } // Calculate the distance using the Euclidean formula - const squaredDifferences = p1.getValue().map((coord, index) => { - const difference = coord - p2.getValue()[index]; - return difference ** 2; - }); + const point1 = p1.getValue(); + const point2 = p2.getValue(); - const sumOfSquares = squaredDifferences.reduce((sum, value) => sum + value, 0); + // Step 1: For each feature, find the difference between the two points, + // square it (multiply it by itself), and add it to a running total. + let sumOfSquares = 0; + for (let i = 0; i < point1.length; i++) { + const difference = point1[i] - point2[i]; + const squaredDifference = difference * difference; + sumOfSquares = sumOfSquares + squaredDifference; + } - return Math.sqrt(sumOfSquares); + // Step 2: The distance is the square root of that total. + const distance = Math.sqrt(sumOfSquares); + return distance; }; diff --git a/src/pages/validation/ValidationPageControlBar.svelte b/src/pages/validation/ValidationPageControlBar.svelte index 7b6754a30..5f61b7cfc 100644 --- a/src/pages/validation/ValidationPageControlBar.svelte +++ b/src/pages/validation/ValidationPageControlBar.svelte @@ -9,7 +9,10 @@ import ControlBar from '../../components/ui/control-bar/ControlBar.svelte'; import { tr } from '../../i18n'; import { stores } from '../../lib/stores/Stores'; + import { onMount } from 'svelte'; + import FileUtility from '../../lib/utils/FileUtility'; const validationSets = stores.getValidationSets(); + const gestures = stores.getGestures(); $: isClearDisabled = $validationSets.length === 0 || $validationSets.map(e => e.recordings.length).reduce((pre, cur) => pre + cur, 0) === @@ -17,6 +20,40 @@ const clearValidationSets = () => confirm($tr('content.data.controlbar.button.clearData.confirm')) && validationSets.clear(); + + const downloadValidationSets = () => + FileUtility.downloadValidationSets(validationSets.exportSets()); + + const uploadValidationSets = () => filePicker.click(); + + let filePicker: HTMLInputElement; + onMount(() => { + filePicker = document.createElement('input'); + filePicker.type = 'file'; + filePicker.accept = 'application/JSON'; + filePicker.onchange = () => { + if (filePicker.files == null || filePicker.files.length < 1) { + return; + } + FileUtility.loadValidationSetsFromFile( + filePicker.files[0], + result => { + if (result.skippedSets.length > 0) { + alert( + $tr('content.validation.upload.skipped', { + values: { names: result.skippedSets.join(', ') }, + }), + ); + } + }, + () => alert($tr('content.validation.upload.error')), + ); + filePicker.value = ''; // To trick element to trigger onChange if same file selected + }; + return () => { + filePicker.remove(); + }; + }); @@ -31,4 +68,28 @@ color={'primary'}> {$tr('content.validation.clearValidations')} +
+ + {$tr('content.validation.downloadValidations')} + +
+ + {$tr('content.validation.uploadValidations')} +