#!/usr/bin/env python3 """ Script to update task_index in parquet files based on caption annotations. This script: 1. Reads all caption files from the captions/ directory 2. Extracts unique captions and assigns them task_index values 3. Updates the tasks.jsonl file with the new tasks 4. Updates all parquet files to set the correct task_index based on frame_index 5. Adds subtask_end_frame_index column to indicate the end frame of each subtask """ import json import os from pathlib import Path from collections import defaultdict try: import pyarrow.parquet as pq import pyarrow as pa except ImportError: print("Error: pyarrow is not installed. Please install it with: pip install pyarrow") print("Or activate the appropriate conda environment.") exit(1) def load_all_captions(captions_dir): """Load all caption files and return a mapping of episode_index -> segments.""" captions_dir = Path(captions_dir) episode_captions = {} # Get all caption files caption_files = sorted(captions_dir.glob("episode_*.json")) for caption_file in caption_files: # Extract episode index from filename episode_idx = int(caption_file.stem.replace("episode_", "")) # Load caption data with open(caption_file, 'r') as f: segments = json.load(f) episode_captions[episode_idx] = segments print(f"Loaded {len(segments)} segments from {caption_file.name}") return episode_captions def extract_unique_tasks(episode_captions): """Extract all unique captions and create task_index mapping.""" unique_captions = set() for episode_idx, segments in episode_captions.items(): for segment in segments: unique_captions.add(segment['caption']) # Sort captions for consistent ordering sorted_captions = sorted(unique_captions) # Create mapping: caption -> task_index caption_to_task_index = {caption: idx for idx, caption in enumerate(sorted_captions)} print(f"\nFound {len(sorted_captions)} unique tasks:") for caption, idx in caption_to_task_index.items(): print(f" {idx}: {caption}") return caption_to_task_index, sorted_captions def update_tasks_file(tasks_file, tasks): """Update the tasks.jsonl file with new tasks.""" tasks_file = Path(tasks_file) # Backup original file backup_file = tasks_file.with_suffix('.jsonl.backup') if tasks_file.exists(): import shutil shutil.copy(tasks_file, backup_file) print(f"\nBacked up original tasks.jsonl to {backup_file}") # Write new tasks with open(tasks_file, 'w') as f: for task_index, task in enumerate(tasks): task_entry = {"task_index": task_index, "task": task} f.write(json.dumps(task_entry) + '\n') print(f"Updated {tasks_file} with {len(tasks)} tasks") def get_task_index_for_frame(frame_index, segments, caption_to_task_index): """Given a frame_index, find which segment it belongs to and return the task_index.""" for segment in segments: if segment['start_frame'] <= frame_index < segment['end_frame']: return caption_to_task_index[segment['caption']] # If frame is beyond all segments, use the last segment's task if segments and frame_index >= segments[-1]['end_frame']: return caption_to_task_index[segments[-1]['caption']] # If frame is before all segments (shouldn't happen), use the first segment's task if segments and frame_index < segments[0]['start_frame']: return caption_to_task_index[segments[0]['caption']] return None def get_subtask_end_frame_for_frame(frame_index, segments): """Given a frame_index, find which segment it belongs to and return the end_frame of that subtask.""" for segment in segments: if segment['start_frame'] <= frame_index < segment['end_frame']: return segment['end_frame'] # If frame is beyond all segments, use the last segment's end_frame if segments and frame_index >= segments[-1]['end_frame']: return segments[-1]['end_frame'] # If frame is before all segments (shouldn't happen), use the first segment's end_frame if segments and frame_index < segments[0]['start_frame']: return segments[0]['end_frame'] return None def update_parquet_file(parquet_file, episode_idx, episode_captions, caption_to_task_index): """Update task_index and add subtask_end_frame_index in a single parquet file.""" # Read the parquet file table = pq.read_table(parquet_file) # Convert to dictionary for easier manipulation data = {col: table.column(col).to_pylist() for col in table.column_names} # Get the segments for this episode if episode_idx not in episode_captions: print(f"Warning: No caption data for episode {episode_idx}") return False segments = episode_captions[episode_idx] # Update task_index and compute subtask_end_frame_index for each row based on frame_index new_task_indices = [] new_subtask_end_frames = [] for frame_idx in data['frame_index']: # Get task_index task_idx = get_task_index_for_frame(frame_idx, segments, caption_to_task_index) if task_idx is None: print(f"Warning: Could not determine task_index for frame {frame_idx} in episode {episode_idx}") task_idx = 0 # Default to 0 if we can't determine new_task_indices.append(task_idx) # Get subtask_end_frame_index subtask_end_frame = get_subtask_end_frame_for_frame(frame_idx, segments) if subtask_end_frame is None: print(f"Warning: Could not determine subtask_end_frame_index for frame {frame_idx} in episode {episode_idx}") subtask_end_frame = frame_idx # Default to current frame if we can't determine new_subtask_end_frames.append(subtask_end_frame) # Replace task_index column data['task_index'] = new_task_indices # Add or update subtask_end_frame_index column data['subtask_end_frame_index'] = new_subtask_end_frames # Create new table with updated data (preserve column order, add new column at the end if it didn't exist) column_names = list(table.column_names) if 'subtask_end_frame_index' not in column_names: column_names.append('subtask_end_frame_index') arrays = [pa.array(data[col]) for col in column_names] new_table = pa.Table.from_arrays(arrays, names=column_names) # Write back to parquet file pq.write_table(new_table, parquet_file) return True def update_all_parquet_files(data_dir, episode_captions, caption_to_task_index): """Update task_index and add subtask_end_frame_index in all parquet files.""" data_dir = Path(data_dir) # Find all parquet files parquet_files = sorted(data_dir.rglob("episode_*.parquet")) print(f"\nUpdating {len(parquet_files)} parquet files...") for i, parquet_file in enumerate(parquet_files): # Extract episode index from filename episode_idx = int(parquet_file.stem.replace("episode_", "")) print(f"Processing {i+1}/{len(parquet_files)}: {parquet_file.name}...", end=' ') success = update_parquet_file(parquet_file, episode_idx, episode_captions, caption_to_task_index) if success: print("✓") else: print("✗") print("\nAll parquet files updated!") def update_info_file(info_file, num_tasks): """Update meta/info.json: ensure subtask_end_frame_index feature exists and total_tasks is correct.""" info_file = Path(info_file) if not info_file.exists(): print(f"Warning: {info_file} does not exist, skipping info.json update") return # Backup original file backup_file = info_file.with_suffix('.json.backup') import shutil shutil.copy(info_file, backup_file) print(f"Backed up original info.json to {backup_file}") with open(info_file, 'r') as f: info = json.load(f) # Update total_tasks info['total_tasks'] = num_tasks # Ensure features.subtask_end_frame_index is declared features = info.setdefault('features', {}) features['subtask_end_frame_index'] = { "dtype": "int64", "shape": [1], "names": None, } with open(info_file, 'w') as f: json.dump(info, f, indent=4) print(f"Updated {info_file} (total_tasks={num_tasks}, added subtask_end_frame_index feature)") def main(dataset_path): dataset_path = Path(dataset_path) captions_dir = dataset_path / "captions" tasks_file = dataset_path / "meta" / "tasks.jsonl" info_file = dataset_path / "meta" / "info.json" data_dir = dataset_path / "data" print("=" * 80) print(f"Task Index Update Script — {dataset_path}") print("=" * 80) # Step 1: Load all captions print("\nStep 1: Loading caption files...") episode_captions = load_all_captions(captions_dir) # Step 2: Extract unique tasks print("\nStep 2: Extracting unique tasks...") caption_to_task_index, unique_tasks = extract_unique_tasks(episode_captions) # Step 3: Update tasks.jsonl print("\nStep 3: Updating tasks.jsonl...") update_tasks_file(tasks_file, unique_tasks) # Step 4: Update all parquet files print("\nStep 4: Updating parquet files...") update_all_parquet_files(data_dir, episode_captions, caption_to_task_index) # Step 5: Update info.json print("\nStep 5: Updating info.json...") update_info_file(info_file, len(unique_tasks)) print("\n" + "=" * 80) print("Task index update completed successfully!") print("=" * 80) if __name__ == "__main__": import sys if len(sys.argv) != 2: print("Usage: python update_task_index.py ") print("Example: python update_task_index.py /nobackup/zy_zhang/data/coffee_make_vla/r1lite-20260422-lerobot_trimmed") sys.exit(1) main(sys.argv[1])