Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

native.ts

452 lines16.0 KB

1// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - native inference and IPC cleanup need killable Promise boundaries outside the Effect runtime.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeSea from "node:sea";
4import type { SpeechStreamText } from "@t3tools/contracts";
5import { createSpeechAudio } from "./audio.ts";
6​
7// Inline the small child entry so the packaged CLI does not need a separate worker artifact.
8const entry = `
9const createSpeechAudio = ${createSpeechAudio.toString()};
10let speech;
11let model;
12let vadModel;
13let vad;
14let session;
15let stream;
16let audio;
17let options;
18let nativeStreaming;
19let useVad;
20let scored;
21let revision;
22let texts;
23let heardAudio;
24const warnVad = () => console.warn("Silero silence filtering unavailable; preserving raw recording and using bounded ASR chunks.");
25const resetAsr = () => {
26 if (stream) stream.reset();
27 if (session) session.dispose();
28 stream = session = undefined;
29};
30const newAudio = (filterSilence) => createSpeechAudio({
31 frameSamples: 512, filterSilence, nativeStreaming: model.capabilities.supportsStreaming,
32 longForm: model.supports("long_form"), maxAudioMs: model.capabilities.maxAudioMs,
33});
34const openAsr = async () => {
35 if (nativeStreaming) {
36 session = model.createSession();
37 stream = await session.stream(options);
38 }
39};
40const begin = async (message, live) => {
41 resetAsr();
42 options = message.options;
43 nativeStreaming = live && model.capabilities.supportsStreaming;
44 texts = [];
45 scored = revision = 0;
46 heardAudio = false;
47 useVad = Boolean(message.vadPath) && (message.filterSilence ||
48 (!model.capabilities.supportsStreaming && !model.supports("long_form")));
49 if (useVad) {
50 try {
51 if (!vadModel) {
52 vadModel = await speech.TranscribeModel.load(message.vadPath, { backend: "cpu" });
53 if (vadModel.vadInfo.sampleRate !== 16000 || vadModel.vadInfo.frameSamples !== 512)
54 throw new Error("Unsupported Silero model frames.");
55 vad = vadModel.createVadSession({ nThreads: 1 });
56 }
57 await vad.streamReset();
58 } catch {
59 vad?.dispose();
60 vadModel?.dispose();
61 vad = vadModel = undefined;
62 useVad = false;
63 warnVad();
64 }
65 }
66 audio = newAudio(useVad && message.filterSilence);
67 await openAsr();
68};
69const transcribe = async (pcm) => {
70 try {
71 const result = await model.transcribe(pcm, options);
72 texts.push(result.text);
73 } catch (error) {
74 if ((error?.constructor?.name !== "OutputTruncated" &&
75 error?.constructor?.name !== "InputTooLong") || pcm.length <= 4000) throw error;
76 const middle = Math.floor(pcm.length / 2);
77 await transcribe(pcm.subarray(0, middle));
78 await transcribe(pcm.subarray(middle));
79 }
80};
81const decode = async (final) => {
82 let preview = null;
83 for (const pcm of audio.take(final)) {
84 if (!pcm.length) continue;
85 heardAudio = true;
86 if (nativeStreaming) {
87 const update = await stream.feed(pcm);
88 if (update.committedChanged || update.tentativeChanged) {
89 const text = stream.text;
90 preview = { committed: text.committed, tentative: text.tentative };
91 }
92 } else {
93 await transcribe(pcm);
94 preview = { committed: texts.join(" ").trim(), tentative: "" };
95 }
96 }
97 return preview;
98};
99const feed = async (pcm, final = false) => {
100 if (pcm) audio.append(pcm);
101 try {
102 if (useVad) {
103 if (pcm) {
104 const result = await vad.streamFeed(pcm);
105 audio.score(result.firstFrame, result.probs);
106 if (result.firstFrame + result.probs.length !== Math.floor(audio.samples() / 512))
107 throw new Error("Incomplete Silero frames.");
108 }
109 if (final) {
110 const result = await vad.streamFlush();
111 audio.score(result.firstFrame, result.probs);
112 if (result.firstFrame + result.probs.length !== Math.ceil(audio.samples() / 512))
113 throw new Error("Incomplete Silero tail.");
114 }
115 } else {
116 const count = final ? Math.ceil(audio.samples() / 512) : Math.floor(audio.samples() / 512);
117 audio.score(scored, new Array(count - scored).fill(1));
118 scored = count;
119 }
120 } catch {
121 // Replay on optional VAD failure, including audio it had withheld; ASR errors stay separate.
122 const raw = audio.audio();
123 useVad = false;
124 warnVad();
125 resetAsr();
126 texts = [];
127 heardAudio = false;
128 audio = newAudio(false);
129 audio.append(raw);
130 scored = final ? Math.ceil(raw.length / 512) : Math.floor(raw.length / 512);
131 audio.score(0, new Array(scored).fill(1));
132 await openAsr();
133 }
134 return await decode(final);
135};
136process.on("message", async (message) => {
137 try {
138 if (message.kind === "load") {
139 speech = await loadSpeechModule(message.moduleUrl);
140 const { TranscribeModel, getAvailableBackends } = speech;
141 const device = message.acceleration.startsWith("gpu:")
142 ? getAvailableBackends().find((item) =>
143 (item.deviceType === "gpu" || item.deviceType === "igpu") &&
144 JSON.stringify([item.kind, item.deviceId ?? item.name]) === message.acceleration.slice(4))
145 : undefined;
146 if (message.acceleration.startsWith("gpu:") && !device)
147 throw new Error("The selected speech GPU is unavailable.");
148 model = await TranscribeModel.load(message.path, device ? { device } : { backend: message.acceleration });
149 process.send({ type: "t3-speech-reply", ok: true, backend: model.backend,
150 supportsStreaming: model.capabilities.supportsStreaming,
151 supportsLongForm: model.supports("long_form"),
152 supportsTranslation: model.capabilities.supportsTranslate,
153 supportsVocabulary: model.supports("vocabulary") });
154 } else if (message.kind === "begin") {
155 await begin(message, true);
156 process.send({ type: "t3-speech-reply", ok: true });
157 } else if (message.kind === "feed") {
158 const preview = await feed(message.pcm);
159 process.send({ type: "t3-speech-reply", ok: true, revision: ++revision, preview });
160 } else if (message.kind === "finish") {
161 await feed(undefined, true);
162 if (nativeStreaming && heardAudio) await stream.finalize();
163 const text = nativeStreaming ? (heardAudio ? stream.text.full : "") : texts.join(" ").trim();
164 resetAsr();
165 audio = undefined;
166 process.send({ type: "t3-speech-reply", ok: true, text });
167 } else if (message.kind === "reset") {
168 resetAsr();
169 if (vad) await vad.streamReset();
170 audio = undefined;
171 process.send({ type: "t3-speech-reply", ok: true });
172 } else if (message.kind === "transcribe") {
173 await begin(message, false);
174 await feed(message.pcm, true);
175 const text = texts.join(" ").trim();
176 audio = undefined;
177 process.send({ type: "t3-speech-reply", ok: true, text });
178 }
179 } catch (error) {
180 process.send({ type: "t3-speech-reply", ok: false,
181 error: error instanceof Error ? error.stack ?? error.message : String(error) });
182 }
183});
184process.on("disconnect", () => process.exit(0));
185`;
186​
187type Reply = {
188 readonly type: "t3-speech-reply";
189 readonly ok: boolean;
190 readonly text?: string;
191 readonly error?: string;
192 readonly supportsStreaming?: boolean;
193 readonly supportsLongForm?: boolean;
194 readonly supportsTranslation?: boolean;
195 readonly supportsVocabulary?: boolean;
196 readonly backend?: string;
197 readonly revision?: number;
198 readonly preview?: SpeechStreamText | null;
199};
200​
201// transcribe-cpp has an import-only export. Load its disk entry with require so
202// Node SEA can reach it, including its native dependencies.
203const loaderEntry = `
204 const { createRequire, findPackageJSON } = await import("node:module");
205 const { dirname, join } = await import("node:path");
206 const loadSpeechModule = async (moduleUrl) => {
207 let speech;
208 if (moduleUrl) speech = await import(moduleUrl);
209 else {
210 const packagePath = findPackageJSON("transcribe-cpp", baseUrl);
211 if (!packagePath) throw new Error("The native speech package is unavailable.");
212 speech = createRequire(packagePath)(join(dirname(packagePath), "dist/index.js"));
213 }
214 if (process.versions.electron && !process.env.TRANSCRIBE_LIBRARY) {
215 const directory = speech.artifactDir();
216 const unpacked = directory.replace(/\\.asar([\\\\/])/g, ".asar.unpacked$1");
217 // Koffi opens native libraries outside Electron's ASAR-aware filesystem.
218 if (unpacked !== directory) process.env.TRANSCRIBE_LIBRARY = join(unpacked,
219 process.platform === "win32" ? "transcribe.dll"
220 : process.platform === "darwin" ? "libtranscribe.dylib" : "libtranscribe.so");
221 }
222 return speech;
223 };
224`;
225​
226const discoveryEntry = `
227 const { getAvailableBackends } = await loadSpeechModule(moduleUrl);
228 process.send(getAvailableBackends().filter((device) =>
229 device.deviceType === "gpu" || device.deviceType === "igpu").map((device) => ({
230 id: JSON.stringify([device.kind, device.deviceId ?? device.name]),
231 name: device.description || device.name,
232 })));
233`;
234​
235export async function runNativeSpeechWorker(mode: "discover" | "model", moduleUrl?: string) {
236 if (!process.send) throw new Error("Speech workers require an IPC channel.");
237 const run = new Function(
238 "baseUrl",
239 "moduleUrl",
240 `return (async () => {${loaderEntry}${mode === "discover" ? discoveryEntry : entry}})();`,
241 ) as (baseUrl: string, moduleUrl?: string) => Promise<void>;
242 await run(import.meta.url, moduleUrl);
244​
245function speechWorkerArgs(mode: "discover" | "model", moduleUrl?: string) {
246 if (NodeSea.isSea()) return ["__speech-worker", mode, ...(moduleUrl ? [moduleUrl] : [])];
247 // Normal Node and Electron hosts can evaluate the same entry without a sibling artifact.
248 const loader = `const baseUrl = ${JSON.stringify(import.meta.url)};
249 const moduleUrl = process.argv[1];${loaderEntry}`;
250 return [
251 "--input-type=module",
252 "-e",
253 loader + (mode === "discover" ? discoveryEntry : entry),
254 ...(moduleUrl ? [moduleUrl] : []),
255 ];
257​
258export async function listNativeSpeechGpuDevices(moduleUrl?: string) {
259 const child = NodeChildProcess.spawn(process.execPath, speechWorkerArgs("discover", moduleUrl), {
260 stdio: ["ignore", "ignore", "inherit", "ipc"],
261 env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
262 });
263 return await new Promise<{ id: string; name: string }[]>((resolve, reject) => {
264 const timer = setTimeout(() => {
265 child.kill();
266 reject(new Error("Speech device discovery timed out."));
267 }, 10_000);
268 child.on("message", (devices: unknown) => {
269 if (
270 Array.isArray(devices) &&
271 devices.every(
272 (device: unknown) =>
273 typeof device === "object" &&
274 device !== null &&
275 "id" in device &&
276 typeof device.id === "string" &&
277 "name" in device &&
278 typeof device.name === "string",
279 )
280 ) {
281 clearTimeout(timer);
282 resolve(devices);
283 child.kill();
284 }
285 });
286 child.once("error", (error) => {
287 clearTimeout(timer);
288 child.kill();
289 reject(error);
290 });
291 child.once("exit", (code) => {
292 clearTimeout(timer);
293 reject(new Error(`Speech device discovery exited (${code}).`));
294 });
295 });
297​
298/** Loads a model in an isolated process. "auto" retries on the CPU when GPU setup fails. */
299export async function loadNativeSpeechModel(
300 path: string,
301 signal: AbortSignal,
302 moduleUrl?: string,
303 acceleration = "auto",
304) {
305 try {
306 return await loadNativeSpeechModelOnce(path, signal, moduleUrl, acceleration);
307 } catch (error) {
308 if (acceleration !== "auto" || signal.aborted) throw error;
309 return await loadNativeSpeechModelOnce(path, signal, moduleUrl, "cpu");
310 }
312​
313async function loadNativeSpeechModelOnce(
314 path: string,
315 signal: AbortSignal,
316 moduleUrl?: string,
317 acceleration = "auto",
318) {
319 signal.throwIfAborted();
320 const child = NodeChildProcess.spawn(process.execPath, speechWorkerArgs("model"), {
321 stdio: ["ignore", "ignore", "inherit", "ipc"],
322 serialization: "advanced",
323 env: {
324 ...process.env,
325 ELECTRON_RUN_AS_NODE: "1",
326 // Backend registration can initialize drivers even when model placement is CPU.
327 ...(acceleration === "cpu" ? { TRANSCRIBE_BACKENDS: "cpu" } : {}),
328 },
329 });
330 let stopped = false;
331 let pending: ReturnType<typeof Promise.withResolvers<Reply>> | undefined;
332 const exited = Promise.withResolvers<void>();
333 const fail = (error: Error) => {
334 stopped = true;
335 pending?.reject(error);
336 pending = undefined;
337 };
338 child.on("error", (error) => {
339 fail(error);
340 exited.resolve();
341 });
342 child.on("exit", (code, exitSignal) => {
343 fail(new Error(`Speech process exited (${exitSignal ?? code}).`));
344 signal.removeEventListener("abort", stop);
345 exited.resolve();
346 });
347 child.on("message", (message: unknown) => {
348 if (
349 typeof message !== "object" ||
350 message === null ||
351 !("type" in message) ||
352 message.type !== "t3-speech-reply"
353 )
354 return;
355 const reply = message as Reply;
356 const request = pending;
357 pending = undefined;
358 if (reply.ok) request?.resolve(reply);
359 else request?.reject(new Error(reply.error ?? "Native speech failed."));
360 });
361 function stop() {
362 fail(new Error("Speech process stopped."));
363 // Never call native dispose while inference is active. The OS owns cleanup of the isolated process.
364 child.kill("SIGKILL");
365 }
366 signal.addEventListener("abort", stop, { once: true });
367 if (signal.aborted) stop();
368 const send = (message: object) => {
369 if (stopped) return Promise.reject(new Error("Speech process stopped."));
370 if (pending) return Promise.reject(new Error("Speech process is busy."));
371 const request = Promise.withResolvers<Reply>();
372 pending = request;
373 child.send(message, (error) => {
374 if (error) {
375 request.reject(error);
376 if (pending === request) pending = undefined;
377 }
378 });
379 return request.promise;
380 };
381 const dispose = async () => {
382 stop();
383 await exited.promise;
384 };
385 let loaded: Reply;
386 try {
387 loaded = await send({ kind: "load", path, moduleUrl, acceleration });
388 } catch (error) {
389 await dispose();
390 throw error;
391 }
392 return {
393 backend: loaded.backend ?? "unknown",
394 supportsStreaming: loaded.supportsStreaming === true,
395 supportsLongForm: loaded.supportsLongForm === true,
396 supportsTranslation: loaded.supportsTranslation === true,
397 supportsVocabulary: loaded.supportsVocabulary === true,
398 begin: async (options: NativeSpeechOptions, filterSilence: boolean, vadPath?: string) => {
399 await send({ kind: "begin", options, filterSilence, vadPath });
400 },
401 feed: async (pcm: Float32Array) => {
402 const reply = await send({ kind: "feed", pcm });
403 if (typeof reply.revision !== "number" || reply.preview === undefined)
404 throw new Error("Invalid speech stream response.");
405 return { revision: reply.revision, text: reply.preview };
406 },
407 finish: async () => {
408 const reply = await send({ kind: "finish" });
409 if (typeof reply.text !== "string") throw new Error("Invalid speech stream response.");
410 return reply.text;
411 },
412 reset: async () => {
413 const inFlight = pending?.promise;
414 if (inFlight) {
415 let timeout: ReturnType<typeof setTimeout> | undefined;
416 try {
417 await Promise.race([
418 inFlight.catch(() => undefined),
419 new Promise<never>((_, reject) => {
420 timeout = setTimeout(
421 () => reject(new Error("Speech stream reset timed out.")),
422 1_000,
423 );
424 }),
425 ]);
426 } finally {
427 clearTimeout(timeout);
428 }
429 }
430 await send({ kind: "reset" });
431 },
432 transcribe: async (
433 pcm: Float32Array,
434 options: NativeSpeechOptions,
435 filterSilence: boolean,
436 vadPath?: string,
437 ) => {
438 const result = await send({ kind: "transcribe", pcm, options, filterSilence, vadPath });
439 if (typeof result.text !== "string") throw new Error("Invalid speech process response.");
440 return { text: result.text };
441 },
442 dispose,
443 };
445​
446type NativeSpeechOptions = {
447 readonly timestamps: "none";
448 readonly task?: "translate";
449 readonly targetLanguage?: "en";
450 readonly language?: string;
451 readonly vocabulary?: readonly string[];
452};