Skip to content

Sources — geocatalog.sources

Discover scenes in external archives: the Source protocol, the STAC / CMR / earthaccess / Earth Engine adapters, and building a catalog straight from STAC. Adapters are extras-gated and imported lazily.

Protocol

geocatalog.sources.Source

Bases: Protocol

A remote catalog that can be queried by bounds + interval.

Implementations live in geocatalog._src.sources.<name> and are extras-gated: EarthAccessSource requires pip install 'geotoolz-catalog[earthaccess]', etc. Importing this Protocol never pulls in any optional dependency.

Two methods. query returns an iterator (so adapters can stream paginated results); auth_status is the introspection hook callers use to fail fast.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/_base.py
@runtime_checkable
class Source(Protocol):
    """A remote catalog that can be queried by bounds + interval.

    Implementations live in `geocatalog._src.sources.<name>` and are
    extras-gated: ``EarthAccessSource`` requires
    ``pip install 'geotoolz-catalog[earthaccess]'``, etc. Importing this
    Protocol never pulls in any optional dependency.

    Two methods. ``query`` returns an iterator (so adapters can
    stream paginated results); ``auth_status`` is the introspection
    hook callers use to fail fast.
    """

    #: Stable adapter name. Used as the value of ``SourceRow.source``
    #: and as a filter key in matchups (``primary={"source": "earthaccess"}``).
    name: str

    def query(
        self,
        bounds: Bounds,
        interval: pd.Interval | None = None,
        *,
        collection: str | None = None,
        filters: Mapping[str, Any] | None = None,
        limit: int | None = None,
    ) -> Iterator[SourceRow]:
        """Yield matching rows from the upstream catalog.

        Args:
            bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
            interval: Optional time window. ``None`` means no temporal
                filter (the adapter may impose its own default if the
                upstream API requires one).
            collection: Upstream collection / short-name. Adapters
                that target a single collection may ignore this; most
                require it.
            filters: Free-form key/value pairs forwarded to the
                upstream API (e.g. STAC's CQL-2 filters, earthaccess's
                ``cloud_cover``). Adapter-specific; unknown keys are
                ignored or rejected per the adapter's policy.
            limit: Cap on the number of rows returned. ``None`` means
                no cap (paginate all results); ``0`` yields nothing and
                makes no request (a dry run); a negative value raises
                `ValueError`. Every adapter follows this — see
                `wants_no_rows`.

        Yields:
            `SourceRow` instances; never opens or downloads data.
        """
        ...

    def auth_status(self) -> AuthStatus:
        """Report whether the adapter can talk to its upstream.

        Never raises. Tools can call this before ``query`` to surface
        login problems early; ``query`` itself raises on auth failures.
        """
        ...

auth_status()

Report whether the adapter can talk to its upstream.

Never raises. Tools can call this before query to surface login problems early; query itself raises on auth failures.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/_base.py
def auth_status(self) -> AuthStatus:
    """Report whether the adapter can talk to its upstream.

    Never raises. Tools can call this before ``query`` to surface
    login problems early; ``query`` itself raises on auth failures.
    """
    ...

query(bounds, interval=None, *, collection=None, filters=None, limit=None)

Yield matching rows from the upstream catalog.

Parameters:

Name Type Description Default
bounds Bounds

(xmin, ymin, xmax, ymax) in EPSG:4326.

required
interval Interval | None

Optional time window. None means no temporal filter (the adapter may impose its own default if the upstream API requires one).

None
collection str | None

Upstream collection / short-name. Adapters that target a single collection may ignore this; most require it.

None
filters Mapping[str, Any] | None

Free-form key/value pairs forwarded to the upstream API (e.g. STAC's CQL-2 filters, earthaccess's cloud_cover). Adapter-specific; unknown keys are ignored or rejected per the adapter's policy.

None
limit int | None

Cap on the number of rows returned. None means no cap (paginate all results); 0 yields nothing and makes no request (a dry run); a negative value raises ValueError. Every adapter follows this — see wants_no_rows.

None

Yields:

Type Description
SourceRow

SourceRow instances; never opens or downloads data.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/_base.py
def query(
    self,
    bounds: Bounds,
    interval: pd.Interval | None = None,
    *,
    collection: str | None = None,
    filters: Mapping[str, Any] | None = None,
    limit: int | None = None,
) -> Iterator[SourceRow]:
    """Yield matching rows from the upstream catalog.

    Args:
        bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
        interval: Optional time window. ``None`` means no temporal
            filter (the adapter may impose its own default if the
            upstream API requires one).
        collection: Upstream collection / short-name. Adapters
            that target a single collection may ignore this; most
            require it.
        filters: Free-form key/value pairs forwarded to the
            upstream API (e.g. STAC's CQL-2 filters, earthaccess's
            ``cloud_cover``). Adapter-specific; unknown keys are
            ignored or rejected per the adapter's policy.
        limit: Cap on the number of rows returned. ``None`` means
            no cap (paginate all results); ``0`` yields nothing and
            makes no request (a dry run); a negative value raises
            `ValueError`. Every adapter follows this — see
            `wants_no_rows`.

    Yields:
        `SourceRow` instances; never opens or downloads data.
    """
    ...

geocatalog.sources.SourceRow dataclass

Normalized output of every Source.query adapter.

Decoupled from the existing in-catalog CatalogRow because the set of fields is broader (STAC-style asset map, per-row provenance, sensor-specific properties). Ingestion maps SourceRow to a CatalogRow by promoting the primary asset to filepath and folding the rest into extras. See design §4.3.

Attributes:

Name Type Description
id str

Stable identifier — granule UR, STAC item id, EE asset path. Round-trips into items.parquet as the primary key.

source str

Stable adapter name ("earthaccess", "stac.pc", "gee", "cmr"). Lets matchups filter by origin.

collection str

Upstream collection identifier — e.g. MOD09GA, sentinel-2-l2a, COPERNICUS/S2_SR_HARMONIZED.

geometry BaseGeometry

Footprint polygon (or multipolygon) in EPSG:4326. The catalog will reproject into its target CRS at ingestion time.

interval Interval

Observation time window. closed='both'; for instantaneous granules time_start == time_end.

assets Mapping[str, str]

Mapping of asset key → URI. For STAC this is the native asset map; for earthaccess it's the granule's data-URL set; for GEE it's a single {"asset": <path>}.

properties Mapping[str, Any]

Sensor-specific metadata — cloud cover, sun zenith, orbit number, processing level, etc. Carried opaquely.

provenance Mapping[str, Any]

{"query_id": ..., "fetched_at": ..., "source_version": ...}. Stamped by Source.query so re-runs are traceable.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/_base.py
@dataclasses.dataclass(frozen=True)
class SourceRow:
    """Normalized output of every ``Source.query`` adapter.

    Decoupled from the existing in-catalog ``CatalogRow`` because the
    set of fields is broader (STAC-style asset map, per-row provenance,
    sensor-specific properties). Ingestion maps `SourceRow` to a
    ``CatalogRow`` by promoting the primary asset to ``filepath`` and
    folding the rest into ``extras``. See design §4.3.

    Attributes:
        id: Stable identifier — granule UR, STAC item id, EE asset
            path. Round-trips into ``items.parquet`` as the primary key.
        source: Stable adapter name (``"earthaccess"``, ``"stac.pc"``,
            ``"gee"``, ``"cmr"``). Lets matchups filter by origin.
        collection: Upstream collection identifier — e.g.
            ``MOD09GA``, ``sentinel-2-l2a``,
            ``COPERNICUS/S2_SR_HARMONIZED``.
        geometry: Footprint polygon (or multipolygon) in EPSG:4326.
            The catalog will reproject into its target CRS at
            ingestion time.
        interval: Observation time window. ``closed='both'``; for
            instantaneous granules ``time_start == time_end``.
        assets: Mapping of asset key → URI. For STAC this is the
            native asset map; for earthaccess it's the granule's
            data-URL set; for GEE it's a single ``{"asset": <path>}``.
        properties: Sensor-specific metadata — cloud cover, sun zenith,
            orbit number, processing level, etc. Carried opaquely.
        provenance: ``{"query_id": ..., "fetched_at": ...,
            "source_version": ...}``. Stamped by `Source.query`
            so re-runs are traceable.
    """

    id: str
    source: str
    collection: str
    geometry: shapely.geometry.base.BaseGeometry
    interval: pd.Interval
    assets: Mapping[str, str] = dataclasses.field(default_factory=dict)
    properties: Mapping[str, Any] = dataclasses.field(default_factory=dict)
    provenance: Mapping[str, Any] = dataclasses.field(default_factory=dict)

