-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSDS_earthcache_client.py
511 lines (358 loc) · 13.9 KB
/
SDS_earthcache_client.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
"""
CREDIT ACKNOWLEDGEMENT: some of the code in this file comes from a public
github repository which can be found at: https://github.com/chris010970/earthcache
"""
"""
This class directly interacts with the API to perform a variety of actions.
SDS_earthcache_api.py uses these functions to complete the tasks outlined in this file.
"""
import os
import wget
import uuid
import json
import time
import shutil
import pycurl
import certifi
import tempfile
import pandas as pd
from io import BytesIO
from io import StringIO
from datetime import datetime
class EcClient:
def __init__(self, cfg_path, key, max_cost=0 ):
"""
constructor
"""
# read api key into string
self._api_key = key
print(key)
# dictionary of api uris
self._uris = { 'archive' : 'https://api.skywatch.co/earthcache/archive',
'base' : 'https://api.skywatch.co/earthcache' ,
'pipeline_price': 'https://api.skywatch.co/earthcache/pipelines/calculate'}
# load template json objects from file
self._templates = dict()
for key in [ 'search', 'pipeline', 'pipeline-search' ]:
with open( os.path.join( cfg_path, f'{key}.json' ), ) as f:
self._templates[ key ] = json.load( f )
# copy args
self._max_cost = max_cost
return
# main functions!
# runs a search based on the given area of interest
# https://api-docs.earthcache.com/#tag/post
def processSearch( self, aoi, window, **kwargs ):
"""
process search
"""
# get delay
delay = kwargs.get( 'delay', 2 )
result = None
# post search job
search_id, status, _ = self.postSearch( aoi, window, **kwargs )
if status == 200 and search_id is not None:
# loop until error or search complete
while True:
# get search result
status, result = self.getSearch( search_id )
if status != 202:
break
# delay between get requests
time.sleep( delay )
return status, result, search_id
# allows you to create a pipeline directly from a previously run search
# https://api-docs.earthcache.com/#tag/pipelines/operation/PipelineCreate
def createPipelineFromSearch( self, search_id, search_results, **kwargs ):
"""
create pipeline
"""
def getPayload():
"""
get payload
"""
# configure payload
payload = self._templates[ 'pipeline-search' ]
# get time range
payload[ 'search_id' ] = search_id
payload[ 'search_results' ] = search_results
# assign max cost
payload[ 'max_cost' ] = self._max_cost
# for each template field
for key in list( payload.keys() ):
# replace tenplate values with kwargs
value = kwargs.get( key )
if value is not None:
payload[ key ] = value
return payload
# create request
request = self.initRequest( self._uris[ 'base' ] + '/pipelines' )
# get payload
payload = json.dumps( getPayload() )
# prepare post
request.setopt( pycurl.POST, 1)
request.setopt( pycurl.READDATA, StringIO( payload ) )
request.setopt( pycurl.POSTFIELDSIZE, len( payload ) )
# capture response
response = BytesIO()
request.setopt( pycurl.WRITEFUNCTION, response.write )
# execute request
request.perform()
# return status code and response
return request.getinfo(pycurl.RESPONSE_CODE ), json.loads( response.getvalue() )
# creates the pipeline with the given parameters
def createPipeline( self, name, start_date, end_date, aoi, **kwargs ):
def getPayloadForPipeline():
"""
get payload
"""
# configure payload
payload = self._templates[ 'pipeline' ]
# assign max cost
payload[ 'max_cost' ] = self._max_cost
payload['name'] = name
payload['start_date'] = start_date
payload['end_date'] = end_date
payload['aoi'] = aoi
# for each template field
for key in list( payload.keys() ):
# replace tenplate values with kwargs
value = kwargs.get( key )
if value is not None:
payload[ key ] = value
return payload
# create request
request = self.initRequest( self._uris[ 'base' ] + '/pipelines' )
# get payload
payload = json.dumps( getPayloadForPipeline() )
# prepare post
request.setopt( pycurl.POST, 1)
request.setopt( pycurl.READDATA, StringIO( payload ) )
request.setopt( pycurl.POSTFIELDSIZE, len( payload ) )
# capture response
response = BytesIO()
request.setopt( pycurl.WRITEFUNCTION, response.write )
# execute request
request.perform()
# return status code and response
return request.getinfo(pycurl.RESPONSE_CODE ), json.loads( response.getvalue() )
# still needs to be tested!
# Calculate cost of area and intervals of a pipeline,
# and the probability of collection of any tasking intervals
# https://api-docs.earthcache.com/#tag/pipelinePost
def calculatePrice(self, resolution, location, start_date, end_date):
"""
post search
"""
parameters = {'resolution': resolution,
'location': location,
'start_date': start_date,
'end_date': end_date
}
# get request
request = self.initRequest( self._uris['pipeline_price'])
# get payload
payload = json.dumps(parameters)
# prepare post
request.setopt( pycurl.POST, 1)
request.setopt( pycurl.READDATA, StringIO( payload ) )
request.setopt( pycurl.POSTFIELDSIZE, len( payload ) )
# capture response
response = BytesIO()
request.setopt( pycurl.WRITEFUNCTION, response.write )
# execute request
request.perform()
# get status
status = request.getinfo(pycurl.RESPONSE_CODE )
# return status code and response
return status, json.loads(response.getvalue())
# helper functions!
def getSearch( self, search_id ):
"""
get search
"""
# execute get request
return self.sendRequest( self._uris[ 'archive' ] + f'/search/{search_id}/search_results' )
def getPipelines( self ):
"""
get pipelines
"""
# run get request
return self.sendRequest( self._uris[ 'base' ] + '/pipelines' )
def getPipeline( self, pipeline_id ):
"""
get pipeline associated with id
"""
# run get request
return self.sendRequest( self._uris[ 'base' ] + f'/pipelines/{pipeline_id}' )
def getPipelineIdFromName( self, name ):
"""
get pipeline associated with id
"""
pipeline_id = None
# run get request
status, result = self.sendRequest( self._uris[ 'base' ] + f'/pipelines' )
if status == 200:
# parse into dataframe
df = pd.DataFrame( result[ 'data'] )
df = df[ df['name'] == name ]
# get id from row
if len( df == 1 ):
pipeline_id = df[ 'id' ].iloc[ 0 ]
return pipeline_id
def deletePipeline( self, pipeline_id ):
"""
delete pipeline
"""
# run custom delete request
return self.sendRequest( self._uris[ 'base' ] + f'/pipelines/{pipeline_id}', action='DELETE' )
return request.getinfo(pycurl.RESPONSE_CODE ), json.loads( response.getvalue() )
def postSearch( self, aoi, window, **kwargs ):
"""
post search
"""
def getPayload():
"""
get payload
"""
# configure payload
payload = self._templates[ 'search' ]
payload[ 'location' ] = aoi
# get time range
payload[ 'start_date' ] = window[ 'start_date' ]
payload[ 'end_date' ] = window[ 'end_date' ]
# for each template field
for key in payload.keys():
# replace tenplate values with kwargs
value = kwargs.get( key )
if value is not None:
payload[ key ] = value
return payload
# get request
search_id = None
request = self.initRequest( self._uris[ 'archive' ] + '/search' )
# get payload
payload = json.dumps( getPayload() )
# prepare post
request.setopt( pycurl.POST, 1)
request.setopt( pycurl.READDATA, StringIO( payload ) )
request.setopt( pycurl.POSTFIELDSIZE, len( payload ) )
# capture response
response = BytesIO()
request.setopt( pycurl.WRITEFUNCTION, response.write )
# execute request
request.perform()
# get status
status = request.getinfo(pycurl.RESPONSE_CODE )
if status == 200:
# parse response for search id
obj = json.loads( response.getvalue() )
if 'data' in obj:
search_id = obj[ 'data' ][ 'id' ]
# return status code and response
return search_id, status, json.loads( response.getvalue() )
def getIntervalResults( self, pipeline_id ):
"""
get interval results
"""
# run get request
return self.sendRequest( self._uris[ 'base' ] + f'/pipelines/{pipeline_id}/interval_results' )
def getImages( self, results, out_path ):
"""
get request
"""
def getDateTimePath( metafile ):
"""
get datetime path
"""
with open( metafile ) as f:
data = json.load( f )
dt = datetime.strptime( data[ 'ProductInfo' ][ 'PRODUCT_SCENE_RASTER_START_TIME' ], '%d-%b-%Y %H:%M:%S.%f')
return dt.strftime( '%Y%m%d_%H%M%S' )
images = []
# convert to dataframe if required
if not isinstance( results, pd.DataFrame ):
results = pd.DataFrame( results )
for row in results.itertuples():
# download metadata file
with tempfile.TemporaryDirectory() as tmpdir:
print ( '... downloading {url}'.format( url=row.metadata_url ) )
metafile = wget.download( row.metadata_url, out=tmpdir )
# determine datetime path from matadata
path = os.path.join( out_path, getDateTimePath( metafile ) )
if not os.path.exists( path ):
os.makedirs( path )
# move metadata file to out_path if not exists
pathname = os.path.join( path, os.path.basename( row.metadata_url ) )
if not os.path.exists( pathname ):
shutil.move( metafile, path )
# download scientific dataset to out_path datetime folder
pathname = os.path.join( path, os.path.basename( row.analytics_url ) )
if not os.path.exists( pathname ):
print ( '... downloading {url}'.format( url=row.analytics_url ) )
images.append( wget.download( row.analytics_url, out=path ) )
return images
def getOutputs( self ):
"""
get request
"""
# run get request
return self.sendRequest( self._uris[ 'base' ] + f'/outputs' )
def getOutputIdFromName( self, name ):
"""
get request
"""
output_id = None
# run get request
status, result = self.sendRequest( self._uris[ 'base' ] + f'/outputs' )
if status == 200:
# parse into dataframe
df = pd.DataFrame( result[ 'data'] )
df = df[ df['name'] == name ]
# get id from row
if len( df == 1 ):
output_id = df[ 'id' ].iloc[ 0 ]
return output_id
def getOutput( self, output_id ):
"""
get request
"""
# run get request
return self.sendRequest( self._uris[ 'base' ] + f'/outputs/{output_id}' )
def initRequest( self, uri ):
"""
get request
"""
# setup curl object - add ssl certification
request = pycurl.Curl()
request.setopt( pycurl.CAINFO, certifi.where() )
# add uri + header
request.setopt( pycurl.URL, uri )
request.setopt( pycurl.HTTPHEADER, self.getHeaderParams() )
return request
def sendRequest( self, uri, action='GET', status_ok=[ 200 ] ):
"""
get request
"""
# create request
request = self.initRequest( uri )
# configure request type
if action == 'GET':
request.setopt( pycurl.HTTPGET, 1)
else:
request.setopt( pycurl.CUSTOMREQUEST, action )
# capture response to request
response = BytesIO()
request.setopt( pycurl.WRITEFUNCTION, response.write )
# execute request
request.perform()
# return status and response
return request.getinfo(pycurl.RESPONSE_CODE), json.loads( response.getvalue() )
def getHeaderParams( self ):
"""
get header parameters + values
"""
# return header attributes
return [ 'Accept: application/json',
'Content-Type: application/json',
'x-api-key: {key}'.format( key=self._api_key ) ]