# Datasets

> Read and edit datasets, merge uploads, and correct an upload with the Qualia SDK

`client.datasets` reads and edits datasets the way the dataset page does. A
dataset is an upload (one recording session), a merged dataset (several uploads
reviewed and trained as one) or a mixture (kept up to date from other datasets).
Every method takes a dataset id or its full name, `accounts/{a}/datasets/{d}`.

These calls go through the qualia.v1 Datasets API, so any API key that can read
the dataset's workspace can make them; a key restricted to workspaces is
refused. Writes need the `data:write` scope and the same role the dashboard asks
for.

## Read datasets

```python
from qualia import Qualia

client = Qualia()

page = client.datasets.list(filter="kind = MIXTURE", limit=50)
[session] = client.datasets.list(filter='slug = "session-0412"').items  # by slug
dataset = client.datasets.get(page.items[0].name)
print(dataset.kind, dataset.counts.episodes, dataset.etag)
```

`list` filters on `kind` (`UPLOAD`, `MERGED`, `MIXTURE`), `state`, `labels.*`,
`target_robot`, `source_robot`, `slug`, `display_name` (`:` for a substring),
`reads`, `readers` and `merged_dataset`. It leaves out uploads merged into
another dataset, unless the filter names one `slug`, one `readers` or one
`merged_dataset` (which lists the uploads that merged dataset holds). `get` also
says which Tasks reference the dataset's episodes (`task_references`).

## Edit a dataset

Only the arguments you pass change. Pass the etag you read to refuse a stale
write (409).

```python
client.datasets.update(dataset.name, display_name="Bench, day 2", etag=dataset.etag)
client.datasets.update(dataset.name, target_robot="accounts/<a>/robots/<r>")
client.datasets.update(dataset.name, rig="Kitchen UMI")  # record the rig; "" clears it
client.datasets.update(
    dataset.name,
    reach_settings={"base_m": [0.0, 0.1, 0.0], "home_heading_rad": 0.0},
)
```

| Argument         | What it sets                                                                                                                                                                        |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `display_name`   | The name                                                                                                                                                                            |
| `description`    | Free text; `""` clears it                                                                                                                                                           |
| `target_robot`   | The robot it plays on, `accounts/{a}/robots/{r}`; `""` clears it                                                                                                                    |
| `rig`            | The rig it was recorded on: a rig's resource name, id or display name in the dataset's workspace; `""` clears it. It must go alone in the call                                      |
| `reach_settings` | How the reach check walks it, replaced as a whole: `base_m` (empty or x, y, z metres), `home_heading_rad`. `{}` resets. A `solver` is refused: a dataset follows its robot's solver |

A merged dataset writes its robots and reach settings to every upload it holds,
and its rig too: a UMI rig when every upload is handheld, an arm rig when none is, a
capture rig always, and `""` clears them all (a mix of handheld and arm uploads refuses a
UMI or an arm rig). `move_merged_poses(rigs=...)` names a rig per upload.
Saving reach settings starts nothing; the next reach check run uses them.

An upload needs no rig, and `rig=` adds one afterwards, changes it, or with `""`
clears it. Any rig of the workspace works (an arm rig, a UMI rig or another capture
rig; a gripper template, an unknown name or a rig of another workspace is
refused), and the recording's kind decides which kind it takes. A UMI rig set
this way is a record only: it moves no poses, so call `resolve_poses` to move
them. With `rig=` in the call, any other field raises `ValueError`. This needs
0.8.0rc17 or newer.

## Merge uploads

The merge as a whole cannot be undone, so preview it first: `validate_only=True`
writes nothing and returns what differs between the uploads. The merged dataset
is a dataset like any other, and `remove_merged_member` takes one upload out
again as a standalone upload.

```python
uploads = [first.name, second.name]
conflicts = client.datasets.merge(uploads, display_name="Bench", validate_only=True)
for c in conflicts:
    print(c.field, c.channel, c.blocking, [side.value for side in c.sides])

merged = client.datasets.merge(
    uploads,
    display_name="Bench",
    resolutions=[{"field": "target_robot", "channel": "", "value": first.target_robot}],
)
```