geocatalog.sources.AuthStatus dataclass

Reported by Source.auth_status so callers can fail fast.

Adapters never raise on construction; they raise on query / ingest if credentials are missing. auth_status is the introspection hook for tooling that wants to surface "you need to log in" before kicking off a long workflow.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/_base.py
@dataclasses.dataclass(frozen=True)
class AuthStatus:
    """Reported by `Source.auth_status` so callers can fail fast.

    Adapters never raise on construction; they raise on
    ``query`` / ``ingest`` if credentials are missing. ``auth_status``
    is the introspection hook for tooling that wants to surface "you
    need to log in" before kicking off a long workflow.
    """

    source: str
    authenticated: bool
    detail: str | None = None

STAC (extras: [stac])

geocatalog.sources.STACSource

Bases: Source

STAC API data discovery.

Parameters:

Name Type Description Default
endpoint str

Root STAC API URL (the catalog landing page).

required
sign_assets bool

If True, sign asset URLs on access (needed for Planetary Computer's blob-storage tokens). Defaults to whatever the factory method sets.

False
name str

Stable adapter identifier. Defaults to "stac"; factories override with "stac.pc", "stac.es".

'stac'

Examples:

>>> src = STACSource.planetary_computer()
>>> rows = list(src.query(
...     bounds=(-10, 35, 5, 45),
...     interval=pd.Interval(
...         pd.Timestamp("2024-06-01", tz="UTC"),
...         pd.Timestamp("2024-06-30", tz="UTC"),
...         closed="both",
...     ),
...     collection="sentinel-2-l2a",
...     filters={"eo:cloud_cover": {"lt": 20}},
...     limit=10,
... ))
>>> rows[0].assets["B04"]  # signed red-band URL
'https://sentinel2l2a01.blob.core.windows.net/...?...&sig=...'
Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/stac.py
class STACSource(Source):
    """STAC API data discovery.

    Args:
        endpoint: Root STAC API URL (the catalog landing page).
        sign_assets: If ``True``, sign asset URLs on access (needed
            for Planetary Computer's blob-storage tokens). Defaults
            to whatever the factory method sets.
        name: Stable adapter identifier. Defaults to ``"stac"``;
            factories override with ``"stac.pc"``, ``"stac.es"``.

    Examples:
        >>> src = STACSource.planetary_computer()
        >>> rows = list(src.query(
        ...     bounds=(-10, 35, 5, 45),
        ...     interval=pd.Interval(
        ...         pd.Timestamp("2024-06-01", tz="UTC"),
        ...         pd.Timestamp("2024-06-30", tz="UTC"),
        ...         closed="both",
        ...     ),
        ...     collection="sentinel-2-l2a",
        ...     filters={"eo:cloud_cover": {"lt": 20}},
        ...     limit=10,
        ... ))
        >>> rows[0].assets["B04"]  # signed red-band URL
        'https://sentinel2l2a01.blob.core.windows.net/...?...&sig=...'
    """

    def __init__(
        self,
        endpoint: str,
        *,
        sign_assets: bool = False,
        name: str = "stac",
    ) -> None:
        if pystac_client is None:
            raise missing_extra(
                "`STACSource`",
                "stac",
                packages="pystac-client>=0.7 planetary-computer>=1.0",
            )
        if sign_assets and planetary_computer is None:
            raise missing_extra(
                "`STACSource(sign_assets=True)`",
                "stac",
                packages="pystac-client>=0.7 planetary-computer>=1.0",
            )
        self.endpoint = endpoint
        self.sign_assets = sign_assets
        self.name = name
        # Cache the client across calls — pystac-client's Client.open
        # does a network round-trip to fetch the root catalog, and
        # there's no reason to redo it for repeated queries.
        self._client: _pystac_client_t.Client | None = None

    @classmethod
    def planetary_computer(cls) -> STACSource:
        """Microsoft Planetary Computer — signs blob URLs automatically."""
        return cls(_PC_ENDPOINT, sign_assets=True, name="stac.pc")

    @classmethod
    def earth_search(cls) -> STACSource:
        """Element 84 Earth Search — public AWS-hosted Sentinel/Landsat."""
        return cls(_EARTH_SEARCH_ENDPOINT, sign_assets=False, name="stac.es")

    @property
    def client(self) -> _pystac_client_t.Client:
        """Lazily-opened, cached `pystac_client.Client`."""
        if self._client is None:
            assert pystac_client is not None  # guarded in __init__
            self._client = pystac_client.Client.open(self.endpoint)
        return self._client

    def query(
        self,
        bounds: Bounds,
        interval: pd.Interval | None = None,
        *,
        collection: str | None = None,
        filters: Mapping[str, Any] | None = None,
        limit: int | None = None,
    ) -> Iterator[SourceRow]:
        """Yield `SourceRow`s for STAC items matching the query.

        Args:
            bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
            interval: Optional time window. STAC's ``datetime`` param
                takes ``"start/end"`` ISO 8601.
            collection: STAC collection id (e.g. ``"sentinel-2-l2a"``,
                ``"landsat-c2-l2"``). Many STAC servers will refuse
                searches without one; pystac-client itself does not
                require it.
            filters: Forwarded to pystac-client's ``query`` keyword
                (the ``eo:cloud_cover`` / property-filter syntax).
                For CQL-2 use a ``"filter"`` key inside this mapping
                — it falls through to pystac-client's ``filter``
                argument.
            limit: Cap on the number of items. ``None`` = paginate
                all results; ``0`` yields nothing without a request;
                negative raises.

        Yields:
            `SourceRow` per matching STAC item; never opens or
            downloads asset data. Asset URLs are signed in place if
            ``self.sign_assets`` is True.
        """
        # Build query_id once per `query()` call so every row from a
        # single search shares provenance metadata (useful when the
        # rows are persisted side-by-side and a user wants to know
        # "which call produced these?").
        # pystac-client reads `max_items=0` as "no limit"; `limit=0`
        # means nothing here (#237).
        if wants_no_rows(limit):
            return
        query_id = uuid.uuid4().hex
        fetched_at = datetime.now(tz=UTC)
        source_version = _pystac_client_version()

        search_kwargs: dict[str, Any] = {"bbox": list(bounds)}
        if collection is not None:
            search_kwargs["collections"] = [collection]
        if interval is not None:
            search_kwargs["datetime"] = _interval_to_stac_datetime(interval)
        if limit is not None:
            search_kwargs["max_items"] = limit
        # `filters` is a soft passthrough: a "filter" key goes to
        # pystac-client's `filter=` (CQL-2), everything else goes to
        # `query=` (legacy property-filter syntax). Both round-trip
        # cleanly through the persisted catalog's `queries.parquet`
        # row.
        if filters is not None:
            filters = dict(filters)
            cql2 = filters.pop("filter", None)
            if cql2 is not None:
                search_kwargs["filter"] = cql2
            if filters:
                search_kwargs["query"] = filters

        logger.debug("STAC search on {}: {!r}", self.endpoint, search_kwargs)
        search = self.client.search(**search_kwargs)
        for item in search.items():
            if self.sign_assets:
                # planetary_computer.sign returns a new Item with
                # signed asset hrefs; the rest of the item is
                # untouched.
                item = planetary_computer.sign(item)
            try:
                row = _item_to_source_row(
                    item,
                    source_name=self.name,
                    query_id=query_id,
                    fetched_at=fetched_at,
                    source_version=source_version,
                )
            except UndecodableItemError as exc:
                # Same policy as the CMR / earthaccess adapters: an item
                # with no footprint or time can't become a row; warn and
                # move on rather than abort the whole search.
                logger.warning("{}: skipping item {!r}: {}", self.name, item.id, exc)
                continue
            yield row

    def auth_status(self) -> AuthStatus:
        """Open the client and probe the root catalog.

        Most public STAC catalogs (PC, Earth Search) don't actually
        gate the search endpoint — auth is on individual assets
        (PC blob SAS, USGS M2M token). So "authenticated" here
        really means "the endpoint is reachable and serves STAC".
        """
        try:
            _ = self.client.get_self_href()
        except Exception as exc:
            return AuthStatus(
                source=self.name,
                authenticated=False,
                detail=f"could not reach {self.endpoint}: {exc}",
            )
        return AuthStatus(
            source=self.name,
            authenticated=True,
            detail=f"reachable at {self.endpoint}",
        )

client property

Lazily-opened, cached pystac_client.Client.

auth_status()

Open the client and probe the root catalog.

Most public STAC catalogs (PC, Earth Search) don't actually gate the search endpoint — auth is on individual assets (PC blob SAS, USGS M2M token). So "authenticated" here really means "the endpoint is reachable and serves STAC".

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/stac.py
def auth_status(self) -> AuthStatus:
    """Open the client and probe the root catalog.

    Most public STAC catalogs (PC, Earth Search) don't actually
    gate the search endpoint — auth is on individual assets
    (PC blob SAS, USGS M2M token). So "authenticated" here
    really means "the endpoint is reachable and serves STAC".
    """
    try:
        _ = self.client.get_self_href()
    except Exception as exc:
        return AuthStatus(
            source=self.name,
            authenticated=False,
            detail=f"could not reach {self.endpoint}: {exc}",
        )
    return AuthStatus(
        source=self.name,
        authenticated=True,
        detail=f"reachable at {self.endpoint}",
    )

Element 84 Earth Search — public AWS-hosted Sentinel/Landsat.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/stac.py
@classmethod
def earth_search(cls) -> STACSource:
    """Element 84 Earth Search — public AWS-hosted Sentinel/Landsat."""
    return cls(_EARTH_SEARCH_ENDPOINT, sign_assets=False, name="stac.es")

planetary_computer() classmethod

Microsoft Planetary Computer — signs blob URLs automatically.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/stac.py
@classmethod
def planetary_computer(cls) -> STACSource:
    """Microsoft Planetary Computer — signs blob URLs automatically."""
    return cls(_PC_ENDPOINT, sign_assets=True, name="stac.pc")

query(bounds, interval=None, *, collection=None, filters=None, limit=None)

Yield SourceRows for STAC items matching the query.

Parameters:

Name Type Description Default
bounds Bounds

(xmin, ymin, xmax, ymax) in EPSG:4326.

required
interval Interval | None

Optional time window. STAC's datetime param takes "start/end" ISO 8601.

None
collection str | None

STAC collection id (e.g. "sentinel-2-l2a", "landsat-c2-l2"). Many STAC servers will refuse searches without one; pystac-client itself does not require it.

None
filters Mapping[str, Any] | None

Forwarded to pystac-client's query keyword (the eo:cloud_cover / property-filter syntax). For CQL-2 use a "filter" key inside this mapping — it falls through to pystac-client's filter argument.

None
limit int | None

Cap on the number of items. None = paginate all results; 0 yields nothing without a request; negative raises.

None

Yields:

Type Description
SourceRow

SourceRow per matching STAC item; never opens or

SourceRow

downloads asset data. Asset URLs are signed in place if

SourceRow

self.sign_assets is True.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/stac.py
def query(
    self,
    bounds: Bounds,
    interval: pd.Interval | None = None,
    *,
    collection: str | None = None,
    filters: Mapping[str, Any] | None = None,
    limit: int | None = None,
) -> Iterator[SourceRow]:
    """Yield `SourceRow`s for STAC items matching the query.

    Args:
        bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
        interval: Optional time window. STAC's ``datetime`` param
            takes ``"start/end"`` ISO 8601.
        collection: STAC collection id (e.g. ``"sentinel-2-l2a"``,
            ``"landsat-c2-l2"``). Many STAC servers will refuse
            searches without one; pystac-client itself does not
            require it.
        filters: Forwarded to pystac-client's ``query`` keyword
            (the ``eo:cloud_cover`` / property-filter syntax).
            For CQL-2 use a ``"filter"`` key inside this mapping
            — it falls through to pystac-client's ``filter``
            argument.
        limit: Cap on the number of items. ``None`` = paginate
            all results; ``0`` yields nothing without a request;
            negative raises.

    Yields:
        `SourceRow` per matching STAC item; never opens or
        downloads asset data. Asset URLs are signed in place if
        ``self.sign_assets`` is True.
    """
    # Build query_id once per `query()` call so every row from a
    # single search shares provenance metadata (useful when the
    # rows are persisted side-by-side and a user wants to know
    # "which call produced these?").
    # pystac-client reads `max_items=0` as "no limit"; `limit=0`
    # means nothing here (#237).
    if wants_no_rows(limit):
        return
    query_id = uuid.uuid4().hex
    fetched_at = datetime.now(tz=UTC)
    source_version = _pystac_client_version()

    search_kwargs: dict[str, Any] = {"bbox": list(bounds)}
    if collection is not None:
        search_kwargs["collections"] = [collection]
    if interval is not None:
        search_kwargs["datetime"] = _interval_to_stac_datetime(interval)
    if limit is not None:
        search_kwargs["max_items"] = limit
    # `filters` is a soft passthrough: a "filter" key goes to
    # pystac-client's `filter=` (CQL-2), everything else goes to
    # `query=` (legacy property-filter syntax). Both round-trip
    # cleanly through the persisted catalog's `queries.parquet`
    # row.
    if filters is not None:
        filters = dict(filters)
        cql2 = filters.pop("filter", None)
        if cql2 is not None:
            search_kwargs["filter"] = cql2
        if filters:
            search_kwargs["query"] = filters

    logger.debug("STAC search on {}: {!r}", self.endpoint, search_kwargs)
    search = self.client.search(**search_kwargs)
    for item in search.items():
        if self.sign_assets:
            # planetary_computer.sign returns a new Item with
            # signed asset hrefs; the rest of the item is
            # untouched.
            item = planetary_computer.sign(item)
        try:
            row = _item_to_source_row(
                item,
                source_name=self.name,
                query_id=query_id,
                fetched_at=fetched_at,
                source_version=source_version,
            )
        except UndecodableItemError as exc:
            # Same policy as the CMR / earthaccess adapters: an item
            # with no footprint or time can't become a row; warn and
            # move on rather than abort the whole search.
            logger.warning("{}: skipping item {!r}: {}", self.name, item.id, exc)
            continue
        yield row

earthaccess (extras: [earthaccess])

geocatalog.sources.EarthAccessSource

Bases: Source

NASA CMR / earthaccess data discovery.

Construct without arguments; authentication is handled by the underlying earthaccess library (earthaccess.login() or a netrc / token in the standard locations). Call auth_status to check whether credentials are usable.

Parameters:

Name Type Description Default
daac str | None

Optional DAAC short-name filter (e.g. "LPDAAC"). Defaults to None (search all DAACs).

None
cloud_hosted bool | None

When True, restrict to Earthdata-Cloud granules. Useful if you want direct S3 reads downstream and don't care about on-prem holdings.

None
retries int

Retries of the search call on transient failures (network errors, HTTP 408 / 429 / 5xx). 0 disables retry.

3
Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/earthaccess.py
class EarthAccessSource(Source):
    """NASA CMR / earthaccess data discovery.

    Construct without arguments; authentication is handled by the
    underlying `earthaccess` library (`earthaccess.login()` or a
    netrc / token in the standard locations). Call ``auth_status``
    to check whether credentials are usable.

    Args:
        daac: Optional DAAC short-name filter (e.g. ``"LPDAAC"``).
            Defaults to None (search all DAACs).
        cloud_hosted: When True, restrict to Earthdata-Cloud
            granules. Useful if you want direct S3 reads
            downstream and don't care about on-prem holdings.
        retries: Retries of the search call on transient failures
            (network errors, HTTP 408 / 429 / 5xx). ``0`` disables retry.
    """

    name = "earthaccess"

    def __init__(
        self,
        *,
        daac: str | None = None,
        cloud_hosted: bool | None = None,
        retries: int = 3,
    ) -> None:
        if earthaccess is None:
            raise missing_extra(
                "`EarthAccessSource`", "earthaccess", packages="earthaccess>=0.10"
            )
        self.daac = daac
        self.cloud_hosted = cloud_hosted
        self.retries = retries

    def query(
        self,
        bounds: Bounds,
        interval: pd.Interval | None = None,
        *,
        collection: str | None = None,
        filters: Mapping[str, Any] | None = None,
        limit: int | None = None,
    ) -> Iterator[SourceRow]:
        """Yield `SourceRow`s for CMR granules matching the query.

        Args:
            bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
            interval: Optional time window. earthaccess expects
                ``temporal=(date_from, date_to)``.
            collection: CMR ``short_name``. Required by CMR for
                non-trivial searches; if omitted the caller almost
                certainly gets an empty result.
            filters: Forwarded as additional kwargs to
                `earthaccess.search_data` (e.g. ``cloud_cover``,
                ``platform``, ``provider``, ``version``). Unknown
                keys silently passed through — `earthaccess` itself
                validates.
            limit: Cap on the number of granules. ``None`` → all;
                ``0`` yields nothing without a request; negative raises.

        Yields:
            `SourceRow` per matching granule.
        """
        # earthaccess reads `count=0` as "all"; `limit=0` means nothing
        # here (#237).
        if wants_no_rows(limit):
            return
        query_id = uuid.uuid4().hex
        fetched_at = datetime.now(tz=UTC)
        version = _earthaccess_version()

        kwargs: dict[str, Any] = {"bounding_box": tuple(bounds)}
        if collection is not None:
            kwargs["short_name"] = collection
        if interval is not None:
            kwargs["temporal"] = (
                pd.Timestamp(interval.left).isoformat(),
                pd.Timestamp(interval.right).isoformat(),
            )
        if self.daac is not None:
            kwargs["daac"] = self.daac
        if self.cloud_hosted is not None:
            kwargs["cloud_hosted"] = self.cloud_hosted
        if filters:
            # `earthaccess.search_data` accepts an open set of kwargs;
            # we forward everything the user passed.
            kwargs.update(filters)

        # `count=-1` means "all" in earthaccess; map our None likewise.
        count = limit if limit is not None else -1

        logger.debug("earthaccess.search_data: {!r} count={!r}", kwargs, count)
        # earthaccess returns the full result list (it has no streaming
        # search API); retry transient HTTP failures of that one call.
        granules = retry_transient_io(
            earthaccess.search_data, count=count, retries=self.retries, **kwargs
        )
        for granule in granules:
            row = _granule_to_source_row(
                granule,
                source_name=self.name,
                query_id=query_id,
                fetched_at=fetched_at,
                source_version=version,
            )
            if row is not None:
                yield row

    def auth_status(self) -> AuthStatus:
        """Check whether `earthaccess` is logged in.

        Builds a requests session via
        ``earthaccess.get_requests_https_session()`` and inspects
        the ``earthaccess.__auth__`` singleton's ``authenticated``
        flag — a cheap, non-network probe of the cached login
        state. The adapter does *not* call ``earthaccess.login()``
        automatically; surface the bare credential state and let
        the caller decide whether to prompt for credentials.
        """
        try:
            session = earthaccess.get_requests_https_session()
        except Exception as exc:
            return AuthStatus(
                source=self.name,
                authenticated=False,
                detail=f"earthaccess session unavailable: {exc}",
            )
        # The cheapest signal: was the session built from an actual
        # auth object? `earthaccess.__auth__` is the singleton.
        auth = getattr(earthaccess, "__auth__", None)
        authenticated = bool(getattr(auth, "authenticated", False))
        del session
        return AuthStatus(
            source=self.name,
            authenticated=authenticated,
            detail=(
                "earthaccess logged in"
                if authenticated
                else "earthaccess not authenticated — call earthaccess.login() "
                "or set EARTHDATA_USERNAME / EARTHDATA_PASSWORD"
            ),
        )

auth_status()

Check whether earthaccess is logged in.

Builds a requests session via earthaccess.get_requests_https_session() and inspects the earthaccess.__auth__ singleton's authenticated flag — a cheap, non-network probe of the cached login state. The adapter does not call earthaccess.login() automatically; surface the bare credential state and let the caller decide whether to prompt for credentials.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/earthaccess.py
def auth_status(self) -> AuthStatus:
    """Check whether `earthaccess` is logged in.

    Builds a requests session via
    ``earthaccess.get_requests_https_session()`` and inspects
    the ``earthaccess.__auth__`` singleton's ``authenticated``
    flag — a cheap, non-network probe of the cached login
    state. The adapter does *not* call ``earthaccess.login()``
    automatically; surface the bare credential state and let
    the caller decide whether to prompt for credentials.
    """
    try:
        session = earthaccess.get_requests_https_session()
    except Exception as exc:
        return AuthStatus(
            source=self.name,
            authenticated=False,
            detail=f"earthaccess session unavailable: {exc}",
        )
    # The cheapest signal: was the session built from an actual
    # auth object? `earthaccess.__auth__` is the singleton.
    auth = getattr(earthaccess, "__auth__", None)
    authenticated = bool(getattr(auth, "authenticated", False))
    del session
    return AuthStatus(
        source=self.name,
        authenticated=authenticated,
        detail=(
            "earthaccess logged in"
            if authenticated
            else "earthaccess not authenticated — call earthaccess.login() "
            "or set EARTHDATA_USERNAME / EARTHDATA_PASSWORD"
        ),
    )

query(bounds, interval=None, *, collection=None, filters=None, limit=None)

Yield SourceRows for CMR granules matching the query.

Parameters:

Name Type Description Default
bounds Bounds

(xmin, ymin, xmax, ymax) in EPSG:4326.

required
interval Interval | None

Optional time window. earthaccess expects temporal=(date_from, date_to).

None
collection str | None

CMR short_name. Required by CMR for non-trivial searches; if omitted the caller almost certainly gets an empty result.

None
filters Mapping[str, Any] | None

Forwarded as additional kwargs to earthaccess.search_data (e.g. cloud_cover, platform, provider, version). Unknown keys silently passed through — earthaccess itself validates.

None
limit int | None

Cap on the number of granules. None → all; 0 yields nothing without a request; negative raises.

None

Yields:

Type Description
SourceRow

SourceRow per matching granule.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/earthaccess.py
def query(
    self,
    bounds: Bounds,
    interval: pd.Interval | None = None,
    *,
    collection: str | None = None,
    filters: Mapping[str, Any] | None = None,
    limit: int | None = None,
) -> Iterator[SourceRow]:
    """Yield `SourceRow`s for CMR granules matching the query.

    Args:
        bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
        interval: Optional time window. earthaccess expects
            ``temporal=(date_from, date_to)``.
        collection: CMR ``short_name``. Required by CMR for
            non-trivial searches; if omitted the caller almost
            certainly gets an empty result.
        filters: Forwarded as additional kwargs to
            `earthaccess.search_data` (e.g. ``cloud_cover``,
            ``platform``, ``provider``, ``version``). Unknown
            keys silently passed through — `earthaccess` itself
            validates.
        limit: Cap on the number of granules. ``None`` → all;
            ``0`` yields nothing without a request; negative raises.

    Yields:
        `SourceRow` per matching granule.
    """
    # earthaccess reads `count=0` as "all"; `limit=0` means nothing
    # here (#237).
    if wants_no_rows(limit):
        return
    query_id = uuid.uuid4().hex
    fetched_at = datetime.now(tz=UTC)
    version = _earthaccess_version()

    kwargs: dict[str, Any] = {"bounding_box": tuple(bounds)}
    if collection is not None:
        kwargs["short_name"] = collection
    if interval is not None:
        kwargs["temporal"] = (
            pd.Timestamp(interval.left).isoformat(),
            pd.Timestamp(interval.right).isoformat(),
        )
    if self.daac is not None:
        kwargs["daac"] = self.daac
    if self.cloud_hosted is not None:
        kwargs["cloud_hosted"] = self.cloud_hosted
    if filters:
        # `earthaccess.search_data` accepts an open set of kwargs;
        # we forward everything the user passed.
        kwargs.update(filters)

    # `count=-1` means "all" in earthaccess; map our None likewise.
    count = limit if limit is not None else -1

    logger.debug("earthaccess.search_data: {!r} count={!r}", kwargs, count)
    # earthaccess returns the full result list (it has no streaming
    # search API); retry transient HTTP failures of that one call.
    granules = retry_transient_io(
        earthaccess.search_data, count=count, retries=self.retries, **kwargs
    )
    for granule in granules:
        row = _granule_to_source_row(
            granule,
            source_name=self.name,
            query_id=query_id,
            fetched_at=fetched_at,
            source_version=version,
        )
        if row is not None:
            yield row

CMR

geocatalog.sources.CMRSource

Bases: Source

Direct CMR REST adapter.

Construct without arguments. Anonymous queries cover most public collections; restricted ones need an EDL bearer token via the token argument.

Parameters:

Name Type Description Default
token str | None

Optional EDL bearer token for protected collections.

None
endpoint str

CMR root URL — override for non-prod environments.

_CMR_ROOT
retries int

Retries per page on transient failures (network errors, HTTP 408 / 429 / 5xx). 0 disables retry.

3
Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/cmr.py
class CMRSource(Source):
    """Direct CMR REST adapter.

    Construct without arguments. Anonymous queries cover most public
    collections; restricted ones need an EDL bearer token via the
    ``token`` argument.

    Args:
        token: Optional EDL bearer token for protected collections.
        endpoint: CMR root URL — override for non-prod environments.
        retries: Retries per page on transient failures (network
            errors, HTTP 408 / 429 / 5xx). ``0`` disables retry.
    """

    name = "cmr"

    def __init__(
        self,
        *,
        token: str | None = None,
        endpoint: str = _CMR_ROOT,
        retries: int = 3,
    ) -> None:
        self.token = token
        self.endpoint = endpoint.rstrip("/")
        self.retries = retries

    def query(
        self,
        bounds: Bounds,
        interval: pd.Interval | None = None,
        *,
        collection: str | None = None,
        filters: Mapping[str, Any] | None = None,
        limit: int | None = None,
    ) -> Iterator[SourceRow]:
        """Yield `SourceRow`s for CMR granules.

        Args:
            bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
            interval: Optional time window → ``temporal`` parameter.
            collection: CMR ``short_name``.
            filters: Forwarded directly as URL parameters. Useful for
                ``version``, ``provider``, ``platform``,
                ``cloud_cover[min]`` / ``cloud_cover[max]``, etc.
            limit: Cap on rows. ``None`` paginates all results; ``0``
                yields nothing without a request; negative raises.

        Yields:
            `SourceRow` per matching granule. Streamed via pagination
            so a large collection doesn't materialise in one chunk.
        """
        # `limit=0` is a dry run: nothing, and no request. Without this
        # guard the page-size math below would clamp to `max(..., 1)`.
        if wants_no_rows(limit):
            return

        query_id = uuid.uuid4().hex
        fetched_at = datetime.now(tz=UTC)

        clashes = sorted(set(filters or ()) & _RESERVED_PARAMS)
        if clashes:
            raise ValueError(
                f"CMRSource.query: filters {clashes} would override the "
                "parameters the adapter builds from bounds / interval / "
                "collection; pass those arguments instead."
            )
        params: dict[str, Any] = {
            "bounding_box": ",".join(str(x) for x in bounds),
        }
        if collection is not None:
            params["short_name"] = collection
        if interval is not None:
            # CMR wants RFC 3339 instants; aware inputs in other zones are
            # converted, naive ones are UTC, sub-second noise is dropped.
            params["temporal"] = (
                f"{_cmr_time(interval.left)},{_cmr_time(interval.right, upper=True)}"
            )
        for k, v in (filters or {}).items():
            # A list is sent as a repeated key (`provider=A&provider=B`, the
            # form CMR documents for provider / version); spell the key
            # `platform[]` yourself where CMR wants bracket syntax.
            params[k] = list(v) if isinstance(v, list | tuple | set) else v

        # Stream pages via the `search-after` header until done or
        # the user's limit is reached.
        emitted = 0
        search_after: str | None = None
        while True:
            page_size = (
                _CMR_PAGE_SIZE
                if limit is None
                else min(_CMR_PAGE_SIZE, max(limit - emitted, 1))
            )
            params["page_size"] = page_size
            url = f"{self.endpoint}/granules.umm_json?" + urllib.parse.urlencode(
                params, doseq=True
            )
            logger.debug("CMR GET: {!r}", url)
            data, next_search_after = retry_transient_io(
                _fetch_page,
                url,
                token=self.token,
                search_after=search_after,
                retries=self.retries,
            )
            items = data.get("items", [])
            for item in items:
                row = _cmr_item_to_source_row(
                    item,
                    source_name=self.name,
                    query_id=query_id,
                    fetched_at=fetched_at,
                )
                if row is not None:
                    yield row
                    emitted += 1
                    if limit is not None and emitted >= limit:
                        return
            if not next_search_after or not items:
                break
            search_after = next_search_after

    def auth_status(self) -> AuthStatus:
        """Probe the CMR root.

        Anonymous queries against public collections always work,
        so "authenticated" here means "we can reach the endpoint".
        Token presence is reported via `detail`.
        """
        try:
            req = urllib.request.Request(
                f"{self.endpoint}/granules.umm_json?page_size=1"
            )
            if self.token:
                req.add_header("Authorization", f"Bearer {self.token}")
            with urllib.request.urlopen(req, timeout=10.0) as resp:
                status = resp.status
        except Exception as exc:
            return AuthStatus(
                source=self.name,
                authenticated=False,
                detail=f"could not reach {self.endpoint}: {exc}",
            )
        ok = status == 200
        if ok:
            detail = f"reachable at {self.endpoint}" + (
                " (token set)" if self.token else " (anonymous)"
            )
        else:
            detail = f"{self.endpoint} returned status {status}"
        return AuthStatus(
            source=self.name,
            authenticated=ok,
            detail=detail,
        )

auth_status()

Probe the CMR root.

Anonymous queries against public collections always work, so "authenticated" here means "we can reach the endpoint". Token presence is reported via detail.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/cmr.py
def auth_status(self) -> AuthStatus:
    """Probe the CMR root.

    Anonymous queries against public collections always work,
    so "authenticated" here means "we can reach the endpoint".
    Token presence is reported via `detail`.
    """
    try:
        req = urllib.request.Request(
            f"{self.endpoint}/granules.umm_json?page_size=1"
        )
        if self.token:
            req.add_header("Authorization", f"Bearer {self.token}")
        with urllib.request.urlopen(req, timeout=10.0) as resp:
            status = resp.status
    except Exception as exc:
        return AuthStatus(
            source=self.name,
            authenticated=False,
            detail=f"could not reach {self.endpoint}: {exc}",
        )
    ok = status == 200
    if ok:
        detail = f"reachable at {self.endpoint}" + (
            " (token set)" if self.token else " (anonymous)"
        )
    else:
        detail = f"{self.endpoint} returned status {status}"
    return AuthStatus(
        source=self.name,
        authenticated=ok,
        detail=detail,
    )

query(bounds, interval=None, *, collection=None, filters=None, limit=None)

Yield SourceRows for CMR granules.

Parameters:

Name Type Description Default
bounds Bounds

(xmin, ymin, xmax, ymax) in EPSG:4326.

required
interval Interval | None

Optional time window → temporal parameter.

None
collection str | None

CMR short_name.

None
filters Mapping[str, Any] | None

Forwarded directly as URL parameters. Useful for version, provider, platform, cloud_cover[min] / cloud_cover[max], etc.

None
limit int | None

Cap on rows. None paginates all results; 0 yields nothing without a request; negative raises.

None

Yields:

Type Description
SourceRow

SourceRow per matching granule. Streamed via pagination

SourceRow

so a large collection doesn't materialise in one chunk.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/cmr.py
def query(
    self,
    bounds: Bounds,
    interval: pd.Interval | None = None,
    *,
    collection: str | None = None,
    filters: Mapping[str, Any] | None = None,
    limit: int | None = None,
) -> Iterator[SourceRow]:
    """Yield `SourceRow`s for CMR granules.

    Args:
        bounds: ``(xmin, ymin, xmax, ymax)`` in EPSG:4326.
        interval: Optional time window → ``temporal`` parameter.
        collection: CMR ``short_name``.
        filters: Forwarded directly as URL parameters. Useful for
            ``version``, ``provider``, ``platform``,
            ``cloud_cover[min]`` / ``cloud_cover[max]``, etc.
        limit: Cap on rows. ``None`` paginates all results; ``0``
            yields nothing without a request; negative raises.

    Yields:
        `SourceRow` per matching granule. Streamed via pagination
        so a large collection doesn't materialise in one chunk.
    """
    # `limit=0` is a dry run: nothing, and no request. Without this
    # guard the page-size math below would clamp to `max(..., 1)`.
    if wants_no_rows(limit):
        return

    query_id = uuid.uuid4().hex
    fetched_at = datetime.now(tz=UTC)

    clashes = sorted(set(filters or ()) & _RESERVED_PARAMS)
    if clashes:
        raise ValueError(
            f"CMRSource.query: filters {clashes} would override the "
            "parameters the adapter builds from bounds / interval / "
            "collection; pass those arguments instead."
        )
    params: dict[str, Any] = {
        "bounding_box": ",".join(str(x) for x in bounds),
    }
    if collection is not None:
        params["short_name"] = collection
    if interval is not None:
        # CMR wants RFC 3339 instants; aware inputs in other zones are
        # converted, naive ones are UTC, sub-second noise is dropped.
        params["temporal"] = (
            f"{_cmr_time(interval.left)},{_cmr_time(interval.right, upper=True)}"
        )
    for k, v in (filters or {}).items():
        # A list is sent as a repeated key (`provider=A&provider=B`, the
        # form CMR documents for provider / version); spell the key
        # `platform[]` yourself where CMR wants bracket syntax.
        params[k] = list(v) if isinstance(v, list | tuple | set) else v

    # Stream pages via the `search-after` header until done or
    # the user's limit is reached.
    emitted = 0
    search_after: str | None = None
    while True:
        page_size = (
            _CMR_PAGE_SIZE
            if limit is None
            else min(_CMR_PAGE_SIZE, max(limit - emitted, 1))
        )
        params["page_size"] = page_size
        url = f"{self.endpoint}/granules.umm_json?" + urllib.parse.urlencode(
            params, doseq=True
        )
        logger.debug("CMR GET: {!r}", url)
        data, next_search_after = retry_transient_io(
            _fetch_page,
            url,
            token=self.token,
            search_after=search_after,
            retries=self.retries,
        )
        items = data.get("items", [])
        for item in items:
            row = _cmr_item_to_source_row(
                item,
                source_name=self.name,
                query_id=query_id,
                fetched_at=fetched_at,
            )
            if row is not None:
                yield row
                emitted += 1
                if limit is not None and emitted >= limit:
                    return
        if not next_search_after or not items:
            break
        search_after = next_search_after

Earth Engine (extras: [gee])

geocatalog.sources.GEESource

Bases: Source

Google Earth Engine asset discovery.

Construct without arguments; authentication is handled by the underlying ee client (ee.Authenticate() + ee.Initialize() or a service-account credentials file). Call auth_status to check.

Parameters:

Name Type Description Default
project str | None

GCP project the EE API requests are billed to. Some collections refuse anonymous reads; pin a project here.

None
Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/gee.py
class GEESource(Source):
    """Google Earth Engine asset discovery.

    Construct without arguments; authentication is handled by the
    underlying `ee` client (`ee.Authenticate()` + `ee.Initialize()`
    or a service-account credentials file). Call ``auth_status`` to
    check.

    Args:
        project: GCP project the EE API requests are billed to. Some
            collections refuse anonymous reads; pin a project here.
    """

    name = "gee"

    def __init__(self, *, project: str | None = None) -> None:
        if ee is None:
            raise missing_extra(
                "`GEESource`", "gee", packages="earthengine-api>=0.1.380"
            )
        self.project = project

    def query(
        self,
        bounds: Bounds,
        interval: pd.Interval | None = None,
        *,
        collection: str | None = None,
        filters: Mapping[str, Any] | None = None,
        limit: int | None = None,
    ) -> Iterator[SourceRow]:
        """Enumerate EE assets intersecting ``bounds`` + ``interval``.

        Scaffolding — not yet implemented (design §8). The shared
        ``limit`` contract already holds: ``limit=0`` yields nothing
        and a negative limit raises `ValueError`.

        Raises:
            NotImplementedError: For any query that could return rows,
                until the staging layer can materialize ``ee.Image``
                assets.
        """
        if wants_no_rows(limit):
            return iter(())
        raise NotImplementedError(
            "GEESource.query is not implemented yet; use STACSource, "
            "EarthAccessSource or CMRSource. GEE follows once the "
            "staging layer can materialize ee.Image assets."
        )

    def auth_status(self) -> AuthStatus:
        """Report whether the `ee` client can reach Earth Engine.

        Scaffolding — not yet implemented (design §8).

        Raises:
            NotImplementedError: Always, until the adapter is implemented.
        """
        raise NotImplementedError("GEESource.auth_status is not implemented yet.")

auth_status()

Report whether the ee client can reach Earth Engine.

Scaffolding — not yet implemented (design §8).

Raises:

Type Description
NotImplementedError

Always, until the adapter is implemented.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/gee.py
def auth_status(self) -> AuthStatus:
    """Report whether the `ee` client can reach Earth Engine.

    Scaffolding — not yet implemented (design §8).

    Raises:
        NotImplementedError: Always, until the adapter is implemented.
    """
    raise NotImplementedError("GEESource.auth_status is not implemented yet.")

query(bounds, interval=None, *, collection=None, filters=None, limit=None)

Enumerate EE assets intersecting bounds + interval.

Scaffolding — not yet implemented (design §8). The shared limit contract already holds: limit=0 yields nothing and a negative limit raises ValueError.

Raises:

Type Description
NotImplementedError

For any query that could return rows, until the staging layer can materialize ee.Image assets.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/sources/gee.py
def query(
    self,
    bounds: Bounds,
    interval: pd.Interval | None = None,
    *,
    collection: str | None = None,
    filters: Mapping[str, Any] | None = None,
    limit: int | None = None,
) -> Iterator[SourceRow]:
    """Enumerate EE assets intersecting ``bounds`` + ``interval``.

    Scaffolding — not yet implemented (design §8). The shared
    ``limit`` contract already holds: ``limit=0`` yields nothing
    and a negative limit raises `ValueError`.

    Raises:
        NotImplementedError: For any query that could return rows,
            until the staging layer can materialize ``ee.Image``
            assets.
    """
    if wants_no_rows(limit):
        return iter(())
    raise NotImplementedError(
        "GEESource.query is not implemented yet; use STACSource, "
        "EarthAccessSource or CMRSource. GEE follows once the "
        "staging layer can materialize ee.Image assets."
    )

Catalogs from STAC (extras: [stac])

geocatalog.sources.from_stac_items(items, *, asset_key='data', engine='memory', crs=None, out_path=None, extra_properties=())

Build a raster catalog from STAC items.

Parameters:

Name Type Description Default
items Iterable[Item]

STAC items to index.

required
asset_key str | Literal['*']

Asset key to index. Pass "*" to emit one row for every asset on each item.

'data'
engine StorageEngine

"memory" or "duckdb". (backend is the deprecated name.)

'memory'
crs Any | None

Optional CRS for catalog footprints. Item geometries are lon/lat (EPSG:4326) and are reprojected, with edge densification, when supplied. (target_crs is the deprecated name.)

None
out_path Path | None

GeoParquet destination required by engine="duckdb".

None
extra_properties Sequence[str]

STAC property keys to preserve as catalog columns. Must not name one of the columns the builder writes itself.

()

Returns:

Type Description
GeoCatalog

A raster GeoCatalog with one row per selected STAC asset.

GeoCatalog

Footprints come from item.geometry (item.bbox only when

GeoCatalog

the geometry is missing), split at the antimeridian; crs is

GeoCatalog

the asset's native CRS from the projection extension

``proj

code/proj:epsg/proj:wkt2`` /

``proj

projjson);filepath`` is the absolute asset href and

