usgsxplore 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
usgsxplore/__init__.py ADDED
File without changes
usgsxplore/api.py ADDED
@@ -0,0 +1,407 @@
1
+ """
2
+ Description: module contain the API class to download and interact with the USGS api (https://m2m.cr.usgs.gov/api/docs/json/).
3
+ This class is highly inspirate from https://github.com/yannforget/landsatxplore.
4
+
5
+ Last modified: 2024
6
+ Author: Luc Godin
7
+ """
8
+
9
+ import json
10
+ import random
11
+ import signal
12
+ import string
13
+ import sys
14
+ import time
15
+ from collections.abc import Generator
16
+ from urllib.parse import urljoin
17
+
18
+ import requests
19
+ from tqdm import tqdm
20
+
21
+ from usgsxplore.errors import (
22
+ APIInvalidParameters,
23
+ ScenesNotFound,
24
+ USGSAuthenticationError,
25
+ USGSError,
26
+ USGSInvalidDataset,
27
+ USGSRateLimitError,
28
+ )
29
+ from usgsxplore.filter import SceneFilter
30
+ from usgsxplore.scenes_downloader import ScenesDownloader
31
+
32
+ API_URL = "https://m2m.cr.usgs.gov/api/api/json/stable/"
33
+
34
+
35
+ class API:
36
+ """EarthExplorer API."""
37
+
38
+ def __init__(self, username: str, password: str | None = None, token: str | None = None) -> None:
39
+ """EarthExplorer API.
40
+
41
+ :param username: EarthExplorer username.
42
+ :param password: EarthExplorer password.
43
+ :param token: EarthExplorer token.
44
+ """
45
+ self.url = API_URL
46
+ self.session = requests.Session()
47
+ self.label = "usgsxplore"
48
+ self.login(username, password, token)
49
+
50
+ @staticmethod
51
+ def raise_api_error(response: requests.Response) -> None:
52
+ """Parse API response and return the appropriate exception.
53
+
54
+ :param response: Response from USGS API.
55
+ :raise USGSAuthenticationError: If credentials are not valid of if user lacks permission.
56
+ :raise USGSRateLimitError: If there are too many request
57
+ :raise USGSError: If the USGS API returns a non-null error code.
58
+ """
59
+ data = response.json()
60
+ error_code = data.get("errorCode")
61
+ error_msg = data.get("errorMessage")
62
+ if error_code:
63
+ if error_code in ("AUTH_INVALID", "AUTH_UNAUTHROIZED", "AUTH_KEY_INVALID"):
64
+ raise USGSAuthenticationError(f"{error_code}: {error_msg}.")
65
+ if error_code == "RATE_LIMIT":
66
+ raise USGSRateLimitError(f"{error_code}: {error_msg}.")
67
+ if error_code == "DATASET_INVALID":
68
+ raise USGSInvalidDataset(f"{error_code}: {error_msg}.")
69
+ raise USGSError(f"{error_code}: {error_msg}.")
70
+
71
+ def request(self, endpoint: str, params: dict = None) -> dict:
72
+ """Perform a request to the USGS M2M API.
73
+ :param endpoint: API endpoint.
74
+ :param params: API parameters.
75
+ :raise USGSAuthenticationError: If credentials are not valid of if user lacks permission.
76
+ :raise USGSRateLimitError: If there are too many request
77
+ :return: JSON data returned by the USGS API.
78
+ """
79
+ url = urljoin(self.url, endpoint)
80
+ data = json.dumps(params)
81
+ r = self.session.get(url, data=data)
82
+ try:
83
+ self.raise_api_error(r)
84
+ except USGSRateLimitError:
85
+ time.sleep(3)
86
+ r = self.session.get(url, data=data)
87
+ self.raise_api_error(r)
88
+ return r.json().get("data")
89
+
90
+ def login(self, username: str, password: str | None = None, token: str | None = None) -> None:
91
+ """Get an API key. With either the login request or the login-token-request
92
+
93
+ :param username: EarthExplorer username.
94
+ :param password: EarthExplorer password.
95
+ :param token: EarthExplorer token.
96
+ :raise APIInvalidParameters: if password and token are None.
97
+ :raise USGSAuthenticationError: If the authentification failed
98
+ """
99
+ if password is None and token is None:
100
+ raise APIInvalidParameters("Either password or token need to be given.")
101
+ if token is not None:
102
+ login_url = urljoin(self.url, "login-token")
103
+ payload = {"username": username, "token": token}
104
+ else:
105
+ login_url = urljoin(self.url, "login")
106
+ payload = {"username": username, "password": password}
107
+ r = self.session.post(login_url, json.dumps(payload))
108
+ self.raise_api_error(r)
109
+ self.session.headers["X-Auth-Token"] = r.json().get("data")
110
+
111
+ def logout(self) -> None:
112
+ """Logout from USGS M2M API."""
113
+ self.request("logout")
114
+ self.session = requests.Session()
115
+
116
+ def get_entity_id(self, display_id: str | list[str], dataset: str) -> str | list[str]:
117
+ """Get scene ID from product ID.
118
+
119
+ Note
120
+ ----
121
+ As the lookup endpoint has been removed in API v1.5, the function makes
122
+ successive calls to scene-list-add and scene-list-get in order to retrieve
123
+ the scene IDs. A temporary sceneList is created and removed at the end of the
124
+ process.
125
+
126
+ :param display_id: Input display ID. Can also be a list of display IDs.
127
+ :param dataset: Dataset alias.
128
+ :return: Output entity ID. Can also be a list of entity IDs depending on input.
129
+ """
130
+ # scene-list-add support both entityId and entityIds input parameters
131
+ param = "entityId"
132
+ if isinstance(display_id, list):
133
+ param = "entityIds"
134
+
135
+ # a random scene list name is created -- better error handling is needed
136
+ # to ensure that the temporary scene list is removed even if scene-list-get
137
+ # fails.
138
+ list_id = _random_string()
139
+ self.request(
140
+ "scene-list-add",
141
+ params={
142
+ "listId": list_id,
143
+ "datasetName": dataset,
144
+ "idField": "displayId",
145
+ param: display_id,
146
+ },
147
+ )
148
+ r = self.request("scene-list-get", params={"listId": list_id})
149
+ entity_id = [scene["entityId"] for scene in r]
150
+ self.request("scene-list-remove", params={"listId": list_id})
151
+
152
+ if param == "entityId":
153
+ return entity_id[0]
154
+
155
+ return entity_id
156
+
157
+ def metadata(self, entity_id: str, dataset: str) -> dict:
158
+ """Get metadata for a given scene.
159
+
160
+ :param entity_id: entity id of the scene
161
+ :param dataset: name of the scene dataset
162
+ :return Scene metadata.
163
+ """
164
+ r = self.request(
165
+ "scene-metadata",
166
+ params={
167
+ "datasetName": dataset,
168
+ "entityId": entity_id,
169
+ "metadataType": "full",
170
+ },
171
+ )
172
+ return r
173
+
174
+ def get_display_id(self, entity_id: str, dataset: str) -> str:
175
+ """
176
+ Get display ID from entity ID.
177
+
178
+ :param entity_id: entity id of the scene
179
+ :param dataset: Dataset alias.
180
+ :return: display id of the scene
181
+ """
182
+ meta = self.metadata(entity_id, dataset)
183
+ return meta["displayId"]
184
+
185
+ def dataset_filters(self, dataset: str) -> list[dict]:
186
+ """
187
+ Return the result of a dataset-filters request
188
+
189
+ :param dataset: Dataset alias.
190
+ :return: result of the dataset-filters request
191
+ """
192
+ return self.request("dataset-filters", {"datasetName": dataset})
193
+
194
+ def dataset_names(self) -> list[str]:
195
+ """
196
+ Return a list of all existing dataset
197
+ """
198
+ list_dataset = self.request("dataset-search")
199
+ return [dataset["datasetAlias"] for dataset in list_dataset]
200
+
201
+ def search(
202
+ self,
203
+ dataset: str,
204
+ location: tuple[float, float] | None = None,
205
+ bbox: tuple[float, float, float, float] | None = None,
206
+ max_cloud_cover: int | None = None,
207
+ date_interval: tuple[str, str] | None = None,
208
+ months: list[int] | None = None,
209
+ meta_filter: str | None = None,
210
+ max_results: int | None = None,
211
+ ) -> list[dict]:
212
+ """
213
+ Search for scenes, and return a list of all scenes found.
214
+ Works with multiple adv_scene_search to get all scenes
215
+
216
+ :param dataset: Alias dataset
217
+ :param location: (longitude, latitude) of the point of interest.
218
+ :param bbox: (xmin, ymin, xmax, ymax) of the bounding box.
219
+ :param max_cloud_cover: Max. cloud cover in percent (1-100).
220
+ :param date_interval: (start_date, end_date) of scene acquisition
221
+ :param months: Limit results to specific months (1-12).
222
+ :param meta_filter: String representation of metadata filter ex: camera=L
223
+ :param max_results: Max. number of results. Return all if not provided
224
+ :return: list of scene metadata
225
+ """
226
+ args = {
227
+ "bbox": bbox,
228
+ "max_cloud_cover": max_cloud_cover,
229
+ "months": months,
230
+ "meta_filter": meta_filter,
231
+ "location": location,
232
+ "date_interval": date_interval,
233
+ }
234
+ scene_filter = SceneFilter.from_args(**args)
235
+ scenes = []
236
+ for batch_scenes in self.batch_search(dataset, scene_filter, max_results):
237
+ scenes += batch_scenes
238
+ return scenes
239
+
240
+ def batch_search(
241
+ self,
242
+ dataset: str,
243
+ scene_filter: SceneFilter | None = None,
244
+ max_results: int | None = None,
245
+ metadata_type: str | None = "full",
246
+ use_tqdm: bool = True,
247
+ batch_size: int = 10000,
248
+ ) -> Generator[list[dict], None, None]:
249
+ """
250
+ Return a Generator with each element is a list of 10000 (batch_size) scenes informations.
251
+ The scenes are filtered with the scene_filter given.
252
+
253
+ :param dataset: Alias dataset
254
+ :param scene_filter: Filter for the scene you want
255
+ :param max_results: max scenes wanted, if None return all scenes found
256
+ :param metadata_type: identifies wich metadata to return (full|summary|None)
257
+ :param use_tqdm: if True display a progress bar of the search
258
+ :param batch_size: number of maxResults of each scene-search
259
+ :return: generator of scenes informations batch
260
+ """
261
+ starting_number = 1
262
+ if use_tqdm:
263
+ total = max_results if max_results else None
264
+ p_bar = tqdm(desc="Import scenes metadata", total=total, unit="Scenes")
265
+
266
+ while True:
267
+ if max_results and starting_number + batch_size > max_results:
268
+ batch_size = max_results - starting_number + 1
269
+ scene_search = self.scene_search(dataset, scene_filter, batch_size, starting_number, metadata_type)
270
+ yield scene_search["results"]
271
+ starting_number = scene_search["nextRecord"]
272
+
273
+ if use_tqdm:
274
+ p_bar.n = starting_number - 1
275
+ p_bar.total = (
276
+ max_results
277
+ if max_results and max_results <= scene_search["totalHits"]
278
+ else scene_search["totalHits"]
279
+ )
280
+ p_bar.refresh()
281
+
282
+ if (max_results and scene_search["nextRecord"] > max_results) or starting_number == scene_search[
283
+ "totalHits"
284
+ ]:
285
+ break
286
+ if use_tqdm:
287
+ p_bar.n = p_bar.total
288
+ p_bar.close()
289
+
290
+ def scene_search(
291
+ self,
292
+ dataset: str,
293
+ scene_filter: SceneFilter | None = None,
294
+ max_results: int = 100,
295
+ starting_number: int = 1,
296
+ metadata_type: str | None = "full",
297
+ ) -> dict:
298
+ """Search for scenes.
299
+
300
+ :param dataset: Case-insensitive dataset alias (e.g. landsat_tm_c1).
301
+ :param scene_filter: Filter for the scene you want
302
+ :param max_results: Max. number of results. Defaults to 100.
303
+ :param starting_number: starting number of the search. Default 1
304
+ :param metadata_type: identifies wich metadata to return (full|summary|None)
305
+ :return: Result of the scene-search request.
306
+ """
307
+ # we compile the metadataFilter if it exist to format it for the API
308
+ if scene_filter and "metadataFilter" in scene_filter:
309
+ scene_filter["metadataFilter"].compile(self.dataset_filters(dataset))
310
+
311
+ r = self.request(
312
+ "scene-search",
313
+ params={
314
+ "datasetName": dataset,
315
+ "sceneFilter": scene_filter,
316
+ "maxResults": max_results,
317
+ "metadataType": metadata_type,
318
+ "startingNumber": starting_number,
319
+ },
320
+ )
321
+ return r
322
+
323
+ def download(
324
+ self,
325
+ dataset: str,
326
+ entity_ids: list[str],
327
+ output_dir: str = ".",
328
+ max_thread: int = 5,
329
+ overwrite: bool = False,
330
+ pbar_type: int = 2,
331
+ ) -> None:
332
+ """
333
+ Download GTiff images identify from their entity id, use the M2M API. Progress of
334
+ the downloading can be displayed in terms of the p_bar_type given.
335
+
336
+ :param dataset: Alias dataset of scenes wanted
337
+ :param entity_ids: list of entity id of scenes wanted
338
+ :param output_dir: output directory to store GTiff images
339
+ :param max_thread: maximum number of thread that would be used for the downloading
340
+ :param p_bar_type: way to display progress bar (0: no pbar, 1: one pbar, 2: pbar for each scenes)
341
+ """
342
+ # first clean the residus of previous download
343
+ self.clean_download()
344
+
345
+ scenes_downloader = ScenesDownloader(entity_ids, output_dir, max_thread, pbar_type, overwrite)
346
+
347
+ # get download-options and send it to the scenes_downloader
348
+ download_options = self.request("download-options", {"datasetName": dataset, "entityIds": entity_ids})
349
+ if download_options is None:
350
+ raise ScenesNotFound(f"No scenes found in the dataset '{dataset}'.")
351
+ scenes_downloader.set_download_options(download_options)
352
+
353
+ # send a download-request with parsed products
354
+ download_list = scenes_downloader.get_downloads()
355
+ request_results = self.request("download-request", {"downloads": download_list, "label": self.label})
356
+
357
+ # defined the ctrl-c signal to stop all downloading thread
358
+ # pylint: disable=unused-argument
359
+ def _handle_sigint(sign, frame):
360
+ scenes_downloader.stop_download()
361
+ sys.exit(0)
362
+
363
+ signal.signal(signal.SIGINT, _handle_sigint)
364
+
365
+ # then loop with download-retrieve request every 30 sec to get
366
+ # all download link
367
+ download_ids = []
368
+ while True:
369
+ retrieve_results = self.request("download-retrieve", {"label": self.label})
370
+
371
+ # loop in all link "available" and "requested" and download it
372
+ # with the Product.download method
373
+ for download in retrieve_results["available"] + retrieve_results["requested"]:
374
+ if download["downloadId"] not in download_ids:
375
+ download_ids.append(download["downloadId"])
376
+ scenes_downloader.download(download["entityId"], download["url"])
377
+
378
+ # if all the link are not ready yet, sleep 30 sec and loop, else exit from the loop
379
+ if len(download_ids) < (len(download_list) - len(request_results["failed"])):
380
+ time.sleep(30)
381
+ else:
382
+ break
383
+
384
+ # cleanup the download order and wait all thread to finish
385
+ self.clean_download()
386
+ scenes_downloader.wait_all_thread()
387
+
388
+ def clean_download(self) -> None:
389
+ """
390
+ This method clean residus of download in the API it first do
391
+ a "download-order-remove", then it do a "download-search" and do a "download-remove" for each download.
392
+ It called by the download method 2 times
393
+ """
394
+ self.request("download-order-remove", {"label": self.label})
395
+ download_search = self.request("download-search", {"label": self.label})
396
+ if download_search:
397
+ for dl in download_search:
398
+ self.request("download-remove", {"downloadId": dl["downloadId"]})
399
+
400
+
401
+ def _random_string(length=10):
402
+ """Generate a random string."""
403
+ letters = string.ascii_lowercase
404
+ return "".join(random.choice(letters) for i in range(length))
405
+
406
+
407
+ # End-of-file (EOF)
usgsxplore/cli.py ADDED
@@ -0,0 +1,242 @@
1
+ # pylint: disable=too-many-locals
2
+ # pylint: disable=unused-argument
3
+ """
4
+ Description: Command line interface of the usgsxplore
5
+
6
+ Last modified: 2024
7
+ Author: Luc Godin
8
+ """
9
+ import json
10
+
11
+ import click
12
+
13
+ from usgsxplore.api import API
14
+ from usgsxplore.errors import FilterFieldError, FilterValueError, USGSInvalidDataset
15
+ from usgsxplore.filter import SceneFilter
16
+ from usgsxplore.utils import read_textfile, sort_strings_by_similarity, to_gpkg
17
+
18
+
19
+ # ----------------------------------------------------------------------------------------------------
20
+ # CALLBACK FUNCTIONS
21
+ # ----------------------------------------------------------------------------------------------------
22
+ def is_valid_output_format(ctx: click.Context, param: click.Parameter, value: str) -> str:
23
+ """
24
+ Callback use to check the format of the output file of the search command.
25
+ """
26
+ if value is None:
27
+ return None
28
+ formats = (".txt", ".json", ".gpkg", ".shp", ".geojson")
29
+ if not value.endswith(formats):
30
+ choices = " | ".join(formats)
31
+ raise click.BadParameter(f"'{value}' file format must be in {choices}")
32
+ return value
33
+
34
+
35
+ def check_log(ctx: click.Context, param: click.Parameter, value: str | None) -> str:
36
+ if value is not None:
37
+ return value
38
+ if ctx.params.get("password") is None:
39
+ raise click.ClickException("Missing argument -p, --password or -t, --token")
40
+
41
+
42
+ def read_dataset_textfile(ctx: click.Context, param: click.Parameter, value: str | None):
43
+ """
44
+ This callback is use to fill the dataset parameter with either the first line of a textfile
45
+ or with the dataset value in parameters
46
+ """
47
+ if value is not None:
48
+ return value
49
+ # treat the first line of the textfile given to see if the dataset is provided
50
+ dataset = None
51
+ with open(ctx.params.get("textfile"), encoding="utf-8") as file:
52
+ first_line = file.readline().strip()
53
+ if first_line.startswith("#"):
54
+ spl = first_line.split("=", maxsplit=1)
55
+ if len(spl) == 2 and "dataset" in spl[0]:
56
+ dataset = spl[1].strip()
57
+
58
+ if dataset is None:
59
+ raise click.MissingParameter(ctx=ctx, param=ctx.params.get("dataset"))
60
+
61
+ return dataset
62
+
63
+
64
+ def is_text_file(ctx: click.Context, param: click.Parameter, value: str) -> str:
65
+ "callback for verify the validity of the textfile"
66
+ if not value.endswith(".txt"):
67
+ raise click.BadParameter(f"'{value}' must be a textfile", ctx=ctx, param=param)
68
+ return value
69
+
70
+
71
+ # ----------------------------------------------------------------------------------------------------
72
+ # COMMAND LINE INTERFACE
73
+ # ----------------------------------------------------------------------------------------------------
74
+ @click.group()
75
+ def cli() -> None:
76
+ """
77
+ Command line interface of the usgsxplore.
78
+ Documentation : https://github.com/adehecq/usgs_explorer
79
+ """
80
+
81
+
82
+ # ----------------------------------------------------------------------------------------------------
83
+ # SEARCH COMMAND
84
+ # ----------------------------------------------------------------------------------------------------
85
+ @click.command()
86
+ @click.option(
87
+ "-u", "--username", type=click.STRING, required=True, help="EarthExplorer username.", envvar="USGSXPLORE_USERNAME"
88
+ )
89
+ @click.option(
90
+ "-p", "--password", type=click.STRING, help="EarthExplorer password.", required=False, envvar="USGSXPLORE_PASSWORD"
91
+ )
92
+ @click.option(
93
+ "-t",
94
+ "--token",
95
+ type=click.STRING,
96
+ help="EarthExplorer token.",
97
+ required=False,
98
+ envvar="USGSXPLORE_TOKEN",
99
+ callback=check_log,
100
+ )
101
+ @click.argument("dataset", type=click.STRING)
102
+ @click.option(
103
+ "-o",
104
+ "--output",
105
+ type=click.Path(file_okay=True),
106
+ help="Output file : (txt, json, gpkg, shp, geojson)",
107
+ callback=is_valid_output_format,
108
+ )
109
+ @click.option(
110
+ "-l",
111
+ "--location",
112
+ type=click.FLOAT,
113
+ nargs=2,
114
+ help="Point of interest (longitude, latitude).",
115
+ )
116
+ @click.option(
117
+ "-b",
118
+ "--bbox",
119
+ type=click.FLOAT,
120
+ nargs=4,
121
+ help="Bounding box (xmin, ymin, xmax, ymax).",
122
+ )
123
+ @click.option("-c", "--clouds", type=click.INT, help="Max. cloud cover (1-100).")
124
+ @click.option(
125
+ "-i",
126
+ "--interval-date",
127
+ type=click.STRING,
128
+ nargs=2,
129
+ help="Date interval (start, end), (YYYY-MM-DD, YYYY-MM-DD).",
130
+ )
131
+ @click.option("-f", "--filter", type=click.STRING, help="String representation of metadata filter")
132
+ @click.option("-m", "--limit", type=click.INT, help="Max. results returned. Return all by default")
133
+ @click.option("--pbar", is_flag=True, default=False, help="Display a progress bar")
134
+ def search(
135
+ username: str,
136
+ password: str | None,
137
+ token: str | None,
138
+ dataset: str,
139
+ output: str | None,
140
+ location: tuple[float, float] | None,
141
+ bbox: tuple[float, float, float, float] | None,
142
+ clouds: int | None,
143
+ interval_date: tuple[str, str] | None,
144
+ filter: str | None, # pylint: disable=redefined-builtin
145
+ limit: int | None,
146
+ pbar: bool,
147
+ ) -> None:
148
+ """
149
+ Search scenes in a dataset with filters.
150
+ """
151
+ api = API(username, password=password, token=token)
152
+ scene_filter = SceneFilter.from_args(
153
+ location=location, bbox=bbox, max_cloud_cover=clouds, date_interval=interval_date, meta_filter=filter
154
+ )
155
+
156
+ try:
157
+ if output is None:
158
+ for batch_scenes in api.batch_search(dataset, scene_filter, limit, None, pbar):
159
+ for scene in batch_scenes:
160
+ click.echo(scene["entityId"])
161
+
162
+ else:
163
+ if output.endswith(".txt"):
164
+ with open(output, "w", encoding="utf-8") as file:
165
+ file.write(f"#dataset={dataset}\n")
166
+ for batch_scenes in api.batch_search(dataset, scene_filter, limit, None, pbar):
167
+ for scene in batch_scenes:
168
+ file.write(scene["entityId"] + "\n")
169
+ elif output.endswith(".json"):
170
+ with open(output, "w", encoding="utf-8") as file:
171
+ scenes = []
172
+ for batch_scenes in api.batch_search(dataset, scene_filter, limit, None, pbar):
173
+ scenes += batch_scenes
174
+ json.dump(scenes, file, indent=4)
175
+ elif output.endswith((".gpkg", ".geojson", "shp")):
176
+ scenes = []
177
+ for batch_scenes in api.batch_search(dataset, scene_filter, limit, "full", pbar):
178
+ scenes += batch_scenes
179
+ to_gpkg(scenes, output)
180
+
181
+ # if dataset is invalid print a list of similar dataset for the user
182
+ except USGSInvalidDataset:
183
+ datasets = api.dataset_names()
184
+ sorted_datasets = sort_strings_by_similarity(dataset, datasets)[:50]
185
+ choices = " | ".join(sorted_datasets)
186
+ click.echo(f"Invalid dataset : '{dataset}', it must be in :\n {choices}")
187
+ # print only the message when a filter error is raise
188
+ except (FilterValueError, FilterFieldError) as e:
189
+ print(e.__class__.__name__, " : ", e)
190
+
191
+ api.logout()
192
+
193
+
194
+ # ----------------------------------------------------------------------------------------------------
195
+ # DOWNLOAD COMMAND
196
+ # ----------------------------------------------------------------------------------------------------
197
+ @click.command()
198
+ @click.option("-u", "--username", type=click.STRING, help="EarthExplorer username.", envvar="USGSXPLORE_USERNAME")
199
+ @click.option(
200
+ "-p", "--password", type=click.STRING, help="EarthExplorer password.", required=False, envvar="USGSXPLORE_PASSWORD"
201
+ )
202
+ @click.option(
203
+ "-t", "--token", type=click.STRING, help="EarthExplorer token.", required=False, envvar="USGSXPLORE_TOKEN"
204
+ )
205
+ @click.argument("textfile", type=click.Path(exists=True, file_okay=True), callback=is_text_file)
206
+ @click.option("--dataset", "-d", type=click.STRING, required=False, help="Dataset", callback=read_dataset_textfile)
207
+ @click.option("--output-dir", "-o", type=click.Path(dir_okay=True), default=".", help="Output directory")
208
+ @click.option("--pbar", "-b", type=click.IntRange(0, 2), default=2, help="Type of progression displaying (0,1,2)")
209
+ @click.option("--max-thread", "-m", type=click.INT, default=5, help="Max thread number (default: 5)")
210
+ @click.option("--overwrite", is_flag=True, default=False, help="Overwrite existing files")
211
+ def download(
212
+ username: str,
213
+ password: str | None,
214
+ token: str | None,
215
+ textfile: str,
216
+ dataset: str,
217
+ output_dir: str,
218
+ pbar: int,
219
+ max_thread: int,
220
+ overwrite: bool,
221
+ ) -> None:
222
+ """
223
+ Download scenes with their entity ids provided in the textfile.
224
+ The dataset can also be provide in the first line of the textfile : #dataset=declassii
225
+ """
226
+ api = API(username, password=password, token=token)
227
+ entity_ids = read_textfile(textfile)
228
+ api.download(dataset, entity_ids, output_dir, max_thread, overwrite, pbar)
229
+ api.logout()
230
+
231
+
232
+ cli.add_command(search)
233
+ cli.add_command(download)
234
+
235
+
236
+ @click.command()
237
+ def cli_gpkg():
238
+ click.echo("hello")
239
+
240
+
241
+ if __name__ == "__main__":
242
+ cli()