Debian Codegraph @

automl/apiv1beta1/prediction_client.go

raw
1 // Copyright 2025 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
17 package automl
18
19 import (
20 "bytes"
21 "context"
22 "fmt"
23 "log/slog"
24 "math"
25 "net/http"
26 "net/url"
27 "time"
28
29 automlpb "cloud.google.com/go/automl/apiv1beta1/automlpb"
30 "cloud.google.com/go/longrunning"
31 lroauto "cloud.google.com/go/longrunning/autogen"
32 longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
33 gax "github.com/googleapis/gax-go/v2"
34 "google.golang.org/api/option"
35 "google.golang.org/api/option/internaloption"
36 gtransport "google.golang.org/api/transport/grpc"
37 httptransport "google.golang.org/api/transport/http"
38 "google.golang.org/grpc"
39 "google.golang.org/protobuf/encoding/protojson"
40 )
41
42 var newPredictionClientHook clientHook
43
44 // PredictionCallOptions contains the retry settings for each method of PredictionClient.
45 type PredictionCallOptions struct {
46 Predict []gax.CallOption
47 BatchPredict []gax.CallOption
48 }
49
50 func defaultPredictionGRPCClientOptions() []option.ClientOption {
51 return []option.ClientOption{
52 internaloption.WithDefaultEndpoint("automl.googleapis.com:443"),
53 internaloption.WithDefaultEndpointTemplate("automl.UNIVERSE_DOMAIN:443"),
54 internaloption.WithDefaultMTLSEndpoint("automl.mtls.googleapis.com:443"),
55 internaloption.WithDefaultUniverseDomain("googleapis.com"),
56 internaloption.WithDefaultAudience("https://automl.googleapis.com/"),
57 internaloption.WithDefaultScopes(DefaultAuthScopes()...),
58 internaloption.EnableJwtWithScope(),
59 internaloption.EnableNewAuthLibrary(),
60 option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
61 grpc.MaxCallRecvMsgSize(math.MaxInt32))),
62 }
63 }
64
65 func defaultPredictionCallOptions() *PredictionCallOptions {
66 return &PredictionCallOptions{
67 Predict: []gax.CallOption{
68 gax.WithTimeout(60000 * time.Millisecond),
69 },
70 BatchPredict: []gax.CallOption{
71 gax.WithTimeout(60000 * time.Millisecond),
72 },
73 }
74 }
75
76 func defaultPredictionRESTCallOptions() *PredictionCallOptions {
77 return &PredictionCallOptions{
78 Predict: []gax.CallOption{
79 gax.WithTimeout(60000 * time.Millisecond),
80 },
81 BatchPredict: []gax.CallOption{
82 gax.WithTimeout(60000 * time.Millisecond),
83 },
84 }
85 }
86
87 // internalPredictionClient is an interface that defines the methods available from Cloud AutoML API.
88 type internalPredictionClient interface {
89 Close() error
90 setGoogleClientInfo(...string)
91 Connection() *grpc.ClientConn
92 Predict(context.Context, *automlpb.PredictRequest, ...gax.CallOption) (*automlpb.PredictResponse, error)
93 BatchPredict(context.Context, *automlpb.BatchPredictRequest, ...gax.CallOption) (*BatchPredictOperation, error)
94 BatchPredictOperation(name string) *BatchPredictOperation
95 }
96
97 // PredictionClient is a client for interacting with Cloud AutoML API.
98 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
99 //
100 // AutoML Prediction API.
101 //
102 // On any input that is documented to expect a string parameter in
103 // snake_case or kebab-case, either of those cases is accepted.
104 type PredictionClient struct {
105 // The internal transport-dependent client.
106 internalClient internalPredictionClient
107
108 // The call options for this service.
109 CallOptions *PredictionCallOptions
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.
121 func (c *PredictionClient) 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.
128 func (c *PredictionClient) setGoogleClientInfo(keyval ...string) {
129 c.internalClient.setGoogleClientInfo(keyval...)
130 }
131
132 // Connection returns a connection to the API service.
133 //
134 // Deprecated: Connections are now pooled so this method does not always
135 // return the same resource.
136 func (c *PredictionClient) Connection() *grpc.ClientConn {
137 return c.internalClient.Connection()
138 }
139
140 // Predict perform an online prediction. The prediction result will be directly
141 // returned in the response.
142 // Available for following ML problems, and their expected request payloads:
143 //
144 // Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes
145 // up to 30MB.
146 //
147 // Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes
148 // up to 30MB.
149 //
150 // Text Classification - TextSnippet, content up to 60,000 characters,
151 // UTF-8 encoded.
152 //
153 // Text Extraction - TextSnippet, content up to 30,000 characters,
154 // UTF-8 NFC encoded.
155 //
156 // Translation - TextSnippet, content up to 25,000 characters, UTF-8
157 // encoded.
158 //
159 // Tables - Row, with column values matching the columns of the model,
160 // up to 5MB. Not available for FORECASTING
161 //
162 // prediction_type.
163 //
164 // Text Sentiment - TextSnippet, content up 500 characters, UTF-8
165 // encoded.
166 func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) {
167 return c.internalClient.Predict(ctx, req, opts...)
168 }
169
170 // BatchPredict perform a batch prediction. Unlike the online Predict, batch
171 // prediction result won’t be immediately available in the response. Instead,
172 // a long running operation object is returned. User can poll the operation
173 // result via GetOperation
174 // method. Once the operation is done, BatchPredictResult is returned in
175 // the response field.
176 // Available for following ML problems:
177 //
178 // Image Classification
179 //
180 // Image Object Detection
181 //
182 // Video Classification
183 //
184 // Video Object Tracking * Text Extraction
185 //
186 // Tables
187 func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) {
188 return c.internalClient.BatchPredict(ctx, req, opts...)
189 }
190
191 // BatchPredictOperation returns a new BatchPredictOperation from a given name.
192 // The name must be that of a previously created BatchPredictOperation, possibly from a different process.
193 func (c *PredictionClient) BatchPredictOperation(name string) *BatchPredictOperation {
194 return c.internalClient.BatchPredictOperation(name)
195 }
196
197 // predictionGRPCClient is a client for interacting with Cloud AutoML API over gRPC transport.
198 //
199 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
200 type predictionGRPCClient struct {
201 // Connection pool of gRPC connections to the service.
202 connPool gtransport.ConnPool
203
204 // Points back to the CallOptions field of the containing PredictionClient
205 CallOptions **PredictionCallOptions
206
207 // The gRPC API client.
208 predictionClient automlpb.PredictionServiceClient
209
210 // LROClient is used internally to handle long-running operations.
211 // It is exposed so that its CallOptions can be modified if required.
212 // Users should not Close this client.
213 LROClient **lroauto.OperationsClient
214
215 // The x-goog-* metadata to be sent with each request.
216 xGoogHeaders []string
217
218 logger *slog.Logger
219 }
220
221 // NewPredictionClient creates a new prediction service client based on gRPC.
222 // The returned client must be Closed when it is done being used to clean up its underlying connections.
223 //
224 // AutoML Prediction API.
225 //
226 // On any input that is documented to expect a string parameter in
227 // snake_case or kebab-case, either of those cases is accepted.
228 func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) {
229 clientOpts := defaultPredictionGRPCClientOptions()
230 if newPredictionClientHook != nil {
231 hookOpts, err := newPredictionClientHook(ctx, clientHookParams{})
232 if err != nil {
233 return nil, err
234 }
235 clientOpts = append(clientOpts, hookOpts...)
236 }
237
238 connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
239 if err != nil {
240 return nil, err
241 }
242 client := PredictionClient{CallOptions: defaultPredictionCallOptions()}
243
244 c := &predictionGRPCClient{
245 connPool: connPool,
246 predictionClient: automlpb.NewPredictionServiceClient(connPool),
247 CallOptions: &client.CallOptions,
248 logger: internaloption.GetLogger(opts),
249 }
250 c.setGoogleClientInfo()
251
252 client.internalClient = c
253
254 client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
255 if err != nil {
256 // This error "should not happen", since we are just reusing old connection pool
257 // and never actually need to dial.
258 // If this does happen, we could leak connp. However, we cannot close conn:
259 // If the user invoked the constructor with option.WithGRPCConn,
260 // we would close a connection that's still in use.
261 // TODO: investigate error conditions.
262 return nil, err
263 }
264 c.LROClient = &client.LROClient
265 return &client, nil
266 }
267
268 // Connection returns a connection to the API service.
269 //
270 // Deprecated: Connections are now pooled so this method does not always
271 // return the same resource.
272 func (c *predictionGRPCClient) Connection() *grpc.ClientConn {
273 return c.connPool.Conn()
274 }
275
276 // setGoogleClientInfo sets the name and version of the application in
277 // the `x-goog-api-client` header passed on each request. Intended for
278 // use by Google-written clients.
279 func (c *predictionGRPCClient) setGoogleClientInfo(keyval ...string) {
280 kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
281 kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "grpc", grpc.Version, "pb", protoVersion)
282 c.xGoogHeaders = []string{
283 "x-goog-api-client", gax.XGoogHeader(kv...),
284 }
285 }
286
287 // Close closes the connection to the API service. The user should invoke this when
288 // the client is no longer required.
289 func (c *predictionGRPCClient) Close() error {
290 return c.connPool.Close()
291 }
292
293 // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
294 type predictionRESTClient struct {
295 // The http endpoint to connect to.
296 endpoint string
297
298 // The http client.
299 httpClient *http.Client
300
301 // LROClient is used internally to handle long-running operations.
302 // It is exposed so that its CallOptions can be modified if required.
303 // Users should not Close this client.
304 LROClient **lroauto.OperationsClient
305
306 // The x-goog-* headers to be sent with each request.
307 xGoogHeaders []string
308
309 // Points back to the CallOptions field of the containing PredictionClient
310 CallOptions **PredictionCallOptions
311
312 logger *slog.Logger
313 }
314
315 // NewPredictionRESTClient creates a new prediction service rest client.
316 //
317 // AutoML Prediction API.
318 //
319 // On any input that is documented to expect a string parameter in
320 // snake_case or kebab-case, either of those cases is accepted.
321 func NewPredictionRESTClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) {
322 clientOpts := append(defaultPredictionRESTClientOptions(), opts...)
323 httpClient, endpoint, err := httptransport.NewClient(ctx, clientOpts...)
324 if err != nil {
325 return nil, err
326 }
327
328 callOpts := defaultPredictionRESTCallOptions()
329 c := &predictionRESTClient{
330 endpoint: endpoint,
331 httpClient: httpClient,
332 CallOptions: &callOpts,
333 logger: internaloption.GetLogger(opts),
334 }
335 c.setGoogleClientInfo()
336
337 lroOpts := []option.ClientOption{
338 option.WithHTTPClient(httpClient),
339 option.WithEndpoint(endpoint),
340 }
341 opClient, err := lroauto.NewOperationsRESTClient(ctx, lroOpts...)
342 if err != nil {
343 return nil, err
344 }
345 c.LROClient = &opClient
346
347 return &PredictionClient{internalClient: c, CallOptions: callOpts}, nil
348 }
349
350 func defaultPredictionRESTClientOptions() []option.ClientOption {
351 return []option.ClientOption{
352 internaloption.WithDefaultEndpoint("https://automl.googleapis.com"),
353 internaloption.WithDefaultEndpointTemplate("https://automl.UNIVERSE_DOMAIN"),
354 internaloption.WithDefaultMTLSEndpoint("https://automl.mtls.googleapis.com"),
355 internaloption.WithDefaultUniverseDomain("googleapis.com"),
356 internaloption.WithDefaultAudience("https://automl.googleapis.com/"),
357 internaloption.WithDefaultScopes(DefaultAuthScopes()...),
358 internaloption.EnableNewAuthLibrary(),
359 }
360 }
361
362 // setGoogleClientInfo sets the name and version of the application in
363 // the `x-goog-api-client` header passed on each request. Intended for
364 // use by Google-written clients.
365 func (c *predictionRESTClient) setGoogleClientInfo(keyval ...string) {
366 kv := append([]string{"gl-go", gax.GoVersion}, keyval...)
367 kv = append(kv, "gapic", getVersionClient(), "gax", gax.Version, "rest", "UNKNOWN", "pb", protoVersion)
368 c.xGoogHeaders = []string{
369 "x-goog-api-client", gax.XGoogHeader(kv...),
370 }
371 }
372
373 // Close closes the connection to the API service. The user should invoke this when
374 // the client is no longer required.
375 func (c *predictionRESTClient) Close() error {
376 // Replace httpClient with nil to force cleanup.
377 c.httpClient = nil
378 return nil
379 }
380
381 // Connection returns a connection to the API service.
382 //
383 // Deprecated: This method always returns nil.
384 func (c *predictionRESTClient) Connection() *grpc.ClientConn {
385 return nil
386 }
387 func (c *predictionGRPCClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) {
388 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
389
390 hds = append(c.xGoogHeaders, hds...)
391 ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
392 opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...)
393 var resp *automlpb.PredictResponse
394 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
395 var err error
396 resp, err = executeRPC(ctx, c.predictionClient.Predict, req, settings.GRPC, c.logger, "Predict")
397 return err
398 }, opts...)
399 if err != nil {
400 return nil, err
401 }
402 return resp, nil
403 }
404
405 func (c *predictionGRPCClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) {
406 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
407
408 hds = append(c.xGoogHeaders, hds...)
409 ctx = gax.InsertMetadataIntoOutgoingContext(ctx, hds...)
410 opts = append((*c.CallOptions).BatchPredict[0:len((*c.CallOptions).BatchPredict):len((*c.CallOptions).BatchPredict)], opts...)
411 var resp *longrunningpb.Operation
412 err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
413 var err error
414 resp, err = executeRPC(ctx, c.predictionClient.BatchPredict, req, settings.GRPC, c.logger, "BatchPredict")
415 return err
416 }, opts...)
417 if err != nil {
418 return nil, err
419 }
420 return &BatchPredictOperation{
421 lro: longrunning.InternalNewOperation(*c.LROClient, resp),
422 }, nil
423 }
424
425 // Predict perform an online prediction. The prediction result will be directly
426 // returned in the response.
427 // Available for following ML problems, and their expected request payloads:
428 //
429 // Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes
430 // up to 30MB.
431 //
432 // Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes
433 // up to 30MB.
434 //
435 // Text Classification - TextSnippet, content up to 60,000 characters,
436 // UTF-8 encoded.
437 //
438 // Text Extraction - TextSnippet, content up to 30,000 characters,
439 // UTF-8 NFC encoded.
440 //
441 // Translation - TextSnippet, content up to 25,000 characters, UTF-8
442 // encoded.
443 //
444 // Tables - Row, with column values matching the columns of the model,
445 // up to 5MB. Not available for FORECASTING
446 //
447 // prediction_type.
448 //
449 // Text Sentiment - TextSnippet, content up 500 characters, UTF-8
450 // encoded.
451 func (c *predictionRESTClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) {
452 m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
453 jsonReq, err := m.Marshal(req)
454 if err != nil {
455 return nil, err
456 }
457
458 baseUrl, err := url.Parse(c.endpoint)
459 if err != nil {
460 return nil, err
461 }
462 baseUrl.Path += fmt.Sprintf("/v1beta1/%v:predict", req.GetName())
463
464 params := url.Values{}
465 params.Add("$alt", "json;enum-encoding=int")
466
467 baseUrl.RawQuery = params.Encode()
468
469 // Build HTTP headers from client and context metadata.
470 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
471
472 hds = append(c.xGoogHeaders, hds...)
473 hds = append(hds, "Content-Type", "application/json")
474 headers := gax.BuildHeaders(ctx, hds...)
475 opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...)
476 unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
477 resp := &automlpb.PredictResponse{}
478 e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
479 if settings.Path != "" {
480 baseUrl.Path = settings.Path
481 }
482 httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
483 if err != nil {
484 return err
485 }
486 httpReq = httpReq.WithContext(ctx)
487 httpReq.Header = headers
488
489 buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, jsonReq, "Predict")
490 if err != nil {
491 return err
492 }
493
494 if err := unm.Unmarshal(buf, resp); err != nil {
495 return err
496 }
497
498 return nil
499 }, opts...)
500 if e != nil {
501 return nil, e
502 }
503 return resp, nil
504 }
505
506 // BatchPredict perform a batch prediction. Unlike the online Predict, batch
507 // prediction result won’t be immediately available in the response. Instead,
508 // a long running operation object is returned. User can poll the operation
509 // result via GetOperation
510 // method. Once the operation is done, BatchPredictResult is returned in
511 // the response field.
512 // Available for following ML problems:
513 //
514 // Image Classification
515 //
516 // Image Object Detection
517 //
518 // Video Classification
519 //
520 // Video Object Tracking * Text Extraction
521 //
522 // Tables
523 func (c *predictionRESTClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) {
524 m := protojson.MarshalOptions{AllowPartial: true, UseEnumNumbers: true}
525 jsonReq, err := m.Marshal(req)
526 if err != nil {
527 return nil, err
528 }
529
530 baseUrl, err := url.Parse(c.endpoint)
531 if err != nil {
532 return nil, err
533 }
534 baseUrl.Path += fmt.Sprintf("/v1beta1/%v:batchPredict", req.GetName())
535
536 params := url.Values{}
537 params.Add("$alt", "json;enum-encoding=int")
538
539 baseUrl.RawQuery = params.Encode()
540
541 // Build HTTP headers from client and context metadata.
542 hds := []string{"x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))}
543
544 hds = append(c.xGoogHeaders, hds...)
545 hds = append(hds, "Content-Type", "application/json")
546 headers := gax.BuildHeaders(ctx, hds...)
547 unm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}
548 resp := &longrunningpb.Operation{}
549 e := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
550 if settings.Path != "" {
551 baseUrl.Path = settings.Path
552 }
553 httpReq, err := http.NewRequest("POST", baseUrl.String(), bytes.NewReader(jsonReq))
554 if err != nil {
555 return err
556 }
557 httpReq = httpReq.WithContext(ctx)
558 httpReq.Header = headers
559
560 buf, err := executeHTTPRequest(ctx, c.httpClient, httpReq, c.logger, jsonReq, "BatchPredict")
561 if err != nil {
562 return err
563 }
564 if err := unm.Unmarshal(buf, resp); err != nil {
565 return err
566 }
567
568 return nil
569 }, opts...)
570 if e != nil {
571 return nil, e
572 }
573
574 override := fmt.Sprintf("/v1beta1/%s", resp.GetName())
575 return &BatchPredictOperation{
576 lro: longrunning.InternalNewOperation(*c.LROClient, resp),
577 pollPath: override,
578 }, nil
579 }
580
581 // BatchPredictOperation returns a new BatchPredictOperation from a given name.
582 // The name must be that of a previously created BatchPredictOperation, possibly from a different process.
583 func (c *predictionGRPCClient) BatchPredictOperation(name string) *BatchPredictOperation {
584 return &BatchPredictOperation{
585 lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
586 }
587 }
588
589 // BatchPredictOperation returns a new BatchPredictOperation from a given name.
590 // The name must be that of a previously created BatchPredictOperation, possibly from a different process.
591 func (c *predictionRESTClient) BatchPredictOperation(name string) *BatchPredictOperation {
592 override := fmt.Sprintf("/v1beta1/%s", name)
593 return &BatchPredictOperation{
594 lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}),
595 pollPath: override,
596 }
597 }