This is an automated email from the ASF dual-hosted git repository.
XiaoHongbo-Hope pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 321bcfa800 [python] Support LeRobot schema evolution and extra text
fields (#11078)
321bcfa800 is described below
commit 321bcfa8001492a6a7a3ac91c4dbc3af76235c9d
Author: Zouxxyy <[email protected]>
AuthorDate: Wed Nov 11 03:57:25 2026 +0800
[python] Support LeRobot schema evolution and extra text fields (#11078)
---
docs/docs/pypaimon/lerobot.md | 103 +++++-
paimon-python/pypaimon/multimodal/connection.py | 10 +-
.../pypaimon/multimodal/lerobot/aggregate.py | 129 ++++---
paimon-python/pypaimon/multimodal/lerobot/api.py | 41 ++-
.../pypaimon/multimodal/lerobot/dataset.py | 55 ++-
.../pypaimon/multimodal/lerobot/loader.py | 7 +-
.../pypaimon/multimodal/lerobot/schema.py | 26 +-
.../pypaimon/multimodal/lerobot/text_fields.py | 184 ++++++++++
.../pypaimon/tests/lerobot_aggregate_test.py | 370 ++++++++++++++++++---
.../pypaimon/tests/lerobot_text_fields_test.py | 94 ++++++
.../pypaimon/tests/multimodal_lerobot_test.py | 5 +
11 files changed, 846 insertions(+), 178 deletions(-)
diff --git a/docs/docs/pypaimon/lerobot.md b/docs/docs/pypaimon/lerobot.md
index 84f275f37e..a7b92cc100 100644
--- a/docs/docs/pypaimon/lerobot.md
+++ b/docs/docs/pypaimon/lerobot.md
@@ -51,8 +51,9 @@ Python 3.10–3.11 uses LeRobot 0.4.x; Python 3.12+ uses
LeRobot 0.6.x.
```python
conn.load_from_lerobot(
- "robot_data",
- "/data/lerobot_dataset",
+ table_name="robot_data",
+ source="/data/lerobot_dataset",
+ dataset_name="dataset_a", # Optional source label.
tag_name="initial-import", # Optional: tag all imported component
snapshots.
)
```
@@ -66,10 +67,9 @@ just an example prefix; choose any unused name:
```python
conn.load_from_lerobot(
- "robot_merged",
- ["oss://bucket/dataset_a", "oss://bucket/dataset_b"],
- dataset_names=["dataset_a", "dataset_b"],
- fps_mode="source", # Allow different source FPS.
+ table_name="robot_merged",
+ source=["oss://bucket/dataset_a", "oss://bucket/dataset_b"],
+ dataset_name=["dataset_a", "dataset_b"],
)
```
@@ -82,8 +82,9 @@ Each source has one row in `_datasets`. Its `info` JSON
contains the original
`meta/info.json`, including FPS; there is no separate FPS column.
The table contains `index`, `name`, `info`, `tasks`, `subtasks`,
and `stats`. Source ranges are derived from the counts in each source's `info`.
-`dataset_names` supplies optional labels; omitted names are null, and duplicate
-labels do not merge sources. Frame and Episode `dataset_index` values reference
+`dataset_name` accepts a string for one source or a list/tuple with one label
per
+source in input order. Omitted names are null, and duplicate labels do not
merge
+sources. Frame and Episode `dataset_index` values reference
`_datasets.index`. The pair `(dataset_index, episode_index)` identifies an
original Episode. Frames keep a
merged `index` and their original `source_index`. Source task/subtask
ID-to-text
@@ -100,17 +101,89 @@ Control-field statistics reflect merged IDs; their
original quantiles are
omitted. Training reads skip `stats`. Repeated task/subtask text within one
source is rejected before creating tables to avoid losing original frame IDs.
-Sources must share robot type and training features. By default they must also
-share FPS; `fps_mode="source"` permits mixed FPS and requires
-`PaimonLeRobotDataset` for training. Pass `dataset_index=N` to that reader to
-select one source.
+Sources must share robot type and compatible definitions for common features.
Each source retains its own
+FPS from `info`; different source frame rates are handled automatically. Use
+`PaimonLeRobotDataset` to train from mixed-FPS groups. Pass `dataset_index=N`
to
+that reader to select one source. Frame-rate handling is automatic and does not
+require an import option.
+
+### Schema evolution
+
+`schema_evolution=True` is the default. The importer plans the union of source
+columns before creating `_frames` and any declared extra `_datasets` columns.
+Merged `_episodes` keeps its fixed typed controls and JSON group columns;
+source-specific keys remain inside those JSON values.
+Missing columns receive typed nulls. Optional columns become nullable; source
+indices, timestamps, task indices, and required Episode controls remain
required.
+Common columns must have identical types, and common frame features must retain
+their dtype, shape, and names. Type promotion and nested schema changes are
+rejected before creating tables.
+
+```python
+conn.load_from_lerobot(
+ table_name="robot_all",
+ source=["/data/dataset_a", "/data/dataset_b"],
+ schema_evolution=True, # Optional; this is the default.
+)
+```
+
+For example, sources with `action, temperature` and `action, pressure` produce
+`action, temperature, pressure`. Rows from the first source have null pressure;
+rows from the second have null temperature. The training reader reconstructs
+`meta.info.features` as the union of the original info stored in `_datasets`;
+feature statistics combine only sources with that feature.
+
+With `schema_evolution=False`, the first source defines the columns. Later
+sources may omit optional columns, which still receive nulls, but adding a
column
+is rejected. This applies to the sources of one import into a new table group.
+
+Readers return `None` for missing features. The built-in training batch reader
+keeps columns containing missing features as lists with `None` entries; fully
+populated features retain their tensor behavior. Select compatible sources or
+handle these missing entries when supplying inputs to a model.
+
+### Extra dataset text fields
+
+`extra_dataset_fields` maps new `_datasets` column names to file paths or glob
+patterns relative to each source root. The same mapping applies independently
to
+every source. UTF-8 `.json`, `.txt`, `.md`, `.yaml`, `.yml`, `.jsonl`,
`.ndjson`,
+`.csv`, and `.tsv` files are supported, including uppercase suffixes. Contents
+remain verbatim text, including whitespace and line endings; they are not
parsed
+as JSON, YAML, or tables.
+
+```python
+conn.load_from_lerobot(
+ table_name="robot_all",
+ source=["/data/dataset_a", "/data/dataset_b"],
+ dataset_name=["dataset_a", "dataset_b"],
+ extra_dataset_fields={
+ "config": "config/*.json",
+ "notes": "notes.md",
+ },
+)
+```
+
+A literal file path creates a `STRING` column. A glob creates a
+`MAP<STRING, STRING>` column, even when it matches only one file. Map values
are
+file contents. Keys are relative to the directory prefix before the first glob
+component, with the final suffix removed. For example, `config/model_a.json`
+matched by `config/*.json` has key `model_a`, accessed in SQL as
+`config['model_a']`. Recursive patterns such as `config/**/*.json` retain
nested
+directories in keys: `config/nested/model_a.json` has key `nested/model_a`.
+
+Missing extra files and empty globs produce null values, with their declared
+`STRING` or `MAP<STRING, STRING>` column types retained. Unsupported
+suffixes, invalid UTF-8, paths outside the source root, duplicate keys after
+removing suffixes, and names that overwrite standard `_datasets` columns are
+rejected before creating target tables. Training readers project only required
+source metadata and skip extra text columns.
For FileIO URIs, pass credentials through `source_options`:
```python
conn.load_from_lerobot(
- "robot_data",
- "oss://source-bucket/lerobot_dataset",
+ table_name="robot_data",
+ source="oss://source-bucket/lerobot_dataset",
source_options={
"fs.oss.endpoint": "oss-cn-hangzhou.aliyuncs.com",
"fs.oss.accessKeyId": "SOURCE_ACCESS_KEY_ID",
@@ -125,7 +198,7 @@ For distributed import, install `pypaimon[ray,lerobot]` on
each worker:
import ray
ray.init(address="auto")
-conn.load_from_lerobot("robot_data", "oss://source-bucket/lerobot_dataset",
+conn.load_from_lerobot(table_name="robot_data",
source="oss://source-bucket/lerobot_dataset",
parallelism=8)
```
diff --git a/paimon-python/pypaimon/multimodal/connection.py
b/paimon-python/pypaimon/multimodal/connection.py
index 29e2324a53..a2f94612fb 100644
--- a/paimon-python/pypaimon/multimodal/connection.py
+++ b/paimon-python/pypaimon/multimodal/connection.py
@@ -142,8 +142,9 @@ class MultimodalConnection:
source_options=None,
tag_name=None,
parallelism=1,
- fps_mode="dataset",
- dataset_names=None) -> None:
+ dataset_name=None,
+ extra_dataset_fields=None,
+ schema_evolution=True) -> None:
"""Import LeRobot v3 sources using table_name as the group prefix.
Creates <table_name>_frames, <table_name>_episodes, and
@@ -159,8 +160,9 @@ class MultimodalConnection:
source_options=source_options,
tag_name=tag_name,
parallelism=parallelism,
- fps_mode=fps_mode,
- dataset_names=dataset_names,
+ dataset_name=dataset_name,
+ extra_dataset_fields=extra_dataset_fields,
+ schema_evolution=schema_evolution,
)
def create_lerobot_tag(self, table_name: str, tag_name: str):
diff --git a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
index 6ed7bb8482..adc68d4ee7 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/aggregate.py
@@ -29,12 +29,13 @@ from pypaimon.multimodal.lerobot.loader import (
_commit_messages, _prepare_dataset, _video_fps,
)
from pypaimon.multimodal.lerobot.metadata import (
- _EPISODE_CONTROL_COLUMNS, _EPISODE_FPS_COLUMN, _commit_metadata,
_json_value,
+ _EPISODE_CONTROL_COLUMNS, _commit_metadata, _json_value,
_load_dataset_metadata,
_metadata_table, _prepare_metadata_tables,
_source_episode_tables, _validated_episode_tables,
)
from pypaimon.multimodal.lerobot.schema import (
+ _V3_REQUIRED_FEATURE_DTYPES, _merge_schemas,
_require_v3, _schema_from_info, _validate_v3_required_features,
_video_feature_names,
)
@@ -45,6 +46,7 @@ from pypaimon.multimodal.lerobot.source import (
)
from pypaimon.multimodal.source_utils import _validate_source_kerberos
from pypaimon.multimodal.table import _target_schema
+from pypaimon.multimodal.lerobot.text_fields import _read_text_fields,
_text_fields_schema
_CONTROLS = ("index", "episode_index", "task_index", "subtask_index")
@@ -196,15 +198,17 @@ def _vocabulary(plans, kind):
tables = [plan["metadata"][key] for plan in plans]
if all(table is None for table in tables):
return None
- if any(table is None for table in tables):
- raise ValueError("LeRobot sources disagree on %s metadata." % kind)
singular = kind[:-1]
index_name = singular + "_index"
- schema = tables[0].schema
+ first_table = next(table for table in tables if table is not None)
+ schema = first_table.schema
label = _pandas_index_column(schema, singular)
- schema = tables[0].select([index_name, label]).schema
+ schema = first_table.select([index_name, label]).schema
rows, by_text = [], {}
for ordinal, (plan, table) in enumerate(zip(plans, tables)):
+ if table is None:
+ plan[index_name] = {}
+ continue
source_label = _pandas_index_column(table.schema, singular)
if (not table.schema.field(index_name).equals(
schema.field(index_name), check_metadata=False)
@@ -232,6 +236,7 @@ def _vocabulary(plans, kind):
def _feature_contract(features):
result = copy.deepcopy(features)
for feature in result.values():
+ feature.pop("nullable", None)
if feature.get("dtype") == "video":
feature.pop("fps", None)
for key in ("info", "video_info"):
@@ -243,72 +248,50 @@ def _feature_contract(features):
return result
-def _same_fields(left, right):
- return (set(left.names) == set(right.names)
- and all(left.field(name).equals(right.field(name),
check_metadata=False)
- for name in right.names))
-
-
-def _plan_merge(plans, fps_mode="dataset"):
+def _plan_merge(plans, extra_dataset_fields=None, schema_evolution=True):
first = plans[0]
- reserved_frame_fields = {
- _DATASET_INDEX_COLUMN, _SOURCE_FRAME_INDEX_COLUMN,
- }
- if reserved_frame_fields.intersection(first["schema"].names):
- raise ValueError("LeRobot source frame features use reserved source
index columns.")
+ mixed_fps = len({plan["metadata"]["fps"] for plan in plans}) > 1
+ reserved_frame_fields = {_DATASET_INDEX_COLUMN, _SOURCE_FRAME_INDEX_COLUMN}
+ for plan in plans:
+ if reserved_frame_fields.intersection(plan["schema"].names):
+ raise ValueError("LeRobot source frame features use reserved
source index columns.")
+ frame_schema = _merge_schemas([plan["schema"] for plan in plans],
schema_evolution,
+ _V3_REQUIRED_FEATURE_DTYPES)
+ features, contracts = {}, {}
+ for ordinal, plan in enumerate(plans):
+ for name, feature in plan["info"]["features"].items():
+ contract = _feature_contract({name: feature})[name]
+ if name in contracts and contracts[name] != contract:
+ raise ValueError("LeRobot source %d has incompatible
features.%s." % (ordinal, name))
+ contracts[name] = contract
+ features.setdefault(name, copy.deepcopy(feature))
+ for field in frame_schema:
+ if field.nullable:
+ features[field.name]["nullable"] = True
info = copy.deepcopy(first["info"])
+ info["features"] = features
metadata = dict(first["metadata"])
- # Keep source file locations and statistics in four JSON columns rather
- # than expanding their source-specific fields into the target schema.
- metadata["episodes_schema"] = pa.schema([
- field for field in metadata["episodes_schema"]
- if not field.name.startswith("stats/")
- and not (fps_mode == "source" and field.name == _EPISODE_FPS_COLUMN)
- ], metadata=metadata["episodes_schema"].metadata)
- required_episode_fields = set(_EPISODE_CONTROL_COLUMNS) | {
- "videos/%s/%s" % (name, suffix)
- for name in first["videos"]
- for suffix in ("chunk_index", "file_index", "from_timestamp",
"to_timestamp")
- }
- # Retain only compatible Episode fields shared by every source.
- metadata["episodes_schema"] = pa.schema([
- field if field.name in required_episode_fields else
field.with_nullable(
- field.nullable or
any(plan["metadata"]["episodes_schema"].field(field.name).nullable
- for plan in plans))
- for field in metadata["episodes_schema"]
- if field.name in required_episode_fields or all(
- field.name in plan["metadata"]["episodes_schema"].names
- and
field.type.equals(plan["metadata"]["episodes_schema"].field(field.name).type)
- for plan in plans)
- ], metadata=metadata["episodes_schema"].metadata)
+ metadata["frame_schema"] = frame_schema
+ # Merged Episode extensions are stored in JSON, not added as typed columns.
+ schemas = [pa.schema([
+ plan["metadata"]["episodes_schema"].field(name)
+ for name in _EPISODE_CONTROL_COLUMNS
+ ]) for plan in plans]
+ metadata["episodes_schema"] = _merge_schemas(schemas, schema_evolution,
_EPISODE_CONTROL_COLUMNS)
frame_offset = episode_offset = 0
for ordinal, plan in enumerate(plans):
other = plan["info"]
compared_keys = ("codebase_version", "robot_type")
- if fps_mode == "dataset":
- compared_keys += ("fps",)
for key in compared_keys:
if info.get(key) != other.get(key):
raise ValueError("LeRobot source %d has incompatible info.%s."
% (ordinal, key))
- expected_features = _feature_contract(info["features"])
- actual_features = _feature_contract(other["features"])
- for name in set(expected_features) | set(actual_features):
- if expected_features.get(name) != actual_features.get(name):
- raise ValueError("LeRobot source %d has incompatible
features.%s." % (ordinal, name))
- if not _same_fields(plan["schema"], first["schema"]):
- raise ValueError("LeRobot source %d has incompatible frame
schema." % ordinal)
- episode_schema = plan["metadata"]["episodes_schema"]
- if any(name not in episode_schema.names
- or not episode_schema.field(name).equals(
- metadata["episodes_schema"].field(name),
check_metadata=False)
- for name in required_episode_fields):
- raise ValueError("LeRobot source %d has incompatible Episode
schema." % ordinal)
# Validate every Episode before creating any target table.
- plan["metadata"]["fps_mode"] = fps_mode
+ if mixed_fps:
+ plan["metadata"]["fps_mode"] = "source"
try:
for name in plan["videos"]:
_video_fps(other, other["features"][name], name)
- for table in _validated_episode_tables(plan["metadata"],
first["videos"]):
+ for table in _validated_episode_tables(plan["metadata"],
plan["videos"]):
_validate_episode_json(table, ordinal)
except ValueError as error:
raise ValueError("LeRobot source %d: %s" % (ordinal, error)) from
error
@@ -354,18 +337,17 @@ def _plan_merge(plans, fps_mode="dataset"):
"tasks": _vocabulary_rows(plan["metadata"]["source_tasks_table"],
"task"),
"subtasks":
_vocabulary_rows(plan["metadata"]["source_subtasks_table"], "subtask"),
"stats": _stats_json(plan["metadata"]["stats_table"]),
+ **plan.get("extra_dataset_fields", {}),
}
for ordinal, plan in enumerate(plans)
- ], schema=_DATASETS_SCHEMA)
- metadata["fps_mode"] = fps_mode
+ ], schema=pa.schema(list(_DATASETS_SCHEMA) +
_text_fields_schema(extra_dataset_fields or {})))
+ metadata["fps_mode"] = "source" if mixed_fps else "dataset"
info.update(total_frames=frame_offset, total_episodes=episode_offset,
total_tasks=metadata["tasks_table"].num_rows,
splits={"train": "0:%d" % episode_offset})
- mixed_fps = len({plan["metadata"]["fps"] for plan in plans}) > 1
info.pop("fps_mode", None)
- if fps_mode == "source":
- info["fps_mode"] = "source"
if mixed_fps:
+ info["fps_mode"] = "source"
info["fps"] = None
for feature in info["features"].values():
if feature.get("dtype") != "video":
@@ -380,9 +362,10 @@ def _plan_merge(plans, fps_mode="dataset"):
"chunks_size", "data_files_size_in_mb",
"video_files_size_in_mb"):
info.pop(key, None)
# Encoder descriptions are not training features. Retain only shared
values.
- for name in first["videos"]:
+ for name in _video_feature_names(info):
for key in ("info", "video_info"):
- details = [p["info"]["features"][name].get(key) for p in plans]
+ details = [p["info"]["features"][name].get(key) for p in plans
+ if name in p["info"]["features"]]
details = [d if isinstance(d, dict) else {} for d in details]
info["features"][name][key] = {
k: v for k, v in details[0].items()
@@ -393,10 +376,9 @@ def _plan_merge(plans, fps_mode="dataset"):
merged_stats = None
if stats[0] is not None:
decoded = [_json_table(s) for s in stats]
- if any(set(s) != set(decoded[0]) for s in decoded[1:]):
- raise ValueError("LeRobot statistics features must match.")
- merged_stats = {name: _merge_stats([s[name] for s in decoded])
- for name in decoded[0] if name not in _CONTROLS}
+ names = dict.fromkeys(name for item in decoded for name in item)
+ merged_stats = {name: _merge_stats([item[name] for item in decoded if
name in item])
+ for name in names if name not in _CONTROLS}
metadata["info_table"] = _metadata_table(info)
metadata["stats_table"] = (None if merged_stats is None
else _metadata_table(merged_stats))
@@ -477,7 +459,7 @@ def _merged_episodes(plans, schema):
def _import_sources(connection, table_name, sources, batch_size, options,
source_options, tag_name, parallelism=1,
- fps_mode="dataset", dataset_names=None):
+ dataset_name=None, extra_dataset_fields=None,
schema_evolution=True):
from functools import partial
from pypaimon.multimodal.lerobot.api import _create_target_table,
_validated_counts
@@ -507,18 +489,19 @@ def _import_sources(connection, table_name, sources,
batch_size, options,
plans.append({"dataset": dataset, "dataset_resources":
dataset_resources,
"source": resolved, "info": info,
_DATASET_INDEX_COLUMN: ordinal,
- "dataset_name": (dataset_names[ordinal] if
dataset_names is not None
+ "dataset_name": (dataset_name[ordinal] if
dataset_name is not None
else None),
"schema": schema, "videos": videos,
+ "extra_dataset_fields": _read_text_fields(resolved,
extra_dataset_fields),
"metadata": _load_dataset_metadata(dataset, info,
resolved)})
- metadata, stats = _plan_merge(plans, fps_mode)
- target_schema = plans[0]["schema"]
+ metadata, stats = _plan_merge(plans, extra_dataset_fields,
schema_evolution)
+ target_schema = metadata["frame_schema"]
for field in (
pa.field(_DATASET_INDEX_COLUMN, pa.int64(), nullable=False),
pa.field(_SOURCE_FRAME_INDEX_COLUMN, pa.int64(),
nullable=False)):
target_schema = target_schema.append(field)
table = _create_target_table(connection, table_name, target_schema,
- options, metadata, plans[0]["videos"])
+ options, metadata,
_video_feature_names(_json_table(metadata["info_table"])))
tables = _prepare_metadata_tables(connection, table.raw_table,
metadata)
episode_schema = _target_schema(tables["episodes"])
commit = table.raw_table.new_batch_write_builder().new_commit()
diff --git a/paimon-python/pypaimon/multimodal/lerobot/api.py
b/paimon-python/pypaimon/multimodal/lerobot/api.py
index 4c47821409..9ee7b312cd 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/api.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/api.py
@@ -58,6 +58,7 @@ from pypaimon.multimodal.source_utils import (
_validated_source_options,
_validate_source_kerberos,
)
+from pypaimon.multimodal.lerobot.text_fields import _validated_text_fields
_VIDEO_LAYOUT_ERROR = (
@@ -76,16 +77,20 @@ def load_from_lerobot(
source_options: Optional[Mapping[str, object]] = None,
tag_name: Optional[str] = None,
parallelism: int = 1,
- fps_mode: str = "dataset",
- dataset_names=None,
+ dataset_name=None,
+ extra_dataset_fields: Optional[Mapping[str, str]] = None,
+ schema_evolution: bool = True,
) -> None:
"""Import one or more LeRobot v3 sources into a new Paimon table group.
``table_name`` is the group prefix; frames are stored in
``<table_name>_frames``.
- Sources must share training features. ``fps_mode='source'`` allows mixed
- FPS. ``_datasets`` retains source metadata; optional ``dataset_names``
- are caller-provided labels, never inferred from paths. ``tag_name`` pins
- component snapshots.
+ Schema evolution adds new columns by default; missing values become null.
+ Common fields must keep their types and feature definitions. Differing
+ source FPS is handled automatically. ``dataset_name`` is a label or an
ordered
+ list of labels. ``extra_dataset_fields`` maps columns to relative UTF-8
+ text file paths or globs in each source. Globs produce maps keyed by paths
+ relative to their static directory prefix, without the final suffix.
+ ``_datasets`` retains source metadata. ``tag_name`` pins component
snapshots.
FileIO credentials come from ``source_options``; ``parallelism > 1`` uses
Ray.
"""
if sys.version_info < (3, 10):
@@ -99,17 +104,21 @@ def load_from_lerobot(
if isinstance(parallelism, bool) or not isinstance(parallelism, int) \
or parallelism <= 0:
raise ValueError("parallelism must be a positive integer.")
- if fps_mode not in ("dataset", "source"):
- raise ValueError("fps_mode must be 'dataset' or 'source'.")
- if dataset_names is not None:
- if not isinstance(dataset_names, (list, tuple)) or len(dataset_names)
!= (
+ if not isinstance(schema_evolution, bool):
+ raise ValueError("schema_evolution must be a boolean.")
+ if dataset_name is not None:
+ if isinstance(dataset_name, str):
+ dataset_name = [dataset_name]
+ if not isinstance(dataset_name, (list, tuple)) or len(dataset_name) !=
(
len(source) if isinstance(source, (list, tuple)) else 1) \
or any(not isinstance(name, str) or not name.strip()
- for name in dataset_names):
- raise ValueError("dataset_names must contain one non-empty name
per source.")
- dataset_names = [name.strip() for name in dataset_names]
- if isinstance(source, (list, tuple)) or fps_mode == "source" \
- or dataset_names is not None:
+ for name in dataset_name):
+ raise ValueError("dataset_name must contain one non-empty name per
source.")
+ dataset_name = [name.strip() for name in dataset_name]
+ if extra_dataset_fields is not None:
+ from pypaimon.multimodal.lerobot.aggregate import _DATASETS_SCHEMA
+ extra_dataset_fields = _validated_text_fields(extra_dataset_fields,
_DATASETS_SCHEMA.names)
+ if isinstance(source, (list, tuple)) or dataset_name is not None or
extra_dataset_fields:
if not isinstance(source, (list, tuple)):
source = [source]
if not source:
@@ -120,7 +129,7 @@ def load_from_lerobot(
return _import_sources(
connection, table_name, source, batch_size, options,
_validated_source_options(source_options), tag_name, parallelism,
- fps_mode, dataset_names)
+ dataset_name, extra_dataset_fields, schema_evolution)
if parallelism > 1:
from pypaimon.multimodal.lerobot.ray_loader import _require_ray,
_ray_source_uri
_require_ray()
diff --git a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
index 99fca15596..98031503d3 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/dataset.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/dataset.py
@@ -52,6 +52,7 @@ from pypaimon.multimodal.lerobot.loader import
_DECLARED_NUMERIC_RANGES, _video_
from pypaimon.multimodal.lerobot.reader import _PaimonTableFrameReader
from pypaimon.multimodal.lerobot.schema import (
_feature_shape,
+ _merge_schemas,
_require_v3,
_schema_from_info,
_validate_lerobot_schema,
@@ -554,14 +555,16 @@ class PaimonDatasetReader(ABC):
item[key] = visual_windows[key][offset]
else:
values = [converted[position][key] for position in
positions]
- if key == "subtask_index" and _contains_none(values):
- item[key] = values
+ if _contains_none(values):
+ item[key] = (None if key != "subtask_index"
+ and all(value is None for value in
values) else values)
else:
item[key] = torch.stack(values)
item.update(plan["padding"])
if self.image_transforms is not None:
for key in self._visual_keys:
- item[key] = self.image_transforms(item[key])
+ if item[key] is not None:
+ item[key] = self.image_transforms(item[key])
result.append(item)
if return_batch:
return _collate_lerobot_batch(result, video_windows)
@@ -1114,7 +1117,9 @@ def _source_vocabulary(sources, singular):
values = [source.get(field) for source in sources]
if all(value is None for value in values) and singular == "subtask":
return None, None
- if any(value is None for value in values):
+ if singular == "subtask":
+ values = [value if value is not None else [] for value in values]
+ elif any(value is None for value in values):
raise ValueError("LeRobot sources disagree on %s metadata." % field)
by_text, rows, maps = {}, [], []
for ordinal, entries in enumerate(values):
@@ -1152,6 +1157,13 @@ def _merged_source_info(sources, tasks, subtasks,
fps_mode):
raise ValueError("LeRobot source %d has invalid info." % ordinal)
infos.append(info)
merged = copy.deepcopy(infos[0])
+ merged["features"] = {}
+ for info in infos:
+ for name, feature in info["features"].items():
+ merged["features"].setdefault(name, copy.deepcopy(feature))
+ for field in _merge_schemas([_schema_from_info(info) for info in infos]):
+ if field.nullable:
+ merged["features"][field.name]["nullable"] = True
for key in list(merged):
if key not in _REBUILT_INFO and key not in ("codebase_version",
"robot_type", "fps") \
and any(info.get(key) != merged[key] for info in infos):
@@ -1181,7 +1193,8 @@ def _merged_source_info(sources, tasks, subtasks,
fps_mode):
if feature.get("dtype") != "video":
continue
for key in ("info", "video_info"):
- details = [info["features"][name].get(key) for info in infos]
+ details = [info["features"][name].get(key) for info in infos
+ if name in info["features"]]
details = [value if isinstance(value, dict) else {} for value in
details]
feature[key] = {k: v for k, v in details[0].items()
if all(value.get(k) == v for value in details[1:])}
@@ -1195,10 +1208,9 @@ def _merged_source_stats(sources, episodes_table):
if any(value is None for value in values):
raise ValueError("LeRobot sources disagree on stats metadata.")
decoded = [json.loads(value) for value in values]
- if any(set(value) != set(decoded[0]) for value in decoded[1:]):
- raise ValueError("LeRobot source statistics features differ.")
- merged = {name: _merge_stats([value[name] for value in decoded])
- for name in decoded[0] if name not in _CONTROLS}
+ names = dict.fromkeys(name for value in decoded for name in value)
+ merged = {name: _merge_stats([value[name] for value in decoded if name in
value])
+ for name in names if name not in _CONTROLS}
columns = _target_schema(episodes_table).names
if "stats" in columns:
stats_rows = _read_arrow(episodes_table,
["stats"])["stats"].to_pylist()
@@ -1632,8 +1644,12 @@ def _numeric_tensor_rows(column, name, feature):
import numpy as np
import torch
- values = column.combine_chunks()
+ values = column.combine_chunks() if isinstance(column, pa.ChunkedArray)
else column
if values.null_count:
+ if feature.get("nullable"):
+ valid = pc.is_valid(values)
+ converted = iter(_numeric_tensor_rows(pc.filter(values, valid),
name, feature))
+ return [next(converted) if present else None for present in
valid.to_pylist()]
raise ValueError(
"LeRobot numeric feature %s contains null values." % name)
shape = _feature_shape(feature, name)
@@ -1776,7 +1792,7 @@ def _resolve_image_blobs(
for rows in row_groups:
for row in rows.values():
for key in image_keys:
- if key in row:
+ if key in row and row[key] is not None:
targets[key].append(row)
values[key].append(row[key])
used = [key for key in image_keys if values[key]]
@@ -1793,7 +1809,7 @@ def _decode_image_rows(row_groups, image_keys, features,
return_uint8):
for rows in row_groups:
for row in rows.values():
for key in image_keys:
- if key in row:
+ if key in row and row[key] is not None:
row[key] = _image_tensor(
row[key], features[key], return_uint8=return_uint8)
@@ -1804,7 +1820,7 @@ def _image_blob_sources(row_groups, image_keys):
for rows in row_groups
for row in rows.values()
for key in image_keys
- if key in row
+ if key in row and row[key] is not None
]
@@ -2052,6 +2068,9 @@ def _collate_lerobot_batch(rows, video_windows):
nullable["subtask_index"], dtype=torch.bool)
if "subtask" in rows[0] and any(_contains_none(row["subtask"]) for row in
rows):
nullable["subtask"] = [row["subtask"] for row in rows]
+ for key in rows[0]:
+ if key not in nullable and any(_contains_none(row[key]) for row in
rows):
+ nullable[key] = [row[key] for row in rows]
if not video_windows and not nullable:
return default_collate(rows)
remaining = [{
@@ -2083,9 +2102,9 @@ def _stack_visual_windows(plans, rows, visual_keys):
def stack(key):
with torch.inference_mode(inference_enabled), \
torch.set_grad_enabled(grad_enabled):
- return [torch.stack([
- rows[position][key] for position in plan["windows"][key]
- ]) for plan in plans]
+ windows = [[rows[position][key] for position in
plan["windows"][key]] for plan in plans]
+ return [None if all(value is None for value in window) else window
+ if _contains_none(window) else torch.stack(window) for
window in windows]
with ThreadPoolExecutor(
max_workers=min(len(keys), _MAX_VISUAL_WORKERS)) as executor:
@@ -2100,6 +2119,8 @@ def _torch_row(row, features, return_uint8=False):
if key not in result:
continue
value = result[key]
+ if value is None:
+ continue
if feature.get("dtype") == "image" and not torch.is_tensor(value):
result[key] = _image_tensor(
value, feature, return_uint8=return_uint8)
@@ -2784,7 +2805,7 @@ def _decode_video_rows(
input_rows = []
for rows in row_groups:
for index, row in rows.items():
- if collator.video_column in row:
+ if collator.video_column in row and row[collator.video_column]
is not None:
targets.append((rows, index))
input_rows.append(row)
if not input_rows:
diff --git a/paimon-python/pypaimon/multimodal/lerobot/loader.py
b/paimon-python/pypaimon/multimodal/lerobot/loader.py
index 4576ef2209..c8c97fe46c 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/loader.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/loader.py
@@ -183,7 +183,12 @@ def _prepare_dataset(
)
observed_tasks.update(seen_tasks)
if transform is not None:
- batch = transform(batch,
episode_index).select(target_schema.names)
+ batch = transform(batch, episode_index)
+ batch = pa.Table.from_arrays([
+ batch[field.name] if field.name in batch.column_names
+ else pa.nulls(batch.num_rows, type=field.type)
+ for field in target_schema
+ ], schema=target_schema)
batch = _strict_lerobot_table(
batch,
target_schema,
diff --git a/paimon-python/pypaimon/multimodal/lerobot/schema.py
b/paimon-python/pypaimon/multimodal/lerobot/schema.py
index 8071a5b14f..73e602fe1a 100644
--- a/paimon-python/pypaimon/multimodal/lerobot/schema.py
+++ b/paimon-python/pypaimon/multimodal/lerobot/schema.py
@@ -157,7 +157,7 @@ def _feature_field(name, feature, legacy_vectors=False):
return pa.field(
name,
arrow_type,
- nullable=name == "subtask_index",
+ nullable=name == "subtask_index" or bool(feature.get("nullable",
False)),
metadata={b"description": description.encode("utf-8")},
)
@@ -188,3 +188,27 @@ def _tensor_type(scalar_type, shape, legacy_vectors=False):
for unused_size in (shape[:-1] if legacy_vectors else shape):
result = pa.list_(result)
return result
+
+
+def _merge_schemas(schemas, schema_evolution=True, required=()):
+ """Merge top-level columns without promoting types or changing nested
schemas."""
+ fields = {}
+ first_names = set(schemas[0].names)
+ for ordinal, schema in enumerate(schemas):
+ missing = set(required) - set(schema.names)
+ if missing:
+ raise ValueError("LeRobot source %d is missing required fields:
%s."
+ % (ordinal, sorted(missing)))
+ for field in schema:
+ if not schema_evolution and field.name not in first_names:
+ raise ValueError("LeRobot source %d adds field %s with
schema_evolution disabled."
+ % (ordinal, field.name))
+ if field.name in fields and not
fields[field.name].type.equals(field.type):
+ raise ValueError("LeRobot source %d has incompatible type for
field %s: %s versus %s."
+ % (ordinal, field.name, field.type,
fields[field.name].type))
+ fields.setdefault(field.name, field)
+ return pa.schema([
+ field.with_nullable(any(name not in schema.names or
schema.field(name).nullable
+ for schema in schemas))
+ for name, field in fields.items()
+ ], metadata=schemas[0].metadata)
diff --git a/paimon-python/pypaimon/multimodal/lerobot/text_fields.py
b/paimon-python/pypaimon/multimodal/lerobot/text_fields.py
new file mode 100644
index 0000000000..ac433848ea
--- /dev/null
+++ b/paimon-python/pypaimon/multimodal/lerobot/text_fields.py
@@ -0,0 +1,184 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Optional source text files stored as LeRobot dataset columns."""
+
+from collections.abc import Mapping
+from fnmatch import fnmatchcase
+from glob import has_magic
+from pathlib import Path
+import posixpath
+from urllib.parse import unquote, urlparse
+
+import pyarrow as pa
+import pyarrow.fs as pafs
+
+from pypaimon.filesystem.pyarrow_file_io import LegacyOssDirectoryListingError
+from pypaimon.multimodal.lerobot.source import (
+ _read_remote_bytes,
+ _relative_dataset_path,
+ _remote_source_path,
+)
+from pypaimon.multimodal.source_utils import _qualified_status_path
+
+
+_TEXT_SUFFIXES = {".json", ".txt", ".md", ".yaml", ".yml", ".jsonl",
".ndjson", ".csv", ".tsv"}
+
+
+def _validated_text_fields(fields, reserved):
+ if fields is None:
+ return {}
+ if not isinstance(fields, Mapping):
+ raise ValueError("extra_dataset_fields must map column names to
relative file paths.")
+ result = {}
+ for name, pattern in fields.items():
+ if not isinstance(name, str) or not name.strip() or name in reserved:
+ raise ValueError("Invalid or reserved extra_dataset_fields column:
%r." % (name,))
+ result[name] = _relative_dataset_path(pattern,
"extra_dataset_fields.%s" % name)
+ if not has_magic(result[name]):
+ _validate_text_suffix(result[name])
+ return result
+
+
+def _text_fields_schema(fields):
+ return [pa.field(name, pa.map_(pa.string(), pa.string()) if
has_magic(pattern) else pa.string(),
+ nullable=True) for name, pattern in fields.items()]
+
+
+def _validate_text_suffix(path):
+ if posixpath.splitext(path)[1].lower() not in _TEXT_SUFFIXES:
+ raise ValueError("Unsupported extra dataset text file suffix: %s." %
path)
+
+
+def _local_text_path(root, relative):
+ path = root / relative
+ try:
+ path.resolve().relative_to(root.resolve())
+ except ValueError as error:
+ raise ValueError("Extra dataset text file must stay within the source
directory: %s."
+ % relative) from error
+ return path
+
+
+def _glob_fileio(source, pattern):
+ def walk(directory, parts):
+ uri = (_remote_source_path(source.path, directory,
"extra_dataset_fields", source.file_io)
+ if directory else source.path)
+ try:
+ statuses = source.file_io.list_status(uri)
+ except FileNotFoundError:
+ return
+ except LegacyOssDirectoryListingError as error:
+ raise ValueError("Extra dataset text file listing is unavailable
at %s; use Jindo "
+ "or upgrade PyArrow." % uri) from error
+ part = parts[0]
+ if part == "**" and len(parts) > 1:
+ yield from walk(directory, parts[1:])
+ for status in statuses:
+ name =
posixpath.basename(unquote(urlparse(_qualified_status_path(uri,
status)).path).rstrip("/"))
+ child = posixpath.join(directory, name)
+ if part == "**":
+ if status.type == pafs.FileType.Directory:
+ yield from walk(child, parts)
+ elif len(parts) == 1 and status.type == pafs.FileType.File:
+ yield child
+ elif fnmatchcase(name, part):
+ if len(parts) == 1 and status.type == pafs.FileType.File:
+ yield child
+ elif len(parts) > 1 and status.type == pafs.FileType.Directory:
+ yield from walk(child, parts[1:])
+
+ return sorted(set(walk("", pattern.split("/"))))
+
+
+def _matches_path(path, pattern):
+ """Match Hub paths with the same directory boundaries as filesystem
globs."""
+ parts, patterns = path.split("/"), pattern.split("/")
+
+ def match(i, j):
+ if j == len(patterns):
+ return i == len(parts)
+ if patterns[j] == "**":
+ return match(i, j + 1) or (i < len(parts) and match(i + 1, j))
+ return i < len(parts) and fnmatchcase(parts[i], patterns[j]) and
match(i + 1, j + 1)
+
+ return match(0, 0)
+
+
+def _read_text_fields(source, fields):
+ if not fields:
+ return {}
+ root = source.root
+ if root is None and urlparse(source.path).scheme == "file":
+ root = Path(source.file_io.to_filesystem_path(source.path))
+ hub_files = None
+ missing_errors = (FileNotFoundError,)
+ if root is None and source.file_io is None:
+ from huggingface_hub.errors import EntryNotFoundError
+ missing_errors += (EntryNotFoundError,)
+ if root is None and source.file_io is None and any(has_magic(pattern) for
pattern in fields.values()):
+ from huggingface_hub import list_repo_files
+ hub_files = list_repo_files(source.repo_id, repo_type="dataset")
+ result = {}
+ for name, pattern in fields.items():
+ multiple = has_magic(pattern)
+ if not multiple:
+ paths = [pattern]
+ elif root is not None:
+ paths = sorted(path.relative_to(root).as_posix()
+ for path in root.glob(pattern) if path.is_file())
+ elif source.file_io is not None:
+ paths = _glob_fileio(source, pattern)
+ else:
+ paths = sorted(path for path in hub_files if _matches_path(path,
pattern))
+ if not paths:
+ result[name] = None
+ continue
+ base = []
+ for part in pattern.split("/"):
+ if has_magic(part):
+ break
+ base.append(part)
+ values = {}
+ for path in paths:
+ _validate_text_suffix(path)
+ try:
+ if root is not None:
+ content = _local_text_path(root, path).read_bytes()
+ elif source.file_io is not None:
+ uri = _remote_source_path(source.path, path,
"extra_dataset_fields.%s" % name,
+ source.file_io)
+ content = _read_remote_bytes(source.file_io, uri)
+ else:
+ from huggingface_hub import hf_hub_download
+ content = Path(hf_hub_download(source.repo_id, path,
repo_type="dataset")).read_bytes()
+ text = content.decode("utf-8")
+ except missing_errors:
+ result[name] = None
+ break
+ except (OSError, UnicodeError) as error:
+ raise ValueError("Cannot read UTF-8 extra dataset field %s
from %s: %s."
+ % (name, path, error)) from error
+ if multiple:
+ key = posixpath.splitext(posixpath.relpath(path,
"/".join(base) or "."))[0]
+ if key in values:
+ raise ValueError("Duplicate extra dataset field key %r for
%s." % (key, name))
+ values[key] = text
+ else:
+ result[name] = text
+ if multiple and name not in result:
+ result[name] = values
+ return result
diff --git a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
index 3f3ae28017..313248d740 100644
--- a/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
+++ b/paimon-python/pypaimon/tests/lerobot_aggregate_test.py
@@ -112,9 +112,10 @@ def source(root, tasks=("pick", "place"),
subtasks=("reach", "grasp"), video=Fal
@pytest.fixture
-def setup(tmp_path):
+def setup(tmp_path, request):
a = source(tmp_path / "a")
- b = source(tmp_path / "b", tasks=("place", "stack"), subtasks=("grasp",
"release"), value=20)
+ b = source(tmp_path / "b", tasks=("place", "stack"), subtasks=("grasp",
"release"), value=20,
+ fps=getattr(request, "param", 10))
conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
return conn, [a, b]
@@ -502,7 +503,7 @@ def test_merge_preserves_integer_statistics(setup):
assert _merge_stats([summary, summary])["count"] == [2 * (2**53 + 1)]
[email protected]("field", ["fps", "robot_type", "features", "stats"])
[email protected]("field", ["robot_type", "features", "stats"])
def test_incompatible_sources_fail_before_creation(setup, field):
conn, sources = setup
root = Path(sources[1][7:])
@@ -514,7 +515,7 @@ def test_incompatible_sources_fail_before_creation(setup,
field):
if field == "features":
info[field]["action"]["names"] = ["different", "axes"]
else:
- info[field] = 20 if field == "fps" else "different"
+ info[field] = "different"
path.write_text(json.dumps(info))
with pytest.raises(ValueError):
conn.load_from_lerobot("merged", sources)
@@ -538,12 +539,12 @@ def test_missing_stats_and_existing_target(setup):
def test_single_source_metadata_opt_in(setup, import_parallelism):
pytest.importorskip("torch")
conn, sources = setup
- conn.load_from_lerobot("single", sources[0], fps_mode="source",
+ conn.load_from_lerobot("single", sources[0], dataset_name="single",
parallelism=import_parallelism)
reader = pm.PaimonLeRobotDataset(conn.get_table("single_frames"))
info = reader.reader.meta.info
assert info["fps"] == 10
- assert info["fps_mode"] == "source"
+ assert "fps_mode" not in info
assert [json.loads(value)["fps"] for value in
rows(conn, "single_datasets")["info"].to_pylist()] == [10]
assert rows(conn, "single_episodes")["dataset_index"].to_pylist() == [0, 0]
@@ -560,7 +561,7 @@ def
test_source_info_remains_distinct_from_merged_info(setup):
info["vendor_extension"] = {"source": ordinal}
path.write_text(json.dumps(info))
conn.load_from_lerobot("merged", sources,
- dataset_names=["move cup", "empty cup"])
+ dataset_name=["move cup", "empty cup"])
assert "vendor_extension" not in metadata(conn, "info")
datasets = rows(conn, "merged_datasets").sort_by("index")
assert datasets["name"].to_pylist() == ["move cup", "empty cup"]
@@ -568,9 +569,8 @@ def
test_source_info_remains_distinct_from_merged_info(setup):
for value in datasets["info"].to_pylist()] == [0, 1]
[email protected]("fps_mode", ["dataset", "source"])
@pytest.mark.parametrize("dataset_index", [None, 0, 1])
-def test_source_selection_derives_unequal_ranges_from_info(setup, fps_mode,
dataset_index):
+def test_source_selection_derives_unequal_ranges_from_info(setup,
dataset_index):
pytest.importorskip("datasets")
pytest.importorskip("torch")
conn, sources = setup
@@ -585,7 +585,7 @@ def
test_source_selection_derives_unequal_ranges_from_info(setup, fps_mode, data
path.write_text(json.dumps(info))
for uri in sources:
(Path(uri[7:]) / "meta/stats.json").unlink()
- conn.load_from_lerobot("merged", sources, fps_mode=fps_mode)
+ conn.load_from_lerobot("merged", sources)
reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"),
dataset_index=dataset_index)
try:
indices = list(range(7)) if dataset_index is None else (
@@ -610,7 +610,7 @@ def
test_source_info_counts_must_match_episode_layout(setup, field, counts):
pytest.importorskip("datasets")
pytest.importorskip("torch")
conn, sources = setup
- conn.load_from_lerobot("merged", sources, fps_mode="source")
+ conn.load_from_lerobot("merged", sources)
reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"))
try:
for dataset, count in zip(reader.meta.datasets, counts):
@@ -633,7 +633,7 @@ def
test_nested_lerobot_source_does_not_infer_business_name(tmp_path):
def test_shared_business_label_does_not_merge_source_datasets(setup):
conn, sources = setup
conn.load_from_lerobot("merged", sources,
- dataset_names=["same task", "same task"])
+ dataset_name=["same task", "same task"])
datasets = rows(conn, "merged_datasets").sort_by("index")
assert datasets["index"].to_pylist() == [0, 1]
assert datasets["name"].to_pylist() == ["same task", "same task"]
@@ -641,13 +641,13 @@ def
test_shared_business_label_does_not_merge_source_datasets(setup):
0, 1, 0, 1]
-def test_dataset_names_validate_before_source_access(tmp_path):
+def test_dataset_name_validate_before_source_access(tmp_path):
conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
with patch("pypaimon.multimodal.lerobot.source._resolved_source",
side_effect=AssertionError("source accessed")):
- with pytest.raises(ValueError, match="dataset_names"):
+ with pytest.raises(ValueError, match="dataset_name"):
conn.load_from_lerobot("merged", ["a", "b"],
- dataset_names=["only one name"])
+ dataset_name=["only one name"])
@pytest.mark.parametrize("sources,parallelism", [([], 1), (["unused",
"unused"], 0)])
@@ -693,7 +693,7 @@ def test_video_sources_with_identical_paths(tmp_path,
import_parallelism):
sources = [source(tmp_path / "a", video=True, value=0),
source(tmp_path / "b", video=True, value=100)]
conn.load_from_lerobot("merged", sources, batch_size=2, tag_name="train",
- parallelism=import_parallelism, fps_mode="source")
+ parallelism=import_parallelism)
table = conn.get_table("merged_frames").raw_table
imported = rows(conn, "merged_frames").sort_by("index")
episodes = episode_rows(conn, "merged_episodes")
@@ -731,12 +731,8 @@ def test_mixed_fps_group_keeps_episode_rates(tmp_path,
import_parallelism):
conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
sources = [source(tmp_path / "a", video=True, fps=25, frames=16),
source(tmp_path / "b", video=True, fps=30, value=100,
frames=16)]
- with pytest.raises(ValueError, match="incompatible info.fps"):
- conn.load_from_lerobot("default_rejected", sources,
parallelism=import_parallelism)
- with pytest.raises(TableNotExistException):
- conn.get_table("default_rejected_frames")
conn.load_from_lerobot("merged", sources, batch_size=2, tag_name="train",
- parallelism=import_parallelism, fps_mode="source")
+ parallelism=import_parallelism)
info = metadata(conn, "info")
assert info["fps"] is None
assert info["fps_mode"] == "source"
@@ -795,7 +791,7 @@ def
test_vocabulary_columns_without_pandas_index_are_preserved(setup):
path = root / ("meta/%s.parquet" % component)
table = pq.read_table(path).replace_schema_metadata(None)
pq.write_table(table, path)
- conn.load_from_lerobot("merged", sources, fps_mode="source")
+ conn.load_from_lerobot("merged", sources)
dataset = rows(conn, "merged_datasets").sort_by("index").to_pylist()[0]
for component in ("tasks", "subtasks"):
expected = pq.read_table(Path(sources[0][7:]) / ("meta/%s.parquet" %
component))
@@ -920,23 +916,15 @@ def test_ray_worker_failure_does_not_commit(setup,
ray_cluster):
assert all(Path(uri[7:]).is_dir() for uri in sources)
[email protected]("mode", [None, "mixed", "", 1, ["episode"]])
-def test_invalid_fps_mode_before_io(tmp_path, mode):
- conn = pm.connect(options={"warehouse": str(tmp_path)})
- with pytest.raises(ValueError, match="fps_mode"):
- conn.load_from_lerobot("invalid", ["unused"], fps_mode=mode)
- assert conn.catalog.list_databases() == []
-
-
[email protected]("multiple", [False, True])
[email protected]("setup", [20], indirect=True)
@pytest.mark.parametrize("rate", [None, 0, -1, True, 10.5, 20])
-def test_source_fps_conflicts_before_creation(setup, tmp_path, multiple, rate):
+def test_source_fps_conflicts_before_creation(setup, tmp_path, rate):
conn, sources = setup
path = tmp_path / "a/meta/episodes/chunk-000/file-000.parquet"
data = pq.read_table(path).append_column("fps", pa.array([rate, rate]))
pq.write_table(data, path)
with pytest.raises(ValueError, match="fps"):
- conn.load_from_lerobot("invalid", sources if multiple else sources[0],
fps_mode="source")
+ conn.load_from_lerobot("invalid", sources)
with pytest.raises(TableNotExistException):
conn.get_table("invalid_frames")
@@ -947,8 +935,8 @@ def test_existing_source_episode_fps(setup, tmp_path,
import_parallelism, multip
conn, sources = setup
path = tmp_path / "a/meta/episodes/chunk-000/file-000.parquet"
pq.write_table(pq.read_table(path).append_column("fps", pa.array([10,
10])), path)
- conn.load_from_lerobot("merged", sources if multiple else sources[0],
- fps_mode="source", parallelism=import_parallelism)
+ conn.load_from_lerobot("merged", sources if multiple else [sources[0]],
+ parallelism=import_parallelism)
episodes = episode_rows(conn, "merged_episodes")
assert "fps" not in episodes.column_names
assert episodes["dataset_index"].to_pylist() == (
@@ -996,7 +984,8 @@ def test_merge_nullable_subtask_import(setup, tmp_path,
import_parallelism, all_
assert second["subtask_index"][0].item() == 0
[email protected]("rate", [None, 0, -1, True, 10.5, 20])
[email protected]("rate", [None, 0, -1, True, 10.5])
[email protected]("setup", [20], indirect=True)
def test_reader_rejects_invalid_source_fps(setup, rate):
pytest.importorskip("datasets")
@@ -1007,7 +996,7 @@ def test_reader_rejects_invalid_source_fps(setup, rate):
raise AssertionError("Invalid FPS must fail before reading frames")
conn, sources = setup
- conn.load_from_lerobot("merged", sources, fps_mode="source")
+ conn.load_from_lerobot("merged", sources)
meta = pm.PaimonLeRobotDataset(conn.get_table("merged_frames")).meta
info = json.loads(meta.datasets[0]["info"])
info["fps"] = rate
@@ -1023,7 +1012,7 @@ def test_reader_accepts_legacy_source_info(setup,
legacy_fps):
pytest.importorskip("datasets")
pytest.importorskip("torch")
conn, sources = setup
- conn.load_from_lerobot("merged", sources, fps_mode="source")
+ conn.load_from_lerobot("merged", sources)
reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"))
try:
for dataset in reader.meta.datasets:
@@ -1055,8 +1044,7 @@ def
test_reader_requires_fps_without_episode_column(setup):
pm.PaimonLeRobotDataset(conn.get_table("merged_frames"))
[email protected]("multiple", [False, True])
-def test_episode_fps_rejects_conflicting_video_feature(tmp_path, multiple):
+def test_episode_fps_rejects_conflicting_video_feature(tmp_path):
conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
uri = source(tmp_path / "source", video=True, fps=25)
path = tmp_path / "source/meta/info.json"
@@ -1064,7 +1052,7 @@ def
test_episode_fps_rejects_conflicting_video_feature(tmp_path, multiple):
info["features"]["camera"]["info"]["video.fps"] = 30
path.write_text(json.dumps(info))
with pytest.raises(ValueError, match="FPS"):
- conn.load_from_lerobot("invalid", [uri] if multiple else uri,
fps_mode="source")
+ conn.load_from_lerobot("invalid", [uri])
with pytest.raises(TableNotExistException):
conn.get_table("invalid_frames")
@@ -1212,6 +1200,7 @@ def test_legacy_single_source_extensions(setup, mode):
reader.close()
[email protected]("setup", [20], indirect=True)
def test_source_mode_rejects_broken_episode_link(setup):
pytest.importorskip("datasets")
pytest.importorskip("torch")
@@ -1222,7 +1211,7 @@ def test_source_mode_rejects_broken_episode_link(setup):
raise AssertionError("Invalid metadata must fail before reading")
conn, sources = setup
- conn.load_from_lerobot("merged", sources, fps_mode="source")
+ conn.load_from_lerobot("merged", sources)
meta = pm.PaimonLeRobotDataset(conn.get_table("merged_frames")).meta
episodes = meta.episodes.to_dict()
episodes["dataset_index"][0] = 1
@@ -1473,7 +1462,7 @@ def
test_merge_rejects_incompatible_episode_controls(setup):
data = pq.read_table(path)
data = data.set_column(data.schema.get_field_index("length"), "length",
data["length"].cast(pa.int32()))
pq.write_table(data, path)
- with pytest.raises(ValueError, match="incompatible Episode schema"):
+ with pytest.raises(ValueError, match="incompatible type.*length"):
conn.load_from_lerobot("merged", sources)
with pytest.raises(TableNotExistException):
conn.get_table("merged_frames")
@@ -1508,8 +1497,7 @@ def test_merge_optional_video_metadata(tmp_path, key,
value, reverse):
@pytest.mark.parametrize("import_parallelism", [1, 2], indirect=True)
[email protected]("fps_mode", ["dataset", "source"])
-def test_merge_reserves_fps_mode(setup, import_parallelism, fps_mode):
+def test_merge_reserves_fps_mode(setup, import_parallelism):
pytest.importorskip("datasets")
pytest.importorskip("torch")
conn, sources = setup
@@ -1518,13 +1506,10 @@ def test_merge_reserves_fps_mode(setup,
import_parallelism, fps_mode):
info = json.loads(path.read_text())
info["fps_mode"] = "episode"
path.write_text(json.dumps(info))
- conn.load_from_lerobot("merged", sources, fps_mode=fps_mode,
+ conn.load_from_lerobot("merged", sources,
parallelism=import_parallelism, tag_name="train")
info = metadata(conn, "info")
- if fps_mode == "dataset":
- assert "fps_mode" not in info
- else:
- assert info["fps_mode"] == "source"
+ assert "fps_mode" not in info
for row in rows(conn, "merged_datasets").to_pylist():
assert json.loads(row["info"])["fps_mode"] == "episode"
reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"),
tag_name="train")
@@ -1614,7 +1599,7 @@ def test_ray_groups_within_each_source(setup,
ray_cluster, multiple):
with patch.object(ray_cluster, "remote", side_effect=track_remote):
conn.load_from_lerobot("merged", sources if multiple else sources[0],
- dataset_names=["A", "B"] if multiple else
["A"], parallelism=2)
+ dataset_name=["A", "B"] if multiple else ["A"],
parallelism=2)
assert dispatched == [[0], [1]] * (2 if multiple else 1)
assert rows(conn, "merged_frames").num_rows == (10 if multiple else 5)
assert rows(conn, "merged_episodes").num_rows == (4 if multiple else 2)
@@ -1668,3 +1653,286 @@ def
test_uncertain_commit_preserves_published_files(setup, tmp_path, fail_commit
assert any("merged_frames" in path.parts for path in files)
episode_files = [path for path in files if "merged_episodes" in path.parts]
assert bool(episode_files) == (fail_commit == 2)
+
+
[email protected]("multiple", [False, True])
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_extra_dataset_text_fields(setup, multiple, import_parallelism):
+ from pypaimon.multimodal.lerobot import dataset as dataset_module
+
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ expected = []
+ for ordinal, uri in enumerate(sources):
+ root = Path(uri[7:])
+ (root / "config").mkdir()
+ contents = {"model_a": '{ "value": %d }\r\n' % ordinal,
+ "model_b": '{ "label": "示例" }\n'}
+ for name, text in contents.items():
+ (root / "config" / (name +
".json")).write_bytes(text.encode("utf-8"))
+ notes = "# Dataset %d\r\nNotes.\n" % ordinal
+ (root / "notes.md").write_bytes(notes.encode("utf-8"))
+ expected.append((contents, notes))
+ conn.load_from_lerobot(
+ table_name="merged", source=sources if multiple else sources[0],
+ dataset_name=["A", "B"] if multiple else "A",
parallelism=import_parallelism,
+ extra_dataset_fields={"config": "config/*.json", "notes": "notes.md"},
tag_name="train")
+ data = rows(conn, "merged_datasets").sort_by("index")
+ assert pa.types.is_map(data.schema.field("config").type)
+ assert data.schema.field("notes").type == pa.string()
+ assert data["name"].to_pylist() == (["A", "B"] if multiple else ["A"])
+ for actual, (config, notes) in zip(data.to_pylist(), expected):
+ assert dict(actual["config"]) == config
+ assert actual["notes"] == notes
+ read_arrow = dataset_module._read_arrow
+
+ def checked_read(table, projection=None):
+ if table.identifier.object.endswith("_datasets"):
+ assert "config" not in projection
+ assert "notes" not in projection
+ return read_arrow(table, projection)
+
+ with patch.object(dataset_module, "_read_arrow", side_effect=checked_read):
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"),
tag_name="train")
+ try:
+ assert len(reader) == (10 if multiple else 5)
+ assert "config" not in reader.meta.datasets[0]
+ assert reader[0]["task"] == "pick"
+ finally:
+ reader.close()
+
+
[email protected]("suffix", ["json", "txt", "md", "yaml", "yml",
"jsonl", "ndjson", "csv", "tsv"])
+def test_extra_dataset_supported_text_suffixes(setup, suffix):
+ conn, sources = setup
+ root = Path(sources[0][7:])
+ text = "Unparsed text\r\n示例\n"
+ filename = "notes." + suffix
+ (root / filename).write_bytes(text.encode("utf-8"))
+ conn.load_from_lerobot(table_name="merged", source=sources[0],
+ extra_dataset_fields={"notes": filename})
+ assert rows(conn, "merged_datasets")["notes"].to_pylist() == [text]
+
+
[email protected]("fields", [
+ [], {"info": "notes.txt"}, {"name": "notes.txt"}, {"": "notes.txt"},
+ {1: "notes.txt"}, {"notes": None}, {"notes": "../notes.txt"},
+ {"notes": "/notes.txt"}, {"notes": "notes.bin"},
+])
+def test_extra_dataset_fields_validate_before_source_access(tmp_path, fields):
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ with patch("pypaimon.multimodal.lerobot.aggregate._resolved_source",
+ side_effect=AssertionError("source accessed")):
+ with pytest.raises(ValueError):
+ conn.load_from_lerobot("merged", "unused",
extra_dataset_fields=fields)
+ assert conn.catalog.list_databases() == []
+
+
[email protected]("failure", ["unsupported", "encoding", "duplicate"])
+def test_invalid_extra_dataset_text_fails_before_table_creation(setup,
failure):
+ conn, sources = setup
+ root = Path(sources[0][7:])
+ (root / "config").mkdir()
+ (root / "config/model.json").write_text("{}")
+ fields = {"config": "config/*"}
+ if failure == "unsupported":
+ (root / "config/model.bin").write_bytes(b"binary")
+ elif failure == "encoding":
+ (root / "config/model.json").write_bytes(b"\xff")
+ elif failure == "duplicate":
+ (root / "config/model.txt").write_text("same key")
+ with pytest.raises(ValueError):
+ conn.load_from_lerobot("merged", sources[0],
+ extra_dataset_fields=fields)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged_frames")
+
+
[email protected]("name", ["A", ["A"]])
+def test_single_dataset_name_forms(setup, name):
+ conn, sources = setup
+ conn.load_from_lerobot("merged", sources[0], dataset_name=name)
+ assert rows(conn, "merged_datasets")["name"].to_pylist() == ["A"]
+
+
[email protected]("name", ["A", ["A"], ["A", ""], ["A", 1], 1])
+def test_invalid_dataset_name_for_multiple_sources(tmp_path, name):
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ with pytest.raises(ValueError, match="dataset_name"):
+ conn.load_from_lerobot("merged", ["a", "b"], dataset_name=name)
+ assert conn.catalog.list_databases() == []
+
+
+def add_frame_feature(uri, name, dtype, values, shape=(1,)):
+ root = Path(uri[7:])
+ path = root / "meta/info.json"
+ info = json.loads(path.read_text())
+ info["features"][name] = {"dtype": dtype, "shape": list(shape), "names":
None}
+ path.write_text(json.dumps(info))
+ path = root / "data/chunk-000/file-000.parquet"
+ from pypaimon.multimodal.lerobot.schema import _schema_from_info
+ field = _schema_from_info(info).field(name)
+ pq.write_table(pq.read_table(path).append_column(field, pa.array(values,
type=field.type)), path)
+ if shape == (1,) and dtype.startswith("float"):
+ path = root / "meta/stats.json"
+ stats = json.loads(path.read_text())
+ stats[name] = _batch_stats(values)
+ path.write_text(json.dumps(stats))
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
[email protected]("reverse", [False, True])
+def test_schema_evolution_unions_three_tables(setup, import_parallelism,
reverse):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ original = sources[:]
+ add_frame_feature(sources[0], "temperature", "float32", [1., 2., 3., 4.,
5.])
+ add_frame_feature(sources[1], "pressure", "float64", [6., 7., 8., 9., 10.])
+ for index, uri in enumerate(sources):
+ root = Path(uri[7:])
+ path = root / "meta/episodes/chunk-000/file-000.parquet"
+ data = pq.read_table(path)
+ data = data.append_column("meta/note", pa.array(["a", "b"])) if index
== 0 else (
+ data.append_column("meta/score", pa.array([0.5, 0.8])))
+ pq.write_table(data, path)
+ if index == 0:
+ (root / "config").mkdir()
+ (root / "config/model.json").write_text('{"name":"model"}')
+ else:
+ (root / "notes.md").write_text("# Notes")
+ if reverse:
+ sources.reverse()
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism,
+ extra_dataset_fields={"config": "config/*.json",
"notes": "notes.md"})
+ data = rows(conn, "merged_frames").sort_by("index")
+ episodes = episode_rows(conn, "merged_episodes").to_pylist()
+ datasets = rows(conn, "merged_datasets").sort_by("index").to_pylist()
+ for ordinal, uri in enumerate(sources):
+ first = uri == original[0]
+ assert data["temperature"].slice(ordinal * 5, 5).to_pylist() == (
+ [1., 2., 3., 4., 5.] if first else [None] * 5)
+ assert data["pressure"].slice(ordinal * 5, 5).to_pylist() == (
+ [None] * 5 if first else [6., 7., 8., 9., 10.])
+ assert json.loads(episodes[ordinal * 2]["meta"]).get("note") == ("a"
if first else None)
+ assert json.loads(episodes[ordinal * 2]["meta"]).get("score") == (None
if first else 0.5)
+ assert datasets[ordinal]["notes"] == (None if first else "# Notes")
+ assert datasets[ordinal]["config"] == ([("model", '{"name":"model"}')]
if first else None)
+ assert metadata(conn, "stats")["temperature"]["count"] == [5]
+ assert metadata(conn, "stats")["pressure"]["mean"] == [8.]
+ assert data.schema.field("temperature").nullable
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"),
+ delta_timestamps={"temperature": [-0.1,
0., 0.1]})
+ try:
+ samples = reader.get_items([0, 5])
+ for item, uri in zip(samples, sources):
+ assert (item["temperature"] is None) == (uri != original[0])
+ assert (item["pressure"] is None) == (uri == original[0])
+ batch = next(iter(reader.to_dataloader(batch_size=10, num_workers=0)))
+ assert isinstance(batch["temperature"], list)
+ finally:
+ reader.close()
+
+
[email protected]("add_new", [False, True])
+def test_schema_evolution_disabled_keeps_first_source_schema(setup, add_new):
+ conn, sources = setup
+ add_frame_feature(sources[1 if add_new else 0], "temperature", "float32",
[1.] * 5)
+ if add_new:
+ with pytest.raises(ValueError, match="schema_evolution disabled"):
+ conn.load_from_lerobot("merged", sources, schema_evolution=False)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged_frames")
+ else:
+ conn.load_from_lerobot("merged", sources, schema_evolution=False)
+ assert rows(conn, "merged_frames")["temperature"].null_count == 5
+
+
[email protected]("kind", ["frame", "shape"])
+def test_schema_evolution_rejects_type_changes(setup, kind):
+ conn, sources = setup
+ for index, uri in enumerate(sources):
+ if kind == "frame":
+ add_frame_feature(uri, "temperature", "float32" if index == 0 else
"float64", [1.] * 5)
+ elif kind == "shape":
+ add_frame_feature(uri, "vector", "float32", [[1.] * (index + 2)] *
5, (index + 2,))
+ with pytest.raises(ValueError, match="incompatible"):
+ conn.load_from_lerobot("merged", sources)
+ with pytest.raises(TableNotExistException):
+ conn.get_table("merged_frames")
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_schema_evolution_allows_missing_video(tmp_path, import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ sources = [source(tmp_path / "with_video", video=True), source(tmp_path /
"without_video")]
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ assert rows(conn, "merged_frames")["camera"].null_count == 5
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"),
video_backend="pyav",
+ delta_timestamps={"camera": [-0.1, 0.,
0.1]})
+ try:
+ samples = reader.get_items([0, 5])
+ assert tuple(samples[0]["camera"].shape) == (3, 3, 16, 16)
+ assert samples[1]["camera"] is None
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_schema_evolution_allows_missing_images(setup, import_parallelism):
+ from PIL import Image
+ import io
+
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ buffer = io.BytesIO()
+ Image.new("RGB", (2, 2), color="red").save(buffer, format="PNG")
+ add_frame_feature(sources[0], "image", "image", [buffer.getvalue()] * 5,
(2, 2, 3))
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"))
+ try:
+ samples = reader.get_items([0, 5])
+ assert tuple(samples[0]["image"].shape) == (3, 2, 2)
+ assert samples[1]["image"] is None
+ finally:
+ reader.close()
+
+
[email protected]("import_parallelism", [1, 2], indirect=True)
+def test_schema_evolution_allows_optional_subtask_column(setup,
import_parallelism):
+ pytest.importorskip("datasets")
+ pytest.importorskip("torch")
+ conn, sources = setup
+ root = Path(sources[0][7:])
+ path = root / "meta/info.json"
+ info = json.loads(path.read_text())
+ del info["features"]["subtask_index"]
+ path.write_text(json.dumps(info))
+ path = root / "data/chunk-000/file-000.parquet"
+ pq.write_table(pq.read_table(path).drop(["subtask_index"]), path)
+ (root / "meta/subtasks.parquet").unlink()
+ path = root / "meta/stats.json"
+ stats = json.loads(path.read_text())
+ del stats["subtask_index"]
+ path.write_text(json.dumps(stats))
+ conn.load_from_lerobot("merged", sources, parallelism=import_parallelism)
+ assert rows(conn, "merged_frames")["subtask_index"].null_count == 5
+ reader = pm.PaimonLeRobotDataset(conn.get_table("merged_frames"))
+ try:
+ samples = reader.get_items([0, 5])
+ assert samples[0]["subtask"] is None
+ assert samples[1]["subtask"] == "grasp"
+ finally:
+ reader.close()
+
+
[email protected]("value", [None, 1, "true"])
+def test_schema_evolution_option_requires_boolean(tmp_path, value):
+ conn = pm.connect(options={"warehouse": str(tmp_path / "warehouse")})
+ with pytest.raises(ValueError, match="schema_evolution"):
+ conn.load_from_lerobot("merged", "unused", schema_evolution=value)
+ assert conn.catalog.list_databases() == []
diff --git a/paimon-python/pypaimon/tests/lerobot_text_fields_test.py
b/paimon-python/pypaimon/tests/lerobot_text_fields_test.py
new file mode 100644
index 0000000000..487535893e
--- /dev/null
+++ b/paimon-python/pypaimon/tests/lerobot_text_fields_test.py
@@ -0,0 +1,94 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import io
+import sys
+from unittest.mock import patch
+from urllib.parse import unquote, urlparse
+
+import pyarrow.fs as pafs
+import pytest
+
+from pypaimon.multimodal.lerobot.source import _LeRobotSource
+from pypaimon.multimodal.lerobot.text_fields import _read_text_fields
+
+
+pytestmark = pytest.mark.skipif(sys.version_info < (3, 10), reason="LeRobot
import requires Python 3.10+")
+
+
+class MemoryFileIO:
+ def __init__(self, root):
+ self.root = root
+
+ def path(self, uri):
+ return self.root /
unquote(urlparse(uri).path).removeprefix("/dataset/")
+
+ def list_status(self, uri):
+ path = self.path(uri + "/" if uri.endswith("/dataset") else uri)
+ return [pafs.FileInfo("memory://bucket/dataset/" +
child.relative_to(self.root).as_posix()
+ + ("/" if child.is_dir() else ""),
+ pafs.FileType.Directory if child.is_dir() else
pafs.FileType.File)
+ for child in path.iterdir()]
+
+ def new_input_stream(self, uri):
+ return io.BytesIO(self.path(uri).read_bytes())
+
+
[email protected]("backend", ["local", "fileio", "hub"])
+def test_text_file_globs_keep_directory_boundaries(tmp_path, backend):
+ files = {"config/model.json": '{ "value": 1 }\r\n',
+ "config/nested/model.json": "nested\n", "config/model a.json":
"spaces\n",
+ "other/config/model.json": "other\n", "notes.md": "# Notes\n"}
+ for name, text in files.items():
+ path = tmp_path / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(text.encode("utf-8"))
+ source = _LeRobotSource(str(tmp_path), tmp_path, "")
+ if backend == "fileio":
+ source = _LeRobotSource("memory://bucket/dataset", None, "",
MemoryFileIO(tmp_path))
+ elif backend == "hub":
+ source = _LeRobotSource("example/dataset", None, "example/dataset")
+ with patch("huggingface_hub.list_repo_files", return_value=list(files)) as
listing, \
+ patch("huggingface_hub.hf_hub_download",
+ side_effect=lambda repo, name, **kw: str(tmp_path / name))
as download:
+ actual = _read_text_fields(source, {"config": "config/*.json",
"notes": "notes.md"})
+ assert actual == {"config": {"model": files["config/model.json"],
+ "model a": files["config/model a.json"]},
+ "notes": files["notes.md"]}
+ recursive = _read_text_fields(source, {"config": "config/**/*.json"})
+ assert recursive["config"]["nested/model"] == "nested\n"
+ assert len(recursive["config"]) == 3
+ single = _read_text_fields(source, {"config": "config/model.json*"})
+ assert single == {"config": {"model": files["config/model.json"]}}
+ assert _read_text_fields(source, {"notes": "missing.md", "config":
"missing/*.json"}) == {
+ "notes": None, "config": None}
+ if backend == "hub":
+ assert listing.call_args.kwargs == {"repo_type": "dataset"}
+ assert download.call_count == 8
+ else:
+ listing.assert_not_called()
+ download.assert_not_called()
+
+
+def test_extra_text_symlink_must_stay_within_source(tmp_path):
+ root = tmp_path / "source"
+ root.mkdir()
+ outside = tmp_path / "outside.txt"
+ outside.write_text("outside")
+ (root / "notes.txt").symlink_to(outside)
+ source = _LeRobotSource(str(root), root, "")
+ with pytest.raises(ValueError, match="within the source directory"):
+ _read_text_fields(source, {"notes": "notes.txt"})
diff --git a/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
b/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
index 15306ac91c..a52d6246b3 100644
--- a/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
+++ b/paimon-python/pypaimon/tests/multimodal_lerobot_test.py
@@ -1234,6 +1234,11 @@ class LeRobotValidationTest(unittest.TestCase):
}
class Reader(pmm.PaimonDatasetReader):
+ # This test checks batching and backend cache reuse with one
decoder.
+ # Replica splitting is covered in video_decode_parallelism_test.py.
+ _table = SimpleNamespace(options=CoreOptions(Options({
+ "read.video.decoders-per-payload": "1",
+ })))
def read_indices(self, indices, columns):
return pa.Table.from_pylist([{