speechflow
Version: 
Speech Processing Flow Graph
145 lines • 5.99 kB
JavaScript
;
/*
**  SpeechFlow - Speech Processing Flow Graph
**  Copyright (c) 2024-2025 Dr. Ralf S. Engelschall <rse@engelschall.com>
**  Licensed under GPL 3.0 <https://spdx.org/licenses/GPL-3.0-only>
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/*  standard dependencies  */
const node_stream_1 = __importDefault(require("node:stream"));
/*  external dependencies  */
const DeepL = __importStar(require("deepl-node"));
/*  internal dependencies  */
const speechflow_node_1 = __importDefault(require("./speechflow-node"));
const util = __importStar(require("./speechflow-util"));
/*  SpeechFlow node for DeepL text-to-text translations  */
class SpeechFlowNodeT2TDeepL extends speechflow_node_1.default {
    /*  declare official node name  */
    static name = "t2t-deepl";
    /*  internal state  */
    deepl = null;
    /*  construct node  */
    constructor(id, cfg, opts, args) {
        super(id, cfg, opts, args);
        /*  declare node configuration parameters  */
        this.configure({
            key: { type: "string", val: process.env.SPEECHFLOW_DEEPL_KEY ?? "" },
            src: { type: "string", pos: 0, val: "de", match: /^(?:de|en|fr|it)$/ },
            dst: { type: "string", pos: 1, val: "en", match: /^(?:de|en|fr|it)$/ },
            optimize: { type: "string", pos: 2, val: "latency", match: /^(?:latency|quality)$/ }
        });
        /*  validate API key  */
        if (this.params.key === "")
            throw new Error("DeepL API key is required");
        /*  sanity check situation  */
        if (this.params.src === this.params.dst)
            throw new Error("source and destination languages cannot be the same");
        /*  declare node input/output format  */
        this.input = "text";
        this.output = "text";
    }
    /*  one-time status of node  */
    async status() {
        const deepl = new DeepL.Translator(this.params.key);
        const usage = await deepl.getUsage();
        const limit = usage?.character?.limit ?? 1;
        const percent = limit > 0 ? ((usage?.character?.count ?? 0) / limit * 100) : 0;
        return { usage: `${percent.toFixed(8)}%` };
    }
    /*  open node  */
    async open() {
        /*  instantiate DeepL API SDK  */
        this.deepl = new DeepL.Translator(this.params.key);
        /*  provide text-to-text translation  */
        const translate = async (text) => {
            const src = this.params.src === "en" ? "en-US" : this.params.src;
            const dst = this.params.dst === "en" ? "en-US" : this.params.dst;
            const result = await this.deepl.translateText(text, src, dst, {
                splitSentences: "off",
                modelType: this.params.optimize === "latency" ?
                    "latency_optimized" : "prefer_quality_optimized",
                preserveFormatting: true,
                formality: "prefer_more"
            });
            return (result?.text ?? text);
        };
        /*  establish a duplex stream and connect it to DeepL translation  */
        this.stream = new node_stream_1.default.Transform({
            readableObjectMode: true,
            writableObjectMode: true,
            decodeStrings: false,
            highWaterMark: 1,
            transform(chunk, encoding, callback) {
                if (Buffer.isBuffer(chunk.payload))
                    callback(new Error("invalid chunk payload type"));
                else if (chunk.payload === "") {
                    this.push(chunk);
                    callback();
                }
                else {
                    translate(chunk.payload).then((payload) => {
                        const chunkNew = chunk.clone();
                        chunkNew.payload = payload;
                        this.push(chunkNew);
                        callback();
                    }).catch((error) => {
                        callback(util.ensureError(error));
                    });
                }
            },
            final(callback) {
                this.push(null);
                callback();
            }
        });
    }
    /*  close node  */
    async close() {
        /*  close stream  */
        if (this.stream !== null) {
            this.stream.destroy();
            this.stream = null;
        }
        /*  shutdown DeepL API  */
        if (this.deepl !== null)
            this.deepl = null;
    }
}
exports.default = SpeechFlowNodeT2TDeepL;
//# sourceMappingURL=speechflow-node-t2t-deepl.js.map