1// Copyright 2021 Google LLC 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// https://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15// Code generated by protoc-gen-go_gapic. DO NOT EDIT. 16 17package speech 18 19import ( 20 "context" 21 "math" 22 "time" 23 24 "cloud.google.com/go/longrunning" 25 lroauto "cloud.google.com/go/longrunning/autogen" 26 gax "github.com/googleapis/gax-go/v2" 27 "google.golang.org/api/option" 28 "google.golang.org/api/option/internaloption" 29 gtransport "google.golang.org/api/transport/grpc" 30 speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" 31 longrunningpb "google.golang.org/genproto/googleapis/longrunning" 32 "google.golang.org/grpc" 33 "google.golang.org/grpc/codes" 34 "google.golang.org/grpc/metadata" 35) 36 37var newClientHook clientHook 38 39// CallOptions contains the retry settings for each method of Client. 40type CallOptions struct { 41 Recognize []gax.CallOption 42 LongRunningRecognize []gax.CallOption 43 StreamingRecognize []gax.CallOption 44} 45 46func defaultGRPCClientOptions() []option.ClientOption { 47 return []option.ClientOption{ 48 internaloption.WithDefaultEndpoint("speech.googleapis.com:443"), 49 internaloption.WithDefaultMTLSEndpoint("speech.mtls.googleapis.com:443"), 50 internaloption.WithDefaultAudience("https://speech.googleapis.com/"), 51 internaloption.WithDefaultScopes(DefaultAuthScopes()...), 52 internaloption.EnableJwtWithScope(), 53 option.WithGRPCDialOption(grpc.WithDisableServiceConfig()), 54 option.WithGRPCDialOption(grpc.WithDefaultCallOptions( 55 grpc.MaxCallRecvMsgSize(math.MaxInt32))), 56 } 57} 58 59func defaultCallOptions() *CallOptions { 60 return &CallOptions{ 61 Recognize: []gax.CallOption{ 62 gax.WithRetry(func() gax.Retryer { 63 return gax.OnCodes([]codes.Code{ 64 codes.Unavailable, 65 codes.DeadlineExceeded, 66 }, gax.Backoff{ 67 Initial: 100 * time.Millisecond, 68 Max: 60000 * time.Millisecond, 69 Multiplier: 1.30, 70 }) 71 }), 72 }, 73 LongRunningRecognize: []gax.CallOption{}, 74 StreamingRecognize: []gax.CallOption{ 75 gax.WithRetry(func() gax.Retryer { 76 return gax.OnCodes([]codes.Code{ 77 codes.Unavailable, 78 codes.DeadlineExceeded, 79 }, gax.Backoff{ 80 Initial: 100 * time.Millisecond, 81 Max: 60000 * time.Millisecond, 82 Multiplier: 1.30, 83 }) 84 }), 85 }, 86 } 87} 88 89// internalClient is an interface that defines the methods availaible from Cloud Speech-to-Text API. 90type internalClient interface { 91 Close() error 92 setGoogleClientInfo(...string) 93 Connection() *grpc.ClientConn 94 Recognize(context.Context, *speechpb.RecognizeRequest, ...gax.CallOption) (*speechpb.RecognizeResponse, error) 95 LongRunningRecognize(context.Context, *speechpb.LongRunningRecognizeRequest, ...gax.CallOption) (*LongRunningRecognizeOperation, error) 96 LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation 97 StreamingRecognize(context.Context, ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) 98} 99 100// Client is a client for interacting with Cloud Speech-to-Text API. 101// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. 102// 103// Service that implements Google Cloud Speech API. 104type Client struct { 105 // The internal transport-dependent client. 106 internalClient internalClient 107 108 // The call options for this service. 109 CallOptions *CallOptions 110 111 // LROClient is used internally to handle long-running operations. 112 // It is exposed so that its CallOptions can be modified if required. 113 // Users should not Close this client. 114 LROClient *lroauto.OperationsClient 115} 116 117// Wrapper methods routed to the internal client. 118 119// Close closes the connection to the API service. The user should invoke this when 120// the client is no longer required. 121func (c *Client) Close() error { 122 return c.internalClient.Close() 123} 124 125// setGoogleClientInfo sets the name and version of the application in 126// the `x-goog-api-client` header passed on each request. Intended for 127// use by Google-written clients. 128func (c *Client) setGoogleClientInfo(keyval ...string) { 129 c.internalClient.setGoogleClientInfo(keyval...) 130} 131 132// Connection returns a connection to the API service. 133// 134// Deprecated. 135func (c *Client) Connection() *grpc.ClientConn { 136 return c.internalClient.Connection() 137} 138 139// Recognize performs synchronous speech recognition: receive results after all audio 140// has been sent and processed. 141func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { 142 return c.internalClient.Recognize(ctx, req, opts...) 143} 144 145// LongRunningRecognize performs asynchronous speech recognition: receive results via the 146// google.longrunning.Operations interface. Returns either an 147// Operation.error or an Operation.response which contains 148// a LongRunningRecognizeResponse message. 149// For more information on asynchronous speech recognition, see the 150// how-to (at https://cloud.google.com/speech-to-text/docs/async-recognize). 151func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { 152 return c.internalClient.LongRunningRecognize(ctx, req, opts...) 153} 154 155// LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. 156// The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. 157func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { 158 return c.internalClient.LongRunningRecognizeOperation(name) 159} 160 161// StreamingRecognize performs bidirectional streaming speech recognition: receive results while 162// sending audio. This method is only available via the gRPC API (not REST). 163func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { 164 return c.internalClient.StreamingRecognize(ctx, opts...) 165} 166 167// gRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. 168// 169// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. 170type gRPCClient struct { 171 // Connection pool of gRPC connections to the service. 172 connPool gtransport.ConnPool 173 174 // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE 175 disableDeadlines bool 176 177 // Points back to the CallOptions field of the containing Client 178 CallOptions **CallOptions 179 180 // The gRPC API client. 181 client speechpb.SpeechClient 182 183 // LROClient is used internally to handle long-running operations. 184 // It is exposed so that its CallOptions can be modified if required. 185 // Users should not Close this client. 186 LROClient **lroauto.OperationsClient 187 188 // The x-goog-* metadata to be sent with each request. 189 xGoogMetadata metadata.MD 190} 191 192// NewClient creates a new speech client based on gRPC. 193// The returned client must be Closed when it is done being used to clean up its underlying connections. 194// 195// Service that implements Google Cloud Speech API. 196func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { 197 clientOpts := defaultGRPCClientOptions() 198 if newClientHook != nil { 199 hookOpts, err := newClientHook(ctx, clientHookParams{}) 200 if err != nil { 201 return nil, err 202 } 203 clientOpts = append(clientOpts, hookOpts...) 204 } 205 206 disableDeadlines, err := checkDisableDeadlines() 207 if err != nil { 208 return nil, err 209 } 210 211 connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) 212 if err != nil { 213 return nil, err 214 } 215 client := Client{CallOptions: defaultCallOptions()} 216 217 c := &gRPCClient{ 218 connPool: connPool, 219 disableDeadlines: disableDeadlines, 220 client: speechpb.NewSpeechClient(connPool), 221 CallOptions: &client.CallOptions, 222 } 223 c.setGoogleClientInfo() 224 225 client.internalClient = c 226 227 client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) 228 if err != nil { 229 // This error "should not happen", since we are just reusing old connection pool 230 // and never actually need to dial. 231 // If this does happen, we could leak connp. However, we cannot close conn: 232 // If the user invoked the constructor with option.WithGRPCConn, 233 // we would close a connection that's still in use. 234 // TODO: investigate error conditions. 235 return nil, err 236 } 237 c.LROClient = &client.LROClient 238 return &client, nil 239} 240 241// Connection returns a connection to the API service. 242// 243// Deprecated. 244func (c *gRPCClient) Connection() *grpc.ClientConn { 245 return c.connPool.Conn() 246} 247 248// setGoogleClientInfo sets the name and version of the application in 249// the `x-goog-api-client` header passed on each request. Intended for 250// use by Google-written clients. 251func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { 252 kv := append([]string{"gl-go", versionGo()}, keyval...) 253 kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) 254 c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) 255} 256 257// Close closes the connection to the API service. The user should invoke this when 258// the client is no longer required. 259func (c *gRPCClient) Close() error { 260 return c.connPool.Close() 261} 262 263func (c *gRPCClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { 264 if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { 265 cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) 266 defer cancel() 267 ctx = cctx 268 } 269 ctx = insertMetadata(ctx, c.xGoogMetadata) 270 opts = append((*c.CallOptions).Recognize[0:len((*c.CallOptions).Recognize):len((*c.CallOptions).Recognize)], opts...) 271 var resp *speechpb.RecognizeResponse 272 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { 273 var err error 274 resp, err = c.client.Recognize(ctx, req, settings.GRPC...) 275 return err 276 }, opts...) 277 if err != nil { 278 return nil, err 279 } 280 return resp, nil 281} 282 283func (c *gRPCClient) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { 284 if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { 285 cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) 286 defer cancel() 287 ctx = cctx 288 } 289 ctx = insertMetadata(ctx, c.xGoogMetadata) 290 opts = append((*c.CallOptions).LongRunningRecognize[0:len((*c.CallOptions).LongRunningRecognize):len((*c.CallOptions).LongRunningRecognize)], opts...) 291 var resp *longrunningpb.Operation 292 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { 293 var err error 294 resp, err = c.client.LongRunningRecognize(ctx, req, settings.GRPC...) 295 return err 296 }, opts...) 297 if err != nil { 298 return nil, err 299 } 300 return &LongRunningRecognizeOperation{ 301 lro: longrunning.InternalNewOperation(*c.LROClient, resp), 302 }, nil 303} 304 305func (c *gRPCClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { 306 ctx = insertMetadata(ctx, c.xGoogMetadata) 307 var resp speechpb.Speech_StreamingRecognizeClient 308 opts = append((*c.CallOptions).StreamingRecognize[0:len((*c.CallOptions).StreamingRecognize):len((*c.CallOptions).StreamingRecognize)], opts...) 309 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { 310 var err error 311 resp, err = c.client.StreamingRecognize(ctx, settings.GRPC...) 312 return err 313 }, opts...) 314 if err != nil { 315 return nil, err 316 } 317 return resp, nil 318} 319 320// LongRunningRecognizeOperation manages a long-running operation from LongRunningRecognize. 321type LongRunningRecognizeOperation struct { 322 lro *longrunning.Operation 323} 324 325// LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. 326// The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. 327func (c *gRPCClient) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { 328 return &LongRunningRecognizeOperation{ 329 lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), 330 } 331} 332 333// Wait blocks until the long-running operation is completed, returning the response and any errors encountered. 334// 335// See documentation of Poll for error-handling information. 336func (op *LongRunningRecognizeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.LongRunningRecognizeResponse, error) { 337 var resp speechpb.LongRunningRecognizeResponse 338 if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { 339 return nil, err 340 } 341 return &resp, nil 342} 343 344// Poll fetches the latest state of the long-running operation. 345// 346// Poll also fetches the latest metadata, which can be retrieved by Metadata. 347// 348// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and 349// the operation has completed with failure, the error is returned and op.Done will return true. 350// If Poll succeeds and the operation has completed successfully, 351// op.Done will return true, and the response of the operation is returned. 352// If Poll succeeds and the operation has not completed, the returned response and error are both nil. 353func (op *LongRunningRecognizeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.LongRunningRecognizeResponse, error) { 354 var resp speechpb.LongRunningRecognizeResponse 355 if err := op.lro.Poll(ctx, &resp, opts...); err != nil { 356 return nil, err 357 } 358 if !op.Done() { 359 return nil, nil 360 } 361 return &resp, nil 362} 363 364// Metadata returns metadata associated with the long-running operation. 365// Metadata itself does not contact the server, but Poll does. 366// To get the latest metadata, call this method after a successful call to Poll. 367// If the metadata is not available, the returned metadata and error are both nil. 368func (op *LongRunningRecognizeOperation) Metadata() (*speechpb.LongRunningRecognizeMetadata, error) { 369 var meta speechpb.LongRunningRecognizeMetadata 370 if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { 371 return nil, nil 372 } else if err != nil { 373 return nil, err 374 } 375 return &meta, nil 376} 377 378// Done reports whether the long-running operation has completed. 379func (op *LongRunningRecognizeOperation) Done() bool { 380 return op.lro.Done() 381} 382 383// Name returns the name of the long-running operation. 384// The name is assigned by the server and is unique within the service from which the operation is created. 385func (op *LongRunningRecognizeOperation) Name() string { 386 return op.lro.Name() 387} 388