|
| 1 | +"""This module provides helper functions for Copernicus Dataspace API.""" |
| 2 | + |
| 3 | +import getpass |
| 4 | +import logging |
| 5 | +from pathlib import Path |
| 6 | +from datetime import datetime as dt |
| 7 | + |
| 8 | +import requests |
| 9 | +from shapely.wkt import loads |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | +def ask_credentials(): |
| 14 | + """Interactive function to ask for Copernicus credentials.""" |
| 15 | + print( |
| 16 | + "If you do not have a Copernicus dataspace user account" |
| 17 | + " go to: https://dataspace.copernicus.eu/ and register" |
| 18 | + ) |
| 19 | + uname = input("Your Copernicus Dataspace Username:") |
| 20 | + pword = getpass.getpass("Your Copernicus Dataspace Password:") |
| 21 | + |
| 22 | + return uname, pword |
| 23 | + |
| 24 | + |
| 25 | +def get_access_token(username, password: None): |
| 26 | + |
| 27 | + if not password: |
| 28 | + logger.info(' Please provide your Copernicus Dataspace password:') |
| 29 | + password = getpass.getpass() |
| 30 | + |
| 31 | + data = { |
| 32 | + "client_id": "cdse-public", |
| 33 | + "username": username, |
| 34 | + "password": password, |
| 35 | + "grant_type": "password", |
| 36 | + } |
| 37 | + try: |
| 38 | + r = requests.post( |
| 39 | + "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token", |
| 40 | + data=data, |
| 41 | + ) |
| 42 | + r.raise_for_status() |
| 43 | + except Exception as e: |
| 44 | + raise Exception( |
| 45 | + f"Access token creation failed. Reponse from the server was: {r.json()}" |
| 46 | + ) |
| 47 | + return r.json()["access_token"] |
| 48 | + |
| 49 | + |
| 50 | +def refresh_access_token(refresh_token: str) -> str: |
| 51 | + data = { |
| 52 | + "client_id": "cdse-public", |
| 53 | + "refresh_token": refresh_token, |
| 54 | + "grant_type": "refresh_token", |
| 55 | + } |
| 56 | + |
| 57 | + try: |
| 58 | + r = requests.post( |
| 59 | + "https://identity.dataspace.copernicus.eu/auth/realms/CDSE/protocol/openid-connect/token", |
| 60 | + data=data, |
| 61 | + ) |
| 62 | + r.raise_for_status() |
| 63 | + except Exception as e: |
| 64 | + raise Exception( |
| 65 | + f"Access token refresh failed. Reponse from the server was: {r.json()}" |
| 66 | + ) |
| 67 | + |
| 68 | + return r.json()["access_token"] |
| 69 | + |
| 70 | + |
| 71 | +def create_aoi_str(aoi): |
| 72 | + """Convert WKT formatted AOI to dataspace's geometry attribute.""" |
| 73 | + # load to shapely geometry to easily test for geometry type |
| 74 | + geom = loads(aoi) |
| 75 | + |
| 76 | + # dependent on the type construct the query string |
| 77 | + if geom.geom_type == "Point": |
| 78 | + return f'&lon={geom.y}&lat={geom.x}' |
| 79 | + |
| 80 | + else: |
| 81 | + # simplify geometry, as we might otherwise bump into too long string issue |
| 82 | + aoi_convex = geom.convex_hull |
| 83 | + |
| 84 | + # create scihub-confrom aoi string |
| 85 | + return f'&geometry={aoi_convex}' |
| 86 | + |
| 87 | +def create_toi_str(start="2014-10-01", end=dt.now().strftime("%Y-%m-%d")): |
| 88 | + """Convert start and end date to scihub's search url time period attribute.""" |
| 89 | + # bring start and end date to query format |
| 90 | + return f"&startDate={start}T00:00:00Z&completionDate={end}T23:59:59Z" |
| 91 | + |
| 92 | +def create_s1_product_specs(product_type=None, polarisation=None, beam=None): |
| 93 | + """Convert Sentinel-1's product metadata to scihub's product attributes.""" |
| 94 | + # transform product type, polarisation and beam to query format |
| 95 | + product_type_query = f'&productType={product_type}' if product_type else '' |
| 96 | + polarisation_query = f'&polarisation={polarisation.replace(" ", "%26")}' if polarisation else '' |
| 97 | + sensor_mode_query = f'&sensorMode={beam}' if beam else '' |
| 98 | + |
| 99 | + return product_type_query + polarisation_query + sensor_mode_query |
| 100 | + |
| 101 | + |
| 102 | +def extract_basic_metadata(properties): |
| 103 | + |
| 104 | + # those are the things we wnat out of the standard json |
| 105 | + wanted = ['title', 'orbitDirection', 'platform', 'polarisation', 'swath', 'thumbnail', 'published'] |
| 106 | + |
| 107 | + # loop through all properties |
| 108 | + _dict = {} |
| 109 | + for k, v in properties.items(): |
| 110 | + # consider if in the list of wanted properties |
| 111 | + if k in wanted: |
| 112 | + if k == 'polarisation': |
| 113 | + # remove & sign |
| 114 | + _dict[k] = v.replace('&', ' ') |
| 115 | + elif k == 'title': |
| 116 | + # remove .SAFE extension |
| 117 | + _dict[k] = v[:-5] |
| 118 | + elif k == 'thumbnail': |
| 119 | + _dict[k] = '/'.join(v.split('/')[:-2]) + '/manifest.safe' |
| 120 | + else: |
| 121 | + _dict[k] = v |
| 122 | + |
| 123 | + sorted_dict = dict(sorted(_dict.items(), key=lambda item: wanted.index(item[0]))) |
| 124 | + return sorted_dict.values() |
| 125 | + |
| 126 | + |
| 127 | +def get_entry(line): |
| 128 | + |
| 129 | + return line.split('>')[1].split('<')[0] |
| 130 | + |
| 131 | + |
| 132 | +def get_advanced_metadata(metafile, access_token): |
| 133 | + |
| 134 | + with requests.Session() as session: |
| 135 | + headers={'Authorization': f'Bearer {access_token}'} |
| 136 | + request = session.request("get", metafile) |
| 137 | + response = session.get(request.url, headers=headers, stream=True) |
| 138 | + |
| 139 | + for line in response.iter_lines(): |
| 140 | + |
| 141 | + line = line.decode('utf-8') |
| 142 | + if 's1sarl1:sliceNumber' in line: |
| 143 | + slicenumber = get_entry(line) |
| 144 | + if 's1sarl1:totalSlices' in line: |
| 145 | + total_slices = get_entry(line) |
| 146 | + if 'relativeOrbitNumber type="start"' in line: |
| 147 | + relativeorbit = get_entry(line) |
| 148 | + if 'relativeOrbitNumber type="stop"' in line: |
| 149 | + lastrelativeorbit = get_entry(line) |
| 150 | + if 'safe:nssdcIdentifier' in line: |
| 151 | + platformidentifier = get_entry(line) |
| 152 | + if 's1sarl1:missionDataTakeID' in line: |
| 153 | + missiondatatakeid = get_entry(line) |
| 154 | + if 's1sarl1:mode' in line: |
| 155 | + sensoroperationalmode = get_entry(line) |
| 156 | + if 'orbitNumber type="start"' in line: |
| 157 | + orbitnumber = get_entry(line) |
| 158 | + if 'orbitNumber type="stop"' in line: |
| 159 | + lastorbitnumber = get_entry(line) |
| 160 | + if 'safe:startTime' in line: |
| 161 | + beginposition = get_entry(line) |
| 162 | + if 'safe:stopTime' in line: |
| 163 | + endposition = get_entry(line) |
| 164 | + if '1sarl1:productType' in line: |
| 165 | + product_type = get_entry(line) |
| 166 | + |
| 167 | + # add acquisitiondate |
| 168 | + acqdate = dt.strftime(dt.strptime(beginposition, '%Y-%m-%dT%H:%M:%S.%f'), format='%Y%m%d') |
| 169 | + |
| 170 | + return ( |
| 171 | + slicenumber, total_slices, |
| 172 | + relativeorbit, lastrelativeorbit, |
| 173 | + platformidentifier, missiondatatakeid, |
| 174 | + sensoroperationalmode, product_type, |
| 175 | + orbitnumber, lastorbitnumber, |
| 176 | + beginposition, endposition, acqdate, |
| 177 | + 0 # placeholder for size |
| 178 | + ) |
0 commit comments