GeoCatalog

href_signed flags hrefs carrying an expiring SAS signature

GeoCatalog

(re-sign them, e.g. with planetary_computer.sign, before

GeoCatalog

reading once the token has lapsed). Times are naive UTC.

GeoCatalog

An item with neither a geometry nor a bbox, or with no time, is

GeoCatalog

skipped with a warning.

Raises:

Type Description
ValueError

extra_properties names a builder-owned column.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/stac.py
@renamed_kwargs(backend="engine", target_crs="crs")
def from_stac_items(
    items: Iterable[pystac.Item],
    *,
    asset_key: str | Literal["*"] = "data",
    engine: StorageEngine = "memory",
    crs: Any | None = None,
    out_path: Path | None = None,
    extra_properties: Sequence[str] = (),
) -> GeoCatalog:
    """Build a raster catalog from STAC items.

    Args:
        items: STAC items to index.
        asset_key: Asset key to index. Pass ``"*"`` to emit one row for
            every asset on each item.
        engine: ``"memory"`` or ``"duckdb"``. (``backend`` is the
            deprecated name.)
        crs: Optional CRS for catalog footprints. Item geometries are
            lon/lat (EPSG:4326) and are reprojected, with edge
            densification, when supplied. (``target_crs`` is the
            deprecated name.)
        out_path: GeoParquet destination required by ``engine="duckdb"``.
        extra_properties: STAC property keys to preserve as catalog columns.
            Must not name one of the columns the builder writes itself.

    Returns:
        A raster `GeoCatalog` with one row per selected STAC asset.
        Footprints come from ``item.geometry`` (``item.bbox`` only when
        the geometry is missing), split at the antimeridian; ``crs`` is
        the asset's native CRS from the projection extension
        (``proj:code`` / ``proj:epsg`` / ``proj:wkt2`` /
        ``proj:projjson``); ``filepath`` is the absolute asset href and
        ``href_signed`` flags hrefs carrying an expiring SAS signature
        (re-sign them, e.g. with ``planetary_computer.sign``, before
        reading once the token has lapsed). Times are naive UTC.

        An item with neither a geometry nor a bbox, or with no time, is
        skipped with a warning.

    Raises:
        ValueError: ``extra_properties`` names a builder-owned column.
    """
    if engine not in ("memory", "duckdb"):
        raise ValueError(
            f"from_stac_items: engine must be 'memory' or 'duckdb'; got {engine!r}"
        )
    _require_pystac()
    clashes = sorted(set(extra_properties) & _STAC_ROW_COLUMNS)
    if clashes:
        raise ValueError(
            f"from_stac_items: extra_properties {clashes} would overwrite "
            "columns the builder writes; drop them from extra_properties."
        )

    catalog_crs = pyproj.CRS.from_user_input(crs) if crs is not None else _STAC_CRS
    rows: list[dict[str, Any]] = []
    for item in items:
        try:
            item_rows = _item_to_rows(
                item,
                asset_key=asset_key,
                catalog_crs=catalog_crs,
                extra_properties=extra_properties,
            )
        except UndecodableItemError as exc:
            # No footprint or no time: skip with a warning, the policy
            # every Source adapter follows too.
            log.warning("from_stac_items: skipping item {!r}: {}", item.id, exc)
            continue
        rows.extend(item_rows)
    # Empty STAC searches are common (overly tight bbox, future date
    # window, collection mismatch); return a typed empty catalog with
    # the same columns rather than raising so callers can branch on `len`.
    columns = {name: [r.get(name) for r in rows] for name in _STAC_ROW_ORDER}
    gdf = gpd.GeoDataFrame(
        {k: v for k, v in columns.items() if k not in _TIME_COLUMNS},
        geometry="geometry",
        crs=catalog_crs,
    )
    # An empty list infers float64; keep the flag boolean either way.
    gdf["href_signed"] = gdf["href_signed"].astype(bool)
    gdf.index = pd.IntervalIndex.from_arrays(
        pd.to_datetime(columns["start_time"]),
        pd.to_datetime(columns["end_time"]),
        closed="both",
        name="datetime",
    )
    for prop_key in extra_properties:
        gdf[prop_key] = [r.get(prop_key) for r in rows]
    catalog = InMemoryGeoCatalog(gdf, kind="raster")
    if engine == "memory":
        return catalog
    if out_path is None:
        raise ValueError("from_stac_items(engine='duckdb') requires out_path")
    to_geoparquet(catalog, out_path)
    from geocatalog._src.backends.duckdb_backend import DuckDBGeoCatalog

    return DuckDBGeoCatalog.open(out_path, kind="raster", crs=catalog_crs)

