/
example.go
337 lines (305 loc) · 10.1 KB
/
example.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package main
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"flag"
"fmt"
"github.com/go-audio/wav"
houndify "github.com/soundhound/houndify-sdk-go"
"io"
"io/ioutil"
"log"
"net/http/httptrace"
"net/textproto"
"os"
"strings"
"time"
)
const (
// This is not the clientId. This is the app user, so many will likely exist per clientId.
// This value can be any string.
// See https://www.houndify.com/docs/ for more details.
userID = "exampleUser"
envClientIDKey = "HOUNDIFY_CLIENT_ID"
envClientKeyKey = "HOUNDIFY_CLIENT_KEY"
cliClientIDKey = "id"
cliClientKeyKey = "key"
)
func main() {
clientIDFlag := flag.String(cliClientIDKey, "", "Client ID")
clientKeyFlag := flag.String(cliClientKeyKey, "", "Client Key")
voiceFlag := flag.String("voice", "", "Audio file to use for voice query")
textFlag := flag.String("text", "", "Message to use for text query")
stdinFlag := flag.Bool("stdin", false, "Text query via stdin messages")
streamFlag := flag.Bool("stream", false, "Stream audio file in real time to server, used with --voice")
verboseFlag := flag.Bool("v", false, "Verbose mode, which prints raw server data")
traceFlag := flag.Bool("trace", false, "Enable http client tracing")
flag.Parse()
// Make log not print out time info
log.SetFlags(0)
clientID := derefOrFetchFromEnv(clientIDFlag, envClientIDKey)
clientKey := derefOrFetchFromEnv(clientKeyFlag, envClientKeyKey)
var errsList []string
if clientID == "" {
msg := fmt.Sprintf("must set the client ID in environment variable: %q or via commmandline flag: -%s", envClientIDKey, cliClientIDKey)
errsList = append(errsList, msg)
}
if clientKey == "" {
msg := fmt.Sprintf("must set the client key in environment variable: %q or via commandline flag: -%s", envClientKeyKey, cliClientKeyKey)
errsList = append(errsList, msg)
}
if len(errsList) > 0 {
log.Fatalf("%s", strings.Join(errsList, "\n"))
}
// create a new client
client := houndify.Client{
ClientID: clientID,
ClientKey: clientKey,
Verbose: *verboseFlag,
}
client.EnableConversationState()
switch {
default:
log.Fatalf("must choose either voice, text or stdin")
case *voiceFlag != "" && !*streamFlag:
// voice query
audioFilePath := *voiceFlag
fileContents, err := ioutil.ReadFile(audioFilePath)
if err != nil {
log.Fatalf("failed to read contents of file %q, err: %v", audioFilePath, err)
}
req := houndify.VoiceRequest{
AudioStream: bytes.NewReader(fileContents),
UserID: userID,
RequestID: createRequestID(),
RequestInfoFields: make(map[string]interface{}),
}
ctx := context.Background()
req.WithContext(ctx)
if *traceFlag {
req.WithContext(httptrace.WithClientTrace(ctx, getDefaultClientTrace()))
}
// listen for partial transcript responses
partialTranscripts := make(chan houndify.PartialTranscript)
go func() {
for partial := range partialTranscripts {
if partial.Message != "" { // ignore the "" partial transcripts, not really useful
fmt.Println(partial.Message)
}
}
}()
serverResponse, err := client.VoiceSearch(req, partialTranscripts)
if err != nil {
log.Fatalf("failed to make voice request: %v\n%s\n", err, serverResponse)
}
writtenResponse, err := houndify.ParseWrittenResponse(serverResponse)
if err != nil {
log.Fatalf("failed to decode hound response\n%s\n", serverResponse)
}
fmt.Println(writtenResponse)
case *textFlag != "":
// text query
req := houndify.TextRequest{
Query: *textFlag,
UserID: userID,
RequestID: createRequestID(),
RequestInfoFields: make(map[string]interface{}),
}
ctx := context.Background()
req.WithContext(ctx)
if *traceFlag {
req.WithContext(httptrace.WithClientTrace(ctx, getDefaultClientTrace()))
}
serverResponse, err := client.TextSearch(req)
if err != nil {
log.Fatalf("failed to make text request: %v\n%s\n", err, serverResponse)
}
writtenResponse, err := houndify.ParseWrittenResponse(serverResponse)
if err != nil {
log.Fatalf("failed to decode hound response\n%s\n", serverResponse)
}
fmt.Println(writtenResponse)
case *stdinFlag:
// text queries in succession, demonstrating conversation state
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Enter a text query: ")
for scanner.Scan() {
req := houndify.TextRequest{
Query: scanner.Text(),
UserID: userID,
RequestID: createRequestID(),
RequestInfoFields: make(map[string]interface{}),
}
serverResponse, err := client.TextSearch(req)
if err != nil {
fmt.Printf("failed to make text request: %v\n%s\nEnter another text query:", err, serverResponse)
continue
}
writtenResponse, err := houndify.ParseWrittenResponse(serverResponse)
if err != nil {
log.Fatalf("failed to decode hound response\n%s\n", serverResponse)
}
fmt.Print(writtenResponse, "\n\n")
fmt.Println("Enter another text query:")
}
case *voiceFlag != "" && *streamFlag:
StreamAudio(client, *voiceFlag, userID)
}
}
// Stream an audio file to the server. This example demonstrates streaming a wav file,
// however this could easily be changed to stream audio from a microphone or something.
// Basically it just writes data from a buffer to the Request body every 1 second. The
// advantage of how golang has the http.Request's Body field is it's a Reader, so using
// io.Pipe() you can actually write any data into it. That means any stream of WAV data
// can just be piped in, and the requests will be made.
//
// This function also demonstrates how you can use the SafeToStopAudio flag to know when
// the server has all the data it needs.
func StreamAudio(client houndify.Client, fname, uid string) {
f, err := os.Open(fname)
defer f.Close()
if err != nil {
log.Fatalf("failed to read contents of file %q, err: %v\n", fname, err)
}
// Read WAV file data, determine bytes per second
d := wav.NewDecoder(f)
d.ReadInfo()
// Use 1 second chunks
bps := int(d.AvgBytesPerSec) * 1
// Build pipe that lets us write into the io.Reader that is in the request
rp, wp := io.Pipe()
req := houndify.VoiceRequest{
AudioStream: rp,
UserID: uid,
RequestID: createRequestID(),
}
// Start the function to write 1 second of data per 1 real second, by using a buffer
// that is the size of 1 second of data. Note that using the .Read() function results
// in the header portion of the file not being read. We have to use the ReadAt()
// function to specify starting at the very first position of the actual file, or the
// header isn't read.
var loc int64 = 0
buf := make([]byte, bps)
done := make(chan bool)
go func(wp *io.PipeWriter) {
defer wp.Close()
for {
select {
case <-done:
//fmt.Println("Exiting write loop")
return
default:
n, err := f.ReadAt(buf, loc)
loc += int64(n)
// At the EOF, the buffer will still have bytes read into it, have to write
// those out before breaking the loop
if err == io.EOF {
wp.Write(buf[:n])
return
}
// Write the amount of bytes that were read in
wp.Write(buf[:n])
time.Sleep(time.Duration(1) * time.Second)
}
}
}(wp)
// listen for partial transcript responses
partialTranscripts := make(chan houndify.PartialTranscript)
go func() {
for partial := range partialTranscripts {
if partial.SafeToStopAudio != nil && *partial.SafeToStopAudio == true {
fmt.Println("Safe to stop audio recieved")
if done != nil {
done <- true
}
return
}
if partial.Message != "" { // ignore the "" partial transcripts, not really useful
fmt.Println(partial.Message)
}
}
}()
serverResponse, err := client.VoiceSearch(req, partialTranscripts)
if err != nil {
log.Fatalf("failed to make voice request: %v\n%s\n", err, serverResponse)
}
writtenResponse, err := houndify.ParseWrittenResponse(serverResponse)
if err != nil {
log.Fatalf("failed to decode hound response\n%s\n", serverResponse)
}
fmt.Println(writtenResponse)
}
// Creates a pseudo unique/random request ID.
//
// SDK users should do something similar so each request to the Hound server
// is signed differently to prevent replay attacks.
func createRequestID() string {
n := 10
b := make([]byte, n)
rand.Read(b)
return fmt.Sprintf("%X", b)
}
// derefOrFetchFromEnv tries to dereference and retrieve a non-empty
// string stored in the string pointer, otherwise it falls back
// to retrieving the value stored in the environment keyed by envKey.
func derefOrFetchFromEnv(strPtr *string, envKey string) string {
if strPtr != nil && *strPtr != "" {
return *strPtr
}
return os.Getenv(envKey)
}
func getDefaultClientTrace() *httptrace.ClientTrace {
traceLogger := log.New(os.Stdout, "[httptrace] ", log.Ltime | log.Lmicroseconds)
trace := &httptrace.ClientTrace{
GotConn: func(info httptrace.GotConnInfo) {
traceLogger.Println("GotConn: ", info)
},
PutIdleConn: func(err error) {
traceLogger.Println("PutIdleConn: ", err)
},
GotFirstResponseByte: func() {
traceLogger.Println("GotFirstResponseByte")
},
Got100Continue: func() {
traceLogger.Println("Got100Continue")
},
Got1xxResponse: func(code int, header textproto.MIMEHeader) error {
traceLogger.Println("Got1xxResponse: ", code, header)
return nil
},
DNSStart: func(info httptrace.DNSStartInfo) {
traceLogger.Println("DNSStart: ", info)
},
DNSDone: func(info httptrace.DNSDoneInfo) {
traceLogger.Println("DNSDone: ", info)
},
ConnectStart: func(network, addr string) {
traceLogger.Println("ConnectStart: ", addr)
},
ConnectDone: func(network, addr string, err error) {
traceLogger.Println("ConnectDone: ", network, addr, err)
},
TLSHandshakeStart: func() {
traceLogger.Println("TLSHandshakeStart")
},
TLSHandshakeDone: func(state tls.ConnectionState, err error) {
traceLogger.Println("TLSHandshakeDone: ", state, err)
},
WroteHeaderField: func(key string, value []string) {
traceLogger.Println("WroteHeaderField: ", key, value)
},
WroteHeaders: func() {
traceLogger.Println("WroteHeaders")
},
Wait100Continue: func() {
traceLogger.Println("Wait100Continue")
},
WroteRequest: func(info httptrace.WroteRequestInfo) {
traceLogger.Println("WroteRequest: ", info)
},
}
return trace
}