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

Lozac'h Loic's avatar
Lozac'h Loic committed
18

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

Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
25
26
logger = py_logging.getLogger("frozenapp.eodags1")

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

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

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

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

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