mirror of
https://github.com/huggingface/lerobot.git
synced 2026-06-28 13:47:02 +00:00
3dd19d043e
* feat(depth): add depth quantization helpers and tests
* feat(video): add ffv1 to supported codecs
* feat(depth): persist depth metadata
* feat(depth): extend quantization tools to better fit the encoding/decoding pipeline
* feat(depth): plumb DepthEncoderConfig through LeRobotDataset and DatasetWriter
* feat(depth): wire StreamingVideoEncoder + writer to depth encoder
* feat(depth): wire DatasetReader to decode_depth_frames
* feat(cameras/realsense): expose async depth in metric meters
* feat(features): route 2D camera shapes to observation.depth.<key>
* feat(robots/so_follower): emit + populate depth keys when use_depth
* feat(record): plumb DepthEncoderConfig through lerobot-record
* feat(viz): render depth observations as rr.DepthImage in Viridis
* feat(depth maps writer): adding support for raw depth maps recording with image writer
* chore(format): format code
* feat(depth shape): ensuring depth maps shape is always including the channel
* feat(is_depth): simplifying is_depth nested name + legacy support
* fix(stop_event): fixing stop_event race condition in camera classes
* fix(plumbing): fixing missing parts in the depth maps pipeline
* chore(typos): fixing typos
* test(fix): fixing exisiting tests to still work with latest features
* tests(depth): adding new tests for depth integration validation
* feat(pix_fmt channels): use PyAv to check get pixel formats number of channels
* feat(refactor): refactor DepthEncoderConfig quantization pipeline, so that the methods do not live in the config class. Add pixel format - channels validation.Move the default pixel format for depth in the config file.
* fix(pre-commit): fixing mutable defautl value
* fix(info): fixing info metadata update when is_depth_map was set
* tests(typos): fixing typos in tests
* fix(realsense): fixing typo in realsense serial number
* fix(normalization): restricting 255 normalization to non depth/uint8 images only
* fix(typo): fixing typo
* fix(TIFF): add missing quantization and cleanup for TIFF files
* feat(batched dequantization): optimizing dequantize_depth for torch based batched dequantization
* feat(tools): adding depth support in LeRobotDataset edition tools
* test(aggregate): extending aggregation tests to depth frames
* test(cleaning): cleaning up tests
* fix(from_video_info): fixing early validation issue in from_video_info
* fix(typo): fixing typo
* fix(is_depth): adding missing doctrings and is_depth arguments in video decoding functions
Co-authored-by: Wensi (Vince) Ai <59036629+wensi-ai@users.noreply.github.com>
* fix(depth units): fixing depth units output for the realsense cameras
* feat(output unit): adding support for output unit specification at dataset reading/training time
Co-authored-by: Wensi (Vince) Ai <59036629+wensi-ai@users.noreply.github.com>
* test(depth): cleaning up depth tests
* test(depth encoding): updating and cleaning video/depth encoding tests
* chore(format): formatting code
* docs(depth): improving depth maps docs
* test(fix): fixing depth tests
* test(dataset tools): adding missing tests for new dataset edition tools features
* chore(format): formatting code
* fix(pyav check): fixing PyAV option validation for integer codec options by normalizing
numeric values before calling `is_integer()`
Co-authored-by: Wensi (Vince) Ai <59036629+wensi-ai@users.noreply.github.com>
* docs(mermaid): fixing mermaid diagram
* fix(rebase): rebase follow up corrections
* feat(dataset tools): adding missing docstrings and features for depth fill support in dataset edition tools
* docs(docstring): updating docstrings
* docs(dataset tools): updating docs
* fix(save images): fixing image saving in dataset tools
* fix(update video info): fixing update video info logic to match the recording and editing use cases
* test(reencode): fixing reencoding monkeypatch
* fix(review): add Claude review
* chore(format): format code
* fix(update video info): ditching the differentiated approahces for video info update - video info are always updated unless for preserved keys.
* chore(rebase): fixing rebase merge conflicts
* test(visualization): fixing visualization tests
* feat(docstrings): adding explicit docstring for encoding parameters. Docstrigns will now show up as description in the CLI --help.
* feat(mm as default): adding a global DEFAULT_DEPTH_UNIT variable setting mm as default depth unit
* fix(RGB <-> camera): renaming camera_encoder to rgb_encoder for clarity
* chore(TODO): removing deprecated TODO
* doc(write_u16_plane): improving docstrings for write_u16_plane
* feat(units): adding constants for depth frames units (m and mm)
* fix(spam): replacing spamming warning but a debug log
* feat(leagcy metadata): adding automatic metadata update for legacy 'video.is_depth_map' feature
* fix(copy&reindex): fixing metadat reshaping for single channel frames
* fix(ImageNet): excluding dpeth frames from ImageNet stats
* fix(PyAV container seek): fixing initial PyAV container seek to be robust againsy codec choice
* feat(lerobot-dataset-viz): adding support for depth in lerobot-dataset-viz
* fix(compress): removing rerun compression for DepthImages
* fix(signle channel squeeze): fixing single channel squeezing
* chore(format): format code
* fix(streaming): adding support for dequantization in streaming_dataset.py
* refactor(read depth): factorizing depth reading methods for realsense camera and adding support for depth-only usage
* chore(renaming): fixing missed RGBEncoderConfig renamings
* docs(renaming): reflecting renamings in a clearer way in the docs
* chore(annotation): excluding depth from the annotation pipeline
* feat(robots): adding depth support in compatible follower robots
* feat(LeSadKiwi): excluding LeKiwi from depth support (for now)
* chore(fail): removing misplaced file
* chore(fail): removing misplaced file
* fix(remove ffv1): removing ffv1 as it does not support MP4
* docs(cheat sheet): adding depth and video encoding to the cheat sheet
* fix(lossless): tuning depth encoding parameters for lossless depth storage
* test(fix): fixing failing tests
* depth(ZMQ): excluding ZMQ from depth support
* Revert "depth(ZMQ): excluding ZMQ from depth support"
This reverts commit b95cf4e4c2.
* fix(image transforms): excluding depth frames from images transforms
* fix(typo): typo
* fix(stats): fixing stats computation for depth frames
* fix(TIFF vs. pytorch): adding an extra uint16 to float32 conversion for depth maps stored as raw TIFF images
* fix(typos): fixing typos
* test(dtype): fixing stats computation typing tests
---------
Signed-off-by: Steven Palma <imstevenpmwork@ieee.org>
Co-authored-by: Wensi (Vince) Ai <59036629+wensi-ai@users.noreply.github.com>
Co-authored-by: Steven Palma <imstevenpmwork@ieee.org>
Co-authored-by: Wensi Ai <wsai@stanford.edu>
239 lines
8.9 KiB
Python
239 lines
8.9 KiB
Python
#!/usr/bin/env python
|
|
|
|
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
|
#
|
|
# Licensed 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.
|
|
"""Contract tests for DatasetWriter."""
|
|
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import numpy as np
|
|
import pytest
|
|
import torch
|
|
from PIL import Image
|
|
|
|
pytest.importorskip("datasets", reason="datasets is required (install lerobot[dataset])")
|
|
|
|
from lerobot.configs import VideoEncoderConfig
|
|
from lerobot.datasets.dataset_writer import _encode_video_worker
|
|
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
|
from lerobot.datasets.utils import DEFAULT_IMAGE_PATH
|
|
from tests.fixtures.constants import DEFAULT_FPS, DUMMY_REPO_ID
|
|
|
|
SIMPLE_FEATURES = {
|
|
"state": {"dtype": "float32", "shape": (6,), "names": None},
|
|
"action": {"dtype": "float32", "shape": (6,), "names": None},
|
|
}
|
|
|
|
|
|
def _make_frame(features: dict, task: str = "Dummy task") -> dict:
|
|
"""Build a valid frame dict for the given features."""
|
|
frame = {"task": task}
|
|
for key, ft in features.items():
|
|
if ft["dtype"] in ("image", "video"):
|
|
frame[key] = np.random.randint(0, 256, size=ft["shape"], dtype=np.uint8)
|
|
elif ft["dtype"] in ("float32", "float64"):
|
|
frame[key] = torch.randn(ft["shape"])
|
|
elif ft["dtype"] == "int64":
|
|
frame[key] = torch.zeros(ft["shape"], dtype=torch.int64)
|
|
return frame
|
|
|
|
|
|
# ── Existing encode_video_worker tests ───────────────────────────────
|
|
|
|
|
|
def test_encode_video_worker_forwards_video_encoder(tmp_path):
|
|
"""_encode_video_worker forwards video_encoder to encode_video_frames."""
|
|
video_key = "observation.images.laptop"
|
|
fpath = DEFAULT_IMAGE_PATH.format(image_key=video_key, episode_index=0, frame_index=0)
|
|
img_dir = tmp_path / Path(fpath).parent
|
|
img_dir.mkdir(parents=True, exist_ok=True)
|
|
Image.new("RGB", (64, 64), color="red").save(img_dir / "frame-000000.png")
|
|
|
|
captured_kwargs = {}
|
|
|
|
def mock_encode(imgs_dir, video_path, fps, **kwargs):
|
|
captured_kwargs.update(kwargs)
|
|
Path(video_path).parent.mkdir(parents=True, exist_ok=True)
|
|
Path(video_path).touch()
|
|
|
|
with patch("lerobot.datasets.dataset_writer.encode_video_frames", side_effect=mock_encode):
|
|
_encode_video_worker(
|
|
video_key,
|
|
0,
|
|
tmp_path,
|
|
fps=30,
|
|
video_encoder=VideoEncoderConfig(vcodec="h264", preset=None),
|
|
encoder_threads=4,
|
|
)
|
|
|
|
assert captured_kwargs["video_encoder"].vcodec == "h264"
|
|
assert captured_kwargs["encoder_threads"] == 4
|
|
|
|
|
|
def test_encode_video_worker_default_video_encoder(tmp_path):
|
|
"""_encode_video_worker passes None video_encoder which encode_video_frames defaults."""
|
|
video_key = "observation.images.laptop"
|
|
fpath = DEFAULT_IMAGE_PATH.format(image_key=video_key, episode_index=0, frame_index=0)
|
|
img_dir = tmp_path / Path(fpath).parent
|
|
img_dir.mkdir(parents=True, exist_ok=True)
|
|
Image.new("RGB", (64, 64), color="red").save(img_dir / "frame-000000.png")
|
|
|
|
captured_kwargs = {}
|
|
|
|
def mock_encode(imgs_dir, video_path, fps, **kwargs):
|
|
captured_kwargs.update(kwargs)
|
|
Path(video_path).parent.mkdir(parents=True, exist_ok=True)
|
|
Path(video_path).touch()
|
|
|
|
with patch("lerobot.datasets.dataset_writer.encode_video_frames", side_effect=mock_encode):
|
|
_encode_video_worker(video_key, 0, tmp_path, fps=30)
|
|
|
|
assert captured_kwargs["video_encoder"] is None
|
|
assert captured_kwargs["encoder_threads"] is None
|
|
|
|
|
|
# ── add_frame contracts ──────────────────────────────────────────────
|
|
|
|
|
|
def test_add_frame_increments_buffer_size(tmp_path):
|
|
"""Each add_frame() call increases episode_buffer['size'] by 1."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
assert dataset.writer.episode_buffer["size"] == 0
|
|
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
assert dataset.writer.episode_buffer["size"] == 1
|
|
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
assert dataset.writer.episode_buffer["size"] == 2
|
|
|
|
|
|
def test_add_frame_rejects_missing_feature(tmp_path):
|
|
"""add_frame() raises ValueError when a required feature is missing."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
with pytest.raises(ValueError, match="Missing features"):
|
|
dataset.add_frame({"task": "Dummy task", "state": torch.randn(6)})
|
|
# missing 'action'
|
|
|
|
|
|
# ── save_episode contracts ───────────────────────────────────────────
|
|
|
|
|
|
def test_save_episode_writes_parquet(tmp_path):
|
|
"""After save_episode(), at least one .parquet file exists under data/."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
for _ in range(3):
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
dataset.save_episode()
|
|
|
|
parquet_files = list((tmp_path / "ds" / "data").rglob("*.parquet"))
|
|
assert len(parquet_files) > 0
|
|
|
|
|
|
def test_save_episode_updates_counters(tmp_path):
|
|
"""After save_episode(), metadata counters are updated."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
for _ in range(5):
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
dataset.save_episode()
|
|
|
|
assert dataset.meta.total_episodes == 1
|
|
assert dataset.meta.total_frames == 5
|
|
|
|
|
|
def test_save_episode_resets_buffer(tmp_path):
|
|
"""After save_episode(), the episode buffer is reset."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
for _ in range(3):
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
dataset.save_episode()
|
|
|
|
assert dataset.writer.episode_buffer["size"] == 0
|
|
|
|
|
|
def test_save_multiple_episodes(tmp_path):
|
|
"""Recording 3 episodes results in correct total counts."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
total_frames = 0
|
|
for ep in range(3):
|
|
n_frames = ep + 2 # 2, 3, 4
|
|
for _ in range(n_frames):
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
dataset.save_episode()
|
|
total_frames += n_frames
|
|
|
|
assert dataset.meta.total_episodes == 3
|
|
assert dataset.meta.total_frames == total_frames
|
|
|
|
|
|
# ── clear / lifecycle ────────────────────────────────────────────────
|
|
|
|
|
|
def test_clear_resets_buffer(tmp_path):
|
|
"""clear_episode_buffer() resets the buffer size to 0."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
assert dataset.writer.episode_buffer["size"] == 1
|
|
|
|
dataset.clear_episode_buffer()
|
|
assert dataset.writer.episode_buffer["size"] == 0
|
|
|
|
|
|
def test_finalize_is_idempotent(tmp_path):
|
|
"""Calling finalize() twice does not raise."""
|
|
dataset = LeRobotDataset.create(
|
|
repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=SIMPLE_FEATURES, root=tmp_path / "ds"
|
|
)
|
|
for _ in range(3):
|
|
dataset.add_frame(_make_frame(SIMPLE_FEATURES))
|
|
dataset.save_episode()
|
|
|
|
dataset.finalize()
|
|
dataset.finalize() # second call should not raise
|
|
|
|
|
|
def test_finalize_then_read_roundtrip(tmp_path):
|
|
"""Write data, finalize, re-open, and verify data matches."""
|
|
root = tmp_path / "roundtrip"
|
|
features = {"state": {"dtype": "float32", "shape": (2,), "names": None}}
|
|
dataset = LeRobotDataset.create(repo_id=DUMMY_REPO_ID, fps=DEFAULT_FPS, features=features, root=root)
|
|
|
|
# Record known values
|
|
known_states = []
|
|
for i in range(5):
|
|
state = torch.tensor([float(i), float(i * 10)])
|
|
known_states.append(state)
|
|
dataset.add_frame({"task": "Test task", "state": state})
|
|
dataset.save_episode()
|
|
dataset.finalize()
|
|
|
|
# Read back
|
|
for i in range(5):
|
|
item = dataset[i]
|
|
assert torch.allclose(item["state"], known_states[i], atol=1e-5)
|