physicalword-assets / rlbench /train /convert_rlbench_npy_to_json.py
codemanCheng's picture
Add files using upload-large-folder tool
00eea01 verified
Raw
History Blame Contribute Delete
5.69 kB
import json
import re
from pathlib import Path
import cv2
import numpy as np
DATA_ROOT = Path("/mnt/nas/zhangyiming/database/rlbench/keyframe_fast_slow_chunk8_addlast_0806/for_rlds")
WORK_ROOT = Path("/mnt/nas/zhangyiming/database/rlbench/utils/npy_to_json_rules_v2")
JSON_ROOT = WORK_ROOT / "json"
JSONL_ROOT = WORK_ROOT / "jsonl"
IMG_ROOT = WORK_ROOT / "images"
VIDEO_ROOT = WORK_ROOT / "videos"
def ensure_dir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
def episode_sort_key(path: Path):
match = re.search(r"episode(\d+)", path.stem)
return int(match.group(1)) if match else path.stem
def to_jsonable(value):
if isinstance(value, np.ndarray):
return value.tolist()
if isinstance(value, np.generic):
return value.item()
return value
def write_episode_images(episode, task: str, episode_name: str):
img_dir = IMG_ROOT / task / episode_name
ensure_dir(img_dir)
for i, step in enumerate(episode):
frame = step["front_image"]
image_path = img_dir / f"front_{i}.png"
cv2.imwrite(str(image_path), cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
return img_dir
def convert_action(action):
action = np.asarray(action, dtype=np.float64).reshape(-1, 7)
return action.tolist()
def longest_language_instruction(npy_files):
best = None
for npy_path in npy_files:
episode = np.load(npy_path, allow_pickle=True)
for step in episode:
instruction = str(step["language_instruction"])
if best is None or len(instruction) > len(best):
best = instruction
if best is None:
raise ValueError("Cannot choose input_prompt from an empty task.")
return best
def convert_episode(npy_path: Path, task: str, input_prompt: str):
episode = np.load(npy_path, allow_pickle=True)
episode_name = npy_path.stem
img_dir = write_episode_images(episode, task, episode_name)
records = []
for frame_index, step in enumerate(episode):
record = {
"input_prompt": input_prompt,
"sub_prompt": step["language_subgoals"],
"front_pic": str(img_dir / f"front_{frame_index}.png"),
}
for key, value in step.items():
if key == "pointcloud":
continue
if key == "front_image":
continue
if key == "action":
record[key] = convert_action(value)
else:
record[key] = to_jsonable(value)
records.append(record)
return records
def write_json_outputs(json_path: Path, jsonl_path: Path, records) -> None:
with json_path.open("w", encoding="utf-8") as f:
json.dump(records, f, ensure_ascii=False, indent=2)
with jsonl_path.open("w", encoding="utf-8") as f:
for record in records:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
def write_statistics(output_path: Path, records, num_trajectories: int) -> None:
action_rows = []
states = []
for record in records:
action_rows.extend(record["action"])
states.append(record["state"])
actions = np.asarray(action_rows, dtype=np.float64)
states = np.asarray(states, dtype=np.float64)
def calculate_stats(data, mask):
return {
"mean": np.mean(data, axis=0).tolist(),
"std": np.std(data, axis=0).tolist(),
"max": np.max(data, axis=0).tolist(),
"min": np.min(data, axis=0).tolist(),
"q01": np.quantile(data, 0.01, axis=0).tolist(),
"q99": np.quantile(data, 0.99, axis=0).tolist(),
"mask": mask,
}
result = {
"rlbench": {
"action": calculate_stats(actions, [True, True, True, True, True, True, False]),
"state": calculate_stats(states, [True, True, True, True, True, True, False]),
"num_transitions": len(records),
"num_trajectories": num_trajectories,
}
}
with output_path.open("w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
def convert_all():
ensure_dir(JSON_ROOT)
ensure_dir(JSONL_ROOT)
ensure_dir(IMG_ROOT)
all_records = []
summary = {}
for task_dir in sorted([p for p in DATA_ROOT.iterdir() if p.is_dir()]):
task = task_dir.name
task_records = []
npy_files = sorted(task_dir.glob("*.npy"), key=episode_sort_key)
input_prompt = longest_language_instruction(npy_files)
for npy_file in npy_files:
task_records.extend(convert_episode(npy_file, task, input_prompt))
json_path = JSON_ROOT / f"{task}.json"
jsonl_path = JSONL_ROOT / f"{task}.jsonl"
stat_path = JSON_ROOT / f"{task}_statistics.json"
write_json_outputs(json_path, jsonl_path, task_records)
write_statistics(stat_path, task_records, len(npy_files))
summary[task] = {
"episodes": len(npy_files),
"samples": len(task_records),
"input_prompt": input_prompt,
"json": str(json_path),
"jsonl": str(jsonl_path),
"statistics": str(stat_path),
}
all_records.extend(task_records)
write_json_outputs(JSON_ROOT / "train.json", JSONL_ROOT / "train.jsonl", all_records)
write_statistics(JSON_ROOT / "train_statistics.json", all_records, sum(item["episodes"] for item in summary.values()))
with (WORK_ROOT / "summary.json").open("w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
print(json.dumps(summary, ensure_ascii=False, indent=2))
if __name__ == "__main__":
convert_all()