@mieweb/ui 0.11.0-dev.7 → 0.11.0-dev.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/brands/index.cjs +12 -12
  2. package/dist/brands/index.js +3 -3
  3. package/dist/{chunk-WGXJNCRG.cjs → chunk-2GBVJHWN.cjs} +47 -28
  4. package/dist/{chunk-WGXJNCRG.cjs.map → chunk-2GBVJHWN.cjs.map} +1 -1
  5. package/dist/chunk-3TUULOTW.cjs +333 -0
  6. package/dist/chunk-3TUULOTW.cjs.map +1 -0
  7. package/dist/{chunk-OODVC2UD.cjs → chunk-AWSSWNJY.cjs} +2 -2
  8. package/dist/{chunk-OODVC2UD.cjs.map → chunk-AWSSWNJY.cjs.map} +1 -1
  9. package/dist/{chunk-GJPCWR4C.js → chunk-DAAJ3B2T.js} +47 -29
  10. package/dist/chunk-DAAJ3B2T.js.map +1 -0
  11. package/dist/{chunk-QJ2L5RU6.js → chunk-DSQCYX7L.js} +2 -2
  12. package/dist/{chunk-QJ2L5RU6.js.map → chunk-DSQCYX7L.js.map} +1 -1
  13. package/dist/{chunk-JTSKPDPH.cjs → chunk-HIYQ3M5V.cjs} +4 -3
  14. package/dist/chunk-HIYQ3M5V.cjs.map +1 -0
  15. package/dist/chunk-IZY4CMOO.js +715 -0
  16. package/dist/chunk-IZY4CMOO.js.map +1 -0
  17. package/dist/{chunk-753ENNB6.js → chunk-J3QEMZCH.js} +2 -2
  18. package/dist/{chunk-753ENNB6.js.map → chunk-J3QEMZCH.js.map} +1 -1
  19. package/dist/{chunk-VNWJTCBQ.js → chunk-MQOYDQTF.js} +4 -3
  20. package/dist/chunk-MQOYDQTF.js.map +1 -0
  21. package/dist/{chunk-NKG2UNXE.js → chunk-OZKJYLN6.js} +3 -3
  22. package/dist/{chunk-NKG2UNXE.js.map → chunk-OZKJYLN6.js.map} +1 -1
  23. package/dist/{chunk-C66JR43M.cjs → chunk-Q6QLGCL7.cjs} +9 -9
  24. package/dist/{chunk-C66JR43M.cjs.map → chunk-Q6QLGCL7.cjs.map} +1 -1
  25. package/dist/{chunk-NAH65KPK.cjs → chunk-TOJ56HKQ.cjs} +2 -2
  26. package/dist/{chunk-NAH65KPK.cjs.map → chunk-TOJ56HKQ.cjs.map} +1 -1
  27. package/dist/chunk-TRZLN32I.cjs +740 -0
  28. package/dist/chunk-TRZLN32I.cjs.map +1 -0
  29. package/dist/chunk-XQIQX5OB.js +309 -0
  30. package/dist/chunk-XQIQX5OB.js.map +1 -0
  31. package/dist/components/DictationButton/index.cjs +23 -0
  32. package/dist/components/DictationButton/index.cjs.map +1 -0
  33. package/dist/components/DictationButton/index.d.cts +67 -0
  34. package/dist/components/DictationButton/index.d.ts +67 -0
  35. package/dist/components/DictationButton/index.js +6 -0
  36. package/dist/components/DictationButton/index.js.map +1 -0
  37. package/dist/components/Markdown/index.cjs +10 -10
  38. package/dist/components/Markdown/index.js +2 -2
  39. package/dist/components/RecordButton/index.cjs +4 -4
  40. package/dist/components/RecordButton/index.js +1 -1
  41. package/dist/components/SuperChat/index.cjs +3 -3
  42. package/dist/components/SuperChat/index.d.cts +2 -2
  43. package/dist/components/SuperChat/index.d.ts +2 -2
  44. package/dist/components/SuperChat/index.js +1 -1
  45. package/dist/components/SuperChat/plugins/index.cjs +3 -3
  46. package/dist/components/SuperChat/plugins/index.d.cts +2 -2
  47. package/dist/components/SuperChat/plugins/index.d.ts +2 -2
  48. package/dist/components/SuperChat/plugins/index.js +2 -2
  49. package/dist/index.cjs +363 -899
  50. package/dist/index.cjs.map +1 -1
  51. package/dist/index.d.cts +102 -1
  52. package/dist/index.d.ts +102 -1
  53. package/dist/index.js +124 -730
  54. package/dist/index.js.map +1 -1
  55. package/dist/styles.css +1 -1
  56. package/dist/{types-Cx1FHLq2.d.cts → types-DSWbrVkM.d.cts} +1 -1
  57. package/dist/{types-Cx1FHLq2.d.ts → types-DSWbrVkM.d.ts} +1 -1
  58. package/dist/whisperTranscribe-AV752TZI.cjs +81 -0
  59. package/dist/whisperTranscribe-AV752TZI.cjs.map +1 -0
  60. package/dist/whisperTranscribe-UBNUWXUQ.js +4 -0
  61. package/dist/whisperTranscribe-UBNUWXUQ.js.map +1 -0
  62. package/package.json +1 -1
  63. package/dist/chunk-GJPCWR4C.js.map +0 -1
  64. package/dist/chunk-JTSKPDPH.cjs.map +0 -1
  65. package/dist/chunk-VNWJTCBQ.js.map +0 -1
