Metadata-Version: 2.3
Name: anyverse-adp
Version: 0.7.2
Summary: CLI and Python SDK for the Anyverse Data Platform catalog, text embeddings, and video embeddings
Requires-Dist: alibabacloud-oss-v2>=1.4.1,<2
Requires-Dist: av>=15.1,<18
Requires-Dist: numpy>=2.0,<3
Requires-Dist: pyarrow>=18
Requires-Dist: tomli>=2.0 ; python_full_version < '3.11'
Requires-Dist: httpx>=0.28,<1
Requires-Dist: prompt-toolkit>=3.0,<4
Requires-Dist: rich>=13.9,<14
Requires-Dist: questionary>=2,<3
Requires-Dist: typer>=0.15,<1
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# Anyverse ADP CLI and Python SDK

`anyverse-adp` provides the `adp-cli` command and a Python SDK for reading the Anyverse Data Platform's registered LeRobot catalog, managing Episode and Clip tags, annotations and clips (including atomic Annotation/Clip writes), storing and searching external video embeddings, and exporting Episode metadata CSV files.

Install it with `pip install anyverse-adp`. Create a Platform API Key with `episodes:read`; Annotation writes, Episode/Clip tag updates, and Clip writes also require `episodes:write`. OSS bucket metadata lookup requires a valid key but no additional scope. Configure the key with an environment variable or reuse the CLI's secure `~/.adp-cli/config.toml`.

```text
adp-cli list
adp-cli --version
adp-cli browse
adp-cli info <dataset-slug>
adp-cli export <dataset-slug> <collection-key> --region <region> --output <directory-or-file.csv>
```

`adp-cli browse` is an inline terminal selector. It redraws a single `Anyverse Data Platform CLI` panel in the current terminal so the selected Dataset, Collection, region, and latest result stay together. Use Up/Down and Enter to select a Dataset, Collection, region, and export mode; type in Dataset and Collection menus to filter choices, and use Backspace to clear the filter. Press Esc to return to the previous level (or exit from Dataset). After a dry-run or completed export, its result remains visible and the selector offers continue or exit. It does not open a full-screen UI or switch to an alternate terminal screen.

The command reads catalog metadata, including the selected Artifact `oss://bucket/prefix/` root in the `oss_location` CSV column, the Episode UUID, and `video_refs` keyed by the original camera/view feature name. Each video reference contains its stable OSS path and indexed start/end offsets in nanoseconds. It does not read or download dataset objects, expose raw annotations, or grant object-storage access.

## Parquet references (0.4.0)

Version 0.4.0 appends `parquet_filepath`, `parquet_row_start`, and `parquet_row_end` to CSV exports. The filepath is a stable `oss://` URI resolved from the selected region's unique Artifact location and the API's relative file path. The row range is zero-based `[start, end)` inside that file, with `end - start == frame_count`; it is not the Episode index. Unindexed references produce three empty cells. Older APIs without all three metadata fields also produce empty cells, so deploy the updated API before using 0.4.0 for Parquet exports. Partial or invalid references fail the export instead of publishing an incomplete CSV.

SDK Episodes expose `parquet_relative_path`, `parquet_filepath`, `parquet_row_start`, and `parquet_row_end`. These are `None` when the reference is unavailable. Resolving a complete path requires exactly one Artifact location in the client's selected region; ambiguous locations raise `AdpResponseError`.

## Text embeddings (0.6.0)

Use `client.list_models()` and `client.embeddings.create(model="dashscope/qwen3-vl-embedding", input="Fold Tabletop Tissues", dimensions=1024)`. Both methods use the existing platform `episodes:read` permission; cache misses generate and persist raw vectors on the server. Each result exposes `.cache_hit`: `True` for a persisted result, `False` for a newly generated result, or `None` when an older server omits the field. The SDK does not normalize vectors or hold provider credentials. See the [text embedding guide](../../docs/user/text-embeddings.md) for batch inputs, response options and OpenAI SDK compatibility. Deploying the updated API and migration is required; building the package does not publish a release.

## Video embeddings (0.6.1)

