File size: 10,124 Bytes
d821aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/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 <dataset_path>")
        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])