42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import {Worker} from 'worker_threads';
|
|
import Path from 'node:path';
|
|
import {AbortablePromise, Ai} from './ai.ts';
|
|
import {canDiarization} from './asr.ts';
|
|
|
|
export class Audio {
|
|
constructor(private ai: Ai) {}
|
|
|
|
asr(file: string, options: { model?: string; speaker?: boolean } = {}): AbortablePromise<string | null> {
|
|
console.log('audio', file);
|
|
const { model = this.ai.options.asr || 'whisper-base', speaker = false } = options;
|
|
let aborted = false;
|
|
const abort = () => { aborted = true; };
|
|
|
|
const p = new Promise<string | null>((resolve, reject) => {
|
|
const worker = new Worker(Path.join(import.meta.dirname, 'asr.js'));
|
|
const handleMessage = ({ text, warning, error }: any) => {
|
|
worker.terminate();
|
|
if(aborted) return;
|
|
if(error) reject(new Error(error));
|
|
else {
|
|
if(warning) console.warn(warning);
|
|
resolve(text);
|
|
}
|
|
};
|
|
const handleError = (err: Error) => {
|
|
worker.terminate();
|
|
if(!aborted) reject(err);
|
|
};
|
|
worker.on('message', handleMessage);
|
|
worker.on('error', handleError);
|
|
worker.on('exit', (code) => {
|
|
if(code !== 0 && !aborted) reject(new Error(`Worker exited with code ${code}`));
|
|
});
|
|
worker.postMessage({file, model, speaker, modelDir: this.ai.options.path});
|
|
});
|
|
return Object.assign(p, { abort });
|
|
}
|
|
|
|
canDiarization = canDiarization;
|
|
}
|