Skip to content

copernicus

Copernicus Data Space Ecosystem (CDSE) tools and constants.

CopernicusS2Band #

Bases: StrEnum

Copernicus Sentinel-2 Bands for Level-2A.

The value of each member corresponds to the asset key for the band. Base band names (e.g., 'B02') default to their native resolution. Explicit resolution members (e.g., 'B02_20m') are also provided.

base_name property #

base_name: str

Returns the base name of the band (e.g., 'B02').

native_res property #

native_res: int

Returns the native resolution of the band in meters.

Defaults to 10m if band base name is not recognized.

at_res #

at_res(resolution: int | CopernicusS2Resolution) -> str

Returns the asset key for this band at the specified resolution.

Parameters:

Name Type Description Default
resolution int | CopernicusS2Resolution

The resolution to get the key for (e.g., 20 or CopernicusS2Resolution.R20M).

required

Returns:

Type Description
str

The asset key string (e.g., 'B02_20m').

Source code in src/geospatial_tools/stac/copernicus/constants.py
184
185
186
187
188
189
190
191
192
193
194
195
def at_res(self, resolution: int | CopernicusS2Resolution) -> str:
    """
    Returns the asset key for this band at the specified resolution.

    Args:
        resolution: The resolution to get the key for (e.g., 20 or CopernicusS2Resolution.R20M).

    Returns:
        The asset key string (e.g., 'B02_20m').
    """
    res_val = resolution.value if isinstance(resolution, CopernicusS2Resolution) else resolution
    return f"{self.base_name}_{res_val}m"

CopernicusS2Collection #

Bases: StrEnum

Copernicus Sentinel-2 Collections.

CopernicusS2Property #

Bases: StrEnum

Copernicus Sentinel-2 STAC query properties.

These are standard STAC properties shared across catalogs. The sortby_field property returns the full JSON path required by the STAC API sortby object.

sortby_field property #

sortby_field: str

Returns the full JSON path prefix required by the STAC API sortby object.

CopernicusS2Resolution #

Bases: int, Enum

Copernicus Sentinel-2 Resolutions in meters.

__str__ #

__str__() -> str

Returns the resolution as a string with 'm' suffix.

Source code in src/geospatial_tools/stac/copernicus/constants.py
65
66
67
def __str__(self) -> str:
    """Returns the resolution as a string with 'm' suffix."""
    return f"{self.value}m"

__repr__ #

__repr__() -> str

Returns the band name as a string.

Source code in src/geospatial_tools/stac/copernicus/constants.py
69
70
71
def __repr__(self) -> str:
    """Returns the band name as a string."""
    return f"{self.value}"

auth #

This module contains authentication-related functions.

get_copernicus_credentials #

get_copernicus_credentials(logger: Logger = LOGGER) -> tuple[str, str] | None

Retrieves Copernicus credentials from environment variables or prompts the user.

This function first checks for COPERNICUS_USERNAME and COPERNICUS_PASSWORD environment variables. If they are not set, it interactively prompts the user for their username and password.

Using environment variables is recommended for security and to comply with the 12-factor app methodology, which separates configuration from code. This prevents hardcoding sensitive information and makes the application more portable across different environments (development, testing, production).

Parameters:

Name Type Description Default
logger Logger

Logger instance.

LOGGER

Returns:

Type Description
tuple[str, str] | None

A tuple containing the username and password, or None if they could not be

tuple[str, str] | None

obtained.

Source code in src/geospatial_tools/stac/copernicus/auth.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def get_copernicus_credentials(logger: logging.Logger = LOGGER) -> tuple[str, str] | None:
    """
    Retrieves Copernicus credentials from environment variables or prompts the user.

    This function first checks for `COPERNICUS_USERNAME` and `COPERNICUS_PASSWORD`
    environment variables. If they are not set, it interactively prompts the user
    for their username and password.

    Using environment variables is recommended for security and to comply with the
    12-factor app methodology, which separates configuration from code. This prevents
    hardcoding sensitive information and makes the application more portable across
    different environments (development, testing, production).

    Args:
        logger: Logger instance.

    Returns:
        A tuple containing the username and password, or None if they could not be
        obtained.
    """
    logger.info("Retrieving Copernicus credentials...")
    username = os.environ.get("COPERNICUS_USERNAME")
    password = os.environ.get("COPERNICUS_PASSWORD")

    if not username:
        logger.warning("COPERNICUS_USERNAME environment variable not set.")
        try:
            username = input("Enter your Copernicus username: ")
        except EOFError:
            logger.error("Could not read username from prompt.")
            return None

    if not password:
        logger.warning("COPERNICUS_PASSWORD environment variable not set.")
        try:
            password = getpass.getpass("Enter your Copernicus password: ")
        except EOFError:
            logger.error("Could not read password from prompt.")
            return None

    if not username or not password:
        logger.error("Username or password could not be obtained. Cannot proceed with authentication.")
        return None

    logger.info("Successfully retrieved Copernicus credentials.")
    return username, password

