Skip to content

Commit 0299b69

Browse files
authored
fix progress conflict with cli prompt (#507)
1 parent 9fa2f05 commit 0299b69

10 files changed

Lines changed: 110 additions & 114 deletions

File tree

rapida/cli/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def cli(ctx):
5353
progress = Progress(disable=False, console=None, transient=True)
5454

5555
# 4. Spin up the progress display canvas
56-
progress.start()
56+
#progress.start()
5757

5858
# 5. Inject it into Click's shared context object
5959
ctx.obj['progress'] = progress

rapida/cli/aclick.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,11 @@ def list_commands(self, ctx):
5252

5353
def add_command(self, cmd: click.Command, name: str = None) -> None:
5454
# Catch-all: forces help display if a subcommand is run empty
55-
#cmd.no_args_is_help = True
55+
has_required_params = any(param.required for param in cmd.params)
56+
is_grp = isinstance(cmd, click.Group) or issubclass(cmd.__class__, self.__class__)
57+
#print(cmd.name, has_required_params, is_grp, cmd.params)
58+
# if not is_grp and has_required_params:
59+
# cmd.no_args_is_help = True
5660
# 2. Automatically inject --debug into every registered subcommand
5761
cmd.params.append(
5862
click.Option(

rapida/cli/auth.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import logging
22
from rapida.az.surgeauth import SurgeTokenCredential
33
import click
4-
from rapida.util.setup_logger import setup_logger
4+
55

66

77
logger = logging.getLogger(__name__)
@@ -18,7 +18,6 @@ def auth(cache_dir):
1818
"""
1919
Authenticate with UNDP account
2020
"""
21-
# setup_logger(name='rapida', level=logging.DEBUG if debug else logging.INFO)
2221

2322
credential = SurgeTokenCredential(cache_dir=cache_dir)
2423
token, exp_ts = credential.get_token("https://storage.azure.com/.default",)

rapida/cli/connectivity.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,8 @@ async def connectivity(ctx, bbox:tuple[float, float, float, float]=None, travel_
8888
):
8989
logger.info(f'Running connectivity analysis ')
9090
progress = ctx.obj.get('progress')
91-
return await run_connectivity_analysis(
92-
bbox=bbox, dst_dir=dst_dir, travel_mode=travel_mode, time_intervals=time_intervals,
93-
barriers_dataset=barriers_dataset, barriers_layer=barriers_layer, barriers_buffer=barriers_buffer, progress=progress
94-
)
91+
with progress:
92+
return await run_connectivity_analysis(
93+
bbox=bbox, dst_dir=dst_dir, travel_mode=travel_mode, time_intervals=time_intervals,
94+
barriers_dataset=barriers_dataset, barriers_layer=barriers_layer, barriers_buffer=barriers_buffer, progress=progress
95+
)

rapida/cli/create.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import click
44
import sys
55
from rapida.session import is_rapida_initialized
6-
from rapida.util.setup_logger import setup_logger
76
from rapida.project.project import Project
87

98
logger = logging.getLogger(__name__)

rapida/cli/delete.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ def delete(project: str, no_input: bool = False, ):
3434
rapida delete --project=<project folder path>: If you are not in a project folder
3535
3636
"""
37-
#setup_logger(name='rapida', level=logging.DEBUG if debug else logging.INFO)
3837

3938
if not is_rapida_initialized():
4039
return

rapida/cli/download.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
import logging
44
from rapida.az.fileshare import download_project
55
from rich.progress import Progress
6-
76
from rapida.session import is_rapida_initialized
8-
from rapida.util.setup_logger import setup_logger
97
from rapida.project.project import Project
108

119
logger = logging.getLogger(__name__)
@@ -24,11 +22,8 @@
2422
is_flag=True,
2523
default=False,
2624
help="Whether to overwrite the project in case it already exists locally.")
27-
@click.option('--debug',
28-
is_flag=True,
29-
default=False,
30-
help="Set log level to debug")
31-
def download(project_name=None, destination_folder=None, max_concurrency=None,force=None, debug: bool =False ):
25+
26+
def download(project_name=None, destination_folder=None, max_concurrency=None,force=None):
3227
"""
3328
Download a project from Azure File Share.
3429
@@ -51,7 +46,6 @@ def download(project_name=None, destination_folder=None, max_concurrency=None,fo
5146
To use `-f/--force`, project data will be overwritten if it already exists in local storage.
5247
5348
"""
54-
setup_logger(name='rapida', level=logging.DEBUG if debug else logging.INFO)
5549

5650
if not is_rapida_initialized():
5751
return

rapida/cli/init.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,13 @@ def setup_prompt(session: Session):
7979
default=False,
8080
help="Optional. If True, it will automatically answer yes to prompts. Default is False.")
8181

82-
def init(no_input: bool = False, debug=False):
82+
def init(no_input: bool = False):
8383
"""
8484
Initialize RAPIDA tool. This command will creates a config file under user home directory (~/.rapida/config.json) to setup RAPIDA tool.
8585
8686
Use `--no-input` to disable prompting. Default is False.
8787
"""
88-
setup_logger(name='rapida', level=logging.DEBUG if debug else logging.INFO)
88+
8989

9090
click.echo("Welcome to rapida CLI tool!")
9191
with Session() as session:

rapida/cli/list.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,16 @@
22
import click
33
from rapida.az.fileshare import list_projects
44
from rapida.session import is_rapida_initialized
5-
from rapida.util.setup_logger import setup_logger
65

76

87
logger = logging.getLogger(__name__)
98

109

1110
@click.command(short_help=f'list RAPIDA projects/folders located in default Azure file share')
12-
@click.option('--debug',
13-
is_flag=True,
14-
default=False,
15-
help="Set log level to debug"
16-
)
17-
def list_project(debug=False):
18-
setup_logger(name='rapida', level=logging.DEBUG if debug else logging.INFO)
11+
12+
13+
def list_project():
14+
1915

2016
if not is_rapida_initialized():
2117
return

rapida/cli/ntl.py

Lines changed: 90 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -114,35 +114,36 @@ def search():
114114
async def search_noaa(ctx, bbox:tuple[float, float, float, float]=None, nominal_date:datetime=None, satellites:list[str] = [], cmask:bool=None):
115115

116116
progress = ctx.obj.get('progress')
117-
table = Table(title=f"VIIRS satellites granules for the night of {nominal_date.date()} covering {bbox}",
118-
title_style="bold yellow")
119-
table.add_column("Position", justify="center", style="white")
120-
table.add_column("Satellite", style="green", justify='center')
121-
table.add_column("Timestamp (UTC)", style="cyan", justify='center')
122-
# table.add_column("Scan Start Date and Time (UTC)", style="red", justify='center')
123-
table.add_column("Bbox offset from SSP (km)", justify="center", style="white")
124-
table.add_column("Elevation above bbox (degrees)", justify="center", style="white")
125-
if cmask:
126-
table.add_column("Cloud coverage in bbox (%)", justify="center", style="white")
127-
table.add_column("Score (%)", justify="center", style="white")
128-
table.add_column("BBOX intersection (%)", justify="center", style="white")
129-
130-
granules = await async_search_granules(
131-
satellites=satellites, nominal_date=nominal_date, bbox=bbox,
132-
cmask=cmask, progress=progress)
133-
if granules:
134-
for i, granule in enumerate(granules, start=1):
135-
if cmask:
136-
values = f'{i}', granule.sat, granule.timestamp, f'{granule.offset}', f'{granule.elevation:.2f}', f'{granule.cloud_cover}', f'{granule.rank}', f'{granule.pint}'
137-
else:
138-
values = f'{i}', granule.sat, granule.timestamp, f'{granule.offset}', f'{granule.elevation:.2f}', f'{granule.rank}', f'{granule.pint}'
139-
table.add_row(*values)
140-
141-
if table.row_count == 0:
142-
progress.console.print("[bold red]No granules found for this criteria.[/bold red]")
143-
else:
144-
progress.console.print(table)
145-
progress.console.print(f"\n[dim]Note: Each granule represents {1025 / 12:.2f}s of instrument data.[/dim]")
117+
with progress:
118+
table = Table(title=f"VIIRS satellites granules for the night of {nominal_date.date()} covering {bbox}",
119+
title_style="bold yellow")
120+
table.add_column("Position", justify="center", style="white")
121+
table.add_column("Satellite", style="green", justify='center')
122+
table.add_column("Timestamp (UTC)", style="cyan", justify='center')
123+
# table.add_column("Scan Start Date and Time (UTC)", style="red", justify='center')
124+
table.add_column("Bbox offset from SSP (km)", justify="center", style="white")
125+
table.add_column("Elevation above bbox (degrees)", justify="center", style="white")
126+
if cmask:
127+
table.add_column("Cloud coverage in bbox (%)", justify="center", style="white")
128+
table.add_column("Score (%)", justify="center", style="white")
129+
table.add_column("BBOX intersection (%)", justify="center", style="white")
130+
131+
granules = await async_search_granules(
132+
satellites=satellites, nominal_date=nominal_date, bbox=bbox,
133+
cmask=cmask, progress=progress)
134+
if granules:
135+
for i, granule in enumerate(granules, start=1):
136+
if cmask:
137+
values = f'{i}', granule.sat, granule.timestamp, f'{granule.offset}', f'{granule.elevation:.2f}', f'{granule.cloud_cover}', f'{granule.rank}', f'{granule.pint}'
138+
else:
139+
values = f'{i}', granule.sat, granule.timestamp, f'{granule.offset}', f'{granule.elevation:.2f}', f'{granule.rank}', f'{granule.pint}'
140+
table.add_row(*values)
141+
142+
if table.row_count == 0:
143+
progress.console.print("[bold red]No granules found for this criteria.[/bold red]")
144+
else:
145+
progress.console.print(table)
146+
progress.console.print(f"\n[dim]Note: Each granule represents {1025 / 12:.2f}s of instrument data.[/dim]")
146147

147148

148149
@search.command(name='nasa', short_help=f'Search for available NTL science data from NASA source')
@@ -187,7 +188,6 @@ async def search_noaa(ctx, bbox:tuple[float, float, float, float]=None, nominal_
187188
def search_nasa(ctx, bbox:tuple[tuple[float, float, float, float]]=None, nominal_date:datetime=None, stream:str = None, processing_level:str=None, route:str=None):
188189

189190
progress = ctx.obj.get('progress')
190-
191191
urls = nasa_search(processing_level=processing_level, nominal_date=nominal_date,
192192
bbox=bbox, stream=stream, route=route, progress=progress, push_to_cache=True)
193193

@@ -259,28 +259,29 @@ async def download_nasa(ctx, timestamp:str = None, product:str=None, tile:str=No
259259
if tile and bbox:
260260
raise click.UsageError("Illegal usage: `--tile` and `--bbox` are mutually exclusive.")
261261

262-
downloaded_files = await download_from_nasa(timestamp=timestamp, product=product,
263-
tile=tile, bbox=bbox, dst_dir=dst_dir,progress=progress)
262+
with progress:
263+
downloaded_files = await download_from_nasa(timestamp=timestamp, product=product,
264+
tile=tile, bbox=bbox, dst_dir=dst_dir,progress=progress)
264265

265266

266267

267-
if downloaded_files:
268-
table = Table(title=f"Downloaded files for {product.upper()} {timestamp} ", title_style="bold yellow")
268+
if downloaded_files:
269+
table = Table(title=f"Downloaded files for {product.upper()} {timestamp} ", title_style="bold yellow")
269270

270-
table.add_column("Path", style="red", justify='center')
271-
table.add_column("Timestamp", style="red", justify='center')
272-
table.add_column("Tile", style="red", justify='center')
273-
table.add_column("Size", style="green", justify='center')
274-
for timestamp, files in downloaded_files.items():
275-
for local_file_path in files:
276-
_, file_name = os.path.split(local_file_path)
277-
file_size = os.path.getsize(local_file_path)
278-
m = NTL_FILENAME_PATTERN.match(file_name)
279-
meta = m.groupdict()
280-
tile = meta['tile']
281-
table.add_row(local_file_path, timestamp, tile, f'{file_size}')
271+
table.add_column("Path", style="red", justify='center')
272+
table.add_column("Timestamp", style="red", justify='center')
273+
table.add_column("Tile", style="red", justify='center')
274+
table.add_column("Size", style="green", justify='center')
275+
for timestamp, files in downloaded_files.items():
276+
for local_file_path in files:
277+
_, file_name = os.path.split(local_file_path)
278+
file_size = os.path.getsize(local_file_path)
279+
m = NTL_FILENAME_PATTERN.match(file_name)
280+
meta = m.groupdict()
281+
tile = meta['tile']
282+
table.add_row(local_file_path, timestamp, tile, f'{file_size}')
282283

283-
progress.console.print(table)
284+
progress.console.print(table)
284285

285286

286287
@download.command(name='noaa', short_help=f'Download operational NTL data from NOAA')
@@ -325,22 +326,23 @@ async def download_nasa(ctx, timestamp:str = None, product:str=None, tile:str=No
325326
@click.pass_context
326327
async def download_noaa(ctx, satellite:str=None, timestamp:str=None, products:Iterable[str]=None, source:str=None, dst_dir:str=None ):
327328
progress = ctx.obj.get('progress')
328-
downloaded_files = await download_from_noaa(satellite=satellite,timestamp=timestamp,
329-
source=source, products=products,dest_dir=dst_dir, progress=progress)
329+
with progress:
330+
downloaded_files = await download_from_noaa(satellite=satellite,timestamp=timestamp,
331+
source=source, products=products,dest_dir=dst_dir, progress=progress)
330332

331-
if downloaded_files:
332-
table = Table(title=f"VIIRS satellites images for the night of {timestamp} ",
333-
title_style="bold yellow")
333+
if downloaded_files:
334+
table = Table(title=f"VIIRS satellites images for the night of {timestamp} ",
335+
title_style="bold yellow")
334336

335-
table.add_column("Satellite", style="green", justify='center')
336-
table.add_column("Timestamp (UTC)", style="cyan", justify='center')
337-
table.add_column("Downloaded file", justify="left", style="red")
338-
table.add_column("File size", justify="center", style="white")
337+
table.add_column("Satellite", style="green", justify='center')
338+
table.add_column("Timestamp (UTC)", style="cyan", justify='center')
339+
table.add_column("Downloaded file", justify="left", style="red")
340+
table.add_column("File size", justify="center", style="white")
339341

340-
for _, local_file_path, file_size in downloaded_files:
341-
values = satellite, timestamp, f'{local_file_path}', f'{bytesto(file_size, "m"):.2f} MB'
342-
table.add_row(*values)
343-
progress.console.print(table)
342+
for _, local_file_path, file_size in downloaded_files:
343+
values = satellite, timestamp, f'{local_file_path}', f'{bytesto(file_size, "m"):.2f} MB'
344+
table.add_row(*values)
345+
progress.console.print(table)
344346

345347

346348

@@ -391,28 +393,28 @@ async def download_noaa(ctx, satellite:str=None, timestamp:str=None, products:It
391393
async def bulk_download(ctx, bbox:tuple[float, float, float, float]=None, start_date:datetime=None, end_date:datetime=None,
392394
products:str=None, dst_dir:str=None):
393395
progress = ctx.obj.get('progress')
396+
with progress:
397+
if start_date > end_date:
398+
raise click.UsageError(f'--from {start_date} must be smaller or equal then --to {end_date}')
394399

395-
if start_date > end_date:
396-
raise click.UsageError(f'--from {start_date} must be smaller or equal then --to {end_date}')
397-
398-
if 'nrt' in products[0].lower():
399-
stream = OPERATIONAL
400-
now = datetime.now()
401-
402-
start_days_difference = abs((now - start_date).days)
403-
if start_days_difference > 7:
404-
raise ValueError(f'Invalid start_date={start_date}.{stream} stream holds max 7 days of data. ')
405-
end_days_difference = abs((now - end_date).days)
406-
if end_days_difference > 7:
407-
raise ValueError(f'Invalid start_date={end_date}.{stream} stream holds max 7 days of data. ')
408-
409-
else:
410-
stream = ARCHIVE
411-
downloaded_files = await bdownload(
412-
bbox=bbox, start_date=start_date, end_date=end_date,
413-
stream=stream, products=products,
414-
dst_dir=dst_dir,progress=progress
415-
)
400+
if 'nrt' in products[0].lower():
401+
stream = OPERATIONAL
402+
now = datetime.now()
403+
404+
start_days_difference = abs((now - start_date).days)
405+
if start_days_difference > 7:
406+
raise ValueError(f'Invalid start_date={start_date}.{stream} stream holds max 7 days of data. ')
407+
end_days_difference = abs((now - end_date).days)
408+
if end_days_difference > 7:
409+
raise ValueError(f'Invalid start_date={end_date}.{stream} stream holds max 7 days of data. ')
410+
411+
else:
412+
stream = ARCHIVE
413+
downloaded_files = await bdownload(
414+
bbox=bbox, start_date=start_date, end_date=end_date,
415+
stream=stream, products=products,
416+
dst_dir=dst_dir,progress=progress
417+
)
416418

417419

418420

@@ -457,7 +459,8 @@ async def bulk_download(ctx, bbox:tuple[float, float, float, float]=None, start_
457459
async def fetch(ctx, bbox:tuple[float, float, float, float]=None, nominal_date:datetime=None, deliverable:str=None, dst_dir:str=None):
458460

459461
progress = ctx.obj.get('progress')
460-
return await fetch_ntl(bbox=bbox,nominal_date=nominal_date, deliverable=deliverable, progress=progress, dst_dir=dst_dir )
462+
with progress:
463+
return await fetch_ntl(bbox=bbox,nominal_date=nominal_date, deliverable=deliverable, progress=progress, dst_dir=dst_dir )
461464

462465

463466
@ntl.command(short_help=f'Execute crisis impact detection (48h Alerts / 72h Assessments)')
@@ -527,10 +530,11 @@ async def fetch(ctx, bbox:tuple[float, float, float, float]=None, nominal_date:d
527530
async def detect(ctx, bbox:tuple[float, float, float, float]=None, nominal_date:datetime=None, deliverable:str=None,
528531
mask_clouds:bool=True, dst_dir:str=None, percentage_drop:int=None, display:bool=False):
529532
progress = ctx.obj.get('progress')
530-
return await detect_outage(
531-
bbox=bbox, nominal_date=nominal_date, deliverable=deliverable, dst_dir=dst_dir,
532-
progress=progress, mask_clouds=mask_clouds, percentage_drop=percentage_drop, display=display
533-
)
533+
with progress:
534+
return await detect_outage(
535+
bbox=bbox, nominal_date=nominal_date, deliverable=deliverable, dst_dir=dst_dir,
536+
progress=progress, mask_clouds=mask_clouds, percentage_drop=percentage_drop, display=display
537+
)
534538

535539

536540

0 commit comments

Comments
 (0)