diff --git a/examples/manage/balances/main.go b/examples/manage/balances/main.go index d02774ae..77456d1a 100644 --- a/examples/manage/balances/main.go +++ b/examples/manage/balances/main.go @@ -10,7 +10,7 @@ import ( "os" api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) func main() { diff --git a/examples/manage/invitations-new-RENAME/main.go b/examples/manage/invitations-new-RENAME/main.go deleted file mode 100644 index 0dffb294..00000000 --- a/examples/manage/invitations-new-RENAME/main.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -// Use of this source code is governed by a MIT license that can be found in the LICENSE file. -// SPDX-License-Identifier: MIT - -package main - -import ( - "context" - "fmt" - "os" - - api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" - interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" -) - -func main() { - // init library - client.InitWithDefault() - - // context - ctx := context.Background() - - //client - dg := client.NewWithDefaults() - mgClient := api.New(dg) - - // list projects - respList, err := mgClient.ListProjects(ctx) - if err != nil { - fmt.Printf("ListProjects failed. Err: %v\n", err) - os.Exit(1) - } - - var projectID string - for _, item := range respList.Projects { - projectID = item.ProjectID - name := item.Name - fmt.Printf("ListProjects() - Name: %s, ID: %s\n", name, projectID) - break - } - - // list invitations - respGet, err := mgClient.ListInvitations(ctx, projectID) - if err != nil { - fmt.Printf("ListInvitations failed. Err: %v\n", err) - os.Exit(1) - } - - if len(respGet.Invites) == 0 { - fmt.Printf("ListInvitations() - No invitations found\n") - } else { - for _, item := range respGet.Invites { - id := item.Email - scope := item.Scope - fmt.Printf("ListInvitations() - ID: %s, Scope: %s\n", id, scope) - } - } - - // send invite - respMessage, err := mgClient.SendInvitation(ctx, projectID, &interfaces.InvitationRequest{ - Email: "spam@spam.com", - Scope: "member", - }) - if err != nil { - fmt.Printf("SendInvitation failed. Err: %v\n", err) - os.Exit(1) - } - fmt.Printf("SendInvitation() - Result: %s\n", respMessage.Message) - - // list invitations - respGet, err = mgClient.ListInvitations(ctx, projectID) - if err != nil { - fmt.Printf("ListInvitations failed. Err: %v\n", err) - os.Exit(1) - } - - if len(respGet.Invites) == 0 { - fmt.Printf("ListInvitations() - No invitations found\n") - } else { - for _, item := range respGet.Invites { - id := item.Email - scope := item.Scope - fmt.Printf("ListInvitations() - ID: %s, Scope: %s\n", id, scope) - } - } - - // delete invitation - respMessage, err = mgClient.DeleteInvitation(ctx, projectID, "spam@spam.com") - if err != nil { - fmt.Printf("DeleteInvitation failed. Err: %v\n", err) - os.Exit(1) - } - fmt.Printf("DeleteInvitation() - Result: %s\n", respMessage.Message) - - // list invitations - respGet, err = mgClient.ListInvitations(ctx, projectID) - if err != nil { - fmt.Printf("ListInvitations failed. Err: %v\n", err) - os.Exit(1) - } - - if len(respGet.Invites) == 0 { - fmt.Printf("ListInvitations() - No invitations found\n") - } else { - for _, item := range respGet.Invites { - id := item.Email - scope := item.Scope - fmt.Printf("ListInvitations() - ID: %s, Scope: %s\n", id, scope) - } - } - - // There isnt an API call to add a member to a project. So will leave this commented out as an example - // Leave Project - // respMessage, err = mgClient.LeaveProject(ctx, projectID) - // if err != nil { - // fmt.Printf("LeaveProject failed. Err: %v\n", err) - // os.Exit(1) - // } - // fmt.Printf("LeaveProject() - Name: %s\n", respMessage.Message) -} diff --git a/examples/manage/invitations/main.go b/examples/manage/invitations/main.go index dff7b037..0dffb294 100644 --- a/examples/manage/invitations/main.go +++ b/examples/manage/invitations/main.go @@ -11,7 +11,7 @@ import ( api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) func main() { diff --git a/examples/manage/keys/main.go b/examples/manage/keys/main.go index bcdc7e02..a5674a6f 100644 --- a/examples/manage/keys/main.go +++ b/examples/manage/keys/main.go @@ -11,7 +11,7 @@ import ( api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) func main() { diff --git a/examples/manage/members/main.go b/examples/manage/members/main.go index 4e73fc54..76045b51 100644 --- a/examples/manage/members/main.go +++ b/examples/manage/members/main.go @@ -10,7 +10,7 @@ import ( "os" api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) const ( diff --git a/examples/manage/projects/main.go b/examples/manage/projects/main.go index c1d854ad..23133ab1 100644 --- a/examples/manage/projects/main.go +++ b/examples/manage/projects/main.go @@ -11,7 +11,7 @@ import ( api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) func main() { diff --git a/examples/manage/scopes/main.go b/examples/manage/scopes/main.go index baa9b21a..0539ca60 100644 --- a/examples/manage/scopes/main.go +++ b/examples/manage/scopes/main.go @@ -11,7 +11,7 @@ import ( api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) const ( diff --git a/examples/manage/usage/main.go b/examples/manage/usage/main.go index 32e96362..ea94aa2d 100644 --- a/examples/manage/usage/main.go +++ b/examples/manage/usage/main.go @@ -14,7 +14,7 @@ import ( api "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/manage/v1/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/rest" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/manage" ) func main() { diff --git a/examples/speech-to-text/rest/callback/callback/main.go b/examples/speech-to-text/rest/callback/callback/main.go index 1230baef..9d57abea 100644 --- a/examples/speech-to-text/rest/callback/callback/main.go +++ b/examples/speech-to-text/rest/callback/callback/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -30,8 +30,8 @@ func main() { ctx := context.Background() //client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send stream res, err := dg.FromURL( diff --git a/examples/speech-to-text/rest/callback/endpoint/main.go b/examples/speech-to-text/rest/callback/endpoint/main.go index bcc3684e..b1e19e4b 100644 --- a/examples/speech-to-text/rest/callback/endpoint/main.go +++ b/examples/speech-to-text/rest/callback/endpoint/main.go @@ -16,7 +16,7 @@ import ( "github.com/gin-gonic/gin" prettyjson "github.com/hokaccha/go-prettyjson" - interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1/interfaces" + interfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest/interfaces" ) type SampleProxy struct { diff --git a/examples/speech-to-text/rest/file-new-RENAME/Bueller-Life-moves-pretty-fast.mp3 b/examples/speech-to-text/rest/file-new-RENAME/Bueller-Life-moves-pretty-fast.mp3 deleted file mode 100644 index 59ce4583..00000000 Binary files a/examples/speech-to-text/rest/file-new-RENAME/Bueller-Life-moves-pretty-fast.mp3 and /dev/null differ diff --git a/examples/speech-to-text/rest/file-new-RENAME/main.go b/examples/speech-to-text/rest/file-new-RENAME/main.go deleted file mode 100644 index 9177bacc..00000000 --- a/examples/speech-to-text/rest/file-new-RENAME/main.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -// Use of this source code is governed by a MIT license that can be found in the LICENSE file. -// SPDX-License-Identifier: MIT - -package main - -import ( - "context" - "encoding/json" - "fmt" - "os" - - prettyjson "github.com/hokaccha/go-prettyjson" - - api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" - interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" -) - -const ( - filePath string = "./Bueller-Life-moves-pretty-fast.mp3" -) - -func main() { - // init library - client.Init(client.InitLib{ - LogLevel: client.LogLevelTrace, // LogLevelStandard / LogLevelFull / LogLevelTrace - }) - - // Go context - ctx := context.Background() - - // set the Transcription options - options := &interfaces.PreRecordedTranscriptionOptions{ - Model: "nova-2", - Punctuate: true, - Paragraphs: true, - SmartFormat: true, - Language: "en-US", - Utterances: true, - } - - // create a Deepgram client - c := client.NewREST("", &interfaces.ClientOptions{ - Host: "https://api.deepgram.com", - }) - dg := api.New(c) - - // example on how to send a custom header - // need to import ( - // "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - // ) - // - // headers := make(map[string][]string, 0) - // headers["MY-CUSTOM-HEADER"] = []string{"CUSTOM"} - // ctx = cfginterfaces.WithCustomHeaders(ctx, headers) - // - // example on how to send a custom parameter - // params := make(map[string][]string, 0) - // params["utterances"] = []string{"true"} - // ctx = cfginterfaces.WithCustomParameters(ctx, params) - - // send/process file to Deepgram - res, err := dg.FromFile(ctx, filePath, options) - if err != nil { - if e, ok := err.(*interfaces.StatusError); ok { - fmt.Printf("DEEPGRAM ERROR:\n%s:\n%s\n", e.DeepgramError.ErrCode, e.DeepgramError.ErrMsg) - } - fmt.Printf("FromStream failed. Err: %v\n", err) - os.Exit(1) - } - - data, err := json.Marshal(res) - if err != nil { - fmt.Printf("json.Marshal failed. Err: %v\n", err) - os.Exit(1) - } - - // make the JSON pretty - prettyJSON, err := prettyjson.Format(data) - if err != nil { - fmt.Printf("prettyjson.Marshal failed. Err: %v\n", err) - os.Exit(1) - } - fmt.Printf("\n\nResult:\n%s\n\n", prettyJSON) - - // dump example VTT - vtt, err := res.ToWebVTT() - if err != nil { - fmt.Printf("ToWebVTT failed. Err: %v\n", err) - os.Exit(1) - } - fmt.Printf("\n\n\nVTT:\n%s\n\n\n", vtt) - - // dump example SRT - srt, err := res.ToSRT() - if err != nil { - fmt.Printf("ToSRT failed. Err: %v\n", err) - os.Exit(1) - } - fmt.Printf("\n\n\nSRT:\n%s\n\n\n", srt) -} diff --git a/examples/speech-to-text/rest/file/main.go b/examples/speech-to-text/rest/file/main.go index 69c7b0c2..9177bacc 100644 --- a/examples/speech-to-text/rest/file/main.go +++ b/examples/speech-to-text/rest/file/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -41,10 +41,10 @@ func main() { } // create a Deepgram client - c := client.New("", &interfaces.ClientOptions{ + c := client.NewREST("", &interfaces.ClientOptions{ Host: "https://api.deepgram.com", }) - dg := prerecorded.New(c) + dg := api.New(c) // example on how to send a custom header // need to import ( diff --git a/examples/speech-to-text/rest/intent/main.go b/examples/speech-to-text/rest/intent/main.go index 4e4d06c7..4b043679 100644 --- a/examples/speech-to-text/rest/intent/main.go +++ b/examples/speech-to-text/rest/intent/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -40,8 +40,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send/process file to Deepgram res, err := dg.FromFile(ctx, filePath, options) diff --git a/examples/speech-to-text/rest/sentiment/main.go b/examples/speech-to-text/rest/sentiment/main.go index a38ed23e..783ab147 100644 --- a/examples/speech-to-text/rest/sentiment/main.go +++ b/examples/speech-to-text/rest/sentiment/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -40,8 +40,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send/process file to Deepgram res, err := dg.FromFile(ctx, filePath, options) diff --git a/examples/speech-to-text/rest/stream/main.go b/examples/speech-to-text/rest/stream/main.go index 4e00d6c3..1b98e31e 100644 --- a/examples/speech-to-text/rest/stream/main.go +++ b/examples/speech-to-text/rest/stream/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -39,8 +39,8 @@ func main() { } //client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // open file sream file, err := os.Open(filePath) diff --git a/examples/speech-to-text/rest/summary/main.go b/examples/speech-to-text/rest/summary/main.go index c7cf6d1d..d555431f 100644 --- a/examples/speech-to-text/rest/summary/main.go +++ b/examples/speech-to-text/rest/summary/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -40,8 +40,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send/process file to Deepgram res, err := dg.FromFile(ctx, filePath, options) diff --git a/examples/speech-to-text/rest/topic/main.go b/examples/speech-to-text/rest/topic/main.go index 1d967bcc..32dded6d 100644 --- a/examples/speech-to-text/rest/topic/main.go +++ b/examples/speech-to-text/rest/topic/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -40,8 +40,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send/process file to Deepgram res, err := dg.FromFile(ctx, filePath, options) diff --git a/examples/speech-to-text/rest/url/main.go b/examples/speech-to-text/rest/url/main.go index 9a297834..502c9737 100644 --- a/examples/speech-to-text/rest/url/main.go +++ b/examples/speech-to-text/rest/url/main.go @@ -12,9 +12,9 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - prerecorded "github.com/deepgram/deepgram-go-sdk/pkg/api/prerecorded/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/prerecorded" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -38,8 +38,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := prerecorded.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send the URL to Deepgram res, err := dg.FromURL(ctx, url, options) diff --git a/examples/speech-to-text/websocket/http/main.go b/examples/speech-to-text/websocket/http/main.go index 044102cc..12fc44bc 100644 --- a/examples/speech-to-text/websocket/http/main.go +++ b/examples/speech-to-text/websocket/http/main.go @@ -13,7 +13,7 @@ import ( "reflect" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/live" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) const ( @@ -37,7 +37,7 @@ func main() { } // create a Deepgram client - dgClient, err := client.NewForDemo(ctx, transcriptOptions) + dgClient, err := client.NewWebSocketForDemo(ctx, transcriptOptions) if err != nil { fmt.Println("ERROR creating LiveTranscription connection:", err) return diff --git a/examples/speech-to-text/websocket/microphone-new-RENAME/main.go b/examples/speech-to-text/websocket/microphone-new-RENAME/main.go deleted file mode 100644 index b36a8a80..00000000 --- a/examples/speech-to-text/websocket/microphone-new-RENAME/main.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -// Use of this source code is governed by a MIT license that can be found in the LICENSE file. -// SPDX-License-Identifier: MIT - -package main - -// streaming -import ( - "bufio" - "context" - "fmt" - "os" - "strings" - - api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/websocket/interfaces" - microphone "github.com/deepgram/deepgram-go-sdk/pkg/audio/microphone" - interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" -) - -// Implement your own callback -type MyCallback struct { - sb *strings.Builder -} - -func (c MyCallback) Message(mr *api.MessageResponse) error { - // handle the message - sentence := strings.TrimSpace(mr.Channel.Alternatives[0].Transcript) - - if len(mr.Channel.Alternatives) == 0 || len(sentence) == 0 { - return nil - } - - if mr.IsFinal { - c.sb.WriteString(sentence) - c.sb.WriteString(" ") - - if mr.SpeechFinal { - fmt.Printf("[------- Is Final]: %s\n", c.sb.String()) - c.sb.Reset() - } - } else { - fmt.Printf("[Interm Result]: %s\n", sentence) - } - - return nil -} - -func (c MyCallback) Open(ocr *api.OpenResponse) error { - // handle the open - fmt.Printf("\n[Open] Received\n") - return nil -} - -func (c MyCallback) Metadata(md *api.MetadataResponse) error { - // handle the metadata - 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) SpeechStarted(ssr *api.SpeechStartedResponse) error { - fmt.Printf("\n[SpeechStarted] Received\n") - return nil -} - -func (c MyCallback) UtteranceEnd(ur *api.UtteranceEndResponse) error { - utterance := strings.TrimSpace(c.sb.String()) - if len(utterance) > 0 { - fmt.Printf("[------- UtteranceEnd]: %s\n", utterance) - c.sb.Reset() - } else { - fmt.Printf("\n[UtteranceEnd] Received\n") - } - - return nil -} - -func (c MyCallback) Close(ocr *api.CloseResponse) error { - // handle the close - fmt.Printf("\n[Close] Received\n") - return nil -} - -func (c MyCallback) Error(er *api.ErrorResponse) error { - // handle the error - fmt.Printf("\n[Error] Received\n") - fmt.Printf("Error.Type: %s\n", er.Type) - fmt.Printf("Error.ErrCode: %s\n", er.ErrCode) - fmt.Printf("Error.Description: %s\n\n", er.Description) - 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 main() { - // init library - microphone.Initialize() - - // print instructions - fmt.Print("\n\nPress ENTER to exit!\n\n") - - /* - DG Streaming API - */ - // init library - client.Init(client.InitLib{ - LogLevel: client.LogLevelDefault, // LogLevelDefault, LogLevelFull, LogLevelDebug, LogLevelTrace - }) - - // Go context - ctx := context.Background() - - // client options - cOptions := &interfaces.ClientOptions{ - EnableKeepAlive: true, - } - - // set the Transcription options - tOptions := &interfaces.LiveTranscriptionOptions{ - Model: "nova-2", - Language: "en-US", - Punctuate: true, - Encoding: "linear16", - Channels: 1, - SampleRate: 16000, - SmartFormat: true, - VadEvents: true, - // To get UtteranceEnd, the following must be set: - InterimResults: true, - UtteranceEndMs: "1000", - // End of UtteranceEnd settings - } - - // example on how to send a custom parameter - // params := make(map[string][]string, 0) - // params["dictation"] = []string{"true"} - // ctx = interfaces.WithCustomParameters(ctx, params) - - // implement your own callback - callback := MyCallback{ - sb: &strings.Builder{}, - } - - // create a Deepgram client - dgClient, err := client.NewWebSocket(ctx, "", cOptions, tOptions, 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) - } - - /* - Microphone package - */ - // mic stuf - mic, err := microphone.New(microphone.AudioConfig{ - InputChannels: 1, - SamplingRate: 16000, - }) - if err != nil { - fmt.Printf("Initialize failed. Err: %v\n", err) - os.Exit(1) - } - - // start the mic - err = mic.Start() - if err != nil { - fmt.Printf("mic.Start failed. Err: %v\n", err) - os.Exit(1) - } - - go func() { - // feed the microphone stream to the Deepgram client (this is a blocking call) - mic.Stream(dgClient) - }() - - // wait for user input to exit - input := bufio.NewScanner(os.Stdin) - input.Scan() - - // close mic stream - err = mic.Stop() - if err != nil { - fmt.Printf("mic.Stop failed. Err: %v\n", err) - os.Exit(1) - } - - // teardown library - microphone.Teardown() - - // close DG client - dgClient.Stop() - - fmt.Printf("\n\nProgram exiting...\n") - // time.Sleep(120 * time.Second) -} diff --git a/examples/speech-to-text/websocket/microphone/main.go b/examples/speech-to-text/websocket/microphone/main.go index 91290e66..b36a8a80 100644 --- a/examples/speech-to-text/websocket/microphone/main.go +++ b/examples/speech-to-text/websocket/microphone/main.go @@ -12,10 +12,10 @@ import ( "os" "strings" - api "github.com/deepgram/deepgram-go-sdk/pkg/api/live/v1/interfaces" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/listen/v1/websocket/interfaces" microphone "github.com/deepgram/deepgram-go-sdk/pkg/audio/microphone" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/live" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) // Implement your own callback @@ -150,7 +150,7 @@ func main() { } // create a Deepgram client - dgClient, err := client.New(ctx, "", cOptions, tOptions, callback) + dgClient, err := client.NewWebSocket(ctx, "", cOptions, tOptions, callback) if err != nil { fmt.Println("ERROR creating LiveTranscription connection:", err) return diff --git a/examples/speech-to-text/websocket/replay/main.go b/examples/speech-to-text/websocket/replay/main.go index c54aa3f1..85a59f6f 100644 --- a/examples/speech-to-text/websocket/replay/main.go +++ b/examples/speech-to-text/websocket/replay/main.go @@ -14,7 +14,7 @@ import ( replay "github.com/deepgram/deepgram-go-sdk/pkg/audio/replay" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/live" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) func main() { @@ -37,7 +37,7 @@ func main() { } // create a Deepgram client - dgClient, err := client.NewForDemo(ctx, options) + dgClient, err := client.NewWebSocketForDemo(ctx, options) if err != nil { log.Println("ERROR creating LiveTranscription connection:", err) return diff --git a/examples/speech-to-text/websocket/test/main.go b/examples/speech-to-text/websocket/test/main.go index 8d49dc33..d222c8a3 100644 --- a/examples/speech-to-text/websocket/test/main.go +++ b/examples/speech-to-text/websocket/test/main.go @@ -14,7 +14,7 @@ import ( microphone "github.com/deepgram/deepgram-go-sdk/pkg/audio/microphone" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/live" //lint:ignore + client "github.com/deepgram/deepgram-go-sdk/pkg/client/listen" ) func main() { @@ -55,7 +55,7 @@ func main() { } // create a Deepgram client - dgClient, err := client.New(ctx, "", cOptions, tOptions, nil) + dgClient, err := client.NewWebSocket(ctx, "", cOptions, tOptions, nil) if err != nil { fmt.Println("ERROR creating LiveTranscription connection:", err) return diff --git a/examples/text-to-speech/rest/file-new-RENAME/hello-world/main.go b/examples/text-to-speech/rest/file-new-RENAME/hello-world/main.go deleted file mode 100644 index 41ece631..00000000 --- a/examples/text-to-speech/rest/file-new-RENAME/hello-world/main.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved. -// Use of this source code is governed by a MIT license that can be found in the LICENSE file. -// SPDX-License-Identifier: MIT - -package main - -import ( - "context" - "encoding/json" - "fmt" - "os" - - prettyjson "github.com/hokaccha/go-prettyjson" - - api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" - interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" - client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" -) - -const ( - textToSpeech string = "Hello, World!" - filePath string = "./test.mp3" -) - -func main() { - // init library - client.Init(client.InitLib{ - LogLevel: client.LogLevelTrace, // LogLevelDefault, LogLevelFull, LogLevelDebug, LogLevelTrace - }) - - // Go context - ctx := context.Background() - - // set the Transcription options - options := &interfaces.SpeakOptions{ - Model: "aura-asteria-en", - } - - // create a Deepgram client - c := client.NewWithDefaults() - dg := api.New(c) - - // send/process file to Deepgram - res, err := dg.ToSave(ctx, filePath, textToSpeech, options) - if err != nil { - fmt.Printf("FromStream failed. Err: %v\n", err) - os.Exit(1) - } - - data, err := json.Marshal(res) - if err != nil { - fmt.Printf("json.Marshal failed. Err: %v\n", err) - os.Exit(1) - } - - // make the JSON pretty - prettyJSON, err := prettyjson.Format(data) - if err != nil { - fmt.Printf("prettyjson.Marshal failed. Err: %v\n", err) - os.Exit(1) - } - fmt.Printf("\n\nResult:\n%s\n\n", prettyJSON) -} diff --git a/examples/text-to-speech/rest/file/hello-world/main.go b/examples/text-to-speech/rest/file/hello-world/main.go index bd4f370f..fa704dd3 100644 --- a/examples/text-to-speech/rest/file/hello-world/main.go +++ b/examples/text-to-speech/rest/file/hello-world/main.go @@ -12,7 +12,7 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - speak "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" ) @@ -37,8 +37,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := speak.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send/process file to Deepgram res, err := dg.ToSave(ctx, filePath, textToSpeech, options) diff --git a/examples/text-to-speech/rest/file/woodchuck/main.go b/examples/text-to-speech/rest/file/woodchuck/main.go index 44836ce9..369b50be 100644 --- a/examples/text-to-speech/rest/file/woodchuck/main.go +++ b/examples/text-to-speech/rest/file/woodchuck/main.go @@ -12,7 +12,7 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - speak "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" ) @@ -37,8 +37,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := speak.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // send/process file to Deepgram res, err := dg.ToSave(ctx, filePath, textToSpeech, options) diff --git a/examples/text-to-speech/rest/stream/hello-world/main.go b/examples/text-to-speech/rest/stream/hello-world/main.go index 81ccd984..24d3f76f 100644 --- a/examples/text-to-speech/rest/stream/hello-world/main.go +++ b/examples/text-to-speech/rest/stream/hello-world/main.go @@ -12,7 +12,7 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - speak "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" ) @@ -35,8 +35,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := speak.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // create file file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o666) diff --git a/examples/text-to-speech/rest/stream/woodchuck/main.go b/examples/text-to-speech/rest/stream/woodchuck/main.go index cbe7ee0a..3eeae433 100644 --- a/examples/text-to-speech/rest/stream/woodchuck/main.go +++ b/examples/text-to-speech/rest/stream/woodchuck/main.go @@ -12,7 +12,7 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - speak "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" ) @@ -35,8 +35,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := speak.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // create file file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o666) diff --git a/examples/text-to-speech/rest/writer/hello-world/main.go b/examples/text-to-speech/rest/writer/hello-world/main.go index f3cb8d16..abf7fa86 100644 --- a/examples/text-to-speech/rest/writer/hello-world/main.go +++ b/examples/text-to-speech/rest/writer/hello-world/main.go @@ -12,7 +12,7 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - speak "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" ) @@ -35,8 +35,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := speak.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // create file file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o666) diff --git a/examples/text-to-speech/rest/writer/woodchuck/main.go b/examples/text-to-speech/rest/writer/woodchuck/main.go index 8ace9df5..cddb8129 100644 --- a/examples/text-to-speech/rest/writer/woodchuck/main.go +++ b/examples/text-to-speech/rest/writer/woodchuck/main.go @@ -12,7 +12,7 @@ import ( prettyjson "github.com/hokaccha/go-prettyjson" - speak "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1" //lint:ignore + api "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/rest" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" client "github.com/deepgram/deepgram-go-sdk/pkg/client/speak" ) @@ -35,8 +35,8 @@ func main() { } // create a Deepgram client - c := client.NewWithDefaults() - dg := speak.New(c) + c := client.NewRESTWithDefaults() + dg := api.New(c) // create file file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o666) diff --git a/examples/text-to-speech/websocket/interactive/main.go b/examples/text-to-speech/websocket/interactive/main.go index 0184ea45..9d15845b 100644 --- a/examples/text-to-speech/websocket/interactive/main.go +++ b/examples/text-to-speech/websocket/interactive/main.go @@ -10,6 +10,7 @@ import ( "fmt" "os" "strings" + "time" msginterfaces "github.com/deepgram/deepgram-go-sdk/pkg/api/speak/v1/websocket/interfaces" interfaces "github.com/deepgram/deepgram-go-sdk/pkg/client/interfaces" @@ -53,12 +54,20 @@ func (c MyCallback) Binary(byMsg []byte) error { func (c MyCallback) Flush(fl *msginterfaces.FlushedResponse) error { fmt.Printf("\n[Flushed] Received\n") + fmt.Printf("\n\nPress 'r' and ENTER to reset the buffer, 'f' and ENTER to flush, enter new text to send it, or just ENTER to exit...\n\n> ") + return nil +} + +func (c MyCallback) Warning(wr *msginterfaces.WarningResponse) error { + fmt.Printf("\n[Warning] Received\n") + fmt.Printf("Warning.Code: %s\n", wr.WarnCode) + fmt.Printf("Warning.Description: %s\n\n", wr.WarnMsg) return nil } func (c MyCallback) Error(er *msginterfaces.ErrorResponse) error { fmt.Printf("\n[Error] Received\n") - fmt.Printf("Error.Type: %s\n", er.Type) + fmt.Printf("Error.Code: %s\n", er.ErrCode) fmt.Printf("Error.Description: %s\n\n", er.Description) return nil } @@ -108,18 +117,9 @@ func main() { os.Exit(1) } - // Send the text input - err = dgClient.WriteJSON(map[string]interface{}{ - "type": "Speak", - "text": TTS_TEXT, - }) - if err != nil { - fmt.Printf("Error sending text input: %v\n", err) - return - } - // Simulate user input to reset the buffer, flush, send new text, or just exit - fmt.Print("\n\nPress 'r' and ENTER to reset the buffer, 'f' and ENTER to flush, enter new text to send it, or just ENTER to exit...\n\n") + time.Sleep(2 * time.Second) + fmt.Printf("\n\nPress 'r' and ENTER to reset the buffer, 'f' and ENTER to flush, enter new text to send it, or just ENTER to exit...\n\n> ") input := bufio.NewScanner(os.Stdin) for input.Scan() { switch input.Text() { @@ -140,15 +140,13 @@ func main() { case "": goto EXIT default: - err = dgClient.WriteJSON(map[string]interface{}{ - "type": "Speak", - "text": input.Text(), - }) + err = dgClient.SpeakWithText(input.Text()) if err != nil { fmt.Printf("Error sending text input: %v\n", err) } else { fmt.Println("Text sent successfully.") } + fmt.Printf("\n\nPress 'r' and ENTER to reset the buffer, 'f' and ENTER to flush, enter new text to send it, or just ENTER to exit...\n\n> ") } } diff --git a/examples/text-to-speech/websocket/simple/main.go b/examples/text-to-speech/websocket/simple/main.go index 0a196e81..67770406 100644 --- a/examples/text-to-speech/websocket/simple/main.go +++ b/examples/text-to-speech/websocket/simple/main.go @@ -56,10 +56,17 @@ func (c MyCallback) Flush(fl *msginterfaces.FlushedResponse) error { return nil } +func (c MyCallback) Warning(wr *msginterfaces.WarningResponse) error { + fmt.Printf("\n[Warning] Received\n") + fmt.Printf("Warning.Code: %s\n", wr.WarnCode) + fmt.Printf("Warning.Description: %s\n\n", wr.WarnMsg) + return nil +} + func (c MyCallback) Error(er *msginterfaces.ErrorResponse) error { fmt.Printf("\n[Error] Received\n") - fmt.Printf("Error.Type: %s\n", er.Type) - fmt.Printf("Error.Description: %s\n\n", er.Description) + fmt.Printf("Error.Code: %s\n", er.ErrCode) + fmt.Printf("Error.Description: %s\n\n", er.ErrMsg) return nil } @@ -106,10 +113,7 @@ func main() { } // Send the text input - err = dgClient.WriteJSON(map[string]interface{}{ - "type": "Speak", - "text": TTS_TEXT, - }) + err = dgClient.SpeakWithText(TTS_TEXT) if err != nil { fmt.Printf("Error sending text input: %v\n", err) return diff --git a/pkg/api/speak/v1/websocket/default.go b/pkg/api/speak/v1/websocket/default.go index 702b1343..b2fc33e3 100644 --- a/pkg/api/speak/v1/websocket/default.go +++ b/pkg/api/speak/v1/websocket/default.go @@ -154,6 +154,39 @@ func (dch DefaultCallbackHandler) Close(or *interfaces.CloseResponse) error { return nil } +// Warning is the callback for error messages +func (dch DefaultCallbackHandler) Warning(wr *interfaces.WarningResponse) error { + var debugStr string + if v := os.Getenv("DEEPGRAM_DEBUG"); v != "" { + klog.V(4).Infof("DEEPGRAM_DEBUG found") + debugStr = v + } + + if strings.EqualFold(debugStr, "true") { + data, err := json.Marshal(wr) + if err != nil { + klog.V(1).Infof("Error json.Marshal failed. Err: %v\n", err) + return err + } + + prettyJSON, err := prettyjson.Format(data) + if err != nil { + klog.V(1).Infof("prettyjson.Marshal failed. Err: %v\n", err) + return err + } + klog.V(2).Infof("\n\nWarning Object:\n%s\n\n", prettyJSON) + + return nil + } + + // handle the message + fmt.Printf("\n[WarningResponse]\n") + fmt.Printf("\nError.Code: %s\n", wr.WarnCode) + fmt.Printf("Error.Message: %s\n", wr.WarnMsg) + + return nil +} + // Error is the callback for error messages func (dch DefaultCallbackHandler) Error(er *interfaces.ErrorResponse) error { var debugStr string diff --git a/pkg/api/speak/v1/websocket/interfaces/constants.go b/pkg/api/speak/v1/websocket/interfaces/constants.go index 32f36386..63ddcff1 100644 --- a/pkg/api/speak/v1/websocket/interfaces/constants.go +++ b/pkg/api/speak/v1/websocket/interfaces/constants.go @@ -12,6 +12,7 @@ const ( TypeFlushedResponse string = "Flushed" TypeCloseResponse string = "Close" - // Error type - TypeErrorResponse string = "Error" + // "Error" type + TypeWarningResponse string = "Warning" + TypeErrorResponse string = "Error" ) diff --git a/pkg/api/speak/v1/websocket/interfaces/interfaces.go b/pkg/api/speak/v1/websocket/interfaces/interfaces.go index d77bb8c2..b6fb1a6c 100644 --- a/pkg/api/speak/v1/websocket/interfaces/interfaces.go +++ b/pkg/api/speak/v1/websocket/interfaces/interfaces.go @@ -8,11 +8,13 @@ package interfacesv1 // SpeakMessageCallback is a callback used to receive notifications for platforms messages type SpeakMessageCallback interface { // These are WS TextMessage that are used for flow control. + Open(or *OpenResponse) error Metadata(md *MetadataResponse) error Flush(fl *FlushedResponse) error - Error(er *ErrorResponse) error Close(cr *CloseResponse) error - Open(or *OpenResponse) error + + Warning(er *WarningResponse) error + Error(er *ErrorResponse) error // These are WS BinaryMessage that are used to send audio data to the client Binary(byMsg []byte) error diff --git a/pkg/api/speak/v1/websocket/interfaces/types.go b/pkg/api/speak/v1/websocket/interfaces/types.go index 995cc744..f4c7fb93 100644 --- a/pkg/api/speak/v1/websocket/interfaces/types.go +++ b/pkg/api/speak/v1/websocket/interfaces/types.go @@ -51,5 +51,8 @@ type CloseResponse struct { Type string `json:"type,omitempty"` } +// WarningResponse is the Deepgram specific response warning +type WarningResponse interfaces.DeepgramWarning + // ErrorResponse is the Deepgram specific response error type ErrorResponse interfaces.DeepgramError diff --git a/pkg/api/speak/v1/websocket/router.go b/pkg/api/speak/v1/websocket/router.go index 24b5bb65..a0e15116 100644 --- a/pkg/api/speak/v1/websocket/router.go +++ b/pkg/api/speak/v1/websocket/router.go @@ -93,6 +93,19 @@ func (r *MessageRouter) processMetadata(byMsg []byte) error { return r.processGeneric("MetadataResponse", byMsg, action, msg) } +func (r *MessageRouter) processWarningResponse(byMsg []byte) error { + var msg interfaces.WarningResponse + if err := json.Unmarshal(byMsg, &msg); err != nil { + return err + } + + action := func(data *interface{}) error { + return r.callback.Warning(&msg) + } + + return r.processGeneric("WarningResponse", byMsg, action, msg) +} + func (r *MessageRouter) processErrorResponse(byMsg []byte) error { var msg interfaces.ErrorResponse if err := json.Unmarshal(byMsg, &msg); err != nil { @@ -127,6 +140,8 @@ func (r *MessageRouter) Message(byMsg []byte) error { err = r.processFlushed(byMsg) case interfaces.TypeMetadataResponse: err = r.processMetadata(byMsg) + case interfaces.TypeWarningResponse: + err = r.processWarningResponse(byMsg) case interfaces.TypeErrorResponse: err = r.processErrorResponse(byMsg) default: diff --git a/pkg/client/common/v1/common.go b/pkg/client/common/v1/common.go index 9eeaf53a..8e328882 100644 --- a/pkg/client/common/v1/common.go +++ b/pkg/client/common/v1/common.go @@ -145,7 +145,8 @@ func decodeResponseBody(res *http.Response, keys []string, resBody interface{}) switch b := resBody.(type) { case *interfaces.RawResponse: klog.V(3).Infof("RawResponse\n") - return retValues, res.Write(b) + _, err := io.Copy(b, res.Body) + return retValues, err case io.Writer: klog.V(3).Infof("io.Writer\n") _, err := io.Copy(b, res.Body) diff --git a/pkg/client/interfaces/utils.go b/pkg/client/interfaces/utils.go index fc8013d3..7906f8e2 100644 --- a/pkg/client/interfaces/utils.go +++ b/pkg/client/interfaces/utils.go @@ -38,5 +38,6 @@ func WithCustomParameters(ctx context.Context, params map[string][]string) conte // common structs found throughout the SDK type RawResponse = interfacesv1.RawResponse +type DeepgramWarning = interfacesv1.DeepgramWarning type DeepgramError = interfacesv1.DeepgramError type StatusError = interfacesv1.StatusError diff --git a/pkg/client/interfaces/v1/utils.go b/pkg/client/interfaces/v1/utils.go index b7f951e1..9e88d4eb 100644 --- a/pkg/client/interfaces/v1/utils.go +++ b/pkg/client/interfaces/v1/utils.go @@ -15,7 +15,7 @@ import ( // constants const ( - sdkVersion string = "v1.2.0" + sdkVersion string = "v1.4.0" ) // DgAgent is the user agent string for the SDK @@ -69,6 +69,15 @@ type RawResponse struct { bytes.Buffer } +// DeepgramWarning is the Deepgram specific response warning +type DeepgramWarning struct { + Type string + WarnCode string `json:"warn_code,omitempty"` + WarnMsg string `json:"warn_msg,omitempty"` + Description string `json:"description,omitempty"` + Variant string `json:"variant,omitempty"` +} + // DeepgramError is the Deepgram specific response error type DeepgramError struct { Type string diff --git a/pkg/client/listen/client.go b/pkg/client/listen/client.go index 7535b742..ccbc7c1d 100644 --- a/pkg/client/listen/client.go +++ b/pkg/client/listen/client.go @@ -23,8 +23,14 @@ const ( RESTPackageVersion = listenv1rest.PackageVersion ) +// RestClient is an alias for listenv1rest.Client type RestClient = listenv1rest.Client +// PreRecordedClient is an alias for listenv1rest.Client +// +// Deprecated: This package is deprecated. Use RestClient instead. This will be removed in a future release. +type PreRecordedClient = listenv1rest.Client + /* NewRESTWithDefaults creates a new analyze/read client with all default options @@ -35,6 +41,11 @@ func NewRESTWithDefaults() *listenv1rest.Client { return listenv1rest.NewWithDefaults() } +// NewPreRecordedWithDefaults is an alias for NewRESTWithDefaults +// +// Deprecated: This package is deprecated. Use NewRESTWithDefaults instead. This will be removed in a future release. +var NewPreRecordedWithDefaults = NewRESTWithDefaults + /* NewREST creates a new prerecorded client with the specified options @@ -46,6 +57,11 @@ func NewREST(apiKey string, options *interfaces.ClientOptions) *listenv1rest.Cli return listenv1rest.New(apiKey, options) } +// NewPreRecorded is an alias for NewREST +// +// Deprecated: This package is deprecated. Use NewREST instead. This will be removed in a future release. +var NewPreRecorded = NewREST + /***********************************/ // LiveClient /***********************************/ @@ -53,8 +69,14 @@ const ( WebSocketPackageVersion = listenv1ws.PackageVersion ) +// WebSocketClient is an alias for listenv1ws.Client type WebSocketClient = listenv1ws.Client +// LiveClient is an alias for listenv1rest.Client +// +// Deprecated: This package is deprecated. Use WebSocketClient instead. This will be removed in a future release. +type LiveClient = listenv1ws.Client + /* NewWebSocketForDemo creates a new websocket connection with all default options @@ -65,6 +87,11 @@ func NewWebSocketForDemo(ctx context.Context, options *interfaces.LiveTranscript return listenv1ws.New(ctx, "", &interfaces.ClientOptions{}, options, nil) } +// NewLiveForDemo is an alias for NewWebSocketForDemo +// +// Deprecated: This package is deprecated. Use NewWebSocketForDemo instead. This will be removed in a future release. +var NewLiveForDemo = NewWebSocketForDemo + /* NewWebSocketWithDefaults creates a new websocket connection with all default options @@ -81,6 +108,11 @@ func NewWebSocketWithDefaults(ctx context.Context, tOptions *interfaces.LiveTran return listenv1ws.New(ctx, "", &interfaces.ClientOptions{}, tOptions, callback) } +// NewLiveWithDefaults is an alias for NewWebSocketWithDefaults +// +// Deprecated: This package is deprecated. Use NewWebSocketWithDefaults instead. This will be removed in a future release. +var NewLiveWithDefaults = NewWebSocketWithDefaults + /* NewWebSocket creates a new websocket connection with the specified options @@ -100,6 +132,11 @@ func NewWebSocket(ctx context.Context, apiKey string, cOptions *interfaces.Clien return listenv1ws.NewWithCancel(ctx, ctxCancel, apiKey, cOptions, tOptions, callback) } +// NewLive is an alias for NewWebSocket +// +// Deprecated: This package is deprecated. Use NewWebSocket instead. This will be removed in a future release. +var NewLive = NewWebSocket + /* NewWebSocketWithCancel creates a new websocket connection but has facilities to BYOC (Bring Your Own Cancel) @@ -118,3 +155,8 @@ Notes: func NewWebSocketWithCancel(ctx context.Context, ctxCancel context.CancelFunc, apiKey string, cOptions *interfaces.ClientOptions, tOptions *interfaces.LiveTranscriptionOptions, callback msginterfaces.LiveMessageCallback) (*listenv1ws.Client, error) { return listenv1ws.NewWithCancel(ctx, ctxCancel, apiKey, cOptions, tOptions, callback) } + +// NewLiveWithCancel is an alias for NewWebSocketWithCancel +// +// Deprecated: This package is deprecated. Use NewWebSocketWithCancel instead. This will be removed in a future release. +var NewLiveWithCancel = NewWebSocketWithCancel diff --git a/pkg/client/listen/v1/websocket/client.go b/pkg/client/listen/v1/websocket/client.go index 51b79391..e20dc764 100644 --- a/pkg/client/listen/v1/websocket/client.go +++ b/pkg/client/listen/v1/websocket/client.go @@ -292,10 +292,29 @@ func (c *Client) internalConnectWithCancel(ctx context.Context, ctxCancel contex return nil } -// this is a complex function. keep as is +//nolint:funlen,gocyclo // this is a complex function. keep as is func (c *Client) listen() { klog.V(6).Infof("live.listen() ENTER\n") + defer func() { + if r := recover(); r != nil { + klog.V(1).Infof("Panic triggered\n") + + // send error on callback + err := ErrFatalPanicRecovered + sendErr := c.sendError(err) + if sendErr != nil { + klog.V(1).Infof("listen: Fatal socket error. Err: %v\n", sendErr) + } + + // fatal close + c.closeWs(true) + + klog.V(6).Infof("live.listen() LEAVE\n") + return + } + }() + for { // doing a read, need to lock c.muConn.Lock() @@ -721,7 +740,25 @@ func (c *Client) closeWs(fatal bool) { func (c *Client) ping() { klog.V(6).Infof("live.ping() ENTER\n") - counter := 0 + defer func() { + if r := recover(); r != nil { + klog.V(1).Infof("Panic triggered\n") + + // send error on callback + err := ErrFatalPanicRecovered + sendErr := c.sendError(err) + if sendErr != nil { + klog.V(1).Infof("listen: Fatal socket error. Err: %v\n", sendErr) + } + + // fatal close + c.closeWs(true) + + klog.V(6).Infof("live.ping() LEAVE\n") + return + } + }() + ticker := time.NewTicker(pingPeriod) defer ticker.Stop() for { @@ -736,7 +773,6 @@ func (c *Client) ping() { return case <-ticker.C: klog.V(5).Infof("Starting ping...") - counter++ // deepgram keepalive message klog.V(5).Infof("Sending Deepgram KeepAlive message...\n") @@ -754,6 +790,25 @@ func (c *Client) ping() { func (c *Client) flush() { klog.V(6).Infof("live.flush() ENTER\n") + defer func() { + if r := recover(); r != nil { + klog.V(1).Infof("Panic triggered\n") + + // send error on callback + err := ErrFatalPanicRecovered + sendErr := c.sendError(err) + if sendErr != nil { + klog.V(1).Infof("listen: Fatal socket error. Err: %v\n", sendErr) + } + + // fatal close + c.closeWs(true) + + klog.V(6).Infof("live.flush() LEAVE\n") + return + } + }() + ticker := time.NewTicker(flushPeriod) defer ticker.Stop() for { @@ -845,12 +900,12 @@ func (c *Client) errorToResponse(err error) *msginterfaces.ErrorResponse { // inspectMessage inspects the message and determines the type to // see if we should do anything with those types of messages func (c *Client) inspect(byMsg []byte) error { - klog.V(7).Infof("client.inspect() ENTER\n") + klog.V(7).Infof("live.inspect() ENTER\n") var mt msginterfaces.MessageType if err := json.Unmarshal(byMsg, &mt); err != nil { klog.V(1).Infof("json.Unmarshal(MessageType) failed. Err: %v\n", err) - klog.V(7).Infof("client.inspect() LEAVE\n") + klog.V(7).Infof("live.inspect() LEAVE\n") return err } @@ -862,7 +917,7 @@ func (c *Client) inspect(byMsg []byte) error { var mr msginterfaces.MessageResponse if err := json.Unmarshal(byMsg, &mr); err != nil { klog.V(1).Infof("json.Unmarshal(MessageResponse) failed. Err: %v\n", err) - klog.V(7).Infof("client.inspect() LEAVE\n") + klog.V(7).Infof("live.inspect() LEAVE\n") return err } @@ -870,7 +925,7 @@ func (c *Client) inspect(byMsg []byte) error { err := c.inspectMessage(&mr) if err != nil { klog.V(1).Infof("inspectMessage() failed. Err: %v\n", err) - klog.V(7).Infof("client.inspect() LEAVE\n") + klog.V(7).Infof("live.inspect() LEAVE\n") return err } default: @@ -878,17 +933,17 @@ func (c *Client) inspect(byMsg []byte) error { } klog.V(7).Info("inspect() succeeded\n") - klog.V(7).Infof("client.inspect() LEAVE\n") + klog.V(7).Infof("live.inspect() LEAVE\n") return nil } func (c *Client) inspectMessage(mr *msginterfaces.MessageResponse) error { - klog.V(7).Infof("client.inspectMessage() ENTER\n") + klog.V(7).Infof("live.inspectMessage() ENTER\n") sentence := strings.TrimSpace(mr.Channel.Alternatives[0].Transcript) if len(mr.Channel.Alternatives) == 0 || sentence == "" { klog.V(7).Info("inspectMessage is empty\n") - klog.V(7).Infof("client.inspectMessage() LEAVE\n") + klog.V(7).Infof("live.inspectMessage() LEAVE\n") return nil } @@ -910,6 +965,6 @@ func (c *Client) inspectMessage(mr *msginterfaces.MessageResponse) error { } klog.V(7).Info("inspectMessage() succeeded\n") - klog.V(7).Infof("client.inspectMessage() LEAVE\n") + klog.V(7).Infof("live.inspectMessage() LEAVE\n") return nil } diff --git a/pkg/client/listen/v1/websocket/constants.go b/pkg/client/listen/v1/websocket/constants.go index 02d09511..4f8bc3f0 100644 --- a/pkg/client/listen/v1/websocket/constants.go +++ b/pkg/client/listen/v1/websocket/constants.go @@ -45,6 +45,9 @@ var ( // ErrInvalidConnection connection is not valid ErrInvalidConnection = errors.New("connection is not valid") + + // ErrFatalPanicRecovered fatal panic recovered + ErrFatalPanicRecovered = errors.New("fatal panic - attempt to recover") ) // internal constants for retry, waits, back-off, etc. diff --git a/pkg/client/speak/client.go b/pkg/client/speak/client.go index 692e1d72..f3968f79 100644 --- a/pkg/client/speak/client.go +++ b/pkg/client/speak/client.go @@ -36,6 +36,8 @@ NewWithDefaults creates a new speak client with all default options Notes: - The Deepgram API KEY is read from the environment variable DEEPGRAM_API_KEY + +Deprecated: This function is deprecated. Please use NewREST(). This will be removed in a future release. */ func NewWithDefaults() *speakv1rest.Client { return speakv1rest.NewWithDefaults() @@ -55,6 +57,16 @@ func New(apiKey string, options *interfaces.ClientOptions) *speakv1rest.Client { return speakv1rest.New(apiKey, options) } +/* +NewRESTWithDefaults creates a new speak client with all default options + +Notes: + - The Deepgram API KEY is read from the environment variable DEEPGRAM_API_KEY +*/ +func NewRESTWithDefaults() *speakv1rest.Client { + return speakv1rest.NewWithDefaults() +} + /* New creates a new speak client with the specified options diff --git a/pkg/client/speak/v1/rest/client.go b/pkg/client/speak/v1/rest/client.go index 211c361e..7f759cfb 100644 --- a/pkg/client/speak/v1/rest/client.go +++ b/pkg/client/speak/v1/rest/client.go @@ -6,9 +6,7 @@ package restv1 import ( - "bytes" "context" - "encoding/json" "net/http" "strings" @@ -79,15 +77,18 @@ func (c *Client) DoText(ctx context.Context, text string, options *interfaces.Sp return nil, err } - var buf bytes.Buffer - err = json.NewEncoder(&buf).Encode(textSource{Text: text}) - if err != nil { - klog.V(1).Infof("json.NewEncoder().Encode() failed. Err: %v\n", err) - klog.V(6).Infof("speak.DoURL() LEAVE\n") - return nil, err - } - - req, err := c.SetupRequest(ctx, "POST", uri, strings.NewReader(buf.String())) + // TODO: detect if the source is JSON. If not, then wrap the text in a JSON object + // and then marshal it to bytes + // var buf bytes.Buffer + // err = json.NewEncoder(&buf).Encode(textSource{Text: text}) + // if err != nil { + // klog.V(1).Infof("json.NewEncoder().Encode() failed. Err: %v\n", err) + // klog.V(6).Infof("speak.DoURL() LEAVE\n") + // return nil, err + // } + + // req, err := c.SetupRequest(ctx, "POST", uri, strings.NewReader(buf.String())) + req, err := c.SetupRequest(ctx, "POST", uri, strings.NewReader(text)) if err != nil { klog.V(1).Infof("SetupRequest failed. Err: %v\n", err) klog.V(6).Infof("prerecorded.DoStream() LEAVE\n") diff --git a/pkg/client/speak/v1/websocket/client.go b/pkg/client/speak/v1/websocket/client.go index 5e78d464..e9af18b4 100644 --- a/pkg/client/speak/v1/websocket/client.go +++ b/pkg/client/speak/v1/websocket/client.go @@ -29,6 +29,7 @@ type controlMessage struct { Type string `json:"type"` } type TextSource struct { + Type string `json:"type"` Text string `json:"text"` } @@ -87,7 +88,7 @@ Notes: - The callback handler is set to the default handler */ func NewWebSocketWithCancel(ctx context.Context, ctxCancel context.CancelFunc, apiKey string, cOptions *interfaces.ClientOptions, sOptions *interfaces.SpeakOptions, callback msginterfaces.SpeakMessageCallback) (*Client, error) { - klog.V(6).Infof("Client.New() ENTER\n") + klog.V(6).Infof("speak.New() ENTER\n") if apiKey != "" { cOptions.APIKey = apiKey @@ -121,7 +122,7 @@ func NewWebSocketWithCancel(ctx context.Context, ctxCancel context.CancelFunc, a } klog.V(3).Infof("NewDeepGramWSClient Succeeded\n") - klog.V(6).Infof("Client.New() LEAVE\n") + klog.V(6).Infof("speak.New() LEAVE\n") return &conn, nil } @@ -160,7 +161,7 @@ func (c *Client) internalConnect() *websocket.Conn { //nolint:funlen // this is a complex function. keep as is func (c *Client) internalConnectWithCancel(ctx context.Context, ctxCancel context.CancelFunc, retryCnt int, lock bool) *websocket.Conn { - klog.V(7).Infof("Client.internalConnectWithCancel() ENTER\n") + klog.V(7).Infof("speak.internalConnectWithCancel() ENTER\n") // set the context c.ctx = ctx @@ -170,7 +171,7 @@ func (c *Client) internalConnectWithCancel(ctx context.Context, ctxCancel contex // we explicitly stopped and should not attempt to reconnect if !c.retry { klog.V(7).Infof("This connection has been terminated. Please either call with AttemptReconnect or create a new Client object using NewWebSocketClient.") - klog.V(7).Infof("Client.internalConnectWithCancel() LEAVE\n") + klog.V(7).Infof("speak.internalConnectWithCancel() LEAVE\n") return nil } @@ -186,11 +187,11 @@ func (c *Client) internalConnectWithCancel(ctx context.Context, ctxCancel contex select { case <-c.ctx.Done(): klog.V(1).Infof("Connection is not valid\n") - klog.V(7).Infof("Client.internalConnectWithCancel() LEAVE\n") + klog.V(7).Infof("speak.internalConnectWithCancel() LEAVE\n") return nil default: klog.V(7).Infof("Connection is good. Return object.") - klog.V(7).Infof("Client.internalConnectWithCancel() LEAVE\n") + klog.V(7).Infof("speak.internalConnectWithCancel() LEAVE\n") return c.wsconn } } else { @@ -251,7 +252,7 @@ func (c *Client) internalConnectWithCancel(ctx context.Context, ctxCancel contex url, err := version.GetSpeakStreamAPI(c.ctx, c.cOptions.Host, c.cOptions.APIVersion, c.cOptions.Path, c.sOptions) if err != nil { klog.V(1).Infof("version.GetSpeakAPI failed. Err: %v\n", err) - klog.V(7).Infof("Client.internalConnectWithCancel() LEAVE\n") + klog.V(7).Infof("speak.internalConnectWithCancel() LEAVE\n") return nil // no point in retrying because this is going to fail on every retry } klog.V(5).Infof("Connecting to %s\n", url) @@ -284,21 +285,40 @@ func (c *Client) internalConnectWithCancel(ctx context.Context, ctxCancel contex } klog.V(3).Infof("WebSocket Connection Successful!") - klog.V(7).Infof("Client.internalConnectWithCancel() LEAVE\n") + klog.V(7).Infof("speak.internalConnectWithCancel() LEAVE\n") return c.wsconn } // if we get here, we failed to connect klog.V(1).Infof("Failed to connect to websocket: %s\n", c.cOptions.Host) - klog.V(7).Infof("Client.ConnectWithRetry() LEAVE\n") + klog.V(7).Infof("speak.ConnectWithRetry() LEAVE\n") return nil } -//nolint:funlen // this is a complex function. keep as is +//nolint:funlen,gocyclo // this is a complex function. keep as is func (c *Client) listen() { - klog.V(6).Infof("Client.listen() ENTER\n") + klog.V(6).Infof("speak.listen() ENTER\n") + + defer func() { + if r := recover(); r != nil { + klog.V(1).Infof("Panic triggered\n") + + // send error on callback + err := ErrFatalPanicRecovered + sendErr := c.sendError(err) + if sendErr != nil { + klog.V(1).Infof("listen: Fatal socket error. Err: %v\n", sendErr) + } + + // fatal close + c.closeWs(true) + + klog.V(6).Infof("live.flush() LEAVE\n") + return + } + }() for { // doing a read, need to lock @@ -330,7 +350,7 @@ func (c *Client) listen() { // graceful close c.closeWs(false) - klog.V(6).Infof("Client.listen() LEAVE\n") + klog.V(6).Infof("speak.listen() LEAVE\n") return case strings.Contains(errStr, UseOfClosedSocket): klog.V(3).Infof("Probable graceful websocket close: %v\n", err) @@ -338,7 +358,7 @@ func (c *Client) listen() { // fatal close c.closeWs(false) - klog.V(6).Infof("Client.listen() LEAVE\n") + klog.V(6).Infof("speak.listen() LEAVE\n") return case strings.Contains(errStr, FatalReadSocketErr): klog.V(1).Infof("Fatal socket error: %v\n", err) @@ -346,27 +366,27 @@ func (c *Client) listen() { // send error on callback sendErr := c.sendError(err) if sendErr != nil { - klog.V(1).Infof("Client.listen(): Fatal socket error. Err: %v\n", sendErr) + klog.V(1).Infof("speak.listen(): Fatal socket error. Err: %v\n", sendErr) } // fatal close c.closeWs(true) - klog.V(6).Infof("Client.listen() LEAVE\n") + klog.V(6).Infof("speak.listen() LEAVE\n") return case strings.Contains(errStr, "Deepgram"): - klog.V(1).Infof("Client.listen(): Deepgram error. Err: %v\n", err) + klog.V(1).Infof("speak.listen(): Deepgram error. Err: %v\n", err) // send error on callback sendErr := c.sendError(err) if sendErr != nil { - klog.V(1).Infof("Client.listen(): Deepgram ErrorMsg. Err: %v\n", sendErr) + klog.V(1).Infof("speak.listen(): Deepgram ErrorMsg. Err: %v\n", sendErr) } // close the connection c.closeWs(false) - klog.V(6).Infof("Client.listen() LEAVE\n") + klog.V(6).Infof("speak.listen() LEAVE\n") return case (err == io.EOF || err == io.ErrUnexpectedEOF) && !c.retry: klog.V(3).Infof("Client object EOF\n") @@ -374,27 +394,27 @@ func (c *Client) listen() { // send error on callback sendErr := c.sendError(err) if sendErr != nil { - klog.V(1).Infof("Client.listen(): EOF error. Err: %v\n", sendErr) + klog.V(1).Infof("speak.listen(): EOF error. Err: %v\n", sendErr) } // close the connection c.closeWs(true) - klog.V(6).Infof("Client.listen() LEAVE\n") + klog.V(6).Infof("speak.listen() LEAVE\n") return default: - klog.V(1).Infof("Client.listen(): Cannot read websocket message. Err: %v\n", err) + klog.V(1).Infof("speak.listen(): Cannot read websocket message. Err: %v\n", err) // send error on callback sendErr := c.sendError(err) if sendErr != nil { - klog.V(1).Infof("Client.listen(): EOF error. Err: %v\n", sendErr) + klog.V(1).Infof("speak.listen(): EOF error. Err: %v\n", sendErr) } // close the connection c.closeWs(true) - klog.V(6).Infof("Client.listen() LEAVE\n") + klog.V(6).Infof("speak.listen() LEAVE\n") return } } @@ -408,7 +428,7 @@ func (c *Client) listen() { // if c.cOptions.InspectMessage() { // err := c.inspect(byMsg) // if err != nil { - // klog.V(1).Infof("Client.listen(): inspect failed. Err: %v\n", err) + // klog.V(1).Infof("speak.listen(): inspect failed. Err: %v\n", err) // } // } @@ -416,39 +436,43 @@ func (c *Client) listen() { case websocket.TextMessage: err := c.router.Message(byMsg) if err != nil { - klog.V(1).Infof("Client.listen(): router.Message failed. Err: %v\n", err) + klog.V(1).Infof("speak.listen(): router.Message failed. Err: %v\n", err) } case websocket.BinaryMessage: err := c.router.Binary(byMsg) if err != nil { - klog.V(1).Infof("Client.listen(): router.Message failed. Err: %v\n", err) + klog.V(1).Infof("speak.listen(): router.Message failed. Err: %v\n", err) } default: - klog.V(7).Infof("Client.listen(): msg recv: type %d, len: %d\n", msgType, len(byMsg)) + klog.V(7).Infof("speak.listen(): msg recv: type %d, len: %d\n", msgType, len(byMsg)) } } } -// WriteBinary writes binary data to the websocket server -func (c *Client) SpeakUsingText(text string) error { - klog.V(6).Infof("Client.SpeakText() ENTER\n") +// SpeakWithText writes binary data to the websocket server +func (c *Client) SpeakWithText(text string) error { + klog.V(6).Infof("speak.SpeakText() ENTER\n") klog.V(4).Infof("text: %s\n", text) - err := c.WriteJSON(TextSource{Text: text}) + err := c.WriteJSON(TextSource{ + Type: MessageTypeSpeak, + Text: text, + }) if err == nil { klog.V(4).Infof("SpeakText Succeeded\n") } else { klog.V(1).Infof("SpeakText failed. Err: %v\n", err) } - klog.V(6).Infof("Client.SpeakText() LEAVE\n") + klog.V(6).Infof("speak.SpeakText() LEAVE\n") return err } -// WriteBinary writes binary data to the websocket server -func (c *Client) SpeakUsingStream(byData []byte) error { - klog.V(6).Infof("Client.SpeakText() ENTER\n") +// SpeakWithStream writes binary data to the websocket server +// NOTE: This is unimplemented on the server side +func (c *Client) SpeakWithStream(byData []byte) error { + klog.V(6).Infof("speak.SpeakText() ENTER\n") err := c.WriteBinary(byData) if err == nil { @@ -457,14 +481,14 @@ func (c *Client) SpeakUsingStream(byData []byte) error { klog.V(1).Infof("SpeakText failed. Err: %v\n", err) } - klog.V(6).Infof("Client.SpeakText() LEAVE\n") + klog.V(6).Infof("speak.SpeakText() LEAVE\n") return err } // WriteBinary writes binary data to the websocket server func (c *Client) WriteBinary(byData []byte) error { - klog.V(6).Infof("Client.WriteBinary() ENTER\n") + klog.V(6).Infof("speak.WriteBinary() ENTER\n") // doing a write, need to lock c.muConn.Lock() @@ -475,7 +499,7 @@ func (c *Client) WriteBinary(byData []byte) error { if ws == nil { err := ErrInvalidConnection klog.V(1).Infof("c.Connect() is nil. Err: %v\n", err) - klog.V(6).Infof("Client.WriteBinary() LEAVE\n") + klog.V(6).Infof("speak.WriteBinary() LEAVE\n") return err } @@ -485,13 +509,13 @@ func (c *Client) WriteBinary(byData []byte) error { byData, ); err != nil { klog.V(1).Infof("WriteBinary WriteMessage failed. Err: %v\n", err) - klog.V(6).Infof("Client.WriteBinary() LEAVE\n") + klog.V(6).Infof("speak.WriteBinary() LEAVE\n") return err } klog.V(6).Infof("WriteBinary Successful\n") klog.V(7).Infof("payload: %x\n", byData) - klog.V(6).Infof("Client.WriteBinary() LEAVE\n") + klog.V(6).Infof("speak.WriteBinary() LEAVE\n") return nil } @@ -501,12 +525,12 @@ WriteJSON writes a JSON control payload to the websocket server. These are contr managing the text-to-speech session on the Deepgram server. */ func (c *Client) WriteJSON(payload interface{}) error { - klog.V(6).Infof("Client.WriteJSON() ENTER\n") + klog.V(6).Infof("speak.WriteJSON() ENTER\n") byData, err := json.Marshal(payload) if err != nil { klog.V(1).Infof("WriteJSON: Error marshaling JSON. Data: %v, Err: %v\n", payload, err) - klog.V(6).Infof("Client.WriteJSON() LEAVE\n") + klog.V(6).Infof("speak.WriteJSON() LEAVE\n") return err } @@ -519,7 +543,7 @@ func (c *Client) WriteJSON(payload interface{}) error { if ws == nil { err := ErrInvalidConnection klog.V(1).Infof("c.internalConnect() is nil. Err: %v\n", err) - klog.V(6).Infof("Client.WriteJSON() LEAVE\n") + klog.V(6).Infof("speak.WriteJSON() LEAVE\n") return err } @@ -528,54 +552,54 @@ func (c *Client) WriteJSON(payload interface{}) error { byData, ); err != nil { klog.V(1).Infof("WriteJSON WriteMessage failed. Err: %v\n", err) - klog.V(6).Infof("Client.WriteJSON() LEAVE\n") + klog.V(6).Infof("speak.WriteJSON() LEAVE\n") return err } klog.V(4).Infof("WriteJSON succeeded.\n") klog.V(7).Infof("payload: %s\n", string(byData)) - klog.V(6).Infof("Client.WriteJSON() LEAVE\n") + klog.V(6).Infof("speak.WriteJSON() LEAVE\n") return nil } // Flush will instruct the server to flush the current text buffer func (c *Client) Flush() error { - klog.V(6).Infof("Client.Flush() ENTER\n") + klog.V(6).Infof("speak.Flush() ENTER\n") err := c.WriteJSON(controlMessage{Type: MessageTypeFlush}) if err != nil { klog.V(1).Infof("Flush failed. Err: %v\n", err) - klog.V(6).Infof("Client.Flush() LEAVE\n") + klog.V(6).Infof("speak.Flush() LEAVE\n") return err } klog.V(4).Infof("Flush Succeeded\n") - klog.V(6).Infof("Client.Flush() LEAVE\n") + klog.V(6).Infof("speak.Flush() LEAVE\n") return err } // Reset will instruct the server to reset the current buffer func (c *Client) Reset() error { - klog.V(6).Infof("Client.Reset() ENTER\n") + klog.V(6).Infof("speak.Reset() ENTER\n") err := c.WriteJSON(controlMessage{Type: MessageTypeReset}) if err != nil { klog.V(1).Infof("Reset failed. Err: %v\n", err) - klog.V(6).Infof("Client.Reset() LEAVE\n") + klog.V(6).Infof("speak.Reset() LEAVE\n") return err } klog.V(4).Infof("Reset Succeeded\n") - klog.V(6).Infof("Client.Reset() LEAVE\n") + klog.V(6).Infof("speak.Reset() LEAVE\n") return nil } func (c *Client) closeStream(lock bool) error { - klog.V(6).Infof("Client.closeStream() ENTER\n") + klog.V(6).Infof("speak.closeStream() ENTER\n") // doing a write, need to lock if lock { @@ -586,19 +610,19 @@ func (c *Client) closeStream(lock bool) error { err := c.wsconn.WriteMessage(websocket.TextMessage, []byte("{ \"type\": \"Close\" }")) if err != nil { klog.V(1).Infof("WriteMessage failed. Err: %v\n", err) - klog.V(6).Infof("Client.closeStream() LEAVE\n") + klog.V(6).Infof("speak.closeStream() LEAVE\n") return err } klog.V(4).Infof("closeStream Succeeded\n") - klog.V(6).Infof("Client.closeStream() LEAVE\n") + klog.V(6).Infof("speak.closeStream() LEAVE\n") return err } func (c *Client) normalClosure(lock bool) error { - klog.V(6).Infof("Client.normalClosure() ENTER\n") + klog.V(6).Infof("speak.normalClosure() ENTER\n") // doing a write, need to lock if lock { @@ -610,7 +634,7 @@ func (c *Client) normalClosure(lock bool) error { if ws == nil { err := ErrInvalidConnection klog.V(1).Infof("c.internalConnect() is nil. Err: %v\n", err) - klog.V(6).Infof("Client.normalClosure() LEAVE\n") + klog.V(6).Infof("speak.normalClosure() LEAVE\n") return err } @@ -625,7 +649,7 @@ func (c *Client) normalClosure(lock bool) error { klog.V(1).Infof("Failed to send CloseNormalClosure. Err: %v\n", err) } - klog.V(6).Infof("Client.normalClosure() LEAVE\n") + klog.V(6).Infof("speak.normalClosure() LEAVE\n") return err } @@ -641,7 +665,7 @@ func (c *Client) Stop() { } func (c *Client) closeWs(fatal bool) { - klog.V(6).Infof("Client.closeWs() closing channels...\n") + klog.V(6).Infof("speak.closeWs() closing channels...\n") // doing a write, need to lock c.muConn.Lock() @@ -673,8 +697,8 @@ func (c *Client) closeWs(fatal bool) { c.wsconn = nil } - klog.V(4).Infof("Client.closeWs() Succeeded\n") - klog.V(6).Infof("Client.closeWs() LEAVE\n") + klog.V(4).Infof("speak.closeWs() Succeeded\n") + klog.V(6).Infof("speak.closeWs() LEAVE\n") } // sendError sends an error message to the callback handler @@ -682,7 +706,7 @@ func (c *Client) sendError(err error) error { response := c.errorToResponse(err) sendErr := c.router.ErrorHelper(response) if err != nil { - klog.V(1).Infof("Client.listen(): router.Error failed. Err: %v\n", sendErr) + klog.V(1).Infof("speak.listen(): router.Error failed. Err: %v\n", sendErr) } return err diff --git a/pkg/client/speak/v1/websocket/constants.go b/pkg/client/speak/v1/websocket/constants.go index 030d2335..d5ad627e 100644 --- a/pkg/client/speak/v1/websocket/constants.go +++ b/pkg/client/speak/v1/websocket/constants.go @@ -31,6 +31,9 @@ const ( ) const ( + // MessageTypeFlush flushes the audio from the server + MessageTypeSpeak string = "Speak" + // MessageTypeFlush flushes the audio from the server MessageTypeFlush string = "Flush" @@ -48,6 +51,9 @@ var ( // ErrInvalidConnection connection is not valid ErrInvalidConnection = errors.New("connection is not valid") + + // ErrFatalPanicRecovered fatal panic recovered + ErrFatalPanicRecovered = errors.New("fatal panic - attempt to recover") ) // internal constants for retry, waits, back-off, etc.