i have this code it fetches data from huggingface
from datasets_utils.lerobot_dataset import LeRobotDataset
dataset = LeRobotDataset("lerobot/stanford_robocook")
print(dataset)
i get this output
LeRobotDataset(
Repository ID: 'lerobot/stanford_robocook',
Split: 'train',
Number of Samples: 112980,
Number of Episodes: 2460,
Type: video (.mp4),
Recorded Frames per Second: 5,
Camera Keys: ['observation.images.image_1', 'observation.images.image_2', 'observation.images.image_4', 'observation.images.image_3'],
Video Frame Keys: ['observation.images.image_1', 'observation.images.image_2', 'observation.images.image_4', 'observation.images.image_3'],
Transformations: None,
Codebase Version: v1.6,
)
If i do this with other data it returns in same format but with some difference depending on the dataset like this one
from datasets_utils.lerobot_dataset import LeRobotDataset
dataset = LeRobotDataset("lerobot/pusht")
print(dataset)
I get this output
Fetching 212 files: 100%|███████████████████████████████████████████████████████████████| 212/212 [00:00<00:00, 6553.12it/s]
LeRobotDataset(
Repository ID: 'lerobot/pusht',
Split: 'train',
Number of Samples: 25650,
Number of Episodes: 206,
Type: video (.mp4),
Recorded Frames per Second: 10,
Camera Keys: ['observation.image'],
Video Frame Keys: ['observation.image'],
Transformations: None,
Codebase Version: v1.6,
)
Is there any way we can download all the data? But we would not have to specify anything manually.
This is LerobotDataset function
code
Assistant
class LeRobotDataset(torch.utils.data.Dataset):
def __init__(
self,
repo_id: str,
root: Path | None = DATA_DIR,
split: str = "train",
image_transforms: Callable | None = None,
delta_timestamps: dict[list[float]] | None = None,
video_backend: str | None = None,
):
super().__init__()
self.repo_id = repo_id
self.root = root
self.split = split
self.image_transforms = image_transforms
self.delta_timestamps = delta_timestamps
# load data from hub or locally when root is provided
# TODO(rcadene, aliberts): implement faster transfer
# https://huggingface.co/docs/huggingface_hub/en/guides/download#faster-downloads
self.hf_dataset = load_hf_dataset(repo_id, CODEBASE_VERSION, root, split)
if split == "train":
self.episode_data_index = load_episode_data_index(repo_id, CODEBASE_VERSION, root)
else:
self.episode_data_index = calculate_episode_data_index(self.hf_dataset)
self.hf_dataset = reset_episode_index(self.hf_dataset)
self.stats = load_stats(repo_id, CODEBASE_VERSION, root)
self.info = load_info(repo_id, CODEBASE_VERSION, root)
if self.video:
self.videos_dir = load_videos(repo_id, CODEBASE_VERSION, root)
self.video_backend = video_backend if video_backend is not None else "pyav"
@property
def fps(self) -> int:
"""Frames per second used during data collection."""
return self.info["fps"]
@property
def video(self) -> bool:
"""Returns True if this dataset loads video frames from mp4 files.
Returns False if it only loads images from png files.
"""
return self.info.get("video", False)
@property
def features(self) -> datasets.Features:
return self.hf_dataset.features
@property
def camera_keys(self) -> list[str]:
"""Keys to access image and video stream from cameras."""
keys = []
for key, feats in self.hf_dataset.features.items():
if isinstance(feats, (datasets.Image, VideoFrame)):
keys.append(key)
return keys
@property
def video_frame_keys(self) -> list[str]:
"""Keys to access video frames that requires to be decoded into images.
Note: It is empty if the dataset contains images only,
or equal to `self.cameras` if the dataset contains videos only,
or can even be a subset of `self.cameras` in a case of a mixed image/video dataset.
"""
video_frame_keys = []
for key, feats in self.hf_dataset.features.items():
if isinstance(feats, VideoFrame):
video_frame_keys.append(key)
return video_frame_keys
@property
def num_samples(self) -> int:
"""Number of samples/frames."""
return len(self.hf_dataset)
@property
def num_episodes(self) -> int:
"""Number of episodes."""
return len(self.hf_dataset.unique("episode_index"))
@property
def tolerance_s(self) -> float:
"""Tolerance in seconds used to discard loaded frames when their timestamps
are not close enough from the requested frames. It is only used when `delta_timestamps`
is provided or when loading video frames from mp4 files.
"""
# 1e-4 to account for possible numerical error
return 1 / self.fps - 1e-4
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
item = self.hf_dataset[idx]
if self.delta_timestamps is not None:
item = load_previous_and_future_frames(
item,
self.hf_dataset,
self.episode_data_index,
self.delta_timestamps,
self.tolerance_s,
)
if self.video:
item = load_from_videos(
item,
self.video_frame_keys,
self.videos_dir,
self.tolerance_s,
self.video_backend,
)
if self.image_transforms is not None:
for cam in self.camera_keys:
item[cam] = self.image_transforms(item[cam])
return item
def __repr__(self):
return (
f"{self.__class__.__name__}(\n"
f" Repository ID: '{self.repo_id}',\n"
f" Split: '{self.split}',\n"
f" Number of Samples: {self.num_samples},\n"
f" Number of Episodes: {self.num_episodes},\n"
f" Type: {'video (.mp4)' if self.video else 'image (.png)'},\n"
f" Recorded Frames per Second: {self.fps},\n"
f" Camera Keys: {self.camera_keys},\n"
f" Video Frame Keys: {self.video_frame_keys if self.video else 'N/A'},\n"
f" Transformations: {self.image_transforms},\n"
f" Codebase Version: {self.info.get('codebase_version', '< v1.6')},\n"
f")"
)
@classmethod
def from_preloaded(
cls,
repo_id: str = "from_preloaded",
root: Path | None = None,
split: str = "train",
transform: callable = None,
delta_timestamps: dict[list[float]] | None = None,
# additional preloaded attributes
hf_dataset=None,
episode_data_index=None,
stats=None,
info=None,
videos_dir=None,
video_backend=None,
) -> "LeRobotDataset":
"""Create a LeRobot Dataset from existing data and attributes instead of loading from the filesystem.
It is especially useful when converting raw data into LeRobotDataset before saving the dataset
on the filesystem or uploading to the hub.
Note: Meta-data attributes like `repo_id`, `version`, `root`, etc are optional and potentially
meaningless depending on the downstream usage of the return dataset.
"""
# create an empty object of type LeRobotDataset
obj = cls.__new__(cls)
obj.repo_id = repo_id
obj.root = root
obj.split = split
obj.image_transforms = transform
obj.delta_timestamps = delta_timestamps
obj.hf_dataset = hf_dataset
obj.episode_data_index = episode_data_index
obj.stats = stats
obj.info = info if info is not None else {}
obj.videos_dir = videos_dir
obj.video_backend = video_backend if video_backend is not None else "pyav"
return obj
I want you to use this function for reference as much as possible.
Yes, you can download all data from a Hugging Face repository without manually specifying each file by leveraging the huggingface_hub library. This approach allows you to automate the download process and integrate it seamlessly with your LeRobotDataset class. Below, I'll provide a step-by-step guide to achieve this.
1. Install Required Libraries
First, ensure you have the necessary libraries installed. You need huggingface_hub for interacting with Hugging Face repositories and tqdm for displaying progress bars.
bash
pip install huggingface_hub tqdm
2. Define a Function to Download All Repository Files
The following function uses the huggingface_hub library to list and download all files from a specified repository. It saves the files to a local directory, which can then be used by the LeRobotDataset class.
python
from huggingface_hub import repository_info, hf_hub_download, list_repo_files
from pathlib import Path
import os
from tqdm import tqdm
def download_all_repo_files(repo_id: str, local_dir: Path = None):
"""
Downloads all files from a Hugging Face repository to a local directory.
Args:
repo_id (str): The repository ID on Hugging Face (e.g., "lerobot/stanford_robocook").
local_dir (Path, optional): The local directory to save the files.
Defaults to './data/<repo_id>'.
Returns:
Path: The path to the local directory containing the downloaded files.
"""
if local_dir is None:
# Replace '/' with '_' to create a valid directory name
local_dir = Path.cwd() / "data" / repo_id.replace('/', '_')
local_dir.mkdir(parents=True, exist_ok=True)
# List all files in the repository
print(f"Listing all files in the repository '{repo_id}'...")
files = list_repo_files(repo_id)
print(f"Found {len(files)} files. Starting download...")
for file in tqdm(files, desc="Downloading files"):
try:
hf_hub_download(
repo_id=repo_id,
filename=file,
local_dir=local_dir,
repo_type='dataset', # Specify the repository type if necessary
local_dir_use_symlinks=False # Set to True if you prefer symlinks
)
except Exception as e:
print(f"Error downloading {file}: {e}")
print(f"All files downloaded to {local_dir}")
return local_dir
3. Integrate with LeRobotDataset
Now, use the downloaded files with your LeRobotDataset class by specifying the root parameter.
python
from datasets_utils.lerobot_dataset import LeRobotDataset
# Specify the repository ID
repo_id = "lerobot/stanford_robocook"
# Download all files to a local directory
local_data_dir = download_all_repo_files(repo_id)
# Initialize the dataset with the local directory
dataset = LeRobotDataset(repo_id=repo_id, root=local_data_dir)
# Verify the dataset
print(dataset)
4. Complete Example
Putting it all together, here's the complete script:
python
from huggingface_hub import repository_info, hf_hub_download, list_repo_files
from pathlib import Path
import os
from tqdm import tqdm
from datasets_utils.lerobot_dataset import LeRobotDataset
def download_all_repo_files(repo_id: str, local_dir: Path = None):
"""
Downloads all files from a Hugging Face repository to a local directory.
Args:
repo_id (str): The repository ID on Hugging Face (e.g., "lerobot/stanford_robocook").
local_dir (Path, optional): The local directory to save the files.
Defaults to './data/<repo_id>'.
Returns:
Path: The path to the local directory containing the downloaded files.
"""
if local_dir is None:
# Replace '/' with '_' to create a valid directory name
local_dir = Path.cwd() / "data" / repo_id.replace('/', '_')
local_dir.mkdir(parents=True, exist_ok=True)
# List all files in the repository
print(f"Listing all files in the repository '{repo_id}'...")
files = list_repo_files(repo_id)
print(f"Found {len(files)} files. Starting download...")
for file in tqdm(files, desc="Downloading files"):
try:
hf_hub_download(
repo_id=repo_id,
filename=file,
local_dir=local_dir,
repo_type='dataset', # Specify the repository type if necessary
local_dir_use_symlinks=False # Set to True if you prefer symlinks
)
except Exception as e:
print(f"Error downloading {file}: {e}")
print(f"All files downloaded to {local_dir}")
return local_dir
# Specify the repository ID
repo_id = "lerobot/stanford_robocook"
# Download all files to a local directory
local_data_dir = download_all_repo_files(repo_id)
# Initialize the dataset with the local directory
dataset = LeRobotDataset(repo_id=repo_id, root=local_data_dir)
# Verify the dataset
print(dataset)
5. Considerations
Storage Space: Ensure you have sufficient storage space to download all files from the repository.
Download Speed: Depending on the size of the dataset and your internet connection, the download process might take some time.
Error Handling: The provided function includes basic error handling. You might want to enhance it based on your specific requirements.
Caching: Hugging Face's hf_hub_download function caches downloads by default. If you run the script multiple times, it won't re-download files unless explicitly instructed to.
6. Alternative Approach: Using LeRobotDataset Directly
If you prefer to use the LeRobotDataset class without separately downloading all files, you can force the dataset to download all data by iterating through it. However, be cautious as this might be time-consuming for large datasets.
python
from datasets_utils.lerobot_dataset import LeRobotDataset
from tqdm import tqdm
def force_download_all(repo_id: str):
"""
Forces the download of all data in the dataset by iterating through it.
Args:
repo_id (str): The repository ID on Hugging Face.
"""
dataset = LeRobotDataset(repo_id=repo_id)
print(f"Starting to download all data for '{repo_id}'...")
for idx in tqdm(range(len(dataset)), desc="Downloading samples"):
_ = dataset[idx] # Accessing each item triggers the download
print("All data downloaded.")
# Usage
force_download_all("lerobot/stanford_robocook")
Note: This method will iterate through each sample in the dataset, triggering the download of each item. It's less efficient than downloading all files at once using huggingface_hub and is generally not recommended for very large datasets.
Conclusion
By using the huggingface_hub library, you can efficiently download all files from a Hugging Face repository without manually specifying each one. Integrating this with your LeRobotDataset class ensures that your dataset is fully populated and ready for use. This approach is scalable, efficient, and leverages existing tools to simplify the data management process.
If you encounter any issues or have further questions, feel free to ask!