Run a STAC API search and build a raster catalog from its items.

Parameters:

Name Type Description Default
client Any | str

Open pystac_client.Client or STAC API URL.

required
collections Sequence[str]

Collection IDs to search.

required
bounds tuple[float, float, float, float] | None

Optional lon/lat search box (minx, miny, maxx, maxy). (bbox is the deprecated name.)

None
datetime str | None

Optional STAC datetime interval string.

None
asset_key str | Literal['*']

Asset key to index. Pass "*" to emit one row for every asset on each item.

'data'
engine StorageEngine

"memory" or "duckdb". (backend is the deprecated name.)

'memory'
limit int | None

Optional maximum number of returned search items to index. (max_items is the deprecated name.)

None
crs Any | None

Optional CRS for catalog footprints. (target_crs is the deprecated name.)

None
out_path Path | None

GeoParquet destination required by engine="duckdb".

None
extra_properties Sequence[str]

STAC property keys to preserve as catalog columns.

()

Returns:

Type Description
GeoCatalog

A raster GeoCatalog over the matching STAC assets.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/stac.py
@renamed_kwargs(bbox="bounds", backend="engine", max_items="limit", target_crs="crs")
def from_stac_search(
    client: Any | str,
    *,
    collections: Sequence[str],
    bounds: tuple[float, float, float, float] | None = None,
    datetime: str | None = None,
    asset_key: str | Literal["*"] = "data",
    engine: StorageEngine = "memory",
    limit: int | None = None,
    crs: Any | None = None,
    out_path: Path | None = None,
    extra_properties: Sequence[str] = (),
) -> GeoCatalog:
    """Run a STAC API search and build a raster catalog from its items.

    Args:
        client: Open `pystac_client.Client` or STAC API URL.
        collections: Collection IDs to search.
        bounds: Optional lon/lat search box ``(minx, miny, maxx, maxy)``.
            (``bbox`` is the deprecated name.)
        datetime: Optional STAC datetime interval string.
        asset_key: Asset key to index. Pass ``"*"`` to emit one row for
            every asset on each item.
        engine: ``"memory"`` or ``"duckdb"``. (``backend`` is the
            deprecated name.)
        limit: Optional maximum number of returned search items to index.
            (``max_items`` is the deprecated name.)
        crs: Optional CRS for catalog footprints. (``target_crs`` is the
            deprecated name.)
        out_path: GeoParquet destination required by ``engine="duckdb"``.
        extra_properties: STAC property keys to preserve as catalog columns.

    Returns:
        A raster `GeoCatalog` over the matching STAC assets.
    """
    pystac_client = _require_pystac_client()
    if isinstance(client, str):
        client = pystac_client.Client.open(client)

    search = client.search(
        collections=collections,
        bbox=bounds,
        datetime=datetime,
        max_items=limit,
    )
    item_iter = search.items()
    if limit is not None:
        item_iter = itertools.islice(item_iter, limit)
    return from_stac_items(
        item_iter,
        asset_key=asset_key,
        engine=engine,
        crs=crs,
        out_path=out_path,
        extra_properties=extra_properties,
    )

