Metadata-Version: 2.4
Name: urbandata
Version: 0.0.1
Summary: Python SDK for the Urban Data Management Platform (UDMP)
Home-page: https://github.com/SLG-European-Projects/udmp-sdk-python
Author-email: Iason Sotiropoulos <isotiropoulos@singularlogic.eu>, Panagiotis Iatrou <piatrou@singularlogic.eu>
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.31
Requires-Dist: tqdm>=4.66
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: home-page

# urbandata

Python SDK for the Urban Data Management Platform (UDMP): datasets, folders, resources, processing
chains, files, sensor measurements and feature tables, on the control plane and the data plane.

- Interactive login against the platform's OIDC provider; the token is kept and refreshed for you
- Streamed uploads and resumable downloads, with progress bars
- Typed errors, and API objects that read as dicts or as attributes

## Install

Python 3.9 or newer.

```bash
git clone <repository-url> udmp-sdk-python
cd udmp-sdk-python
pip install -e .
```

Or only the dependencies (`requests`, `tqdm`), to use the sources in place:

```bash
pip install -r requirements.txt
```

## Configuration

Where to log in is not passed in code. The SDK reads it from the environment:

| Variable | Holds |
|---|---|
| `UDMP_OIDC_URL` | the issuer URL of the realm (`http://keycloak.localhost:8080/realms/ENHANCE`), or its token endpoint |
| `UDMP_CLIENT_ID` | the OIDC client to log in through (`control-plane` on a standard installation) |
| `UDMP_CLIENT_SECRET` | optional: the secret, when the client is confidential |

or from a JSON file named `.udmp`, in the working directory or in your home folder
(copy [`.udmp.example`](.udmp.example)):

```json
{
  "oidc_url": "http://keycloak.localhost:8080/realms/ENHANCE",
  "client_id": "control-plane",
  "client_secret": "only-for-a-confidential-client"
}
```

Each setting is taken from the first place that has it: an argument to `UrbanDataClient` (`oidc_url=`,
`client_id=`, `client_secret=`), the environment variable, the file. `UDMP_CONFIG_FILE` or
`UrbanDataClient(..., config_file=...)` names a file elsewhere. When the OIDC URL or the client id is in none
of them, `UrbanDataClient(...)` raises `ConfigError`, which says to set the environment variables or the
`.udmp` file.

`.udmp` is in `.gitignore`: it can hold a secret, so keep it out of version control.

## Quick start

```python
from urbandata import UrbanDataClient

client = UrbanDataClient(
    control_plane_url="http://control-plane.localhost:8080",
    data_plane_url="http://data-plane.localhost:8080",
)
client.login()   # asks: UDMP username, UDMP password

dataset = client.datasets.create("Chlorophyll", owner_org="slg", visibility="private")
resource = client.resources.create(dataset.identifier, "mosaic", processing=["raster-to-tiles"])

client.files.upload(resource.identifier, "mosaic_chl_oc3.tif")
client.processing.wait(resource.identifier)
client.files.download_all(resource.identifier, "out/", step="raster-to-tiles")
```

## Authentication

```python
client = UrbanDataClient(control_plane_url, data_plane_url)

client.login()                    # asks for the username and the password
client.login("alice")             # asks for the password only
client.login("alice", "secret")   # asks for nothing (scripts, CI)

client.token       # the access token; None before login()
client.logged_in   # True once there is a token
client.whoami()    # user_id, username, email, name, roles, organizations
client.logout()    # forgets the token
client.ping()      # both planes answer? needs no login
```

- The password is not echoed when typed on a terminal. IDE run consoles and notebooks have no
  terminal, so there it is read with a plain prompt and is visible.
- The token is sent with every call and refreshed on its own shortly before it expires. When the
  session itself has expired, the next call raises `UnauthorizedError` and `login()` is needed again.
- A call made before `login()` raises `UnauthorizedError` without contacting the server.
- `login()` returns the access token.

A token obtained elsewhere can be used instead of logging in. It needs no OIDC settings:

```python
client = UrbanDataClient(control_plane_url, data_plane_url, token="eyJ...")
client.token = "eyJ..."   # or set it later
```

Other parameters of `UrbanDataClient`: `timeout` in seconds (default 30), `session` (a `requests.Session` of
your own) and `progress` (see below).

Auth objects can still be passed, as `auth=` or as the third argument:

| Object | Use |
|---|---|
| `OidcAuth(oidc_url, client_id, client_secret=None, token=None)` | what `UrbanDataClient` creates from the configuration: `login()`, `refresh()`, `logout()` |
| `PasswordAuth(keycloak_url, realm, username, password, client_id="control-plane", client_secret=None)` | credentials known up front, token fetched on first use |
| `TokenAuth(token)` | a token string, or a callable returning one |

```python
from urbandata import UrbanDataClient, PasswordAuth

client = UrbanDataClient(control_plane_url, data_plane_url,
            PasswordAuth("http://keycloak.localhost:8080", "ENHANCE", "alice", "secret"))
```

## API

| Attribute | Covers | Methods |
|---|---|---|
| `client.datasets` | datasets and their shares | `list` `get` `create` `update` `delete` `restore` `shares` `share` `unshare` |
| `client.folders` | folders | `list` `get` `create` `rename` `delete` |
| `client.resources` | resources, including sensor resources | `list` `get` `create` `update` `delete` |
| `client.extensions` | the extension registry (admin) | `list` `get` `register` `update` `delete` |
| `client.processing` | a resource's chain and its runs | `get` `set` `enable` `runs` `run` `trigger` `cancel` `resume` `wait` |
| `client.files` | uploads and downloads, raw or per `step` | `list` `upload` `download_url` `download` `download_all` `delete_all` |
| `client.sensors` | device, current values, measurements | `device` `current` `measurements` `measurement` `add_measurement` `add_measurements` `delete_measurement` |
| `client.tables` | tables, GeoJSON features, vector tiles | `list` `get` `features` `tile` `create` `insert_features` `drop` |
| `client.serve` | the routes a step's extension serves over its outputs (tiles, metadata, statistics) | `routes` `get` `json` `content` |

