This repository has been archived by the owner on Dec 31, 2023. It is now read-only.
/
tables_client.py
2838 lines (2600 loc) · 121 KB
/
tables_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A tables helper for the google.cloud.automl_v1beta1 AutoML API"""
import pkg_resources
import logging
from google.api_core.gapic_v1 import client_info
from google.api_core import exceptions
from google.cloud.automl_v1beta1 import gapic
from google.cloud.automl_v1beta1.proto import data_types_pb2
from google.cloud.automl_v1beta1.tables import gcs_client
_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-automl").version
_LOGGER = logging.getLogger(__name__)
class TablesClient(object):
"""
AutoML Tables API helper.
This is intended to simplify usage of the auto-generated python client,
in particular for the `AutoML Tables product
<https://cloud.google.com/automl-tables/>`_.
"""
def __init__(
self,
project=None,
region="us-central1",
credentials=None,
client=None,
prediction_client=None,
gcs_client=None,
**kwargs
):
"""Constructor.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
Args:
project (Optional[str]): The project ID of the GCP project all
future calls will default to. Most methods take `project` as an
optional parameter, and can override your choice of `project`
supplied here.
region (Optional[str]): The region all future calls will
default to. Most methods take `region` as an optional
parameter, and can override your choice of `region` supplied
here. Note, only `us-central1` is supported to-date.
transport (Union[~.AutoMlGrpcTransport, Callable[[~.Credentials, type], ~.AutoMlGrpcTransport]):
A transport instance, responsible for actually making the API
calls. The default transport uses the gRPC protocol. This
argument may also be a callable which returns a transport
instance. Callables will be sent the credentials as the first
argument and the default transport class as the second
argument.
channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
through which to make calls. This argument is mutually exclusive
with ``credentials``; providing both will raise an exception.
credentials (google.auth.credentials.Credentials): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is mutually exclusive with providing a
transport instance to ``transport``; doing so will raise
an exception.
client_config (dict): DEPRECATED. A dictionary of call options for
each method. If not specified, the default configuration is used.
client_options (Union[dict, google.api_core.client_options.ClientOptions]):
Client options used to set user options on the client. API Endpoint
should be set through client_options.
"""
version = _GAPIC_LIBRARY_VERSION
user_agent = "automl-tables-wrapper/{}".format(version)
client_info_ = kwargs.get("client_info")
if client_info_ is None:
client_info_ = client_info.ClientInfo(
user_agent=user_agent, gapic_version=version
)
else:
client_info_.user_agent = user_agent
client_info_.gapic_version = version
kwargs.pop("client_info", None)
if client is None:
self.auto_ml_client = gapic.auto_ml_client.AutoMlClient(
credentials=credentials, client_info=client_info_, **kwargs
)
else:
self.auto_ml_client = client
if prediction_client is None:
self.prediction_client = gapic.prediction_service_client.PredictionServiceClient(
credentials=credentials, client_info=client_info_, **kwargs
)
else:
self.prediction_client = prediction_client
self.project = project
self.region = region
self.credentials = credentials
self.gcs_client = gcs_client
def __lookup_by_display_name(self, object_type, items, display_name):
relevant_items = [i for i in items if i.display_name == display_name]
if len(relevant_items) == 0:
raise exceptions.NotFound(
"The {} with display_name='{}' was not found.".format(
object_type, display_name
)
)
elif len(relevant_items) == 1:
return relevant_items[0]
else:
raise ValueError(
(
"Multiple {}s match display_name='{}': {}\n\n"
"Please use the `.name` (unique identifier) field instead"
).format(
object_type,
display_name,
", ".join([str(i) for i in relevant_items]),
)
)
def __location_path(self, project=None, region=None):
if project is None:
if self.project is None:
raise ValueError(
"Either initialize your client with a value "
"for 'project', or provide 'project' as a "
"parameter for this method."
)
project = self.project
if region is None:
if self.region is None:
raise ValueError(
"Either initialize your client with a value "
"for 'region', or provide 'region' as a "
"parameter for this method."
)
region = self.region
return self.auto_ml_client.location_path(project, region)
# the returned metadata object doesn't allow for updating fields, so
# we need to manually copy user-updated fields over
def __update_metadata(self, metadata, k, v):
new_metadata = {}
new_metadata["ml_use_column_spec_id"] = metadata.ml_use_column_spec_id
new_metadata["weight_column_spec_id"] = metadata.weight_column_spec_id
new_metadata["target_column_spec_id"] = metadata.target_column_spec_id
new_metadata[k] = v
return new_metadata
def __dataset_from_args(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
project=None,
region=None,
**kwargs
):
if dataset is None and dataset_display_name is None and dataset_name is None:
raise ValueError(
"One of 'dataset', 'dataset_name' or "
"'dataset_display_name' must be set."
)
# we prefer to make a live call here in the case that the
# dataset object is out-of-date
if dataset is not None:
dataset_name = dataset.name
return self.get_dataset(
dataset_display_name=dataset_display_name,
dataset_name=dataset_name,
project=project,
region=region,
**kwargs
)
def __model_from_args(
self,
model=None,
model_display_name=None,
model_name=None,
project=None,
region=None,
**kwargs
):
if model is None and model_display_name is None and model_name is None:
raise ValueError(
"One of 'model', 'model_name' or " "'model_display_name' must be set."
)
# we prefer to make a live call here in the case that the
# model object is out-of-date
if model is not None:
model_name = model.name
return self.get_model(
model_display_name=model_display_name,
model_name=model_name,
project=project,
region=region,
**kwargs
)
def __dataset_name_from_args(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
project=None,
region=None,
**kwargs
):
if dataset is None and dataset_display_name is None and dataset_name is None:
raise ValueError(
"One of 'dataset', 'dataset_name' or "
"'dataset_display_name' must be set."
)
if dataset_name is None:
if dataset is None:
dataset = self.get_dataset(
dataset_display_name=dataset_display_name,
project=project,
region=region,
**kwargs
)
dataset_name = dataset.name
else:
# we do this to force a NotFound error when needed
self.get_dataset(
dataset_name=dataset_name, project=project, region=region, **kwargs
)
return dataset_name
def __table_spec_name_from_args(
self,
table_spec_index=0,
dataset=None,
dataset_display_name=None,
dataset_name=None,
project=None,
region=None,
**kwargs
):
dataset_name = self.__dataset_name_from_args(
dataset=dataset,
dataset_name=dataset_name,
dataset_display_name=dataset_display_name,
project=project,
region=region,
**kwargs
)
table_specs = [
t for t in self.list_table_specs(dataset_name=dataset_name, **kwargs)
]
table_spec_full_id = table_specs[table_spec_index].name
return table_spec_full_id
def __model_name_from_args(
self,
model=None,
model_display_name=None,
model_name=None,
project=None,
region=None,
**kwargs
):
if model is None and model_display_name is None and model_name is None:
raise ValueError(
"One of 'model', 'model_name' or " "'model_display_name' must be set."
)
if model_name is None:
if model is None:
model = self.get_model(
model_display_name=model_display_name,
project=project,
region=region,
**kwargs
)
model_name = model.name
else:
# we do this to force a NotFound error when needed
self.get_model(
model_name=model_name, project=project, region=region, **kwargs
)
return model_name
def __log_operation_info(self, message, op):
name = "UNKNOWN"
try:
if (
op is not None
and op.operation is not None
and op.operation.name is not None
):
name = op.operation.name
except AttributeError:
pass
_LOGGER.info(
(
"Operation '{}' is running in the background. The returned "
"Operation '{}' can be used to query or block on the status "
"of this operation. Ending your python session will _not_ "
"cancel this operation. Read the documentation here:\n\n"
"\thttps://googleapis.dev/python/google-api-core/latest/operation.html\n\n"
"for more information on the Operation class."
).format(message, name)
)
return op
def __column_spec_name_from_args(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
table_spec_name=None,
table_spec_index=0,
column_spec_name=None,
column_spec_display_name=None,
project=None,
region=None,
**kwargs
):
column_specs = self.list_column_specs(
dataset=dataset,
dataset_display_name=dataset_display_name,
dataset_name=dataset_name,
table_spec_name=table_spec_name,
table_spec_index=table_spec_index,
project=project,
region=region,
**kwargs
)
if column_spec_display_name is not None:
column_specs = {s.display_name: s for s in column_specs}
if column_specs.get(column_spec_display_name) is None:
raise exceptions.NotFound(
"No column with "
+ "column_spec_display_name: '{}' found".format(
column_spec_display_name
)
)
column_spec_name = column_specs[column_spec_display_name].name
elif column_spec_name is not None:
column_specs = {s.name: s for s in column_specs}
if column_specs.get(column_spec_name) is None:
raise exceptions.NotFound(
"No column with "
+ "column_spec_name: '{}' found".format(column_spec_name)
)
else:
raise ValueError(
"Either supply 'column_spec_name' or "
"'column_spec_display_name' for the column to update"
)
return column_spec_name
def __type_code_to_value_type(self, type_code, value):
if value is None:
return {"null_value": 0}
elif type_code == data_types_pb2.FLOAT64:
return {"number_value": value}
elif type_code == data_types_pb2.TIMESTAMP:
return {"string_value": value}
elif type_code == data_types_pb2.STRING:
return {"string_value": value}
elif type_code == data_types_pb2.ARRAY:
return {"list_value": value}
elif type_code == data_types_pb2.STRUCT:
return {"struct_value": value}
elif type_code == data_types_pb2.CATEGORY:
return {"string_value": value}
else:
raise ValueError("Unknown type_code: {}".format(type_code))
def __ensure_gcs_client_is_initialized(self, credentials, project):
"""Checks if GCS client is initialized. Initializes it if not.
Args:
credentials (google.auth.credentials.Credentials): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If none
are specified, the client will attempt to ascertain the
credentials from the environment.
project (str): The ID of the project to use with the GCS
client. If none is specified, the client will attempt to
ascertain the credentials from the environment.
"""
if self.gcs_client is None:
self.gcs_client = gcs_client.GcsClient(
project=project, credentials=credentials
)
def list_datasets(self, project=None, region=None, **kwargs):
"""List all datasets in a particular project and region.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> ds = client.list_datasets()
>>>
>>> for d in ds:
... # do something
... pass
...
Args:
project (Optional[str]): The ID of the project that owns the
datasets. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
Returns:
A :class:`~google.api_core.page_iterator.PageIterator` instance.
An iterable of :class:`~google.cloud.automl_v1beta1.types.Dataset`
instances. You can also iterate over the pages of the response
using its `pages` property.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
return self.auto_ml_client.list_datasets(
self.__location_path(project=project, region=region), **kwargs
)
def get_dataset(
self,
project=None,
region=None,
dataset_name=None,
dataset_display_name=None,
**kwargs
):
"""Gets a single dataset in a particular project and region.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> d = client.get_dataset(dataset_display_name='my_dataset')
>>>
Args:
project (Optional[str]): The ID of the project that owns the
dataset. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
dataset_name (Optional[str]):
This is the fully-qualified name generated by the AutoML API
for this dataset. This is not to be confused with the
human-assigned `dataset_display_name` that is provided when
creating a dataset. Either `dataset_name` or
`dataset_display_name` must be provided.
dataset_display_name (Optional[str]):
This is the name you provided for the dataset when first
creating it. Either `dataset_name` or `dataset_display_name`
must be provided.
Returns:
A :class:`~google.cloud.automl_v1beta1.types.Dataset` instance if
found, `None` otherwise.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
if dataset_name is None and dataset_display_name is None:
raise ValueError(
"One of 'dataset_name' or " "'dataset_display_name' must be set."
)
if dataset_name is not None:
return self.auto_ml_client.get_dataset(dataset_name, **kwargs)
return self.__lookup_by_display_name(
"dataset",
self.list_datasets(project, region, **kwargs),
dataset_display_name,
)
def create_dataset(
self, dataset_display_name, metadata={}, project=None, region=None, **kwargs
):
"""Create a dataset. Keep in mind, importing data is a separate step.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> d = client.create_dataset(dataset_display_name='my_dataset')
>>>
Args:
project (Optional[str]): The ID of the project that will own the
dataset. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
dataset_display_name (str):
A human-readable name to refer to this dataset by.
Returns:
A :class:`~google.cloud.automl_v1beta1.types.Dataset` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
return self.auto_ml_client.create_dataset(
self.__location_path(project, region),
{"display_name": dataset_display_name, "tables_dataset_metadata": metadata},
**kwargs
)
def delete_dataset(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
project=None,
region=None,
**kwargs
):
"""Deletes a dataset. This does not delete any models trained on
this dataset.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> op = client.delete_dataset(dataset_display_name='my_dataset')
>>>
>>> op.result() # blocks on delete request
>>>
Args:
project (Optional[str]): The ID of the project that owns the
dataset. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
dataset_display_name (Optional[str]):
The human-readable name given to the dataset you want to
delete. This must be supplied if `dataset` or `dataset_name`
are not supplied.
dataset_name (Optional[str]):
The AutoML-assigned name given to the dataset you want to
delete. This must be supplied if `dataset_display_name` or
`dataset` are not supplied.
dataset (Optional[Dataset]):
The `Dataset` instance you want to delete. This must be
supplied if `dataset_display_name` or `dataset_name` are not
supplied.
Returns:
google.api_core.operation.Operation:
An operation future that can be used to check for
completion synchronously or asynchronously.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
try:
dataset_name = self.__dataset_name_from_args(
dataset=dataset,
dataset_name=dataset_name,
dataset_display_name=dataset_display_name,
project=project,
region=region,
**kwargs
)
# delete is idempotent
except exceptions.NotFound:
return None
op = self.auto_ml_client.delete_dataset(dataset_name, **kwargs)
self.__log_operation_info("Delete dataset", op)
return op
def import_data(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
pandas_dataframe=None,
gcs_input_uris=None,
bigquery_input_uri=None,
project=None,
region=None,
credentials=None,
**kwargs
):
"""Imports data into a dataset.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> d = client.create_dataset(dataset_display_name='my_dataset')
>>>
>>> response = client.import_data(dataset=d,
... gcs_input_uris='gs://cloud-ml-tables-data/bank-marketing.csv')
...
>>> def callback(operation_future):
... result = operation_future.result()
...
>>> response.add_done_callback(callback)
>>>
Args:
project (Optional[str]): The ID of the project that owns the
dataset. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If none
are specified, the client will attempt to ascertain the
credentials from the environment.
dataset_display_name (Optional[str]):
The human-readable name given to the dataset you want to import
data into. This must be supplied if `dataset` or `dataset_name`
are not supplied.
dataset_name (Optional[str]):
The AutoML-assigned name given to the dataset you want to
import data into. This must be supplied if
`dataset_display_name` or `dataset` are not supplied.
dataset (Optional[Dataset]):
The `Dataset` instance you want to import data into. This must
be supplied if `dataset_display_name` or `dataset_name` are not
supplied.
pandas_dataframe (Optional[pandas.DataFrame]):
A Pandas Dataframe object containing the data to import. The data
will be converted to CSV, and this CSV will be staged to GCS in
`gs://{project}-automl-tables-staging/{uploaded_csv_name}`
This parameter must be supplied if neither `gcs_input_uris` nor
`bigquery_input_uri` is supplied.
gcs_input_uris (Optional[Union[str, Sequence[str]]]):
Either a single `gs://..` prefixed URI, or a list of URIs
referring to GCS-hosted CSV files containing the data to
import. This must be supplied if neither `bigquery_input_uri`
nor `pandas_dataframe` is supplied.
bigquery_input_uri (Optional[str]):
A URI pointing to the BigQuery table containing the data to
import. This must be supplied if neither `gcs_input_uris` nor
`pandas_dataframe` is supplied.
Returns:
google.api_core.operation.Operation:
An operation future that can be used to check for
completion synchronously or asynchronously.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
dataset_name = self.__dataset_name_from_args(
dataset=dataset,
dataset_name=dataset_name,
dataset_display_name=dataset_display_name,
project=project,
region=region,
**kwargs
)
request = {}
if pandas_dataframe is not None:
project = project or self.project
region = region or self.region
credentials = credentials or self.credentials
self.__ensure_gcs_client_is_initialized(credentials, project)
self.gcs_client.ensure_bucket_exists(project, region)
gcs_input_uri = self.gcs_client.upload_pandas_dataframe(pandas_dataframe)
request = {"gcs_source": {"input_uris": [gcs_input_uri]}}
elif gcs_input_uris is not None:
if type(gcs_input_uris) != list:
gcs_input_uris = [gcs_input_uris]
request = {"gcs_source": {"input_uris": gcs_input_uris}}
elif bigquery_input_uri is not None:
request = {"bigquery_source": {"input_uri": bigquery_input_uri}}
else:
raise ValueError(
"One of 'gcs_input_uris', or 'bigquery_input_uri', or 'pandas_dataframe' must be set."
)
op = self.auto_ml_client.import_data(dataset_name, request, **kwargs)
self.__log_operation_info("Data import", op)
return op
def export_data(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
gcs_output_uri_prefix=None,
bigquery_output_uri=None,
project=None,
region=None,
**kwargs
):
"""Exports data from a dataset.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> d = client.create_dataset(dataset_display_name='my_dataset')
>>>
>>> response = client.export_data(dataset=d,
... gcs_output_uri_prefix='gs://cloud-ml-tables-data/bank-marketing.csv')
...
>>> def callback(operation_future):
... result = operation_future.result()
...
>>> response.add_done_callback(callback)
>>>
Args:
project (Optional[str]): The ID of the project that owns the
dataset. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
dataset_display_name (Optional[str]):
The human-readable name given to the dataset you want to export
data from. This must be supplied if `dataset` or `dataset_name`
are not supplied.
dataset_name (Optional[str]):
The AutoML-assigned name given to the dataset you want to
export data from. This must be supplied if
`dataset_display_name` or `dataset` are not supplied.
dataset (Optional[Dataset]):
The `Dataset` instance you want to export data from. This must
be supplied if `dataset_display_name` or `dataset_name` are not
supplied.
gcs_output_uri_prefix (Optional[Union[str, Sequence[str]]]):
A single `gs://..` prefixed URI to export to. This must be
supplied if `bigquery_output_uri` is not.
bigquery_output_uri (Optional[str]):
A URI pointing to the BigQuery table containing the data to
export. This must be supplied if `gcs_output_uri_prefix` is not.
Returns:
google.api_core.operation.Operation:
An operation future that can be used to check for
completion synchronously or asynchronously.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
dataset_name = self.__dataset_name_from_args(
dataset=dataset,
dataset_name=dataset_name,
dataset_display_name=dataset_display_name,
project=project,
region=region,
**kwargs
)
request = {}
if gcs_output_uri_prefix is not None:
request = {"gcs_destination": {"output_uri_prefix": gcs_output_uri_prefix}}
elif bigquery_output_uri is not None:
request = {"bigquery_destination": {"output_uri": bigquery_output_uri}}
else:
raise ValueError(
"One of 'gcs_output_uri_prefix', or 'bigquery_output_uri' must be set."
)
op = self.auto_ml_client.export_data(dataset_name, request, **kwargs)
self.__log_operation_info("Export data", op)
return op
def get_table_spec(self, table_spec_name, project=None, region=None, **kwargs):
"""Gets a single table spec in a particular project and region.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> d = client.get_table_spec('my_table_spec')
>>>
Args:
table_spec_name (str):
This is the fully-qualified name generated by the AutoML API
for this table spec.
project (Optional[str]): The ID of the project that owns the
table. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
Returns:
A :class:`~google.cloud.automl_v1beta1.types.TableSpec` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
return self.auto_ml_client.get_table_spec(table_spec_name, **kwargs)
def list_table_specs(
self,
dataset=None,
dataset_display_name=None,
dataset_name=None,
project=None,
region=None,
**kwargs
):
"""Lists table specs.
Example:
>>> from google.cloud import automl_v1beta1
>>>
>>> from google.oauth2 import service_account
>>>
>>> client = automl_v1beta1.TablesClient(
... credentials=service_account.Credentials.from_service_account_file('~/.gcp/account.json'),
... project='my-project', region='us-central1')
...
>>> for s in client.list_table_specs(dataset_display_name='my_dataset')
... # process the spec
... pass
...
Args:
project (Optional[str]): The ID of the project that owns the
dataset. If you have initialized the client with a value for
`project` it will be used if this parameter is not supplied.
Keep in mind, the service account this client was initialized
with must have access to this project.
region (Optional[str]):
If you have initialized the client with a value for `region` it
will be used if this parameter is not supplied.
dataset_display_name (Optional[str]):
The human-readable name given to the dataset you want to read
specs from. This must be supplied if `dataset` or
`dataset_name` are not supplied.
dataset_name (Optional[str]):
The AutoML-assigned name given to the dataset you want to read
specs from. This must be supplied if `dataset_display_name` or
`dataset` are not supplied.
dataset (Optional[Dataset]):
The `Dataset` instance you want to read specs from. This must
be supplied if `dataset_display_name` or `dataset_name` are not
supplied.
Returns:
A :class:`~google.api_core.page_iterator.PageIterator` instance.
An iterable of
:class:`~google.cloud.automl_v1beta1.types.TableSpec` instances.
You can also iterate over the pages of the response using its
`pages` property.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If required parameters are missing.
"""
dataset_name = self.__dataset_name_from_args(
dataset=dataset,
dataset_name=dataset_name,
dataset_display_name=dataset_display_name,
project=project,
region=region,
**kwargs
)
return self.auto_ml_client.list_table_specs(dataset_name, **kwargs)
def get_column_spec(self, column_spec_name, project=None, region=None, **kwargs):
"""Gets a single column spec in a particular project and region.
Example:
>>> from google.cloud import automl_v1beta1