js-tts-wrapper
Version:
A JavaScript/TypeScript library that provides a unified API for working with multiple cloud-based Text-to-Speech (TTS) services
232 lines (231 loc) • 8.08 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 XaiTTSClient 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
});
Object.defineProperty(this, "language", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.apiKey = credentials.apiKey || process.env.XAI_API_KEY || "";
this.baseUrl = credentials.baseURL || "https://api.x.ai/v1";
this.model = credentials.model || "grok-tts";
this.voiceId = "avalon-47";
this.language = "auto";
this._models = [{ id: "grok-tts", features: ["streaming", "audio-tags"] }];
this.sampleRate = 24000;
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);
}
}
}
}
processAudioTags(text) {
return text;
}
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);
}
processedText = this.processAudioTags(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;
case "language":
return this.language;
default:
return super.getProperty(property);
}
}
setProperty(property, value) {
switch (property) {
case "model":
this.setModel(value);
break;
case "voice":
this.setVoice(value);
break;
case "language":
this.language = value;
break;
default:
super.setProperty(property, value);
break;
}
}
async checkCredentials() {
if (!this.apiKey)
return false;
try {
const response = await fetch(`${this.baseUrl}/tts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({ text: "test", language: "auto" }),
});
return response.ok;
}
catch {
return false;
}
}
getRequiredCredentials() {
return ["apiKey"];
}
async _getVoices() {
return XaiTTSClient.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: "xai",
}));
}
async synthToBytes(text, options = {}) {
const preparedText = await this.prepareText(text, options);
const voiceId = options.voice || this.voiceId;
const body = {
language: options.language || this.language,
...options.providerOptions,
text: preparedText,
};
if (voiceId) {
body.voice_id = voiceId;
}
const response = await fetch(`${this.baseUrl}/tts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`xAI 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 voiceId = options.voice || this.voiceId;
const body = {
language: options.language || this.language,
...options.providerOptions,
text: preparedText,
};
if (voiceId) {
body.voice_id = voiceId;
}
const response = await fetch(`${this.baseUrl}/tts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`xAI 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(XaiTTSClient, "VOICES", {
enumerable: true,
configurable: true,
writable: true,
value: [
{ id: "avalon-47", name: "Avalon", gender: "Female", language: "en-US" },
{ id: "orion-56", name: "Orion", gender: "Male", language: "en-US" },
{ id: "luna-30", name: "Luna", gender: "Female", language: "en-US" },
{ id: "atlas-84", name: "Atlas", gender: "Male", language: "en-US" },
{ id: "aria-42", name: "Aria", gender: "Female", language: "en-US" },
{ id: "cosmo-01", name: "Cosmo", gender: "Male", language: "en-US" },
]
});