File size: 7,455 Bytes
208faa0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | """Preprocess 5000 episodes with 24-frame RGB and 25-frame aligned reason data.
Per episode (same episode list as coaf_dataset/splits/train_5k.json):
rgb/ frame_0001.png .. frame_0024.png (256x256, 24 frames)
rgb_align/ frame_0001.png .. frame_0025.png (same timesteps as reason)
state/state.npy (25, 7) — indices match rgb_align / depth / pose / flow / follow
action/action.npy (25, 7)
instruction/instruction.txt
manifest.json records both index arrays and shapes
"""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
import cv2
import numpy as np
import tensorflow_datasets as tfds
SCRIPT_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(SCRIPT_DIR))
from sampling import RGB_FRAMES, REASON_FRAMES, reason_indices, rgb_indices
TFDS_DIR = "/project/llmsvgen/sunkai/robomaster_3d/CoAF/data/bridge_v_full/1.0.0"
DATASET_ROOT = Path("/project/llmsvgen/sunkai/robomaster_3d/Casual_CoAF/coaf_dataset_24_25")
SPLIT_FILE = DATASET_ROOT / "splits" / "train_5k.json"
OUTPUT_ROOT = DATASET_ROOT / "raw"
IMAGE_SIZE = 256
MIN_RAW_FRAMES = max(RGB_FRAMES, REASON_FRAMES)
def save_rgb_frames(frames: np.ndarray, out_dir: Path, image_size: int) -> None:
out_dir.mkdir(parents=True, exist_ok=True)
for i, frame in enumerate(frames):
if frame.shape[0] != image_size or frame.shape[1] != image_size:
frame = cv2.resize(
frame, (image_size, image_size), interpolation=cv2.INTER_LANCZOS4
)
cv2.imwrite(
str(out_dir / f"frame_{i + 1:04d}.png"),
cv2.cvtColor(frame, cv2.COLOR_RGB2BGR),
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tfds-dir", type=str, default=TFDS_DIR)
parser.add_argument("--split-file", type=Path, default=SPLIT_FILE)
parser.add_argument("--output-root", type=Path, default=OUTPUT_ROOT)
parser.add_argument("--image-size", type=int, default=IMAGE_SIZE)
parser.add_argument("--skip-existing", action="store_true")
parser.add_argument(
"--start",
type=int,
default=0,
help="Minimum dataset output index (episode_000000 -> 0)",
)
parser.add_argument(
"--stop",
type=int,
default=None,
help="Exclusive max dataset output index (default: all in split)",
)
args = parser.parse_args()
episode_ids = json.loads(args.split_file.read_text())
if args.stop is not None:
episode_ids = episode_ids[args.start : args.stop]
else:
episode_ids = episode_ids[args.start :]
print(f"Loaded {len(episode_ids)} episode IDs from {args.split_file} "
f"(dataset_idx {args.start}..{args.stop if args.stop is not None else 'end'})")
builder = tfds.builder_from_directory(args.tfds_dir)
dataset = builder.as_dataset(split="train")
args.output_root.mkdir(parents=True, exist_ok=True)
target_set = set(episode_ids)
target_sorted = sorted(episode_ids)
id_to_out = {eid: i for i, eid in enumerate(target_sorted)}
start_time = time.time()
processed = 0
failed = []
print(f"RGB frames={RGB_FRAMES}, reason-aligned frames={REASON_FRAMES}")
print(f"Episode ID range: {target_sorted[0]} ~ {target_sorted[-1]}")
for episode_idx, episode in enumerate(dataset):
if episode_idx > target_sorted[-1]:
break
if episode_idx not in target_set:
continue
out_idx = id_to_out[episode_idx]
episode_dir = args.output_root / f"episode_{out_idx:06d}"
done_marker = episode_dir / "rgb" / f"frame_{RGB_FRAMES:04d}.png"
if args.skip_existing and done_marker.exists():
processed += 1
continue
try:
steps = list(episode["steps"].as_numpy_iterator())
num_steps = len(steps)
if num_steps < MIN_RAW_FRAMES:
raise ValueError(f"num_steps={num_steps} < {MIN_RAW_FRAMES}")
states_raw = np.stack([s["observation"]["state"] for s in steps])
actions_raw = np.stack([s["action"] for s in steps])
rgb_raw = np.stack([s["observation"]["image_0"] for s in steps])
instruction = steps[0]["language_instruction"]
if isinstance(instruction, bytes):
instruction = instruction.decode("utf-8", errors="replace")
instruction = instruction.strip()
idx_rgb = rgb_indices(num_steps)
idx_reason = reason_indices(num_steps)
states = states_raw[idx_reason]
actions = actions_raw[idx_reason]
rgb_frames = rgb_raw[idx_rgb]
rgb_align_frames = rgb_raw[idx_reason]
assert states.shape == (REASON_FRAMES, 7)
assert actions.shape == (REASON_FRAMES, 7)
assert len(rgb_frames) == RGB_FRAMES
assert len(rgb_align_frames) == REASON_FRAMES
save_rgb_frames(rgb_frames, episode_dir / "rgb", args.image_size)
save_rgb_frames(rgb_align_frames, episode_dir / "rgb_align", args.image_size)
state_dir = episode_dir / "state"
action_dir = episode_dir / "action"
instr_dir = episode_dir / "instruction"
for d in (state_dir, action_dir, instr_dir):
d.mkdir(parents=True, exist_ok=True)
np.save(str(state_dir / "state.npy"), states)
np.save(str(action_dir / "action.npy"), actions)
(instr_dir / "instruction.txt").write_text(instruction, encoding="utf-8")
manifest = {
"original_episode_idx": episode_idx,
"dataset_idx": out_idx,
"num_raw_frames": num_steps,
"instruction": instruction,
"rgb_frames": RGB_FRAMES,
"reason_frames": REASON_FRAMES,
"rgb_indices": idx_rgb.tolist(),
"reason_indices": idx_reason.tolist(),
"state_shape": list(states.shape),
"action_shape": list(actions.shape),
"image_size": args.image_size,
"sampling_note": (
"rgb uses rgb_indices; rgb_align/state/action/reason modalities "
"share reason_indices"
),
}
(episode_dir / "manifest.json").write_text(
json.dumps(manifest, indent=2) + "\n"
)
processed += 1
if processed % 200 == 0:
elapsed = time.time() - start_time
eps = processed / elapsed
remaining = (len(episode_ids) - processed) / eps
print(
f" [{processed}/{len(episode_ids)}] episode_idx={episode_idx}, "
f"{elapsed:.0f}s elapsed, ~{remaining:.0f}s remaining"
)
except Exception as e:
print(f" [FAIL] episode_idx={episode_idx}: {e}")
failed.append({"episode_idx": episode_idx, "error": str(e)})
elapsed = time.time() - start_time
print(f"\nDone! Processed {processed}/{len(episode_ids)} episodes in {elapsed:.0f}s")
if failed:
fail_path = args.output_root / "preprocess_failures.json"
fail_path.write_text(json.dumps(failed, indent=2) + "\n")
print(f"Failures saved to {fail_path}")
if __name__ == "__main__":
main()
|