Use `Episode.upsert_embeddings()` / `Clip.upsert_embeddings()` or the corresponding Client methods to store externally generated camera vectors. `Client.search_video_embeddings()` searches Episode and Clip vectors by cosine distance. See the [video embedding guide](../../docs/user/lerobot-video-embeddings.md) for batch writes, permissions, and the current Qwen3-VL space.

## Python SDK (0.6.0)

The SDK uses a synchronous `Client` and resource handles organized as `Dataset → Collection → LeRobot → Episode`. Client and Dataset lists are materialized for indexing; LeRobot and Episode collections remain lazy and page as you iterate.

Read the installed package version from Python with `import anyverse_adp; print(anyverse_adp.__version__)`. It reports `"unknown"` when package metadata is unavailable, such as when importing an unpackaged source checkout.

```python
from anyverse_adp import AdpAuthorizationError, AdpError, Client

client = Client()  # explicit api_key, ADP_API_KEY, ADP_CLI_API_KEY, then ~/.adp-cli/config.toml
try:
    datasets = client.get_datasets()
    dataset = client.get_dataset("agibot_world")
    collections = dataset.get_collections()
    collection = dataset.get_collection("dexhand_auto_views")
    lerobot = next(iter(collection.lerobots))
    episode = lerobot.get_episode(index=100)  # one direct server lookup by (LeRobot, index)
    print(episode.episode_uuid, episode.index)
    episode = client.get_episode(episode_uuid=episode.episode_uuid)  # direct lookup by Episode UUID
    episode = lerobot.get_episode(episode_uuid=episode.episode_uuid)  # scoped to this LeRobot
    episode = collection.lerobots.get_episode(episode_uuid=episode.episode_uuid)  # scoped to this Collection

    # Bulk traversal remains lazy and cursor paged.
    for item in lerobot.get_episodes():
        print(item.index)

    # These are complete lists scoped to this Episode. List entries contain summaries;
    # accessing .annotation fetches the individual JSON body.
    annotations = episode.annotations
    annotation = episode.get_annotation("scene", "prompt-v3")
    print(annotations[0].annotation_type, annotation.annotation)

    clips = episode.get_clips("scene", "prompt-v3")
    if clips:
        print(clips[0].label, clips[0].annotation)

    # Writes use episodes:write and are keyed upserts; repeated keys update the same record.
    episode.add_clip(
        annotation_type="scene",
        model_prompt_version="prompt-v4",
        segment_id=1,
        frame_start=12,
        frame_end=48,
        label="pick up object",
        annotation={"object": "cup"},
    )
    episode.add_annotation(
        annotation_type="scene",
        model_prompt_version="prompt-v4",
        artifact_uri="oss://annotations/episode-100.json",
        result_flag=True,
        annotation={"summary": "The robot picks up the object."},
    )
except AdpAuthorizationError as exc:
    print(f"This operation requires {exc.required_scope}: {exc.operation}")
except AdpError as exc:
    print(f"ADP request failed: {exc}")
finally:
    client.close()
```

The default endpoint is `https://data-platform.cloud.anyverse.work` and the default region is `cn-shanghai`. Pass `endpoint=`, `region=`, or `api_key=` to override them. API Key precedence is explicit `api_key`, `ADP_API_KEY`, `ADP_CLI_API_KEY`, then the CLI config file `~/.adp-cli/config.toml`. The SDK reads that file only, preserves its permission and symlink checks, never prompts, and never writes it.

Use `client.get_episode(artifact_id, episode_index)` or `lerobot.get_episode(index)` for one Episode. The Platform API looks up that `(artifact_id, episode_index)` key directly. `iter_episodes()` and `get_episodes()` continue to use lazy cursor pagination.

`get_episode()` accepts one selector: `client.get_episode(artifact_id, episode_index)` (or `artifact_id=` and `episode_index=`) for index lookup, or `client.get_episode(episode_uuid=...)` for UUID lookup. The same UUID selector is available on `lerobot.get_episode()` and `collection.lerobots.get_episode()`; those resource methods constrain the result to the current LeRobot Artifact or Dataset Collection. `client.get_episode_by_uuid(episode_uuid)` remains as a compatibility alias. The Platform API looks up the Episode UUID primary key and returns the same metadata and region-scoped Artifact locations as index lookup. Direct lookups require `episodes:read`; a missing UUID or a UUID outside the selected resource scope raises `AdpNotFoundError`. No database migration is required.

