eodags1.py 13.6 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
test    
Lozac'h Loic committed
43
        setup_logging(verbose=2,no_progress_bar=False)
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
        mpolywkt= str(qs_tile[0].wgs84.ewkt).split(";")
Lozac'h Loic's avatar
Lozac'h Loic committed
58
59
        print(mpolywkt[1])
        
Lozac'h Loic's avatar
Lozac'h Loic committed
60
61
        product_types = ['S1_SAR_GRD','S2_MSI_L2A','S2_MSI_L3A_WASP']
        
Lozac'h Loic's avatar
eodag1    
Lozac'h Loic committed
62
        products_availability={}
Lozac'h Loic's avatar
Lozac'h Loic committed
63
        if prodtypenum in [0,1]:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
64
            logger.info("Search on Scihub...")
Lozac'h Loic's avatar
Lozac'h Loic committed
65
66
67
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,
                    geom=mpolywkt[1]
                )
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
75
            logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
76
77
                    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
78
            logger.info("Search on Peps...")
Lozac'h Loic's avatar
Lozac'h Loic committed
79
80
81
            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
82
                    productType=product_types[prodtypenum],
Lozac'h Loic's avatar
Lozac'h Loic committed
83
84
85
86
87
                    start=startdate,
                    end=enddate,
                    geom=mpolywkt[1]
                )
            
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
88
            logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
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
                    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
117
                        nbsci_online += 1
Lozac'h Loic's avatar
Lozac'h Loic committed
118
119
120
121
122
123
124
            
            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
125
                        nbpeps_online += 1
Lozac'h Loic's avatar
Lozac'h Loic committed
126
            
Lozac'h Loic's avatar
test    
Lozac'h Loic committed
127
128
            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
129
130
            
        elif prodtypenum == 2:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
131
            logger.info("Search on Theia...")
Lozac'h Loic's avatar
Lozac'h Loic committed
132
133
134
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,
                    geom=mpolywkt[1]
                )
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
141
            logger.info(
Lozac'h Loic's avatar
Lozac'h Loic committed
142
143
144
145
146
147
148
149
                    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
150
            logger.info(
Lozac'h Loic's avatar
test    
Lozac'h Loic committed
151
                    f"THIEA has got {nbtheia_online} ONLINE products over {estimated_theia_of_results}"
Lozac'h Loic's avatar
Lozac'h Loic committed
152
153
154
                )
            
        else:
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
155
            logger.error("error")
Lozac'h Loic's avatar
Lozac'h Loic committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
            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
179
            logger.info(f"Serializing downloaded products to {serialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
180
181
            dps = SearchResult(downloadedprods)
            self.mEODataAccessGateway.serialize(dps, serialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
182
183
            
            if len(altdownloadedprods) > 0 :
Lozac'h Loic's avatar
test    
Lozac'h Loic committed
184
                logger.info(f"Serializing alternate products to {altserialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
185
                adps = SearchResult(altdownloadedprods)
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
186
                self.mEODataAccessGateway.serialize(adps, altserialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
187
188
189
190
191
192
193
194
195
196
        
        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
197
            logger.info(f"Serializing downloaded products to {remainserialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
198
199
            rps = SearchResult(remainingprods)
            self.mEODataAccessGateway.serialize(rps, remainserialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
200
201
            
            if len(altremainingprods) > 0 :
Lozac'h Loic's avatar
test    
Lozac'h Loic committed
202
                logger.info(f"Serializing alternate products to {altremainserialfile}")
Lozac'h Loic's avatar
debug    
Lozac'h Loic committed
203
204
                arps = SearchResult(altremainingprods)
                self.mEODataAccessGateway.serialize(arps, altremainserialfile)
Lozac'h Loic's avatar
Lozac'h Loic committed
205
206
207
208

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

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