-
Notifications
You must be signed in to change notification settings - Fork 0
/
sentinelsearch.py
2014 lines (1500 loc) · 59.1 KB
/
sentinelsearch.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
'''
Docstring.
'''
import ast
import sys
import os.path
import zipfile
import traceback
import xml.etree.ElementTree as etree
import requests
import qgis
from PyQt4.QtCore import QDate, Qt, QObject, pyqtSignal
from PyQt4.QtGui import QMessageBox, QFileDialog, QTableWidgetItem, QWidget
class SentinelSearch(QObject):
'''
This class holds all of the search and download functionality.
'''
query_check = pyqtSignal(str)
finished = pyqtSignal(bool)
finished_download = pyqtSignal(bool)
set_message = pyqtSignal(str)
connecting_message = pyqtSignal(str)
searching_message = pyqtSignal(str)
download_message = pyqtSignal(str)
search_progress_max = pyqtSignal(int)
search_progress_set = pyqtSignal(int)
download_progress_set = pyqtSignal(int)
download_progress_max = pyqtSignal(int)
enable_btnSearch = pyqtSignal()
def __init__(self, dialog):
QObject.__init__(self)
self.dlg = dialog
self.killed = False
self.value = self.set_value()
self.session = None
self.fileDialog = None
self.maxrecords = None
def open(self):
'''
Open file dialog and return selected directory path.
'''
self.fileDialog = QFileDialog()
# self.fileDialog.show()
self.dlg.writeDir_txtPath.setText(
self.fileDialog.getExistingDirectory())
def get_arguments(self):
'''
This function retrieves user input information from GUI.
'''
#
# Create options namespace. Perhaps (definitely) bad practice.
#
options = Namespace()
#
# Determine data download hub (e.g. ESA API or dhus)
#
if self.dlg.hub_comboBox.currentText() == 'API Hub':
options.hub = 'apihub'
options.huburl = 'https://scihub.copernicus.eu/apihub/'
self.maxrecords = 100
elif self.dlg.hub_comboBox.currentText() == 'Dhus':
options.hub = 'dhus'
options.huburl = 'https://scihub.copernicus.eu/dhus/'
self.maxrecords = 10
elif self.dlg.hub_comboBox.currentText() == 'ZAMG':
options.hub = 'zamg'
options.huburl = 'https://data.sentinel.zamg.ac.at/'
self.maxrecords = 100
elif self.dlg.hub_comboBox.currentText() == 'HNSDMS':
options.hub = 'hnsdms'
options.huburl = 'https://sentinels.space.noa.gr/dhus/'
self.maxrecords = 100
# elif self.dlg.hub_comboBox.currentText() == 'Finhub':
# options.hub = 'finhub'
# options.huburl = 'https://finhub.nsdc.fmi.fi/odata/'
# self.maxrecords = 100
else:
options.hub = None
options.huburl = None
self.maxrecords = None
#
# Define which sensor should be queried.
#
if self.dlg.sensor_comboBox.currentText() == 'All':
options.sentinel = None
elif self.dlg.sensor_comboBox.currentText() == 'Sentinel-1':
options.sentinel = 'S1'
elif self.dlg.sensor_comboBox.currentText() == 'Sentinel-1A':
options.sentinel = 'S1A'
elif self.dlg.sensor_comboBox.currentText() == 'Sentinel-1B':
options.sentinel = 'S1B'
elif self.dlg.sensor_comboBox.currentText() == 'Sentinel-2':
options.sentinel = 'S2'
elif self.dlg.sensor_comboBox.currentText() == 'Sentinel-2A':
options.sentinel = 'S2A'
elif self.dlg.sensor_comboBox.currentText() == 'Sentinel-2B':
options.sentinel = 'S2B'
#
# Sort results by ingestion or acquisition date, asc. or desc..
#
if self.dlg.orderBy_comboBox.currentText() != '':
options.orderby = self.dlg.orderBy_comboBox.currentText()
else:
options.orderby = None
#
# User credentials.
#
if self.dlg.user_lineEdit.text() != '':
options.user = self.dlg.user_lineEdit.text()
else:
options.user = None
if self.dlg.pass_lineEdit.text() != '':
options.password = self.dlg.pass_lineEdit.text()
else:
options.password = None
#
# Coordinates for polygon or point locations.
#
if self.dlg.LLX_lineEdit.text() != '':
options.lonmin = self.dlg.LLX_lineEdit.text()
else:
options.lonmin = None
if self.dlg.ULX_lineEdit.text() != '':
options.lonmax = self.dlg.ULX_lineEdit.text()
else:
options.lonmax = None
if self.dlg.LLY_lineEdit.text() != '':
options.latmin = self.dlg.LLY_lineEdit.text()
else:
options.latmin = None
if self.dlg.ULY_lineEdit.text() != '':
options.latmax = self.dlg.ULY_lineEdit.text()
else:
options.latmax = None
if self.dlg.lat_lineEdit.text() != '':
options.lat = self.dlg.lat_lineEdit.text()
else:
options.lat = None
if self.dlg.lon_lineEdit.text() != '':
options.lon = self.dlg.lon_lineEdit.text()
else:
options.lon = None
#
# Sentinel-2 tile name for S2 tile extraction.
#
if (self.dlg.s2Extract_checkBox.isChecked() is True
and self.dlg.s2Extract_checkBox.isEnabled() is True):
options.tile = (self.dlg.s2Tile_lineEdit.text()).upper()
else:
options.tile = None
#
# Directory to save data.
#
if self.dlg.writeDir_txtPath.text() != '':
options.write_dir = self.dlg.writeDir_txtPath.text()
else:
options.write_dir = None
#
# Maximum record number (max. 100 for API hub, 10 for dhus).
#
options.max_records = self.dlg.maxRecords_spinBox.cleanText()
#
# Ingestion dates.
#
if self.dlg.ingest_enable.isChecked():
options.start_ingest_date = self.dlg.ingestFrom_dateEdit.date()
options.end_ingest_date = self.dlg.ingestTo_dateEdit.date()
#
# Convert ingestion dates to proper ISO format.
#
options.start_ingest_date = QDate.toString(
options.start_ingest_date, 'yyyy-MM-dd')
options.end_ingest_date = QDate.toString(
options.end_ingest_date, 'yyyy-MM-dd')
else:
options.start_ingest_date = None
options.end_ingest_date = None
#
# Dates of capture.
#
if self.dlg.date_enable.isChecked():
options.start_date = self.dlg.dateFrom_dateEdit.date()
options.end_date = self.dlg.dateTo_dateEdit.date()
#
# Convert sensing dates to proper ISO format.
#
options.start_date = QDate.toString(
options.start_date, 'yyyy-MM-dd')
options.end_date = QDate.toString(
options.end_date, 'yyyy-MM-dd')
else:
options.start_date = None
options.end_date = None
#
# Orbit direction (e.g. ascending, descending).
#
if self.dlg.orbitDir_comboBox.currentText() != '':
options.orbitdir = self.dlg.orbitDir_comboBox.currentText()
else:
options.orbitdir = None
#
# Relative or absolute orbit number.
#
if (self.dlg.orbit_lineEdit.text() != ''
and self.dlg.relOrbit_radioButton.isChecked() is True):
options.rel_orbit = self.dlg.orbit_lineEdit.text()
options.abs_orbit = None
elif (self.dlg.orbit_lineEdit.text() != ''
and self.dlg.absOrbit_radioButton.isChecked() is True):
options.rel_orbit = None
options.abs_orbit = self.dlg.orbit_lineEdit.text()
else:
options.rel_orbit = None
options.abs_orbit = None
#
# S1 product (e.g. GRD, SLC, OCN).
#
if (self.dlg.s1Product_comboBox.currentText() != ''
and self.dlg.s1Product_comboBox.isEnabled() is True):
options.s1product = self.dlg.s1Product_comboBox.currentText()
else:
options.s1product = None
#
# S1 polarisation (e.g. HH, VH, HV, VV, HH+HV, VV+VH).
#
if (self.dlg.s1Polar_comboBox.currentText() != ''
and self.dlg.s1Polar_comboBox.isEnabled() is True):
options.s1polar = self.dlg.s1Polar_comboBox.currentText()
else:
options.s1polar = None
#
# S1 operational mode (e.g. SM, IW, EW, WV).
#
if (self.dlg.s1Mode_comboBox.currentText() != ''
and self.dlg.s1Mode_comboBox.isEnabled() is True):
options.s1mode = self.dlg.s1Mode_comboBox.currentText()
else:
options.s1mode = None
#
# S2 product (e.g. S2MSI1C, S2MSI2Ap).
#
if (self.dlg.s2Product_comboBox.currentText() != ''
and self.dlg.s2Product_comboBox.isEnabled() is True):
options.s2product = self.dlg.s2Product_comboBox.currentText()
else:
options.s2product = None
#
# Maximum cloud cover percentage for S2 images.
#
if (self.dlg.cloudCover_enable.isChecked()
and self.dlg.cloudCover_spinBox.isEnabled() is True):
options.max_cloud = self.dlg.cloudCover_spinBox.cleanText()
else:
options.max_cloud = None
return options
def args_to_messagebox(self, options, query=None):
'''
This function prints GUI input arguments to a message box as a test.
'''
options_dict = vars(options)
options_string = ''
for key, val in options_dict.iteritems():
options_string += '{} : {}\n'.format(key, val)
msg_args = QMessageBox()
msg_args.setIcon(QMessageBox.Information)
msg_args.setText(options_string)
# msg_args.setInformativeText("This is additional information")
# msg_args.setWindowTitle("MessageBox demo")
if query is not None:
msg_args.setDetailedText(query)
msg_args.exec_()
def text_to_messagebox(self, header, message, long_text=None):
msg_txt = QMessageBox()
msg_txt.setIcon(QMessageBox.Information)
msg_txt.setText(message)
# msg_txt.setInformativeText("This is additional information")
msg_txt.setWindowTitle(header)
if long_text is not None:
msg_txt.setDetailedText(long_text)
msg_txt.exec_()
def get_tile_coords(self):
'''
Prints returned tile center coordinates to GUI or creates an
error message box.
'''
#
# Get tile name from GUI and conduct API request with kml_api()
#
s2_tile = self.dlg.s2Tile_lineEdit.text()
coords = self.kml_api(s2_tile)
#
# Parse the response and print to GUI or throw exception.
#
try:
lon = str(round((float(coords[0])), 4))
lat = str(round((float(coords[1])), 4))
self.dlg.lat_lineEdit.setText(lat)
self.dlg.lon_lineEdit.setText(lon)
except:
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText('API failed or tile not found.')
msg.setWindowTitle('Sentinel-2 Tile Search')
msg.exec_()
def kml_api(self, tile):
'''
Returns the center point of a defined S2 tile based on an
API developed by M. Sudmanns.
'''
with requests.Session() as s:
api_request = (
'http://cf000008.geo.sbg.ac.at/cgi-bin/s2-dashboard/api.py?'
'centroid={}').format(tile)
try:
r = s.get(api_request)
#
# TODO: This needs beter exception handling.
#
if r.status_code != 200:
r.raise_for_status()
#
# Read string result as a dictionary.
#
result = {}
result = r.text
result = ast.literal_eval(result)
#
# Catch base-class exception.
#
except requests.exceptions.RequestException as e:
# print '\n\n{}\n\n'.format(e)
result = {"status": "FAIL"}
#
# Extract lat, lon from API request, or try to get from file if failed.
#
if result["status"] == "OK" and result["data"]:
coords = [result["data"]["x"], result["data"]["y"]]
return coords
else:
return 'API failed.'
def create_query(self, options):
'''
Creates a query string for the data hub based on GUI input.
'''
#
# Build in checks for valid commands related to the spatial aspect.
#
if ((options.latmin is not None
or options.lonmin is not None
or options.latmax is not None
or options.lonmax is not None)
and (options.lat is not None or options.lon is not None)):
self.query_check.emit('Inconsistent geometries.')
return None
elif options.lat is not None and options.lon is not None:
geom = 'point'
elif (options.latmin is not None
and options.lonmin is not None
and options.latmax is not None
and options.lonmax is not None):
geom = 'rectangle'
else:
geom = None
if geom is None and (options.lat is not None or options.lon is not None):
self.query_check.emit('Incomplete point.')
return None
elif geom is None and (options.latmin is not None
or options.lonmin is not None
or options.latmax is not None
or options.lonmax is not None):
self.query_check.emit('Incomplete polygon.')
return None
#
# Instantiate query string.
#
query = ''
#
# Create spatial parts of the query ::: point or rectangle.
# Beware of the quotation marks in the query string.
#
if geom == 'point':
if (sys.platform.startswith('linux')
or sys.platform.startswith('darwin')):
query += '(footprint:\\"Intersects({} {})\\")'.format(
options.lon, options.lat)
else:
query += '(footprint:"Intersects({} {})")'.format(
options.lon, options.lat)
elif geom == 'rectangle':
if (sys.platform.startswith('linux')
or sys.platform.startswith('darwin')):
query += (
'(footprint:\\"Intersects(POLYGON(({lonmin} {latmin}, '
'{lonmax} {latmin}, {lonmax} {latmax}, {lonmin} {latmax}, '
'{lonmin} {latmin})))\\")').format(
latmin=options.latmin,
latmax=options.latmax, lonmin=options.lonmin,
lonmax=options.lonmax)
else:
query += (
'(footprint:"Intersects(POLYGON(({lonmin} {latmin}, '
'{lonmax} {latmin}, {lonmax} {latmax}, {lonmin} {latmax}, '
'{lonmin} {latmin})))")').format(
latmin=options.latmin,
latmax=options.latmax, lonmin=options.lonmin,
lonmax=options.lonmax)
else:
pass
#
# Add Sentinel mission.
#
if options.sentinel == 'S1':
query += ' AND (platformname:Sentinel-1)'
elif options.sentinel == 'S2':
query += ' AND (platformname:Sentinel-2)'
elif options.sentinel == 'S3':
query += ' AND (platformname:Sentinel-3)'
elif options.sentinel == 'S1A':
query += ' AND (platformname:Sentinel-1 AND filename:S1A_*)'
elif options.sentinel == 'S1B':
query += ' AND (platformname:Sentinel-1 AND filename:S1B_*)'
elif options.sentinel == 'S2A':
query += ' AND (platformname:Sentinel-2 AND filename:S2A_*)'
elif options.sentinel == 'S2B':
query += ' AND (platformname:Sentinel-2 AND filename:S2B_*)'
else:
pass
#
# Add sensing/acquisition/capture date.
#
if options.start_date is not None or options.end_date is not None:
query += (
' AND (beginPosition:[{0}T00:00:00.000Z TO {1}T23:59:59.999Z] '
'AND endPosition:[{0}T00:00:00.000Z TO {1}T23:59:59.999Z])'
).format(
options.start_date, options.end_date)
else:
pass
#
# Add database ingestion date.
#
if (options.start_ingest_date is not None
or options.end_ingest_date is not None):
query += (
' AND (ingestionDate:[{}T00:00:00.000Z TO {}T23:59:59.999Z])'
).format(
options.start_ingest_date, options.end_ingest_date)
else:
pass
#
# Add orbits, if defined (default: NONE).
#
if options.rel_orbit is not None:
query += ' AND (relativeorbitnumber:{})'.format(options.rel_orbit)
elif options.abs_orbit is not None:
query += ' AND (orbitnumber:{})'.format(options.abs_orbit)
else:
pass
#
# Orbit direction as free text.
#
if options.orbitdir is not None:
query += ' AND {}'.format(options.orbitdir)
else:
pass
#
# Add Sentinel-1 specific query parameters.
#
if options.s1product is not None:
query += ' AND (producttype:{})'.format(options.s1product)
else:
pass
if options.s1polar is not None:
query += ' AND (polarisationmode:{})'.format(options.s1polar)
else:
pass
if options.s1mode is not None:
query += ' AND (sensoroperationalmode:{})'.format(options.s1mode)
else:
pass
#
# Add Sentinel-2 specific query parameters.
#
if options.s2product is not None:
query += ' AND (producttype:{})'.format(options.s2product)
else:
pass
if (options.max_cloud is not None
and (
options.sentinel == 'S2'
or options.sentinel == 'S2A'
or options.sentinel == 'S2B')):
query += ' AND (cloudcoverpercentage:[0.0 TO {}])'.format(
options.max_cloud)
else:
pass
#
# Sort results, if desired.
#
if options.orderby == 'Ingestion date, ascending':
orderby = 'orderby=ingestiondate asc'
elif options.orderby == 'Ingestion date, descending':
orderby = 'orderby=ingestiondate desc'
elif options.orderby == 'Sensing date, ascending':
orderby = 'orderby=beginposition asc'
elif options.orderby == 'Sensing date, descending':
orderby = 'orderby=beginposition desc'
else:
orderby = None
#
# Set rows to number of maxrecords or less, if query is smaller.
#
if int(options.max_records) <= self.maxrecords:
self.maxrecords = options.max_records
else:
self.maxrecords = str(self.maxrecords)
#
# Correct query string if no geographic coordinates are given.
#
if query.startswith(' AND'):
query = query[5:]
if query == '' or query is None:
self.query_check.emit('No Parameters.')
return None
#
# Create query string.
#
if orderby is not None:
query = '{}search?q=({})&rows={}&{}'.format(
options.huburl, query, self.maxrecords, orderby)
else:
query = '{}search?q=({})&rows={}'.format(
options.huburl, query, self.maxrecords)
#
# Print arguments to message box for test.
#
# self.args_to_messagebox(options, query)
# self.text_to_messagebox('Query', query)
return query
def start_session(self, options):
'''
This function creates a requests session based on authorization info
input in the GUI (i.e. hub, user and pass).
'''
#
# Emit message to UI.
#
self.connecting_message.emit('Connecting . . .')
#
# Authorize ESA API or DataHub Credentials
#
if options.user is not None and options.password is not None:
account = options.user
passwd = options.password
else:
account = None
passwd = None
#
# Start session/authorization using requests module.
#
self.session = requests.Session()
self.session.auth = (account, passwd)
def set_value(self):
'''
A place to set platform dependent bits.
'''
if (sys.platform.startswith('linux')
or sys.platform.startswith('darwin')):
value = '\$value'
else:
value = '$value'
return value
def get_query_xml(self):
'''
This function retrieves an xml result from the query to the hub.
'''
options = self.get_arguments()
if (options.tile is not None
and options.sentinel != 'S2'
and options.sentinel != 'S2A'
and options.sentinel != 'S2B'):
self.query_check.emit('Tile extraction error')
self.finished.emit(True)
return
if options.user is None or options.password is None:
self.query_check.emit('Missing authorization credentials.')
self.finished.emit(True)
return
query = self.create_query(options)
if query is None:
self.finished.emit(True)
return
#
# Create authenticated http session.
#
self.start_session(options)
tW1 = self.dlg.s1Results_tableWidget
tW2 = self.dlg.s2Results_tableWidget
# TODO: add loop to accomodate larger queries of more than 100
# records, where start is updated. Max rows are hardcoded or
# modified to smallernumbers already in create_query().
#
# Create GET request from hub and parse it.
#
try:
response = self.session.get(query, stream=True, timeout=5)
except (requests.HTTPError,
requests.ConnectionError,
requests.Timeout) as e:
self.query_check.emit(str(e))
self.session.close()
self.finished.emit(True)
return
query_tree = etree.fromstring(response.content)
entries = query_tree.findall('{http://www.w3.org/2005/Atom}entry')
#
# Create progress bar with maximum as the number of entries.
#
self.search_progress_max.emit(len(entries))
self.searching_message.emit('Searching . . .')
#
# Set a counter to reference the progress.
#
i = 0
for entry in range(len(entries)):
if self.killed is True:
# kill request received, exit loop early.
break
#
# Update progress bar.
#
i = i + 1
percent = int((i/float(len(entries))) * 100)
self.search_progress_set.emit(percent)
#
# The UUID element is unique for each record and the key
# ingredient for creating the path to the file.
#
uuid_element = (entries[entry].find(
'{http://www.w3.org/2005/Atom}id')).text
title_element = (entries[entry].find(
'{http://www.w3.org/2005/Atom}title')).text
#
# Check both tables for UUID and filename.
# Skip if already in either table.
#
tW1_UUIDs = []
tW1_fns = []
tW1Rows = tW1.rowCount()
for row in xrange(0, tW1Rows):
#
# Try loop to avoid when UUID is None (Database issue)
#
try:
tw1_col11 = tW1.item(row, 11).text()
tW1_UUIDs.append(tw1_col11)
tw1_col0 = tW1.item(row, 0).text()
tW1_fns.append(tw1_col0)
except:
# This seems to happen, if UUID is None.
pass
tW2_UUIDs = []
tW2_fns = []
tW2Rows = tW2.rowCount()
for row in xrange(0, tW2Rows):
#
# Try loop to avoid when UUID is None (Database issue)
#
try:
tw2_col11 = tW2.item(row, 11).text()
tW2_UUIDs.append(tw2_col11)
tw2_col0 = tW2.item(row, 0).text()
tW2_fns.append(tw2_col0)
except:
# This seems to happen, if UUID is None.
pass
if uuid_element in tW2_UUIDs or uuid_element in tW1_UUIDs:
continue
elif title_element in tW2_fns or title_element in tW1_fns:
continue
elif uuid_element is None or title_element is None:
continue
#
# If UUID and titel not in one of the tables, add record
# to respective table.
#
else:
#
# The title element contains the corresponding file name.
#
filename = (entries[entry].find(
'.//*[@name="filename"]')).text
size_element = (entries[entry].find(
'.//*[@name="size"]')).text
rel_orbit = int((entries[entry].find(
'.//*[@name="relativeorbitnumber"]')).text)
footprint = (entries[entry].find(
'.//*[@name="footprint"]')).text
sensing_date = ((entries[entry].find(
'.//*[@name="beginposition"]')).text)[:10]
sentinel_link = ("{}odata/v1/Products('{}')/{}").format(
options.huburl, uuid_element, self.value)
footprint = footprint.replace(
'POLYGON ((', "").replace('))', "").split(',')
xList = []
yList = []
for coords in footprint:
xList.append(float(coords.split(' ')[0]))
yList.append(float(coords.split(' ')[1]))
lonmin = float('{0:.2f}'.format(min(xList)))
lonmax = float('{0:.2f}'.format(max(xList)))
latmin = float('{0:.2f}'.format(min(yList)))
latmax = float('{0:.2f}'.format(max(yList)))
if filename.startswith('S1'):
try:
s1Product = (entries[entry].find(
'.//*[@name="producttype"]')).text
except:
s1Product = '---'
try:
s1Polar = (entries[entry].find(
'.//*[@name="polarisationmode"]')).text
except:
s1Polar = '---'
try:
s1Mode = (entries[entry].find(
'.//*[@name="sensoroperationalmode"]')).text
except:
s1Mode = '---'
#
# Add items to S1 table.
#
c = tW1.rowCount()
tW1.setRowCount(c + 1)
self.add_to_table(tW1, title_element, c, 0)
self.add_to_table(tW1, s1Product, c, 1)
self.add_to_table(tW1, s1Polar, c, 2)
self.add_to_table(tW1, s1Mode, c, 3)
self.add_to_table(tW1, sensing_date, c, 4)
self.add_to_table(tW1, rel_orbit, c, 5)
self.add_to_table(tW1, size_element, c, 6)
self.add_to_table(tW1, latmin, c, 7)