To export a catalog as a STAC collection, see to_stac_collection.

Source rows to catalog rows

geocatalog.sources.source_row_to_gdf_row(row, *, crs, primary_asset=None)

Map a SourceRow to a flat dict suitable for a GeoDataFrame row.

Output keys: * geometry: the footprint, reprojected from EPSG:4326 to crs if necessary. * start_time / end_time: pulled from the interval. * filepath: chosen asset URL (see primary_asset resolution). * id, source, collection: as-is from the SourceRow. * assets, properties, provenance: JSON-encoded dicts (Parquet can't store nested dicts directly without schema acrobatics; JSON-as-string is the boring-but-robust path).

Parameters:

Name Type Description Default
row SourceRow

The source row to convert.

required
crs CRS

CRS to reproject the geometry into. SourceRow geometries come in EPSG:4326 by convention.

required
primary_asset str | None

Asset key to promote to filepath. If None, the first key in row.assets is used (Python dicts preserve insertion order); if the assets dict is empty, filepath is an empty string.

None

Raises:

Type Description
KeyError

primary_asset is given but the row has no such asset — silently indexing another band instead would be a wrong-data bug, not a fallback.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/storage/bundle.py
@renamed_kwargs(target_crs="crs")
def source_row_to_gdf_row(
    row: SourceRow,
    *,
    crs: pyproj.CRS,
    primary_asset: str | None = None,
) -> dict[str, Any]:
    """Map a `SourceRow` to a flat dict suitable for a `GeoDataFrame` row.

    Output keys:
    * ``geometry``: the footprint, reprojected from EPSG:4326 to
      ``crs`` if necessary.
    * ``start_time`` / ``end_time``: pulled from the interval.
    * ``filepath``: chosen asset URL (see ``primary_asset`` resolution).
    * ``id``, ``source``, ``collection``: as-is from the SourceRow.
    * ``assets``, ``properties``, ``provenance``: JSON-encoded
      dicts (Parquet can't store nested dicts directly without
      schema acrobatics; JSON-as-string is the boring-but-robust path).

    Args:
        row: The source row to convert.
        crs: CRS to reproject the geometry into. SourceRow
            geometries come in EPSG:4326 by convention.
        primary_asset: Asset key to promote to ``filepath``. If
            ``None``, the first key in ``row.assets`` is used (Python
            dicts preserve insertion order); if the assets dict is
            empty, ``filepath`` is an empty string.

    Raises:
        KeyError: ``primary_asset`` is given but the row has no such
            asset — silently indexing another band instead would be a
            wrong-data bug, not a fallback.
    """
    # Reproject if needed. The shapely geometry doesn't carry its
    # CRS — we use `crs` as the authoritative target and assume
    # `SourceRow.geometry` is in EPSG:4326 (the `Source` Protocol
    # convention).
    geometry = reproject_geometry(row.geometry, LONLAT, crs)

    # Pick a filepath. For STAC items the "first asset" convention
    # is usually a sensible default (it's typically the lowest-res
    # overview or the canonical band); users who care can pass
    # `primary_asset` explicitly.
    # Strict on an explicit key (#240): silently indexing another band
    # instead would be a wrong-data bug, not a fallback.
    if primary_asset is not None:
        if primary_asset not in row.assets:
            raise KeyError(
                f"source row {row.id!r} has no asset {primary_asset!r}; "
                f"available: {sorted(row.assets)}"
            )
        key: str | None = primary_asset
    else:
        key = next(iter(row.assets), None)
    filepath = row.assets[key] if key is not None else ""
    # Native CRS of the promoted asset, when the source knows it (STAC
    # `proj:*`); granule sources such as CMR leave it unset.
    asset_crs = row.properties.get(ASSET_CRS_PROPERTY)
    crs = asset_crs.get(key) if isinstance(asset_crs, Mapping) else None

    return {
        "geometry": geometry,
        # Naive UTC, the catalog's stored time form: source adapters emit
        # tz-aware intervals, existing catalogs hold naive ones (#231).
        "start_time": to_naive_utc(row.interval.left),
        "end_time": to_naive_utc(row.interval.right),
        "filepath": filepath,
        "crs": crs,
        # Planetary Computer SAS signatures expire after ~1 h; flag them
        # so a persisted bundle says which hrefs need re-signing (#238).
        "href_signed": is_signed_href(filepath),
        "id": row.id,
        "source": row.source,
        "collection": row.collection,
        "assets": json.dumps(dict(row.assets)),
        "properties": json.dumps(dict(row.properties), default=str),
        "provenance": json.dumps(dict(row.provenance), default=str),
    }