Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/assets/messages/ui.da.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
4 changes: 4 additions & 0 deletions src/assets/messages/ui.de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
4 changes: 4 additions & 0 deletions src/assets/messages/ui.en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
19 changes: 13 additions & 6 deletions src/core/utils/Math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
75 changes: 75 additions & 0 deletions src/lib/domain/stores/ValidationSets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ValidationSet[]> {
private validationSets: Writable<ValidationSet[]>;

Expand Down Expand Up @@ -90,6 +106,65 @@ class ValidationSets implements Readable<ValidationSet[]> {
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<GestureID, RecordingData[]>();
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<ValidationSet[]>,
invalidate?: Invalidator<ValidationSet[]> | undefined,
Expand Down
39 changes: 37 additions & 2 deletions src/lib/utils/FileUtility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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<FileReader>) {
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);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/utils/graphUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
61 changes: 61 additions & 0 deletions src/pages/validation/ValidationPageControlBar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,51 @@
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) ===
0;
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();
};
});
</script>

<ControlBar>
Expand All @@ -31,4 +68,28 @@
color={'primary'}>
{$tr('content.validation.clearValidations')}
</StandardButton>
<div class="ml-2" />
<StandardButton
fillOnHover
small
disabled={isClearDisabled}
onClick={downloadValidationSets}
bold={false}
outlined
shadows={false}
color={'primary'}>
{$tr('content.validation.downloadValidations')}
</StandardButton>
<div class="ml-2" />
<StandardButton
fillOnHover
small
disabled={$gestures.length === 0}
onClick={uploadValidationSets}
bold={false}
outlined
shadows={false}
color={'primary'}>
{$tr('content.validation.uploadValidations')}
</StandardButton>
</ControlBar>
Loading