@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/deepgram.ts ADDED
@@ -0,0 +1,497 @@
1
+ // Deepgram: Nova-3 hears a recording or a stream and tells its speakers
2
+ // apart, Flux hears a call and knows when a speaker's turn ends, Aura-2
3
+ // speaks. It has no model that talks, so a call runs on it as hearing and
4
+ // speaking around another model. Flux tells no speakers apart. Prices are its
5
+ // pay-as-you-go list, 2026-11-05; telling a recording's speakers apart is in
6
+ // its price, a stream's is $0.0020 a minute more (2026-11-13).
7
+ // https://developers.deepgram.com/reference/speech-to-text/listen-pre-recorded
8
+ // https://developers.deepgram.com/docs/diarization
9
+ // https://developers.deepgram.com/docs/utterances
10
+ // https://developers.deepgram.com/docs/nova-quickstart
11
+ // https://developers.deepgram.com/reference/text-to-speech/speak-request
12
+ // https://developers.deepgram.com/docs/flux/quickstart
13
+ // https://developers.deepgram.com/reference/speech-to-text/listen-flux
14
+ // https://developers.deepgram.com/reference/speech-to-text/listen-streaming
15
+ // https://deepgram.com/pricing
16
+ import type { Cue, Format, Provider, Turn } from './mod.ts'
17
+ import { query } from './query.js'
18
+
19
+ let encoded = (format: Format) =>
20
+ format.encoding == 'mp3'
21
+ ? { encoding: 'mp3' }
22
+ : { encoding: format.encoding, sample_rate: format.rate }
23
+
24
+ type Listened = {
25
+ metadata?: { duration?: number }
26
+ results?: {
27
+ channels?: { alternatives?: { transcript?: string }[] }[]
28
+ utterances?: {
29
+ speaker?: number
30
+ transcript?: string
31
+ start: number
32
+ end: number
33
+ }[]
34
+ }
35
+ }
36
+
37
+ type Info = {
38
+ type?: string
39
+ event?: string
40
+ transcript?: string
41
+ turn_index?: number
42
+ description?: string
43
+ audio_window_start?: number | string
44
+ audio_window_end?: number | string
45
+ }
46
+
47
+ /**
48
+ * What one message from Flux means: a turn starting, a turn ended with its
49
+ * words and the stretch of the stream it took, or nothing to act on.
50
+ *
51
+ * ```ts
52
+ * import { equal } from '@yaks/testing'
53
+ * import { DEEPGRAM } from '@yaks/speech'
54
+ * let read = DEEPGRAM.turns[0].reader()
55
+ * equal(
56
+ * read(JSON.stringify({
57
+ * type: 'TurnInfo',
58
+ * event: 'EndOfTurn',
59
+ * transcript: 'Hi',
60
+ * audio_window_start: '1.5',
61
+ * audio_window_end: '2.25',
62
+ * })),
63
+ * { ended: [{ speaker: 0, text: 'Hi', from: 1.5, to: 2.25 }] },
64
+ * )
65
+ * equal(read('{"type":"TurnInfo","event":"StartOfTurn"}'), { start: true })
66
+ * equal(read('{"type":"TurnInfo","event":"Update"}'), {})
67
+ * ```
68
+ */
69
+ let cueOf = (data: unknown): Cue => {
70
+ let info: Info
71
+ try {
72
+ info = JSON.parse(String(data))
73
+ } catch {
74
+ return {}
75
+ }
76
+ if (info.type == 'Error') return { error: String(info.description) }
77
+ if (info.type != 'TurnInfo') return {}
78
+ if (info.event == 'StartOfTurn') return { start: true }
79
+ let key = info.turn_index == null ? {} : { key: String(info.turn_index) }
80
+ if (info.event == 'Update' && info.transcript != null) {
81
+ return { hearing: { text: info.transcript, ...key } }
82
+ }
83
+ if (info.event != 'EndOfTurn') return {}
84
+ // Flux words the seconds of the stream a turn took as strings.
85
+ let from = Number(info.audio_window_start), to = Number(info.audio_window_end)
86
+ let end = { speaker: 0, text: info.transcript?.trim() ?? '', ...key }
87
+ return { ended: [isNaN(from + to) ? end : { ...end, from, to }] }
88
+ }
89
+
90
+ type Word = {
91
+ word: string
92
+ punctuated_word?: string
93
+ start: number
94
+ end: number
95
+ speaker?: number
96
+ }
97
+
98
+ type Results = {
99
+ type?: string
100
+ description?: string
101
+ is_final?: boolean
102
+ speech_final?: boolean
103
+ from_finalize?: boolean
104
+ channel?: { alternatives?: { words?: Word[] }[] }
105
+ }
106
+
107
+ // Words in a row, a turn each time the speaker changes.
108
+ let spoken = (words: Word[]): Turn[] =>
109
+ words.reduce((turns: Turn[], w) => {
110
+ let speaker = w.speaker ?? 0, text = w.punctuated_word ?? w.word
111
+ let last = turns.at(-1)
112
+ if (last?.speaker == speaker) {
113
+ last.text += ' ' + text
114
+ last.to = w.end
115
+ } else turns.push({ speaker, text, from: w.start, to: w.end })
116
+ return turns
117
+ }, [])
118
+
119
+ /**
120
+ * What reads one Nova-3 stream: its final words are kept until a pause ends
121
+ * them (`speech_final`), or the stream is flushed or ends, and a speaker's
122
+ * turn ends sooner when another starts.
123
+ *
124
+ * ```ts
125
+ * import { equal } from '@yaks/testing'
126
+ * import { DEEPGRAM, streamOf } from '@yaks/speech'
127
+ * let read = streamOf(DEEPGRAM, 'nova-3').reader()
128
+ * let said = (words: [string, number, number, number][], end = false) =>
129
+ * JSON.stringify({
130
+ * type: 'Results',
131
+ * is_final: true,
132
+ * speech_final: end,
133
+ * channel: {
134
+ * alternatives: [{
135
+ * words: words.map(([w, speaker, start, end]) => ({
136
+ * word: w.toLowerCase(),
137
+ * punctuated_word: w,
138
+ * speaker,
139
+ * start,
140
+ * end,
141
+ * })),
142
+ * }],
143
+ * },
144
+ * })
145
+ * equal(read(said([['I', 0, 0, 0.2], ['move', 0, 0.2, 0.5]])), { ended: [] })
146
+ * equal(read(said([['approval.', 0, 0.5, 1], ['Second.', 1, 1.5, 2]])), {
147
+ * ended: [{ speaker: 0, text: 'I move approval.', from: 0, to: 1 }],
148
+ * })
149
+ * equal(read(said([], true)), {
150
+ * ended: [{ speaker: 1, text: 'Second.', from: 1.5, to: 2 }],
151
+ * })
152
+ * ```
153
+ */
154
+ let listening = () => {
155
+ let held: Word[] = []
156
+ return (data: unknown): Cue => {
157
+ let r: Results
158
+ try {
159
+ r = JSON.parse(String(data))
160
+ } catch {
161
+ return {}
162
+ }
163
+ if (r.type == 'Error') return { error: String(r.description) }
164
+ if (r.type == 'Metadata') return { ended: spoken(held.splice(0)) }
165
+ if (r.type != 'Results' || !r.is_final) return {}
166
+ held.push(...r.channel?.alternatives?.[0]?.words ?? [])
167
+ if (r.speech_final || r.from_finalize) {
168
+ return { ended: spoken(held.splice(0)) }
169
+ }
170
+ // Every speaker before the one still talking has finished.
171
+ let talking = held.at(-1)?.speaker
172
+ let since = held.findLastIndex((w) => w.speaker != talking) + 1
173
+ return { ended: spoken(held.splice(0, since)) }
174
+ }
175
+ }
176
+
177
+ export let DEEPGRAM: Provider = {
178
+ name: 'deepgram',
179
+ title: 'Deepgram',
180
+ api: 'https://api.deepgram.com',
181
+ live: 'wss://api.deepgram.com',
182
+ authorization: (key) => `token ${key}`,
183
+ protocols: (key) => ['token', key],
184
+ hear: {
185
+ model: 'nova-3',
186
+ perMinute: 0.0043,
187
+ speakers: true,
188
+ // Its pre-recorded limit. The body may be a stream, sent as it is read.
189
+ bytes: 2 * 1024 ** 3,
190
+ // Each of its utterances is one speaker's words up to a pause.
191
+ request: (audio, type, model) => ({
192
+ path: `/v1/listen?${
193
+ query({
194
+ model,
195
+ smart_format: 'true',
196
+ diarize_model: 'latest',
197
+ utterances: 'true',
198
+ })
199
+ }`,
200
+ init: { method: 'POST', headers: { 'content-type': type }, body: audio },
201
+ }),
202
+ read: (said) => {
203
+ let { metadata, results } = said as Listened
204
+ return {
205
+ text: results?.channels?.[0]?.alternatives?.[0]?.transcript ?? '',
206
+ seconds: metadata?.duration ?? 0,
207
+ turns: results?.utterances?.map((u) => ({
208
+ speaker: u.speaker ?? 0,
209
+ text: u.transcript?.trim() ?? '',
210
+ from: u.start,
211
+ to: u.end,
212
+ })).filter((turn) => turn.text),
213
+ }
214
+ },
215
+ },
216
+ turns: [{
217
+ model: 'flux-general-en',
218
+ perMinute: 0.0077,
219
+ speakers: false,
220
+ // Flux's lowest end-of-turn confidence, 0.5 against its default 0.7:
221
+ // measured on spoken questions in a call's μ-law, the turn ended a median
222
+ // 0.22 s after the last word instead of 1.0 s, none of 12 cut short.
223
+ path: (format, model) =>
224
+ `/v2/listen?${query({ model, ...encoded(format), eot_threshold: 0.5 })}`,
225
+ opening: () => [],
226
+ audio: (bytes) => bytes,
227
+ reader: () => cueOf,
228
+ closing: JSON.stringify({ type: 'CloseStream' }),
229
+ }, {
230
+ // A meeting's: Nova-3 tells its speakers apart, at its listed $0.0077 a
231
+ // minute (a promotion has it at $0.0048 for now) and $0.0020 for the
232
+ // speakers, and a turn ends at a second's pause or another's voice.
233
+ model: 'nova-3',
234
+ perMinute: 0.0097,
235
+ speakers: true,
236
+ path: (format, model) =>
237
+ `/v1/listen?${
238
+ query({
239
+ model,
240
+ ...encoded(format),
241
+ smart_format: 'true',
242
+ diarize_model: 'latest',
243
+ endpointing: 1000,
244
+ })
245
+ }`,
246
+ opening: () => [],
247
+ audio: (bytes) => bytes,
248
+ reader: listening,
249
+ closing: JSON.stringify({ type: 'CloseStream' }),
250
+ }],
251
+ speak: {
252
+ voice: 'aura-2-thalia-en',
253
+ // Aura-2's English voices, as its voice list describes them.
254
+ // https://developers.deepgram.com/docs/tts-models
255
+ voices: [
256
+ {
257
+ id: 'aura-2-amalthea-en',
258
+ name: 'Amalthea',
259
+ about: 'feminine, Filipino, engaging, natural, cheerful',
260
+ },
261
+ {
262
+ id: 'aura-2-andromeda-en',
263
+ name: 'Andromeda',
264
+ about: 'feminine, American, casual, expressive, comfortable',
265
+ },
266
+ {
267
+ id: 'aura-2-apollo-en',
268
+ name: 'Apollo',
269
+ about: 'masculine, American, confident, comfortable, casual',
270
+ },
271
+ {
272
+ id: 'aura-2-arcas-en',
273
+ name: 'Arcas',
274
+ about: 'masculine, American, natural, smooth, clear, comfortable',
275
+ },
276
+ {
277
+ id: 'aura-2-aries-en',
278
+ name: 'Aries',
279
+ about: 'masculine, American, warm, energetic, caring',
280
+ },
281
+ {
282
+ id: 'aura-2-asteria-en',
283
+ name: 'Asteria',
284
+ about: 'feminine, American, clear, confident, knowledgeable, energetic',
285
+ },
286
+ {
287
+ id: 'aura-2-athena-en',
288
+ name: 'Athena',
289
+ about: 'feminine, American, calm, smooth, professional',
290
+ },
291
+ {
292
+ id: 'aura-2-atlas-en',
293
+ name: 'Atlas',
294
+ about:
295
+ 'masculine, American, enthusiastic, confident, approachable, friendly',
296
+ },
297
+ {
298
+ id: 'aura-2-aurora-en',
299
+ name: 'Aurora',
300
+ about: 'feminine, American, cheerful, expressive, energetic',
301
+ },
302
+ {
303
+ id: 'aura-2-callista-en',
304
+ name: 'Callista',
305
+ about: 'feminine, American, clear, energetic, professional, smooth',
306
+ },
307
+ {
308
+ id: 'aura-2-cora-en',
309
+ name: 'Cora',
310
+ about: 'feminine, American, smooth, melodic, caring',
311
+ },
312
+ {
313
+ id: 'aura-2-cordelia-en',
314
+ name: 'Cordelia',
315
+ about: 'feminine, American, approachable, warm, polite',
316
+ },
317
+ {
318
+ id: 'aura-2-delia-en',
319
+ name: 'Delia',
320
+ about: 'feminine, American, casual, friendly, cheerful, breathy',
321
+ },
322
+ {
323
+ id: 'aura-2-draco-en',
324
+ name: 'Draco',
325
+ about: 'masculine, British, warm, approachable, trustworthy, baritone',
326
+ },
327
+ {
328
+ id: 'aura-2-electra-en',
329
+ name: 'Electra',
330
+ about: 'feminine, American, professional, engaging, knowledgeable',
331
+ },
332
+ {
333
+ id: 'aura-2-harmonia-en',
334
+ name: 'Harmonia',
335
+ about: 'feminine, American, empathetic, clear, calm, confident',
336
+ },
337
+ {
338
+ id: 'aura-2-helena-en',
339
+ name: 'Helena',
340
+ about: 'feminine, American, caring, natural, positive, friendly, raspy',
341
+ },
342
+ {
343
+ id: 'aura-2-hera-en',
344
+ name: 'Hera',
345
+ about: 'feminine, American, smooth, warm, professional',
346
+ },
347
+ {
348
+ id: 'aura-2-hermes-en',
349
+ name: 'Hermes',
350
+ about: 'masculine, American, expressive, engaging, professional',
351
+ },
352
+ {
353
+ id: 'aura-2-hyperion-en',
354
+ name: 'Hyperion',
355
+ about: 'masculine, Australian, caring, warm, empathetic',
356
+ },
357
+ {
358
+ id: 'aura-2-iris-en',
359
+ name: 'Iris',
360
+ about: 'feminine, American, cheerful, positive, approachable',
361
+ },
362
+ {
363
+ id: 'aura-2-janus-en',
364
+ name: 'Janus',
365
+ about: 'feminine, American, Southern, smooth, trustworthy',
366
+ },
367
+ {
368
+ id: 'aura-2-juno-en',
369
+ name: 'Juno',
370
+ about: 'feminine, American, natural, engaging, melodic, breathy',
371
+ },
372
+ {
373
+ id: 'aura-2-jupiter-en',
374
+ name: 'Jupiter',
375
+ about: 'masculine, American, expressive, knowledgeable, baritone',
376
+ },
377
+ {
378
+ id: 'aura-2-luna-en',
379
+ name: 'Luna',
380
+ about: 'feminine, American, friendly, natural, engaging',
381
+ },
382
+ {
383
+ id: 'aura-2-mars-en',
384
+ name: 'Mars',
385
+ about: 'masculine, American, smooth, patient, trustworthy, baritone',
386
+ },
387
+ {
388
+ id: 'aura-2-minerva-en',
389
+ name: 'Minerva',
390
+ about: 'feminine, American, positive, friendly, natural',
391
+ },
392
+ {
393
+ id: 'aura-2-neptune-en',
394
+ name: 'Neptune',
395
+ about: 'masculine, American, professional, patient, polite',
396
+ },
397
+ {
398
+ id: 'aura-2-odysseus-en',
399
+ name: 'Odysseus',
400
+ about: 'masculine, American, calm, smooth, comfortable, professional',
401
+ },
402
+ {
403
+ id: 'aura-2-ophelia-en',
404
+ name: 'Ophelia',
405
+ about: 'feminine, American, expressive, enthusiastic, cheerful',
406
+ },
407
+ {
408
+ id: 'aura-2-orion-en',
409
+ name: 'Orion',
410
+ about: 'masculine, American, approachable, comfortable, calm, polite',
411
+ },
412
+ {
413
+ id: 'aura-2-orpheus-en',
414
+ name: 'Orpheus',
415
+ about:
416
+ 'masculine, American, professional, clear, confident, trustworthy',
417
+ },
418
+ {
419
+ id: 'aura-2-pandora-en',
420
+ name: 'Pandora',
421
+ about: 'feminine, British, smooth, calm, melodic, breathy',
422
+ },
423
+ {
424
+ id: 'aura-2-phoebe-en',
425
+ name: 'Phoebe',
426
+ about: 'feminine, American, energetic, warm, casual',
427
+ },
428
+ {
429
+ id: 'aura-2-pluto-en',
430
+ name: 'Pluto',
431
+ about: 'masculine, American, smooth, calm, empathetic, baritone',
432
+ },
433
+ {
434
+ id: 'aura-2-saturn-en',
435
+ name: 'Saturn',
436
+ about: 'masculine, American, knowledgeable, confident, baritone',
437
+ },
438
+ {
439
+ id: 'aura-2-selene-en',
440
+ name: 'Selene',
441
+ about: 'feminine, American, expressive, engaging, energetic',
442
+ },
443
+ {
444
+ id: 'aura-2-thalia-en',
445
+ name: 'Thalia',
446
+ about: 'feminine, American, clear, confident, energetic, enthusiastic',
447
+ },
448
+ {
449
+ id: 'aura-2-theia-en',
450
+ name: 'Theia',
451
+ about: 'feminine, Australian, expressive, polite, sincere',
452
+ },
453
+ {
454
+ id: 'aura-2-vesta-en',
455
+ name: 'Vesta',
456
+ about: 'feminine, American, natural, expressive, patient, empathetic',
457
+ },
458
+ {
459
+ id: 'aura-2-zeus-en',
460
+ name: 'Zeus',
461
+ about: 'masculine, American, deep, trustworthy, smooth',
462
+ },
463
+ ],
464
+ // https://developers.deepgram.com/docs/tts-voice-controls
465
+ speeds: { min: 0.7, max: 1.5 },
466
+ // Aura-2's model is named by its voice's id.
467
+ models: [{ model: 'aura-2', perThousand: 0.030 }],
468
+ request: (text, voice, format, speed) => ({
469
+ path: `/v1/speak?${
470
+ query({
471
+ model: voice,
472
+ ...encoded(format),
473
+ ...speed == 1 ? {} : { speed: String(speed) },
474
+ ...format.encoding == 'mp3' ? {} : { container: 'none' },
475
+ })
476
+ }`,
477
+ init: {
478
+ method: 'POST',
479
+ headers: { 'content-type': 'application/json' },
480
+ body: JSON.stringify({ text }),
481
+ },
482
+ }),
483
+ },
484
+ balance: async (ask) => {
485
+ let { projects } = await (await ask('/v1/projects')).json() as {
486
+ projects?: { project_id: string }[]
487
+ }
488
+ let total = 0
489
+ for (let { project_id } of projects ?? []) {
490
+ let { balances } = await (await ask(
491
+ `/v1/projects/${project_id}/balances`,
492
+ )).json() as { balances?: { amount?: number }[] }
493
+ for (let b of balances ?? []) total += b.amount ?? 0
494
+ }
495
+ return total
496
+ },
497
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/speech","version":"0.2.36","license":"Apache-2.0","description":"Speech to text, text to speech and speech to speech, each provider given as data: Deepgram, OpenAI and ElevenLabs, their endpoints, models, voices and prices.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./ui":"./ui.ts"},"imports":{"@yaks/speech":"./mod.ts","@yaks/speech/vocab":"./vocab.ts","@yaks/speech/ui":"./ui.ts"}}