ivr-tester-transcriber-google-speech-to-text
Version:
Google Speech-to-Text integration for IVR Tester
74 lines (73 loc) • 2.73 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GoogleSpeechToText = void 0;
const speech_1 = require("@google-cloud/speech");
const ivr_tester_1 = require("ivr-tester");
const Debugger_1 = require("./Debugger");
class GoogleSpeechToText extends ivr_tester_1.TypedEmitter {
constructor(languageCode, speechPhrases = [], useEnhanced = false, speechClient = new speech_1.SpeechClient()) {
super();
this.speechClient = speechClient;
this.config = GoogleSpeechToText.createConfig(languageCode, speechPhrases, useEnhanced);
GoogleSpeechToText.debug("Configuration: %O", this.config);
}
static createConfig(languageCode, speechPhrases, useEnhanced) {
return {
config: {
encoding: speech_1.protos.google.cloud.speech.v1.RecognitionConfig.AudioEncoding.MULAW,
sampleRateHertz: 8000,
languageCode,
model: "phone_call",
speechContexts: [{ phrases: speechPhrases }],
useEnhanced,
},
interimResults: true,
singleUtterance: false,
};
}
transcribe(payload) {
this.getStream().write(payload.toString("base64"));
}
close() {
if (this.stream) {
this.stream.removeAllListeners();
this.stream.write(Buffer.from([]));
this.stream.destroy();
this.stream = null;
GoogleSpeechToText.debug("Stream destroyed");
}
}
createStream() {
return (this.stream = this.speechClient
.streamingRecognize(this.config)
.on("error", (error) => {
GoogleSpeechToText.debug(error);
this.stream.removeAllListeners();
this.stream.destroy();
this.stream = null;
})
.on("data", (data) => {
GoogleSpeechToText.debug("Data: %O", data);
const result = data.results[0];
if ((result === null || result === void 0 ? void 0 : result.alternatives[0]) !== undefined) {
const event = {
transcription: result.alternatives[0].transcript.trim(),
isFinal: result.isFinal,
};
GoogleSpeechToText.debug("Emitted: %O", event);
this.emit("transcription", event);
}
}));
}
getStream() {
if (!this.stream) {
this.stream = this.createStream();
}
return this.stream;
}
transcriptionComplete() {
this.close();
}
}
exports.GoogleSpeechToText = GoogleSpeechToText;
GoogleSpeechToText.debug = Debugger_1.Debugger.getPackageDebugger();