Objects come back as `Record`: the API's JSON as a dict whose keys also read as attributes
(`dataset["identifier"]` and `dataset.identifier`).

Notes:

- `step=` on `files`, `tables` and `sensors` selects what that extension of the processing chain
  produced, instead of the resource's own data.
- `files.upload` streams the file from disk. `files.download` writes to `<dest>.part`, resumes
  from it after an interruption (up to `max_retries` attempts) and renames it when complete.
- `processing.wait` blocks until the chain completes and returns its state.
- `sensors.add_measurement` takes a `datetime` or an ISO 8601 UTC string for the observation time;
  `sensors.add_measurements` sends a list in one call.
- `serve.routes(resource_id)` lists what each step offers; `serve.json(resource_id, step, "info")` and
  `serve.content(resource_id, step, "tiles/8/140/98", rescale=["0,3000"])` call a route, with the
  query parameters it declares as keywords.
- `delete` on datasets and resources is a soft delete unless `permanent=True`; `datasets.restore`
  undoes a soft delete.
- `resources.list` needs the dataset: `client.resources.list(dataset_id, folder_id=...)`.
- Rights: creating a dataset needs membership of the owning organisation; updating, sharing and
  deleting it need an admin of that organisation; restoring and deleting permanently need a platform
  admin (realm role `admin`). Without the right, the call raises `ForbiddenError`.

## Helpers

`urbandata.utils` holds the functions the package shares, usable in your own scripts:

| Function | Does |
|---|---|
| `fix_localhost()` | resolves `*.localhost` to 127.0.0.1 for this process; needed on Windows for a platform on a local cluster |
| `utc_timestamp(when=None)` | a `datetime` (now by default) as the `2026-10-01T12:00:00Z` form the platform takes |
| `Record`, `records(items)` | the dict with attribute access that the API objects are |
| `clean`, `csv`, `seg`, `quote_path`, `presigned_headers` | building query parameters, URL paths and storage requests |

## Progress bars

`files.upload`, `files.download`, `files.download_all` and `processing.wait` show a
[tqdm](https://tqdm.github.io) progress bar (bytes for transfers, completed steps for processing).
It renders in terminals and in notebooks.

```python
client = UrbanDataClient(control_plane_url, data_plane_url, progress=False)             # off for this client
client.files.upload(resource_id, "big.tif", progress=True)                   # on for this call
client.files.download_all(resource_id, "out/", progress=False)               # off for this call
```

## Errors

| Exception | Raised when |
|---|---|
| `UrbanDataError` | any failed call; base class of the rest. Carries `status`, `code`, `body` |
| `ConfigError` | the OIDC URL or the client id is in neither the environment nor a `.udmp` file |
| `UnauthorizedError` | 401, a failed login, a call before `login()`, an expired session |
| `ForbiddenError` | 403 |
| `NotFoundError` | 404 |
| `ConflictError` | 409 |
| `ProcessingFailed` | `processing.wait()` and the chain failed. Carries `resource_id`, `state` |
| `ProcessingTimeout` | `processing.wait()` and the chain did not finish within `timeout_seconds` |

```python
from urbandata import NotFoundError, UrbanDataError

try:
    client.datasets.get(dataset_id)
except NotFoundError:
    ...
except UrbanDataError as e:
    print(e.status, e.code, e.body)
```

## Examples

Runnable scripts in [`examples/`](examples). Besides the configuration above, they read
`UDMP_CONTROL_PLANE_URL` and `UDMP_DATA_PLANE_URL` (default: the local development stack) and
optionally `UDMP_USERNAME` and `UDMP_ORG`, and ask for the password.

| Script | Shows |
|---|---|
| `01_login.py` | ping, interactive login, the kept token, whoami, reusing a token, logout |
| `02_datasets_and_folders.py` | datasets, nested folders, resources, shares, soft and permanent delete |
| `03_upload_process_download.py` | upload, wait for processing, download the outputs, with progress bars |
| `04_sensors.py` | a sensor resource, adding measurements one by one and in a batch, queries, paging |
| `05_tables.py` | creating a table, inserting GeoJSON, bbox queries, vector tiles |
| `06_extensions.py` | the extension registry and a resource's processing chain |
| `07_errors.py` | the exceptions and how to handle them |
| `08_serve.py` | listing and calling the routes of a processing step |

```bash
python examples/01_login.py
python examples/03_upload_process_download.py mosaic_chl_oc3.tif
```

## Development

```bash
pip install -e .
pip install -r requirements-dev.txt
pytest
```

The tests need no running platform: HTTP is replaced by fakes (`tests/conftest.py`). They cover
every module of the package, and `tests/test_examples.py` runs the numbered examples against a
stand-in platform so that they stay in step with the SDK.

```
src/urbandata/
    client.py       UrbanDataClient: the URLs, login(), token, whoami(), ping(), and the API attributes
    config.py       the OIDC settings from the environment or a .udmp file
    transport.py    HTTP to the two planes, bearer token
    errors.py       the exceptions
    progress.py     tqdm bars
    auth/           OidcAuth (login), PasswordAuth, TokenAuth
    api/            one module per API attribute: datasets, folders, resources, extensions,
                    processing, files, sensors, tables, serve
    utils/          shared helpers: records, http, timestamps, network
tests/              pytest suite
examples/           runnable scripts
src/udmp/           the old import name, kept working: Udmp, UdmpError
```
