-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset_downloads.py
328 lines (224 loc) · 9.05 KB
/
dataset_downloads.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
from email.parser import Parser
from lxml import etree
import ConfigParser
import requests
import json
import os
import progressbar
import time
import sys
def listWatersheds():
'''
listWatersheds function contacts GSTORE and returns a list of watersheds.
'''
wIndex = 1
collectionNames = []
collectionIds = []
#Get URL from config file
collection_url = config.get('URLs', 'collectionURL')
rWatersheds = requests.get(collection_url)
rData = rWatersheds.json()
watershedResults = rData['results']
#Get the length of Watershed list
countOfWatersheds = rData['subtotal']
#displays the name of all watersheds
print "\n\nName of watersheds available:\n\n"
for wResult in watershedResults:
print wIndex, ":", wResult['name']
wIndex += 1
collectionNames.append(wResult['name'])
collectionIds.append(wResult['uuid'])
return countOfWatersheds, collectionNames, collectionIds
def getWatershedDetails(userWatershedChoice, wDetails):
'''
getWatershedDetails function returns the name and uid of the selected watershed
'''
nameOfWatershed = wDetails[1][userWatershedChoice - 1]
uidOfWatershed = wDetails[2][userWatershedChoice - 1]
return nameOfWatershed, uidOfWatershed
def listDatasets(nameOfWatershed, uidOfWatershed):
'''
listDatasets function contacts GSTORE and returns a list of datasets for the watershed selected by the user
'''
uid = uidOfWatershed
rIndex = 1
datasetNames = []
datasetIds = []
#Get URL from config file
dataset_url = config.get('URLs', 'datasetURL')
rDatasets = requests.get(dataset_url %uidOfWatershed)
rrData = rDatasets.json()
dataResults = rrData['results']
#Get the length of Dataset list
countOfDatasets = rrData['subtotal']
#displays the name of all datasets
print "\n\nDatasets available for %s: " %nameOfWatershed, "\n\n"
for dResult in dataResults:
print rIndex, ":", dResult['name']
rIndex += 1
datasetNames.append(dResult['name'])
datasetIds.append(dResult['uuid'])
return countOfDatasets, datasetNames, datasetIds
def getDatasetDetails(userDatasetChoice, dDetails):
'''
getDatasetDetails function returns the name and uid of the selected dataset
'''
nameOfDataset = dDetails[1][userDatasetChoice - 1]
uidOfDataset = dDetails[2][userDatasetChoice - 1]
return nameOfDataset, uidOfDataset
def getCapabilities(uidOfDataset):
'''
getCapabilities function returns the coverage name from the GetCapabilities XML response
'''
#Get URL from config file
serviceDes_url = config.get('URLs', 'getCapabilitiesURL')
#Dataset service description
rServiceDes = requests.get(serviceDes_url %uidOfDataset)
serviceDescription_data = rServiceDes.json()
#WCS GetCapabilities request from dataset service description
cap_url = serviceDescription_data['services'][1]['wcs']
rCap = requests.get(cap_url)
with open("capabilities.xml", "wb") as code:
code.write(rCap.content)
tree = etree.parse('capabilities.xml')
#Coverage Name
identifier = tree.find('.//{http://www.opengis.net/wcs/1.1}Identifier')
coverageName = identifier.text
return coverageName
def describeCoverage(uidOfDataset, coverageName):
'''
describeCoverage function returns the Supported format, CRS, BoundingBox coordinates from the DescribeCoverage XML response
'''
bboxValues = []
#Get URL from config file
desCoverage_url = config.get('URLs', 'describeCoverageURL')
#DescribeCoverage request
rDesCoverage = requests.get(desCoverage_url %(uidOfDataset, coverageName))
with open("coverage.xml", "wb") as code:
code.write(rDesCoverage.content)
tree = etree.parse('coverage.xml')
#Supported Format
formats = tree.find('.//{http://www.opengis.net/wcs}formats')
supportedFormat = formats.text
#CRS
crs = tree.find('.//{http://www.opengis.net/wcs}requestResponseCRSs')
CRS = crs.text
#Bounding Box coordinates
envelopeValue = tree.findall('.//{http://www.opengis.net/gml}Envelope')
posValue = envelopeValue[1].findall('{http://www.opengis.net/gml}pos')
boundingBox1 = posValue[0].text
fValues = boundingBox1.split()
for fvalue in fValues:
bboxValues.append(fvalue)
boundingBox2 = posValue[1].text
lValues = boundingBox2.split()
for lvalue in lValues:
bboxValues.append(lvalue)
coordinates = bboxValues[0]+","+ bboxValues[1]+","+ bboxValues[2]+","+ bboxValues[3]
return supportedFormat, coordinates, CRS
def getCoverage(uidOfDataset, supportedFormat, coverageName, coordinates, CRS):
'''
getCoverage function requests for the dataset using the values returned by getCapabilities and describeCoverage functions.
The function returns the content and content type of getCoverage request.
'''
#Get URL from config file
getCoverage_url = config.get('URLs', 'getCoverageURL')
#GetCoverage request
rGetCoverage = requests.get(getCoverage_url %(uidOfDataset, supportedFormat, coverageName, coordinates, CRS, CRS))
c = rGetCoverage.content
content_type = rGetCoverage.headers['content-type']
return c, content_type
def isGeotiff(content_type):
'''
isGeotiff function checks for the geotiff chunk
'''
return content_type.split(';')[0].lower() in 'image/tiff'
def parse_tiff_response(c, content_type):
'''
parse_tiff_response function strips out just the tiff and returns the image
'''
parser = Parser()
parts = parser.parsestr("Content-type:%s\n\n%s" % (content_type, c.rstrip("--wcs--\n\n"))).get_payload()
for p in parts:
try:
if isGeotiff(p.get_content_type()):
return p.get_payload(), p.items()
except:
raise
return None, None
def downloadDataset(tiff, nameOfDataset):
'''
downloadDataset function downloads the datset and stores it in a file.
'''
progress = progressbar.ProgressBar()
directoryName = "Datasets"
if not os.path.exists(directoryName):
os.makedirs(directoryName)
print "\nDownloading ..."
for i in progress(range(50)):
with open(os.path.join(directoryName, nameOfDataset), "w") as f:
f.write(tiff)
time.sleep(0.1)
print "\nDownloading completed\n"
def multipleDatasetSelect(watershedDetails):
'''
multipleDatasetSelect function asks user for more dataset selects
'''
while True:
userMDChoice = raw_input("\nDo you want to download more datasets? (Yes/No):\t")
if userMDChoice == "Yes":
dsteps(watershedDetails)
elif userMDChoice == "No":
multipleWatershedSelect()
else:
print "Invalid Choice"
def multipleWatershedSelect():
'''
multipleWatershedSelect function asks user for more watershed selects
'''
while True:
userMWChoice = raw_input("\nDo you want to select another watershed? (Yes/No):\t")
if userMWChoice == "Yes":
steps()
elif userMWChoice == "No":
print "\n\n"
sys.exit()
else:
print "Invalid Choice"
def steps():
wDetails = listWatersheds()
while True:
try:
userWatershedChoice = raw_input("\n\nSelect an option: ")
userWatershedChoice = int(userWatershedChoice)
if 1 <= userWatershedChoice <= wDetails[0]:
break
else:
print "Invalid option. Please try again..."
except ValueError:
print "No valid integer!Please try again..."
watershedDetails = getWatershedDetails(userWatershedChoice, wDetails)
dsteps(watershedDetails)
def dsteps(watershedDetails):
dDetails = listDatasets(watershedDetails[0], watershedDetails[1])
while True:
try:
userDatasetChoice = raw_input("\n\nSelect an option: ")
userDatasetChoice = int(userDatasetChoice)
if 1 <= userDatasetChoice <= dDetails[0]:
break
else:
print "Invalid option. Please try again."
except ValueError:
print "No valid integer!Please try again..."
datasetDetails = getDatasetDetails(userDatasetChoice, dDetails)
coverageName = getCapabilities(datasetDetails[1])
desCoverage = describeCoverage(datasetDetails[1], coverageName)
getCov = getCoverage(datasetDetails[1], desCoverage[0], coverageName, desCoverage[1], desCoverage[2])
tiff, headers = parse_tiff_response(getCov[0], getCov[1])
downloadDataset(tiff, datasetDetails[0])
multipleDatasetSelect(watershedDetails)
if __name__ == "__main__":
config = ConfigParser.ConfigParser()
config.read('path.cfg')
steps()