eodags1.py 13.8 KB
Newer Older
Lozac'h Loic's avatar
Lozac'h Loic committed
1
2
3
4
5
'''
Created on 18 juin 2021

@author: loic
'''
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
6
import os, time, logging
Lozac'h Loic's avatar
Lozac'h Loic committed
7
8
from eodag.utils.logging import setup_logging
from eodag.api.core import EODataAccessGateway
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
9
from eodag.api.search_result import SearchResult
Lozac'h Loic's avatar
Lozac'h Loic committed
10
from frozenapp.models import TileEnvelope
Lozac'h Loic's avatar
Lozac'h Loic committed
11
12
13
14
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
15
from datetime import datetime, timedelta
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
16

Lozac'h Loic's avatar
Lozac'h Loic committed
17

Lozac'h Loic's avatar
Lozac'h Loic committed
18
19
20
21
22
# 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
23

Lozac'h Loic's avatar
Lozac'h Loic committed
24
class EodagS1():
Lozac'h Loic's avatar
Lozac'h Loic committed
25
26
27
    '''
    classdocs
    '''
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
28
    logger=None
Lozac'h Loic's avatar
Lozac'h Loic committed
29
30
31
    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
32
#     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
33
34
    products_downloaded = {}
    products_availability = {}
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
35
    
Lozac'h Loic's avatar
Lozac'h Loic committed
36
    def __init__(self):
Lozac'h Loic's avatar
Lozac'h Loic committed
37
38
39
        '''
        Constructor
        '''
Lozac'h Loic's avatar
Lozac'h Loic committed
40
        self.mEODataAccessGateway = EODataAccessGateway(user_conf_file_path=self.user_conf_file_path)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
41
        setup_logging(verbose=3,no_progress_bar=True)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
42
43
        self.logger = logging.getLogger(__name__)
        self.logger.info("EODataAccessGateway initialized.")
Lozac'h Loic's avatar
Lozac'h Loic committed
44
45
46

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

Lozac'h Loic's avatar
Lozac'h Loic committed
47
        qs_tile =  TileEnvelope.objects.annotate(wgs84=Transform('geom',4326)).filter(tile__exact=mrgstile
Lozac'h Loic's avatar
Lozac'h Loic committed
48
49
                                                  )
        if len(qs_tile) != 1 :
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
50
            self.logger.info("Can't find tile "+mrgstile)
Lozac'h Loic's avatar
Lozac'h Loic committed
51
            exit()
Lozac'h Loic's avatar
Lozac'h Loic committed
52
53
            
#         geomwgs84 = Transform(qs_tile[0].geom, 4326)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
54
        self.logger.info(qs_tile[0].wgs84)
Lozac'h Loic's avatar
Lozac'h Loic committed
55
        
Lozac'h Loic's avatar
Lozac'h Loic committed
56
        mpolywkt= str(qs_tile[0].wgs84.ewkt).split(";")
Lozac'h Loic's avatar
Lozac'h Loic committed
57
58
        print(mpolywkt[1])
        
Lozac'h Loic's avatar
Lozac'h Loic committed
59
60
        product_types = ['S1_SAR_GRD','S2_MSI_L2A','S2_MSI_L3A_WASP']
        
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
61
        products_availability={}
Lozac'h Loic's avatar
Lozac'h Loic committed
62
        if prodtypenum in [0,1]:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
63
            self.logger.info("Search on Scihub...")
Lozac'h Loic's avatar
Lozac'h Loic committed
64
65
66
67
68
69
70
71
72
73
            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]
                )
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
74
            self.logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
75
76
                    f"The Scihub search has found an estimated number of {estimated_scihub_of_results} products matching your criteria "
                )
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
77
            self.logger.info("Search on Peps...")
Lozac'h Loic's avatar
Lozac'h Loic committed
78
79
80
            self.mEODataAccessGateway.set_preferred_provider("peps")
            
            products_peps, estimated_peps_of_results = self.mEODataAccessGateway.search(
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
81
                    productType=product_types[prodtypenum],
Lozac'h Loic's avatar
Lozac'h Loic committed
82
83
84
85
86
                    start=startdate,
                    end=enddate,
                    geom=mpolywkt[1]
                )
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
87
            self.logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
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
                    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
116
                        nbsci_online += 1
Lozac'h Loic's avatar
Lozac'h Loic committed
117
118
119
120
121
122
123
            
            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
124
                        nbpeps_online += 1
Lozac'h Loic's avatar
Lozac'h Loic committed
125
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
126
            self.logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
127
128
129
130
131
                    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:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
132
            self.logger.info("Search on Theia...")
Lozac'h Loic's avatar
Lozac'h Loic committed
133
134
135
136
137
138
139
140
141
            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]
                )
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
142
            self.logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
143
144
145
146
147
148
149
150
                    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
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
151
            self.logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