get_copernicus_token #

get_copernicus_token(logger: Logger = LOGGER) -> str | None

Retrieves an access token from the Copernicus Data Space Ecosystem.

This function uses the credentials obtained from get_copernicus_credentials to request an access token from the authentication endpoint.

Parameters:

Name Type Description Default
logger Logger

Logger instance.

LOGGER

Returns:

Type Description
str | None

The access token as a string, or None if authentication fails.

Source code in src/geospatial_tools/stac/copernicus/auth.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def get_copernicus_token(logger: logging.Logger = LOGGER) -> str | None:
    """
    Retrieves an access token from the Copernicus Data Space Ecosystem.

    This function uses the credentials obtained from `get_copernicus_credentials`
    to request an access token from the authentication endpoint.

    Args:
        logger: Logger instance.

    Returns:
        The access token as a string, or None if authentication fails.
    """
    credentials = get_copernicus_credentials(logger)
    if not credentials:
        return None

    username, password = credentials
    data = {
        "client_id": "cdse-public",
        "username": username,
        "password": password,
        "grant_type": "password",
    }

    try:
        response = requests.post(COPERNICUS_AUTH_URL, data=data, timeout=10)
        response.raise_for_status()
        token_data = response.json()
        access_token = token_data.get("access_token")
        if access_token:
            logger.info("Successfully obtained Copernicus access token.")
            return access_token
        logger.error("Access token not found in response.")
        return None
    except requests.exceptions.RequestException as e:
        logger.error(f"Failed to obtain access token: {e}")
        return None

constants #

This module contains Enums for Sentinel-2 on Copernicus Data Space Ecosystem (CDSE).

CopernicusS2Collection #

Bases: StrEnum

Copernicus Sentinel-2 Collections.

CopernicusS2Property #

Bases: StrEnum

Copernicus Sentinel-2 STAC query properties.

These are standard STAC properties shared across catalogs. The sortby_field property returns the full JSON path required by the STAC API sortby object.

sortby_field property #

sortby_field: str

Returns the full JSON path prefix required by the STAC API sortby object.

CopernicusS2Resolution #

Bases: int, Enum

Copernicus Sentinel-2 Resolutions in meters.

__str__ #

__str__() -> str

Returns the resolution as a string with 'm' suffix.

Source code in src/geospatial_tools/stac/copernicus/constants.py
65
66
67
def __str__(self) -> str:
    """Returns the resolution as a string with 'm' suffix."""
    return f"{self.value}m"

__repr__ #

__repr__() -> str

Returns the band name as a string.

Source code in src/geospatial_tools/stac/copernicus/constants.py
69
70
71
def __repr__(self) -> str:
    """Returns the band name as a string."""
    return f"{self.value}"

CopernicusS2Band #

Bases: StrEnum

Copernicus Sentinel-2 Bands for Level-2A.

The value of each member corresponds to the asset key for the band. Base band names (e.g., 'B02') default to their native resolution. Explicit resolution members (e.g., 'B02_20m') are also provided.

base_name property #

base_name: str

Returns the base name of the band (e.g., 'B02').

native_res property #

native_res: int

Returns the native resolution of the band in meters.

Defaults to 10m if band base name is not recognized.

at_res #

at_res(resolution: int | CopernicusS2Resolution) -> str

Returns the asset key for this band at the specified resolution.

Parameters:

Name Type Description Default
resolution int | CopernicusS2Resolution

The resolution to get the key for (e.g., 20 or CopernicusS2Resolution.R20M).

required

Returns:

Type Description
str

The asset key string (e.g., 'B02_20m').

Source code in src/geospatial_tools/stac/copernicus/constants.py
184
185
186
187
188
189
190
191
192
193
194
195
def at_res(self, resolution: int | CopernicusS2Resolution) -> str:
    """
    Returns the asset key for this band at the specified resolution.

    Args:
        resolution: The resolution to get the key for (e.g., 20 or CopernicusS2Resolution.R20M).

    Returns:
        The asset key string (e.g., 'B02_20m').
    """
    res_val = resolution.value if isinstance(resolution, CopernicusS2Resolution) else resolution
    return f"{self.base_name}_{res_val}m"