# Specify the local directory path where you want to save the model
local_dir = "D:/_2_omni_projects/agent_builder"
# Ensure the directory exists or create it
os.makedirs(local_dir, exist_ok=True)
dataset = LeRobotDataset("lerobot/pusht")
print(dataset)
This prints this kind of data.
code
PS D:\_2_omni_projects\agent_builder> python .\app\temp.py
Fetching 212 files: 100%|██████████████████████████████████████████████████████████████████████| 212/212 [00:00<00:00, 6553.17it/s]
LeRobotDataset(
Fetching 212 files: 100%|██████████████████████████████████████████████████████████████████████| 212/212 [00:00<00:00, 6553.17it/s]
LeRobotDataset(
Repository ID: 'lerobot/pusht',
Split: 'train',
Split: 'train',
Number of Samples: 25650,
Number of Episodes: 206,
Type: video (.mp4),
Type: video (.mp4),
Recorded Frames per Second: 10,
Camera Keys: ['observation.image'],
Video Frame Keys: ['observation.image'],
Transformations: None,
Codebase Version: v1.6,
)
I want to download all of this data locally.
Assistant
To download all the data from the LeRobotDataset locally, you can iterate through each sample in the dataset and save the video files to your specified local directory. Below is a step-by-step guide along with sample code to achieve this.
Assumptions
Data Access: The LeRobotDataset either provides URLs to the video files or includes the video data directly (as bytes).
Key for Videos: The key 'observation.image' in each sample contains the video URL or the video data itself.
Dependencies:
requests library for downloading videos from URLs.
tqdm for displaying a progress bar.
Step-by-Step Guide
Set Up the Environment:
Ensure you have the necessary libraries installed. If not, you can install them using pip:
bash
pip install requests tqdm
Prepare the Local Directory:
Specify the path where you want to save the videos.
Create the directory if it doesn't exist.
Initialize the Dataset:
Load the LeRobotDataset using the provided identifier.
Iterate and Download:
Loop through each sample in the dataset.
Extract the video URL or data from each sample.
Download the video if it's a URL, or save the data directly if it's raw bytes.
Handle Different Data Formats:
If the video is provided as a URL, use HTTP requests to download it.
If the video data is provided directly, write it to a file.
Sample Code
python
import os
import shutil
from tqdm import tqdm
import requests
from datasets_utils.lerobot_dataset import LeRobotDataset
# 1. Specify the local directory path where you want to save the videos
local_dir = "D:/_2_omni_projects/agent_builder"
# 2. Ensure the directory exists or create it
os.makedirs(local_dir, exist_ok=True)
# 3. Initialize the dataset
dataset = LeRobotDataset("lerobot/pusht")
# Optional: Print the first sample to understand the structure
# print(dataset[0])
# 4. Iterate through all samples in the dataset with a progress bar
for idx, sample in enumerate(tqdm(dataset, desc="Downloading videos")):
video_info = sample.get('observation.image')
if not video_info:
print(f"Sample {idx} does not contain 'observation.image'. Skipping.")
continue
# 5a. If 'observation.image' is a URL, download the video
if isinstance(video_info, str) and video_info.startswith(('http://', 'https://')):
video_url = video_info
video_filename = os.path.basename(video_url.split("?")[0]) # Remove any query params
local_path = os.path.join(local_dir, video_filename)
# Skip download if file already exists
if os.path.exists(local_path):
continue
try:
response = requests.get(video_url, stream=True)
response.raise_for_status() # Check for HTTP errors
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
except requests.exceptions.RequestException as e:
print(f"Failed to download {video_url}: {e}")
# 5b. If 'observation.image' is a local path, copy the video
elif isinstance(video_info, str):
source_path = video_info
if not os.path.isabs(source_path):
# If the path is relative, make it absolute based on dataset's root
source_path = os.path.join(dataset.dataset_dir, source_path)
if os.path.exists(source_path):
video_filename = os.path.basename(source_path)
local_path = os.path.join(local_dir, video_filename)
# Skip copy if file already exists
if not os.path.exists(local_path):
shutil.copy2(source_path, local_path)
else:
print(f"Source file {source_path} does not exist. Skipping.")
# 5c. If 'observation.image' contains raw bytes, save directly
elif isinstance(video_info, bytes):
video_filename = f"video_{idx}.mp4"
local_path = os.path.join(local_dir, video_filename)
with open(local_path, 'wb') as f:
f.write(video_info)
else:
print(f"Unsupported format for 'observation.image' in sample {idx}. Skipping.")
print("Download completed.")
Explanation of the Code
Directory Handling: The script ensures that the local_dir exists. If not, it creates the directory.
Dataset Initialization: It initializes the LeRobotDataset with the identifier "lerobot/pusht".
Progress Bar: Using tqdm to display a progress bar during the download process.
Handling Different Data Types:
URL: If the video is provided as a URL, the script downloads it using the requests library.
Local Path: If the video is provided as a local path, it copies the file to the local_dir.
Raw Bytes: If the video data is provided directly as bytes, it writes the bytes to a file with a unique name.
Error Handling: The script includes basic error handling to skip samples that don't contain the expected data or encounter issues during download.
Additional Tips
Inspecting Sample Structure: It's a good idea to inspect a few samples to understand the exact structure of the data. You can uncomment the print(dataset[0]) line to see the first sample's content.
python
print(dataset[0])
Optimizing Downloads: To avoid re-downloading or copying files that already exist in the local_dir, the script checks if the file is already present and skips the download or copy if it is.
Logging: For larger datasets, consider implementing more robust logging to keep track of successes and failures.
Parallel Downloads: For faster downloads, especially if dealing with URLs, consider using parallel processing libraries like concurrent.futures. However, be cautious with rate limits and server policies.
Potential Adjustments
Dataset Structure: If the key 'observation.image' isn't the correct key for accessing video data, adjust the script accordingly based on the dataset's structure.
Authentication: If the dataset requires authentication (e.g., API keys), ensure you handle that in the script, especially for downloading videos from URLs.
Conclusion
By following the above approach, you should be able to download all videos from the LeRobotDataset to your specified local directory. Ensure you understand the dataset's structure and adjust the script as needed to fit your specific use case.