152
153
154
155
                    f"\nTHIEA has got {nbtheia_online} ONLINE products over {estimated_theia_of_results}"
                )
            
        else:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
156
            self.logger.error("error")
Lozac'h Loic's avatar
Lozac'h Loic committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
            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])
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
180
            self.logger.info(f"\nSerializing downloaded products to {serialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
181
182
            dps = SearchResult(downloadedprods)
            self.mEODataAccessGateway.serialize(dps, serialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
183
184
            
            if len(altdownloadedprods) > 0 :
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
185
                self.logger.info(f"\nSerializing alternate products to {altserialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
186
                adps = SearchResult(altdownloadedprods)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
187
                self.mEODataAccessGateway.serialize(adps, altserialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
188
189
190
191
192
193
194
195
196
197
        
        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])
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
198
            self.logger.info(f"\nSerializing downloaded products to {remainserialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
199
200
            rps = SearchResult(remainingprods)
            self.mEODataAccessGateway.serialize(rps, remainserialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
201
202
            
            if len(altremainingprods) > 0 :
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
203
                self.logger.info(f"\nSerializing alternate products to {altremainserialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
204
205
                arps = SearchResult(altremainingprods)
                self.mEODataAccessGateway.serialize(arps, altremainserialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
206
207
208
209

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

Lozac'h Loic's avatar
Lozac'h Loic committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    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]
                    
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
227
228
        self.logger.info("Geojson files successfully imported")
        self.logger.info("Use start_downloads() to launch downloads")
Lozac'h Loic's avatar
Lozac'h Loic committed
229
230
231
232
233
234
235
236
    
    
    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
237
238
        passwait=[10,30,60,120,300]
        still2download = True
Lozac'h Loic's avatar
Lozac'h Loic committed
239
        nbProducts2d = len(self.products_availability)
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
240
        nb_allretry = 0
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
241
        
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
242
        while still2download:
Lozac'h Loic's avatar
Lozac'h Loic committed
243
244
            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
245
                self.logger.info(f"\nStarting Download {p} from {firstprovider}...")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
246
247
248
249
250
                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
debug    
Lozac'h Loic committed
251
                            self.mEODataAccessGateway.download(self.products_availability[p][0], bar, extract=False, outputs_prefix=downdir, timeout=1)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
252
253
254
                except Exception as err:
                    failed=True
                    print(err)
Lozac'h Loic's avatar
Lozac'h Loic committed
255
256
257
                    
                if not failed and self.products_availability[p][0].location[-3:] != "zip":
                    failed=True
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
258
             
Lozac'h Loic's avatar
Lozac'h Loic committed
259
260
                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
261
                    failed=False
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
262
                    self.logger.info(f"\nDownload failed. Trying with {secndprovider}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
263
264
265
266
                    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
debug    
Lozac'h Loic committed
267
                                self.mEODataAccessGateway.download(self.products_availability[p][1], bar, extract=False, outputs_prefix=downdir, timeout=1)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
268
269
270
                    except Exception as err:
                        failed=True
                        print(err)
Lozac'h Loic's avatar
Lozac'h Loic committed
271
272
                        
                    self.products_availability[p].pop(0)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
273
274
   
         
Lozac'h Loic's avatar
Lozac'h Loic committed
275
276
                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
277
         
Lozac'h Loic's avatar
Lozac'h Loic committed
278
279
280
281
            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
282
283
            nb_allretry += 1
             
Lozac'h Loic's avatar
Lozac'h Loic committed
284
            if len(self.products_downloaded) == nbProducts2d :
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
285
                still2download = False
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
286
                self.logger.info(
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
287
288
                    f"\nAll downloads successful."
                    )
Lozac'h Loic's avatar
Lozac'h Loic committed
289
290
291
292
                self.__export_geojson(downdir, 0)
                
                print("Done.")
                
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
293
294
            elif nb_allretry == 5 :
                still2download = False
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
295
                self.logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
296
297
298
299
300
                    """
                    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
301
                    )
Lozac'h Loic's avatar
Lozac'h Loic committed
302
303
                self.__export_geojson(downdir, 1)
                
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
304
                self.logger.info("Done.")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
305
            else:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
306
307
                self.logger.info(f"\nPass n#{nb_allretry} has reached {len(self.products_downloaded)} over {nbProducts2d} expected")
                self.logger.info(f"\nWaiting {passwait[nb_allretry-1]} minutes before retrying...")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
308
309
                restartd = datetime.now()+timedelta(minutes=passwait[nb_allretry-1])
                restartstr = restartd.strftime("%Y/%m/%d-%H:%M:%S")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
310
                self.logger.info(f"\nRestart at {restartstr}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
311
312
                time.sleep(passwait[nb_allretry-1]*60)
             
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
313
314
315