eodags1.py 13.1 KB
Newer Older
Lozac'h Loic's avatar
Lozac'h Loic committed
1
2
3
4
5
6
7
8
9
'''
Created on 18 juin 2021

@author: loic
'''
import os
from eodag.utils.logging import setup_logging
from eodag.api.core import EODataAccessGateway
from frozenapp.models import TileEnvelope
Lozac'h Loic's avatar
Lozac'h Loic committed
10
11
12
13
from django.contrib.gis.db.models.functions import Transform
from eodag.utils import ProgressCallback
from contextlib import closing
from io import StringIO
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
14
15
from datetime import datetime, timedelta
import time
Lozac'h Loic's avatar
Lozac'h Loic committed
16

Lozac'h Loic's avatar
Lozac'h Loic committed
17
18
19
20
21
# os.environ["EODAG__PEPS__AUTH__CREDENTIALS__USERNAME"] = "loic.lozach"
# os.environ["EODAG__PEPS__AUTH__CREDENTIALS__PASSWORD"] = "PMUQc22$"
# os.environ["EODAG__SCIHUB__AUTH__CREDENTIALS__USERNAME"] = "loic.lozach"
# os.environ["EODAG__SCIHUB__AUTH__CREDENTIALS__PASSWORD"] = "PMUQc22$"
CONFIG_SCIHUB_ENDPOINT="https://apihub.copernicus.eu/apihub/"
Lozac'h Loic's avatar
Lozac'h Loic committed
22

Lozac'h Loic's avatar
Lozac'h Loic committed
23
class EodagS1():
Lozac'h Loic's avatar
Lozac'h Loic committed
24
25
26
27
28
29
30
    '''
    classdocs
    '''
    
    mEODataAccessGateway = None
    user_conf_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),"eodag/user_conf.yml")
    locations_conf_path = None
Lozac'h Loic's avatar
Lozac'h Loic committed
31
#     providers_conf_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),"eodag/providers.yml")
Lozac'h Loic's avatar
Lozac'h Loic committed
32
33
    products_downloaded = {}
    products_availability = {}
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
34
    
Lozac'h Loic's avatar
Lozac'h Loic committed
35
    def __init__(self):
Lozac'h Loic's avatar
Lozac'h Loic committed
36
37
38
        '''
        Constructor
        '''
Lozac'h Loic's avatar
Lozac'h Loic committed
39
        self.mEODataAccessGateway = EODataAccessGateway(user_conf_file_path=self.user_conf_file_path)
Lozac'h Loic's avatar
Lozac'h Loic committed
40
        setup_logging(verbose=3)
Lozac'h Loic's avatar
Lozac'h Loic committed
41
42
43
44
        print("")

    def search_and_download(self, prodtypenum, mrgstile, startdate, enddate, downdir):

Lozac'h Loic's avatar
Lozac'h Loic committed
45
        qs_tile =  TileEnvelope.objects.annotate(wgs84=Transform('geom',4326)).filter(tile__exact=mrgstile
Lozac'h Loic's avatar
Lozac'h Loic committed
46
47
48
49
                                                  )
        if len(qs_tile) != 1 :
            print("Can't find tile "+mrgstile)
            exit()
Lozac'h Loic's avatar
Lozac'h Loic committed
50
51
52
            
#         geomwgs84 = Transform(qs_tile[0].geom, 4326)
        print(qs_tile[0].wgs84)
Lozac'h Loic's avatar
Lozac'h Loic committed
53
        
Lozac'h Loic's avatar
Lozac'h Loic committed
54
        mpolywkt= str(qs_tile[0].wgs84.ewkt).split(";")
Lozac'h Loic's avatar
Lozac'h Loic committed
55
56
        print(mpolywkt[1])
        
Lozac'h Loic's avatar
Lozac'h Loic committed
57
58
        product_types = ['S1_SAR_GRD','S2_MSI_L2A','S2_MSI_L3A_WASP']
        
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
59
        products_availability={}
