-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy patheodms_cli.py
2179 lines (1760 loc) · 84.5 KB
/
eodms_cli.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
##############################################################################
#
# Copyright (c) His Majesty the King in Right of Canada, as
# represented by the Minister of Natural Resources, 2024
#
# Licensed under the MIT license
# (see LICENSE or <http://opensource.org/licenses/MIT>) All files in the
# project carrying such notice may not be copied, modified, or distributed
# except according to those terms.
#
##############################################################################
__title__ = 'EODMS-CLI'
__author__ = 'Kevin Ballantyne'
__copyright__ = 'Copyright (c) His Majesty the King in Right of Canada, ' \
'as represented by the Minister of Natural Resources, 2024'
__license__ = 'MIT License'
__description__ = 'Script used to search, order and download imagery from ' \
'the EODMS using the REST API (RAPI) service.'
__version__ = '3.6.2'
__maintainer__ = 'Kevin Ballantyne'
__email__ = 'eodms-sgdot@nrcan-rncan.gc.ca'
import sys
import os
import re
import requests
# import argparse
import click
import traceback
import getpass
import datetime
import textwrap
# from geomet import wkt
# import json
# import configparser
import base64
import binascii
import logging
import logging.handlers as handlers
import pathlib
from colorama import Fore, Back, Style
# from distutils.version import LooseVersion
# from distutils.version import StrictVersion
from packaging import version as pack_v
# import unicodedata
import eodms_rapi
# from eodms_rapi import EODMSRAPI
from scripts import utils as eod_util
from scripts import field
from scripts import config_util
from scripts import sar
# from utils import csv_util
# from utils import image
# from utils import geo
proc_choices = {'full': {
'name': 'Search, order and/or download',
'desc': 'Search, order and/or download images using an AOI '
'and/or filters'
},
'order_csv': {
'name': 'EODMS UI Ordering',
'desc': 'Order & download images using EODMS UI search '
'results (CSV file)'
},
'record_id': {
'name': 'Record IDs',
'desc': 'Order and download a single or set of images '
'using Record IDs'
},
'download_available': {
'name': 'Download Available Order Items',
'desc': 'Downloads order items with status '
'AVAILABLE_FOR_DOWNLOAD'
},
'download_results': {
'name': 'Download EODMS-CLI Results',
'desc': 'Download existing orders using a CSV file from '
'a previous order/download process (files found '
'under "results" folder)'
},
'order_st': {
'name': 'Submit Order to SAR Toolbox',
'desc': 'Submit order to the SAR Toolbox'
}
}
min_rapi_version = '1.9.0'
class Prompter:
"""
Class used to prompt the user for all inputs.
"""
def __init__(self, eod, config_util, params, in_click, testing=False):
"""
Initializer for the Prompter class.
:param eod: The Eodms_OrderDownload object.
:type eod: self.Eodms_OrderDownload
:param config_util: The ConfigUtils object
:type config_util: ConfigUtils
:param params: An empty dictionary of parameters.
:type params: dict
"""
self.eod = eod
self.eod.set_prompter(self)
self.reset_col = eod.get_colour(reset=True)
self.config_util = config_util
self.config_info = config_util.get_info()
self.params = params
self.click = in_click
self.process = None
self.testing = testing
self.logger = logging.getLogger('eodms')
# def remove_accents(self, s):
# nkfd_form = unicodedata.normalize('NFKD', s)
# return u''.join([c for c in nkfd_form
# if not unicodedata.combining(c)])
def ask_aoi(self, input_fn):
"""
Asks the user for the geospatial input filename.
:param input_fn: The geospatial input filename if already set by the
command-line.
:type input_fn: str
:return: The geospatial filename entered by the user.
:rtype: str
"""
if input_fn is None or input_fn == '':
# if self.eod.silent:
# err_msg = "No AOI file or feature specified. Exiting process."
# self.eod.print_support(err_msg)
# self.logger.error(err_msg)
# sys.exit(1)
if not self.eod.silent:
self.print_header("Enter Input Geospatial File or Feature")
msg = f"Enter the full path name of a " \
f"{self.eod.var_colour}.gml{self.eod.reset_colour}, " \
f"{self.eod.var_colour}.kml{self.eod.reset_colour}, " \
f"{self.eod.var_colour}.shp{self.eod.reset_colour} or " \
f"{self.eod.var_colour}.geojson{self.eod.reset_colour} " \
f" containing an AOI or a WKT feature to " \
f"restrict the search to a specific location"
err_msg = "No AOI or feature specified. Please enter a WKT " \
"feature or a valid GML, KML, Shapefile or GeoJSON " \
"file"
def_msg = "leave blank to exclude spatial filtering"
input_fn = self.get_input(msg, err_msg, required=False,
def_msg=def_msg)
if input_fn is None or input_fn == '':
return None
if os.path.exists(input_fn):
if input_fn.find('.shp') > -1:
try:
import osgeo.ogr as ogr
import osgeo.osr as osr
# GDAL_INCLUDED = True
except ImportError:
try:
import ogr
import osr
# GDAL_INCLUDED = True
except ImportError:
err_msg = "Cannot open a Shapefile without GDAL. " \
"Please install the GDAL Python package if " \
"you'd like to use a Shapefile for your AOI."
self.eod.print_msg(err_msg, heading='warning')
self.logger.warning(err_msg)
return None
input_fn = input_fn.strip()
input_fn = input_fn.strip("'")
input_fn = input_fn.strip('"')
# ---------------------------------
# Check validity of the input file
# ---------------------------------
input_fn = self.eod.validate_file(input_fn, True)
if not input_fn:
return None
elif any(s in input_fn for s in self.eod.aoi_extensions):
err_msg = f"Input file {os.path.abspath(input_fn)} does not exist."
# self.eod.print_support(err_msg)
self.eod.print_msg(err_msg, heading="warning")
self.logger.warning(err_msg)
return None
else:
if not self.eod.eodms_geo.is_wkt(input_fn):
err_msg = "Input feature is not a valid WKT."
# self.eod.print_support(err_msg)
self.eod.print_msg(err_msg, heading="warning")
self.logger.warning(err_msg)
return None
return input_fn
def ask_aws(self, aws):
"""
Asks the user if they'd like to download the image using AWS,
if applicable.
:param aws: If already entered by the command-line, True if the user
wishes to download from AWS.
:type aws: boolean
:return: True if the user wishes to download from AWS.
:rtype: boolean
"""
if not aws:
if not self.eod.silent:
self.print_header("Download from AWS?")
print("\nSome Radarsat-1 images contain direct download "
"links to GeoTIFF files in an Open Data AWS "
"Repository.")
msg = "For images that have an AWS link, would you like to " \
"download the GeoTIFFs from the repository instead of " \
"submitting an order to the EODMS?"
aws = self.get_input(msg, required=False, default='y',
options=['Yes', 'No'])
if aws.lower().find('y') > -1:
aws = True
else:
aws = False
return aws
def ask_collection(self, coll, coll_lst=None):
"""
Asks the user for the collection(s).
:param coll: The collections if already set by the command-line.
:type coll: str
:param coll_lst: A list of collections retrieved from the RAPI.
:type coll_lst: list[str]
:return: A list of collections entered by the user.
:rtype: list[str]
"""
if coll is None:
if coll_lst is None:
coll_lst = self.eod.eodms_rapi.get_collections(True, opt='both')
if self.eod.silent:
err_msg = "No collection specified. Exiting process."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
# print(dir(coll_lst))
# print("coll_lst: %s" % coll_lst)
self.print_header("Enter Collection")
# List available collections for this user
print("\nAvailable Collections:\n")
# print(f"coll_lst: {coll_lst}")
coll_lst = sorted(coll_lst, key=lambda x: x['title'])
# coll_lst.sort()
for idx, c in enumerate(coll_lst):
msg = f"{self.eod.var_colour}{idx + 1}{self.eod.reset_colour}" \
f". {c['title']} ({c['id']})"
# if c['id'] == 'NAPL':
# msg += ' (open data only)'
print(self.wrap_text(msg))
# Prompted user for number(s) from list
msg = "Enter the number of a collection from the list " \
"above (for multiple collections, enter each number " \
"separated with a comma)"
err_msg = "At least one collection must be specified."
in_coll = self.get_input(msg, err_msg)
# Convert number(s) to collection name(s)
coll_vals = in_coll.split(',')
# ---------------------------------------
# Check validity of the collection entry
# ---------------------------------------
check = self.eod.validate_int(coll_vals, len(coll_lst))
if not check:
err_msg = "A valid Collection must be specified. " \
"Exiting process."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
coll = [coll_lst[int(i) - 1]['id'] for i in coll_vals
if i.isdigit()]
else:
coll = coll.split(',')
# ------------------------------
# Check validity of Collections
# ------------------------------
for c in coll:
check = self.eod.validate_collection(c)
if not check:
err_msg = f"Collection '{c}'' is not valid."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
return coll
def ask_dates(self, dates):
"""
Asks the user for dates.
:param dates: The dates if already set by the command-line.
:type dates: str
:return: The dates entered by the user.
:rtype: str
"""
# Get the date range
if dates is None:
if not self.eod.silent:
self.print_header("Enter Date Range")
msg = f"Enter a date range (ex: " \
f"{self.eod.var_colour}20200525-20200630T200950" \
f"{self.eod.reset_colour}) or a previous time-frame " \
f"({self.eod.var_colour}24 hours{self.eod.reset_colour})"
def_msg = "leave blank to search all years"
dates = self.get_input(msg, required=False, def_msg=def_msg)
# -------------------------------
# Check validity of filter input
# -------------------------------
if dates is not None and not dates == '':
dates = self.eod.validate_dates(dates)
if not dates:
err_msg = "The dates entered are invalid. "
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
return dates
def ask_fields(self, csv_fields, fields):
if csv_fields is not None:
return csv_fields.split(',')
srch_fields = []
for f in fields:
if f.lower() in self.eod.csv_unique:
srch_fields.append(f.lower())
if len(srch_fields) > 0:
return srch_fields
if not self.eod.silent:
self.print_header("Enter CSV Unique Fields")
print("\nAvailable fields in the CSV file:")
for f in fields:
print(f" {f}")
msg = "Enter the fields from the CSV file which can be used to " \
"determine the images (separate each with a comma)"
# err_msg = "At least one collection must be specified."
input_fields = self.get_input(msg) # , err_msg)
srch_fields = [f.strip() for f in input_fields.split(',')]
return srch_fields
def ask_filter(self, filters):
"""
Asks the user for the search filters.
:param filters: The filters if already set by the command-line.
:type filters: str
:return: A dictionary containing the filters entered by the user.
:rtype: dict
"""
if filters is None:
filt_dict = {}
if not self.eod.silent:
self.print_header("Enter Filters")
# Ask for the filters for the given collection(s)
for coll in self.params['collections']:
coll_id = self.eod.get_full_collid(coll)
coll_fields = self.eod.field_mapper.get_fields(coll_id)
# coll_fields = self.eod.get_filters(coll_id)
if coll_id in self.eod.field_mapper.get_colls():
# field_map = self.eod.get_fieldMap()[coll_id]
print(f"\nAvailable fields for '{coll}':")
# for f in coll_fields.get_eod_fieldnames():
# print(f" {f}")
avail_fields = coll_fields.get_eod_fieldnames(True)
fields_str = ', '.join(avail_fields)
print(self.wrap_text(fields_str, init_indent=' '))
print(self.wrap_text(f"\nFilters must be entered in " \
f"the format of {self.eod.var_colour}" \
f"[field_id]=[value]|[value]|" \
f"{self.eod.reset_colour}... "
f"(field IDs are not case sensitive); "
f"separate each filter with a comma.\nTo see "
f"a list of field choices, enter '" \
f"{self.eod.var_colour}? [field_id]" \
f"{self.eod.reset_colour}'."
f"\n\nExample: BEAM_MNEMONIC=16M4|16M7,"
f"PIXEL_SPACING<=20"))
msg = "Enter the filters you would like to apply " \
"to the search"
filt_items = '?'
while filt_items.find('?') > -1:
# print(f"\n{msg}:\n")
# filt_items = input(f"{self.add_arrow()} ")
def_msg = "leave blank for no fields"
filt_items = self.get_input(msg, required=False,
def_msg=def_msg)
# filt_items = input(f"\n{self.add_arrow()} " \
# f"{msg}:\n")
if filt_items.find('?') > -1:
field_val = filt_items.replace('?', '').strip()
field_obj = coll_fields.get_field(field_val)
field_title = field_obj.get_rapi_title()
if field_title is None:
print("Not a valid field.")
continue
field_choices = self.eod.eodms_rapi. \
get_field_choices(coll_id, field_title)
if isinstance(field_choices, dict):
field_choices = f'any %s value' % \
field_choices['data_type']
else:
field_choices = ', '.join(field_choices)
print(f"\nAvailable choices for "
f"'{field_val}': {field_choices}")
if filt_items == '':
filt_dict[coll_id] = []
else:
# -------------------------------
# Check validity of filter input
# -------------------------------
filt_items = self.eod.validate_filters(filt_items,
coll_id)
if not filt_items:
self.eod.exit_cli(1)
filt_items = filt_items.split(',')
# In case the user put collections in filters
filt_items = [f.split('.')[1]
if f.find('.') > -1
else f for f in filt_items]
filt_dict[coll_id] = filt_items
else:
# User specified in command-line
# Possible formats:
# 1. Only one collection: <field_id>=<value>|<value>,
# <field_id>=<value>&<value>,...
# 2. Multiple collections but only specifying one set of filters:
# <coll_id>.<field_id>=<value>|<value>,...
# 3. Multiple collections with filters:
# <coll_id>.<field_id>=<value>,...
# <coll_id>.<field_id>=<value>,...
filt_dict = {}
for coll in self.params['collections']:
# Split filters by comma
filt_lst = filters.split(',')
for f in filt_lst:
f = f.strip('"')
if f == '':
continue
if f.find('.') > -1:
coll, filt_items = f.split('.')
filt_items = self.eod.validate_filters(filt_items,
coll)
if not filt_items:
self.eod.exit_cli(1)
coll_id = self.eod.get_full_collid(coll)
if coll_id in filt_dict.keys():
coll_filters = filt_dict.get(coll_id)
else:
coll_filters = []
coll_filters.append(
filt_items.replace('"', '').replace("'", ''))
filt_dict[coll_id] = coll_filters
else:
coll_id = self.eod.get_collid_by_name(coll)
if coll_id in filt_dict.keys():
coll_filters = filt_dict[coll_id]
else:
coll_filters = []
coll_filters.append(f)
filt_dict[coll_id] = coll_filters
# print(f"filt_dict: {filt_dict}")
return filt_dict
def ask_input_file(self, input_fn, msg):
"""
Asks the user for the input filename.
:param input_fn: The input filename if already set by the command-line.
:type input_fn: str
:param msg: The message used to ask the user.
:type msg: str
:return: The input filename.
:rtype: str
"""
if input_fn is None or input_fn == '':
if self.eod.silent:
err_msg = "No CSV file specified. Exiting process."
self.eod.print_msg(err_msg, heading='error')
# self.eod.print_support(True, err_msg)
self.logger.error(err_msg)
self.eod.exit_cli(1)
self.print_header("Enter Input CSV File")
err_msg = "No CSV specified. Please enter a valid CSV file"
input_fn = self.get_input(msg, err_msg)
if not os.path.exists(input_fn):
# err_msg = "Not a valid CSV file. Please enter a valid CSV file."
err_msg = f"The specified CSV file ({input_fn}) does not exist. " \
f"Please enter a valid CSV file."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
return input_fn
def ask_maximum(self, maximum, max_type='order'):
"""
Asks the user for maximum number of order items and the number of
items per order.
:param maximum: The maximum if already set by the command-line.
:type maximum: str
:param max_type: The type of maximum to set ('order' or 'download').
:type max_type: str
:param no_order: Determines whether the maximum is for searching or
ordering.
:type no_order: boolean
:return: If max_type is 'order', the maximum number of order items
and/or number of items per order, separated by ':'. If max_type is
'download', a single number specifying how many images to download.
:rtype: str
"""
# Get the no_order value
no_order = self.params.get('no_order')
if maximum is None or maximum == '':
if not self.eod.silent:
if no_order:
self.print_header("Enter Maximum Search Results")
msg = "Enter the maximum number of images you would " \
"like to search for"
def_msg = "leave blank to search for all images"
maximum = self.get_input(msg, required=False,
def_msg=def_msg)
return maximum
if max_type == 'download':
self.print_header("Enter Maximum for Downloads")
msg = "Enter the number of images with status " \
"AVAILABLE_FOR_DOWNLOAD you would like to " \
"download"
def_msg = "leave blank to download all images with " \
"this status"
maximum = self.get_input(msg, required=False,
def_msg=def_msg)
return maximum
else:
if not self.process == 'order_csv':
self.print_header("Enter Maximums for Ordering")
msg = "Enter the total number of images you'd " \
"like to order"
def_msg = "leave blank for no limit"
total_records = self.get_input(msg, required=False,
def_msg=def_msg)
# ------------------------------------------
# Check validity of the total_records entry
# ------------------------------------------
if total_records == '':
total_records = None
else:
total_records = self.eod.validate_int(total_records)
if not total_records:
self.eod.print_msg("Total number of images "
"value not valid. "
"Excluding it.",
indent=False,
heading='warning')
total_records = None
else:
total_records = str(total_records)
else:
total_records = None
msg = "If you'd like a limit of images per order, " \
"enter a value (EODMS sets a maximum limit of " \
"100)"
def_msg = "leave blank to order all images in one order " \
"(up to 100)"
order_limit = self.get_input(msg, required=False,
def_msg=def_msg)
if order_limit == '':
order_limit = None
else:
order_limit = self.eod.validate_int(order_limit,
100)
if not order_limit:
self.eod.print_msg("Order limit "
"value not valid. "
"Excluding it.",
indent=False, heading='warning')
order_limit = None
else:
order_limit = str(order_limit)
maximum = ':'.join(filter(None, [total_records,
order_limit]))
else:
if max_type == 'order':
if self.process == 'order_csv':
self.print_header("Enter Images per Order")
if maximum.find(':') > -1:
total_records, order_limit = maximum.split(':')
else:
total_records = None
order_limit = maximum
maximum = ':'.join(filter(None, [total_records,
order_limit]))
return maximum
def ask_orderitems(self, orderitems):
"""
Asks the user for a list Order IDs or Order Item IDs.
:param orderitems
"""
if orderitems is None:
if not self.eod.silent:
self.print_header("Order/Order Item IDs")
msg = "\nEnter a list of Order IDs and/or Order Item IDs, " \
"separating each ID with a comma and separating Order " \
"IDs and Order Items with a vertical line " \
"(ex: 'orders:<order_id>,<order_id>|items:" \
"<order_item_id>,...')"
def_msg = "leave blank to skip"
orderitems = self.get_input(msg, required=False,
def_msg=def_msg)
return orderitems
def ask_order(self, no_order):
"""
Asks the user if they would like to suppress ordering and downloading.
:param no_order:
:return:
"""
if no_order is None:
if not self.eod.silent:
self.print_header("Suppress Ordering")
msg = "Would you like to only search and not order?"
no_order = self.get_input(msg, required=False,
options=['Yes', 'No'], default='n')
if no_order.lower().find('y') > -1:
no_order = True
else:
no_order = False
return no_order
def ask_output(self, output):
"""
Asks the user for the output geospatial file.
:param output: The output if already set by the command-line.
:type output: str
:return: The output geospatial filename.
:rtype: str
"""
if output is None:
if not self.eod.silent:
self.print_header("Enter Output Geospatial File")
msg = f"\nEnter the full path of the output geospatial file " \
f"(can also be " \
f"{self.eod.var_colour}.geojson{self.eod.reset_colour}," \
f" {self.eod.var_colour}.kml{self.eod.reset_colour}, " \
f"{self.eod.var_colour}.gml{self.eod.reset_colour}, or" \
f" {self.eod.var_colour}.shp{self.eod.reset_colour})"
def_msg = "default is no output file"
output = self.get_input(msg, required=False,
def_msg=def_msg)
return output
def ask_overlap(self, overlap):
if overlap is None:
if not self.eod.silent:
self.print_header("Enter Minimum Overlap Percentage")
msg = "\nEnter the minimum percentage of overlap between " \
"images and the AOI"
def_msg = "leave blank for no overlap limit"
overlap = self.get_input(msg, required=False, def_msg=def_msg)
return overlap
def ask_priority(self, priority):
"""
Asks the user for the order priority level
:param priority: The priority if already set by the command-line.
:type priority: str
:return: The priority level.
:rtype: str
"""
priorities = ['low', 'medium', 'high', 'urgent']
if priority is None:
if not self.eod.silent:
self.print_header("Enter Priority")
msg = "Enter the priority level for the order"
priority = self.get_input(msg, required=False,
options=priorities, default='medium')
if priority is None or priority == '':
priority = 'Medium'
elif priority.lower() not in priorities:
self.eod.print_msg("Not a valid 'priority' entry. "
"Setting priority to 'Medium'.", indent=False,
heading='warning')
priority = 'Medium'
return priority
def ask_process(self):
"""
Asks the user what process they would like to run.
:return: The value the process the user has chosen.
:rtype: str
"""
if self.eod.silent:
process = 'full'
else:
self.print_header("Choose Process Option")
choice_strs = []
# print(f"proc_choices.items(): {proc_choices.items()}")
for idx, v in enumerate(proc_choices.items()):
desc_str = re.sub(r'\s+', ' ', v[1]['desc'].replace('\n', ''))
choice_strs.append(self.wrap_text(f"{self.eod.var_colour}{idx + 1}" \
f"{self.eod.reset_colour}: ({v[0]}) " \
f"{desc_str}", sub_indent=' '))
choices = '\n'.join(choice_strs)
print(f"\nWhat would you like to do?\n\n{choices}")
msg = "Please choose the type of process"
# process = input(f"{self.add_arrow()} ")
process = self.get_input(msg, required=False, default='1')
# process = input(f"{self.add_arrow()} " \
# f"Please choose the type of process [1]: ")
if self.testing:
print(f"FOR TESTING - Process entered: {process}")
if process == '':
process = 'full'
else:
# Set process value and check its validity
process = self.eod.validate_int(process)
if not process:
err_msg = "Invalid value entered for the 'process' " \
"parameter."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
if process > len(proc_choices.keys()):
err_msg = "Invalid value entered for the 'process' " \
"parameter."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
else:
process = list(proc_choices.keys())[int(process) - 1]
return process
def ask_record_ids(self, ids, single_coll=False):
"""
Asks the user for a single or set of Record IDs.
:param ids: A single or set of Record IDs with their collections.
:type ids: str
"""
if ids is None or ids == '':
if not self.eod.silent:
self.print_header("Enter Record Id(s)")
msg = "\nEnter a single or set of Record IDs. Include the " \
"Collection ID at the start of IDs separated by a " \
"pipe. Separate collection's Ids with a comma. " \
f"(Ex: {self.eod.var_colour}" \
f"RCMImageProducts:7625368|25654750" \
f",NAPL:3736869{self.eod.reset_colour})\n"
if single_coll:
msg = f"\nEnter a single or set of Record IDs with the " \
f"Collection ID at the start of IDs separated by a " \
f"pipe (Ex: {self.eod.var_colour}" \
f"RCMImageProducts:7625368|25654750" \
f"{self.eod.reset_colour})\n"
ids = self.get_input(msg, required=False)
process = self.eod.validate_record_ids(ids, single_coll)
if not process:
err_msg = "Invalid entry for the Record Ids."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
return ids
def ask_st_images(self, ids):
"""
Asks the user for Record IDs or Order Keys for SAR Toolbox orders.
:param ids: A single or set of Record IDs with their collections.
:type ids: str
"""
if ids is None or ids == '':
if not self.eod.silent:
self.print_header("Enter Record Id(s) or Order Key(s)")
msg = f"\nEnter a single or set of Record IDs or enter a " \
f"single or set of Order Keys separated by a pipe. " \
f"Include the Collection Id at the beginning of the set." \
f" (Ex: {self.eod.var_colour}" \
f"RCMImageProducts:7625368|25654750" \
f"{self.eod.reset_colour} or {self.eod.var_colour}" \
f"RCMImageProducts:RCM2_OK1373330_PK1530425_1_16M12_" \
f"20210326_111202_HH_HV_GRD|RCM2_OK1373330_PK1524695_1_" \
f"16M17_20210321_225956_HH_HV_GRD{self.eod.reset_colour})\n"
ids = self.get_input(msg, required=False)
process = self.eod.validate_st_images(ids)
if not process:
err_msg = "Invalid entry for the Record Ids or Order Keys."
# self.eod.print_support(True, err_msg)
self.eod.print_msg(err_msg, heading='error')
self.logger.error(err_msg)
self.eod.exit_cli(1)
return ids
def ask_st(self):
"""
Ask user for all SAR Toolbox information
"""
def ask_param(param):
default = param.get_default(as_listidx=True, include_label=True)
# print(f"default: {default}")
if param.const_vals:
default_val = param.get_default(as_listidx=True)
default_str = param.get_default(as_listidx=True,
include_label=True)
labels = [c.get('label') for c in param.const_vals
if c.get('active')]
multiple = param.multiple
choice = ask_item(param.label, labels, 'param',
multiple=multiple,
default=default_val,
def_msg=default_str)
else:
msg = f'Enter the "{param.get_label()}"'
choice = self.get_input(msg, required=False,
default=default)
# print(f"choice: {choice}")
val_check = param.set_value(choice)
if not val_check:
err_msg = f"An invalid value has been entered. The value has " \
f"to be of type '{param.get_data_type()}'"
self.eod.print_msg(err_msg, heading='error')