-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcommands.py
More file actions
2104 lines (1749 loc) · 69.8 KB
/
commands.py
File metadata and controls
2104 lines (1749 loc) · 69.8 KB
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
"""Commands supported by the Earth Engine command line interface.
Each command is implemented by extending the Command class. Each class
defines the supported positional and optional arguments, as well as
the actions to be taken when the command is executed.
"""
import argparse
import calendar
import collections
import datetime
import json
import logging
import os
import re
import shutil
import sys
import tempfile
from typing import Any, Dict, List, Sequence, Tuple, Type, Union
import urllib.parse
# Prevent TensorFlow from logging anything at the native level.
# pylint: disable=g-import-not-at-top
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# Suppress non-error logs while TF initializes
old_level = logging.getLogger().level
logging.getLogger().setLevel(logging.ERROR)
TENSORFLOW_INSTALLED = False
# pylint: disable=g-import-not-at-top
try:
import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.saved_model import utils as saved_model_utils
from tensorflow.compat.v1.saved_model import signature_constants
from tensorflow.compat.v1.saved_model import signature_def_utils
# This triggers a warning about disable_resource_variables
tf.disable_v2_behavior()
# Prevent TensorFlow from logging anything at the python level.
tf.logging.set_verbosity(tf.logging.ERROR)
TENSORFLOW_INSTALLED = True
except ImportError:
pass
except TypeError:
# The installed version of the protobuf package is incompatible with
# Tensorflow. A type error is thrown when trying to generate proto
# descriptors. Reinstalling Tensorflow should fix any dep versioning issues.
pass
finally:
logging.getLogger().setLevel(old_level)
TENSORFLOW_ADDONS_INSTALLED = False
# pylint: disable=g-import-not-at-top
if TENSORFLOW_INSTALLED:
try:
# This import is enough to register TFA ops though isn't directly used
# (for now).
# pylint: disable=unused-import
import tensorflow_addons as tfa
tfa.register_all(custom_kernels=False) # pytype: disable=module-attr
TENSORFLOW_ADDONS_INSTALLED = True
except ImportError:
pass
except AttributeError:
# This can be thrown by "tfa.register_all()" which means the
# tensorflow_addons version is registering ops the old way, i.e.
# automatically at import time. If this is the case, we've actually
# successfully registered TFA.
TENSORFLOW_ADDONS_INSTALLED = True
# pylint: disable=g-import-not-at-top, g-bad-import-order
import ee
from ee.cli import utils
# Constants used in ACLs.
ALL_USERS = 'allUsers'
ALL_USERS_CAN_READ = 'all_users_can_read'
READERS = 'readers'
WRITERS = 'writers'
# Constants used in setting metadata properties.
TYPE_DATE = 'date'
TYPE_NUMBER = 'number'
TYPE_STRING = 'string'
SYSTEM_TIME_START = 'system:time_start'
SYSTEM_TIME_END = 'system:time_end'
# A regex that parses properties of the form "[(type)]name=value". The
# second, third, and fourth group are type, name, and number, respectively.
PROPERTY_RE = re.compile(r'(\(([^\)]*)\))?([^=]+)=(.*)')
# Translate internal task type identifiers to user-friendly strings that
# are consistent with the language in the API and docs.
TASK_TYPES = {
'EXPORT_FEATURES': 'Export.table',
'EXPORT_IMAGE': 'Export.image',
'EXPORT_TILES': 'Export.map',
'EXPORT_VIDEO': 'Export.video',
'INGEST': 'Upload',
'INGEST_IMAGE': 'Upload',
'INGEST_TABLE': 'Upload',
}
TF_RECORD_EXTENSIONS = ['.tfrecord', 'tfrecord.gz']
# Maximum size of objects in a SavedModel directory that we're willing to
# download from GCS.
SAVED_MODEL_MAX_SIZE = 400 * 1024 * 1024
# Default path to SavedModel variables.
DEFAULT_VARIABLES_PREFIX = '/variables/variables'
def _add_wait_arg(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
'--wait', '-w', nargs='?', default=-1, type=int, const=sys.maxsize,
help=('Wait for the task to finish,'
' or timeout after the specified number of seconds.'
' Without this flag, the command just starts an export'
' task in the background, and returns immediately.'))
def _add_overwrite_arg(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
'--force', '-f', action='store_true',
help='Overwrite any existing version of the asset.')
def _upload(
args: argparse.Namespace, request: Dict[str, Any], ingestion_function: Any
) -> None:
if 0 <= args.wait < 10:
raise ee.EEException('Wait time should be at least 10 seconds.')
request_id = ee.data.newTaskId()[0]
task_id = ingestion_function(request_id, request, args.force)['id']
print('Started upload task with ID: %s' % task_id)
if args.wait >= 0:
print('Waiting for the upload task to complete...')
utils.wait_for_task(task_id, args.wait)
# Argument types
def _comma_separated_strings(string: str) -> List[str]:
"""Parses an input consisting of comma-separated strings."""
error_msg = 'Argument should be a comma-separated list of strings: {}'
values = string.split(',')
if not values:
raise argparse.ArgumentTypeError(error_msg.format(string))
return values
def _comma_separated_numbers(string: str) -> List[float]:
"""Parses an input consisting of comma-separated numbers."""
error_msg = 'Argument should be a comma-separated list of numbers: {}'
values = string.split(',')
if not values:
raise argparse.ArgumentTypeError(error_msg.format(string))
numbervalues = []
for value in values:
try:
numbervalues.append(int(value))
except ValueError:
try:
numbervalues.append(float(value))
except ValueError:
# pylint: disable-next=raise-missing-from
raise argparse.ArgumentTypeError(error_msg.format(string))
return numbervalues
def _comma_separated_pyramiding_policies(string: str) -> List[str]:
"""Parses an input consisting of comma-separated pyramiding policies."""
error_msg = ('Argument should be a comma-separated list of: '
'{{"mean", "sample", "min", "max", "mode"}}: {}')
values = string.split(',')
if not values:
raise argparse.ArgumentTypeError(error_msg.format(string))
redvalues = []
for value in values:
value = value.upper()
if value not in {'MEAN', 'SAMPLE', 'MIN', 'MAX', 'MODE', 'MEDIAN'}:
raise argparse.ArgumentTypeError(error_msg.format(string))
redvalues.append(value)
return redvalues
def _decode_number(string: str) -> float:
"""Decodes a number from a command line argument."""
try:
return float(string)
except ValueError:
raise argparse.ArgumentTypeError( # pylint: disable=raise-missing-from
'Invalid value for property of type "number": "%s".' % string)
def _timestamp_ms_for_datetime(datetime_obj: datetime.datetime) -> int:
"""Returns time since the epoch in ms for the given UTC datetime object."""
return (
int(calendar.timegm(datetime_obj.timetuple()) * 1000) +
datetime_obj.microsecond // 1000)
def _cloud_timestamp_for_timestamp_ms(timestamp_ms: float) -> str:
"""Returns a Cloud-formatted date for the given millisecond timestamp."""
# Desired format is like '2003-09-07T19:30:12.345Z'
timestamp = datetime.datetime.fromtimestamp(
timestamp_ms / 1000.0, datetime.timezone.utc
)
return timestamp.replace(tzinfo=None).isoformat() + 'Z'
def _parse_millis(millis: float) -> datetime.datetime:
return datetime.datetime.fromtimestamp(millis / 1000)
def _decode_date(string: str) -> Union[float, str]:
"""Decodes a date from a command line argument, returning msec since epoch".
Args:
string: See AssetSetCommand class comment for the allowable
date formats.
Returns:
long, ms since epoch, or '' if the input is empty.
Raises:
argparse.ArgumentTypeError: if string does not conform to a legal
date format.
"""
if not string:
return ''
try:
return int(string)
except ValueError:
date_formats = ['%Y-%m-%d',
'%Y-%m-%dT%H:%M:%S',
'%Y-%m-%dT%H:%M:%S.%f']
for date_format in date_formats:
try:
dt = datetime.datetime.strptime(string, date_format)
return _timestamp_ms_for_datetime(dt)
except ValueError:
continue
raise argparse.ArgumentTypeError(
'Invalid value for property of type "date": "%s".' % string)
def _decode_property(string: str) -> Tuple[str, Any]:
"""Decodes a general key-value property from a command-line argument.
Args:
string: The string must have the form name=value or (type)name=value, where
type is one of 'number', 'string', or 'date'. The value format for dates
is YYYY-MM-DD[THH:MM:SS[.MS]]. The value 'null' is special: it evaluates
to None unless it is cast to a string of 'null'.
Returns:
a tuple representing the property in the format (name, value)
Raises:
argparse.ArgumentTypeError: if the flag value could not be decoded or if
the type is not recognized
"""
m = PROPERTY_RE.match(string)
if not m:
raise argparse.ArgumentTypeError(
'Invalid property: "%s". Must have the form "name=value" or '
'"(type)name=value".' % string)
_, type_str, name, value_str = m.groups()
if value_str == 'null' and type_str != TYPE_STRING:
return (name, None)
if type_str is None:
# Guess numeric types automatically.
try:
value = _decode_number(value_str)
except argparse.ArgumentTypeError:
value = value_str
elif type_str == TYPE_DATE:
value = _decode_date(value_str)
elif type_str == TYPE_NUMBER:
value = _decode_number(value_str)
elif type_str == TYPE_STRING:
value = value_str
else:
raise argparse.ArgumentTypeError(
'Unrecognized property type name: "%s". Expected one of "string", '
'"number", or "date".' % type_str)
return (name, value)
def _add_property_flags(parser: argparse.ArgumentParser) -> None:
"""Adds command line flags related to metadata properties to a parser."""
parser.add_argument(
'--property', '-p',
help='A property to set, in the form [(type)]name=value. If no type '
'is specified the type will be "number" if the value is numeric and '
'"string" otherwise. May be provided multiple times.',
action='append',
type=_decode_property)
parser.add_argument(
'--time_start', '-ts',
help='Sets the start time property to a number or date.',
type=_decode_date)
parser.add_argument(
'--time_end', '-te',
help='Sets the end time property to a number or date.',
type=_decode_date)
def _decode_property_flags(args: argparse.Namespace) -> Dict[str, Any]:
"""Decodes metadata properties from args as a name->value dict."""
property_list = list(args.property or [])
names = [name for name, _ in property_list]
duplicates = [
name for name, count in collections.Counter(names).items() if count > 1]
if duplicates:
raise ee.EEException('Duplicate property name(s): %s.' % duplicates)
return dict(property_list)
def _check_valid_files(filenames: Sequence[str]) -> None:
"""Returns true if the given filenames are valid upload file URIs."""
for filename in filenames:
if not filename.startswith('gs://'):
raise ee.EEException('Invalid Cloud Storage URL: ' + filename)
def _pretty_print_json(json_obj: Any) -> None:
"""Pretty-prints a JSON object to standard output."""
print(json.dumps(json_obj, sort_keys=True, indent=2, separators=(',', ': ')))
class Dispatcher:
"""Dispatches to a set of commands implemented as command classes."""
COMMANDS: List[Any]
command_dict: Dict[str, Any]
dest: str
name: str
def __init__(self, parser: argparse.ArgumentParser):
self.command_dict = {}
self.dest = self.name + '_cmd'
subparsers = parser.add_subparsers(title='Commands', dest=self.dest)
subparsers.required = True # Needed for proper missing arg handling in 3.x
for command in self.COMMANDS:
command_help = None
if command.__doc__ and command.__doc__.splitlines():
command_help = command.__doc__.splitlines()[0]
subparser = subparsers.add_parser(
command.name,
description=command.__doc__,
help=command_help)
self.command_dict[command.name] = command(subparser)
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
self.command_dict[vars(args)[self.dest]].run(args, config)
class AuthenticateCommand:
"""Prompts the user to authorize access to Earth Engine via OAuth2.
Note that running this command in the default interactive mode within
JupyterLab with a bash magic command (i.e. "!earthengine authenticate") is
problematic (see https://github.com/ipython/ipython/issues/10499). To avoid
this issue, use the non-interactive mode
(i.e. "!earthengine authenticate --quiet").
"""
name = 'authenticate'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument(
'--authorization-code',
help='Use this specified authorization code.')
parser.add_argument(
'--quiet',
action='store_true',
help='Do not prompt for input, run gcloud-legacy in no-browser mode.')
parser.add_argument(
'--code-verifier',
help='PKCE verifier to prevent auth code stealing.')
parser.add_argument(
'--auth_mode',
help='One of: notebook - use notebook authenticator; colab - use Colab'
' authenticator; gcloud / gcloud-legacy - use gcloud;'
' localhost[:PORT|:0] - use local browser')
parser.add_argument(
'--scopes', help='Optional comma-separated list of scopes.')
parser.add_argument(
'--force',
action='store_true',
help='Run authentication even if credentials already exist.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Prompts for an auth code, requests a token and saves it."""
del config # Unused
# Filter for arguments relevant for ee.Authenticate()
args_auth = {x: vars(args)[x] for x in (
'authorization_code', 'quiet', 'code_verifier', 'auth_mode', 'force')}
if args.scopes:
args_auth['scopes'] = args.scopes.split(',')
if ee._utils.in_colab_shell(): # pylint: disable=protected-access
print(
'Authenticate: Limited support in Colab. Use ee.Authenticate()'
' or --auth_mode=notebook instead.'
)
if not args.auth_mode:
args_auth['auth_mode'] = 'notebook'
if ee.Authenticate(**args_auth):
print('Authenticate: Credentials already exist. Use --force to refresh.')
class SetProjectCommand:
"""Sets the default user project to be used for all API calls."""
name = 'set_project'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument('project', help='project id or number to use.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Saves the project to the config file."""
config_path = config.config_file
try:
with open(config_path) as json_config_file:
config = json.load(json_config_file)
except FileNotFoundError:
# File may not exist if we initialized from default credentials.
config = {}
config['project'] = args.project
ee.oauth.write_private_json(config_path, config)
print('Successfully saved project id')
class UnSetProjectCommand:
"""UnSets the default user project to be used for all API calls."""
name = 'unset_project'
def __init__(self, parser: argparse.ArgumentParser):
del parser # Unused.
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Saves the project to the config file."""
del args # Unused.
config_path = config.config_file
try:
with open(config_path) as json_config_file:
config = json.load(json_config_file)
except FileNotFoundError:
# File may not exist if we initialized from default credentials.
config = {}
if 'project' in config:
del config['project']
ee.oauth.write_private_json(config_path, config)
print('Successfully unset project id')
class AclChCommand:
"""Changes the access control list for an asset.
Each change specifies the email address of a user or group and,
for additions, one of R or W corresponding to the read or write
permissions to be granted, as in "user@domain.com:R". Use the
special name "allUsers" to change whether all users can read the
asset.
"""
name = 'ch'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument('-u', action='append', metavar='user permission',
help='Add or modify a user\'s permission.')
parser.add_argument('-d', action='append', metavar='remove user',
help='Remove all permissions for a user.')
parser.add_argument('-g', action='append', metavar='group permission',
help='Add or modify a group\'s permission.')
parser.add_argument('-dg', action='append', metavar='remove group',
help='Remove all permissions for a user.')
parser.add_argument('asset_id', help='ID of the asset.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Performs an ACL update."""
config.ee_init()
permissions = self._parse_permissions(args)
acl = ee.data.getAssetAcl(args.asset_id)
self._apply_permissions(acl, permissions)
ee.data.setAssetAcl(args.asset_id, json.dumps(acl))
def _set_permission(
self, permissions: Dict[str, str], grant: str, prefix: str
) -> None:
"""Sets the permission for a given user/group."""
parts = grant.rsplit(':', 1)
if len(parts) != 2 or parts[1] not in ['R', 'W']:
raise ee.EEException('Invalid permission "%s".' % grant)
user, role = parts
prefixed_user = user
if not self._is_all_users(user):
prefixed_user = prefix + user
if prefixed_user in permissions:
raise ee.EEException('Multiple permission settings for "%s".' % user)
if self._is_all_users(user) and role == 'W':
raise ee.EEException('Cannot grant write permissions to all users.')
permissions[prefixed_user] = role
def _remove_permission(
self, permissions: Dict[str, str], user: str, prefix: str
) -> None:
"""Removes permissions for a given user/group."""
prefixed_user = user
if not self._is_all_users(user):
prefixed_user = prefix + user
if prefixed_user in permissions:
raise ee.EEException('Multiple permission settings for "%s".' % user)
permissions[prefixed_user] = 'D'
def _user_account_type(self, user: str) -> str:
"""Returns the appropriate account type for a user email."""
# Here 'user' ends with ':R', ':W', or ':D', so we extract
# just the username.
if user.split(':')[0].endswith('.gserviceaccount.com'):
return 'serviceAccount:'
else:
return 'user:'
def _parse_permissions(self, args: argparse.Namespace) -> Dict[str, str]:
"""Decodes and sanity-checks the permissions in the arguments."""
# A dictionary mapping from user ids to one of 'R', 'W', or 'D'.
permissions = {}
if args.u:
for user in args.u:
self._set_permission(permissions, user, self._user_account_type(user))
if args.d:
for user in args.d:
self._remove_permission(
permissions, user, self._user_account_type(user))
if args.g:
for group in args.g:
self._set_permission(permissions, group, 'group:')
if args.dg:
for group in args.dg:
self._remove_permission(permissions, group, 'group:')
return permissions
def _apply_permissions(
self, acl: Dict[str, Union[bool, List[str]]], permissions: Dict[str, str]
) -> None:
"""Applies the given permission edits to the given acl."""
for user, role in permissions.items():
if self._is_all_users(user):
acl[ALL_USERS_CAN_READ] = role == 'R'
else:
readers = acl[READERS]
writers = acl[WRITERS]
# Make pytype understand the types.
assert isinstance(readers, list)
assert isinstance(writers, list)
if role == 'R':
if user not in readers:
readers.append(user)
if user in writers:
writers.remove(user)
elif role == 'W':
if user in readers:
readers.remove(user)
if user not in writers:
writers.append(user)
elif role == 'D':
if user in readers:
readers.remove(user)
if user in writers:
writers.remove(user)
def _is_all_users(self, user: str) -> bool:
"""Determines if a user name represents the special "all users" entity."""
# We previously used "AllUsers" as the magic string to denote that we wanted
# to apply some permission to everyone. However, Google Cloud convention for
# this concept is "allUsers". Because some people might be using one and
# some the other, we do a case-insensitive comparison.
return user.lower() == ALL_USERS.lower()
class AclGetCommand:
"""Prints the access control list for an asset."""
name = 'get'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument('asset_id', help='ID of the asset.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
config.ee_init()
acl = ee.data.getAssetAcl(args.asset_id)
_pretty_print_json(acl)
class AclSetCommand:
"""Sets the access control list for an asset.
The ACL may be the name of a canned ACL, or it may be the path to a
file containing the output from "acl get". The recognized canned ACL
names are "private", indicating that no users other than the owner
have access, and "public", indicating that all users have read
access. It is currently not possible to modify the owner ACL using
this tool.
"""
name = 'set'
CANNED_ACLS = {
'private': {
READERS: [],
WRITERS: [],
ALL_USERS_CAN_READ: False,
},
'public': {
READERS: [],
WRITERS: [],
ALL_USERS_CAN_READ: True,
},
}
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument('file_or_acl_name',
help='File path or canned ACL name.')
parser.add_argument('asset_id', help='ID of the asset.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Sets asset ACL to a canned ACL or one provided in a JSON file."""
config.ee_init()
if args.file_or_acl_name in list(self.CANNED_ACLS.keys()):
acl = self.CANNED_ACLS[args.file_or_acl_name]
else:
acl = json.load(open(args.file_or_acl_name))
ee.data.setAssetAcl(args.asset_id, json.dumps(acl))
class AclCommand(Dispatcher):
"""Prints or updates the access control list of the specified asset."""
name = 'acl'
COMMANDS = [
AclChCommand,
AclGetCommand,
AclSetCommand,
]
class AssetInfoCommand:
"""Prints metadata and other information about an Earth Engine asset."""
name = 'info'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument('asset_id', help='ID of the asset to print.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
config.ee_init()
info = ee.data.getInfo(args.asset_id)
if info:
_pretty_print_json(info)
else:
raise ee.EEException(
'Asset does not exist or is not accessible: %s' % args.asset_id)
class AssetSetCommand:
"""Sets metadata properties of an Earth Engine asset.
Properties may be of type "string", "number", or "date". Dates must
be specified in the form YYYY-MM-DD[Thh:mm:ss[.ff]] in UTC and are
stored as numbers representing the number of milliseconds since the
Unix epoch (00:00:00 UTC on 1 January 1970).
To delete a property, set it to null without a type:
prop=null.
To set a property to the string value 'null', use the assignment
(string)prop4=null.
"""
name = 'set'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument('asset_id', help='ID of the asset to update.')
_add_property_flags(parser)
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Runs the asset update."""
config.ee_init()
properties = _decode_property_flags(args)
if not properties and args.time_start is None and args.time_end is None:
raise ee.EEException('No properties specified.')
update_mask = [
'properties.' + property_name for property_name in properties
]
asset = {}
if properties:
asset['properties'] = {
k: v for k, v in properties.items() if v is not None
}
# args.time_start and .time_end could have any of three falsy values, with
# different meanings:
# None: the --time_start flag was not provided at all
# '': the --time_start flag was explicitly set to the empty string
# 0: the --time_start flag was explicitly set to midnight 1 Jan 1970.
# pylint:disable=g-explicit-bool-comparison
if args.time_start is not None:
update_mask.append('start_time')
if args.time_start != '':
asset['start_time'] = _cloud_timestamp_for_timestamp_ms(
args.time_start)
if args.time_end is not None:
update_mask.append('end_time')
if args.time_end != '':
asset['end_time'] = _cloud_timestamp_for_timestamp_ms(args.time_end)
# pylint:enable=g-explicit-bool-comparison
ee.data.updateAsset(args.asset_id, asset, update_mask)
return
class AssetCommand(Dispatcher):
"""Prints or updates metadata associated with an Earth Engine asset."""
name = 'asset'
COMMANDS = [
AssetInfoCommand,
AssetSetCommand,
]
class CopyCommand:
"""Creates a new Earth Engine asset as a copy of another asset."""
name = 'cp'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument(
'source', help='Full path of the source asset.')
parser.add_argument(
'destination', help='Full path of the destination asset.')
_add_overwrite_arg(parser)
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Runs the asset copy."""
config.ee_init()
ee.data.copyAsset(
args.source,
args.destination,
args.force
)
class CreateCommandBase:
"""Base class for implementing Create subcommands."""
def __init__(self, parser, fragment, asset_type):
parser.add_argument(
'asset_id', nargs='+',
help='Full path of %s to create.' % fragment)
parser.add_argument(
'--parents', '-p', action='store_true',
help='Make parent folders as needed.')
self.asset_type = asset_type
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
config.ee_init()
ee.data.create_assets(args.asset_id, self.asset_type, args.parents)
class CreateCollectionCommand(CreateCommandBase):
"""Creates one or more image collections."""
name = 'collection'
def __init__(self, parser: argparse.ArgumentParser):
super().__init__(
parser, 'an image collection', ee.data.ASSET_TYPE_IMAGE_COLL)
class CreateFolderCommand(CreateCommandBase):
"""Creates one or more folders."""
name = 'folder'
def __init__(self, parser: argparse.ArgumentParser):
super().__init__(parser, 'a folder', ee.data.ASSET_TYPE_FOLDER)
class CreateCommand(Dispatcher):
"""Creates assets and folders."""
name = 'create'
COMMANDS = [
CreateCollectionCommand,
CreateFolderCommand,
]
class ListCommand:
"""Prints the contents of a folder or collection."""
name = 'ls'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument(
'asset_id', nargs='*',
help='A folder or image collection to be inspected.')
parser.add_argument(
'--long_format',
'-l',
action='store_true',
help='Print output in long format.')
parser.add_argument(
'--max_items', '-m', default=-1, type=int,
help='Maximum number of items to list for each collection.')
parser.add_argument(
'--recursive',
'-r',
action='store_true',
help='List folders recursively.')
parser.add_argument(
'--filter',
'-f',
default='',
type=str,
help=(
'Filter string to use on a collection. Accepts property names'
' "start_time", "end_time", "update_time", and "properties.foo"'
' (where "foo" is any user-defined property). Example filter'
' strings: properties.SCENE_ID="ABC";'
' start_time>"2023-02-03T00:00:00+00:00"'
),
)
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Runs the list command."""
config.ee_init()
if not args.asset_id:
roots = ee.data.getAssetRoots()
self._print_assets(roots, args.max_items, '', args.long_format,
args.recursive)
return
assets = args.asset_id
count = 0
for asset in assets:
if count > 0:
print()
self._list_asset_content(
asset, args.max_items, len(assets), args.long_format,
args.recursive, args.filter)
count += 1
def _print_assets(self, assets, max_items, indent, long_format, recursive):
"""Prints the listing of given assets."""
if not assets:
return
max_type_length = max([len(asset['type']) for asset in assets])
if recursive:
# fallback to max to include the string 'ImageCollection'
max_type_length = ee.data.MAX_TYPE_LENGTH
format_str = '%s{:%ds}{:s}' % (indent, max_type_length + 4)
for asset in assets:
if long_format:
# Example output:
# [Image] user/test/my_img
# [ImageCollection] user/test/my_coll
print(format_str.format('['+asset['type']+']', asset['id']))
else:
print(asset['id'])
if recursive and asset['type'] in (ee.data.ASSET_TYPE_FOLDER,
ee.data.ASSET_TYPE_FOLDER_CLOUD):
list_req = {'id': asset['id']}
children = ee.data.getList(list_req)
self._print_assets(children, max_items, indent, long_format, recursive)
def _list_asset_content(self, asset, max_items, total_assets, long_format,
recursive, filter_string):
"""Prints the contents of an asset and its children."""
try:
list_req = {'id': asset}
if max_items >= 0:
list_req['num'] = max_items
if filter_string:
list_req['filter'] = filter_string
children = ee.data.getList(list_req)
indent = ''
if total_assets > 1:
print('%s:' % asset)
indent = ' '
self._print_assets(children, max_items, indent, long_format, recursive)
except ee.EEException as e:
print(e)
class SizeCommand:
"""Prints the size and names of all items in a given folder or collection."""
name = 'du'
def __init__(self, parser: argparse.ArgumentParser):
parser.add_argument(
'asset_id',
nargs='*',
help='A folder or image collection to be inspected.')
parser.add_argument(
'--summarize', '-s', action='store_true',
help='Display only a total.')
def run(
self, args: argparse.Namespace, config: utils.CommandLineConfig
) -> None:
"""Runs the du command."""
config.ee_init()
# Select all available asset roots if no asset ids are given.
if not args.asset_id:
assets = ee.data.getAssetRoots()
else:
assets = [ee.data.getInfo(asset) for asset in args.asset_id]
# If args.summarize is True, list size+name for every leaf child asset,
# and show totals for non-leaf children.
# If args.summarize is False, print sizes of all children.
for index, asset in enumerate(assets):
if args.asset_id and not asset:
asset_id = args.asset_id[index]
print('Asset does not exist or is not accessible: %s' % asset_id)
continue
is_parent = asset['type'] in (
ee.data.ASSET_TYPE_FOLDER,
ee.data.ASSET_TYPE_IMAGE_COLL,
ee.data.ASSET_TYPE_FOLDER_CLOUD,
ee.data.ASSET_TYPE_IMAGE_COLL_CLOUD,
)
if not is_parent or args.summarize:
self._print_size(asset)
else:
children = ee.data.getList({'id': asset['id']})
if not children:
# A leaf asset
children = [asset]
for child in children:
self._print_size(child)
def _print_size(self, asset):
size = self._get_size(asset)
print('{:>16d} {}'.format(size, asset['id']))
def _get_size(self, asset):
"""Returns the size of the given asset in bytes."""
size_parsers = {
'Image': self._get_size_asset,
'Folder': self._get_size_folder,
'ImageCollection': self._get_size_image_collection,