@dxos/plugin-transformer 0.10.0 → 0.11.0
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.
- package/dist/lib/TransformerPlugin.mjs +16 -0
- package/dist/lib/TransformerPlugin.mjs.map +1 -0
- package/dist/lib/{neutral/chunk-2UJUBMOA.mjs → chunk-meta.mjs} +16 -25
- package/dist/lib/chunk-meta.mjs.map +1 -0
- package/dist/lib/components.mjs +171 -0
- package/dist/lib/components.mjs.map +1 -0
- package/dist/lib/hooks.mjs +349 -0
- package/dist/lib/hooks.mjs.map +1 -0
- package/dist/lib/index.mjs +2 -0
- package/dist/lib/meta.mjs +2 -0
- package/dist/lib/plugin.mjs +8 -0
- package/dist/lib/plugin.mjs.map +1 -0
- package/dist/lib/translations.mjs +7 -0
- package/dist/lib/translations.mjs.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +24 -24
- package/dist/lib/neutral/TransformerPlugin.mjs +0 -38
- package/dist/lib/neutral/TransformerPlugin.mjs.map +0 -7
- package/dist/lib/neutral/chunk-2UJUBMOA.mjs.map +0 -7
- package/dist/lib/neutral/components/index.mjs +0 -136
- package/dist/lib/neutral/components/index.mjs.map +0 -7
- package/dist/lib/neutral/hooks/index.mjs +0 -339
- package/dist/lib/neutral/hooks/index.mjs.map +0 -7
- package/dist/lib/neutral/index.mjs +0 -7
- package/dist/lib/neutral/index.mjs.map +0 -7
- package/dist/lib/neutral/meta.json +0 -1
- package/dist/lib/neutral/meta.mjs +0 -7
- package/dist/lib/neutral/meta.mjs.map +0 -7
- package/dist/lib/neutral/plugin.mjs +0 -11
- package/dist/lib/neutral/plugin.mjs.map +0 -7
- package/dist/lib/neutral/translations.mjs +0 -15
- package/dist/lib/neutral/translations.mjs.map +0 -7
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Plugin } from "@dxos/app-framework";
|
|
2
|
+
import { AppPlugin } from "@dxos/app-toolkit";
|
|
3
|
+
import { meta } from "#meta";
|
|
4
|
+
import { translations } from "#translations";
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/TransformerPlugin.tsx
|
|
7
|
+
var TransformerPlugin = Plugin.define(meta).pipe(AppPlugin.addSchemaModule({ schema: [] }), AppPlugin.addTranslationsModule({ translations }), AppPlugin.addPluginAssetModule({ asset: {
|
|
8
|
+
pluginId: meta.profile.key,
|
|
9
|
+
path: "PLUGIN.mdl",
|
|
10
|
+
content: "---\nid: org.dxos.plugin.transformer\nname: TransformerPlugin\nversion: 0.1.0\n---\n\nA browser-based machine learning plugin for DXOS Composer that runs Hugging Face Transformers.js\nmodels entirely in-browser via WebAssembly and WebGPU. It provides automatic speech recognition\n(Whisper) through a React hook and component layer, enabling real-time voice transcription without\nany server-side inference infrastructure.\n\n## Extensions\n\nThe following extension dialects are used in this document.\nEach extension is defined in the Appendix or resolved via its URI.\n\n| Term | URI |\n|-------------|--------------------------------|\n| `type` | `org.dxos.mdl.type@1.0` |\n| `feat` | `org.dxos.mdl.feat@1.0` |\n| `test` | `org.dxos.mdl.test@1.0` |\n| `component` | `org.dxos.mdl.component@1.0` |\n| `op` | `org.dxos.mdl.op@1.0` |\n\n## Types\n\n```mdl\ntype PipelineConfig\n fields:\n model: string # Hugging Face model id, e.g. 'Xenova/whisper-base'\n active?: boolean # whether to load and run the pipeline\n debug?: boolean # enable verbose logging\n```\n\n```mdl\ntype PipelineState\n fields:\n gpuInfo: string # WebGPU adapter description, or fallback message\n isLoaded: boolean # true once the model is fully initialised\n isLoading: boolean # true while the model is being downloaded/compiled\n error: string | null # error message if loading failed\n```\n\n```mdl\ntype AudioStreamConfig\n fields:\n active?: boolean # start/stop microphone capture\n debug?: boolean\n onAudioData?(audioData: Float32Array): Promise<void>\n```\n\n```mdl\ntype AudioStreamState\n fields:\n stream: MediaStream | null # live microphone stream, or null when inactive\n error: string | null # error from getUserMedia or audio processing\n audioLevel: number # 0-255 RMS level for visualisation\n```\n\n```mdl\ntype TranscriptionOptions\n fields:\n sampling_rate: number # audio sample rate in Hz (16000)\n chunk_length_s: number # seconds of audio per chunk\n stride_length_s: number # overlap between adjacent chunks\n return_timestamps: boolean # include word-level timestamps in output\n language: string # target language hint, e.g. 'english'\n```\n\n```mdl\ntype EmbeddingOutput\n fields:\n data: number[] # embedding vector as a flat float array\n```\n\n## Components\n\n```mdl\ncomponent Voice\n desc: |\n Composite component that wires usePipeline and useAudioStream together to provide\n live Whisper transcription from the microphone. Accumulates the running transcript\n in local state and renders a DebugInfo panel showing model status, audio level, and\n the current transcription text.\n props:\n active?: boolean # start/stop the entire pipeline\n debug?: boolean\n model?: string # defaults to 'Xenova/whisper-base'\n state:\n isTranscribing: boolean # true while a transcription call is in-flight\n transcription: string # accumulated transcript text\n layout: |\n ┌──────────────────────────────────────┐\n │ [DebugInfo panel] │\n │ model: Xenova/whisper-base │\n │ gpu: GPU Available │\n │ stream: active / inactive │\n │ level: ███░░░░ (audioLevel bar) │\n │ ────────────────────────────── │\n │ [transcription text] │\n └──────────────────────────────────────┘\n```\n\n## Operations\n\n```mdl\nop LoadModel\n desc: |\n Loads a Transformers.js automatic-speech-recognition pipeline for the given model id.\n Configures ONNX backend to use WebGPU if available, falling back to WASM/CPU.\n Invoked automatically when the Voice component mounts with active = true.\n input: void\n output: void\n effects: [http, fs]\n note: Model weights are cached in ./.cache by the Transformers.js env settings.\n```\n\n```mdl\nop Transcribe\n desc: |\n Runs the loaded ASR pipeline against a Float32Array of 16 kHz mono audio.\n Returns the transcribed text string from the pipeline result.\n input: void\n output: string\n effects: [gpu]\n note: Guarded by isTranscribing flag to prevent concurrent calls.\n```\n\n```mdl\nop CaptureAudio\n desc: |\n Requests microphone permission via getUserMedia and wires an AudioWorklet that\n accumulates 2-second chunks (32000 samples at 16 kHz) before forwarding them to\n the onAudioData callback.\n input: void\n output: void\n effects: [audio]\n note: Cleaned up automatically when the component unmounts or active becomes false.\n```\n\n## Features\n\n```mdl\nfeat F-1: In-Browser ASR Pipeline\n\n req F-1.1:\n when: Voice component mounts with active = true\n then: usePipeline loads the Whisper model via Transformers.js; isLoading is true until complete\n\n req F-1.2:\n when: WebGPU is available in the browser\n then: the ONNX backend is configured for WebGPU execution and gpuInfo reflects the adapter\n\n req F-1.3:\n when: WebGPU is not available\n then: the pipeline falls back to WASM/CPU and gpuInfo is set to a 'not supported' message\n\n req F-1.4:\n when: model loading fails\n then: PipelineState.error contains a human-readable message; isLoading is false\n```\n\n```mdl\nfeat F-2: Microphone Capture\n\n req F-2.1:\n when: useAudioStream is activated\n then: getUserMedia is called with mono 16 kHz audio and echo/noise cancellation enabled\n\n req F-2.2:\n when: audio is captured\n then: an AudioWorklet accumulates samples and emits 2-second chunks via the onAudioData callback\n\n req F-2.3:\n when: active is set to false or the component unmounts\n then: all MediaStream tracks are stopped, AudioContext is closed, and AnimationFrame is cancelled\n\n req F-2.4:\n when: getUserMedia is denied\n then: AudioStreamState.error is set with the underlying error message\n```\n\n```mdl\nfeat F-3: Live Transcription\n\n req F-3.1:\n when: a 2-second audio chunk arrives and the model is loaded\n then: usePipeline.transcribe is called with 16 kHz mono options and the result appended to the transcript\n\n req F-3.2:\n when: transcription is already in progress (isTranscribing = true)\n then: the incoming audio chunk is dropped to avoid concurrent inference\n\n req F-3.3:\n when: transcription returns an empty or whitespace-only string\n then: the transcript state is not updated\n```\n\n```mdl\nfeat F-4: RAG Embedding Pipeline (Testing)\n\n req F-4.1:\n when: RagPipeline.generateCompletions is called with an input and a knowledge base\n then: embeddings are generated for both the input and each knowledge-base entry\n\n req F-4.2:\n when: embeddings are available\n then: cosine similarity is computed and the top-3 most similar contexts are selected\n```\n\n## Acceptance\n\n```mdl\ntest T-1: Model loads and transitions isLoaded\n given: Voice component mounts with active = true and model = 'Xenova/whisper-base'\n when: model download and ONNX compilation complete\n then:\n - isLoading transitions from true to false\n - isLoaded is true\n - error is null\n```\n\n```mdl\ntest T-2: Model load failure sets error state\n given: the model download throws a network error\n when: usePipeline attempts to load the model\n then:\n - isLoading is false\n - error contains the error message string\n - isLoaded is false\n```\n\n```mdl\ntest T-3: Microphone capture populates stream state\n given: getUserMedia is granted\n when: useAudioStream activates\n then:\n - AudioStreamState.stream is a non-null MediaStream\n - AudioStreamState.error is null\n```\n\n```mdl\ntest T-4: Audio chunk triggers transcription\n given: model is loaded and stream is active\n when: AudioWorklet posts a 32000-sample chunk\n then:\n - isTranscribing becomes true during the pipeline call\n - transcription string is updated with the returned text\n - isTranscribing returns to false after completion\n```\n\n```mdl\ntest T-5: Concurrent transcription calls are dropped\n given: isTranscribing is true\n when: a second audio chunk arrives\n then: the chunk is discarded and no second pipeline call is made\n```\n\n---\n\n## Appendix: Extension Definitions\n\nExtension block types used in this document are defined below using\nthe core `ext` primitive — the only construct the base language provides.\n\n```mdl\next type\n uri: org.dxos.mdl.type@1.0\n desc: A named data structure with typed fields and optional literals.\n fields:\n desc?: Prose\n fields?: FieldMap # name[?]: TypeExpr (# inline comment)\n literals?: UnionList # a | b | c\n extends?: TypeRef[]\n```\n\n```mdl\next feat\n uri: org.dxos.mdl.feat@1.0\n desc: A named feature grouping one or more requirements.\n fields:\n desc?: Prose\n req: RequirementList\n nesting: self # feat blocks may contain feat blocks\n```\n\n```mdl\next test\n uri: org.dxos.mdl.test@1.0\n desc: An acceptance scenario expressed as given / when / then steps.\n fields:\n given?: Step | Step[]\n when?: Step | Step[]\n then: Step | Step[]\n tags?: TagList\n```\n\n```mdl\next component\n uri: org.dxos.mdl.component@1.0\n desc: A UI component with props, internal state, slots, actions, and events.\n fields:\n desc?: Prose\n props?: FieldMap # external inputs (immutable inside component)\n state?: FieldMap # internal reactive state\n slots?: FieldMap # named ReactNode injection points\n actions?: ActionMap # methods the component exposes or handles\n emits?: EventMap # events the component raises to its parent\n layout?: CodeBlock # ASCII sketch of visual structure (non-normative)\n```\n\n```mdl\next op\n uri: org.dxos.mdl.op@1.0\n desc: |\n A named operation with typed inputs, outputs, and declared errors.\n Pure ops have no effects or requires. Effectful ops declare both.\n fields:\n desc?: Prose\n input?: FieldMap # named input parameters\n output?: TypeExpr # return type\n errors?: ErrorMap # name: Prose (when this error occurs)\n effects?: EffectList # echo:read | echo:write | http | fs | ...\n requires?: ServiceList # injected service dependencies\n note?: Prose # implementation guidance (non-normative)\n```\n",
|
|
11
|
+
mimeType: "application/x-mdl"
|
|
12
|
+
} }), Plugin.make);
|
|
13
|
+
//#endregion
|
|
14
|
+
export { TransformerPlugin, TransformerPlugin as default };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=TransformerPlugin.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TransformerPlugin.mjs","names":[],"sources":["../../src/TransformerPlugin.tsx"],"sourcesContent":["//\n// Copyright 2024 DXOS.org\n//\n\nimport { Plugin } from '@dxos/app-framework';\nimport { AppPlugin } from '@dxos/app-toolkit';\n\n// import { IntentResolver } from './capabilities';\nimport { meta } from '#meta';\nimport { translations } from '#translations';\n\n// eslint-disable-next-line import/no-relative-packages\nimport pluginSpec from '../PLUGIN.mdl?raw';\n\nexport const TransformerPlugin = Plugin.define(meta).pipe(\n AppPlugin.addSchemaModule({ schema: [] }),\n AppPlugin.addTranslationsModule({ translations }),\n // Plugin.addModule({\n // id: 'intent-resolver',\n // activatesOn: Events.SetupIntentResolver,\n // activate: IntentResolver,\n // }),\n AppPlugin.addPluginAssetModule({\n asset: { pluginId: meta.profile.key, path: 'PLUGIN.mdl', content: pluginSpec, mimeType: 'application/x-mdl' },\n }),\n Plugin.make,\n);\n\nexport default TransformerPlugin;\n"],"mappings":";;;;;;AAcA,IAAa,oBAAoB,OAAO,OAAO,IAAI,CAAC,CAAC,KACnD,UAAU,gBAAgB,EAAE,QAAQ,CAAC,EAAE,CAAC,GACxC,UAAU,sBAAsB,EAAE,aAAa,CAAC,GAMhD,UAAU,qBAAqB,EAC7B,OAAO;CAAE,UAAU,KAAK,QAAQ;CAAK,MAAM;CAAc,SAAS;CAAY,UAAU;AAAoB,EAC9G,CAAC,GACD,OAAO,IACT"}
|
|
@@ -1,15 +1,12 @@
|
|
|
1
|
-
// src/meta.ts
|
|
2
1
|
import { Plugin } from "@dxos/app-framework";
|
|
3
|
-
|
|
4
|
-
// dx.config.ts
|
|
5
2
|
import { Config2 } from "@dxos/app-framework/config";
|
|
6
3
|
import { trim } from "@dxos/util";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
4
|
+
//#region dx.config.ts
|
|
5
|
+
var dx_config_default = Config2.make({ plugin: {
|
|
6
|
+
key: "org.dxos.plugin.transformer",
|
|
7
|
+
name: "Transformer",
|
|
8
|
+
author: "DXOS",
|
|
9
|
+
description: trim`
|
|
13
10
|
Browser-based machine learning plugin that runs Hugging Face Transformers.js models
|
|
14
11
|
entirely in-browser via WebAssembly and WebGPU — no server-side inference required.
|
|
15
12
|
|
|
@@ -25,21 +22,15 @@ var dx_config_default = Config2.make({
|
|
|
25
22
|
experiments, with cosine similarity ranking for selecting the most relevant
|
|
26
23
|
knowledge-base contexts before text generation.
|
|
27
24
|
`,
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
]
|
|
36
|
-
}
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
// src/meta.ts
|
|
25
|
+
source: "https://github.com/dxos/dxos/tree/main/packages/plugins/plugin-transformer",
|
|
26
|
+
icon: { key: "ph--cpu--regular" },
|
|
27
|
+
spec: "PLUGIN.mdl",
|
|
28
|
+
tags: ["labs"]
|
|
29
|
+
} });
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/meta.ts
|
|
40
32
|
var meta = Plugin.getMetaFromConfig(dx_config_default);
|
|
33
|
+
//#endregion
|
|
34
|
+
export { meta as t };
|
|
41
35
|
|
|
42
|
-
|
|
43
|
-
meta
|
|
44
|
-
};
|
|
45
|
-
//# sourceMappingURL=chunk-2UJUBMOA.mjs.map
|
|
36
|
+
//# sourceMappingURL=chunk-meta.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chunk-meta.mjs","names":[],"sources":["../../dx.config.ts","../../src/meta.ts"],"sourcesContent":["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Config2 } from '@dxos/app-framework/config';\nimport { trim } from '@dxos/util';\n\nexport default Config2.make({\n plugin: {\n key: 'org.dxos.plugin.transformer',\n name: 'Transformer',\n author: 'DXOS',\n description: trim`\n Browser-based machine learning plugin that runs Hugging Face Transformers.js models\n entirely in-browser via WebAssembly and WebGPU — no server-side inference required.\n\n Provides automatic speech recognition through a Whisper pipeline hook (usePipeline)\n and a microphone capture hook (useAudioStream) that buffers 16 kHz mono audio into\n 2-second chunks before forwarding them to the model.\n\n Exposes a Voice component that wires the two hooks together to deliver live\n transcription, accumulating the running transcript in local state and rendering\n a debug panel with model status, GPU info, and audio level visualisation.\n\n Includes a RAG embedding pipeline base class for retrieval-augmented generation\n experiments, with cosine similarity ranking for selecting the most relevant\n knowledge-base contexts before text generation.\n `,\n source: 'https://github.com/dxos/dxos/tree/main/packages/plugins/plugin-transformer',\n icon: { key: 'ph--cpu--regular' },\n spec: 'PLUGIN.mdl',\n tags: ['labs'],\n },\n});\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { Plugin } from '@dxos/app-framework';\n\nimport config from '../dx.config';\n\nexport const meta = Plugin.getMetaFromConfig(config);\n"],"mappings":";;;;AAOA,IAAA,oBAAe,QAAQ,KAAK,EAC1B,QAAQ;CACN,KAAK;CACL,MAAM;CACN,QAAQ;CACR,aAAa,IAAI;;;;;;;;;;;;;;;;CAgBjB,QAAQ;CACR,MAAM,EAAE,KAAK,mBAAmB;CAChC,MAAM;CACN,MAAM,CAAC,MAAM;AACf,EACF,CAAC;;;ACzBD,IAAa,OAAO,OAAO,kBAAkB,iBAAM"}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState } from "react";
|
|
2
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { log } from "@dxos/log";
|
|
4
|
+
import { useAudioStream, usePipeline } from "#hooks";
|
|
5
|
+
//#region src/components/Voice/DebugInfo.tsx
|
|
6
|
+
var DebugInfo = ({ error, isModelLoading, stream, isTranscribing, transcription, audioLevel, gpuInfo, model, debug = false }) => {
|
|
7
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
8
|
+
className: "p-4",
|
|
9
|
+
children: [
|
|
10
|
+
error && /* @__PURE__ */ jsxs("div", {
|
|
11
|
+
className: "mb-4 text-red-600",
|
|
12
|
+
children: [
|
|
13
|
+
/* @__PURE__ */ jsx("strong", { children: "Error:" }),
|
|
14
|
+
" ",
|
|
15
|
+
error
|
|
16
|
+
]
|
|
17
|
+
}),
|
|
18
|
+
isModelLoading && /* @__PURE__ */ jsxs("div", {
|
|
19
|
+
className: "mb-4",
|
|
20
|
+
children: [/* @__PURE__ */ jsx("div", { children: "Loading model..." }), /* @__PURE__ */ jsx("div", {
|
|
21
|
+
className: "text-sm text-gray-500",
|
|
22
|
+
children: "This may take a few moments"
|
|
23
|
+
})]
|
|
24
|
+
}),
|
|
25
|
+
stream ? /* @__PURE__ */ jsxs("div", { children: [
|
|
26
|
+
/* @__PURE__ */ jsxs("div", {
|
|
27
|
+
className: "mb-2 text-green-600",
|
|
28
|
+
children: [
|
|
29
|
+
/* @__PURE__ */ jsx("strong", { children: "Status:" }),
|
|
30
|
+
" Microphone is active",
|
|
31
|
+
debug && audioLevel && /* @__PURE__ */ jsx("div", {
|
|
32
|
+
className: "mt-2 w-48 h-5 bg-gray-200 rounded-sm relative",
|
|
33
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
34
|
+
className: "h-full bg-green-500 transition-all duration-100 rounded-sm",
|
|
35
|
+
style: { width: `${audioLevel / 255 * 100}%` }
|
|
36
|
+
})
|
|
37
|
+
})
|
|
38
|
+
]
|
|
39
|
+
}),
|
|
40
|
+
isTranscribing && /* @__PURE__ */ jsx("div", {
|
|
41
|
+
className: "mb-2 text-gray-500",
|
|
42
|
+
children: "Processing audio..."
|
|
43
|
+
}),
|
|
44
|
+
debug && /* @__PURE__ */ jsxs("div", {
|
|
45
|
+
className: "mb-4 text-sm text-gray-500 space-y-1",
|
|
46
|
+
children: [
|
|
47
|
+
/* @__PURE__ */ jsxs("div", { children: ["Model: ", model] }),
|
|
48
|
+
/* @__PURE__ */ jsx("div", { children: "Sample Rate: 16000 Hz" }),
|
|
49
|
+
/* @__PURE__ */ jsx("div", { children: "Format: audio/wav" }),
|
|
50
|
+
/* @__PURE__ */ jsx("div", { children: "Chunk Size: 10 seconds" }),
|
|
51
|
+
/* @__PURE__ */ jsxs("div", { children: ["GPU: ", gpuInfo || "Not available"] }),
|
|
52
|
+
/* @__PURE__ */ jsx("div", { children: "Backend: WebGPU" })
|
|
53
|
+
]
|
|
54
|
+
}),
|
|
55
|
+
transcription && /* @__PURE__ */ jsxs("div", {
|
|
56
|
+
className: "mt-4",
|
|
57
|
+
children: [/* @__PURE__ */ jsx("strong", { children: "Transcription:" }), /* @__PURE__ */ jsx("p", {
|
|
58
|
+
className: "mt-2 p-4 bg-gray-100 rounded-sm whitespace-pre-wrap",
|
|
59
|
+
children: transcription
|
|
60
|
+
})]
|
|
61
|
+
})
|
|
62
|
+
] }) : /* @__PURE__ */ jsx("div", { children: !isModelLoading && !error && /* @__PURE__ */ jsx("div", {
|
|
63
|
+
className: "text-gray-500",
|
|
64
|
+
children: "Microphone is inactive"
|
|
65
|
+
}) })
|
|
66
|
+
]
|
|
67
|
+
});
|
|
68
|
+
};
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/components/Voice/Voice.tsx
|
|
71
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/plugins/plugin-transformer/src/components/Voice/Voice.tsx";
|
|
72
|
+
var Voice = ({ active, debug, model = "Xenova/whisper-base" }) => {
|
|
73
|
+
const [isTranscribing, setIsTranscribing] = useState(false);
|
|
74
|
+
const [transcription, setTranscription] = useState("");
|
|
75
|
+
const { transcribe, gpuInfo, isLoaded: isModelLoaded, isLoading: isModelLoading, error: pipelineError } = usePipeline({
|
|
76
|
+
active,
|
|
77
|
+
debug,
|
|
78
|
+
model
|
|
79
|
+
});
|
|
80
|
+
const { stream, error: audioError, audioLevel } = useAudioStream({
|
|
81
|
+
active,
|
|
82
|
+
debug
|
|
83
|
+
});
|
|
84
|
+
const handleAudioData = useCallback(async (audioData) => {
|
|
85
|
+
if (!isModelLoaded) return;
|
|
86
|
+
if (isTranscribing) return;
|
|
87
|
+
setIsTranscribing(true);
|
|
88
|
+
try {
|
|
89
|
+
const result = await transcribe(audioData, {
|
|
90
|
+
sampling_rate: 16e3,
|
|
91
|
+
chunk_length_s: 5,
|
|
92
|
+
stride_length_s: 1,
|
|
93
|
+
return_timestamps: false,
|
|
94
|
+
language: "english"
|
|
95
|
+
});
|
|
96
|
+
if (result?.text?.trim()) setTranscription((prev) => prev + " " + result.text);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
log.error("transcription error", { err }, {
|
|
99
|
+
"~LogMeta": "~LogMeta",
|
|
100
|
+
F: __dxlog_file,
|
|
101
|
+
L: 65,
|
|
102
|
+
S: void 0
|
|
103
|
+
});
|
|
104
|
+
throw err;
|
|
105
|
+
} finally {
|
|
106
|
+
setIsTranscribing(false);
|
|
107
|
+
}
|
|
108
|
+
}, [transcribe, isTranscribing]);
|
|
109
|
+
log.info("handleAudioData", { handleAudioData }, {
|
|
110
|
+
"~LogMeta": "~LogMeta",
|
|
111
|
+
F: __dxlog_file,
|
|
112
|
+
L: 73,
|
|
113
|
+
S: void 0
|
|
114
|
+
});
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
if (debug) log.info("audio state", {
|
|
117
|
+
hasStream: !!stream,
|
|
118
|
+
audioError,
|
|
119
|
+
audioLevel,
|
|
120
|
+
shouldBeActive: active && isModelLoaded
|
|
121
|
+
}, {
|
|
122
|
+
"~LogMeta": "~LogMeta",
|
|
123
|
+
F: __dxlog_file,
|
|
124
|
+
L: 77,
|
|
125
|
+
S: void 0
|
|
126
|
+
});
|
|
127
|
+
}, [
|
|
128
|
+
debug,
|
|
129
|
+
stream,
|
|
130
|
+
audioError,
|
|
131
|
+
audioLevel,
|
|
132
|
+
active,
|
|
133
|
+
isModelLoaded
|
|
134
|
+
]);
|
|
135
|
+
useEffect(() => {
|
|
136
|
+
if (debug) log.info("transcription state", {
|
|
137
|
+
active,
|
|
138
|
+
isModelLoaded,
|
|
139
|
+
isModelLoading,
|
|
140
|
+
isTranscribing,
|
|
141
|
+
pipelineError
|
|
142
|
+
}, {
|
|
143
|
+
"~LogMeta": "~LogMeta",
|
|
144
|
+
F: __dxlog_file,
|
|
145
|
+
L: 88,
|
|
146
|
+
S: void 0
|
|
147
|
+
});
|
|
148
|
+
}, [
|
|
149
|
+
active,
|
|
150
|
+
debug,
|
|
151
|
+
isModelLoaded,
|
|
152
|
+
isModelLoading,
|
|
153
|
+
pipelineError,
|
|
154
|
+
isTranscribing
|
|
155
|
+
]);
|
|
156
|
+
return /* @__PURE__ */ jsx(DebugInfo, {
|
|
157
|
+
error: audioError || pipelineError || void 0,
|
|
158
|
+
isModelLoading,
|
|
159
|
+
stream,
|
|
160
|
+
isTranscribing,
|
|
161
|
+
transcription,
|
|
162
|
+
audioLevel,
|
|
163
|
+
gpuInfo,
|
|
164
|
+
model,
|
|
165
|
+
debug
|
|
166
|
+
});
|
|
167
|
+
};
|
|
168
|
+
//#endregion
|
|
169
|
+
export { DebugInfo, Voice };
|
|
170
|
+
|
|
171
|
+
//# sourceMappingURL=components.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components.mjs","names":[],"sources":["../../src/components/Voice/DebugInfo.tsx","../../src/components/Voice/Voice.tsx"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\nimport React, { type FC } from 'react';\n\nexport type DebugInfoProps = {\n error: string;\n isModelLoading: boolean;\n stream: MediaStream | null;\n isTranscribing: boolean;\n transcription: string;\n audioLevel: number;\n gpuInfo: string;\n model: string;\n debug: boolean;\n};\n\nexport const DebugInfo: FC<Partial<DebugInfoProps>> = ({\n error,\n isModelLoading,\n stream,\n isTranscribing,\n transcription,\n audioLevel,\n gpuInfo,\n model,\n debug = false,\n}) => {\n return (\n <div className='p-4'>\n {error && (\n <div className='mb-4 text-red-600'>\n <strong>Error:</strong> {error}\n </div>\n )}\n {isModelLoading && (\n <div className='mb-4'>\n <div>Loading model...</div>\n <div className='text-sm text-gray-500'>This may take a few moments</div>\n </div>\n )}\n {stream ? (\n <div>\n <div className='mb-2 text-green-600'>\n <strong>Status:</strong> Microphone is active\n {debug && audioLevel && (\n <div className='mt-2 w-48 h-5 bg-gray-200 rounded-sm relative'>\n <div\n className='h-full bg-green-500 transition-all duration-100 rounded-sm'\n style={{ width: `${(audioLevel / 255) * 100}%` }}\n />\n </div>\n )}\n </div>\n {isTranscribing && <div className='mb-2 text-gray-500'>Processing audio...</div>}\n {debug && (\n <div className='mb-4 text-sm text-gray-500 space-y-1'>\n <div>Model: {model}</div>\n <div>Sample Rate: 16000 Hz</div>\n <div>Format: audio/wav</div>\n <div>Chunk Size: 10 seconds</div>\n <div>GPU: {gpuInfo || 'Not available'}</div>\n <div>Backend: WebGPU</div>\n </div>\n )}\n {transcription && (\n <div className='mt-4'>\n <strong>Transcription:</strong>\n <p className='mt-2 p-4 bg-gray-100 rounded-sm whitespace-pre-wrap'>{transcription}</p>\n </div>\n )}\n </div>\n ) : (\n <div>{!isModelLoading && !error && <div className='text-gray-500'>Microphone is inactive</div>}</div>\n )}\n </div>\n );\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport React, { useCallback, useEffect, useState } from 'react';\n\nimport { log } from '@dxos/log';\n\nimport { useAudioStream, usePipeline } from '#hooks';\n\nimport { DebugInfo } from './DebugInfo';\n\nexport type VoiceProps = {\n active?: boolean;\n debug?: boolean;\n model?: string;\n};\n\nexport const Voice = ({ active, debug, model = 'Xenova/whisper-base' }: VoiceProps) => {\n const [isTranscribing, setIsTranscribing] = useState(false);\n const [transcription, setTranscription] = useState<string>('');\n\n const {\n transcribe,\n gpuInfo,\n isLoaded: isModelLoaded,\n isLoading: isModelLoading,\n error: pipelineError,\n } = usePipeline({ active, debug, model });\n\n const {\n stream,\n error: audioError,\n audioLevel,\n } = useAudioStream({\n active,\n debug,\n // onAudioData: handleAudioData\n });\n\n const handleAudioData = useCallback(\n async (audioData: Float32Array) => {\n if (!isModelLoaded) {\n return;\n }\n\n if (isTranscribing) {\n return;\n }\n\n setIsTranscribing(true);\n try {\n const result = await transcribe(audioData, {\n sampling_rate: 16000,\n chunk_length_s: 5,\n stride_length_s: 1,\n return_timestamps: false,\n language: 'english',\n });\n\n if (result?.text?.trim()) {\n setTranscription((prev) => prev + ' ' + result.text);\n }\n } catch (err) {\n log.error('transcription error', { err });\n throw err;\n } finally {\n setIsTranscribing(false);\n }\n },\n [transcribe, isTranscribing],\n );\n log.info('handleAudioData', { handleAudioData });\n\n useEffect(() => {\n if (debug) {\n log.info('audio state', {\n hasStream: !!stream,\n audioError,\n audioLevel,\n shouldBeActive: active && isModelLoaded,\n });\n }\n }, [debug, stream, audioError, audioLevel, active, isModelLoaded]);\n\n useEffect(() => {\n if (debug) {\n log.info('transcription state', {\n active,\n isModelLoaded,\n isModelLoading,\n isTranscribing,\n pipelineError,\n });\n }\n }, [active, debug, isModelLoaded, isModelLoading, pipelineError, isTranscribing]);\n\n return (\n <DebugInfo\n error={audioError || pipelineError || undefined}\n isModelLoading={isModelLoading}\n stream={stream}\n isTranscribing={isTranscribing}\n transcription={transcription}\n audioLevel={audioLevel}\n gpuInfo={gpuInfo}\n model={model}\n debug={debug}\n />\n );\n};\n"],"mappings":"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"}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { log } from "@dxos/log";
|
|
3
|
+
import { env, pipeline } from "@xenova/transformers";
|
|
4
|
+
import { invariant } from "@dxos/invariant";
|
|
5
|
+
//#region src/hooks/useAudioStream.ts
|
|
6
|
+
var __dxlog_file$1 = "/__w/dxos/dxos/packages/plugins/plugin-transformer/src/hooks/useAudioStream.ts";
|
|
7
|
+
var useAudioStream = ({ active, debug, onAudioData }) => {
|
|
8
|
+
const [state, setState] = useState({
|
|
9
|
+
stream: null,
|
|
10
|
+
error: null,
|
|
11
|
+
audioLevel: 0
|
|
12
|
+
});
|
|
13
|
+
const audioContextRef = useRef(null);
|
|
14
|
+
const analyserRef = useRef(null);
|
|
15
|
+
const animationFrameRef = useRef(void 0);
|
|
16
|
+
const workletNodeRef = useRef(null);
|
|
17
|
+
const isProcessingRef = useRef(false);
|
|
18
|
+
const mediaStreamRef = useRef(null);
|
|
19
|
+
const audioBufferRef = useRef([]);
|
|
20
|
+
const updateAudioLevel = useCallback(() => {
|
|
21
|
+
if (analyserRef.current) {
|
|
22
|
+
const dataArray = new Uint8Array(analyserRef.current.frequencyBinCount);
|
|
23
|
+
analyserRef.current.getByteFrequencyData(dataArray);
|
|
24
|
+
const average = dataArray.reduce((acc, val) => acc + val, 0) / dataArray.length;
|
|
25
|
+
setState((prev) => ({
|
|
26
|
+
...prev,
|
|
27
|
+
audioLevel: average
|
|
28
|
+
}));
|
|
29
|
+
animationFrameRef.current = requestAnimationFrame(updateAudioLevel);
|
|
30
|
+
}
|
|
31
|
+
}, []);
|
|
32
|
+
const cleanup = useCallback(() => {
|
|
33
|
+
log("cleaning up audio resources", void 0, {
|
|
34
|
+
"~LogMeta": "~LogMeta",
|
|
35
|
+
F: __dxlog_file$1,
|
|
36
|
+
L: 49,
|
|
37
|
+
S: void 0
|
|
38
|
+
});
|
|
39
|
+
if (mediaStreamRef.current) {
|
|
40
|
+
mediaStreamRef.current.getTracks().forEach((track) => {
|
|
41
|
+
track.stop();
|
|
42
|
+
track.enabled = false;
|
|
43
|
+
});
|
|
44
|
+
mediaStreamRef.current = null;
|
|
45
|
+
}
|
|
46
|
+
if (workletNodeRef.current) {
|
|
47
|
+
workletNodeRef.current.disconnect();
|
|
48
|
+
workletNodeRef.current = null;
|
|
49
|
+
}
|
|
50
|
+
if (analyserRef.current) {
|
|
51
|
+
analyserRef.current.disconnect();
|
|
52
|
+
analyserRef.current = null;
|
|
53
|
+
}
|
|
54
|
+
if (audioContextRef.current) {
|
|
55
|
+
audioContextRef.current.close();
|
|
56
|
+
audioContextRef.current = null;
|
|
57
|
+
}
|
|
58
|
+
if (animationFrameRef.current) {
|
|
59
|
+
cancelAnimationFrame(animationFrameRef.current);
|
|
60
|
+
animationFrameRef.current = void 0;
|
|
61
|
+
}
|
|
62
|
+
audioBufferRef.current = [];
|
|
63
|
+
setState({
|
|
64
|
+
stream: null,
|
|
65
|
+
error: null,
|
|
66
|
+
audioLevel: 0
|
|
67
|
+
});
|
|
68
|
+
}, [debug]);
|
|
69
|
+
useEffect(() => {
|
|
70
|
+
let mounted = true;
|
|
71
|
+
const startStream = async () => {
|
|
72
|
+
try {
|
|
73
|
+
if (active) {
|
|
74
|
+
cleanup();
|
|
75
|
+
log.info("initializing audio stream...", void 0, {
|
|
76
|
+
"~LogMeta": "~LogMeta",
|
|
77
|
+
F: __dxlog_file$1,
|
|
78
|
+
L: 93,
|
|
79
|
+
S: void 0
|
|
80
|
+
});
|
|
81
|
+
const stream = await navigator.mediaDevices.getUserMedia({
|
|
82
|
+
audio: {
|
|
83
|
+
channelCount: 1,
|
|
84
|
+
sampleRate: 16e3,
|
|
85
|
+
echoCancellation: true,
|
|
86
|
+
noiseSuppression: true,
|
|
87
|
+
autoGainControl: true
|
|
88
|
+
},
|
|
89
|
+
video: false
|
|
90
|
+
});
|
|
91
|
+
if (!mounted || !active) {
|
|
92
|
+
stream.getTracks().forEach((track) => {
|
|
93
|
+
track.stop();
|
|
94
|
+
track.enabled = false;
|
|
95
|
+
});
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
mediaStreamRef.current = stream;
|
|
99
|
+
const context = new AudioContext({ sampleRate: 16e3 });
|
|
100
|
+
await context.audioWorklet.addModule(URL.createObjectURL(new Blob([`class AudioProcessor extends AudioWorkletProcessor {
|
|
101
|
+
constructor() {
|
|
102
|
+
super();
|
|
103
|
+
this._buffer = [];
|
|
104
|
+
this._samplesProcessed = 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
process(inputs, outputs) {
|
|
108
|
+
const input = inputs[0];
|
|
109
|
+
const channel = input[0];
|
|
110
|
+
|
|
111
|
+
if (channel) {
|
|
112
|
+
this._buffer.push(new Float32Array(channel));
|
|
113
|
+
this._samplesProcessed += channel.length;
|
|
114
|
+
|
|
115
|
+
// Process every 2 seconds (32000 samples at 16kHz).
|
|
116
|
+
if (this._samplesProcessed >= 32000) {
|
|
117
|
+
const combinedLength = this._buffer.reduce((acc, curr) => acc + curr.length, 0);
|
|
118
|
+
const combinedAudio = new Float32Array(combinedLength);
|
|
119
|
+
let offset = 0;
|
|
120
|
+
|
|
121
|
+
for (const buffer of this._buffer) {
|
|
122
|
+
combinedAudio.set(buffer, offset);
|
|
123
|
+
offset += buffer.length;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
this.port.postMessage({ type: 'audio-data', data: combinedAudio });
|
|
127
|
+
|
|
128
|
+
// Reset buffer and counter.
|
|
129
|
+
this._buffer = [];
|
|
130
|
+
this._samplesProcessed = 0;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
registerProcessor('audio-processor', AudioProcessor);`], { type: "application/javascript" })));
|
|
138
|
+
const source = context.createMediaStreamSource(stream);
|
|
139
|
+
const analyser = context.createAnalyser();
|
|
140
|
+
analyserRef.current = analyser;
|
|
141
|
+
const workletNode = new AudioWorkletNode(context, "audio-processor");
|
|
142
|
+
workletNodeRef.current = workletNode;
|
|
143
|
+
workletNode.port.onmessage = async (event) => {
|
|
144
|
+
if (!mounted || !active) return;
|
|
145
|
+
if (event.data.type === "audio-data") {
|
|
146
|
+
isProcessingRef.current = true;
|
|
147
|
+
try {
|
|
148
|
+
log("processing audio", {
|
|
149
|
+
sampleRate: context.sampleRate,
|
|
150
|
+
length: event.data.data.length,
|
|
151
|
+
min: Math.min(...event.data.data),
|
|
152
|
+
max: Math.max(...event.data.data)
|
|
153
|
+
}, {
|
|
154
|
+
"~LogMeta": "~LogMeta",
|
|
155
|
+
F: __dxlog_file$1,
|
|
156
|
+
L: 183,
|
|
157
|
+
S: void 0
|
|
158
|
+
});
|
|
159
|
+
await onAudioData?.(event.data.data);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
if (mounted) setState((prev) => ({
|
|
162
|
+
...prev,
|
|
163
|
+
error: "Error processing audio: " + err.message
|
|
164
|
+
}));
|
|
165
|
+
log.error("audio processing error", { err }, {
|
|
166
|
+
"~LogMeta": "~LogMeta",
|
|
167
|
+
F: __dxlog_file$1,
|
|
168
|
+
L: 198,
|
|
169
|
+
S: void 0
|
|
170
|
+
});
|
|
171
|
+
} finally {
|
|
172
|
+
isProcessingRef.current = false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
source.connect(analyser);
|
|
177
|
+
analyser.connect(workletNode);
|
|
178
|
+
workletNode.connect(context.destination);
|
|
179
|
+
if (debug) {
|
|
180
|
+
analyser.fftSize = 256;
|
|
181
|
+
updateAudioLevel();
|
|
182
|
+
}
|
|
183
|
+
audioContextRef.current = context;
|
|
184
|
+
if (mounted && active) setState({
|
|
185
|
+
stream,
|
|
186
|
+
error: null,
|
|
187
|
+
audioLevel: 0
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (mounted) setState((prev) => ({
|
|
192
|
+
...prev,
|
|
193
|
+
error: "Error accessing microphone: " + err.message,
|
|
194
|
+
stream: null
|
|
195
|
+
}));
|
|
196
|
+
log.error("microphone error", { err }, {
|
|
197
|
+
"~LogMeta": "~LogMeta",
|
|
198
|
+
F: __dxlog_file$1,
|
|
199
|
+
L: 232,
|
|
200
|
+
S: void 0
|
|
201
|
+
});
|
|
202
|
+
cleanup();
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
startStream();
|
|
206
|
+
return () => {
|
|
207
|
+
mounted = false;
|
|
208
|
+
cleanup();
|
|
209
|
+
};
|
|
210
|
+
}, [
|
|
211
|
+
active,
|
|
212
|
+
debug,
|
|
213
|
+
onAudioData,
|
|
214
|
+
updateAudioLevel,
|
|
215
|
+
cleanup
|
|
216
|
+
]);
|
|
217
|
+
useEffect(() => {
|
|
218
|
+
if (!active) cleanup();
|
|
219
|
+
}, [active, cleanup]);
|
|
220
|
+
return state;
|
|
221
|
+
};
|
|
222
|
+
//#endregion
|
|
223
|
+
//#region src/hooks/usePipeline.ts
|
|
224
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/plugins/plugin-transformer/src/hooks/usePipeline.ts";
|
|
225
|
+
env.cacheDir = "./.cache";
|
|
226
|
+
env.allowLocalModels = true;
|
|
227
|
+
env.backends.onnx.wasm.numThreads = 1;
|
|
228
|
+
env.backends.onnx.provider = "webgpu";
|
|
229
|
+
env.backends.onnx.webgpu = { profilingMode: true };
|
|
230
|
+
var usePipeline = ({ active, model, debug }) => {
|
|
231
|
+
const [state, setState] = useState({
|
|
232
|
+
gpuInfo: "",
|
|
233
|
+
isLoaded: false,
|
|
234
|
+
isLoading: false,
|
|
235
|
+
error: null
|
|
236
|
+
});
|
|
237
|
+
const pipelineRef = useRef(null);
|
|
238
|
+
useEffect(() => {
|
|
239
|
+
const loadModel = async () => {
|
|
240
|
+
try {
|
|
241
|
+
setState((prev) => ({
|
|
242
|
+
...prev,
|
|
243
|
+
isLoading: true,
|
|
244
|
+
error: null
|
|
245
|
+
}));
|
|
246
|
+
if (!navigator.gpu) {
|
|
247
|
+
log.warn("WebGPU is not supported, falling back to CPU", void 0, {
|
|
248
|
+
"~LogMeta": "~LogMeta",
|
|
249
|
+
F: __dxlog_file,
|
|
250
|
+
L: 62,
|
|
251
|
+
S: void 0
|
|
252
|
+
});
|
|
253
|
+
setState((prev) => ({
|
|
254
|
+
...prev,
|
|
255
|
+
gpuInfo: "WebGPU not supported (using CPU)"
|
|
256
|
+
}));
|
|
257
|
+
} else try {
|
|
258
|
+
const adapter = await navigator.gpu.requestAdapter();
|
|
259
|
+
if (!adapter) throw new Error("No GPU adapter found");
|
|
260
|
+
const adapterInfo = adapter.info;
|
|
261
|
+
if (adapterInfo) setState((prev) => ({
|
|
262
|
+
...prev,
|
|
263
|
+
gpuInfo: `${adapterInfo.description || "GPU"} (${adapterInfo.vendor || "Unknown"})`
|
|
264
|
+
}));
|
|
265
|
+
else setState((prev) => ({
|
|
266
|
+
...prev,
|
|
267
|
+
gpuInfo: "GPU Available (details unknown)"
|
|
268
|
+
}));
|
|
269
|
+
} catch (err) {
|
|
270
|
+
log.warn("WebGPU initialization failed", { err }, {
|
|
271
|
+
"~LogMeta": "~LogMeta",
|
|
272
|
+
F: __dxlog_file,
|
|
273
|
+
L: 82,
|
|
274
|
+
S: void 0
|
|
275
|
+
});
|
|
276
|
+
setState((prev) => ({
|
|
277
|
+
...prev,
|
|
278
|
+
gpuInfo: "GPU initialization failed (using CPU)"
|
|
279
|
+
}));
|
|
280
|
+
}
|
|
281
|
+
const pipe = await pipeline("automatic-speech-recognition", model, {
|
|
282
|
+
quantized: true,
|
|
283
|
+
progress_callback: (progress) => {
|
|
284
|
+
if (debug) log(`loading model: ${Math.round(progress.progress * 100)}%`, void 0, {
|
|
285
|
+
"~LogMeta": "~LogMeta",
|
|
286
|
+
F: __dxlog_file,
|
|
287
|
+
L: 91,
|
|
288
|
+
S: void 0
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
pipelineRef.current = pipe;
|
|
293
|
+
setState((prev) => ({
|
|
294
|
+
...prev,
|
|
295
|
+
isLoaded: true,
|
|
296
|
+
isLoading: false
|
|
297
|
+
}));
|
|
298
|
+
log.info("model loaded successfully", void 0, {
|
|
299
|
+
"~LogMeta": "~LogMeta",
|
|
300
|
+
F: __dxlog_file,
|
|
301
|
+
L: 98,
|
|
302
|
+
S: void 0
|
|
303
|
+
});
|
|
304
|
+
} catch (err) {
|
|
305
|
+
log.error("error loading model", { err }, {
|
|
306
|
+
"~LogMeta": "~LogMeta",
|
|
307
|
+
F: __dxlog_file,
|
|
308
|
+
L: 100,
|
|
309
|
+
S: void 0
|
|
310
|
+
});
|
|
311
|
+
setState((prev) => ({
|
|
312
|
+
...prev,
|
|
313
|
+
isLoading: false,
|
|
314
|
+
error: "error loading model: " + err.message
|
|
315
|
+
}));
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
if (active) loadModel();
|
|
319
|
+
return () => {
|
|
320
|
+
pipelineRef.current = null;
|
|
321
|
+
setState((prev) => ({
|
|
322
|
+
...prev,
|
|
323
|
+
isLoaded: false
|
|
324
|
+
}));
|
|
325
|
+
};
|
|
326
|
+
}, [
|
|
327
|
+
active,
|
|
328
|
+
debug,
|
|
329
|
+
model
|
|
330
|
+
]);
|
|
331
|
+
const transcribe = async (audioData, options) => {
|
|
332
|
+
invariant(pipelineRef.current, "pipeline not initialized", {
|
|
333
|
+
"~LogMeta": "~LogMeta",
|
|
334
|
+
F: __dxlog_file,
|
|
335
|
+
L: 120,
|
|
336
|
+
S: void 0,
|
|
337
|
+
A: ["pipelineRef.current", "'pipeline not initialized'"]
|
|
338
|
+
});
|
|
339
|
+
return await pipelineRef.current(audioData, options);
|
|
340
|
+
};
|
|
341
|
+
return {
|
|
342
|
+
...state,
|
|
343
|
+
transcribe
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
//#endregion
|
|
347
|
+
export { useAudioStream, usePipeline };
|
|
348
|
+
|
|
349
|
+
//# sourceMappingURL=hooks.mjs.map
|