`episode.video_refs` maps each camera feature key to a tuple of `VideoRef` values. Each reference exposes `relative_path`, `oss_uri`, `time_start_ns`, and `time_end_ns`. `oss_uri` combines the reference with the unique Artifact location for the Client's selected region. It is `None` if that location is ambiguous. Direct Episode lookups and paginated Episode reads populate the same fields.

`episode.get_tags()` / `clip.get_tags()` read the current tags from the Platform API. `episode.get_tag_confidence()` reads the Episode's `tag_code -> confidence` mapping; `episode.tag_confidence` and `episode.tags` contain the values returned with a loaded Episode. Episode writes use three methods: `update_tags(tags)` replaces the full tag list while retaining confidence for codes that remain; `update_tags_with_confidence(mapping)` replaces tags and confidence together, deriving the complete tag list from mapping keys in insertion order; and `add_tag(name=..., confidence=None)` appends one tag, optionally setting its confidence. An empty mapping to `update_tags_with_confidence` clears both tags and confidence. `confidence=None` leaves existing confidence unchanged (a newly added tag has no confidence); a number sets that tag's confidence without reading Episode metadata or replacing other confidence values. Confidence values must be finite numbers from 0 through 1. The SDK intentionally has no standalone confidence write method. Tag reads require `episodes:read`; writes require `episodes:write`.

The corresponding `Client` methods write directly by Episode UUID and do not fetch the full Episode first:

```python
client.update_episode_tags(episode_uuid, ["scene:private_living:kitchen"])
client.update_episode_tags_with_confidence(
    episode_uuid,
    {"scene:private_living:kitchen": 0.93},
)
client.add_episode_tag(
    episode_uuid,
    name="object:cup",
    confidence=0.87,
)
```

```python
episode = client.get_episode(episode_uuid="<episode_uuid>")
print(episode.get_tag_confidence())

# Replace tags and confidence together; the mapping keys become the complete tag list.
episode.update_tags_with_confidence({"scene:private_living:kitchen": 0.93})

# Add a tag and confidence atomically, preserving other confidence entries.
episode.add_tag(name="object:cup", confidence=0.87)
```

`episode.get_annotations()` / `episode.annotations` and `episode.get_clips()` / `episode.clips` return complete lists for one Episode. The server returns summary fields for lists, avoiding transfer of every JSON body. Use `episode.get_annotation(annotation_type, model_prompt_version)` for an Annotation body; Clip list items load their body through `clip.annotation`. Annotation and Clip writes are keyed upserts using the existing `episodes:write` scope. Use `episode.add_annotation_with_clips(...)` when one Annotation and its Clips must be written together: the SDK sends one request, the server stores them in one transaction, and each Clip is linked to the resulting Annotation automatically. Read calls require `episodes:read`; writes without `episodes:write` raise `AdpAuthorizationError` with `required_scope` and `operation`. Invalid request data raises `AdpValidationError` with the safe server code and message. Other typed failures include authentication, not-found, region, timeout, network, response-shape, and unhandled HTTP errors. Exceptions never include the API Key or raw response body.

The SDK's `Client` reads metadata and annotation or Clip records through the Platform API using the platform API Key. The Reader uses a separate set of OSS credentials.

Use `client.oss.get_bucket_info(bucket_name)` to read registered Aliyun OSS bucket metadata. `lerobot.get_bucket_info()` and `episode.get_bucket_info()` resolve the bucket from that resource's selected-region locations; `episode.bucket_info` is the property form. The SDK requires exactly one distinct OSS bucket in those locations and never guesses a bucket from an HTTP URL.

OSS object prefixes may contain ordinary spaces, such as `oss://example-bucket/Pouring Water/`. Bucket metadata lookup preserves these paths and resolves only the bucket name; control characters and invalid bucket names are rejected.

