@yaks/speech 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/elevenlabs.js ADDED
@@ -0,0 +1,339 @@
1
+ // ElevenLabs: Multilingual v2 speaks unless another of its models is asked
2
+ // for (Flash v2.5, v4 Turbo and v3 Conversational, quicker and half the
3
+ // price; v4), Scribe v2 hears a recording and tells its speakers apart, and
4
+ // an account keeps voices of its own: the premade ones, voices designed from
5
+ // a description, and voices cloned from recordings. It has no model here that
6
+ // hears a stream or talks. The key goes in its own header, `xi-api-key`.
7
+ // Prices are its API pay-as-you-go list, 2026-12-04: $0.08 per thousand
8
+ // characters spoken by Multilingual v2 and v4, $0.04 by Flash v2.5, v4 Turbo
9
+ // and v3 Conversational, and $0.20 an hour heard by Scribe v2.
10
+ // https://elevenlabs.io/docs/overview/models
11
+ // https://elevenlabs.io/docs/api-reference/text-to-speech/convert
12
+ // https://elevenlabs.io/docs/api-reference/speech-to-text/convert
13
+ // https://elevenlabs.io/docs/api-reference/voices/search
14
+ // https://elevenlabs.io/docs/api-reference/text-to-voice/design
15
+ // https://elevenlabs.io/docs/api-reference/text-to-voice/create
16
+ // https://elevenlabs.io/docs/api-reference/voices/ivc/create
17
+ // https://elevenlabs.io/pricing/api
18
+ import { audioForm } from "./mod.js";
19
+ import { unbase64 } from "./audio.js";
20
+ import { query } from "./query.js";
21
+ // The output format a request names: an MP3, μ-law at 8 kHz, or raw 16-bit
22
+ // PCM at a rate it speaks.
23
+ let output = (format)=>format.encoding == 'mp3' ? 'mp3_44100_128' : format.encoding == 'mulaw' ? `ulaw_${format.rate}` : `pcm_${format.rate}`;
24
+ /**
25
+ * A voice as the account lists it: its id, its name, how it sounds (its
26
+ * description, else its labels), and the sample it plays.
27
+ *
28
+ * ```ts
29
+ * import { equal } from '@yaks/testing'
30
+ * import { ELEVENLABS } from '@yaks/speech'
31
+ * equal(
32
+ * ELEVENLABS.voices!.read({
33
+ * voices: [{
34
+ * voice_id: 'v1',
35
+ * name: 'Ada',
36
+ * category: 'cloned',
37
+ * labels: { accent: 'british', gender: 'female' },
38
+ * preview_url: 'https://x/ada.mp3',
39
+ * }],
40
+ * has_more: true,
41
+ * next_page_token: 'p2',
42
+ * }),
43
+ * {
44
+ * voices: [{
45
+ * id: 'v1',
46
+ * name: 'Ada',
47
+ * about: 'british, female',
48
+ * sample: 'https://x/ada.mp3',
49
+ * custom: true,
50
+ * }],
51
+ * next: 'p2',
52
+ * },
53
+ * )
54
+ * ```
55
+ */ let voiceOf = (v)=>({
56
+ id: v.voice_id,
57
+ name: v.name ?? v.voice_id,
58
+ about: v.description?.trim() || Object.values(v.labels ?? {}).join(', '),
59
+ ...v.preview_url ? {
60
+ sample: v.preview_url
61
+ } : {},
62
+ ...v.category && v.category != 'premade' ? {
63
+ custom: true
64
+ } : {}
65
+ });
66
+ // Scribe's words in a row, a turn each time the speaker changes; spacing
67
+ // joins words, and sounds such as (laughter) are left out.
68
+ let turnsOf = (words)=>words.reduce((turns, w)=>{
69
+ if (w.type == 'audio_event') return turns;
70
+ let speaker = Number(w.speaker_id?.match(/\d+$/)?.[0] ?? 0);
71
+ let last = turns.at(-1);
72
+ if (w.type == 'spacing') {
73
+ if (last) last.text += w.text;
74
+ return turns;
75
+ }
76
+ if (last?.speaker == speaker) {
77
+ last.text += w.text;
78
+ if (w.end != null) last.to = w.end;
79
+ } else {
80
+ turns.push({
81
+ speaker,
82
+ text: w.text,
83
+ ...w.start == null ? {} : {
84
+ from: w.start
85
+ },
86
+ ...w.end == null ? {} : {
87
+ to: w.end
88
+ }
89
+ });
90
+ }
91
+ return turns;
92
+ }, []).map((t)=>({
93
+ ...t,
94
+ text: t.text.trim()
95
+ }));
96
+ // Premade voices every account has, as it lists them (GET /v1/voices).
97
+ let PREMADE = [
98
+ [
99
+ 'JBFqnCBsd6RMkjVDRZzb',
100
+ 'George',
101
+ 'warm, captivating storyteller; British'
102
+ ],
103
+ [
104
+ 'onwK4e9ZLuTAKqWW03F9',
105
+ 'Daniel',
106
+ 'steady broadcaster; British'
107
+ ],
108
+ [
109
+ 'Xb7hH8MSUJpSbSDYk0k2',
110
+ 'Alice',
111
+ 'clear, engaging educator; British'
112
+ ],
113
+ [
114
+ 'pFZP5JQG7iQjIQuC4Bku',
115
+ 'Lily',
116
+ 'velvety actress; British'
117
+ ],
118
+ [
119
+ 'EXAVITQu4vr4xnSDxMaL',
120
+ 'Sarah',
121
+ 'mature, reassuring, confident; American'
122
+ ],
123
+ [
124
+ 'CwhRBWXzGAHq8TQ4Fs17',
125
+ 'Roger',
126
+ 'laid-back, casual, resonant; American'
127
+ ],
128
+ [
129
+ 'nPczCjzI2devNBz1zQrb',
130
+ 'Brian',
131
+ 'deep, resonant, comforting; American'
132
+ ],
133
+ [
134
+ 'XrExE9yKIg1WjnnlVkGX',
135
+ 'Matilda',
136
+ 'knowledgeable, professional; American'
137
+ ],
138
+ [
139
+ 'cjVigY5qzO86Huf0OWal',
140
+ 'Eric',
141
+ 'smooth, trustworthy; American'
142
+ ],
143
+ [
144
+ 'SAz9YHcvj6GT2YYXdXww',
145
+ 'River',
146
+ 'relaxed, neutral, informative; American'
147
+ ],
148
+ [
149
+ 'N2lVS1w4EtoT3dr4eOWO',
150
+ 'Callum',
151
+ 'husky trickster; American'
152
+ ],
153
+ [
154
+ 'IKne3meq5aSn9XLyUdCD',
155
+ 'Charlie',
156
+ 'deep, confident, energetic; Australian'
157
+ ],
158
+ [
159
+ 'pqHfZKP75CvOlQylNhV4',
160
+ 'Bill',
161
+ 'wise, mature, balanced; American'
162
+ ]
163
+ ].map(([id, name, about])=>({
164
+ id,
165
+ name,
166
+ about
167
+ }));
168
+ // Voices of its library an account speaks in by id, as it does the premade.
169
+ // https://elevenlabs.io/voices/sd63ZkbzEI8aQTTWX7VK
170
+ let LIBRARY = [
171
+ {
172
+ id: 'sd63ZkbzEI8aQTTWX7VK',
173
+ name: 'Jon',
174
+ about: 'rich, expressive, natural and conversational; American'
175
+ }
176
+ ];
177
+ export let ELEVENLABS = {
178
+ name: 'elevenlabs',
179
+ title: 'ElevenLabs',
180
+ api: 'https://api.elevenlabs.io',
181
+ live: 'wss://api.elevenlabs.io',
182
+ header: 'xi-api-key',
183
+ authorization: (key)=>key,
184
+ protocols: ()=>[],
185
+ hear: {
186
+ model: 'scribe_v3',
187
+ perMinute: 0.20 / 60,
188
+ speakers: true,
189
+ // Its limit is 5 GB, sent whole in a form.
190
+ bytes: 5 * 1024 ** 3,
191
+ request: (audio, type, model)=>({
192
+ path: '/v1/speech-to-text',
193
+ init: audioForm({
194
+ model_id: model,
195
+ diarize: 'true',
196
+ tag_audio_events: 'false'
197
+ }, audio, type)
198
+ }),
199
+ read: (said)=>{
200
+ let { text, words, audio_duration_secs } = said;
201
+ return {
202
+ text: text ?? '',
203
+ seconds: audio_duration_secs ?? words?.findLast((w)=>w.end != null)?.end,
204
+ ...words?.length ? {
205
+ turns: turnsOf(words)
206
+ } : {}
207
+ };
208
+ }
209
+ },
210
+ turns: [],
211
+ speak: {
212
+ voice: PREMADE[0].id,
213
+ voices: [
214
+ ...PREMADE,
215
+ ...LIBRARY
216
+ ],
217
+ // https://elevenlabs.io/docs/api-reference/text-to-speech/convert
218
+ // (voice_settings.speed)
219
+ speeds: {
220
+ min: 0.7,
221
+ max: 1.2
222
+ },
223
+ models: [
224
+ {
225
+ model: 'eleven_v4',
226
+ perThousand: 0.08
227
+ },
228
+ {
229
+ model: 'eleven_multilingual_v2',
230
+ perThousand: 0.08
231
+ },
232
+ {
233
+ model: 'eleven_flash_v2_5',
234
+ perThousand: 0.04
235
+ },
236
+ {
237
+ model: 'eleven_v4_turbo',
238
+ perThousand: 0.04
239
+ },
240
+ {
241
+ model: 'eleven_v3_conversational',
242
+ perThousand: 0.04
243
+ }
244
+ ],
245
+ request: (text, voice, format, speed, model)=>({
246
+ path: `/v1/text-to-speech/${encodeURIComponent(voice)}?${query({
247
+ output_format: output(format)
248
+ })}`,
249
+ init: {
250
+ method: 'POST',
251
+ headers: {
252
+ 'content-type': 'application/json'
253
+ },
254
+ body: JSON.stringify({
255
+ text,
256
+ model_id: model,
257
+ ...speed == 1 ? {} : {
258
+ voice_settings: {
259
+ speed
260
+ }
261
+ }
262
+ })
263
+ }
264
+ })
265
+ },
266
+ voices: {
267
+ request: (page)=>({
268
+ path: `/v2/voices?${query({
269
+ page_size: 100,
270
+ include_total_count: 'false',
271
+ next_page_token: page
272
+ })}`,
273
+ init: {}
274
+ }),
275
+ read: (said)=>{
276
+ let { voices, has_more, next_page_token } = said;
277
+ return {
278
+ voices: (voices ?? []).map(voiceOf),
279
+ ...has_more && next_page_token ? {
280
+ next: next_page_token
281
+ } : {}
282
+ };
283
+ }
284
+ },
285
+ make: {
286
+ design: (description, text)=>({
287
+ path: '/v1/text-to-voice/design?output_format=mp3_44100_128',
288
+ init: {
289
+ method: 'POST',
290
+ headers: {
291
+ 'content-type': 'application/json'
292
+ },
293
+ body: JSON.stringify({
294
+ voice_description: description,
295
+ ...text ? {
296
+ text
297
+ } : {
298
+ auto_generate_text: true
299
+ }
300
+ })
301
+ }
302
+ }),
303
+ designs: (said)=>(said.previews ?? []).map((p)=>({
304
+ id: p.generated_voice_id,
305
+ audio: unbase64(p.audio_base_64),
306
+ type: p.media_type ?? 'audio/mpeg',
307
+ seconds: p.duration_secs ?? 0
308
+ })),
309
+ keep: (design, name, description)=>({
310
+ path: '/v1/text-to-voice',
311
+ init: {
312
+ method: 'POST',
313
+ headers: {
314
+ 'content-type': 'application/json'
315
+ },
316
+ body: JSON.stringify({
317
+ voice_name: name,
318
+ voice_description: description,
319
+ generated_voice_id: design
320
+ })
321
+ }
322
+ }),
323
+ clone: (name, samples, description)=>{
324
+ let form = new FormData();
325
+ form.set('name', name);
326
+ if (description) form.set('description', description);
327
+ samples.forEach((s, n)=>form.append('files', s, `sample-${n + 1}`));
328
+ return {
329
+ path: '/v1/voices/add',
330
+ init: {
331
+ method: 'POST',
332
+ body: form
333
+ }
334
+ };
335
+ },
336
+ made: (said)=>String(said.voice_id ?? '')
337
+ }
338
+ };
339
+ //# sourceMappingURL=elevenlabs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"elevenlabs.js","sources":["./elevenlabs.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,wEAAwE;AACxE,4EAA4E;AAC5E,6EAA6E;AAC7E,8EAA8E;AAC9E,yEAAyE;AACzE,wEAAwE;AACxE,6EAA6E;AAC7E,+DAA+D;AAC/D,6CAA6C;AAC7C,kEAAkE;AAClE,kEAAkE;AAClE,yDAAyD;AACzD,gEAAgE;AAChE,gEAAgE;AAChE,6DAA6D;AAC7D,oCAAoC;AACpC,SACE,SAAS,mBAKM;AACjB,SAAS,QAAQ,qBAAoB;AACrC,SAAS,KAAK,qBAAoB;AAElC,2EAA2E;AAC3E,2BAA2B;AAC3B,IAAI,SAAS,CAAC,SACZ,OAAO,QAAQ,IAAI,QACf,kBACA,OAAO,QAAQ,IAAI,UACnB,CAAC,KAAK,EAAE,OAAO,IAAI,EAAE,GACrB,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE;AAW1B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GACD,IAAI,UAAU,CAAC,IAAqB,CAAC;IACnC,IAAI,EAAE,QAAQ;IACd,MAAM,EAAE,IAAI,IAAI,EAAE,QAAQ;IAC1B,OAAO,EAAE,WAAW,EAAE,UACpB,OAAO,MAAM,CAAC,EAAE,MAAM,IAAI,CAAC,GAAG,IAAI,CAAC;IACrC,GAAG,EAAE,WAAW,GAAG;MAAE,QAAQ,EAAE,WAAW;IAAC,IAAI,CAAC,CAAC;IACjD,GAAG,EAAE,QAAQ,IAAI,EAAE,QAAQ,IAAI,YAAY;MAAE,QAAQ;IAAK,IAAI,CAAC,CAAC;EAClE,CAAC;AAUD,yEAAyE;AACzE,2DAA2D;AAC3D,IAAI,UAAU,CAAC,QACb,MAAM,MAAM,CAAC,CAAC,OAAe;IAC3B,IA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QAAQ;UACR,SAAS;YAAE,gBAAgB;UAAmB;UAC9C,MAAM,KAAK,SAAS,CAAC;YACnB,YAAY;YACZ,mBAAmB;YACnB,oBAAoB;UACtB;QACF;MACF,CAAC;IACD,OAAO,CAAC,MAAM,SAAS;MACrB,IAAI,OAAO,IAAI;MACf,KAAK,GAAG,CAAC,QAAQ;MACjB,IAAI,aAAa,KAAK,GAAG,CAAC,eAAe;MACzC,QAAQ,OAAO,CAAC,CAAC,GAAG,IAAM,KAAK,MAAM,CAAC,SAAS,GAAG,CAAC,OAAO,EAAE,IAAI,GAAG;MACnE,OAAO;QAAE,MAAM;QAAkB,MAAM;UAAE,QAAQ;UAAQ,MAAM;QAAK;MAAE;IACxE;IACA,MAAM,CAAC,OAAS,OAAO,AAAC,KAA+B,QAAQ,IAAI;EACrE;AACF,EAAC"}
package/elevenlabs.ts ADDED
@@ -0,0 +1,284 @@
1
+ // ElevenLabs: Multilingual v2 speaks unless another of its models is asked
2
+ // for (Flash v2.5, v4 Turbo and v3 Conversational, quicker and half the
3
+ // price; v4), Scribe v2 hears a recording and tells its speakers apart, and
4
+ // an account keeps voices of its own: the premade ones, voices designed from
5
+ // a description, and voices cloned from recordings. It has no model here that
6
+ // hears a stream or talks. The key goes in its own header, `xi-api-key`.
7
+ // Prices are its API pay-as-you-go list, 2026-12-04: $0.08 per thousand
8
+ // characters spoken by Multilingual v2 and v4, $0.04 by Flash v2.5, v4 Turbo
9
+ // and v3 Conversational, and $0.20 an hour heard by Scribe v2.
10
+ // https://elevenlabs.io/docs/overview/models
11
+ // https://elevenlabs.io/docs/api-reference/text-to-speech/convert
12
+ // https://elevenlabs.io/docs/api-reference/speech-to-text/convert
13
+ // https://elevenlabs.io/docs/api-reference/voices/search
14
+ // https://elevenlabs.io/docs/api-reference/text-to-voice/design
15
+ // https://elevenlabs.io/docs/api-reference/text-to-voice/create
16
+ // https://elevenlabs.io/docs/api-reference/voices/ivc/create
17
+ // https://elevenlabs.io/pricing/api
18
+ import {
19
+ audioForm,
20
+ type Format,
21
+ type Provider,
22
+ type Turn,
23
+ type Voice,
24
+ } from './mod.js'
25
+ import { unbase64 } from './audio.js'
26
+ import { query } from './query.js'
27
+
28
+ // The output format a request names: an MP3, μ-law at 8 kHz, or raw 16-bit
29
+ // PCM at a rate it speaks.
30
+ let output = (format: Format) =>
31
+ format.encoding == 'mp3'
32
+ ? 'mp3_44100_128'
33
+ : format.encoding == 'mulaw'
34
+ ? `ulaw_${format.rate}`
35
+ : `pcm_${format.rate}`
36
+
37
+ type Listed = {
38
+ voice_id: string
39
+ name?: string
40
+ category?: string | null
41
+ description?: string | null
42
+ labels?: Record<string, string> | null
43
+ preview_url?: string | null
44
+ }
45
+
46
+ /**
47
+ * A voice as the account lists it: its id, its name, how it sounds (its
48
+ * description, else its labels), and the sample it plays.
49
+ *
50
+ * ```ts
51
+ * import { equal } from '@yaks/testing'
52
+ * import { ELEVENLABS } from '@yaks/speech'
53
+ * equal(
54
+ * ELEVENLABS.voices!.read({
55
+ * voices: [{
56
+ * voice_id: 'v1',
57
+ * name: 'Ada',
58
+ * category: 'cloned',
59
+ * labels: { accent: 'british', gender: 'female' },
60
+ * preview_url: 'https://x/ada.mp3',
61
+ * }],
62
+ * has_more: true,
63
+ * next_page_token: 'p2',
64
+ * }),
65
+ * {
66
+ * voices: [{
67
+ * id: 'v1',
68
+ * name: 'Ada',
69
+ * about: 'british, female',
70
+ * sample: 'https://x/ada.mp3',
71
+ * custom: true,
72
+ * }],
73
+ * next: 'p2',
74
+ * },
75
+ * )
76
+ * ```
77
+ */
78
+ let voiceOf = (v: Listed): Voice => ({
79
+ id: v.voice_id,
80
+ name: v.name ?? v.voice_id,
81
+ about: v.description?.trim() ||
82
+ Object.values(v.labels ?? {}).join(', '),
83
+ ...v.preview_url ? { sample: v.preview_url } : {},
84
+ ...v.category && v.category != 'premade' ? { custom: true } : {},
85
+ })
86
+
87
+ type Word = {
88
+ text: string
89
+ type?: string
90
+ start?: number
91
+ end?: number
92
+ speaker_id?: string
93
+ }
94
+
95
+ // Scribe's words in a row, a turn each time the speaker changes; spacing
96
+ // joins words, and sounds such as (laughter) are left out.
97
+ let turnsOf = (words: Word[]): Turn[] =>
98
+ words.reduce((turns: Turn[], w) => {
99
+ if (w.type == 'audio_event') return turns
100
+ let speaker = Number(w.speaker_id?.match(/\d+$/)?.[0] ?? 0)
101
+ let last = turns.at(-1)
102
+ if (w.type == 'spacing') {
103
+ if (last) last.text += w.text
104
+ return turns
105
+ }
106
+ if (last?.speaker == speaker) {
107
+ last.text += w.text
108
+ if (w.end != null) last.to = w.end
109
+ } else {
110
+ turns.push({
111
+ speaker,
112
+ text: w.text,
113
+ ...w.start == null ? {} : { from: w.start },
114
+ ...w.end == null ? {} : { to: w.end },
115
+ })
116
+ }
117
+ return turns
118
+ }, []).map((t) => ({ ...t, text: t.text.trim() }))
119
+
120
+ // Premade voices every account has, as it lists them (GET /v1/voices).
121
+ let PREMADE: Voice[] = [
122
+ ['JBFqnCBsd6RMkjVDRZzb', 'George', 'warm, captivating storyteller; British'],
123
+ ['onwK4e9ZLuTAKqWW03F9', 'Daniel', 'steady broadcaster; British'],
124
+ ['Xb7hH8MSUJpSbSDYk0k2', 'Alice', 'clear, engaging educator; British'],
125
+ ['pFZP5JQG7iQjIQuC4Bku', 'Lily', 'velvety actress; British'],
126
+ ['EXAVITQu4vr4xnSDxMaL', 'Sarah', 'mature, reassuring, confident; American'],
127
+ ['CwhRBWXzGAHq8TQ4Fs17', 'Roger', 'laid-back, casual, resonant; American'],
128
+ ['nPczCjzI2devNBz1zQrb', 'Brian', 'deep, resonant, comforting; American'],
129
+ ['XrExE9yKIg1WjnnlVkGX', 'Matilda', 'knowledgeable, professional; American'],
130
+ ['cjVigY5qzO86Huf0OWal', 'Eric', 'smooth, trustworthy; American'],
131
+ ['SAz9YHcvj6GT2YYXdXww', 'River', 'relaxed, neutral, informative; American'],
132
+ ['N2lVS1w4EtoT3dr4eOWO', 'Callum', 'husky trickster; American'],
133
+ ['IKne3meq5aSn9XLyUdCD', 'Charlie', 'deep, confident, energetic; Australian'],
134
+ ['pqHfZKP75CvOlQylNhV4', 'Bill', 'wise, mature, balanced; American'],
135
+ ].map(([id, name, about]) => ({ id, name, about }))
136
+
137
+ // Voices of its library an account speaks in by id, as it does the premade.
138
+ // https://elevenlabs.io/voices/sd63ZkbzEI8aQTTWX7VK
139
+ let LIBRARY: Voice[] = [{
140
+ id: 'sd63ZkbzEI8aQTTWX7VK',
141
+ name: 'Jon',
142
+ about: 'rich, expressive, natural and conversational; American',
143
+ }]
144
+
145
+ export let ELEVENLABS: Provider = {
146
+ name: 'elevenlabs',
147
+ title: 'ElevenLabs',
148
+ api: 'https://api.elevenlabs.io',
149
+ live: 'wss://api.elevenlabs.io',
150
+ header: 'xi-api-key',
151
+ authorization: (key) => key,
152
+ protocols: () => [],
153
+ hear: {
154
+ model: 'scribe_v3',
155
+ perMinute: 0.20 / 60,
156
+ speakers: true,
157
+ // Its limit is 5 GB, sent whole in a form.
158
+ bytes: 5 * 1024 ** 3,
159
+ request: (audio, type, model) => ({
160
+ path: '/v1/speech-to-text',
161
+ init: audioForm(
162
+ {
163
+ model_id: model,
164
+ diarize: 'true',
165
+ tag_audio_events: 'false',
166
+ },
167
+ audio,
168
+ type,
169
+ ),
170
+ }),
171
+ read: (said) => {
172
+ let { text, words, audio_duration_secs } = said as {
173
+ text?: string
174
+ words?: Word[]
175
+ audio_duration_secs?: number
176
+ }
177
+ return {
178
+ text: text ?? '',
179
+ seconds: audio_duration_secs ??
180
+ words?.findLast((w) => w.end != null)?.end,
181
+ ...words?.length ? { turns: turnsOf(words) } : {},
182
+ }
183
+ },
184
+ },
185
+ turns: [],
186
+ speak: {
187
+ voice: PREMADE[0].id,
188
+ voices: [...PREMADE, ...LIBRARY],
189
+ // https://elevenlabs.io/docs/api-reference/text-to-speech/convert
190
+ // (voice_settings.speed)
191
+ speeds: { min: 0.7, max: 1.2 },
192
+ models: [
193
+ { model: 'eleven_v4', perThousand: 0.08 },
194
+ { model: 'eleven_multilingual_v2', perThousand: 0.08 },
195
+ { model: 'eleven_flash_v2_5', perThousand: 0.04 },
196
+ { model: 'eleven_v4_turbo', perThousand: 0.04 },
197
+ { model: 'eleven_v3_conversational', perThousand: 0.04 },
198
+ ],
199
+ request: (text, voice, format, speed, model) => ({
200
+ path: `/v1/text-to-speech/${encodeURIComponent(voice)}?${
201
+ query({ output_format: output(format) })
202
+ }`,
203
+ init: {
204
+ method: 'POST',
205
+ headers: { 'content-type': 'application/json' },
206
+ body: JSON.stringify({
207
+ text,
208
+ model_id: model,
209
+ ...speed == 1 ? {} : { voice_settings: { speed } },
210
+ }),
211
+ },
212
+ }),
213
+ },
214
+ voices: {
215
+ request: (page) => ({
216
+ path: `/v2/voices?${
217
+ query({
218
+ page_size: 100,
219
+ include_total_count: 'false',
220
+ next_page_token: page,
221
+ })
222
+ }`,
223
+ init: {},
224
+ }),
225
+ read: (said) => {
226
+ let { voices, has_more, next_page_token } = said as {
227
+ voices?: Listed[]
228
+ has_more?: boolean
229
+ next_page_token?: string | null
230
+ }
231
+ return {
232
+ voices: (voices ?? []).map(voiceOf),
233
+ ...has_more && next_page_token ? { next: next_page_token } : {},
234
+ }
235
+ },
236
+ },
237
+ make: {
238
+ design: (description, text) => ({
239
+ path: '/v1/text-to-voice/design?output_format=mp3_44100_128',
240
+ init: {
241
+ method: 'POST',
242
+ headers: { 'content-type': 'application/json' },
243
+ body: JSON.stringify({
244
+ voice_description: description,
245
+ ...text ? { text } : { auto_generate_text: true },
246
+ }),
247
+ },
248
+ }),
249
+ designs: (said) =>
250
+ ((said as {
251
+ previews?: {
252
+ generated_voice_id: string
253
+ audio_base_64: string
254
+ media_type?: string
255
+ duration_secs?: number
256
+ }[]
257
+ }).previews ?? []).map((p) => ({
258
+ id: p.generated_voice_id,
259
+ audio: unbase64(p.audio_base_64),
260
+ type: p.media_type ?? 'audio/mpeg',
261
+ seconds: p.duration_secs ?? 0,
262
+ })),
263
+ keep: (design, name, description) => ({
264
+ path: '/v1/text-to-voice',
265
+ init: {
266
+ method: 'POST',
267
+ headers: { 'content-type': 'application/json' },
268
+ body: JSON.stringify({
269
+ voice_name: name,
270
+ voice_description: description,
271
+ generated_voice_id: design,
272
+ }),
273
+ },
274
+ }),
275
+ clone: (name, samples, description) => {
276
+ let form = new FormData()
277
+ form.set('name', name)
278
+ if (description) form.set('description', description)
279
+ samples.forEach((s, n) => form.append('files', s, `sample-${n + 1}`))
280
+ return { path: '/v1/voices/add', init: { method: 'POST', body: form } }
281
+ },
282
+ made: (said) => String((said as { voice_id?: string }).voice_id ?? ''),
283
+ },
284
+ }