js-tts-wrapper
Version:
A JavaScript/TypeScript library that provides a unified API for working with multiple cloud-based Text-to-Speech (TTS) services
236 lines (235 loc) • 9.07 kB
JavaScript
import { AbstractTTSClient } from "../core/abstract-tts.js";
import * as SSMLUtils from "../core/ssml-utils.js";
import * as SpeechMarkdown from "../markdown/converter.js";
import { getFetch } from "../utils/fetch-utils.js";
import { toIso639_3, toLanguageDisplay } from "../utils/language-utils.js";
const fetch = getFetch();
export class DeepgramTTSClient extends AbstractTTSClient {
constructor(credentials = {}) {
super(credentials);
Object.defineProperty(this, "apiKey", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "baseUrl", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "model", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.apiKey = credentials.apiKey || process.env.DEEPGRAM_API_KEY || "";
this.baseUrl = credentials.baseURL || "https://api.deepgram.com/v1";
this.model = credentials.model || "aura-2";
this.voiceId = "aura-2-apollo-en";
this._models = [
{ id: "aura-2", features: ["streaming"] },
{ id: "aura", features: ["streaming"] },
];
this.applyCredentialProperties(credentials);
}
applyCredentialProperties(credentials) {
const rawProps = credentials.properties ??
credentials.propertiesJson ??
credentials.propertiesJSON;
if (rawProps) {
let parsed = null;
if (typeof rawProps === "string") {
try {
parsed = JSON.parse(rawProps);
}
catch {
/* ignore */
}
}
else if (typeof rawProps === "object") {
parsed = rawProps;
}
if (parsed) {
for (const [key, value] of Object.entries(parsed)) {
this.setProperty(key, value);
}
}
}
}
async prepareText(text, options) {
let processedText = text;
if (options?.useSpeechMarkdown && SpeechMarkdown.isSpeechMarkdown(processedText)) {
const ssml = await SpeechMarkdown.toSSML(processedText, "w3c");
processedText = SSMLUtils.stripSSML(ssml);
}
if (SSMLUtils.isSSML(processedText)) {
processedText = SSMLUtils.stripSSML(processedText);
}
return processedText;
}
setModel(model) {
this.model = model;
}
setVoice(voiceId) {
this.voiceId = voiceId;
}
getProperty(property) {
switch (property) {
case "model":
return this.model;
case "voice":
return this.voiceId;
default:
return super.getProperty(property);
}
}
setProperty(property, value) {
switch (property) {
case "model":
this.setModel(value);
break;
case "voice":
this.setVoice(value);
break;
default:
super.setProperty(property, value);
break;
}
}
async checkCredentials() {
if (!this.apiKey)
return false;
try {
const response = await fetch(`${this.baseUrl}/voices`, {
method: "GET",
headers: {
Authorization: `Token ${this.apiKey}`,
},
});
return response.ok;
}
catch {
return false;
}
}
getRequiredCredentials() {
return ["apiKey"];
}
async _getVoices() {
return DeepgramTTSClient.VOICES;
}
async _mapVoicesToUnified(rawVoices) {
return rawVoices.map((voice) => ({
id: voice.id,
name: voice.name,
gender: voice.gender,
languageCodes: [
{
bcp47: voice.language || "en-US",
iso639_3: toIso639_3(voice.language || "en-US"),
display: toLanguageDisplay(voice.language || "en-US"),
},
],
provider: "deepgram",
}));
}
async synthToBytes(text, options = {}) {
const preparedText = await this.prepareText(text, options);
const voiceParam = options.voice || this.voiceId || "aura-2-apollo-en";
const modelParam = `${options.model || this.model}-${voiceParam}`;
const url = `${this.baseUrl}/speak?model=${encodeURIComponent(modelParam)}`;
const body = {
...options.providerOptions,
text: preparedText,
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${this.apiKey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Deepgram API error: ${response.status} ${response.statusText} - ${errorText}`);
}
const arrayBuffer = await response.arrayBuffer();
this._createEstimatedWordTimings(preparedText);
return new Uint8Array(arrayBuffer);
}
async synthToBytestream(text, options = {}) {
const preparedText = await this.prepareText(text, options);
const voiceParam = options.voice || this.voiceId || "aura-2-apollo-en";
const modelParam = `${options.model || this.model}-${voiceParam}`;
const url = `${this.baseUrl}/speak?model=${encodeURIComponent(modelParam)}`;
const body = {
...options.providerOptions,
text: preparedText,
};
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${this.apiKey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Deepgram API error: ${response.status} ${response.statusText} - ${errorText}`);
}
if (!response.body) {
const arrayBuffer = await response.arrayBuffer();
const audioData = new Uint8Array(arrayBuffer);
const readableStream = new ReadableStream({
start(controller) {
controller.enqueue(audioData);
controller.close();
},
});
return { audioStream: readableStream, wordBoundaries: [] };
}
return { audioStream: response.body, wordBoundaries: [] };
}
}
Object.defineProperty(DeepgramTTSClient, "VOICES", {
enumerable: true,
configurable: true,
writable: true,
value: [
{ id: "aura-asteria-english", name: "Asteria", gender: "Female", language: "en-US" },
{ id: "aura-luna-english", name: "Luna", gender: "Female", language: "en-US" },
{ id: "aura-stella-english", name: "Stella", gender: "Female", language: "en-US" },
{ id: "aura-athena-english", name: "Athena", gender: "Female", language: "en-US" },
{ id: "aura-hera-english", name: "Hera", gender: "Female", language: "en-US" },
{ id: "aura-orion-english", name: "Orion", gender: "Male", language: "en-US" },
{ id: "aura-arcas-english", name: "Arcas", gender: "Male", language: "en-US" },
{ id: "aura-perseus-english", name: "Perseus", gender: "Male", language: "en-US" },
{ id: "aura-angus-english", name: "Angus", gender: "Male", language: "en-US" },
{ id: "aura-orpheus-english", name: "Orpheus", gender: "Male", language: "en-US" },
{ id: "aura-helios-english", name: "Helios", gender: "Male", language: "en-US" },
{ id: "aura-zeus-english", name: "Zeus", gender: "Male", language: "en-US" },
{ id: "aura-2-andromeda-en", name: "Andromeda", gender: "Female", language: "en-US" },
{
id: "aura-2-cassiopeia-en",
name: "Cassiopeia",
gender: "Female",
language: "en-US",
},
{ id: "aura-2-dianna-en", name: "Dianna", gender: "Female", language: "en-US" },
{ id: "aura-2-thalia-en", name: "Thalia", gender: "Female", language: "en-US" },
{ id: "aura-2-algernon-en", name: "Algernon", gender: "Male", language: "en-US" },
{
id: "aura-2-bellerophon-en",
name: "Bellerophon",
gender: "Male",
language: "en-US",
},
{ id: "aura-2-callisto-en", name: "Callisto", gender: "Female", language: "en-US" },
{ id: "aura-2-apollo-en", name: "Apollo", gender: "Male", language: "en-US" },
]
});