You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

268 lines
9.8 KiB

  1. // Copyright 2018 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. // AUTO-GENERATED CODE. DO NOT EDIT.
  15. package speech
  16. import (
  17. "time"
  18. "cloud.google.com/go/internal/version"
  19. "cloud.google.com/go/longrunning"
  20. lroauto "cloud.google.com/go/longrunning/autogen"
  21. gax "github.com/googleapis/gax-go"
  22. "golang.org/x/net/context"
  23. "google.golang.org/api/option"
  24. "google.golang.org/api/transport"
  25. speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1beta1"
  26. longrunningpb "google.golang.org/genproto/googleapis/longrunning"
  27. "google.golang.org/grpc"
  28. "google.golang.org/grpc/codes"
  29. "google.golang.org/grpc/metadata"
  30. )
  31. // CallOptions contains the retry settings for each method of Client.
  32. type CallOptions struct {
  33. SyncRecognize []gax.CallOption
  34. AsyncRecognize []gax.CallOption
  35. StreamingRecognize []gax.CallOption
  36. }
  37. func defaultClientOptions() []option.ClientOption {
  38. return []option.ClientOption{
  39. option.WithEndpoint("speech.googleapis.com:443"),
  40. option.WithScopes(DefaultAuthScopes()...),
  41. }
  42. }
  43. func defaultCallOptions() *CallOptions {
  44. retry := map[[2]string][]gax.CallOption{
  45. {"default", "idempotent"}: {
  46. gax.WithRetry(func() gax.Retryer {
  47. return gax.OnCodes([]codes.Code{
  48. codes.DeadlineExceeded,
  49. codes.Unavailable,
  50. }, gax.Backoff{
  51. Initial: 100 * time.Millisecond,
  52. Max: 60000 * time.Millisecond,
  53. Multiplier: 1.3,
  54. })
  55. }),
  56. },
  57. }
  58. return &CallOptions{
  59. SyncRecognize: retry[[2]string{"default", "idempotent"}],
  60. AsyncRecognize: retry[[2]string{"default", "idempotent"}],
  61. StreamingRecognize: retry[[2]string{"default", "non_idempotent"}],
  62. }
  63. }
  64. // Client is a client for interacting with Google Cloud Speech API.
  65. //
  66. // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
  67. type Client struct {
  68. // The connection to the service.
  69. conn *grpc.ClientConn
  70. // The gRPC API client.
  71. client speechpb.SpeechClient
  72. // LROClient is used internally to handle longrunning operations.
  73. // It is exposed so that its CallOptions can be modified if required.
  74. // Users should not Close this client.
  75. LROClient *lroauto.OperationsClient
  76. // The call options for this service.
  77. CallOptions *CallOptions
  78. // The x-goog-* metadata to be sent with each request.
  79. xGoogMetadata metadata.MD
  80. }
  81. // NewClient creates a new speech client.
  82. //
  83. // Service that implements Google Cloud Speech API.
  84. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
  85. conn, err := transport.DialGRPC(ctx, append(defaultClientOptions(), opts...)...)
  86. if err != nil {
  87. return nil, err
  88. }
  89. c := &Client{
  90. conn: conn,
  91. CallOptions: defaultCallOptions(),
  92. client: speechpb.NewSpeechClient(conn),
  93. }
  94. c.setGoogleClientInfo()
  95. c.LROClient, err = lroauto.NewOperationsClient(ctx, option.WithGRPCConn(conn))
  96. if err != nil {
  97. // This error "should not happen", since we are just reusing old connection
  98. // and never actually need to dial.
  99. // If this does happen, we could leak conn. However, we cannot close conn:
  100. // If the user invoked the function with option.WithGRPCConn,
  101. // we would close a connection that's still in use.
  102. // TODO(pongad): investigate error conditions.
  103. return nil, err
  104. }
  105. return c, nil
  106. }
  107. // Connection returns the client's connection to the API service.
  108. func (c *Client) Connection() *grpc.ClientConn {
  109. return c.conn
  110. }
  111. // Close closes the connection to the API service. The user should invoke this when
  112. // the client is no longer required.
  113. func (c *Client) Close() error {
  114. return c.conn.Close()
  115. }
  116. // setGoogleClientInfo sets the name and version of the application in
  117. // the `x-goog-api-client` header passed on each request. Intended for
  118. // use by Google-written clients.
  119. func (c *Client) setGoogleClientInfo(keyval ...string) {
  120. kv := append([]string{"gl-go", version.Go()}, keyval...)
  121. kv = append(kv, "gapic", version.Repo, "gax", gax.Version, "grpc", grpc.Version)
  122. c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
  123. }
  124. // SyncRecognize performs synchronous speech recognition: receive results after all audio
  125. // has been sent and processed.
  126. func (c *Client) SyncRecognize(ctx context.Context, req *speechpb.SyncRecognizeRequest, opts ...gax.CallOption) (*speechpb.SyncRecognizeResponse, error) {
  127. ctx = insertMetadata(ctx, c.xGoogMetadata)
  128. opts = append(c.CallOptions.SyncRecognize[0:len(c.CallOptions.SyncRecognize):len(c.CallOptions.SyncRecognize)], opts...)
  129. var resp *speechpb.SyncRecognizeResponse
  130. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  131. var err error
  132. resp, err = c.client.SyncRecognize(ctx, req, settings.GRPC...)
  133. return err
  134. }, opts...)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return resp, nil
  139. }
  140. // AsyncRecognize performs asynchronous speech recognition: receive results via the
  141. // [google.longrunning.Operations]
  142. // (/speech/reference/rest/v1beta1/operations#Operation)
  143. // interface. Returns either an
  144. // Operation.error or an Operation.response which contains
  145. // an AsyncRecognizeResponse message.
  146. func (c *Client) AsyncRecognize(ctx context.Context, req *speechpb.AsyncRecognizeRequest, opts ...gax.CallOption) (*AsyncRecognizeOperation, error) {
  147. ctx = insertMetadata(ctx, c.xGoogMetadata)
  148. opts = append(c.CallOptions.AsyncRecognize[0:len(c.CallOptions.AsyncRecognize):len(c.CallOptions.AsyncRecognize)], opts...)
  149. var resp *longrunningpb.Operation
  150. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  151. var err error
  152. resp, err = c.client.AsyncRecognize(ctx, req, settings.GRPC...)
  153. return err
  154. }, opts...)
  155. if err != nil {
  156. return nil, err
  157. }
  158. return &AsyncRecognizeOperation{
  159. lro: longrunning.InternalNewOperation(c.LROClient, resp),
  160. }, nil
  161. }
  162. // StreamingRecognize performs bidirectional streaming speech recognition: receive results while
  163. // sending audio. This method is only available via the gRPC API (not REST).
  164. func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) {
  165. ctx = insertMetadata(ctx, c.xGoogMetadata)
  166. opts = append(c.CallOptions.StreamingRecognize[0:len(c.CallOptions.StreamingRecognize):len(c.CallOptions.StreamingRecognize)], opts...)
  167. var resp speechpb.Speech_StreamingRecognizeClient
  168. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  169. var err error
  170. resp, err = c.client.StreamingRecognize(ctx, settings.GRPC...)
  171. return err
  172. }, opts...)
  173. if err != nil {
  174. return nil, err
  175. }
  176. return resp, nil
  177. }
  178. // AsyncRecognizeOperation manages a long-running operation from AsyncRecognize.
  179. type AsyncRecognizeOperation struct {
  180. lro *longrunning.Operation
  181. }
  182. // AsyncRecognizeOperation returns a new AsyncRecognizeOperation from a given name.
  183. // The name must be that of a previously created AsyncRecognizeOperation, possibly from a different process.
  184. func (c *Client) AsyncRecognizeOperation(name string) *AsyncRecognizeOperation {
  185. return &AsyncRecognizeOperation{
  186. lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
  187. }
  188. }
  189. // Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
  190. //
  191. // See documentation of Poll for error-handling information.
  192. func (op *AsyncRecognizeOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*speechpb.AsyncRecognizeResponse, error) {
  193. var resp speechpb.AsyncRecognizeResponse
  194. if err := op.lro.WaitWithInterval(ctx, &resp, 45000*time.Millisecond, opts...); err != nil {
  195. return nil, err
  196. }
  197. return &resp, nil
  198. }
  199. // Poll fetches the latest state of the long-running operation.
  200. //
  201. // Poll also fetches the latest metadata, which can be retrieved by Metadata.
  202. //
  203. // If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
  204. // the operation has completed with failure, the error is returned and op.Done will return true.
  205. // If Poll succeeds and the operation has completed successfully,
  206. // op.Done will return true, and the response of the operation is returned.
  207. // If Poll succeeds and the operation has not completed, the returned response and error are both nil.
  208. func (op *AsyncRecognizeOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*speechpb.AsyncRecognizeResponse, error) {
  209. var resp speechpb.AsyncRecognizeResponse
  210. if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
  211. return nil, err
  212. }
  213. if !op.Done() {
  214. return nil, nil
  215. }
  216. return &resp, nil
  217. }
  218. // Metadata returns metadata associated with the long-running operation.
  219. // Metadata itself does not contact the server, but Poll does.
  220. // To get the latest metadata, call this method after a successful call to Poll.
  221. // If the metadata is not available, the returned metadata and error are both nil.
  222. func (op *AsyncRecognizeOperation) Metadata() (*speechpb.AsyncRecognizeMetadata, error) {
  223. var meta speechpb.AsyncRecognizeMetadata
  224. if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
  225. return nil, nil
  226. } else if err != nil {
  227. return nil, err
  228. }
  229. return &meta, nil
  230. }
  231. // Done reports whether the long-running operation has completed.
  232. func (op *AsyncRecognizeOperation) Done() bool {
  233. return op.lro.Done()
  234. }
  235. // Name returns the name of the long-running operation.
  236. // The name is assigned by the server and is unique within the service from which the operation is created.
  237. func (op *AsyncRecognizeOperation) Name() string {
  238. return op.lro.Name()
  239. }