Download Code/data_pipeline/data_split/benchmark_data_splitter.py from zgong313/sage3d: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/datasets/zgong313/sage3d/resolve/main/Code/data_pipeline/data_split/benchmark_data_splitter.py
- Command line
-
hf download hf://datasets/zgong313/sage3d/Code/data_pipeline/data_split/benchmark_data_splitter.py
-
curl -L -o benchmark_data_splitter.py https://huggingface.co/datasets/zgong313/sage3d/resolve/main/Code/data_pipeline/data_split/benchmark_data_splitter.py
19.4 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| Benchmark Dataset Splitter & Renamer. | |
| This script reads the JSON mapping files generated by `trajectory_split_domain_aware.py`, | |
| extracts the corresponding samples from the original merged trajectory data, and optionally | |
| renames the output files with split-specific prefixes. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from copy import deepcopy | |
| from pathlib import Path | |
| from typing import Dict, List | |
| # ==================== Default Configuration ==================== | |
| DEFAULT_ORIGINAL_DATA_DIR = Path("Data/trajectories/trajectory_splits") | |
| DEFAULT_MAPPING_DIR = Path("Data/trajectories/data_splits") | |
| DEFAULT_OUTPUT_BASE = Path("Data/trajectories/data_splits") | |
| DEFAULT_TRAIN_DIR = DEFAULT_OUTPUT_BASE / "train" | |
| DEFAULT_VAL_DIR = DEFAULT_OUTPUT_BASE / "val" | |
| DEFAULT_SCENE_UNSEEN_DIR = DEFAULT_OUTPUT_BASE / "test_scene_unseen" | |
| DEFAULT_TRAJECTORY_UNSEEN_DIR = DEFAULT_OUTPUT_BASE / "test_trajectory_unseen" | |
| DEFAULT_INSTRUCTION_UNSEEN_DIR = DEFAULT_OUTPUT_BASE / "test_instruction_unseen" | |
| DEFAULT_PREFIXES = { | |
| "train": "train_", | |
| "val": "val_", | |
| "scene_unseen": "test_", | |
| "trajectory_unseen": "test_", | |
| "instruction_unseen": "test_", | |
| } | |
| MAPPING_FILENAMES = { | |
| "train": "GSNav-Bench_Train_Split_Domain.json", | |
| "val": "GSNav-Bench_Val_Split_Domain.json", | |
| "scene_unseen": "GSNav-Bench_Test_Scene_Unseen_Split_Domain.json", | |
| "trajectory_unseen": "GSNav-Bench_Test_Trajectory_Unseen_Split_Domain.json", | |
| "instruction_unseen": "GSNav-Bench_Test_Instruction_Unseen_Split_Domain.json", | |
| } | |
| # ==================== Helper Class ==================== | |
| class BenchmarkDatasetBuilder: | |
| """Extract split data according to mapping files and optionally rename outputs.""" | |
| def __init__( | |
| self, | |
| original_data_dir: Path, | |
| mapping_dir: Path, | |
| output_dirs: Dict[str, Path], | |
| prefixes: Dict[str, str], | |
| rename_files: bool = True, | |
| ): | |
| self.original_data_dir = original_data_dir | |
| self.mapping_dir = mapping_dir | |
| self.output_dirs = output_dirs | |
| self.prefixes = prefixes | |
| self.rename_files = rename_files | |
| self.split_mappings: Dict[str, Dict] = {} | |
| # ---------- Data Loading ---------- | |
| def load_split_mappings(self) -> None: | |
| """Load all split mapping JSON files.""" | |
| print("Loading split mapping files...") | |
| for split_name, filename in MAPPING_FILENAMES.items(): | |
| file_path = self.mapping_dir / filename | |
| if not file_path.exists(): | |
| raise FileNotFoundError(f"Mapping file not found: {file_path}") | |
| with file_path.open("r", encoding="utf-8") as f: | |
| self.split_mappings[split_name] = json.load(f) | |
| scene_count = len(self.split_mappings[split_name].get("scenes", {})) | |
| print(f" Loaded {split_name:<20s}: {scene_count} scenes") | |
| def load_original_scene_data(self, scene_id: str) -> Dict: | |
| """Load the original trajectory JSON for a scene.""" | |
| scene_dir = self.original_data_dir / scene_id | |
| trajectory_files = list(scene_dir.glob("trajectories_overall_*.json")) | |
| if not trajectory_files: | |
| raise FileNotFoundError(f"No trajectories_overall_*.json found for scene {scene_id}") | |
| with trajectory_files[0].open("r", encoding="utf-8") as f: | |
| return json.load(f) | |
| # ---------- Output Directories ---------- | |
| def create_output_directories(self) -> None: | |
| """Create output directories for all splits.""" | |
| print("Creating output directories...") | |
| for split_name, output_path in self.output_dirs.items(): | |
| output_path.mkdir(parents=True, exist_ok=True) | |
| print(f" {split_name:<20s} -> {output_path}") | |
| # ---------- Extraction Helpers ---------- | |
| def _get_scene_filename(self, scene_id: str) -> str: | |
| scene_dir = self.original_data_dir / scene_id | |
| trajectory_files = list(scene_dir.glob("trajectories_overall_*.json")) | |
| if trajectory_files: | |
| return trajectory_files[0].name | |
| return f"trajectories_overall_{scene_id}.json" | |
| def _save_scene_data(self, data: Dict, output_dir: Path, filename: str) -> None: | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| output_path = output_dir / filename | |
| with output_path.open("w", encoding="utf-8") as f: | |
| json.dump(data, f, indent=2, ensure_ascii=False) | |
| # ---------- Split Extraction ---------- | |
| def extract_scene_unseen(self) -> None: | |
| """Extract Scene-Unseen test data (full scenes).""" | |
| print("\n=== Extracting Scene-Unseen test set ===") | |
| split_data = self.split_mappings["scene_unseen"] | |
| output_dir = self.output_dirs["scene_unseen"] | |
| total_scenes = total_trajectories = total_instructions = 0 | |
| for scene_id in split_data["scenes"].keys(): | |
| print(f" Scene {scene_id}") | |
| original_data = self.load_original_scene_data(scene_id) | |
| scene_filename = self._get_scene_filename(scene_id) | |
| scene_output_dir = output_dir / scene_id | |
| self._save_scene_data(original_data, scene_output_dir, scene_filename) | |
| samples = original_data["scenes"][0]["samples"] | |
| total_scenes += 1 | |
| total_trajectories += len(samples) | |
| total_instructions += sum(len(sample["instructions"]) for sample in samples) | |
| print( | |
| f"Scene-Unseen done: {total_scenes} scenes, {total_trajectories} trajectories, {total_instructions} instructions" | |
| ) | |
| def extract_val(self) -> None: | |
| """Extract validation data (full scenes).""" | |
| print("\n=== Extracting validation set ===") | |
| split_data = self.split_mappings["val"] | |
| output_dir = self.output_dirs["val"] | |
| total_scenes = total_trajectories = total_instructions = 0 | |
| for scene_id in split_data["scenes"].keys(): | |
| print(f" Scene {scene_id}") | |
| original_data = self.load_original_scene_data(scene_id) | |
| scene_filename = self._get_scene_filename(scene_id) | |
| scene_output_dir = output_dir / scene_id | |
| self._save_scene_data(original_data, scene_output_dir, scene_filename) | |
| samples = original_data["scenes"][0]["samples"] | |
| total_scenes += 1 | |
| total_trajectories += len(samples) | |
| total_instructions += sum(len(sample["instructions"]) for sample in samples) | |
| print( | |
| f"Validation done: {total_scenes} scenes, {total_trajectories} trajectories, {total_instructions} instructions" | |
| ) | |
| def extract_trajectory_unseen(self) -> None: | |
| """Extract Trajectory-Unseen test data (subset of trajectories).""" | |
| print("\n=== Extracting Trajectory-Unseen test set ===") | |
| split_data = self.split_mappings["trajectory_unseen"] | |
| output_dir = self.output_dirs["trajectory_unseen"] | |
| total_scenes = total_trajectories = total_instructions = 0 | |
| for scene_id, scene_info in split_data["scenes"].items(): | |
| print(f" Scene {scene_id}") | |
| original_data = self.load_original_scene_data(scene_id) | |
| samples = original_data["scenes"][0]["samples"] | |
| trajectory_map = {sample["trajectory_id"]: sample for sample in samples} | |
| selected_samples = [] | |
| scene_instruction_count = 0 | |
| for traj_info in scene_info["trajectories"]: | |
| traj_id = traj_info["trajectory_id"] | |
| sample = trajectory_map.get(traj_id) | |
| if sample: | |
| selected_samples.append(deepcopy(sample)) | |
| scene_instruction_count += len(sample["instructions"]) | |
| else: | |
| print(f" [WARN] Trajectory {traj_id} not found in scene {scene_id}") | |
| if selected_samples: | |
| new_data = deepcopy(original_data) | |
| new_data["scenes"][0]["samples"] = selected_samples | |
| scene_output_dir = output_dir / scene_id | |
| scene_filename = self._get_scene_filename(scene_id) | |
| self._save_scene_data(new_data, scene_output_dir, scene_filename) | |
| total_scenes += 1 | |
| total_trajectories += len(selected_samples) | |
| total_instructions += scene_instruction_count | |
| print( | |
| f" Selected {len(selected_samples)} trajectories, {scene_instruction_count} instructions" | |
| ) | |
| print( | |
| f"Trajectory-Unseen done: {total_scenes} scenes, {total_trajectories} trajectories, {total_instructions} instructions" | |
| ) | |
| def extract_instruction_unseen(self) -> None: | |
| """Extract Instruction-Unseen test data (subset of instructions).""" | |
| print("\n=== Extracting Instruction-Unseen test set ===") | |
| split_data = self.split_mappings["instruction_unseen"] | |
| output_dir = self.output_dirs["instruction_unseen"] | |
| total_scenes = total_trajectories = total_instructions = 0 | |
| for scene_id, scene_info in split_data["scenes"].items(): | |
| print(f" Scene {scene_id}") | |
| original_data = self.load_original_scene_data(scene_id) | |
| samples = original_data["scenes"][0]["samples"] | |
| trajectory_map = {sample["trajectory_id"]: sample for sample in samples} | |
| selected_samples = [] | |
| scene_instruction_count = 0 | |
| for traj_info in scene_info["trajectories"]: | |
| traj_id = traj_info["trajectory_id"] | |
| indices = traj_info["selected_instruction_indices"] | |
| sample = trajectory_map.get(traj_id) | |
| if sample: | |
| new_sample = deepcopy(sample) | |
| new_sample["instructions"] = [ | |
| sample["instructions"][idx] | |
| for idx in indices | |
| if 0 <= idx < len(sample["instructions"]) | |
| ] | |
| if new_sample["instructions"]: | |
| selected_samples.append(new_sample) | |
| scene_instruction_count += len(new_sample["instructions"]) | |
| else: | |
| print(f" [WARN] Trajectory {traj_id} not found in scene {scene_id}") | |
| if selected_samples: | |
| new_data = deepcopy(original_data) | |
| new_data["scenes"][0]["samples"] = selected_samples | |
| scene_output_dir = output_dir / scene_id | |
| scene_filename = self._get_scene_filename(scene_id) | |
| self._save_scene_data(new_data, scene_output_dir, scene_filename) | |
| total_scenes += 1 | |
| total_trajectories += len(selected_samples) | |
| total_instructions += scene_instruction_count | |
| print( | |
| f" Selected {len(selected_samples)} trajectories, {scene_instruction_count} instructions" | |
| ) | |
| print( | |
| f"Instruction-Unseen done: {total_scenes} scenes, {total_trajectories} trajectories, {total_instructions} instructions" | |
| ) | |
| def extract_train(self) -> None: | |
| """Extract training data (exclude test trajectories/instructions).""" | |
| print("\n=== Extracting training set ===") | |
| split_data = self.split_mappings["train"] | |
| output_dir = self.output_dirs["train"] | |
| total_scenes = total_trajectories = total_instructions = 0 | |
| for scene_id, scene_info in split_data["scenes"].items(): | |
| print(f" Scene {scene_id}") | |
| original_data = self.load_original_scene_data(scene_id) | |
| samples = original_data["scenes"][0]["samples"] | |
| trajectory_map = {sample["trajectory_id"]: sample for sample in samples} | |
| selected_samples = [] | |
| scene_instruction_count = 0 | |
| for traj_info in scene_info["trajectories"]: | |
| traj_id = traj_info["trajectory_id"] | |
| available_indices = set(traj_info["available_instruction_indices"]) | |
| sample = trajectory_map.get(traj_id) | |
| if sample and available_indices: | |
| new_sample = deepcopy(sample) | |
| new_sample["instructions"] = [ | |
| sample["instructions"][idx] | |
| for idx in sorted(available_indices) | |
| if 0 <= idx < len(sample["instructions"]) | |
| ] | |
| if new_sample["instructions"]: | |
| selected_samples.append(new_sample) | |
| scene_instruction_count += len(new_sample["instructions"]) | |
| else: | |
| print(f" [WARN] Trajectory {traj_id} not found or has no available instructions") | |
| if selected_samples: | |
| new_data = deepcopy(original_data) | |
| new_data["scenes"][0]["samples"] = selected_samples | |
| scene_output_dir = output_dir / scene_id | |
| scene_filename = self._get_scene_filename(scene_id) | |
| self._save_scene_data(new_data, scene_output_dir, scene_filename) | |
| total_scenes += 1 | |
| total_trajectories += len(selected_samples) | |
| total_instructions += scene_instruction_count | |
| print( | |
| f" Selected {len(selected_samples)} trajectories, {scene_instruction_count} instructions" | |
| ) | |
| print( | |
| f"Training set done: {total_scenes} scenes, {total_trajectories} trajectories, {total_instructions} instructions" | |
| ) | |
| # ---------- Renaming ---------- | |
| def rename_split_files(self) -> None: | |
| """Rename files in each split directory using configured prefixes.""" | |
| if not self.rename_files: | |
| return | |
| print("\n=== Renaming split files ===") | |
| for split_name, directory_path in self.output_dirs.items(): | |
| prefix = self.prefixes.get(split_name) | |
| if not prefix: | |
| continue | |
| self._rename_files_in_directory(directory_path, prefix, split_name) | |
| self._verify_renaming() | |
| def _rename_files_in_directory(self, directory_path: Path, prefix: str, split_name: str) -> None: | |
| if not directory_path.exists(): | |
| print(f"[WARN] Directory does not exist: {directory_path}") | |
| return | |
| total_files = renamed_files = 0 | |
| for scene_dir in directory_path.iterdir(): | |
| if scene_dir.is_dir(): | |
| for file_path in scene_dir.iterdir(): | |
| if file_path.is_file(): | |
| total_files += 1 | |
| if not file_path.name.startswith(prefix): | |
| new_path = scene_dir / f"{prefix}{file_path.name}" | |
| file_path.rename(new_path) | |
| renamed_files += 1 | |
| print( | |
| f" {split_name:<20s}: {renamed_files}/{total_files} files renamed with prefix '{prefix}'" | |
| ) | |
| def _verify_renaming(self) -> None: | |
| print("\n=== Rename verification ===") | |
| for split_name, directory_path in self.output_dirs.items(): | |
| if not directory_path.exists(): | |
| print(f"{split_name:<20s}: directory missing") | |
| continue | |
| prefix = self.prefixes.get(split_name, "") | |
| total_files = prefixed_files = 0 | |
| for scene_dir in directory_path.iterdir(): | |
| if scene_dir.is_dir(): | |
| for file_path in scene_dir.iterdir(): | |
| if file_path.is_file(): | |
| total_files += 1 | |
| if file_path.name.startswith(prefix): | |
| prefixed_files += 1 | |
| if total_files > 0: | |
| ratio = prefixed_files / total_files * 100 | |
| print(f"{split_name:<20s}: {prefixed_files}/{total_files} ({ratio:.1f}% prefixed)") | |
| else: | |
| print(f"{split_name:<20s}: no files") | |
| # ---------- Pipeline ---------- | |
| def run(self) -> None: | |
| """Run the full pipeline: load mappings, extract splits, rename.""" | |
| print("=" * 80) | |
| print(" Benchmark Dataset Split & Rename") | |
| print("=" * 80) | |
| self.load_split_mappings() | |
| self.create_output_directories() | |
| self.extract_scene_unseen() | |
| self.extract_trajectory_unseen() | |
| self.extract_instruction_unseen() | |
| self.extract_train() | |
| self.extract_val() | |
| self.rename_split_files() | |
| print("\nDone. Output directories:") | |
| for split_name, path in self.output_dirs.items(): | |
| scene_count = len([d for d in path.iterdir() if d.is_dir()]) if path.exists() else 0 | |
| print(f" {split_name:<20s}: {path} ({scene_count} scenes)") | |
| # ==================== CLI ==================== | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description="Extract benchmark splits and rename files.") | |
| parser.add_argument( | |
| "--original-data-dir", | |
| type=Path, | |
| default=DEFAULT_ORIGINAL_DATA_DIR, | |
| help="Directory containing original merged trajectory scenes", | |
| ) | |
| parser.add_argument( | |
| "--mapping-dir", | |
| type=Path, | |
| default=DEFAULT_MAPPING_DIR, | |
| help="Directory containing split mapping JSON files", | |
| ) | |
| parser.add_argument( | |
| "--train-dir", | |
| type=Path, | |
| default=DEFAULT_TRAIN_DIR, | |
| help="Output directory for the training split", | |
| ) | |
| parser.add_argument( | |
| "--val-dir", | |
| type=Path, | |
| default=DEFAULT_VAL_DIR, | |
| help="Output directory for the validation split", | |
| ) | |
| parser.add_argument( | |
| "--scene-unseen-dir", | |
| type=Path, | |
| default=DEFAULT_SCENE_UNSEEN_DIR, | |
| help="Output directory for the scene-unseen split", | |
| ) | |
| parser.add_argument( | |
| "--trajectory-unseen-dir", | |
| type=Path, | |
| default=DEFAULT_TRAJECTORY_UNSEEN_DIR, | |
| help="Output directory for the trajectory-unseen split", | |
| ) | |
| parser.add_argument( | |
| "--instruction-unseen-dir", | |
| type=Path, | |
| default=DEFAULT_INSTRUCTION_UNSEEN_DIR, | |
| help="Output directory for the instruction-unseen split", | |
| ) | |
| parser.add_argument( | |
| "--no-rename", | |
| action="store_true", | |
| help="Disable renaming of output files with split-specific prefixes", | |
| ) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| # Validate directories | |
| if not args.original_data_dir.exists(): | |
| print(f"[ERROR] Original data dir does not exist: {args.original_data_dir}") | |
| return | |
| if not args.mapping_dir.exists(): | |
| print(f"[ERROR] Mapping dir does not exist: {args.mapping_dir}") | |
| return | |
| output_dirs = { | |
| "train": args.train_dir, | |
| "val": args.val_dir, | |
| "scene_unseen": args.scene_unseen_dir, | |
| "trajectory_unseen": args.trajectory_unseen_dir, | |
| "instruction_unseen": args.instruction_unseen_dir, | |
| } | |
| builder = BenchmarkDatasetBuilder( | |
| original_data_dir=args.original_data_dir, | |
| mapping_dir=args.mapping_dir, | |
| output_dirs=output_dirs, | |
| prefixes=DEFAULT_PREFIXES, | |
| rename_files=not args.no_rename, | |
| ) | |
| builder.run() | |
| if __name__ == "__main__": | |
| main() | |