Successful results are cached in memory by provider and bucket for the lifetime of one `Client`. The cache has no expiration or public refresh/clear method. A new `Client` reads the current directory value from the Platform API; a failed lookup is retried on the next call. Each `Client` has an isolated cache, and closing it clears its cached values.

可直接运行的完整示例位于 `examples/sdk_catalog.py`：

```bash
ADP_API_KEY='<完整 API Key>' \
python packages/anyverse-adp/examples/sdk_catalog.py agibot_world --collection dexhand_auto_views
```

Jupyter 代码示例位于 [`examples/sdk_catalog.ipynb`](examples/sdk_catalog.ipynb)，按单元依次演示 Dataset、Collection、LeRobot 和 Episode 的读取。它只读取目录元数据，不下载 OSS 对象。

## Read Episode data from OSS

Install `anyverse-adp` on Python 3.10 or later to use `anyverse_adp.reader`. Version 0.7.0 adds the Alibaba Cloud OSS SDK V2, PyArrow, PyAV, and NumPy 2.x as installation dependencies. Projects pinned to NumPy 1.x need to update their dependency constraints before upgrading. The catalog `Client` and `adp-cli` can run without OSS credentials.

Keep the catalog `Client` open while the Reader resolves the Episode's registered bucket. The Client uses the platform API Key to query the catalog. The Reader uses caller-supplied OSS read access for `HeadObject` and `GetObject`. Pass `credentials=OssCredentials(...)` or an Alibaba Cloud OSS SDK V2 `CredentialsProvider` to `EpisodeReader`, or set `OSS_ACCESS_KEY_ID`, `OSS_ACCESS_KEY_SECRET`, and `OSS_SESSION_TOKEN` when using STS. The Reader also accepts the legacy group `ALIYUN_OSS_ACCESS_KEY_ID`, `ALIYUN_OSS_ACCESS_KEY_SECRET`, and `ALIYUN_OSS_SECURITY_TOKEN` when the primary group is unset.

If your application already supplies the OSS values, pass them directly as `EpisodeReader(access_key_id=key_id, access_key_secret=key_secret)`. Add `security_token=token` for STS. Use either the direct arguments or `credentials=`.

```python
from anyverse_adp.reader import EpisodeReader

reader = EpisodeReader()
try:
    sample = reader.read_episode(
        "<episode_uuid>",
        columns=["observation.state", "action"],
        frame_range=(0, 16),
        cameras="all",
        include_tasks=True,
        include_features=True,
    )
    states = sample.table["observation.state"]
    actions = sample.table["action"]
    tasks = sample.frame_tasks
    cameras = {key: video.frames for key, video in sample.videos.items()}
    action_definition = sample.features.get("action")
finally:
    reader.close()
```

Frame windows are Episode-relative and half-open. Omit the window to read the whole Episode. For shorter Episodes, cap the end at `episode.frame_count`. The example uses an Artifact with `observation.state` and `action` columns. Use the names in your Artifact's schema. Pass camera keys in the desired order, or use `cameras="all"` for registered MP4 cameras in catalog order. `cameras=None` and `cameras=[]` return an empty video mapping. Every returned camera frame aligns with the corresponding table row. Internal `timestamp` and `task_index` reads preserve the requested table schema and order. Include `timestamp` in `columns` to expose the Episode-relative nanoseconds in `sample.timestamps_ns`.

`include_features=True` returns the original feature definitions for the returned columns and cameras. Entries without definitions are omitted. With the option off, `features` is `None`. `sample.stats` includes the combined call's OSS I/O, and each entry in `sample.videos` reports its own video I/O and decode time. For long Episodes, use smaller windows to limit RGB buffer memory.

`read_episode` and `read_frames` accept an Episode UUID as a string or a `uuid.UUID`. The Reader resolves it through the catalog using the usual Platform API Key configuration and closes the Client it creates when the Reader closes. To reuse an existing Client, including its region and endpoint, pass `EpisodeReader(client=client)` and close that Client yourself.

```python
from anyverse_adp.reader import EpisodeReader

reader = EpisodeReader()
try:
    table = reader.read_episode("<episode_uuid>", columns=["timestamp"]).table
    video = reader.read_frames("<episode_uuid>", "<camera_key>", frame_range=(0, 16))
finally:
    reader.close()
```

