Jarbas commited on
Commit
d1bcdf2
·
verified ·
1 Parent(s): adcaa8e

Sign every request with the page's __sign parameter and show file errors

Browse files

A private Space runs in an iframe on huggingface.co where the browser refuses the Space's SameSite=Lax cookie, so requests made without __sign (the worker's onnxruntime import, the wasm, the models) were answered 401 and the scoring worker never started. Every file the page, its worker and its audio worklet request now carries the __sign parameter of the page URL when there is one, and a failed or timed-out request is shown with its HTTP status and file name.

Files changed (3) hide show
  1. app.js +51 -9
  2. index.html +27 -2
  3. worker.js +59 -7
app.js CHANGED
@@ -3,6 +3,34 @@ const BLOCK = 1280;
3
  const BLOCK_SEC = BLOCK / SR;
4
  const LIVE_SPAN_SEC = 10;
5
  const LIVE_KEEP_BLOCKS = 12.5 * 600;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  // Similar-sounding words each model fires on at its default threshold, from the model repository's README.
8
  const CONFUSIONS = {
@@ -30,7 +58,7 @@ const els = {
30
  };
31
 
32
  // ---- worker -------------------------------------------------------------------------------------
33
- const worker = new Worker(new URL("./worker.js", import.meta.url), {type: "module"});
34
  const pending = new Map();
35
  let nextId = 1;
36
  function call(msg, transfer = []) {
@@ -48,7 +76,11 @@ worker.onmessage = (e) => {
48
  if (m.ok) p.resolve(m);
49
  else p.reject(new Error(m.error));
50
  };
51
- worker.onerror = (e) => setStatus(`The scoring worker failed: ${e.message || "unknown error"}`, true);
 
 
 
 
52
 
53
  // ---- state --------------------------------------------------------------------------------------
54
  let models = [];
@@ -191,7 +223,7 @@ async function selectModel(name) {
191
  const token = ++loadToken;
192
  setStatus(`Loading the ${spoken(entry.name)} model…`);
193
  try {
194
- await call({type: "load", model: entry.name});
195
  if (token !== loadToken) return;
196
  if (mode === "live") {
197
  resetLive();
@@ -296,7 +328,13 @@ async function startMic() {
296
  ctx = new AudioContext();
297
  src = ctx.createMediaStreamSource(stream);
298
  }
299
- await ctx.audioWorklet.addModule(new URL("./worklet.js", import.meta.url));
 
 
 
 
 
 
300
  const node = new AudioWorkletNode(ctx, "wake-capture", {numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1]});
301
  const sink = ctx.createGain();
302
  sink.gain.value = 0;
@@ -523,9 +561,13 @@ els.file.addEventListener("change", async () => {
523
  });
524
  els.runExample.addEventListener("click", async () => {
525
  const name = els.example.value;
526
- const r = await fetch(`clips/${name}.wav`);
527
- if (!r.ok) { setStatus(`Could not fetch the example clip (${r.status}).`, true); return; }
528
- const blob = await r.blob();
 
 
 
 
529
  await loadClip(await blob.arrayBuffer(), `example "${name.replace(/_/g, " ")}"`, blob);
530
  });
531
  els.plot.addEventListener("pointermove", hover);
@@ -534,8 +576,8 @@ new ResizeObserver(() => draw()).observe(els.plot);
534
 
535
  async function init() {
536
  themeLabel();
537
- const [m, r] = await Promise.all([fetch("models.json").then((x) => x.json()),
538
- fetch("results.json").then((x) => x.json())]);
539
  models = m.models;
540
  results = r;
541
  for (const e of models) {
 
3
  const BLOCK_SEC = BLOCK / SR;
4
  const LIVE_SPAN_SEC = 10;
5
  const LIVE_KEEP_BLOCKS = 12.5 * 600;
6
+ const FETCH_TIMEOUT_MS = 90_000;
7
+ const LOAD_TIMEOUT_MS = 180_000;
8
+
9
+ // The page's own files carry the __sign parameter of the page URL (see index.html).
10
+ const signed = (path) => window.signedUrl(path);
11
+
12
+ async function fetchFile(path) {
13
+ const ctl = new AbortController();
14
+ const timer = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
15
+ try {
16
+ const r = await fetch(signed(path), {signal: ctl.signal});
17
+ if (!r.ok) throw new Error(`${path}: HTTP ${r.status}${r.status === 401 || r.status === 403 ? " (not signed in to this Space)" : ""}`);
18
+ return r;
19
+ } catch (err) {
20
+ if (err.name === "AbortError") throw new Error(`${path}: no response after ${FETCH_TIMEOUT_MS / 1000} s`);
21
+ if (err instanceof TypeError) throw new Error(`${path}: ${err.message}`);
22
+ throw err;
23
+ } finally {
24
+ clearTimeout(timer);
25
+ }
26
+ }
27
+
28
+ function withTimeout(promise, ms, what) {
29
+ let timer;
30
+ return Promise.race([promise, new Promise((_, reject) => {
31
+ timer = setTimeout(() => reject(new Error(`${what}: no result after ${ms / 1000} s`)), ms);
32
+ })]).finally(() => clearTimeout(timer));
33
+ }
34
 
35
  // Similar-sounding words each model fires on at its default threshold, from the model repository's README.
36
  const CONFUSIONS = {
 
58
  };
59
 
60
  // ---- worker -------------------------------------------------------------------------------------
61
+ const worker = new Worker(signed("worker.js"), {type: "module"});
62
  const pending = new Map();
63
  let nextId = 1;
64
  function call(msg, transfer = []) {
 
76
  if (m.ok) p.resolve(m);
77
  else p.reject(new Error(m.error));
78
  };
79
+ worker.onerror = (e) => {
80
+ setStatus(`The scoring worker failed to start (worker.js): ${e.message || "the file could not be loaded"}`, true);
81
+ for (const p of pending.values()) p.reject(new Error("the scoring worker failed to start"));
82
+ pending.clear();
83
+ };
84
 
85
  // ---- state --------------------------------------------------------------------------------------
86
  let models = [];
 
223
  const token = ++loadToken;
224
  setStatus(`Loading the ${spoken(entry.name)} model…`);
225
  try {
226
+ await withTimeout(call({type: "load", model: entry.name}), LOAD_TIMEOUT_MS, `Loading ${entry.name}`);
227
  if (token !== loadToken) return;
228
  if (mode === "live") {
229
  resetLive();
 
328
  ctx = new AudioContext();
329
  src = ctx.createMediaStreamSource(stream);
330
  }
331
+ try {
332
+ await ctx.audioWorklet.addModule(signed("worklet.js"));
333
+ } catch (err) {
334
+ stream.getTracks().forEach((t) => t.stop());
335
+ ctx.close();
336
+ throw new Error(`worklet.js could not be loaded: ${err.message}`);
337
+ }
338
  const node = new AudioWorkletNode(ctx, "wake-capture", {numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1]});
339
  const sink = ctx.createGain();
340
  sink.gain.value = 0;
 
561
  });
562
  els.runExample.addEventListener("click", async () => {
563
  const name = els.example.value;
564
+ let blob;
565
+ try {
566
+ blob = await (await fetchFile(`clips/${name}.wav`)).blob();
567
+ } catch (err) {
568
+ setStatus(`Could not fetch the example clip: ${err.message}`, true);
569
+ return;
570
+ }
571
  await loadClip(await blob.arrayBuffer(), `example "${name.replace(/_/g, " ")}"`, blob);
572
  });
573
  els.plot.addEventListener("pointermove", hover);
 
576
 
577
  async function init() {
578
  themeLabel();
579
+ const [m, r] = await Promise.all([fetchFile("models.json").then((x) => x.json()),
580
+ fetchFile("results.json").then((x) => x.json())]);
581
  models = m.models;
582
  results = r;
583
  for (const e of models) {
index.html CHANGED
@@ -6,8 +6,21 @@
6
  <title>WakeHuBERT Wake Words</title>
7
  <meta name="description" content="Try the OpenVoiceOS WakeHuBERT wake-word models in the browser, with a microphone or an audio file.">
8
  <link rel="icon" href="data:,">
9
- <link rel="stylesheet" href="style.css">
10
  <script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  try {
12
  const t = localStorage.getItem("theme");
13
  if (t === "light" || t === "dark") document.documentElement.dataset.theme = t;
@@ -105,6 +118,18 @@
105
  </section>
106
  </main>
107
  <footer class="wrap foot">Models and code Apache-2.0. onnxruntime-web MIT.</footer>
108
- <script type="module" src="app.js"></script>
 
 
 
 
 
 
 
 
 
 
 
 
109
  </body>
110
  </html>
 
6
  <title>WakeHuBERT Wake Words</title>
7
  <meta name="description" content="Try the OpenVoiceOS WakeHuBERT wake-word models in the browser, with a microphone or an audio file.">
8
  <link rel="icon" href="data:,">
 
9
  <script>
10
+ // A private Space runs in an iframe whose cookie the browser may refuse; the page then reaches its own files
11
+ // only with the __sign parameter of its URL, so every one of them is requested with it.
12
+ window.signedUrl = (path) => {
13
+ const url = new URL(path, document.baseURI);
14
+ const sign = new URLSearchParams(location.search).get("__sign");
15
+ if (sign) url.searchParams.set("__sign", sign);
16
+ return url.href;
17
+ };
18
+ (() => {
19
+ const css = document.createElement("link");
20
+ css.rel = "stylesheet";
21
+ css.href = window.signedUrl("style.css");
22
+ document.head.append(css);
23
+ })();
24
  try {
25
  const t = localStorage.getItem("theme");
26
  if (t === "light" || t === "dark") document.documentElement.dataset.theme = t;
 
118
  </section>
119
  </main>
120
  <footer class="wrap foot">Models and code Apache-2.0. onnxruntime-web MIT.</footer>
121
+ <script>
122
+ (() => {
123
+ const app = document.createElement("script");
124
+ app.type = "module";
125
+ app.src = window.signedUrl("app.js");
126
+ app.onerror = () => {
127
+ const status = document.getElementById("status");
128
+ status.textContent = "Could not load app.js. Reload the page; if this Space is private, sign in to Hugging Face.";
129
+ status.classList.add("error");
130
+ };
131
+ document.body.append(app);
132
+ })();
133
+ </script>
134
  </body>
135
  </html>
worker.js CHANGED
@@ -1,10 +1,55 @@
1
  // Wake-word scoring, a port of the scoring path of ovos-ww-plugin-wakeforge
2
  // (WakeForgeHotwordPlugin.update / found_wake_word, OnnxWindowedWakeWord.push with
3
  // isolated windows, PredictionSmoother with the ready-model defaults).
4
- import * as ort from "./vendor/ort/ort.wasm.min.mjs";
 
 
 
5
 
6
- ort.env.wasm.wasmPaths = new URL("./vendor/ort/", import.meta.url).href;
7
- ort.env.wasm.numThreads = 1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  const SAMPLE_RATE = 16000;
10
  const HOP = 320; // featurizer hop (config.json output.hop_samples)
@@ -21,8 +66,15 @@ let models = null;
21
 
22
  function session(path) {
23
  if (!sessions.has(path)) {
24
- const url = new URL("./" + path, import.meta.url).href;
25
- const p = ort.InferenceSession.create(url, {executionProviders: ["wasm"]});
 
 
 
 
 
 
 
26
  p.catch(() => sessions.delete(path));
27
  sessions.set(path, p);
28
  }
@@ -31,8 +83,8 @@ function session(path) {
31
 
32
  async function modelEntry(name) {
33
  if (!models) {
34
- const r = await fetch(new URL("./models.json", import.meta.url));
35
- models = Object.fromEntries((await r.json()).models.map((m) => [m.name, m]));
36
  }
37
  const entry = models[name];
38
  if (!entry) throw new Error(`unknown model ${name}`);
 
1
  // Wake-word scoring, a port of the scoring path of ovos-ww-plugin-wakeforge
2
  // (WakeForgeHotwordPlugin.update / found_wake_word, OnnxWindowedWakeWord.push with
3
  // isolated windows, PredictionSmoother with the ready-model defaults).
4
+ // The worker's URL carries the page's __sign parameter; every file it fetches carries it too, since a private
5
+ // Space's iframe may have no cookie to authenticate them.
6
+ const SIGN = new URL(import.meta.url).searchParams.get("__sign");
7
+ const FETCH_TIMEOUT_MS = 90_000;
8
 
9
+ function signed(path) {
10
+ const url = new URL("./" + path, import.meta.url);
11
+ url.search = "";
12
+ if (SIGN) url.searchParams.set("__sign", SIGN);
13
+ return url.href;
14
+ }
15
+
16
+ async function fetchBytes(path) {
17
+ const ctl = new AbortController();
18
+ const timer = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
19
+ try {
20
+ const r = await fetch(signed(path), {signal: ctl.signal});
21
+ if (!r.ok) throw new Error(`${path}: HTTP ${r.status}${r.status === 401 || r.status === 403 ? " (not signed in to this Space)" : ""}`);
22
+ return new Uint8Array(await r.arrayBuffer());
23
+ } catch (err) {
24
+ if (err.name === "AbortError") throw new Error(`${path}: no response after ${FETCH_TIMEOUT_MS / 1000} s`);
25
+ if (err instanceof TypeError) throw new Error(`${path}: ${err.message}`);
26
+ throw err;
27
+ } finally {
28
+ clearTimeout(timer);
29
+ }
30
+ }
31
+
32
+ let ort = null;
33
+ let ortLoading = null;
34
+
35
+ function loadOrt() {
36
+ ortLoading ??= (async () => {
37
+ const mjs = "vendor/ort/ort.wasm.min.mjs";
38
+ let mod;
39
+ try {
40
+ mod = await import(signed(mjs));
41
+ } catch (err) {
42
+ throw new Error(`${mjs} could not be loaded: ${err.message}`);
43
+ }
44
+ mod.env.wasm.numThreads = 1;
45
+ mod.env.wasm.wasmBinary = await fetchBytes("vendor/ort/ort-wasm-simd-threaded.wasm");
46
+ mod.env.wasm.wasmPaths = {mjs: signed("vendor/ort/ort-wasm-simd-threaded.mjs"),
47
+ wasm: signed("vendor/ort/ort-wasm-simd-threaded.wasm")};
48
+ ort = mod;
49
+ })();
50
+ ortLoading.catch(() => { ortLoading = null; });
51
+ return ortLoading;
52
+ }
53
 
54
  const SAMPLE_RATE = 16000;
55
  const HOP = 320; // featurizer hop (config.json output.hop_samples)
 
66
 
67
  function session(path) {
68
  if (!sessions.has(path)) {
69
+ const p = (async () => {
70
+ await loadOrt();
71
+ const bytes = await fetchBytes(path);
72
+ try {
73
+ return await ort.InferenceSession.create(bytes, {executionProviders: ["wasm"]});
74
+ } catch (err) {
75
+ throw new Error(`${path} could not be opened: ${err.message}`);
76
+ }
77
+ })();
78
  p.catch(() => sessions.delete(path));
79
  sessions.set(path, p);
80
  }
 
83
 
84
  async function modelEntry(name) {
85
  if (!models) {
86
+ const json = JSON.parse(new TextDecoder().decode(await fetchBytes("models.json")));
87
+ models = Object.fromEntries(json.models.map((m) => [m.name, m]));
88
  }
89
  const entry = models[name];
90
  if (!entry) throw new Error(`unknown model ${name}`);