Skip to content

Commit

Permalink
Fixed json outputs
Browse files Browse the repository at this point in the history
  • Loading branch information
Corey White committed Aug 29, 2024
1 parent d01fb11 commit 3172243
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 30 deletions.
18 changes: 15 additions & 3 deletions src/temporal/t.stac/libstac/staclib.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import json
from datetime import datetime
from dateutil import parser
from io import StringIO
from pprint import pprint
import grass.script as gs
from grass.exceptions import CalledModuleError
from grass.pygrass.vector import VectorTopo
Expand Down Expand Up @@ -90,7 +92,7 @@ def get_all_collections(self):
gs.fatal(_("Error getting collections: {}".format(e)))

def get_collection(self, collection_id):
"""Get a collection from STAC Client"""
"""Get a collection frofrom io import StringIOm STAC Client"""
try:
collection = self.client.get_collection(collection_id)
self.collection = collection.to_dict()
Expand Down Expand Up @@ -120,7 +122,7 @@ def search_api(self, **kwargs):
gs.fatal(_("Error searching STAC API: {}".format(e)))

try:
sys.stdout.write(f"Search Matched: {search.matched()} items\n")
gs.message(_(f"Search Matched: {search.matched()} items"))
except e:
gs.warning(_(f"No items found: {e}"))
return None
Expand Down Expand Up @@ -267,6 +269,17 @@ def print_summary(data, depth=1):
sys.stdout.write(f"# {indentation}{key}: {value}\n")


def print_json_to_stdout(data, pretty=False):
"""Pretty print data to stdout"""
if pretty:
output = StringIO()
pprint(data, stream=output)
sys.stdout.write(output.getvalue())
else:
json_output = json.dumps(data)
sys.stdout.write(json_output)


def print_list_attribute(data, title):
"Print a list attribute"
sys.stdout.write(f"{'-' * 75}\n")
Expand Down Expand Up @@ -403,7 +416,6 @@ def region_to_wgs84_decimal_degrees_bbox():
float(c)
for c in [region["ll_w"], region["ll_s"], region["ll_e"], region["ll_n"]]
]
sys.stdout.write("BBOX: {}\n".format(bbox))
return bbox


Expand Down
8 changes: 1 addition & 7 deletions src/temporal/t.stac/t.stac.catalog/t.stac.catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,7 @@ def main():
return None
else:
client_dict = client.to_dict()
if pretty_print:
output = StringIO()
pprint(client_dict, stream=output)
sys.stdout.write(output.getvalue())
else:
json_output = json.dumps(client.to_dict())
sys.stdout.write(json_output)
libstac.print_json_to_stdout(client_dict, pretty_print)

except Exception as e:
gs.fatal(_("Error: {}".format(e)))
Expand Down
10 changes: 2 additions & 8 deletions src/temporal/t.stac/t.stac.collection/t.stac.collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,8 @@ def main():
if basic_info:
return libstac.print_basic_collection_info(collection_dict)
return libstac.print_summary(collection_dict)
else:
if pretty_print:
output = StringIO()
pprint(collection_dict, stream=output)
sys.stdout.write(output.getvalue())
else:
json_output = json.dumps(collection_dict)
sys.stdout.write(json_output)
elif format == "json":
return libstac.print_json_to_stdout(collection_dict, pretty_print)


if __name__ == "__main__":
Expand Down
32 changes: 20 additions & 12 deletions src/temporal/t.stac/t.stac.item/t.stac.item.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@
# % description: Dowload and import assets
# %end

# %flag
# % key: p
# % description: Pretty print the JSON output
# %end

# %option G_OPT_M_NPROCS
# %end

Expand All @@ -261,6 +266,7 @@
import sys
from pprint import pprint
import json
from io import StringIO
from contextlib import contextmanager
import grass.script as gs
from grass.pygrass.utils import get_lib_path
Expand Down Expand Up @@ -347,6 +353,7 @@ def main():
item_metadata = flags["i"]
asset_metadata = flags["a"]
download = flags["d"]
pretty_print = flags["p"] # optional

# Output options
strds_output = options["strds_output"] # optional
Expand Down Expand Up @@ -378,13 +385,9 @@ def main():
if format == "plain":
return libstac.collection_metadata(collection)
elif format == "json":
return json.dumps(collection)
else:
# Return plain text by default
return libstac.collection_metadata(collection)
return libstac.print_json_to_stdout(collection, pretty_print)

# Start item search

if intersects:
# Convert the vector to a geojson
output_geojson = "tmp_stac_intersects.geojson"
Expand All @@ -403,7 +406,7 @@ def main():

# Set the bbox to the current region if the user did not specify the bbox or intersects option
if not bbox and not intersects:
gs.message(_("Setting bbox to current region: {}".format(bbox)))
gs.verbose(_("Setting bbox to current region: {}".format(bbox)))
bbox = libstac.region_to_wgs84_decimal_degrees_bbox()

if datetime:
Expand Down Expand Up @@ -450,12 +453,14 @@ def main():
# Report item metadata
if item_metadata:
if format == "plain":
gs.message(_("bbox: {}\n".format(bbox)))
gs.message(_(f"Items Found: {len(list(items))}"))
for item in items:
stac_helper.report_stac_item(item)
return None
if format == "json":
return json.dumps([item.to_dict() for item in items])
item_list = [item.to_dict() for item in items]
return libstac.print_json_to_stdout(item_list, pretty_print)

for item in items:
asset = collect_item_assets(item, asset_keys, asset_roles=item_roles)
Expand All @@ -466,13 +471,16 @@ def main():
strds_output = os.path.abspath(strds_output)
libstac.register_strds_from_items(collection_items_assets, strds_output)

gs.message(_(f"{len(collection_items_assets)} Assets Ready for download..."))
if asset_metadata:
for asset in collection_items_assets:
if format == "plain":
if format == "plain":
gs.message(
_(f"{len(collection_items_assets)} Assets Ready for download...")
)
for asset in collection_items_assets:
libstac.report_plain_asset_summary(asset)
if format == "json":
return pprint(asset)

if format == "json":
return libstac.print_json_to_stdout(collection_items_assets, pretty_print)

if download:
# Download and Import assets
Expand Down

0 comments on commit 3172243

Please sign in to comment.