generated from deepgram-starters/project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
318 lines (258 loc) · 8.02 KB
/
main.go
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
msginterfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/websocket/interfaces"
clientinterfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces"
client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak"
)
type MyHandler struct {
binaryChan chan *[]byte
openChan chan *msginterfaces.OpenResponse
flushedChan chan *msginterfaces.FlushedResponse
closeChan chan *msginterfaces.CloseResponse
errorChan chan *msginterfaces.ErrorResponse
wsUI *websocket.Conn
}
func NewMyHandler(uiWebsocket *websocket.Conn) MyHandler {
handler := MyHandler{
binaryChan: make(chan *[]byte),
openChan: make(chan *msginterfaces.OpenResponse),
flushedChan: make(chan *msginterfaces.FlushedResponse),
closeChan: make(chan *msginterfaces.CloseResponse),
errorChan: make(chan *msginterfaces.ErrorResponse),
wsUI: uiWebsocket,
}
go func() {
handler.Run()
}()
return handler
}
// GetUnhandled returns the binary event channels
func (dch MyHandler) GetBinary() []*chan *[]byte {
return []*chan *[]byte{&dch.binaryChan}
}
// GetOpen returns the open channels
func (dch MyHandler) GetOpen() []*chan *msginterfaces.OpenResponse {
return []*chan *msginterfaces.OpenResponse{&dch.openChan}
}
// GetMetadata returns the metadata channels
func (dch MyHandler) GetMetadata() []*chan *msginterfaces.MetadataResponse {
return []*chan *msginterfaces.MetadataResponse{}
}
// GetFlushed returns the flush channels
func (dch MyHandler) GetFlush() []*chan *msginterfaces.FlushedResponse {
return []*chan *msginterfaces.FlushedResponse{&dch.flushedChan}
}
// GetClose returns the close channels
func (dch MyHandler) GetClose() []*chan *msginterfaces.CloseResponse {
return []*chan *msginterfaces.CloseResponse{&dch.closeChan}
}
// GetWarning returns the warning channels
func (dch MyHandler) GetWarning() []*chan *msginterfaces.WarningResponse {
return []*chan *msginterfaces.WarningResponse{}
}
// GetError returns the error channels
func (dch MyHandler) GetError() []*chan *msginterfaces.ErrorResponse {
return []*chan *msginterfaces.ErrorResponse{&dch.errorChan}
}
// GetUnhandled returns the unhandled event channels
func (dch MyHandler) GetUnhandled() []*chan *[]byte {
return []*chan *[]byte{}
}
// Open is the callback for when the connection opens
// golintci: funlen
func (dch MyHandler) Run() error {
wgReceivers := sync.WaitGroup{}
// open channel
wgReceivers.Add(1)
go func() {
defer wgReceivers.Done()
for or := range dch.openChan {
fmt.Printf("------------ [OPEN] Deepgram WebSocket connection opened\n")
// Send metadata to the UI
openJSON, err := json.Marshal(or)
if err != nil {
log.Println("Failed to marshal open to JSON:", err)
continue
}
fmt.Printf("Open JSON: %s\n", openJSON)
dch.wsUI.WriteMessage(websocket.TextMessage, openJSON)
}
}()
// flushed channel
wgReceivers.Add(1)
go func() {
defer wgReceivers.Done()
for fr := range dch.flushedChan {
fmt.Printf("------------ [FLUSHED] Final Binary\n")
// Send metadata to the UI
flushedJSON, err := json.Marshal(fr)
if err != nil {
log.Println("Failed to marshal flushed to JSON:", err)
continue
}
fmt.Printf("Flushed JSON: %s\n", flushedJSON)
dch.wsUI.WriteMessage(websocket.TextMessage, flushedJSON)
}
}()
// binary channel
wgReceivers.Add(1)
go func() {
defer wgReceivers.Done()
lastTime := time.Now().Add(-5 * time.Second)
for br := range dch.binaryChan {
if time.Since(lastTime) > 3*time.Second {
fmt.Printf("------------ [Binary Data] Attach header.\n")
// Add a wav audio container header to the file if you want to play the audio
// using the AudioContext or media player like VLC, Media Player, or Apple Music
// Without this header in the Chrome browser case, the audio will not play.
header := []byte{
0x52, 0x49, 0x46, 0x46, // "RIFF"
0x00, 0x00, 0x00, 0x00, // Placeholder for file size
0x57, 0x41, 0x56, 0x45, // "WAVE"
0x66, 0x6d, 0x74, 0x20, // "fmt "
0x10, 0x00, 0x00, 0x00, // Chunk size (16)
0x01, 0x00, // Audio format (1 for PCM)
0x01, 0x00, // Number of channels (1)
0x80, 0xbb, 0x00, 0x00, // Sample rate (48000)
0x00, 0xee, 0x02, 0x00, // Byte rate (48000 * 2)
0x02, 0x00, // Block align (2)
0x10, 0x00, // Bits per sample (16)
0x64, 0x61, 0x74, 0x61, // "data"
0x00, 0x00, 0x00, 0x00, // Placeholder for data size
}
dch.wsUI.WriteMessage(websocket.BinaryMessage, header)
lastTime = time.Now()
}
fmt.Printf("------------ [Binary Data] (len: %d)\n", len(*br))
dch.wsUI.WriteMessage(websocket.BinaryMessage, *br)
}
}()
// close channel
wgReceivers.Add(1)
go func() {
defer wgReceivers.Done()
for cr := range dch.closeChan {
fmt.Printf("------------ [Close] Deepgram WebSocket connection closed\n")
// Send metadata to the UI
closeJSON, err := json.Marshal(cr)
if err != nil {
log.Println("Failed to marshal close to JSON:", err)
continue
}
fmt.Printf("Close JSON: %s\n", closeJSON)
dch.wsUI.WriteMessage(websocket.TextMessage, closeJSON)
}
}()
// error channel
wgReceivers.Add(1)
go func() {
defer wgReceivers.Done()
for er := range dch.errorChan {
fmt.Printf("------------ [Error] ErrCode: %s\n", er.ErrCode)
fmt.Printf("ErrMsg: %s\n", er.ErrMsg)
fmt.Printf("Description: %s\n", er.Description)
// Send metadata to the UI
errorJSON, err := json.Marshal(er)
if err != nil {
log.Println("Failed to marshal error to JSON:", err)
continue
}
fmt.Printf("Error JSON: %s\n", errorJSON)
dch.wsUI.WriteMessage(websocket.TextMessage, errorJSON)
}
}()
// wait for all receivers to finish
wgReceivers.Wait()
return nil
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var requestData struct {
Text string `json:"text"`
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
// get the model from the query string
model := r.URL.Query().Get("model")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Failed to upgrade connection to WebSocket:", err)
return
}
defer conn.Close()
if model == "" {
fmt.Println("No model specified, using default model")
model = "aura-asteria-en"
}
// context
ctx := context.Background()
// client options, if needed
cOptions := clientinterfaces.ClientOptions{}
// Create a new Deepgram WebSocket client
sOptions := clientinterfaces.WSSpeakOptions{
Model: model,
Encoding: "linear16",
SampleRate: 48000,
}
callback := NewMyHandler(conn)
wsClient, err := client.NewWSUsingChan(ctx, "", &cOptions, &sOptions, callback)
if err != nil {
log.Fatalf("Failed to create WebSocket client: %v", err)
return
}
// Wait for the connection to be established
isConnected := wsClient.Connect()
if !isConnected {
log.Fatalf("Failed to connect to Deepgram")
return
}
for {
// Read message from the WebSocket connection
msgType, message, err := conn.ReadMessage()
if err != nil {
log.Println("Failed to read message from WebSocket:", err)
break
}
if msgType == websocket.TextMessage {
err = json.Unmarshal(message, &requestData)
if err != nil {
log.Println("Failed to unmarshal JSON:", err)
continue
}
if requestData.Text == "" {
log.Println("Text is required in the request")
continue
}
log.Printf("Text: %s\n", requestData.Text)
err = wsClient.SpeakWithText(requestData.Text)
if err != nil {
log.Println("Failed to send text to Deepgram:", err)
}
err = wsClient.Flush()
if err != nil {
fmt.Printf("Error flushing: %v\n", err)
return
}
}
}
}
func main() {
client.Init(client.InitLib{
LogLevel: client.LogLevelDefault, // LogLevelDefault, LogLevelFull, LogLevelDebug, LogLevelTrace
})
fs := http.FileServer(http.Dir("./public"))
http.Handle("/", fs)
http.HandleFunc("/ws", handleWebSocket)
fmt.Printf("Open the UI at http://localhost:3000\n")
log.Fatal(http.ListenAndServe(":3000", nil))
}