Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

265 рядки
9.8 KiB

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