A blocking conflict (what training freezes: features, cameras, channel names,
fps, where the poses are) settles only by leaving uploads out. The others take
one value each from `resolutions`; labels and the Task default to the uploads'
commonest. `into=` adds uploads to an existing merged dataset. While the
dataset's recordings are being re-processed to a new time sync, an upload added
with `into=` is checked and queued instead of refused: it is not in
`source_datasets` yet, the returned dataset's `joining_uploads` (empty for an ordinary append) names it, it is
listed in `sync_preparation.joining` (with the reason if it could no longer
join), and it joins once the current re-processing has settled and is
re-processed then when the dataset has a current time sync (not after a
Cancel). `client.data.upload(..., merge_target=)` reports it as
`merge_append.status == "joining"`, also when the upload is run again. A tool
center point move, and a merge that carries `resolutions`, are refused instead
while that goes on.

Uploads recorded on different source robots merge without a question: the
merged dataset's `source_robot` is the robot every upload shares, and empty when
they differ. Each upload keeps its own, unless you pass a `source_robot`
resolution while the uploads' robots differ (with `into=`, counting the uploads
the merged dataset already holds); with one shared robot the resolution is
ignored. The robot it names then becomes every upload's explicit assignment and
the merged dataset's. The rigs a merged dataset was recorded on are listed in
the API's `Dataset.rigs`.

## Curate from a version

A branch is a mixture that reads one upload as a version froze it. It is named
after the version unless you name it.

```python
branch = client.datasets.create(curated_from=f"{dataset.name}/versions/1.0")
```

## Delete a dataset

```python
client.datasets.delete(dataset.name, force=True)
```

This deletes a mixture, or retires an upload or a merged dataset (with the
uploads it holds). Nothing is erased, and versions cut from it keep resolving.
It is refused while a mixture reads it, and while Tasks reference its episodes
unless `force=True`, which removes those references.

## Map channels onto canonical keys

```python
result = client.datasets.remap_channels(
    dataset.name, {"/arm/joint_0": "left.joint_0.pos", "/arm/joint_1": ""}
)
print(result.interface_hash)
```

Renames add to earlier ones; `""` resets a channel to the key read from its
name. A key another channel holds is refused and nothing is written.

## Re-ingest an MCAP upload

```python
toml = open("ingest.toml").read()
reingest = client.datasets.reingest(dataset.name, toml)
done = client.datasets.wait_reingest(reingest.name, timeout=1800)
print(done.episode_count, done.frame_count)
```

The new `meta/ingest.toml` replaces the published one and the upload's next
generation is published. The published config again runs nothing (`unchanged`).
A config with `[episodes] spans` re-cuts the upload and is refused while any
episode holds a person's ruling, issue, note or edit. `wait_reingest` raises
`QualiaError` with the reason when it fails, and `TimeoutError` when it has not
ended; the work keeps running either way. `get_reingest` reads one at any time.
A merged dataset is not re-ingested with `reingest`: its time sync is set as
described next.

## Change a merged dataset's time sync

A merged dataset has one time sync, a clock and an alignment per channel, that
every upload it holds is processed to.

```python
toml = 'schema = 1\n\n[channels."/imu"]\nalign = "hold"\n'
check = client.datasets.precheck_merged_sync(merged.name, toml)
print(f"{check.current_members} of {check.total_members} uploads hold it")
for upload in check.members:
    print(upload.display_name, upload.state, upload.reason)

client.datasets.apply_merged_sync(merged.name, toml, check.membership_revision)
status = client.datasets.merged_sync_status(merged.name)
```

The text is a patch: `schema = 1`, a `[clock]` (`row_clock_topic` or `fixed_hz`)
and `[channels.<topic>]` `align` entries. Any other table is refused. It is
composed onto each upload's own `meta/ingest.toml`, so an upload keeps its camera
offsets, its rig and its episode boundaries. A channel an upload does not have is
skipped for it and named in its `skipped_topics`; a clock topic it lacks blocks it.

A check starts nothing. It reads the dataset first and sends its current
membership revision, as the server requires; pass `membership_revision=` to check
against a revision you already hold. Each upload is `CURRENT` (it already holds the time sync),
`WAITING` (it can be processed to it), `BLOCKED` with a reason, or
`NOT_APPLICABLE` (a LeRobot upload has no time sync). A merged dataset's time sync
cannot change its uploads' frame rate yet: an upload the time sync would give
another frame rate is blocked, and so is one that holds trims or batch edits. The
uploads it cannot move are listed with their reasons.