@@ -0,0 +1,715 @@
1
+ // src/components/AI/modelCache.ts
2
+ var registered = /* @__PURE__ */ new Set();
3
+ function registerModelServiceWorker(swUrl = "/ozwell-model-sw.js") {
4
+ if (typeof navigator === "undefined" || !("serviceWorker" in navigator))
5
+ return;
6
+ if (registered.has(swUrl)) return;
7
+ registered.add(swUrl);
8
+ navigator.serviceWorker.register(swUrl).then(
9
+ () => console.log("[modelCache] model service worker registered"),
10
+ (e) => {
11
+ registered.delete(swUrl);
12
+ console.warn(
13
+ "[modelCache] SW registration failed (models will still load, just not cached):",
14
+ e
15
+ );
16
+ }
17
+ );
18
+ }
19
+
20
+ // src/components/AI/ozwellChat.ts
21
+ var DEFAULT_BASE = "https://api.ozwell.ai";
22
+ var OLLAMA_BASE = "http://localhost:11434";
23
+ var DEFAULTS = {
24
+ model: "gpt-4o-mini",
25
+ system: "You are Ozwell, a concise and helpful clinical assistant. Answer briefly and clearly.",
26
+ temperature: 0.7
27
+ };
28
+ function readWindowGlobal() {
29
+ if (typeof window === "undefined") return {};
30
+ const get = (w) => {
31
+ try {
32
+ return w?.__ozwell;
33
+ } catch {
34
+ return void 0;
35
+ }
36
+ };
37
+ return get(window) || get(window.parent) || get(window.top) || {};
38
+ }
39
+ function sanitizeConfig(o) {
40
+ if (!o || typeof o !== "object") return {};
41
+ const out = {};
42
+ for (const k of Object.keys(o)) {
43
+ if (k === "__proto__" || k === "constructor" || k === "prototype") continue;
44
+ out[k] = o[k];
45
+ }
46
+ return out;
47
+ }
48
+ function readRaw() {
49
+ let stored = {};
50
+ try {
51
+ stored = sanitizeConfig(
52
+ JSON.parse(localStorage.getItem("ozwellConfig") || "{}")
53
+ );
54
+ } catch {
55
+ }
56
+ return { ...stored, ...sanitizeConfig(readWindowGlobal()) };
57
+ }
58
+ function getOzwellConfig() {
59
+ const c = readRaw();
60
+ const apiKey = c.apiKey || "";
61
+ const baseURL = c.baseURL || (apiKey === "ollama" ? OLLAMA_BASE : DEFAULT_BASE);
62
+ return {
63
+ baseURL,
64
+ apiKey,
65
+ model: c.model || DEFAULTS.model,
66
+ system: c.system ?? DEFAULTS.system,
67
+ // Coerce: temperature set via console/localStorage often arrives as a string; a string in the request
68
+ // body can be rejected by OpenAI-compatible servers. Fall back to the default if it's not a real number —
69
+ // and guard the empty/whitespace string explicitly, since Number('') is 0 (a valid-looking temperature)
70
+ // and would silently pin sampling to 0 instead of using the default.
71
+ temperature: c.temperature != null && String(c.temperature).trim() !== "" && Number.isFinite(Number(c.temperature)) ? Number(c.temperature) : DEFAULTS.temperature
72
+ };
73
+ }
74
+ function isOzwellConfigured() {
75
+ return !!getOzwellConfig().apiKey;
76
+ }
77
+ function toOzwellMessages(msgs) {
78
+ const out = [];
79
+ for (const m of msgs) {
80
+ if (m.role !== "user" && m.role !== "assistant") continue;
81
+ const text = (m.content || []).map((c) => c.text || "").join(" ").trim();
82
+ if (text) out.push({ role: m.role, content: text });
83
+ }
84
+ return out;
85
+ }
86
+ function withSystem(messages, system) {
87
+ if (!system || messages.some((m) => m.role === "system")) return messages;
88
+ return [{ role: "system", content: system }, ...messages];
89
+ }
90
+ function buildRequest(messages, cfg, stream) {
91
+ const msgs = typeof messages === "string" ? [{ role: "user", content: messages }] : messages;
92
+ return {
93
+ url: `${cfg.baseURL.replace(/\/$/, "")}/v1/chat/completions`,
94
+ headers: {
95
+ "Content-Type": "application/json",
96
+ // 'ollama' is a sentinel that points baseURL at the local Ollama server, not a real credential —
97
+ // don't send it as a Bearer token (some local OpenAI-compatible servers reject unexpected auth).
98
+ ...cfg.apiKey && cfg.apiKey !== "ollama" ? { Authorization: `Bearer ${cfg.apiKey}` } : {}
99
+ },
100
+ body: JSON.stringify({
101
+ model: cfg.model,
102
+ messages: withSystem(msgs, cfg.system),
103
+ temperature: cfg.temperature,
104
+ stream
105
+ })
106
+ };
107
+ }
108
+ function resolveConfig(opts) {
109
+ const cfg = { ...getOzwellConfig(), ...opts };
110
+ if (opts.apiKey && !opts.baseURL && !readRaw().baseURL) {
111
+ cfg.baseURL = cfg.apiKey === "ollama" ? OLLAMA_BASE : DEFAULT_BASE;
112
+ }
113
+ return cfg;
114
+ }
115
+ async function askOzwell(messages, opts = {}) {
116
+ const cfg = resolveConfig(opts);
117
+ const req = buildRequest(messages, cfg, false);
118
+ const res = await fetch(req.url, {
119
+ method: "POST",
120
+ headers: req.headers,
121
+ body: req.body,
122
+ signal: opts.signal
123
+ });
124
+ if (!res.ok) throw new Error(`Ozwell API ${res.status}: ${res.statusText}`);
125
+ const data = await res.json();
126
+ return (data?.choices?.[0]?.message?.content ?? "").trim();
127
+ }
128
+ async function askOzwellStream(messages, onToken, opts = {}) {
129
+ const cfg = resolveConfig(opts);
130
+ const req = buildRequest(messages, cfg, true);
131
+ const res = await fetch(req.url, {
132
+ method: "POST",
133
+ headers: req.headers,
134
+ body: req.body,
135
+ signal: opts.signal
136
+ });
137
+ if (!res.ok || !res.body)
138
+ throw new Error(`Ozwell API ${res.status}: ${res.statusText}`);
139
+ const reader = res.body.getReader();
140
+ const decoder = new TextDecoder();
141
+ let buf = "";
142
+ let full = "";
143
+ const processEvent = (ev) => {
144
+ for (const line of ev.split(/\r?\n/)) {
145
+ if (!line.startsWith("data:")) continue;
146
+ const payload = line.slice(5).trim();
147
+ if (payload === "[DONE]") return true;
148
+ try {
149
+ const json = JSON.parse(payload);
150
+ const delta = json?.choices?.[0]?.delta?.content || "";
151
+ if (delta) {
152
+ full += delta;
153
+ onToken(delta, full);
154
+ }
155
+ } catch {
156
+ }
157
+ }
158
+ return false;
159
+ };
160
+ try {
161
+ for (; ; ) {
162
+ const { done, value } = await reader.read();
163
+ if (done) break;
164
+ buf += decoder.decode(value, { stream: true });
165
+ const events = buf.split(/\r?\n\r?\n/);
166
+ buf = events.pop() || "";
167
+ for (const ev of events) if (processEvent(ev)) return full;
168
+ }
169
+ buf += decoder.decode();
170
+ if (buf.trim()) processEvent(buf);
171
+ } finally {
172
+ try {
173
+ await reader.cancel();
174
+ } catch {
175
+ }
176
+ }
177
+ return full;
178
+ }
179
+
180
+ // src/components/AI/whisperTranscribe.ts
181
+ var HF_HOST = "https://huggingface.co";
182
+ var HF_PATH = "{model}/resolve/{revision}/";
183
+ var R2_HOST = "https://pub-64db68afc2cb4e108ff06e7e583f09d1.r2.dev";
184
+ function whisperHost() {
185
+ if (typeof window === "undefined") return R2_HOST;
186
+ const fromWin = (w) => {
187
+ try {
188
+ return w?.__ozwellWhisperHost;
189
+ } catch {
190
+ return void 0;
191
+ }
192
+ };
193
+ const win = fromWin(window) || fromWin(window.parent) || fromWin(window.top);
194
+ if (win) return win.replace(/\/$/, "");
195
+ try {
196
+ const h = JSON.parse(
197
+ localStorage.getItem("ozwellConfig") || "{}"
198
+ ).whisperHost;
199
+ if (h) return String(h).replace(/\/$/, "");
200
+ } catch {
201
+ }
202
+ return R2_HOST;
203
+ }
204
+ var SMALL_MODELS = {
205
+ tiny: "Xenova/whisper-tiny.en",
206
+ "tiny.en": "Xenova/whisper-tiny.en",
207
+ base: "Xenova/whisper-base.en",
208
+ "base.en": "Xenova/whisper-base.en",
209
+ small: "Xenova/whisper-small.en",
210
+ "small.en": "Xenova/whisper-small.en"
211
+ };
212
+ var GATE_MODEL = "Xenova/whisper-base.en";
213
+ function whisperPref() {
214
+ if (typeof window === "undefined") return null;
215
+ const fromWin = (w) => {
216
+ try {
217
+ return w?.__ozwell?.whisper;
218
+ } catch {
219
+ return void 0;
220
+ }
221
+ };
222
+ const win = fromWin(window) || fromWin(window.parent) || fromWin(window.top);
223
+ if (win) return win;
224
+ try {
225
+ return JSON.parse(localStorage.getItem("ozwellConfig") || "{}").whisper || null;
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+ function whisperDevice() {
231
+ if (typeof window === "undefined") return null;
232
+ const fromWin = (w) => {
233
+ try {
234
+ return w?.__ozwell?.whisperDevice;
235
+ } catch {
236
+ return void 0;
237
+ }
238
+ };
239
+ const win = fromWin(window) || fromWin(window.parent) || fromWin(window.top);
240
+ if (win) return win;
241
+ try {
242
+ return JSON.parse(localStorage.getItem("ozwellConfig") || "{}").whisperDevice || null;
243
+ } catch {
244
+ return null;
245
+ }
246
+ }
247
+ function whisperDtype() {
248
+ if (typeof window === "undefined") return null;
249
+ const fromWin = (w) => {
250
+ try {
251
+ return w?.__ozwell?.whisperDtype;
252
+ } catch {
253
+ return void 0;
254
+ }
255
+ };
256
+ const win = fromWin(window) || fromWin(window.parent) || fromWin(window.top);
257
+ if (win) return win;
258
+ try {
259
+ return JSON.parse(localStorage.getItem("ozwellConfig") || "{}").whisperDtype || null;
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+ var DEFAULT_TRANSFORMERS_URL = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";
265
+ function transformersUrl() {
266
+ try {
267
+ const w = window.__ozwellTransformersUrl;
268
+ if (w) return w;
269
+ const ls = localStorage.getItem("ozwellTransformersUrl");
270
+ if (ls) return ls;
271
+ } catch {
272
+ }
273
+ return DEFAULT_TRANSFORMERS_URL;
274
+ }
275
+ var dictationLoad = {
276
+ active: false,
277
+ progress: 0,
278
+ done: false
279
+ };
280
+ var loadListeners = /* @__PURE__ */ new Set();
281
+ function setDictationLoad(patch) {
282
+ dictationLoad = { ...dictationLoad, ...patch };
283
+ loadListeners.forEach((l) => l());
284
+ }
285
+ function getDictationLoad() {
286
+ return dictationLoad;
287
+ }
288
+ function subscribeDictationLoad(cb) {
289
+ loadListeners.add(cb);
290
+ return () => {
291
+ loadListeners.delete(cb);
292
+ };
293
+ }
294
+ var WORKER_SRC = `
295
+ let cfg = null, modP = null, pipeP = null, gateP = null, isMulti = false;
296
+ let chain = Promise.resolve();
297
+ const serialize = (fn) => { const r = chain.then(fn, fn); chain = r.then(() => {}, () => {}); return r; };
298
+
299
+ function getMod() {
300
+ if (modP) return modP;
301
+ modP = (async () => {
302
+ const mod = await import(cfg.transformersUrl);
303
+ mod.env.allowLocalModels = false;
304
+ // transformers.js's OWN cache STREAMS the model straight to the Cache API (how whisper-web caches this
305
+ // 1.2GB turbo model). A hand-rolled SW that buffers the whole file chokes (QuotaExceeded).
306
+ mod.env.useBrowserCache = true;
307
+ mod.env.backends.onnx.wasm.numThreads = 1;
308
+ try { if (navigator.storage && navigator.storage.persist) await navigator.storage.persist(); } catch (e) {}
309
+ return mod;
310
+ })();
311
+ return modP;
312
+ }
313
+
314
+ function progressCb() {
315
+ const frac = {};
316
+ const report = () => {
317
+ const v = Object.values(frac);
318
+ self.postMessage({ type: 'progress', frac: v.length ? v.reduce((a, b) => a + b, 0) / v.length : 0 });
319
+ };
320
+ return (p) => {
321
+ if (!p || !p.file) return;
322
+ if (p.status === 'initiate') { frac[p.file] = frac[p.file] || 0; report(); }
323
+ else if (p.status === 'done') { frac[p.file] = 1; report(); }
324
+ else if (p.status === 'progress' && typeof p.progress === 'number') { frac[p.file] = p.progress / 100; report(); }
325
+ };
326
+ }
327
+
328
+ async function buildEnglish(modelId) {
329
+ const mod = await getMod();
330
+ mod.env.remoteHost = cfg.hfHost;
331
+ mod.env.remotePathTemplate = cfg.hfPath;
332
+ if ((cfg.whisperDevice || '').toLowerCase() !== 'wasm') {
333
+ try {
334
+ const gpuDtype = cfg.whisperDtype || 'q8';
335
+ const pipe = await mod.pipeline('automatic-speech-recognition', modelId, { device: 'webgpu', dtype: gpuDtype, progress_callback: progressCb() });
336
+ console.log('[whisper] ready (' + modelId + ' / WebGPU ' + gpuDtype + ', worker)');
337
+ return pipe;
338
+ } catch (e) { /* fall through to wasm */ }
339
+ }
340
+ const pipe = await mod.pipeline('automatic-speech-recognition', modelId, { dtype: 'q8', progress_callback: progressCb() });
341
+ console.log('[whisper] ready (' + modelId + ' / wasm, worker)');
342
+ return pipe;
343
+ }
344
+
345
+ async function buildTurbo() {
346
+ const mod = await getMod();
347
+ mod.env.remoteHost = cfg.whisperHost;
348
+ mod.env.remotePathTemplate = '{model}/';
349
+ const pipe = await mod.pipeline('automatic-speech-recognition', 'whisper-turbo', {
350
+ device: 'webgpu',
351
+ dtype: { encoder_model: 'fp16', decoder_model_merged: 'q4' },
352
+ progress_callback: progressCb(),
353
+ });
354
+ isMulti = true;
355
+ console.log('[whisper] ready (turbo / worker)');
356
+ return pipe;
357
+ }
358
+
359
+ function loadWhisper() {
360
+ if (pipeP) return pipeP;
361
+ self.postMessage({ type: 'loadState', patch: { active: true, progress: 0, done: false } });
362
+ pipeP = (async () => {
363
+ const pref = (cfg.whisperPref || '').toLowerCase();
364
+ if (pref && pref !== 'turbo' && cfg.smallModels[pref]) {
365
+ console.log('[whisper] loading ' + pref + ' (forced via ozwellConfig.whisper)\u2026');
366
+ return serialize(() => buildEnglish(cfg.smallModels[pref]));
367
+ }
368
+ console.log('[whisper] loading turbo\u2026');
369
+ try { return await serialize(() => buildTurbo()); }
370
+ catch (e) {
371
+ console.log('[whisper] turbo unavailable (' + (e && e.message ? e.message : e) + ') \u2192 base.en fallback');
372
+ return serialize(() => buildEnglish(cfg.gateModel));
373
+ }
374
+ })();
375
+ pipeP.then(
376
+ () => self.postMessage({ type: 'loadState', patch: { active: false, progress: 1, done: true } }),
377
+ () => { pipeP = null; self.postMessage({ type: 'loadState', patch: { active: false } }); }
378
+ );
379
+ return pipeP;
380
+ }
381
+
382
+ function loadGate() {
383
+ if (gateP) return gateP;
384
+ console.log('[whisper] loading stop-confirm gate (base.en)\u2026');
385
+ gateP = serialize(() => buildEnglish(cfg.gateModel));
386
+ gateP.catch(() => { gateP = null; });
387
+ return gateP;
388
+ }
389
+
390
+ self.onmessage = async (e) => {
391
+ const m = e.data;
392
+ if (!m) return;
393
+ if (m.type === 'init') { cfg = m.cfg; return; }
394
+ if (m.type === 'warm') { loadWhisper().catch(() => {}); return; }
395
+ if (m.type === 'warmGate') { loadGate().catch(() => {}); return; }
396
+ if (m.type === 'transcribe') {
397
+ try {
398
+ let pipe, opts;
399
+ if (m.want === 'gate') { pipe = await loadGate(); opts = { chunk_length_s: 30 }; }
400
+ else {
401
+ pipe = await loadWhisper();
402
+ if (m.want === 'segments' || m.want === 'words') opts = Object.assign({ chunk_length_s: 30, return_timestamps: m.want === 'words' ? 'word' : true }, isMulti ? { language: 'english', task: 'transcribe' } : {});
403
+ else opts = isMulti ? { chunk_length_s: 30, language: 'english', task: 'transcribe' } : { chunk_length_s: 30 };
404
+ }
405
+ const out = await pipe(m.samples, opts);
406
+ self.postMessage({ type: 'result', id: m.id, text: (out && out.text ? out.text : '').trim(), chunks: (out && out.chunks) || null });
407
+ } catch (err) {
408
+ self.postMessage({ type: 'error', id: m.id, message: err && err.message ? err.message : String(err) });
409
+ }
410
+ }
411
+ };
412
+ `;
413
+ var worker = null;
414
+ var reqId = 0;
415
+ var pending = /* @__PURE__ */ new Map();
416
+ function buildWorkerCfg() {
417
+ return {
418
+ transformersUrl: transformersUrl(),
419
+ whisperHost: whisperHost(),
420
+ whisperPref: whisperPref(),
421
+ whisperDevice: whisperDevice(),
422
+ whisperDtype: whisperDtype(),
423
+ hfHost: HF_HOST,
424
+ hfPath: HF_PATH,
425
+ smallModels: SMALL_MODELS,
426
+ gateModel: GATE_MODEL
427
+ };
428
+ }
429
+ function getWorker() {
430
+ if (worker) return worker;
431
+ registerModelServiceWorker();
432
+ const url = URL.createObjectURL(
433
+ new Blob([WORKER_SRC], { type: "application/javascript" })
434
+ );
435
+ const w = new Worker(url, { type: "module" });
436
+ w.onmessage = (e) => {
437
+ const m = e.data;
438
+ if (!m) return;
439
+ if (m.type === "loadState") {
440
+ setDictationLoad(m.patch);
441
+ return;
442
+ }
443
+ if (m.type === "progress") {
444
+ setDictationLoad({ progress: m.frac });
445
+ return;
446
+ }
447
+ if (m.type === "result") {
448
+ const p = pending.get(m.id);
449
+ if (p) {
450
+ pending.delete(m.id);
451
+ p.resolve({ text: m.text, chunks: m.chunks });
452
+ }
453
+ return;
454
+ }
455
+ if (m.type === "error") {
456
+ const p = pending.get(m.id);
457
+ if (p) {
458
+ pending.delete(m.id);
459
+ p.reject(new Error(m.message));
460
+ }
461
+ return;
462
+ }
463
+ };
464
+ w.onerror = (e) => {
465
+ const err = new Error(
466
+ `whisper worker error: ${e.message || "failed to load"}`
467
+ );
468
+ pending.forEach((p) => p.reject(err));
469
+ pending.clear();
470
+ setDictationLoad({ active: false });
471
+ };
472
+ w.postMessage({ type: "init", cfg: buildWorkerCfg() });
473
+ worker = w;
474
+ return worker;
475
+ }
476
+ function callWorker(want, samples) {
477
+ const w = getWorker();
478
+ const id = ++reqId;
479
+ return new Promise((resolve, reject) => {
480
+ pending.set(id, { resolve, reject });
481
+ w.postMessage({ type: "transcribe", id, want, samples }, [samples.buffer]);
482
+ });
483
+ }
484
+ function isWhisperLoaded() {
485
+ return getDictationLoad().done;
486
+ }
487
+ function resetWhisperWorker() {
488
+ if (!worker) return;
489
+ const err = new Error("whisper worker reset");
490
+ pending.forEach((p) => p.reject(err));
491
+ pending.clear();
492
+ worker.terminate();
493
+ worker = null;
494
+ setDictationLoad({ active: false, progress: 0, done: false });
495
+ }
496
+ function warmWhisper() {
497
+ getWorker().postMessage({ type: "warm" });
498
+ }
499
+ function warmStopGate() {
500
+ getWorker().postMessage({ type: "warmGate" });
501
+ }
502
+ function downmixToMono(audio) {
503
+ if (audio.numberOfChannels <= 1) return audio.getChannelData(0);
504
+ const n = audio.length;
505
+ const out = new Float32Array(n);
506
+ for (let ch = 0; ch < audio.numberOfChannels; ch++) {
507
+ const data = audio.getChannelData(ch);
508
+ for (let i = 0; i < n; i++) out[i] += data[i];
509
+ }
510
+ for (let i = 0; i < n; i++) out[i] /= audio.numberOfChannels;
511
+ return out;
512
+ }
513
+ function resampleTo16kMono(src, sampleRate) {
514
+ const ratio = 16e3 / sampleRate;
515
+ const n = Math.round(src.length * ratio);
516
+ const out = new Float32Array(n);
517
+ for (let i = 0; i < n; i++) {
518
+ const t = i / ratio;
519
+ const i0 = Math.floor(t);
520
+ const i1 = Math.min(i0 + 1, src.length - 1);
521
+ out[i] = src[i0] + (src[i1] - src[i0]) * (t - i0);
522
+ }
523
+ return out;
524
+ }
525
+ async function decodeTo16kMono(blob) {
526
+ const Ctx = window.AudioContext || window.webkitAudioContext;
527
+ const ctx = new Ctx();
528
+ try {
529
+ const audio = await ctx.decodeAudioData(await blob.arrayBuffer());
530
+ return resampleTo16kMono(downmixToMono(audio), audio.sampleRate);
531
+ } finally {
532
+ void ctx.close();
533
+ }
534
+ }
535
+ function encodeWav16kMono(samples) {
536
+ const sr = 16e3;
537
+ const buf = new ArrayBuffer(44 + samples.length * 2);
538
+ const view = new DataView(buf);
539
+ const str = (o2, s) => {
540
+ for (let i = 0; i < s.length; i++) view.setUint8(o2 + i, s.charCodeAt(i));
541
+ };
542
+ str(0, "RIFF");
543
+ view.setUint32(4, 36 + samples.length * 2, true);
544
+ str(8, "WAVE");
545
+ str(12, "fmt ");
546
+ view.setUint32(16, 16, true);
547
+ view.setUint16(20, 1, true);
548
+ view.setUint16(22, 1, true);
549
+ view.setUint32(24, sr, true);
550
+ view.setUint32(28, sr * 2, true);
551
+ view.setUint16(32, 2, true);
552
+ view.setUint16(34, 16, true);
553
+ str(36, "data");
554
+ view.setUint32(40, samples.length * 2, true);
555
+ let o = 44;
556
+ for (let i = 0; i < samples.length; i++) {
557
+ const s = Math.max(-1, Math.min(1, samples[i]));
558
+ view.setInt16(o, s < 0 ? s * 32768 : s * 32767, true);
559
+ o += 2;
560
+ }
561
+ return new Blob([buf], { type: "audio/wav" });
562
+ }
563
+ async function trimTrailingStopPhrase(blob, phraseHintSec = 0) {
564
+ let samples;
565
+ try {
566
+ samples = await decodeTo16kMono(blob);
567
+ } catch {
568
+ return blob;
569
+ }
570
+ const SR = 16e3;
571
+ const n = samples.length;
572
+ if (n < SR * 0.8) return blob;
573
+ const fr = Math.round(SR * 0.03);
574
+ const nf = Math.ceil(n / fr);
575
+ const e = new Float32Array(nf);
576
+ let peak = 0;
577
+ for (let f = 0; f < nf; f++) {
578
+ const a = f * fr, b = Math.min(n, a + fr);
579
+ let s = 0;
580
+ for (let i = a; i < b; i++) s += samples[i] * samples[i];
581
+ e[f] = Math.sqrt(s / (b - a));
582
+ if (e[f] > peak) peak = e[f];
583
+ }
584
+ const sil = Math.max(8e-3, peak * 0.15);
585
+ const minGap = Math.max(1, Math.round(0.15 * SR / fr));
586
+ const maxTrimFrames = Math.round(2.2 * SR / fr);
587
+ const floor = Math.max(0, nf - maxTrimFrames);
588
+ let cutFrame;
589
+ if (phraseHintSec > 0.2) {
590
+ const anchor = Math.max(0, nf - Math.round(phraseHintSec * SR / fr));
591
+ const win = Math.round(0.35 * SR / fr);
592
+ let best = -1, bestDist = Infinity;
593
+ for (let f = Math.max(0, anchor - win); f <= Math.min(nf - 1, anchor + win); f++) {
594
+ if (e[f] < sil) {
595
+ const dist = Math.abs(f - anchor);
596
+ if (dist < bestDist) {
597
+ bestDist = dist;
598
+ best = f;
599
+ }
600
+ }
601
+ }
602
+ cutFrame = best >= 0 ? best : anchor;
603
+ } else {
604
+ let k = nf - 1;
605
+ while (k >= floor && e[k] < sil) k--;
606
+ cutFrame = -1;
607
+ while (k >= floor) {
608
+ if (e[k] < sil) {
609
+ let m = k;
610
+ while (m >= floor && e[m] < sil) m--;
611
+ if (k - m >= minGap) {
612
+ cutFrame = k + 1;
613
+ break;
614
+ }
615
+ k = m;
616
+ } else k--;
617
+ }
618
+ if (cutFrame < 0) cutFrame = Math.max(0, nf - Math.round(1.1 * SR / fr));
619
+ }
620
+ cutFrame = Math.max(cutFrame, floor);
621
+ const cutSample = Math.min(n, cutFrame * fr);
622
+ if (cutSample < SR * 0.2) return blob;
623
+ return encodeWav16kMono(samples.subarray(0, cutSample));
624
+ }
625
+ async function transcribeBlob(blob, trimEndSeconds = 0) {
626
+ let samples = await decodeTo16kMono(blob);
627
+ if (trimEndSeconds > 0) {
628
+ const cut = Math.round(trimEndSeconds * 16e3);
629
+ if (samples.length > cut + 16e3)
630
+ samples = samples.slice(0, samples.length - cut);
631
+ }
632
+ const out = await callWorker("text", samples);
633
+ return (out.text ?? "").trim();
634
+ }
635
+ async function transcribeSamples(samples, sampleRate) {
636
+ const out = await callWorker("text", resampleTo16kMono(samples, sampleRate));
637
+ return (out.text ?? "").trim();
638
+ }
639
+ function chunksToSegments(chunks) {
640
+ return (chunks ?? []).map((c) => ({
641
+ start: c.timestamp?.[0] ?? 0,
642
+ end: c.timestamp?.[1] ?? c.timestamp?.[0] ?? 0,
643
+ text: (c.text ?? "").trim()
644
+ })).filter((s) => s.text);
645
+ }
646
+ async function transcribeSegments(blob) {
647
+ const samples = await decodeTo16kMono(blob);
648
+ const out = await callWorker("segments", samples);
649
+ return chunksToSegments(out.chunks);
650
+ }
651
+ async function transcribeWords(blob) {
652
+ return transcribeWordsFromSamples(await decodeTo16kMono(blob));
653
+ }
654
+ async function transcribeWordsFromSamples(samples) {
655
+ const out = await callWorker("words", samples);
656
+ return chunksToSegments(out.chunks);
657
+ }
658
+ async function transcribeSegmentsFromSamples(samples) {
659
+ const out = await callWorker("segments", samples);
660
+ return chunksToSegments(out.chunks);
661
+ }
662
+ function serverAsrModel() {
663
+ try {
664
+ return JSON.parse(localStorage.getItem("ozwellConfig") || "{}").serverWhisper || "whisper-1";
665
+ } catch {
666
+ return "whisper-1";
667
+ }
668
+ }
669
+ async function transcribeServer(blob) {
670
+ const cfg = getOzwellConfig();
671
+ const form = new FormData();
672
+ form.append("file", blob, "audio.webm");
673
+ form.append("model", serverAsrModel());
674
+ const url = `${cfg.baseURL.replace(/\/$/, "")}/v1/audio/transcriptions`;
675
+ const headers = {};
676
+ if (cfg.apiKey && cfg.apiKey !== "ollama")
677
+ headers.Authorization = `Bearer ${cfg.apiKey}`;
678
+ const res = await fetch(url, { method: "POST", headers, body: form });
679
+ if (!res.ok) {
680
+ const body = await res.text().catch(() => "");
681
+ throw new Error(
682
+ `Server ASR ${res.status}: ${res.statusText || body.slice(0, 200) || "request failed"}`
683
+ );
684
+ }
685
+ const data = await res.json();
686
+ return (typeof data?.text === "string" ? data.text : "").trim();
687
+ }
688
+ async function transcribeGate(samples, sampleRate) {
689
+ const out = await callWorker("gate", resampleTo16kMono(samples, sampleRate));
690
+ return (out.text ?? "").trim();
691
+ }
692
+ function stripStopPhrase(text) {
693
+ const tail = /(?:\b(?:oz\s{0,4}well|all(?:['’]?s|\s{1,4}was)?\s{0,4}well|as\s{0,4}well|also|oswald)\b[\s,]{0,6}i(?:['’]?m|\s{1,4}am)\s{1,4}done\b|\b(?:oz\s{0,4}well|all(?:['’]?s|\s{1,4}was)?\s{0,4}well|oswald)\b|\bi(?:['’]?m|\s{1,4}am)\s{1,4}done\b|\b(?:that\s{1,4}was\s{1,4}|was\s{1,4})?well\s{1,4}done\b|\bthat['’]?s?\s{1,4}(?:was\s{1,4})?all\b|\bthank(?:s|\s{1,4}you)(?:\s{1,4}for\s{1,4}watching)?\b|\bbye\b)[\s.,!?-]{0,24}$/i;
694
+ let prev = null;
695
+ let t = text;
696
+ while (t !== prev && t) {
697
+ prev = t;
698
+ t = trimTrailingPunct(t.replace(tail, ""));
699
+ }
700
+ return t.trim();
701
+ }
702
+ function trimTrailingPunct(s) {
703
+ let end = s.length;
704
+ while (end > 0 && /[\s.,!?-]/.test(s[end - 1])) end--;
705
+ return end === s.length ? s : s.slice(0, end);
706
+ }
707
+ function endsWithDone(text) {
708
+ return /\b(?:i(?:['’]?m|\s{1,4}am)\s{1,4}|all\s{1,4}|well\s{1,4})?done\b[\s.,!?-]{0,24}$/i.test(
709
+ text
710
+ );
711
+ }
712
+
713
+ export { askOzwell, askOzwellStream, decodeTo16kMono, endsWithDone, getDictationLoad, getOzwellConfig, isOzwellConfigured, isWhisperLoaded, registerModelServiceWorker, resetWhisperWorker, stripStopPhrase, subscribeDictationLoad, toOzwellMessages, transcribeBlob, transcribeGate, transcribeSamples, transcribeSegments, transcribeSegmentsFromSamples, transcribeServer, transcribeWords, transcribeWordsFromSamples, trimTrailingStopPhrase, warmStopGate, warmWhisper };
714
+ //# sourceMappingURL=chunk-IZY4CMOO.js.map
715
+ //# sourceMappingURL=chunk-IZY4CMOO.js.map