|
""" |
|
This project is built upon the open-source project 🤗 LeRobot: https://github.com/huggingface/lerobot |
|
|
|
We are grateful to the LeRobot team for their outstanding work and their contributions to the community. |
|
|
|
If you find this project useful, please also consider supporting and exploring LeRobot. |
|
""" |
|
|
|
import os |
|
import cv2 |
|
import json |
|
import glob |
|
import shutil |
|
import logging |
|
import argparse |
|
from pathlib import Path |
|
from typing import Callable |
|
from functools import partial |
|
from math import ceil |
|
from copy import deepcopy |
|
import subprocess |
|
from multiprocessing import Pool, cpu_count |
|
|
|
|
|
import h5py |
|
import torch |
|
import einops |
|
import numpy as np |
|
from PIL import Image |
|
from tqdm import tqdm |
|
|
|
|
|
HEAD_COLOR = "head.mp4" |
|
HAND_LEFT_COLOR = "hand_left.mp4" |
|
HAND_RIGHT_COLOR = "hand_right.mp4" |
|
HEAD_CENTER_FISHEYE_COLOR = "head_front_fisheye.mp4" |
|
HEAD_LEFT_FISHEYE_COLOR = "head_left_fisheye.mp4" |
|
HEAD_RIGHT_FISHEYE_COLOR = "head_right_fisheye.mp4" |
|
BACK_LEFT_FISHEYE_COLOR = "back_left_fisheye.mp4" |
|
BACK_RIGHT_FISHEYE_COLOR = "back_right_fisheye.mp4" |
|
HEAD_DEPTH = "head" |
|
ALL_VIDEOS = [HEAD_COLOR, HAND_LEFT_COLOR, HAND_RIGHT_COLOR, HEAD_CENTER_FISHEYE_COLOR, HEAD_LEFT_FISHEYE_COLOR, HEAD_RIGHT_FISHEYE_COLOR, BACK_LEFT_FISHEYE_COLOR, BACK_RIGHT_FISHEYE_COLOR] |
|
|
|
DEFAULT_IMAGE_PATH = ( |
|
"images/{image_key}/episode_{episode_index:06d}/frame_{frame_index:06d}.jpg" |
|
) |
|
|
|
FEATURES = { |
|
"observation.images.top_head": { |
|
"dtype": "video", |
|
"shape": [480, 640, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.cam_top_depth": { |
|
"dtype": "image", |
|
"shape": [480, 640, 1], |
|
"names": ["height", "width", "channel"], |
|
}, |
|
"observation.images.hand_left": { |
|
"dtype": "video", |
|
"shape": [480, 640, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.hand_right": { |
|
"dtype": "video", |
|
"shape": [480, 640, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.head_center_fisheye": { |
|
"dtype": "video", |
|
"shape": [748, 960, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.head_left_fisheye": { |
|
"dtype": "video", |
|
"shape": [748, 960, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.head_right_fisheye": { |
|
"dtype": "video", |
|
"shape": [748, 960, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.back_left_fisheye": { |
|
"dtype": "video", |
|
"shape": [748, 960, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.images.back_right_fisheye": { |
|
"dtype": "video", |
|
"shape": [748, 960, 3], |
|
"names": ["height", "width", "channel"], |
|
"video_info": { |
|
"video.fps": 30.0, |
|
"video.codec": "av1", |
|
"video.pix_fmt": "yuv420p", |
|
"video.is_depth_map": False, |
|
"has_audio": False, |
|
}, |
|
}, |
|
"observation.state": { |
|
"dtype": "float32", |
|
"shape": [22], |
|
}, |
|
"action": { |
|
"dtype": "float32", |
|
"shape": [22], |
|
}, |
|
"episode_index": { |
|
"dtype": "int64", |
|
"shape": [1], |
|
"names": None, |
|
}, |
|
"frame_index": { |
|
"dtype": "int64", |
|
"shape": [1], |
|
"names": None, |
|
}, |
|
"index": { |
|
"dtype": "int64", |
|
"shape": [1], |
|
"names": None, |
|
}, |
|
"task_index": { |
|
"dtype": "int64", |
|
"shape": [1], |
|
"names": None, |
|
}, |
|
} |
|
|
|
|
|
|
|
|
|
from modified_lerobot_dataset import AgiBotDataset |
|
|
|
|
|
|
|
|
|
def process_video(video_path): |
|
output = video_path.replace('.mp4', '_encode.mp4') |
|
try: |
|
command = [ |
|
"ffmpeg", |
|
"-i", video_path, |
|
"-vcodec", "libsvtav1", |
|
"-pix_fmt", "yuv420p", |
|
"-r", "30", |
|
"-g", "2", |
|
"-crf", "30", |
|
"-vf", "scale=640:360:flags=bicubic", |
|
"-loglevel", "error", |
|
"-y", output |
|
] |
|
subprocess.run(command, check=True) |
|
|
|
except subprocess.CalledProcessError as e: |
|
print(f"Video failure: {' '.join(command)}, error: {e}") |
|
except Exception as e: |
|
print(f"Video unknwon failure: {' '.join(command)}, error: {e}") |
|
finally: |
|
pass |
|
|
|
|
|
def preprocess_vides(episode_list, debug=False): |
|
video_paths = [] |
|
for episode_path in episode_list: |
|
video_dir = episode_path.replace('meta_info', 'observation') + "/video" |
|
for file in ALL_VIDEOS: |
|
video_path = os.path.join(video_dir, file) |
|
video_paths.append(video_path) |
|
|
|
if debug: |
|
for video in video_paths: |
|
process_video(video) |
|
else: |
|
with Pool(processes=os.cpu_count() // 2) as pool: |
|
for _ in tqdm(pool.imap_unordered(process_video, video_paths), total=len(video_paths), desc="Video preprocessing"): |
|
pass |
|
|
|
|
|
def load_depths(root_dir: str, camera_name: str): |
|
cam_path = Path(root_dir) |
|
all_imgs = sorted(list(cam_path.glob(f"*")), key=lambda x: int(x.stem)) |
|
return [np.array(Image.open(f"{file}/{camera_name}.png")).astype(np.float32) / 1000 for file in all_imgs] |
|
|
|
|
|
def load_local_dataset(episode_path: str) -> list | None: |
|
"""Load local dataset and return a dict with observations and actions""" |
|
observation_path = episode_path.replace('meta_info', 'observation') |
|
with open(f"{episode_path}/task_info.json") as f: |
|
task_info = json.load(f) |
|
task = task_info['task_name'] |
|
|
|
with h5py.File(Path(episode_path) / "aligned_joints.h5") as f: |
|
state_joint = np.array(f["state/joint/position"]) |
|
joint_names = f["state/joint"].attrs['name'].tolist() |
|
|
|
|
|
head_joint_names = [ |
|
"joint_head_yaw", |
|
"joint_head_pitch", |
|
] |
|
body_joint_names = [ |
|
"joint_lift_body", |
|
"joint_body_pitch", |
|
] |
|
arm_joint_names = [ |
|
"Joint1_l", |
|
"Joint1_r", |
|
"Joint2_l", |
|
"Joint2_r", |
|
"Joint3_l", |
|
"Joint3_r", |
|
"Joint4_l", |
|
"Joint4_r", |
|
"Joint5_l", |
|
"Joint5_r", |
|
"Joint6_l", |
|
"Joint6_r", |
|
"Joint7_l", |
|
"Joint7_r", |
|
] |
|
effector_joint_names = [ |
|
"right_Left_1_Joint", |
|
"right_Right_1_Joint", |
|
"left_Left_1_Joint", |
|
"left_Right_1_Joint" |
|
] |
|
|
|
|
|
head_joint_indices = [joint_names.index(name) for name in head_joint_names] |
|
body_joint_indices = [joint_names.index(name) for name in body_joint_names] |
|
arm_joint_indices = [joint_names.index(name) for name in arm_joint_names] |
|
effector_joint_indices = [joint_names.index(name) for name in effector_joint_names] |
|
|
|
|
|
state_head = state_joint[:, head_joint_indices] |
|
state_body = state_joint[:, body_joint_indices] |
|
state_arm = state_joint[:, arm_joint_indices] |
|
state_effector = state_joint[:, effector_joint_indices] |
|
|
|
|
|
|
|
action_head = state_head[1:] - state_head[:-1] |
|
action_body = state_body[1:] - state_body[:-1] |
|
action_arm = state_arm[1:] - state_arm[:-1] |
|
action_effector = state_effector[1:] - state_effector[:-1] |
|
|
|
|
|
action_head = np.concatenate([action_head, action_head[-1:]]) |
|
action_body = np.concatenate([action_body, action_body[-1:]]) |
|
action_arm = np.concatenate([action_arm, action_arm[-1:]]) |
|
action_effector = np.concatenate([action_effector, action_effector[-1:]]) |
|
|
|
|
|
|
|
states_value = np.hstack( |
|
[state_head, state_body, state_arm, state_effector] |
|
).astype(np.float32) |
|
assert ( |
|
action_arm.shape[0] == action_effector.shape[0] |
|
), f"shape of action_arm:{action_arm.shape};shape of action_effector:{action_effector.shape}" |
|
action_value = np.hstack( |
|
[action_head, action_body, action_arm, action_effector] |
|
).astype(np.float32) |
|
|
|
depth_imgs = load_depths(f"{observation_path}/depth", HEAD_DEPTH) |
|
|
|
assert len(depth_imgs) == len( |
|
states_value |
|
), f"Number of images and states are not equal" |
|
assert len(depth_imgs) == len( |
|
action_value |
|
), f"Number of images and actions are not equal" |
|
frames = [ |
|
{ |
|
"observation.images.cam_top_depth": depth_imgs[i], |
|
"observation.state": states_value[i], |
|
"action": action_value[i], |
|
} |
|
for i in range(len(depth_imgs)) |
|
] |
|
|
|
v_path = observation_path + "/video" |
|
videos = { |
|
"observation.images.top_head": f"{v_path}/{HEAD_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.hand_left": f"{v_path}/{HAND_LEFT_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.hand_right": f"{v_path}/{HAND_RIGHT_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.head_center_fisheye": f"{v_path}/{HEAD_CENTER_FISHEYE_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.head_left_fisheye": f"{v_path}/{HEAD_LEFT_FISHEYE_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.head_right_fisheye": f"{v_path}/{HEAD_RIGHT_FISHEYE_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.back_left_fisheye": f"{v_path}/{BACK_LEFT_FISHEYE_COLOR}".replace('.mp4', '_encode.mp4'), |
|
"observation.images.back_right_fisheye": f"{v_path}/{BACK_RIGHT_FISHEYE_COLOR}".replace('.mp4', '_encode.mp4'), |
|
} |
|
return { |
|
'frames': frames, |
|
'videos': videos, |
|
'task': task |
|
} |
|
|
|
|
|
|
|
|
|
|
|
def main( |
|
src_path: str, |
|
tgt_path: str, |
|
repo_id: str, |
|
preprocess_video: bool = False, |
|
debug: bool = True, |
|
): |
|
|
|
if os.path.exists(f"{tgt_path}/{repo_id}"): |
|
shutil.rmtree(f"{tgt_path}/{repo_id}") |
|
dataset = AgiBotDataset.create( |
|
repo_id=repo_id, |
|
root=f"{tgt_path}/{repo_id}", |
|
fps=30, |
|
robot_type="a2d", |
|
features=FEATURES, |
|
) |
|
|
|
episode_list = sorted( |
|
[ |
|
f |
|
for f in glob.glob(f"{src_path}/meta_info/*/*") |
|
if os.path.isdir(f) |
|
] |
|
) |
|
|
|
|
|
if preprocess_video: |
|
preprocess_vides(episode_list, debug) |
|
|
|
|
|
raw_datasets_before_filter = [ |
|
load_local_dataset(episode_path) |
|
for episode_path in tqdm(episode_list) |
|
] |
|
|
|
|
|
raw_datasets = [ |
|
dataset for dataset in raw_datasets_before_filter if dataset is not None |
|
] |
|
|
|
for episode_data in tqdm(raw_datasets, desc="Generating dataset from raw datasets"): |
|
for frame in tqdm(episode_data['frames'], desc="Generating dataset from raw dataset"): |
|
dataset.add_frame(frame) |
|
|
|
dataset.save_episode(task=episode_data['task'], videos=episode_data['videos']) |
|
dataset.consolidate(run_compute_stats=True) |
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
parser = argparse.ArgumentParser() |
|
parser.add_argument( |
|
"--data_dir", |
|
type=str, |
|
required=True, |
|
) |
|
parser.add_argument( |
|
"--save_dir", |
|
type=str, |
|
required=True, |
|
) |
|
parser.add_argument( |
|
"--repo_id", |
|
type=str, |
|
required=True, |
|
) |
|
parser.add_argument( |
|
"--preprocess_video", |
|
action="store_true", |
|
) |
|
parser.add_argument( |
|
"--debug", |
|
action="store_true", |
|
) |
|
args = parser.parse_args() |
|
|
|
|
|
|
|
assert os.path.exists(args.data_dir), f"Cannot find {args.data_dir}." |
|
|
|
|
|
main(args.data_dir, args.save_dir, args.repo_id, args.preprocess_video, args.debug) |