generated from deepgram-starters/project-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
191 lines (163 loc) · 4.84 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
api "github.com/deepgram/deepgram-go-sdk/pkg/api/live/v1/interfaces"
interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces"
client "github.com/deepgram/deepgram-go-sdk/pkg/client/live"
"github.com/joho/godotenv"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// Allow all origins
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type WebSocketMessage struct {
Type string `json:"type"`
}
// Implement the api.Callback interface
type MyCallback struct {
socket *websocket.Conn
}
// Deepgram will call these methods when it receives a response: NewMyCallback, Message, Metadata, UtteranceEnd, Error
func NewMyCallback(conn *websocket.Conn) *MyCallback {
return &MyCallback{
socket: conn,
}
}
func (c MyCallback) Open(ocr *api.OpenResponse) error {
// handle the open
fmt.Printf("\n[Open] Received\n")
return nil
}
func (c MyCallback) SpeechStarted(ssr *api.SpeechStartedResponse) error {
fmt.Printf("\n[SpeechStarted] Received\n")
return nil
}
func (c *MyCallback) Message(mr *api.MessageResponse) error {
sentence := strings.TrimSpace(mr.Channel.Alternatives[0].Transcript)
if len(mr.Channel.Alternatives) == 0 || len(sentence) == 0 {
return nil
}
fmt.Printf("\nDeepgram: %s\n\n", sentence)
c.socket.WriteJSON(sentence)
return nil
}
func (c MyCallback) Metadata(md *api.MetadataResponse) error {
fmt.Printf("\n[Metadata] Received\n")
fmt.Printf("Metadata.RequestID: %s\n", strings.TrimSpace(md.RequestID))
fmt.Printf("Metadata.Channels: %d\n", md.Channels)
fmt.Printf("Metadata.Created: %s\n\n", strings.TrimSpace(md.Created))
return nil
}
func (c MyCallback) UtteranceEnd(ur *api.UtteranceEndResponse) error {
fmt.Printf("\n[UtteranceEnd] Received\n")
return nil
}
func (c MyCallback) Error(er *api.ErrorResponse) error {
fmt.Printf("\n[Error] Received\n")
fmt.Printf("Error.Type: %s\n", er.Type)
fmt.Printf("Error.Message: %s\n", er.ErrMsg)
fmt.Printf("Error.Description: %s\n\n", er.Description)
return nil
}
func (c MyCallback) Close(ocr *api.CloseResponse) error {
// handle the close
fmt.Printf("\n[Close] Received\n")
return nil
}
func (c MyCallback) UnhandledEvent(byData []byte) error {
// handle the unhandled event
fmt.Printf("\n[UnhandledEvent] Received\n")
fmt.Printf("UnhandledEvent: %s\n\n", string(byData))
return nil
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("WebSocket upgrade failed:", err)
return
}
fmt.Println("WebSocket: connection established")
// Configuration for the Deepgram client
ctx := context.Background()
apiKey := os.Getenv("DEEPGRAM_API_KEY")
fmt.Println("Using API key:", apiKey)
clientOptions := interfaces.ClientOptions{
// EnableKeepAlive: true,
}
transcriptOptions := interfaces.LiveTranscriptionOptions{
Language: "en-US",
Model: "nova-2",
SmartFormat: true,
}
// Callback used to handle responses from Deepgram
callback := NewMyCallback(conn)
// Create a new Deepgram LiveTranscription client with config options
dgClient, err := client.New(ctx, apiKey, &clientOptions, &transcriptOptions, callback)
if err != nil {
fmt.Println("ERROR creating LiveTranscription connection:", err)
return
}
// Connect the websocket to Deepgram
bConnected := dgClient.Connect()
if !bConnected {
fmt.Println("Client.Connect failed")
os.Exit(1)
}
var clientMsg WebSocketMessage
// Set up a loop to continuously read messages from the WebSocket
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
if websocket.IsCloseError(err, websocket.CloseGoingAway) {
fmt.Println("Client closed connection (going away)")
return
}
fmt.Println("Error reading WebSocket message:", err)
return
}
if messageType == websocket.BinaryMessage {
// Send the audio data to Deepgram
n, err := dgClient.Write(p)
if err != nil {
fmt.Println("Error sending data to Deepgram:", err)
} else {
fmt.Println("WebSocket: data sent to Deepgram")
}
fmt.Printf("WebSocket: %d bytes from client \n", n)
} else if messageType == websocket.TextMessage {
err := json.Unmarshal(p, &clientMsg)
if err != nil {
fmt.Println("Error decoding JSON:", err)
continue
}
fmt.Printf("WebSocket: %s\n", clientMsg.Type)
if clientMsg.Type == "closeMicrophone" {
// Close the connection to Deepgram
dgClient.Stop()
fmt.Println("WebSocket: closed connection to Deepgram")
return
}
}
}
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
client.InitWithDefault()
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./public"))))
http.HandleFunc("/ws", handleWebSocket)
http.ListenAndServe(":8080", nil)
}