Lozac'h Loic's avatar
Lozac'h Loic committed
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
        if prodtypenum in [0,1]:
            print("Search on Scihub...")
            self.mEODataAccessGateway.set_preferred_provider("scihub")
            
            
            products_scihub, estimated_scihub_of_results = self.mEODataAccessGateway.search(
                    productType=product_types[prodtypenum],
                    start=startdate,
                    end=enddate,
                    geom=mpolywkt[1]
                )
            
            print(
                    f"The Scihub search has found an estimated number of {estimated_scihub_of_results} products matching your criteria "
                )
            print("Search on Peps...")
            self.mEODataAccessGateway.set_preferred_provider("peps")
            
            products_peps, estimated_peps_of_results = self.mEODataAccessGateway.search(
                    productType=product_type,
                    start=startdate,
                    end=enddate,
                    geom=mpolywkt[1]
                )
            
            print(
                    f"The PEPS search has found an estimated number of {estimated_peps_of_results} products matching your criteria "
                )
            
            nbsci_online=0
            nbpeps_online=0
            
            for ps in products_scihub :
                found=False
                for pp in products_peps :
                    if pp.properties["id"] == ps.properties["id"]:
                        if ps.properties["storageStatus"] == "ONLINE" and pp.properties["storageStatus"] == "ONLINE":
                            products_availability[ps.properties["id"]] = [ps,pp]
                            nbsci_online += 1
                            nbpeps_online += 1
                        elif ps.properties["storageStatus"] == "ONLINE" and pp.properties["storageStatus"] == "OFFLINE":
                            products_availability[ps.properties["id"]] = [ps,pp]
                            nbsci_online += 1
                        elif ps.properties["storageStatus"] == "OFFLINE" and pp.properties["storageStatus"] == "ONLINE":
                            products_availability[ps.properties["id"]] = [pp,ps]
                            nbpeps_online += 1
                        elif ps.properties["storageStatus"] == "OFFLINE" and pp.properties["storageStatus"] == "OFFLINE":
                            products_availability[ps.properties["id"]] = [ps,pp]
                            
                        found=True
                        break
                if found == False:
                    products_availability[ps.properties["id"]] = [ps]
                    if ps.properties["storageStatus"] == "ONLINE":
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
114
                        nbsci_online += 1
Lozac'h Loic's avatar
Lozac'h Loic committed
115
116
117
118
119
120
121
            
            for pp in products_peps :
                found=False
                
                if not pp.properties["id"] in products_availability.keys():
                    products_availability[pp.properties["id"]] = [pp]
                    if pp.properties["storageStatus"] == "ONLINE":
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
122
                        nbpeps_online += 1
Lozac'h Loic's avatar
Lozac'h Loic committed
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
            
            print(
                    f"\nScihub has got {nbsci_online} ONLINE products over {estimated_scihub_of_results}"
                    f"\nPEPS has got {nbpeps_online} ONLINE products over {estimated_peps_of_results}"
                )
            
        elif prodtypenum == 2:
            print("Search on Theia...")
            self.mEODataAccessGateway.set_preferred_provider("theia")
            
            
            products_theia, estimated_theia_of_results = self.mEODataAccessGateway.search(
                    productType=product_types[prodtypenum],
                    start=startdate,
                    end=enddate,
                    geom=mpolywkt[1]
                )
            print(
                    f"The THEIA search has found an estimated number of {estimated_theia_of_results} products matching your criteria "
                )
            nbtheia_online=0
            for pt in products_theia :
                products_availability[pt.properties["id"]] = [pt]
                if pt.properties["storageStatus"] == "ONLINE":
                        nbtheia_online += 1
            
            print(
                    f"\nTHIEA has got {nbtheia_online} ONLINE products over {estimated_theia_of_results}"
                )
            
        else:
            print("error")
            return
        
        self.products_availability = products_availability
        
        self.start_downloads(downdir)
        

    def __export_geojson(self,downdir, remain):
        nowstr = datetime.now().strftime("%Y%m%dT%H%M%S")
        serialfile = os.path.join(downdir,nowstr+"_DownloadedProducts.geojson")
        altserialfile = os.path.join(downdir,nowstr+"_AlternateProducts.geojson")
        remainserialfile = os.path.join(downdir,nowstr+"_RemainingProducts.geojson")
        altremainserialfile = os.path.join(downdir,nowstr+"_AlternateRemainingProducts.geojson")
        
        if len(self.products_downloaded) > 0 :

            downloadedprods = []
            altdownloadedprods = []
            for d in self.products_downloaded.keys() :
                downloadedprods.append(self.products_downloaded[d][0])
                if len(self.products_downloaded[d]) == 2 :
                    altdownloadedprods.append(self.products_downloaded[d][1])
            
            print(f"\nSerializing downloaded products to {serialfile}")
            self.mEODataAccessGateway.serialize(downloadedprods, serialfile)
            
            if len(altdownloadedprods) > 0 :
                print(f"\nSerializing alternate products to {altserialfile}")
                self.mEODataAccessGateway.serialize(altdownloadedprods, altserialfile)
        
        if remain == 1 :
            
            remainingprods = []
            altremainingprods = []
            for d in self.products_availability.keys() :
                remainingprods.append(self.products_availability[d][0])
                if len(self.products_availability[d]) == 2 :
                    altremainingprods.append(self.products_availability[d][1])
            
            print(f"\nSerializing downloaded products to {remainserialfile}")
            self.mEODataAccessGateway.serialize(remainingprods, remainserialfile)
            
            if len(altremainingprods) > 0 :
                print(f"\nSerializing alternate products to {altremainserialfile}")
                self.mEODataAccessGateway.serialize(altremainingprods, altremainserialfile)

            
        
        
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
204

