-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathaudio.go
More file actions
216 lines (190 loc) · 6.16 KB
/
Copy pathaudio.go
File metadata and controls
216 lines (190 loc) · 6.16 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
package openrouter
import (
"context"
"encoding/base64"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
const (
audioSpeechSuffix = "/audio/speech"
audioTranscriptionsSuffix = "/audio/transcriptions"
)
// SpeechResponseFormat controls the audio container returned by the speech endpoint.
type SpeechResponseFormat string
const (
SpeechResponseFormatMp3 SpeechResponseFormat = "mp3"
SpeechResponseFormatPcm SpeechResponseFormat = "pcm"
)
// AudioProvider contains provider-specific passthrough options keyed by provider slug.
type AudioProvider struct {
Options map[string]map[string]any `json:"options,omitempty"`
}
// SpeechRequest represents a request to the /audio/speech endpoint.
//
// API reference: https://openrouter.ai/docs/api/api-reference/speech/create-audio-speech
type SpeechRequest struct {
// Model is the TTS model slug to use.
Model string `json:"model"`
// Input is the text to synthesize.
Input string `json:"input"`
// Voice is the provider-specific voice identifier.
Voice string `json:"voice"`
// ResponseFormat controls the returned audio format. Defaults to pcm when omitted.
ResponseFormat SpeechResponseFormat `json:"response_format,omitempty"`
// Speed controls playback speed for providers that support it.
Speed float64 `json:"speed,omitempty"`
// Provider contains provider-specific passthrough options.
Provider *AudioProvider `json:"provider,omitempty"`
}
// SpeechResponse contains raw audio bytes and selected response headers from /audio/speech.
type SpeechResponse struct {
Audio []byte
ContentType string
GenerationID string
}
// TranscriptionInputAudio is base64-encoded audio input for /audio/transcriptions.
type TranscriptionInputAudio struct {
Data string `json:"data"`
Format AudioFormat `json:"format"`
}
// TranscriptionRequest represents a request to the /audio/transcriptions endpoint.
//
// API reference: https://openrouter.ai/docs/api/api-reference/transcriptions/create-audio-transcriptions
type TranscriptionRequest struct {
// Model is the STT model slug to use.
Model string `json:"model"`
// InputAudio is base64-encoded audio to transcribe.
InputAudio TranscriptionInputAudio `json:"input_audio"`
// Language is an optional ISO-639-1 language code. The API auto-detects language when omitted.
Language string `json:"language,omitempty"`
// Temperature controls sampling temperature for transcription. Use a pointer to send an explicit zero.
Temperature *float64 `json:"temperature,omitempty"`
// Provider contains provider-specific passthrough options.
Provider *AudioProvider `json:"provider,omitempty"`
}
// TranscriptionUsage contains usage and billing details returned by /audio/transcriptions.
type TranscriptionUsage struct {
Cost float64 `json:"cost"`
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
Seconds float64 `json:"seconds"`
TotalTokens int `json:"total_tokens"`
}
// TranscriptionResponse represents the response from /audio/transcriptions.
type TranscriptionResponse struct {
Text string `json:"text"`
Usage *TranscriptionUsage `json:"usage,omitempty"`
}
// NewTranscriptionInputAudio base64-encodes raw audio bytes for a transcription request.
func NewTranscriptionInputAudio(audio []byte, format AudioFormat) TranscriptionInputAudio {
return TranscriptionInputAudio{
Data: encodeAudio(audio),
Format: format,
}
}
// NewTranscriptionInputAudioFromFile reads an audio file and base64-encodes it for a transcription request.
func NewTranscriptionInputAudioFromFile(filePath string) (TranscriptionInputAudio, error) {
audio, format, err := readAudioFile(filePath)
if err != nil {
return TranscriptionInputAudio{}, err
}
return NewTranscriptionInputAudio(audio, format), nil
}
// CreateSpeech synthesizes speech from text and returns the raw audio bytestream.
func (c *Client) CreateSpeech(ctx context.Context, request SpeechRequest) (SpeechResponse, error) {
req, err := c.newRequest(
ctx,
http.MethodPost,
c.fullURL(audioSpeechSuffix),
withBody(request),
withContentType("application/json; charset=utf-8"),
)
if err != nil {
return SpeechResponse{}, err
}
req.Header.Set("Accept", "audio/*")
res, err := c.config.HTTPClient.Do(req)
if err != nil {
return SpeechResponse{}, err
}
defer res.Body.Close()
if isFailureStatusCode(res) {
return SpeechResponse{}, c.handleErrorResp(res)
}
audio, err := io.ReadAll(res.Body)
if err != nil {
return SpeechResponse{}, err
}
return SpeechResponse{
Audio: audio,
ContentType: res.Header.Get("Content-Type"),
GenerationID: res.Header.Get("X-Generation-Id"),
}, nil
}
// CreateTranscription transcribes base64-encoded audio into text.
func (c *Client) CreateTranscription(
ctx context.Context,
request TranscriptionRequest,
) (TranscriptionResponse, error) {
req, err := c.newRequest(
ctx,
http.MethodPost,
c.fullURL(audioTranscriptionsSuffix),
withBody(request),
)
if err != nil {
return TranscriptionResponse{}, err
}
var response TranscriptionResponse
if err := c.sendRequest(req, &response); err != nil {
return TranscriptionResponse{}, err
}
return response, nil
}
func encodeAudio(audio []byte) string {
return base64.StdEncoding.EncodeToString(audio)
}
func readAudioFile(filePath string) ([]byte, AudioFormat, error) {
fileData, err := os.ReadFile(filePath)
if err != nil {
return nil, "", err
}
format, err := audioFormatFromFilePath(filePath)
if err != nil {
return nil, "", err
}
return fileData, format, nil
}
func audioFormatFromFilePath(filePath string) (AudioFormat, error) {
ext := strings.ToLower(filepath.Ext(filePath))
switch ext {
case ".mp3":
return AudioFormatMp3, nil
case ".wav":
return AudioFormatWav, nil
case ".flac":
return AudioFormatFlac, nil
case ".opus":
return AudioFormatOpus, nil
case ".pcm16":
return AudioFormatPcm16, nil
case ".pcm24":
return AudioFormatPcm24, nil
case ".aiff", ".aif":
return AudioFormatAiff, nil
case ".aac":
return AudioFormatAac, nil
case ".ogg":
return AudioFormatOgg, nil
case ".m4a":
return AudioFormatM4a, nil
case ".webm":
return AudioFormatWebm, nil
default:
return "", fmt.Errorf("unsupported audio format: %s", ext)
}
}