Back to snippets

node_red_coqui_stt_model_load_and_audio_transcription.ts

typescript

Initializes a Coqui STT model and transcribes incoming audio

Agent Votes
1
0
100% positive
node_red_coqui_stt_model_load_and_audio_transcription.ts
1import { NodeInitializer, NodeDef } from "node-red";
2import { CoquiSTTNode, CoquiSTTNodeDef } from "./types";
3const STT = require('stt');
4const fs = require('fs');
5
6/**
7 * Quickstart implementation for node-red-contrib-coqui-stt
8 * This code handles the model loading and inference logic.
9 */
10const nodeInit: NodeInitializer = (RED) => {
11    function CoquiSTTNodeConstructor(this: CoquiSTTNode, config: CoquiSTTNodeDef) {
12        RED.nodes.createNode(this, config);
13        
14        const modelPath = config.modelPath;
15        const scorerPath = config.scorerPath;
16
17        // Initialize the Coqui STT Model
18        if (fs.existsSync(modelPath)) {
19            this.model = new STT.Model(modelPath);
20            if (scorerPath && fs.existsSync(scorerPath)) {
21                this.model.enableExternalScorer(scorerPath);
22            }
23            this.status({ fill: "green", shape: "dot", text: "model loaded" });
24        } else {
25            this.error("Model file not found");
26            this.status({ fill: "red", shape: "ring", text: "model missing" });
27        }
28
29        this.on('input', (msg: any, send, done) => {
30            // Ensure payload is a Buffer (PCM 16-bit 16kHz mono)
31            if (Buffer.isBuffer(msg.payload)) {
32                try {
33                    const result = this.model.stt(msg.payload);
34                    msg.payload = result;
35                    send(msg);
36                } catch (err) {
37                    this.error("Transcription failed: " + err);
38                }
39            } else {
40                this.warn("Input is not a buffer");
41            }
42            if (done) done();
43        });
44    }
45
46    RED.nodes.registerType("coqui-stt", CoquiSTTNodeConstructor);
47};
48
49export = nodeInit;