1313# limitations under the License.
1414
1515import os
16+ import time
1617
1718import backoff
1819from google .api_core .client_options import ClientOptions
1920from google .api_core .exceptions import DeadlineExceeded
21+ from google .api_core .exceptions import FailedPrecondition
2022from google .cloud import datalabeling_v1beta1 as datalabeling
2123
2224import create_annotation_spec_set as annotation_spec_set_sample
2325import create_instruction as instruction_sample
24- import manage_dataset as dataset_sample
2526import import_data as import_sample
27+ import manage_dataset as dataset_sample
28+
2629
2730RETRY_DEADLINE = 60
2831
@@ -48,6 +51,27 @@ def delete_dataset(name):
4851 return dataset_sample .delete_dataset (name )
4952
5053
54+ def delete_old_datasets (project_id ):
55+ client = create_client ()
56+ formatted_project_name = client .project_path (project_id )
57+
58+ response = client .list_datasets (formatted_project_name )
59+ # It will delete datasets created more than 2 hours ago
60+ cutoff_time = time .time () - 7200
61+ for element in response :
62+ if element .create_time .seconds < cutoff_time :
63+ print ("Deleting {}" .format (element .name ))
64+ try :
65+ dataset_sample .delete_dataset (element .name )
66+ except FailedPrecondition as e :
67+ # We're always getting FailedPrecondition with 400
68+ # resource conflict. I don't know why.
69+ print ("Deleting {} failed." .format (element .name ))
70+ print ("Detail: {}" .format (e ))
71+ # To avoid quota error
72+ time .sleep (1 )
73+
74+
5175@backoff .on_exception (backoff .expo , DeadlineExceeded , max_time = RETRY_DEADLINE )
5276def create_annotation_spec_set (project_id ):
5377 return annotation_spec_set_sample .create_annotation_spec_set (project_id )
0 commit comments