Files
lerobot/tests/annotations/test_frames.py
T
Caroline Pascal 3dd19d043e feat(depth maps): adding support for depth in LeRobot (#3644)
* 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>
2026-06-27 14:21:21 +02:00

248 lines
9.6 KiB
Python

#!/usr/bin/env python
# Copyright 2026 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.
"""Unit tests for :class:`VideoFrameProvider` method bindings.
These were prompted by a real regression: ``video_for_episode`` was once
indented one level too deep so it ended up nested *inside* a module-level
helper (after that function's ``return`` statement) — silently dead code
that meant production runs with ``use_video_url=False`` would
``AttributeError`` on ``self.frame_provider.video_for_episode(...)``. The
existing module tests didn't catch it because they exercise stub providers.
The tests below assert on the class itself (not on an instance), so a
future reindent regression flips them to red without needing a real
LeRobot dataset on disk.
"""
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
import pytest
import torch
pytest.importorskip("datasets", reason="datasets is required (install lerobot[dataset])")
from lerobot.annotations.steerable_pipeline.frames import VideoFrameProvider # noqa: E402
class _FakeMeta:
"""Minimal metadata stub exposing ``video_keys`` / ``camera_keys``."""
def __init__(self, video_keys: list[str], image_keys: list[str], video_path: Path | None = None) -> None:
self.video_keys = video_keys
self.camera_keys = [*video_keys, *image_keys]
self.depth_keys = []
self._video_path = video_path
self.episodes = {0: {f"videos/{key}/from_timestamp": 0.0 for key in video_keys}}
def get_video_file_path(self, episode_index: int, camera_key: str) -> Path:
return self._video_path
def test_default_camera_key_skips_image_only_cameras(tmp_path: Path, monkeypatch) -> None:
"""The default camera must be a *video* key — image-stored cameras have no
``videos/<key>/from_timestamp`` and would KeyError in the clip/decode path.
Regression: a dataset whose first ``camera_keys`` entry was an image-stored
camera (e.g. ``observation.images.wrist``) crashed at clip extraction.
"""
fake = _FakeMeta(
video_keys=["observation.images.robot0_agentview_right"],
image_keys=["observation.images.wrist"],
)
import lerobot.datasets.dataset_metadata as meta_mod
monkeypatch.setattr(meta_mod, "LeRobotDatasetMetadata", lambda *a, **k: fake, raising=True)
provider = VideoFrameProvider(root=tmp_path)
assert provider.camera_key == "observation.images.robot0_agentview_right"
assert "observation.images.wrist" not in provider.camera_keys
def test_video_for_episode_is_a_method_of_videoframeprovider():
"""``video_for_episode`` must be a bound method, not nested dead code."""
assert callable(getattr(VideoFrameProvider, "video_for_episode", None))
def test_episode_clip_path_is_a_method_of_videoframeprovider():
"""``episode_clip_path`` is now a method (was a free function reaching
into ``provider._meta`` from outside the class)."""
assert callable(getattr(VideoFrameProvider, "episode_clip_path", None))
def test_videoframeprovider_has_a_lock_for_concurrent_use():
"""A ``ThreadPoolExecutor`` runs the plan / interjections / vqa phases
concurrently; the cache + warn-flag accesses must be guarded.
"""
import threading
# Fresh-instance check via a minimal fake to avoid touching the hub.
# The lock is declared with ``init=False`` and has a default factory,
# so a constructed instance must own a real ``threading.Lock``.
lock_field = next(
(f for f in VideoFrameProvider.__dataclass_fields__.values() if f.name == "_lock"),
None,
)
assert lock_field is not None
assert lock_field.default_factory is threading.Lock
@pytest.fixture
def sample_video(tmp_path: Path) -> Path:
"""A 3 s 10 fps test-pattern mp4, written with ffmpeg."""
if shutil.which("ffmpeg") is None:
pytest.skip("ffmpeg not available")
out = tmp_path / "sample.mp4"
subprocess.run(
[
"ffmpeg",
"-y",
"-f",
"lavfi",
"-i",
"testsrc=duration=3:size=160x120:rate=10",
"-pix_fmt",
"yuv420p",
str(out),
],
check=True,
capture_output=True,
)
return out
def _provider_for_video(tmp_path: Path, video: Path, monkeypatch) -> VideoFrameProvider:
"""A provider whose single camera resolves to ``video`` via fake metadata."""
fake = _FakeMeta(video_keys=["observation.images.cam"], image_keys=[], video_path=video)
import lerobot.datasets.dataset_metadata as meta_mod
monkeypatch.setattr(meta_mod, "LeRobotDatasetMetadata", lambda *a, **k: fake, raising=True)
return VideoFrameProvider(root=tmp_path, tolerance_s=0.2)
def test_decode_returns_one_uint8_frame_per_timestamp(
sample_video: Path, tmp_path: Path, monkeypatch
) -> None:
"""``_decode`` routes through ``decode_video_frames`` (torchcodec when
available, PyAV otherwise) — no subprocess fallback.
"""
provider = _provider_for_video(tmp_path, sample_video, monkeypatch)
timestamps = [0.0, 1.0, 2.5]
frames = provider._decode(0, timestamps, "observation.images.cam")
assert len(frames) == len(timestamps)
for frame in frames:
assert isinstance(frame, torch.Tensor)
assert frame.dtype == torch.uint8
assert frame.shape == (3, 120, 160)
def test_frames_at_snaps_mid_frame_grid_to_real_frames(
sample_video: Path, tmp_path: Path, monkeypatch
) -> None:
"""Uniform sampling grids land mid-frame; ``frames_at`` must snap them to
real frame timestamps before decoding.
Regression: ``decode_video_frames`` rejects queries farther than
``tolerance_s`` (default 10 ms) from a decodable frame, so un-snapped
mid-frame queries raised ``FrameTimestampError`` wholesale and the plan
module silently lost its contact sheets for most episodes.
"""
from types import SimpleNamespace
fake = _FakeMeta(video_keys=["observation.images.cam"], image_keys=[], video_path=sample_video)
import lerobot.datasets.dataset_metadata as meta_mod
monkeypatch.setattr(meta_mod, "LeRobotDatasetMetadata", lambda *a, **k: fake, raising=True)
provider = VideoFrameProvider(root=tmp_path) # default 10 ms tolerance
# 10 fps fixture -> frames at 0.0, 0.1, ...; queries sit mid-frame.
record = SimpleNamespace(episode_index=0, frame_timestamps=[i / 10 for i in range(30)])
frames = provider.frames_at(record, [0.149, 1.234, 2.04], camera_key="observation.images.cam")
assert len(frames) == 3
for frame in frames:
assert isinstance(frame, torch.Tensor)
assert frame.shape == (3, 120, 160)
def test_decode_returns_empty_list_on_missing_file(tmp_path: Path, monkeypatch) -> None:
"""A missing video is a recoverable no-frames condition, never a crash."""
provider = _provider_for_video(tmp_path, tmp_path / "does_not_exist.mp4", monkeypatch)
assert provider._decode(0, [0.0], "observation.images.cam") == []
def test_episode_clip_path_trims_via_reencode_video(tmp_path: Path, monkeypatch) -> None:
"""Clip extraction delegates to ``video_utils.reencode_video`` with the
episode's ``[from_timestamp, to_timestamp)`` trim window — no subprocess.
"""
from types import SimpleNamespace
import lerobot.annotations.steerable_pipeline.frames as frames_mod
src = tmp_path / "src.mp4"
src.write_bytes(b"src")
fake = _FakeMeta(video_keys=["observation.images.cam"], image_keys=[], video_path=src)
fake.episodes[0]["videos/observation.images.cam/from_timestamp"] = 1.5
fake.episodes[0]["videos/observation.images.cam/to_timestamp"] = 4.0
import lerobot.datasets.dataset_metadata as meta_mod
monkeypatch.setattr(meta_mod, "LeRobotDatasetMetadata", lambda *a, **k: fake, raising=True)
captured = {}
def fake_reencode(
input_video_path,
output_video_path,
video_encoder=None,
overwrite=False,
start_time_s=None,
end_time_s=None,
):
captured.update(
src=Path(input_video_path),
encoder=video_encoder,
start_time_s=start_time_s,
end_time_s=end_time_s,
)
Path(output_video_path).write_bytes(b"clip")
monkeypatch.setattr(frames_mod, "reencode_video", fake_reencode, raising=True)
provider = VideoFrameProvider(root=tmp_path)
record = SimpleNamespace(episode_index=0, frame_timestamps=[0.0, 1.0])
out = provider.episode_clip_path(record, tmp_path / "clips")
assert out == tmp_path / "clips" / "ep_000000.mp4"
assert captured["src"] == src
assert captured["start_time_s"] == 1.5
assert captured["end_time_s"] == 4.0
# H.264 so the clip is decodable by vllm's libav build (sources are often AV1).
assert captured["encoder"].vcodec == "h264"
def test_videoframeprovider_serializes_decodes_with_a_lock() -> None:
"""torchcodec's cached per-file decoder is single-threaded; the provider
must own a dedicated lock that ``_decode`` holds around the decoder call.
"""
import threading
lock_field = VideoFrameProvider.__dataclass_fields__.get("_decode_lock")
assert lock_field is not None
assert lock_field.default_factory is threading.Lock