-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio.go
More file actions
449 lines (378 loc) · 13.3 KB
/
audio.go
File metadata and controls
449 lines (378 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package ai
import (
"context"
"fmt"
"os"
)
// ═══════════════════════════════════════════════════════════════════════════
// Audio Models
// ═══════════════════════════════════════════════════════════════════════════
// TTSModel represents a text-to-speech model identifier.
type TTSModel string
const (
// OpenAI TTS Models
TTSTTS1 TTSModel = "tts-1" // Standard quality, faster
TTSTTS1HD TTSModel = "tts-1-hd" // High definition, slower
TTSGpt4oAudio TTSModel = "gpt-4o-mini-tts" // GPT-4o audio
// Google TTS (via Gemini)
TTSGemini TTSModel = "gemini-2.5-flash-preview-tts"
)
// STTModel represents a speech-to-text model identifier.
type STTModel string
const (
// OpenAI STT Models
STTWhisper1 STTModel = "whisper-1"
STTGpt4oAudio STTModel = "gpt-4o-transcribe"
// Google STT (via Gemini)
STTGemini STTModel = "gemini-2.5-flash-preview-stt"
)
// Voice represents a TTS voice identifier.
type Voice string
const (
// OpenAI Voices
VoiceAlloy Voice = "alloy"
VoiceAsh Voice = "ash"
VoiceBallad Voice = "ballad"
VoiceCoral Voice = "coral"
VoiceEcho Voice = "echo"
VoiceFable Voice = "fable"
VoiceOnyx Voice = "onyx"
VoiceNova Voice = "nova"
VoiceSage Voice = "sage"
VoiceShimmer Voice = "shimmer"
VoiceVerse Voice = "verse"
)
// AudioFormat represents the output audio format.
type AudioFormat string
const (
AudioFormatMP3 AudioFormat = "mp3"
AudioFormatOpus AudioFormat = "opus"
AudioFormatAAC AudioFormat = "aac"
AudioFormatFLAC AudioFormat = "flac"
AudioFormatWAV AudioFormat = "wav"
AudioFormatPCM AudioFormat = "pcm"
)
// DefaultTTSModel is the default text-to-speech model used by Speak.
// DefaultSTTModel is the default speech-to-text model used by Transcribe.
// DefaultVoice is the default voice used by Speak.
// DefaultAudioFormat is the default audio format used by Speak.
var (
DefaultTTSModel = TTSTTS1
DefaultSTTModel = STTWhisper1
DefaultVoice = VoiceAlloy
DefaultAudioFormat = AudioFormatMP3
)
// ═══════════════════════════════════════════════════════════════════════════
// TTS Request/Response
// ═══════════════════════════════════════════════════════════════════════════
// TTSRequest is a provider-agnostic request for text-to-speech.
type TTSRequest struct {
Model string
Input string // text to speak
Voice string // voice ID
Format string // output format
Speed float64 // 0.25 to 4.0 (1.0 is default)
}
// TTSResponse is a provider-agnostic response from text-to-speech.
type TTSResponse struct {
Audio []byte // raw audio data
Format string
ContentType string
}
// ═══════════════════════════════════════════════════════════════════════════
// STT Request/Response
// ═══════════════════════════════════════════════════════════════════════════
// STTRequest is a provider-agnostic request for speech-to-text.
type STTRequest struct {
Model string
Audio []byte // audio data
AudioURL string // or audio URL
Filename string // filename for format detection
Language string // optional: language hint (ISO 639-1)
Prompt string // optional: context/prompt to guide transcription
Temperature float64
Timestamps bool // include word-level timestamps
}
// STTResponse is a provider-agnostic response from speech-to-text.
type STTResponse struct {
Text string
Language string
Duration float64 // audio duration in seconds
Words []WordTimestamp
}
// WordTimestamp represents a word with timing information.
type WordTimestamp struct {
Word string
Start float64 // seconds
End float64 // seconds
}
// ═══════════════════════════════════════════════════════════════════════════
// TTS Builder - Fluent API
// ═══════════════════════════════════════════════════════════════════════════
// TTSBuilder provides a fluent API for text-to-speech.
type TTSBuilder struct {
model TTSModel
text string
voice Voice
format AudioFormat
speed float64
client *Client
ctx context.Context
}
// Speak creates a new TTSBuilder.
func Speak(text string) *TTSBuilder {
return &TTSBuilder{
model: DefaultTTSModel,
text: text,
voice: DefaultVoice,
format: DefaultAudioFormat,
speed: 1.0,
}
}
// Model sets the TTS model.
func (t *TTSBuilder) Model(model TTSModel) *TTSBuilder {
t.model = model
return t
}
// Voice sets the voice.
func (t *TTSBuilder) Voice(voice Voice) *TTSBuilder {
t.voice = voice
return t
}
// Format sets the output audio format.
func (t *TTSBuilder) Format(format AudioFormat) *TTSBuilder {
t.format = format
return t
}
// Speed sets the speech speed (0.25 to 4.0).
func (t *TTSBuilder) Speed(speed float64) *TTSBuilder {
if speed < 0.25 {
speed = 0.25
}
if speed > 4.0 {
speed = 4.0
}
t.speed = speed
return t
}
// HD switches to the high-definition TTS model.
func (t *TTSBuilder) HD() *TTSBuilder {
t.model = TTSTTS1HD
return t
}
// WithClient sets a specific client/provider to execute the request with.
func (t *TTSBuilder) WithClient(client *Client) *TTSBuilder {
t.client = client
return t
}
// WithContext sets a context for cancellation.
func (t *TTSBuilder) WithContext(ctx context.Context) *TTSBuilder {
t.ctx = ctx
return t
}
// ═══════════════════════════════════════════════════════════════════════════
// TTS Execution
// ═══════════════════════════════════════════════════════════════════════════
// Do generates audio and returns raw bytes.
func (t *TTSBuilder) Do() ([]byte, error) {
resp, err := t.DoWithMeta()
if err != nil {
return nil, err
}
return resp.Audio, nil
}
// DoWithMeta generates audio and returns the full response.
func (t *TTSBuilder) DoWithMeta() (*TTSResponse, error) {
client := t.client
if client == nil {
client = getDefaultClient()
}
ctx := t.ctx
if ctx == nil {
ctx = context.Background()
}
// Check if provider supports TTS
audioProvider, ok := client.provider.(AudioProvider)
if !ok {
return nil, fmt.Errorf("provider %s does not support text-to-speech", client.provider.Name())
}
req := &TTSRequest{
Model: string(t.model),
Input: t.text,
Voice: string(t.voice),
Format: string(t.format),
Speed: t.speed,
}
if Debug {
fmt.Printf("%s TTS: %d chars → %s voice, %s format\n",
colorCyan("→"), len(t.text), t.voice, t.format)
}
waitForRateLimit()
resp, err := audioProvider.TextToSpeech(ctx, req)
if err != nil {
return nil, err
}
if Debug {
fmt.Printf("%s Generated %d bytes of audio\n", colorGreen("✓"), len(resp.Audio))
}
return resp, nil
}
// Save generates audio and saves it to a file.
func (t *TTSBuilder) Save(path string) error {
audio, err := t.Do()
if err != nil {
return err
}
if err := os.WriteFile(path, audio, 0644); err != nil {
return fmt.Errorf("failed to save audio: %w", err)
}
if Debug {
fmt.Printf("%s Saved audio to %s\n", colorGreen("✓"), path)
}
return nil
}
// ═══════════════════════════════════════════════════════════════════════════
// STT Builder - Fluent API
// ═══════════════════════════════════════════════════════════════════════════
// STTBuilder provides a fluent API for speech-to-text
type STTBuilder struct {
model STTModel
audio []byte
audioURL string
filename string
language string
prompt string
temperature float64
timestamps bool
client *Client
ctx context.Context
}
// Transcribe creates a new STT builder from a file path
func Transcribe(path string) *STTBuilder {
audio, err := os.ReadFile(path)
if err != nil {
fmt.Printf("%s Error loading audio %s: %v\n", colorRed("✗"), path, err)
return &STTBuilder{model: DefaultSTTModel}
}
return &STTBuilder{
model: DefaultSTTModel,
audio: audio,
filename: path,
}
}
// TranscribeBytes creates a new STT builder from audio bytes
func TranscribeBytes(audio []byte, filename string) *STTBuilder {
return &STTBuilder{
model: DefaultSTTModel,
audio: audio,
filename: filename,
}
}
// TranscribeURL creates a new STT builder from an audio URL
func TranscribeURL(url string) *STTBuilder {
return &STTBuilder{
model: DefaultSTTModel,
audioURL: url,
}
}
// Model sets the STT model
func (s *STTBuilder) Model(model STTModel) *STTBuilder {
s.model = model
return s
}
// Language sets the language hint (ISO 639-1 code, e.g., "en", "es", "fr")
func (s *STTBuilder) Language(lang string) *STTBuilder {
s.language = lang
return s
}
// Prompt sets context to guide transcription
func (s *STTBuilder) Prompt(prompt string) *STTBuilder {
s.prompt = prompt
return s
}
// Temperature sets the sampling temperature (0 to 1)
func (s *STTBuilder) Temperature(temp float64) *STTBuilder {
s.temperature = temp
return s
}
// WithTimestamps enables word-level timestamps
func (s *STTBuilder) WithTimestamps() *STTBuilder {
s.timestamps = true
return s
}
// WithClient sets a specific client/provider
func (s *STTBuilder) WithClient(client *Client) *STTBuilder {
s.client = client
return s
}
// WithContext sets a context for cancellation
func (s *STTBuilder) WithContext(ctx context.Context) *STTBuilder {
s.ctx = ctx
return s
}
// ═══════════════════════════════════════════════════════════════════════════
// STT Execution
// ═══════════════════════════════════════════════════════════════════════════
// Do transcribes the audio and returns text
func (s *STTBuilder) Do() (string, error) {
resp, err := s.DoWithMeta()
if err != nil {
return "", err
}
return resp.Text, nil
}
// DoWithMeta transcribes audio and returns full response
func (s *STTBuilder) DoWithMeta() (*STTResponse, error) {
client := s.client
if client == nil {
client = getDefaultClient()
}
ctx := s.ctx
if ctx == nil {
ctx = context.Background()
}
// Check if provider supports STT
audioProvider, ok := client.provider.(AudioProvider)
if !ok {
return nil, fmt.Errorf("provider %s does not support speech-to-text", client.provider.Name())
}
req := &STTRequest{
Model: string(s.model),
Audio: s.audio,
AudioURL: s.audioURL,
Filename: s.filename,
Language: s.language,
Prompt: s.prompt,
Temperature: s.temperature,
Timestamps: s.timestamps,
}
if Debug {
fmt.Printf("%s STT: %d bytes audio, model=%s\n",
colorCyan("→"), len(s.audio), s.model)
}
waitForRateLimit()
resp, err := audioProvider.SpeechToText(ctx, req)
if err != nil {
return nil, err
}
if Debug {
fmt.Printf("%s Transcribed: %d chars, duration=%.1fs\n",
colorGreen("✓"), len(resp.Text), resp.Duration)
}
return resp, nil
}
// ═══════════════════════════════════════════════════════════════════════════
// Provider-Specific Shortcuts
// ═══════════════════════════════════════════════════════════════════════════
// Speak creates a TTS builder using this client
func (c *Client) Speak(text string) *TTSBuilder {
return Speak(text).WithClient(c)
}
// Transcribe creates an STT builder using this client
func (c *Client) Transcribe(path string) *STTBuilder {
return Transcribe(path).WithClient(c)
}
// TranscribeBytes creates an STT builder from bytes using this client
func (c *Client) TranscribeBytes(audio []byte, filename string) *STTBuilder {
return TranscribeBytes(audio, filename).WithClient(c)
}