`apply_merged_sync` takes the `membership_revision` of the check. A dataset whose
uploads changed since is refused (409, `ABORTED`), so check again. Apply stores the
time sync and returns. The server then re-processes the uploads that do not hold it,
four at a time per merged dataset, each as a new generation of that upload.
Rulings, issues and reaches stay with their episodes. Applying the same time sync
again starts nothing new. `merged_sync_status` reads where the uploads stand:
`target` is the time sync last applied (empty before any was applied and after
it was cancelled, when no count is reported), `members` lists only the uploads that do
not hold it yet (`WAITING`, `RUNNING`, `BLOCKED`, `FAILED`), `joining` lists the
recordings appended meanwhile that wait to join, and it is cheap to
poll. A `RUNNING` upload's `operation_id` is a bare id, so follow it with
`get_reingest(member.operation_id, dataset=member.upload)`.

With a time sync applied, every recording appended to the merged dataset is brought
to it too (see `merge`). While recordings re-process, the dataset's uploads cannot
change: an append is queued and joins once the work has settled, and
`remove_merged_member`, a version and the solver are refused (`FAILED_PRECONDITION`)
with a message that counts the recordings still re-processing. Wait for
`merged_sync_status` to show them done, or follow the message.

Try again is `apply_merged_sync(merged.name, status.target, status.membership_revision,
members=[upload])`: only that upload is checked again and, if it can take the time
sync, set to wait. To take an upload out of the merged dataset instead, use
`remove_merged_member`.

## Resolve a handheld upload's poses

```python
started = client.datasets.resolve_poses(dataset.name, gripper="<gripper id>")
client.datasets.resolve_poses(dataset.name, "root")  # undo: back at the gripper root
```

The gripper's tracker-to-TCP calibration is read and sent as it stands; a
gripper with none is refused before anything is sent. Without `gripper=` it is
the upload's capture gripper: the UMI rig it records (`Dataset.rig`), else the
workspace's one UMI rig of the upload's kind. A workspace with none is refused
(make one from a gripper template: New rig, UMI in the dashboard, or
`client.robots.make_umi_rig`), and with several that the upload does not record
the rig cannot be told: pass `gripper=` naming the rig it was recorded on, or
record it with `update(rig=)`. The work re-derives the whole upload, and the call
waits for it; `wait=False` returns once it is accepted, and `started.operation`
names the re-ingest it started (`wait_resolve(started.operation)`, or
`wait_reingest`, which waits for the same thing). `no_op` means the poses were
already there.

A merged dataset moves its uploads with `precheck_merged_poses` and
`move_merged_poses` (which takes the membership revision the check returns), one
upload at a time with that upload's own rig's calibration. With several UMI
rigs of one kind the dataset does not record which rig an upload was recorded on:
an upload is blocked and lists its `candidate_rigs`, with `matching_rig` naming the
one whose calibration the upload already carries (a hint, never applied). Name the rig it was recorded
on with `rigs={upload: rig}` on the check or the move. A rig named this way must
be a UMI rig of the upload's kind with a complete calibration. A move that lands stores its
rig as the upload's own (`composed_umi_rig`), so later checks and moves need no name. For an
upload already at that rig's calibration, a move request stores it at once. A move that fails
before landing stores nothing yet, and retrying it repeats its rig. A check stores nothing.
If the stored rig is deleted, the upload asks again. Resolving an upload on its own with
`resolve_poses` leaves its stored rig, because a calibration does not name a rig. If the poses
then carry the calibration of one other rig, the stored rig is not trusted: the merged check asks,
and hints at that rig. The CLI's `qualia dataset poses-precheck` and
`poses-move` take `--rig UPLOAD=RIG` for the same, and the dashboard's merged
dataset has a **Recorded on** select for it on its Poses line. The select shows
only for an upload that is waiting for its rig, lists the `matching_rig` first
and leaves the choice empty. It also shows for a failed move that has no rig to
repeat, so you can name one to retry. A rig that is not calibrated cannot be chosen
there. A request with one bad rig name is refused whole, and the dashboard shows
the message.

## Read the ingest report

```python
report = client.datasets.ingest_report(dataset.name)
if report.omission != "OMISSION_UNSPECIFIED":
    raise RuntimeError(f"report unreadable: {report.omission}")
for source in report.report["sources"]:
    print(source["path"], [c["camera"] for c in source.get("cameras", [])])
```

`report.report` is the document ingest wrote. A merged dataset answers its
uploads' reports folded into one: the `sources` of its `base` upload, `findings`
rolled up across uploads, `sync_agreement` and the `uploads` read so far.
