web-ai-toolkit
Version:
AI powered features on the web made easy
88 lines (87 loc) • 2.32 kB
JavaScript
import { _ as f, a as m } from "./transformers-kV3s9sef.js";
import { w as g } from "./utils-DJ16RMae.js";
let a;
function v(e, t = "Xenova/whisper-tiny") {
return new Promise(async (s, n) => {
try {
a || await y(t || "Xenova/whisper-tiny", !1, "en");
const i = new FileReader();
i.onloadend = async () => {
const _ = new AudioContext({
sampleRate: 16e3
}), p = i.result, r = await _.decodeAudioData(p);
let l;
if (r.numberOfChannels === 2) {
const h = Math.sqrt(2), u = r.getChannelData(0), w = r.getChannelData(1);
l = new Float32Array(u.length);
for (let c = 0; c < r.length; ++c)
l[c] = h * (u[c] + w[c]) / 2;
} else
l = r.getChannelData(0);
const d = await k(l);
s(d);
}, i.readAsArrayBuffer(e);
} catch (i) {
n(i);
}
});
}
async function y(e = "Xenova/whisper-tiny", t, s) {
return new Promise(async (n) => {
a || (f.allowLocalModels = !1, f.useBrowserCache = !1, a = await m("automatic-speech-recognition", e || "Xenova/whisper-tiny", {
// @ts-ignore
return_timestamps: t,
language: s,
// @ts-ignore
device: await g() ? "webgpu" : "wasm"
})), n();
});
}
async function k(e) {
return new Promise(async (t, s) => {
if (a) {
const n = await a(e, {
chunk_length_s: 30,
stride_length_s: 5,
// @ts-ignore
callback_function: C,
// after each generation step
chunk_callback: b
// after each chunk is processed
});
t(n.text);
} else
s();
});
}
const o = [
{
tokens: [],
finalised: !1
}
];
function b(e) {
const t = o[o.length - 1];
Object.assign(t, e), t.finalised = !0, e.is_last || o.push({
tokens: [],
finalised: !1
});
}
function C(e) {
const t = a.processor.feature_extractor.config.chunk_length / a.model.config.max_source_positions, s = o[o.length - 1];
s.tokens = [...e[0].output_token_ids];
const n = a.tokenizer._decode_asr(o, {
time_precision: t,
return_timestamps: !0,
force_full_sequences: !1
});
self.postMessage({
type: "transcribe-interim",
transcription: n[0]
});
}
export {
v as doLocalWhisper,
y as loadTranscriber,
k as localTranscribe
};