!pip install up42-py --upgrade -q
import up42, geojson, pathlibfrom datetime import date, timedeltafrom itertools import islicefrom IPython.display import ImageRun the cell below to create a credentials.json file in a directory named .up42 in your home folder.
# Defines the credentials file path if it doesn't existcredentials_file_path = pathlib.Path.home().joinpath(".up42/credentials.json")credentials_file_path.parent.mkdir(parents=True, exist_ok=True)credentials_file_path.touch(exist_ok=True)
# Prints the path to the fileprint(f"Credentials file is located at: {credentials_file_path}")- Click the link above to the created file and paste the following code:
JSON {"username": "<your-email-address>","password": "<your-password>"} - Retrieve the email address and password used for logging into the console. Use them as values for
usernameandpassword. - Save the
credentials.jsonfile.
up42.authenticate(cfg_file=credentials_file_path)
# Use region if you're logging with the NSG service# up42.authenticate(cfg_file=credentials_file_path, region="sa")
catalog = up42.catalog_client()Search the catalog to find a full scene that fits your requirements. The search covers all catalog collections. To limit it to one or more collections, add the collections parameter with their IDs, for example collections=["phr", "spot"].
# Define the time interval to search the last 3 monthsend_date = date.today()start_date = end_date - timedelta(days=90)
# Define search geometrygeometry = { "type": "Polygon", "coordinates": [ [ [13.369713, 52.452327], [13.369713, 52.470760], [13.339159, 52.470760], [13.339159, 52.452327], [13.369713, 52.452327], ] ],}
# Search for scenesitems = list( catalog.search( intersects=geometry, datetime=f"{start_date}/{end_date}", filter={ "op": "and", "args": [ {"op": "<", "args": [{"property": "eo:cloud_cover"}, 20]}, {"op": "<=", "args": [{"property": "gsd"}, 0.5]}, ], }, max_items=100, ).items())Output the scenes that match the specified parameters.
print(f"\nFound {len(items)} scenes matching the criteria:\n")for item in islice(items, 3): # Print first 3 print(f"- Scene ID: {item.id}") print(f" Acquisition date: {item.datetime}") print(f" Cloud coverage: {item.properties.get('eo:cloud_cover')}%") print(f" Resolution: {item.properties.get('gsd')} m\n")Some data hosts provide free, low-resolution quicklooks that you can view before creating an order:
- Quicklooks are previews of full scenes. Some quicklooks may not fully match the scene they represent.
- Thumbnails are small, light-weighted previews of full scenes. For some data hosts, thumbnails can be cropped and rotated compared to quicklooks.
# Create an iterator to view quicklooks from search resultsql_items = (item for item in items if "quicklook" in item.assets)Run this cell to view quicklooks from search results one by one:
# Select the next scene that provides a quicklookitem = next(ql_items, None)if item is None: raise RuntimeError("No scenes with a quicklook were found.")print(f"Collection title: {item.get_collection().title}")print(f"Scene ID: {item.id}") # This is needed for ordering
# Download quicklook to quicklooks directoryquicklooks_dir = pathlib.Path("quicklooks")quicklooks_dir.mkdir(exist_ok=True)quicklook_path = item.assets["quicklook"].file.download(quicklooks_dir)Image(quicklook_path)Data products are a type of imagery with a specific geometric and radiometric processing level and file format. All collections have different data products corresponding to their technical specifications.
# Provide scene ID or default to current quicklookselected_id = input(f"Enter scene ID [{item.id}]: ").strip() or item.idmatches = [scene for scene in items if scene.id == selected_id]if len(matches) != 1: raise RuntimeError( f"Expected one search result with scene ID {selected_id}, found {len(matches)}." )item = matches[0]collection = item.get_collection()# Find data products available for the scene previewed abovedata_products = { name: asset.extra_fields["id"] for name, asset in collection.assets.items() if "data" in (asset.roles or [])}
for name in data_products: asset = collection.assets[name] print(f"- Title: {asset.title}") print(f" Data product name: {name}") print(f" Data product ID: {asset.extra_fields.get('id')}") print(f" Description: {asset.description}\n")# Select a data product for ordering from the ones printed aboveavailable = list(data_products)if not available: raise RuntimeError("No data products are available for this scene.")default_name = available[0]data_product_name = ( input(f"Enter data product name [{default_name}]: ").strip() or default_name)if data_product_name not in data_products: raise RuntimeError( f"{data_product_name} is not a data product of this scene. " f"Available products: {', '.join(available)}." )data_product_id = data_products[data_product_name]Once you’ve found a scene you want to order, check the requirements of its collection and review its EULA.
Some collections require an access approval before you can order them. Check if the collection of the chosen scene requires one.
# Retrieve the selected collectionprint(f"Collection ID: {collection.id}")print(f"Collection title: {collection.title}")
if collection.extra_fields.get("access:approval_required"): print("You need to request access first")else: print("No access request is required")If needed, request access to the collection. Your request will be reviewed in up to 3 working days. You’ll get an email once a decision has been reached.
If you want to order the collection for the first time, review and accept its end-user license agreement (EULA). If a EULA is updated, you need to re-accept it before creating your next order.
Create an order template for the chosen scene and data product.
features = geojson.FeatureCollection(features=[geojson.Feature(geometry=geometry)])order_template = up42.BatchOrderTemplate( data_product_id=data_product_id, display_name=f"{data_product_name}-{date.today()}", features=features, params={"id": item.id}, tags=["sdk", data_product_name],)Before creating an order, estimate the price in UP42 credits. The factors considered in the final price calculation are the size of the area of interest, the data collection, and the type of data product.
order_template.estimateThe response returns the overall credit amount that will be deducted from your credit balance if you decide to proceed with the ordering.
Create an order with the requested parameters.
Credits will be deducted upon successful completion of the created catalog order. The transaction can’t be reversed.
order_references = order_template.place()order_reference = order_references[0]if not hasattr(order_reference, "order"): raise RuntimeError(order_reference.message)order = order_reference.orderorderTo learn about the time frames of catalog orders, see Asset delivery time.
Check the status of your order. The following order statuses mean you can download assets from storage:
BEING_FULFILLEDSome order assets might have been delivered.FULFILLEDAll order assets have been delivered.
order.statusYou can also track the order until it is fulfilled. Tracking waits until the status is FULFILLED and raises an error if the order fails or is canceled.
order.track(report_time=150)