-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendown.py
executable file
·417 lines (395 loc) · 18.2 KB
/
sendown.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
#!/usr/bin/env python
import os
import datetime
import pprint
import requests
from xml.etree import ElementTree
import csv
import urlparse
import getpass
import shutil
import argparse
import time
import zipfile
from PIL import Image
import sys
desc = """This command-line tool helps you download Sentinel-1A and \
Sentinel-2A data products from the European Space Agency's Scientific\
Datahub.
It also allows us to download only one Sentinel-2A tile from a product."""
def ParseProducts(xml):
tree = ElementTree.ElementTree(ElementTree.fromstring(xml.content))
root = tree.getroot()
entryList = tree.findall('{http://www.w3.org/2005/Atom}entry')
HEADER = ["href", "quicklook", "filename",
"orbitdirection", "platformserialidentifier",
"instrument", "processingbaseline",
"processinglevel", "size"]
Sentinel2Ameta = []
for entry in entryList:
links = entry.findall("{http://www.w3.org/2005/Atom}link")
qSen = {}
qSen['href'] = links[0].attrib['href']
qSen['quicklook'] = links[2].attrib['href']
strings = entry.findall("{http://www.w3.org/2005/Atom}str")
for string in strings:
if string.attrib['name'] in HEADER:
qSen[string.attrib['name']] = string.text
Sentinel2Ameta.append(qSen)
return Sentinel2Ameta
def QueryTileCoords(tileid):
path = os.path.dirname(os.path.realpath(__file__))
tiledatabase = path + os.sep + 'sen2tiles.csv'
tiledict = {}
with open(tiledatabase, 'rt') as f:
reader = csv.reader(f)
for row in reader:
tiledict[row[0]] = [row[2], row[1]]
return tiledict[tileid]
def DownloadFile(user, password, requrl, opath, auth):
valid = False
while valid == False:
with open(opath, 'wb') as f:
print " - Start downloading ... "
print " - " + os.path.split(opath)[1]
start = time.time()
r = requests.get(requrl, auth=auth, verify=False, stream=True)
fileLength = int(r.headers.get('content-length'))
dl = 0
if fileLength is None:
f.write(r.content)
else:
done = 0
sys.stdout.write("[%s]" % (" " * 50))
sys.stdout.flush()
sys.stdout.write("\b" * (51))
for chunk in r.iter_content(1024):
dl += len(chunk)
f.write(chunk)
changed = int(50 * dl / fileLength) != done
done = int(50 * dl / fileLength)
if changed == True:
sys.stdout.write("[%s\r" % (done * "="))
sys.stdout.flush()
sys.stdout.write("\n")
elapsedtime = (time.time() - start)/60
if os.path.splitext(opath)[1] == ".zip":
try:
valid = zipfile.is_zipfile(opath)
except:
print "Failed downloading. Sendown is gonna try it again."
print requrl
if os.path.splitext(opath)[1] in [".jp2", ".jpg"]:
try:
img = Image.open(opath)
valid = True
img = None
except:
print "Failed downloading. Sendown is gonna try it again."
if valid == True:
print "Download complete ... Time: %s mins" % (str(elapsedtime))
def QueryProducts(user, password, query):
try:
session = requests.Session()
session.auth = (user, password)
response = requests.get(query, auth=session.auth, verify=False)
if response.status_code == 503:
print ("503 error code - Service Unavailable")
return response
except Exception as e:
print " Request: ", e
def MenuText(listofdicts, quick, odir):
print 50 * '-'
print "No. QUERY RESULT "
print 50 * "-"
for i in range(1, len(listofdicts) + 1):
print i, listofdicts[i - 1]['filename']
print "* All product"
print 50 * "-"
if (quick == True):
print ' -- Check your quicklooks in your output directory : ', odir
print " -- Enter the number of the product(s) " \
"you wish to download."
print " -- Listed above i.e. 1,2,4"
print " -- If you need all products than just enter * "
def GetEntries(url, sessionauth):
response = requests.get(url, auth=sessionauth, verify=False)
tree = ElementTree.ElementTree(ElementTree.fromstring(response.content))
root = tree.getroot()
linklist = tree.findall("{http://www.w3.org/2005/Atom}entry")
return linklist
def MakeRootDir(rootnodeurl, odir, sessionauth):
entries = GetEntries(rootnodeurl, sessionauth)
for entry in entries:
for child in entry:
if child.tag == "{http://www.w3.org/2005/Atom}title":
odir = odir + os.sep + child.text
if not os.path.exists(odir):
os.mkdir(odir)
return odir
def PullTile(nodeurl, tileid, sessionauth):
try:
tildict = {}
entries = GetEntries(nodeurl, sessionauth)
for entry in entries:
for child in entry:
if child.tag == "{http://www.w3.org/2005/Atom}link":
if 'title' in child.attrib.keys():
if child.attrib['title'] == 'Nodes':
inurl = urlparse.urljoin(nodeurl, child.attrib[
'href']) + "('GRANULE')/Nodes"
tileentries = GetEntries(inurl, sessionauth)
for tileentry in tileentries:
for child in tileentry:
if "{http://www.w3.org/2005/Atom}title" ==\
child.tag:
if tileid == child.text[-13:-7]:
tildirurl = inurl + \
"('%s')/Nodes('IMG_DATA')/Nodes" \
% (child.text)
bandentries = GetEntries(tildirurl,
sessionauth)
for bandentry in bandentries:
for bandchild in bandentry:
if bandchild.tag == \
'{http://www.w3.org/2005/Atom}title':
tildict[bandchild.text]\
= tildirurl + \
"('%s')/$value" %\
(bandchild.text)
return (tildict)
except Exception as e:
print e
def main():
parser = argparse.ArgumentParser(description=desc,
version='%prog version 0.1')
parser.add_argument('-l', '--latlon',
help='WGS84 point coordinates i.e. Budapest 47.5 19.04',
dest='latlon',
nargs=2, action='store')
parser.add_argument('-s', '--sat',
help='Which satellite/platform i.e. S1A or S2A',
dest='platform')
parser.add_argument('-e', '--extent',
help='Extent Coordinates xmin ymin xmax ymax i.e. '
'16.72 45.74 22.21 48.37 for Hungary',
dest='extent', nargs=4)
parser.add_argument('-t', '--tile',
help='Sentinel-2A Tile ID i.e. T34TCT for Budapest',
dest='tile')
parser.add_argument('-d', '--dates',
help='Date Interval, if not set it only checks that day',
dest='dates', nargs=2,
default=(
datetime.datetime.now().strftime("%Y-%m-%d"),
datetime.datetime.now().strftime("%Y-%m-%d")))
parser.add_argument('-u', '--username',
help='username - SciHub username, if '
'not set it goes by guest by default',
dest='user', default='guest')
parser.add_argument('-o', '--odir', help='Output Directory', dest='odir',
default=os.getcwd())
parser.add_argument('-y', '--type',
help='Sentinel-1A Product Type i.e. RAW, SLC, GRD',
dest='type')
parser.add_argument('-q', '--quicklook',
help='At first download quicklooks to the Output Directory',
dest='quick',
action='store_true', default=False)
parser.add_argument('--hun', help='Extent of Hungary', dest='hun',
action='store_true', default=False)
args = parser.parse_args()
apihub = 'https://scihub.copernicus.eu/dhus/search?rows=10000&q='
if args.user is 'guest':
args.password = 'guest'
if args.user is not 'guest':
args.password = getpass.getpass()
if args.hun:
args.extent = ['16.72', '45.74', '22.21', '48.37']
if (args.tile is not None) and (
args.latlon is not None or args.extent is not None):
print ' -- You need to switch on the [-t, --tile] option OR the ' \
'[-l, --latlon] OR [-e, --extent] options to specify your '\
'Area of Interest'
print ' -- If you plan to perform downloading by tile you ' \
'would switch only the [-t, --tile] option.' \
' i.e. -t T34TCT for Budapest'
quit()
if args.platform is None:
print ' -- You forget to set the satellite option [-s, --sat]: S1A ' \
'or S2A'
if args.tile is not None:
print " -- Start querying products by tile"
print " -- Username : ", args.user
print " -- TileID : ", args.tile
args.platform = "Sentinel-2"
platform = 'AND (platformname:%s)' % (args.platform)
print " -- Platform : ", args.platform
args.tilelatlon = QueryTileCoords(args.tile)
if args.tilelatlon:
footprint = '( footprint:"Intersects(%s)" )' % (
",".join(list(args.tilelatlon)))
print " -- LatLon : ", args.tilelatlon
date0, date1 = args.dates
if date0 == date1:
date1 = (
datetime.datetime.strptime(date0,
"%Y-%m-%d") + datetime.timedelta(
1)).strftime("%Y-%m-%d")
interval = ' AND beginPosition:[' + date0 + 'T00:00:00.000Z TO ' \
+ date1 + 'T00:00:00.000Z] AND endPosition:[' \
+ date0 + 'T00:00:00.000Z TO ' + date1 + 'T00:00:00.000Z]'
print " -- Date Interval : ", date0, date1
query = apihub + footprint + interval + platform
print " -- This is your OPENDATA query:"
print query
xml = QueryProducts(args.user, args.password, query)
meta = list(reversed(ParseProducts(xml)))
print ' -- Product number : ', len(meta)
if (args.quick == True) and (len(meta) > 0):
print " -- Downloading quicklooks ... "
session = requests.Session()
session.auth = (args.user, args.password)
for product in meta:
ofile = args.odir + os.sep + \
os.path.splitext(product['filename'])[0] + ".jpg"
print "Quicklook : ", ofile
DownloadFile(args.user, args.password, product['quicklook'],
ofile, session.auth)
if (len(meta) > 0):
MenuText(meta, args.quick, args.odir)
while True:
try:
userinput = raw_input('Number(s):')
productnumbers = [i.strip() for i in userinput.split(',')]
if ('*' in productnumbers) and (len(productnumbers) == 1):
print ' -- Downloading all listed products!'
productnumbers = [i for i in range(1, len(meta) + 1)]
break
else:
productnumbers = [int(i.strip()) for i in
userinput.split(',')]
except Exception:
print '!!! Your input is not valid !!!'
continue
subsettest = set(productnumbers) <= set(
[p + 1 for p in range(0, len(meta))])
if subsettest == True:
break
if subsettest == False:
print '!!! Your input is not valid !!!'
if (len(productnumbers) > 0):
try:
session = requests.Session()
session.auth = (args.user, args.password)
for i in productnumbers:
rooturl = os.path.split(meta[i - 1]['href'])[
0] + '/Nodes'
productdir = MakeRootDir(rooturl, args.odir,
session.auth)
tiledir = productdir + os.sep + args.tile
if os.path.exists(tiledir):
shutil.rmtree(tiledir)
os.mkdir(tiledir)
tiledict = PullTile(rooturl, args.tile, session.auth)
for band in tiledict:
print "Band: ", band
oband = tiledir + os.sep + band
with open(oband, "wb") as code:
r = requests.get(tiledict[band],
auth=session.auth,
verify=False)
code.write(r.content)
except Exception as e:
print e
if (args.latlon is not None or args.extent is not None and
args.platform is not None):
print " -- Start querying products by latlon or extent"
if args.latlon:
footprint = '( footprint:"Intersects(%s)" )' % (
",".join(list(args.latlon)))
print "LatLon : ", ",".join(list(args.latlon))
if args.extent:
footprint = '( footprint:"Intersects(POLYGON(({xmin} {ymin}, ' \
'{xmax} {ymin}, {xmax} {ymax}, ' \
'{xmin} {ymax},{xmin} {ymin})))" )'.format(
xmin=args.extent[0], ymin=args.extent[1], xmax=args.extent[2],
ymax=args.extent[3])
print "Extent : ", list(args.extent)
if args.platform == "S1A":
longplat = "Sentinel-1"
platform = ' AND (platformname:%s)' % (longplat)
if args.platform == "S3A":
longplat = "Sentinel-3"
platform = ' AND (platformname:%s)' % (longplat)
if args.platform == "S2A":
longplat = "Sentinel-2"
platform = ' AND (platformname:%s)' % (longplat)
print "Platform : ", longplat
if args.type in ['GRD', 'SLC', 'RAW']:
platform = 'AND (platformname:%s AND producttype:%s)' % (
longplat, args.type)
date0, date1 = args.dates
if date0 == date1:
date1 = (
datetime.datetime.strptime(date0,
"%Y-%m-%d") + datetime.timedelta(
1)).strftime("%Y-%m-%d")
interval = ' AND beginPosition:[' + date0 + 'T00:00:00.000Z TO ' +\
date1 + 'T00:00:00.000Z] AND endPosition:' \
'[' + date0 + 'T00:00:00.000Z TO ' + date1 + \
'T00:00:00.000Z]'
print "Date Interval: ", date0, date1
query = apihub + footprint + interval + platform
print query
xml = QueryProducts(args.user, args.password, query)
meta = list(reversed(ParseProducts(xml)))
meta = ParseProducts(xml)
print 'Product number : ', len(meta)
if (args.quick == True) and (len(meta) > 0):
print " -- Downloading quicklooks ... "
session = requests.Session()
session.auth = (args.user, args.password)
for product in meta:
ofile = args.odir + os.sep + \
os.path.splitext(product['filename'])[0] + ".jpg"
print "Quicklook : ", ofile
DownloadFile(args.user, args.password, product['quicklook'],
ofile, session.auth)
if (len(meta) > 0):
MenuText(meta, args.quick, args.odir)
while True:
try:
userinput = raw_input('Number(s):')
productnumbers = [i.strip() for i in userinput.split(',')]
if ('*' in productnumbers) and (len(productnumbers) == 1):
print ' -- Downloading all listed products!'
productnumbers = [i for i in range(1, len(meta) + 1)]
break
else:
productnumbers = [int(i.strip()) for i in
userinput.split(',')]
except Exception:
print '!!! Your input is not valid !!!'
continue
subsettest = set(productnumbers) <= set(
[p + 1 for p in range(0, len(meta))])
if subsettest == True:
break
if subsettest == False:
print '!!! Your input is not valid !!!'
if (len(productnumbers) > 0):
try:
session = requests.Session()
session.auth = (args.user, args.password)
for i in productnumbers:
zf = meta[i - 1]['href']
ofile = args.odir + os.sep + \
os.path.splitext(meta[i - 1]['filename'])[
0] + ".zip"
DownloadFile(args.user, args.password, zf, ofile,
session.auth)
except Exception as e:
print e
if __name__ == '__main__':
main()