Lozac'h Loic's avatar
Lozac'h Loic committed
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
    def import_geojson(self,products_geojson,alternate_products_geojson=None):
        
        self.products_availability = {}
        deserialized_products = self.mEODataAccessGateway.deserialize(products_geojson)
        
        for pt in deserialized_products :
            self.products_availability[pt.properties["id"]] = [pt]
        
        if not alternate_products_geojson == None :
            deserialized_alt_products = self.mEODataAccessGateway.deserialize(alternate_products_geojson)
            for pp in deserialized_alt_products :
                if pp.properties["id"] in self.products_availability.keys():
                    self.products_availability[pp.properties["id"]].append(pp)
                else:
                    self.products_availability[pp.properties["id"]] = [pp]
                    
        print("Geojson files successfully imported")
        print("Use start_downloads() to launch downloads")
    
    
    def start_downloads(self,downdir):
        
        if not os.path.exists(downdir):
            os.mkdir(downdir)
        
        self.products_downloaded={}
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
231
232
        passwait=[10,30,60,120,300]
        still2download = True
Lozac'h Loic's avatar
Lozac'h Loic committed
233
        nbProducts2d = len(self.products_availability)
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
234
        nb_allretry = 0
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
235
        
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
236
        while still2download:
Lozac'h Loic's avatar
Lozac'h Loic committed
237
238
            for p in sorted(self.products_availability, key=lambda k: len(self.products_availability[k]), reverse=True):
                firstprovider = self.products_availability[p][0].provider
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
239
240
241
242
243
244
                print(f"\nStarting Download {p} from {firstprovider}...")
                self.mEODataAccessGateway.set_preferred_provider(firstprovider)
                failed=False
                try:
                    with closing(StringIO()) as tqdm_out:
                        with ProgressCallback(file=tqdm_out) as bar:
Lozac'h Loic's avatar
Lozac'h Loic committed
245
                            self.mEODataAccessGateway.download(self.products_availability[p][0], bar, extract=False, outputs_prefix=downdir)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
246
247
248
                except Exception as err:
                    failed=True
                    print(err)
Lozac'h Loic's avatar
Lozac'h Loic committed
249
250
251
                    
                if not failed and self.products_availability[p][0].location[-3:] != "zip":
                    failed=True
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
252
             
Lozac'h Loic's avatar
Lozac'h Loic committed
253
254
                if failed and len(self.products_availability[p]) == 2:
                    secndprovider = self.products_availability[p][1].provider
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
255
                    failed=False
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
256
                    print(f"\nDownload failed. Trying with {secndprovider}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
257
258
259
260
                    self.mEODataAccessGateway.set_preferred_provider(secndprovider)
                    try:
                        with closing(StringIO()) as tqdm_out:
                            with ProgressCallback(file=tqdm_out) as bar:
Lozac'h Loic's avatar
Lozac'h Loic committed
261
                                self.mEODataAccessGateway.download(self.products_availability[p][1], bar, extract=False, outputs_prefix=downdir)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
262
263
264
                    except Exception as err:
                        failed=True
                        print(err)
Lozac'h Loic's avatar
Lozac'h Loic committed
265
266
                        
                    self.products_availability[p].pop(0)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
267
268
   
         
Lozac'h Loic's avatar
Lozac'h Loic committed
269
270
                if self.products_availability[p][0].location[:5] == "file:":
                    self.products_downloaded[p] = self.products_availability[p]
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
271
         
Lozac'h Loic's avatar
Lozac'h Loic committed
272
273
274
275
            for p in self.products_downloaded.keys():
                if p in self.products_availability.keys():
                    self.products_availability.pop(p)
                    
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
276
277
            nb_allretry += 1
             
Lozac'h Loic's avatar
Lozac'h Loic committed
278
            if len(self.products_downloaded) == nbProducts2d :
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
279
280
281
282
                still2download = False
                print(
                    f"\nAll downloads successful."
                    )
Lozac'h Loic's avatar
Lozac'h Loic committed
283
284
285
286
                self.__export_geojson(downdir, 0)
                
                print("Done.")
                
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
287
288
289
            elif nb_allretry == 5 :
                still2download = False
                print(
Lozac'h Loic's avatar
Lozac'h Loic committed
290
291
292
293
294
                    """
                    Max number of retries has been completed.
                    There is still products to download.
                    Use import_geoson() with _RemainingProducts.geojson file to restart downloads.
                    """
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
295
                    )
Lozac'h Loic's avatar
Lozac'h Loic committed
296
297
298
                self.__export_geojson(downdir, 1)
                
                print("Done.")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
299
            else:
Lozac'h Loic's avatar
Lozac'h Loic committed
300
                print(f"\nPass n#{nb_allretry} has reached {len(self.products_downloaded)} over {nbProducts2d} expected")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
301
302
303
304
305
306
                print(f"\nWaiting {passwait[nb_allretry-1]} minutes before retrying...")
                restartd = datetime.now()+timedelta(minutes=passwait[nb_allretry-1])
                restartstr = restartd.strftime("%Y/%m/%d-%H:%M:%S")
                print(f"\nRestart at {restartstr}")
                time.sleep(passwait[nb_allretry-1]*60)
             
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
307
308
309