|
| 1 | +# Run with `uv run examples/seed-db.py` |
| 2 | +# /// script |
| 3 | +# dependencies = [ |
| 4 | +# "pystac", |
| 5 | +# "pystac-client", |
| 6 | +# "stacrs", |
| 7 | +# "pgstacrs", |
| 8 | +# ] |
| 9 | +# /// |
| 10 | +# ruff: noqa |
| 11 | + |
| 12 | +import asyncio |
| 13 | +import logging |
| 14 | +import os |
| 15 | + |
| 16 | +import stacrs |
| 17 | +from pgstacrs import Client as PgstacClient |
| 18 | +from pystac import Collection, Extent, ItemCollection |
| 19 | +from pystac_client import Client as PystacClient |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +async def get_data_set( |
| 25 | + dataset_path: str, bbox: list[float], collections: str, max_items: int |
| 26 | +): |
| 27 | + if not os.path.exists(dataset_path): |
| 28 | + logger.info(f"Downloading dataset to {dataset_path}") |
| 29 | + client = PystacClient.open( |
| 30 | + "https://planetarycomputer.microsoft.com/api/stac/v1" |
| 31 | + ) |
| 32 | + item_search = client.search( |
| 33 | + bbox=bbox, collections=collections, max_items=max_items |
| 34 | + ) |
| 35 | + items = item_search.item_collection() |
| 36 | + await stacrs.write(dataset_path, list(item.to_dict() for item in items)) |
| 37 | + else: |
| 38 | + logger.info(f"Loading dataset from {dataset_path}") |
| 39 | + item_collection = await stacrs.read(dataset_path) |
| 40 | + items = ItemCollection.from_dict(item_collection) |
| 41 | + |
| 42 | + assert os.path.exists(dataset_path), f"Dataset {dataset_path} does not exist" |
| 43 | + return items |
| 44 | + |
| 45 | + |
| 46 | +async def seed_db(items: ItemCollection, db_url: str): |
| 47 | + logger.info(f"Seeding database with {len(items)} items") |
| 48 | + extent = Extent.from_items(items) |
| 49 | + collection = Collection( |
| 50 | + "naip", "NAIP data in the Planetary Computer", extent=extent |
| 51 | + ) |
| 52 | + items = list( |
| 53 | + item.to_dict(transform_hrefs=False) for item in items |
| 54 | + ) # https://github.com/stac-utils/pystac/issues/960 |
| 55 | + |
| 56 | + pgstac_client = await PgstacClient.open(db_url) |
| 57 | + await pgstac_client.upsert_collection(collection.to_dict()) |
| 58 | + _ = await pgstac_client.upsert_items(items) |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + logging.basicConfig(level=logging.INFO) |
| 63 | + |
| 64 | + async def main(): |
| 65 | + colorado_naip = await get_data_set( |
| 66 | + dataset_path="./naip.parquet", |
| 67 | + bbox=[-109.0591, 36.9927, -102.04212, 41.0019], |
| 68 | + collections="naip", |
| 69 | + max_items=10000, |
| 70 | + ) |
| 71 | + await seed_db( |
| 72 | + items=colorado_naip, |
| 73 | + db_url="postgresql://username:password@localhost:5439/postgis", |
| 74 | + ) |
| 75 | + |
| 76 | + asyncio.run(main()) |
0 commit comments