|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +import click |
| 4 | +import pystac |
| 5 | +from pystac import Catalog, Collection |
| 6 | + |
| 7 | + |
| 8 | +def format_summary(summary: dict[str, Any], indent: int = 4) -> str: |
| 9 | + out = "" |
| 10 | + for var in summary: |
| 11 | + if type(summary[var]) == dict: |
| 12 | + out += var + ": \n" + " " * indent + str(summary[var]) + "\n" |
| 13 | + else: |
| 14 | + out += var + ": " + str(summary[var]) + "\n" |
| 15 | + return out |
| 16 | + |
| 17 | + |
| 18 | +def print_summaries(collection_path: str, force_resummary: bool = False) -> None: |
| 19 | + col = pystac.read_file(collection_path) |
| 20 | + if isinstance(col, Collection): |
| 21 | + orig_summaries = col.summaries.to_dict() |
| 22 | + if force_resummary or len(orig_summaries) == 0: |
| 23 | + new_summaries = pystac.summaries.Summarizer().summarize(col).to_dict() |
| 24 | + if len(orig_summaries) == 0: |
| 25 | + print( |
| 26 | + "Collection's summaries were empty. Printing recalculated summaries:" |
| 27 | + ) |
| 28 | + print(format_summary(new_summaries)) |
| 29 | + else: |
| 30 | + print(format_summary(orig_summaries)) |
| 31 | + elif isinstance(col, Catalog): |
| 32 | + print("Input is a catalog, not a collection.") |
| 33 | + print( |
| 34 | + "Run 'stac describe -h {}' to discover collections in this catalog".format( |
| 35 | + collection_path |
| 36 | + ) |
| 37 | + ) |
| 38 | + return |
| 39 | + else: |
| 40 | + print("{} is not a collection".format(collection_path)) |
| 41 | + return |
| 42 | + |
| 43 | + |
| 44 | +def create_summary_command(cli: click.Group) -> click.Command: |
| 45 | + @cli.command("summary", short_help="Summarize a STAC collection's contents.") |
| 46 | + @click.option( |
| 47 | + "-f", |
| 48 | + "--force_resummary", |
| 49 | + is_flag=True, |
| 50 | + default=False, |
| 51 | + help="Ignore existing summaries in the collection and print recalculated summaries", |
| 52 | + ) |
| 53 | + @click.argument("collection_path") |
| 54 | + def summary_command(collection_path: str, force_resummary: bool) -> None: |
| 55 | + print_summaries(collection_path, force_resummary) |
| 56 | + |
| 57 | + return summary_command |
0 commit comments