46 lines
2.2 KiB
JavaScript
46 lines
2.2 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import test from "node:test";
|
|
import { BrowserYamnetClassifier } from "../src/scripts/browser-yamnet-classifier.js";
|
|
|
|
test("YAMNet peak scores are mapped and all owned resources are disposed", async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
const disposed = [];
|
|
const values = new Float32Array(2 * 521);
|
|
values[0] = .4;
|
|
values[521] = .9;
|
|
const output = { shape: [2, 521], data: async () => values, dispose: () => disposed.push("output") };
|
|
const model = { executeAsync: async () => [output], dispose: () => disposed.push("model") };
|
|
const tf = {
|
|
ready: async () => {}, getBackend: () => "cpu", memory: () => ({ numTensors: 0 }),
|
|
loadGraphModel: async () => model,
|
|
tensor1d: () => ({ dispose: () => disposed.push("input") }),
|
|
};
|
|
globalThis.fetch = async () => ({ ok: true, json: async () => ["Fireworks", ...Array(520).fill("Other")] });
|
|
try {
|
|
const predictions = await BrowserYamnetClassifier.classify(new Float32Array(16000), {
|
|
modelUrl: "/static/browser-yamnet/model.json", classMapUrl: "/static/browser-yamnet/yamnet_class_map.json",
|
|
loadTensorFlow: async () => tf,
|
|
});
|
|
assert.equal(predictions[0].class, "Fireworks");
|
|
assert.equal(predictions[0].score, values[521]);
|
|
assert.equal(predictions[0].timeSeconds, .48);
|
|
assert.deepEqual(disposed, ["input", "output", "model"]);
|
|
} finally { globalThis.fetch = originalFetch; }
|
|
});
|
|
|
|
test("model failure still disposes the loaded model", async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
let disposed = false;
|
|
const tf = {
|
|
ready: async () => {}, getBackend: () => "cpu", memory: () => ({ numTensors: 0 }),
|
|
loadGraphModel: async () => ({ dispose: () => { disposed = true; } }),
|
|
};
|
|
globalThis.fetch = async () => ({ ok: false });
|
|
try {
|
|
await assert.rejects(BrowserYamnetClassifier.classify(new Float32Array(16000), {
|
|
modelUrl: "/model.json", classMapUrl: "/map.json", loadTensorFlow: async () => tf,
|
|
}));
|
|
assert.equal(disposed, true);
|
|
} finally { globalThis.fetch = originalFetch; }
|
|
});
|