UNPKG

js-tts-wrapper

Version:

A JavaScript/TypeScript library that provides a unified API for working with multiple cloud-based Text-to-Speech (TTS) services

209 lines (208 loc) 7.63 kB
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 UnrealSpeechTTSClient 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 }); this.apiKey = credentials.apiKey || process.env.UNREAL_SPEECH_API_KEY || ""; this.baseUrl = credentials.baseURL || "https://api.v8.unrealspeech.com"; this.voiceId = "Sierra"; this._models = [{ id: "default", features: ["streaming"] }]; 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); } } } } 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; } setVoice(voiceId) { this.voiceId = voiceId; } getProperty(property) { switch (property) { case "voice": return this.voiceId; default: return super.getProperty(property); } } setProperty(property, value) { switch (property) { 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}/speech`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify({ Text: "test", VoiceId: "Sierra", AudioFormat: "mp3", OutputFormat: "uri", }), }); return response.status !== 401; } catch { return false; } } getRequiredCredentials() { return ["apiKey"]; } async _getVoices() { return UnrealSpeechTTSClient.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: "unrealspeech", })); } async synthToBytes(text, options = {}) { const preparedText = await this.prepareText(text, options); const voiceId = options.voice || this.voiceId; const body = { ...options.providerOptions, AudioFormat: options.audioFormat || "mp3", OutputFormat: "uri", VoiceId: voiceId, Text: preparedText, }; const response = await fetch(`${this.baseUrl}/speech`, { 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(`Unreal Speech API error: ${response.status} ${response.statusText} - ${errorText}`); } const json = (await response.json()); const audioResponse = await fetch(json.OutputUri); if (!audioResponse.ok) { throw new Error(`Unreal Speech download error: ${audioResponse.status}`); } const arrayBuffer = await audioResponse.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 = { ...options.providerOptions, AudioFormat: options.audioFormat || "mp3", VoiceId: voiceId, Text: preparedText, }; const response = await fetch(`${this.baseUrl}/stream`, { 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(`Unreal Speech API error: ${response.status} ${response.statusText} - ${errorText}`); } if (!response.body) { const bytes = await this.synthToBytes(text, options); const readableStream = new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); }, }); return { audioStream: readableStream, wordBoundaries: [] }; } return { audioStream: response.body, wordBoundaries: [] }; } } Object.defineProperty(UnrealSpeechTTSClient, "VOICES", { enumerable: true, configurable: true, writable: true, value: [ { id: "Sierra", name: "Sierra", gender: "Female", language: "en-US" }, { id: "Dan", name: "Dan", gender: "Male", language: "en-US" }, { id: "Will", name: "Will", gender: "Male", language: "en-US" }, { id: "Scarlett", name: "Scarlett", gender: "Female", language: "en-US" }, { id: "Liv", name: "Liv", gender: "Female", language: "en-US" }, { id: "Amy", name: "Amy", gender: "Female", language: "en-US" }, { id: "Eric", name: "Eric", gender: "Male", language: "en-US" }, { id: "Brian", name: "Brian", gender: "Male", language: "en-US" }, ] });