To traverse an Artifact, read its definitions once and reuse the Reader across Episodes:

```python
from anyverse_adp import Client
from anyverse_adp.reader import EpisodeReader

client = Client()
try:
    reader = EpisodeReader(client=client)
    try:
        artifact = client.get_lerobot("<artifact_id>")
        info = reader.read_info(artifact)
        for episode in artifact.iter_episodes():
            window = (0, min(16, episode.frame_count))
            table = reader.read_episode(episode, columns=["action"], frame_range=window).table
            print(episode.episode_uuid, table.num_rows)
    finally:
        reader.close()
finally:
    client.close()
```

### LeRobot training metadata (0.7.2)

`read_info`, `read_tasks`, and `read_stats` accept a `LeRobot`, an `Episode`, or an Episode UUID. All three return metadata for the registered Artifact. Reuse an `Episode` object to resolve the catalog entry once across reads.

```python
from anyverse_adp import Client
from anyverse_adp.reader import EpisodeReader, MissingMetadataError

client = Client()
try:
    reader = EpisodeReader(client=client)
    try:
        episode = client.get_episode(episode_uuid="<episode_uuid>")
        info = reader.read_info(episode)
        task_table = reader.read_tasks(episode)
        result = reader.read_episode(
            episode,
            columns=["timestamp", "action"],
            include_tasks=True,
        )
        print(info.features["action"].get("names"), info.robot_type)
        print(task_table.tasks_by_index, result.frame_tasks, result.tasks)

        try:
            normalization = reader.read_stats(episode)
        except MissingMetadataError:
            normalization = None
        if normalization is not None:
            print(normalization.features["action"]["mean"])
    finally:
        reader.close()
finally:
    client.close()
```

`read_info()` exposes structured fields and the full `raw` JSON. `read_tasks()` reads v3 Parquet or v2.1 JSONL. For an Episode target, it tries Parquet first and falls back on HTTP 404. `read_stats()` reads published `meta/stats.json` values as NumPy arrays, including any available quantiles. An Artifact with only per-Episode statistics raises `MissingMetadataError`. Invalid metadata raises `InvalidMetadataError`.

`include_tasks=True` resolves task text for each row as `frame_tasks` and returns the window's distinct texts in first-occurrence order as `tasks`. The Reader projects `task_index` internally as needed and returns the requested table columns. Both task fields default to `None` and become `()` for an enabled empty window. Missing, invalid, or unknown frame task indices are reported by subclasses of `InvalidTaskReferenceError`. Task metadata requests and cache events are included in `result.stats`.

### Video and cache behavior

Pass one of `frame_range`, `frame_indices`, or `timestamps_ns` to `read_frames`. Omit all three to read the Episode's full frame window. Results preserve request order and contain an RGB `uint8` array shaped `(N, H, W, 3)` and the matched presentation timestamps relative to the Episode start. Explicit timestamps use nanoseconds and return `frame_indices=None`. For each target the Reader picks the nearest frame inside the selected Episode's video interval, within half a frame period by default. Pass `tolerance_ns` to set the limit explicitly.

`OssReaderConfig()` uses the registered public endpoint. Use `endpoint_mode="internal"` when the registered internal endpoint is reachable, or pass `endpoint_overrides={bucket_name: https_endpoint}` to override individual buckets. Each Reader owns bounded block, Parquet footer, and parsed metadata caches. Set `max_cached_metadata=0` to disable the parsed metadata cache. Each logical open checks the current ETag, and Range requests use that ETag as a precondition. **Keep registered object paths immutable.** An overwrite before a read can invalidate the catalog offsets. Reader results report OSS I/O statistics, and video reads report decode time separately. Keep one Reader per process and call `reader.close()` when finished.

Video reads require exactly one MP4 reference for the selected camera. Use [`examples/benchmark_oss_reader.py`](examples/benchmark_oss_reader.py) to compare the three Reader paths with independent whole-file reads on a shared Episode. See the [OSS Reader usage guide](../../docs/user/anyverse-adp-oss-reader.md) for a concise Chinese walkthrough.
