File size: 52,507 Bytes
f83b064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
"""
Convert mcap files to lerobot format within a single file.
Supports Human-in-the-Loop (HIL) data filtering by action_type.

Example Usage:
    Notice:
        if use multiprocessing, please make sure the repo id is a temperary repo (e.g., we_d900_temp/accessory-return) 
        to avoid multiple processes pushing to the same repo at the same time. After the conversion is done, 
        you can rename the repo to the final name (e.g., we_d900/accessory-return).
    
    1. Normal teleoperation data processing 
        -> Without HIL filtering (keep all actions):
        
    python posttraining/scripts/dataset/convert_mcap_to_lerobot.py \
        --task 'accessory-return' \
        --num_process 40 \
        --robot_type arx \
        --repo_id we_d900_temp/accessory-return \
        --final_dataset_repo_root we_d900 \
        --tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
        --dataset_root /nas/volume1/scratch/datasets \

    2. Generate human-in-the-loop (HIL) data with filtering:
    python posttraining/scripts/dataset/convert_mcap_to_lerobot.py \
        --task 'accessory-return' \
        --num_process 40 \
        --robot_type arx \
        --repo_id we_d900_temp/accessory-return \
        --final_dataset_repo_root we_d900 \
        --tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
        --dataset_root /nas/volume1/scratch/datasets \
        --hil_filter

    3. With custom action types, e.g. only keep "teleop":
    python posttraining/scripts/dataset/convert_mcap_to_lerobot.py 
        --task 'accessory-return' \
        --num_process 40 \
        --robot_type arx \
        --repo_id we_d900_temp/accessory-return \
        --final_dataset_repo_root we_d900 \
        --tasks_json_path /home/shiduozhang/projects/tasks_hil.json \
        --dataset_root /nas/volume1/scratch/datasets \
        --action_types ["teleop"]


"""

from pathlib import Path
import gc
import os
import cv2
import tqdm
import json
import subprocess
import numpy as np
import logging
import shutil
import pandas as pd
from typing import Literal
from mcap.reader import make_reader
from lerobot.utils.constants import HF_LEROBOT_HOME
from lerobot.datasets.lerobot_dataset import LeRobotDataset
from typing import Iterable
from foxglove_schemas_protobuf.CompressedImage_pb2 import CompressedImage
from foxglove_schemas_protobuf.FrameTransforms_pb2 import FrameTransforms
from packaging import version
from concurrent.futures import ProcessPoolExecutor
from lerobot.datasets.utils import load_tasks
import pyarrow as pa
import pyarrow.parquet as pq
import dataclasses
import argparse

logger = logging.getLogger()

DATASET_ROOT = "/nas/volume1/scratch/datasets"
TASKS_JSON_PATH = "/home/shiduozhang/projects/tasks_hil.json"

# Default commander_state values to keep for HIL data
DEFAULT_HIL_ACTION_TYPES = {"INFERENCE", "TELEOP"}


def load_task_folders(task_name: str, tasks_json_path: str = TASKS_JSON_PATH) -> list[str]:
    """
    Load folder names for a specific task from tasks_merged.json.

    Args:
        task_name: The task name to look up
        tasks_json_path: Path to the tasks_merged.json file

    Returns:
        List of folder names for the task
    """
    import json
    with open(tasks_json_path, "r", encoding="utf-8") as f:
        tasks = json.load(f)

    if task_name not in tasks:
        available_tasks = list(tasks.keys())
        raise ValueError(f"Task '{task_name}' not found. Available tasks: {available_tasks}")

    return tasks[task_name]


def get_mcap_info_from_folder(folder_path: str) -> tuple[str | None, str]:
    """
    Get mcap file path and version from a folder.

    Args:
        folder_path: Path to the folder containing mcap and metadata.json

    Returns:
        Tuple of (mcap_file_path, mcap_version)
    """
    import json
    from glob import glob

    # Find mcap file (recursively)
    mcap_files = glob(os.path.join(folder_path, "**/*.mcap"), recursive=True)
    if not mcap_files:
        # Fallback to non-recursive search
        mcap_files = glob(os.path.join(folder_path, "*.mcap"))
    if not mcap_files:
        logger.warning(f"No mcap file found in {folder_path}")
        return None, "1.12.7"  # Default version

    mcap_path = mcap_files[0]

    # Read metadata.json for version
    metadata_path = os.path.join(folder_path, "metadata.json")
    mcap_version = "1.12.7"  # Default version
    if os.path.exists(metadata_path):
        try:
            with open(metadata_path, "r", encoding="utf-8") as f:
                metadata = json.load(f)
            mcap_version = metadata.get("version", metadata.get("mcap_version", "1.12.7"))
        except Exception as e:
            logger.warning(f"Error reading metadata from {metadata_path}: {e}")

    return mcap_path, mcap_version

############################################# Protobuf Types #############################################
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# NO CHECKED-IN PROTOBUF GENCODE
# source: robotics.proto
# Protobuf Python Version: 5.29.4
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder

# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()


from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2


DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(
    b'\n\x0erobotics.proto\x12\x0cworld_engine\x1a\x1fgoogle/protobuf/timestamp.proto"\xc0\x01\n\x10RobotObservation\x12\x17\n\x0fjoint_positions\x18\x01 \x03(\x01\x12\x0e\n\x06\x65\x65_pos\x18\x02 \x03(\x01\x12-\n\ttimestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x18\n\x10joint_velocities\x18\x04 \x03(\x01\x12\x10\n\x08\x63urrents\x18\x05 \x03(\x01\x12\x0f\n\x07torques\x18\x06 \x03(\x01\x12\x17\n\x0f\x63ommander_state\x18\x07 \x01(\t"L\n\x0bRobotAction\x12\x0e\n\x06\x61\x63tion\x18\x01 \x03(\x01\x12-\n\ttimestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"\xbe\x02\n\x0eSyncTimestamps\x12:\n\x16robot_action_timestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12?\n\x1brobot_observation_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x38\n\x14top_camera_timestamp\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x39\n\x15left_camera_timestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12:\n\x16right_camera_timestamp\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestampb\x06proto3'
)

_globals = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "robotics_pb2", _globals)
if not _descriptor._USE_C_DESCRIPTORS:
    DESCRIPTOR._loaded_options = None
    _globals["_ROBOTOBSERVATION"]._serialized_start = 66
    _globals["_ROBOTOBSERVATION"]._serialized_end = 258
    _globals["_ROBOTACTION"]._serialized_start = 260
    _globals["_ROBOTACTION"]._serialized_end = 336
    _globals["_SYNCTIMESTAMPS"]._serialized_start = 339
    _globals["_SYNCTIMESTAMPS"]._serialized_end = 657
# @@protoc_insertion_point(module_scope)


############################################# Dataset Config #############################################
@dataclasses.dataclass(frozen=True)
class DatasetConfig:
    use_videos: bool = True
    tolerance_s: float = 0.0001
    image_writer_processes: int = 10
    image_writer_threads: int = 5
    video_backend: str | None = None


DEFAULT_DATASET_CONFIG = DatasetConfig()


############################################# Robot Config #############################################
@dataclasses.dataclass(frozen=True)
class DualArmConfig:
    robot_type: str = "piper"
    left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])
    right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])
    arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [])  # Exclude gripper
    motors: list[str] = dataclasses.field(default_factory=lambda: [])
    camera_keys: list[str] = dataclasses.field(default_factory=lambda: [])
    cam_key_maps: dict[str, str] = dataclasses.field(default_factory=lambda: {})


@dataclasses.dataclass(frozen=True)
class DualPiperConfig(DualArmConfig):
    robot_type: str = "piper"
    left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 6])
    right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [7, 8, 9, 10, 11, 12, 13])
    arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12])  # Exclude gripper
    motors: list[str] = dataclasses.field(
        default_factory=lambda: [
            "left_waist",
            "left_shoulder",
            "left_elbow",
            "left_forearm_roll",
            "left_wrist_angle",
            "left_wrist_rotate",
            "left_gripper",
            "right_waist",
            "right_shoulder",
            "right_elbow",
            "right_forearm_roll",
            "right_wrist_angle",
            "right_wrist_rotate",
            "right_gripper",
        ]
    )
    camera_keys: list[str] = dataclasses.field(
        default_factory=lambda: [
            "left_camera",
            "right_camera",
            "top_camera",
        ]
    )
    cam_key_maps: dict[str, str] = dataclasses.field(
        default_factory=lambda: {
            "left_camera": "cam_left_wrist",
            "right_camera": "cam_right_wrist",
            "top_camera": "cam_high",
        }
    )


@dataclasses.dataclass(frozen=True)
class DualArxConfig(DualArmConfig):
    robot_type: str = "arx"
    left_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 6])
    right_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [7, 8, 9, 10, 11, 12, 13])
    arm_joint_idx: list[int] = dataclasses.field(default_factory=lambda: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12])  # Exclude gripper
    motors: list[str] = dataclasses.field(
        default_factory=lambda: [
            "left_waist",
            "left_shoulder",
            "left_elbow",
            "left_forearm_roll",
            "left_wrist_angle",
            "left_wrist_rotate",
            "left_gripper",
            "right_waist",
            "right_shoulder",
            "right_elbow",
            "right_forearm_roll",
            "right_wrist_angle",
            "right_wrist_rotate",
            "right_gripper",
        ]
    )
    camera_keys: list[str] = dataclasses.field(
        default_factory=lambda: [
            "left_camera",
            "right_camera",
            "top_camera",
        ]
    )
    cam_key_maps: dict[str, str] = dataclasses.field(
        default_factory=lambda: {
            "left_camera": "cam_left_wrist",
            "right_camera": "cam_right_wrist",
            "top_camera": "cam_high",
        }
    )


############################################# LeRobot Utils #############################################
def create_empty_dataset(
    repo_id: str,
    robot_type: str,
    mode: Literal["video", "image"] = "video",
    *,
    dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
    fps=60,
    image_size: tuple[int, int] = (320, 180),
    cam_key_maps: dict[str, str] = {},
    motors: list[str] = [],
    generate_vel: bool = False,
    record_mcap_path: bool = False,
) -> LeRobotDataset:
    """Create an empty LeRobot dataset."""
    cameras = list(cam_key_maps.values())

    features = {
        "observation.state": {
            "dtype": "float32",
            "shape": (len(motors),),
            "names": motors,
        },
        "observation.commander_state": {
            "dtype": "string",
            "shape": (1,),
            "names": ["commander_states"],
        },
        "action": {
            "dtype": "float32",
            "shape": (len(motors),),
            "names": motors,
        },
    }
    if record_mcap_path:
        features["mcap_path"] = {
            "dtype": "string",
            "shape": (1,),
            "names": ["mcap_path"],
        }
    if generate_vel:
        features["observation.velocity"] = {
            "dtype": "float32",
            "shape": (len(motors),),
            "names": motors,
        }
        features["action_vel"] = {
            "dtype": "float32",
            "shape": (len(motors),),
            "names": motors,
        }

    for cam in cameras:
        features[f"observation.images.{cam}"] = {
            "dtype": mode,
            "shape": (image_size[1], image_size[0], 3),
            "names": [
                "height",
                "width",
                "channels",
            ],
        }
    features["subtask"] = {
        "dtype": "string",
        "shape": (1,),
        "names": ["subtask"],
    }

    if Path(HF_LEROBOT_HOME / repo_id).exists():
        shutil.rmtree(HF_LEROBOT_HOME / repo_id)

    dataset = LeRobotDataset.create(
        repo_id=repo_id,
        fps=fps,
        robot_type=robot_type,
        features=features,
        use_videos=dataset_config.use_videos,
        tolerance_s=dataset_config.tolerance_s,
        image_writer_processes=dataset_config.image_writer_processes,
        image_writer_threads=dataset_config.image_writer_threads,
        video_backend=dataset_config.video_backend,
    )
    dataset.meta.update_chunk_settings(data_files_size_in_mb=0, video_files_size_in_mb=0)
    return dataset

def check_mcap_validity(data_dict_chunk: dict, action_threshold: float = 10.0) -> bool:
    actions_raw = data_dict_chunk["actions"]
    if np.max(np.abs(actions_raw)) > action_threshold:
        mcap_info = data_dict_chunk.get("mcap_path", "unknown")
        logger.warning(
            f"Skipping mcap file {mcap_info}: max abs actions value "
            f"{np.max(np.abs(actions_raw)):.4f} exceeds {action_threshold}"
        )
        return True
    return False

def populate_dataset_from_raw_loader(
    dataset: LeRobotDataset,
    raw_episode_loader: Iterable[dict],
    cam_keys: list[str],
    cam_key_maps: dict[str, str],
    task: str | list[str] = "Do something",
    generate_vel: bool = False,
    chunk_size: int = 1000,
    record_mcap_path: bool = False,
):
    """Populate a LeRobot dataset from a raw data loader."""
    pbar = tqdm.tqdm(total=len(raw_episode_loader))
    skip_current_episode = False
    is_first_chunk_of_episode = True  # Track first chunk to avoid orphaned frames
    for is_new_episode, data_dict_chunk in raw_episode_loader:
        if is_new_episode:
            # Update the episode index
            if not skip_current_episode:
                dataset.save_episode()
            pbar.update(1)
            skip_current_episode = False  # Reset for new episode
            is_first_chunk_of_episode = True  # New episode starts

        # Only check validity on the FIRST chunk of each episode.
        # Checking on later chunks is unsafe: frames from earlier chunks are already
        # in the LeRobot buffer and cannot be undone, so setting skip_current_episode=True
        # mid-episode leaves orphan frames that corrupt the next episode.
        if is_first_chunk_of_episode:
            skip_current_episode = check_mcap_validity(data_dict_chunk)
            is_first_chunk_of_episode = False

        if skip_current_episode:
            continue

        num_frames_chunk = len(data_dict_chunk["joint_poses"])
        camera_images = {key: data_dict_chunk["camera_images"][key] for key in cam_keys}

        valid_frames = list(range(num_frames_chunk))
        joint_poses = data_dict_chunk["joint_poses"][valid_frames]
        ee_poses = data_dict_chunk["ee_poses"][valid_frames]
        if "commander_states" in data_dict_chunk:
            commander_states = [data_dict_chunk["commander_states"][i].lower() for i in valid_frames]
        else:
            commander_states = ["teleop"] * len(valid_frames)
        actions = data_dict_chunk["actions"][valid_frames]
        if generate_vel:
            joint_vel = data_dict_chunk["joint_vel"][valid_frames]
            actions_vel = data_dict_chunk["actions_vel"][valid_frames]
        for cam_key in cam_keys:
            camera_images[cam_key] = data_dict_chunk["camera_images"][cam_key][valid_frames]
        num_frames_chunk = len(joint_poses)

        # Get mcap_path if recording
        mcap_path = data_dict_chunk.get("mcap_path", "") if record_mcap_path else None

        if "task" in data_dict_chunk:
            task_episode = data_dict_chunk["task"]
        elif task is None:
            task_episode = "Do something"
        else:
            task_episode = task

        for frame_idx in range(num_frames_chunk):
            # FIXME: Allow the episode to change task within the episode
            frame = {
                "task": task_episode[frame_idx] if isinstance(task_episode, list) else task_episode,
                "observation.state": joint_poses[frame_idx],
                "action": actions[frame_idx],
            }
            if generate_vel:
                frame["observation.velocity"] = joint_vel[frame_idx]
                frame["action_vel"] = actions_vel[frame_idx]
            frame["observation.commander_state"] = commander_states[frame_idx]
            if record_mcap_path and mcap_path:
                frame["mcap_path"] = mcap_path
            for cam_key in cam_keys:
                frame[f"observation.images.{cam_key_maps[cam_key]}"] = camera_images[cam_key][frame_idx]
            frame["subtask"] = "TODO" # TODO: add subtask annotation
            dataset.add_frame(frame)
    # Save the last episode
    if not skip_current_episode:
        dataset.save_episode()
    pbar.update(1)
    pbar.close()


############################################# Utils #############################################
def resize_image(img_str, resize=True, image_size: tuple[int, int] = (320, 180)):
    # Handle case where input is already bytes
    if isinstance(img_str, bytes):
        img_bytes = img_str
    else:
        # Original code for hex string
        img_bytes = bytes.fromhex(img_str)

    img_np = np.frombuffer(img_bytes, dtype=np.uint8)
    img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
    if resize:
        img = cv2.resize(img, (image_size[0], image_size[1]))
    # Convert rgb to bgr
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    return img


############################################# Load raw data from mcap #############################################


def read_mcap_msg(mcap_path, cam_keys: list[str]):
    """
    Read messages from an MCAP file.

    Args:
        mcap_path: Path to the MCAP file
    """
    # Verify file exists
    if not os.path.exists(mcap_path):
        raise FileNotFoundError(f"MCAP file not found at {mcap_path}")

    # Dictionary to store message type handlers
    handlers = {
        "robot_observation": RobotObservation,
        "robot_action": RobotAction,
        "sync_timestamps": SyncTimestamps,
        "/tf": FrameTransforms,
    }
    for cam_key in cam_keys:
        handlers[cam_key] = CompressedImage

    # Statistics to track message counts
    message_counts = {topic: 0 for topic in handlers.keys()}
    messages = []

    # Open and read the MCAP file
    with open(mcap_path, "rb") as f:
        reader = make_reader(f)

        # Iterate through all messages
        for schema, channel, message in reader.iter_messages():
            # Get the appropriate message handler
            if channel.topic in handlers:
                message_type = handlers[channel.topic]
                parsed_msg = message_type()
                parsed_msg.ParseFromString(message.data)

                # Update message count
                message_counts[channel.topic] += 1
                # Read out data based topic
                if channel.topic == "robot_observation":
                    data = {
                        "joint_positions": parsed_msg.joint_positions,
                        "joint_velocities": parsed_msg.joint_velocities,
                        "ee_pose": parsed_msg.ee_pos,
                        "currents": parsed_msg.currents,
                        "torques": parsed_msg.torques,
                        "commander_state": parsed_msg.commander_state,
                    }
                    timestamp = parsed_msg.timestamp.ToNanoseconds()
                elif channel.topic == "robot_action":
                    data = parsed_msg.action
                    timestamp = parsed_msg.timestamp.ToNanoseconds()
                elif channel.topic == "sync_timestamps":
                    data = {
                        f"{k}_timestamp": parsed_msg.__getattribute__(f"{k}_timestamp").ToNanoseconds()
                        for k in handlers.keys()
                        if hasattr(parsed_msg, f"{k}_timestamp")
                    }
                    timestamp = min(data.values())
                elif channel.topic in cam_keys:
                    data = parsed_msg.data
                    timestamp = parsed_msg.timestamp.ToNanoseconds()
                elif channel.topic == "tf":
                    data = parsed_msg.data
                    timestamp = parsed_msg.timestamp.ToNanoseconds()
                messages.append(
                    {
                        "timestamp": timestamp,
                        "data": data,
                        "channel": channel.topic,
                        "schema": schema,
                    }
                )
    return messages


def read_mcap_file(file_path, cam_keys: list[str]):
    """
    Read messages from an MCAP file
    """
    messages = read_mcap_msg(file_path, cam_keys=cam_keys)

    robot_joint_pos = {}
    robot_action = {}
    robo_ee_pose = {}
    commander_state = {}
    camera_images = {key: {} for key in cam_keys}
    sync_timestamps = {}

    for message in messages:
        data = message["data"]

        if message["channel"] == "robot_observation":
            robot_joint_pos[message["timestamp"]] = data["joint_positions"]
            commander_state[message["timestamp"]] = data["commander_state"]
            robo_ee_pose[message["timestamp"]] = data["ee_pose"]
        elif message["channel"] == "robot_action":
            robot_action[message["timestamp"]] = data
        elif message["channel"] in cam_keys:
            camera_images[message["channel"]][message["timestamp"]] = data
        elif message["channel"] == "sync_timestamps":
            sync_timestamps[message["timestamp"]] = data

    return {
        "robot_joint_pos": robot_joint_pos,
        "robot_action": robot_action,
        "robo_ee_pose": robo_ee_pose,
        "commander_state": commander_state,
        "camera_images": camera_images,
        "sync_timestamps": sync_timestamps,
    }


def load_timed_data_from_mcap(
    mcap_file: str,
    cam_keys,
    fps=60,
    start_frame=0,
    max_frame=None,
    resize=True,
    image_size: tuple[int, int] = (320, 180),
    mcap_version: str = "0.0.0",
    generate_vel: bool = False,
    chunk_size: int = 1000,  # Process data in chunks to reduce memory pressure
    robot_type: str = "piper",
    filter_action_types: set[str] | None = None,  # HIL: action types to keep
):
    """Load the timed data from mcap with a given fps.

    Args:
        mcap_file: Path to the MCAP file
        cam_keys: List of camera keys
        fps: Frames per second
        start_frame: Starting frame index
        max_frame: Maximum number of frames to process
        resize: Whether to resize images
        image_size: Target image size (width, height)
        mcap_version: MCAP version string
        generate_vel: Whether to generate velocity data
        chunk_size: Process data in chunks
        robot_type: Type of robot
        filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
                            If None, all actions are kept.
    """
    # Read MCAP file
    mcap_dict = read_mcap_file(mcap_file, cam_keys=cam_keys)
    ds_sync_timestamps = mcap_dict["sync_timestamps"]

    # If there are no explicit sync_timestamps in the MCAP, build a fallback
    # nearest-neighbor synchronization using robot_observation timestamps as the
    # reference timeline and matching camera & action timestamps to the closest
    # available times. This keeps behavior robust when recordings don't emit
    # a dedicated sync message.
    if not ds_sync_timestamps:
        logger.info("No sync_timestamps found in MCAP; building fallback nearest-neighbor sync using camera as reference")
        from bisect import bisect_left

        def nearest(sorted_list, value):
            if not sorted_list:
                return None
            i = bisect_left(sorted_list, value)
            if i == 0:
                return sorted_list[0]
            if i == len(sorted_list):
                return sorted_list[-1]
            before = sorted_list[i - 1]
            after = sorted_list[i]
            if abs(after - value) < abs(value - before):
                return after
            else:
                return before

        # tolerance for matching (seconds -> nanoseconds).
        fallback_tol_s = max(DEFAULT_DATASET_CONFIG.tolerance_s, 1.0 / fps / 2.0)
        tol_ns = int(fallback_tol_s * 1e9)

        # prepare sorted timestamp lists
        obs_ts = sorted(mcap_dict["robot_joint_pos"].keys())
        action_ts = sorted(mcap_dict["robot_action"].keys())
        cam_ts_map = {k: sorted(mcap_dict["camera_images"][k].keys()) for k in cam_keys}

        # Use the first camera as the reference timeline
        reference_cam_key = cam_keys[0]
        reference_cam_ts = cam_ts_map.get(reference_cam_key, [])

        if not reference_cam_ts:
            logger.warning(f"Reference camera {reference_cam_key} has no timestamps")
            ds_sync_timestamps = {}
        else:
            ds_sync_timestamps = {}
            for cam_t in reference_cam_ts:
                sync = {}
                sync[f"{reference_cam_key}_timestamp"] = cam_t

                # nearest robot observation
                no = nearest(obs_ts, cam_t)
                if no is None or abs(no - cam_t) > tol_ns:
                    continue
                sync["robot_observation_timestamp"] = no

                # nearest action
                na = nearest(action_ts, cam_t)
                if na is None or abs(na - cam_t) > tol_ns:
                    continue
                sync["robot_action_timestamp"] = na

                # nearest timestamps for other cameras
                skip = False
                for cam_key in cam_keys:
                    if cam_key == reference_cam_key:
                        continue  # already added
                    nc = nearest(cam_ts_map.get(cam_key, []), cam_t)
                    if nc is None or abs(nc - cam_t) > tol_ns:
                        # If camera is missing or too far from reference camera, skip this frame
                        skip = True
                        break
                    sync[f"{cam_key}_timestamp"] = nc

                if skip:
                    continue

                # use reference camera timestamp as the dict key for ordering
                ds_sync_timestamps[cam_t] = sync
    # Pre-allocate arrays for the current chunk
    chunk_joint_poses = []
    chunk_ee_poses = []
    chunk_commander_states = []
    chunk_actions = []
    chunk_camera_images = {key: [] for key in cam_keys}

    episode_length = 0
    has_zero_ts = False
    has_missing_ts = False
    filtered_count = 0  # Count of frames filtered by action_type

    # Process timestamps in sorted order
    sorted_timestamps = sorted(ds_sync_timestamps.keys())
    total_frames = len(sorted_timestamps)

    for idx, key in enumerate(sorted_timestamps):
        if idx < start_frame:
            continue
        if max_frame is not None and idx >= (start_frame + max_frame):
            break

        sync_ts = ds_sync_timestamps[key]

        # Skip if any camera timestamp is None or 0
        is_zero_ts = False
        for cam_key in cam_keys:
            if sync_ts[f"{cam_key}_timestamp"] is None or sync_ts[f"{cam_key}_timestamp"] == 0:
                is_zero_ts = True
                break
        if is_zero_ts:
            has_zero_ts = True
            continue

        # Check existence of sync_ts in all camera_images
        is_missing_ts = False
        for cam_key in cam_keys:
            if sync_ts[f"{cam_key}_timestamp"] not in mcap_dict["camera_images"][cam_key]:
                logger.warning(f"Sync timestamp {sync_ts[f'{cam_key}_timestamp']} not found in {cam_key} camera images, mcap file: {mcap_file}")
                is_missing_ts = True
                break
        if is_missing_ts:
            has_missing_ts = True
            continue

        # HIL Filtering: Check commander_state and skip if not in filter set
        if filter_action_types is not None:
            obs_ts = sync_ts["robot_observation_timestamp"]
            cmd_state = mcap_dict["commander_state"].get(obs_ts, "")
            if cmd_state not in filter_action_types:
                filtered_count += 1
                continue

        episode_length += 1

        # Process current frame
        joint_pos = np.array(mcap_dict["robot_joint_pos"][sync_ts["robot_observation_timestamp"]]).reshape(1, -1)
        ee_pos = np.array(mcap_dict["robo_ee_pose"][sync_ts["robot_observation_timestamp"]]).reshape(1, -1)
        commander_state = mcap_dict["commander_state"][sync_ts["robot_observation_timestamp"]]
        if filter_action_types is not None:
            commander_state = "ap_" + commander_state.lower()  # Prefix with "ap_" to indicate it's autopilot state (e.g., "ap_inference", "ap_teleop")
        action = np.array(mcap_dict["robot_action"][sync_ts["robot_action_timestamp"]]).reshape(1, -1)

        # Append to current chunk
        chunk_joint_poses.append(joint_pos)
        chunk_ee_poses.append(ee_pos)
        chunk_commander_states.append(commander_state)
        chunk_actions.append(action)

        # Process images
        for cam_key in cam_keys:
            img_data = mcap_dict["camera_images"][cam_key][sync_ts[f"{cam_key}_timestamp"]]
            img = resize_image(img_data, resize=resize, image_size=image_size)
            chunk_camera_images[cam_key].append(img)

        # Process chunk if it reaches the specified size or we're at the end
        if len(chunk_joint_poses) >= chunk_size or idx == total_frames - 1:
            # Skip if no data in chunk (all frames were filtered)
            if len(chunk_joint_poses) == 0:
                continue

            # Convert lists to numpy arrays
            joint_poses_chunk = np.concatenate(chunk_joint_poses, axis=0).astype(np.float32)
            ee_poses_chunk = np.concatenate(chunk_ee_poses, axis=0).astype(np.float32)
            actions_chunk = np.concatenate(chunk_actions, axis=0).astype(np.float32)

            # Version-aware action normalization
            if version.parse(mcap_version) <= version.parse("1.10.1"):
                actions_chunk[:, 6] = actions_chunk[:, 6] / 0.08
                actions_chunk[:, 13] = actions_chunk[:, 13] / 0.08
            # if robot_type == "arx" and version.parse(mcap_version) <= version.parse("1.12.7"):
            #     actions_chunk[:, 6] = actions_chunk[:, 6] * 0.08
            #     actions_chunk[:, 13] = actions_chunk[:, 13] * 0.08

            # Process camera images
            camera_images_chunk = {}
            for cam_key in cam_keys:
                camera_images_chunk[cam_key] = np.stack(chunk_camera_images[cam_key], axis=0).astype(np.uint8)

            # Generate velocities if requested
            if generate_vel:
                joint_vel_chunk = np.diff(joint_poses_chunk, axis=0)
                joint_vel_chunk = np.concatenate([joint_vel_chunk, np.zeros((1, joint_vel_chunk.shape[1]))], axis=0).astype(np.float32)
                actions_vel_chunk = np.diff(actions_chunk, axis=0)
                actions_vel_chunk = np.concatenate([actions_vel_chunk, np.zeros((1, actions_vel_chunk.shape[1]))], axis=0).astype(np.float32)

            # Yield the current chunk
            chunk_data = {
                "joint_poses": joint_poses_chunk,
                "ee_poses": ee_poses_chunk,
                "commander_states": chunk_commander_states,
                "actions": actions_chunk,
                "camera_images": camera_images_chunk,
                "info": {
                    "has_zero_ts": has_zero_ts,
                    "has_missing_ts": has_missing_ts,
                    "filtered_count": filtered_count,  # Include filtered count in info
                },
            }

            if generate_vel:
                chunk_data["joint_vel"] = joint_vel_chunk
                chunk_data["actions_vel"] = actions_vel_chunk

            yield chunk_data

            # Clear chunk data
            chunk_joint_poses = []
            chunk_ee_poses = []
            chunk_commander_states = []
            chunk_actions = []
            chunk_camera_images = {key: [] for key in cam_keys}

            # Force garbage collection
            gc.collect()

    # Log filtering statistics
    if filter_action_types is not None and filtered_count > 0:
        logger.info(f"HIL filtering: {filtered_count} frames filtered out (kept action_types: {filter_action_types})")


############################################# Generate LeRobot Dataset #############################################
class McapDataLoader:
    """
    Load data from mcap files and convert to LeRobot format.
    McapDataLoader load mcap in chunks to reduce memory pressure.
    """

    def __init__(
        self,
        mcap_files: list[str],
        mcap_versions: list[str],
        cam_keys: list[str],
        image_size: tuple[int, int],
        generate_vel: bool = False,
        chunk_size: int = 1000,
        robot_type: str = "piper",
        record_mcap_path: bool = False,
        filter_action_types: set[str] | None = None,  # HIL: action types to keep
    ):
        self.mcap_files = mcap_files
        self.mcap_versions = mcap_versions
        self.cam_keys = cam_keys
        self.image_size = image_size
        self.generate_vel = generate_vel
        self.episode_idx = 0
        self.chunk_size = chunk_size
        self.robot_type = robot_type
        self.record_mcap_path = record_mcap_path
        self.filter_action_types = filter_action_types

    def __len__(self):
        return len(self.mcap_files)

    def __iter__(self):
        while self.episode_idx < len(self.mcap_files):
            mcap_file = self.mcap_files[self.episode_idx]
            mcap_version = self.mcap_versions[self.episode_idx]
            print(f"Processing {mcap_file} with version {mcap_version}")
            # Ensure the loop variable exists even if the loader yields nothing
            data_dict_chunk = None
            for _i, data_dict_chunk in enumerate(load_timed_data_from_mcap(
                mcap_file,
                cam_keys=self.cam_keys,
                image_size=self.image_size,
                mcap_version=mcap_version,
                generate_vel=self.generate_vel,
                chunk_size=self.chunk_size,
                robot_type=self.robot_type,
                filter_action_types=self.filter_action_types,  # Pass HIL filter
                )):
                # Add mcap_path to chunk data if recording
                if self.record_mcap_path:
                    data_dict_chunk["mcap_path"] = mcap_file
                yield (_i == 0) and (self.episode_idx != 0), data_dict_chunk

            # Clear memory (only delete if assigned)
            if data_dict_chunk is not None:
                del data_dict_chunk
            # Collect garbage
            gc.collect()
            # Increment episode index
            self.episode_idx += 1


def populate_dataset_from_mcap(
    task: str | list[str],
    dataset: LeRobotDataset,
    mcap_files: list[str],
    mcap_versions: list[str],
    episodes: list[int] | None = None,
    image_size: tuple[int, int] = (320, 180),
    cam_keys: list[str] = ["top_camera", "left_camera", "right_camera"],
    cam_key_maps: dict[str, str] = {
        "top_camera": "cam_high",
        "left_camera": "cam_left_wrist",
        "right_camera": "cam_right_wrist",
    },
    arm_joint_idx: list[int] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12],
    generate_vel: bool = False,
    chunk_size: int = 1000,
    robot_type: str = "piper",
    record_mcap_path: bool = False,
    filter_action_types: set[str] | None = None,  # HIL: action types to keep
) -> LeRobotDataset:
    """
    Populate the dataset with the raw data from the mcap files.
    Args:
        dataset: The dataset to populate.
        mcap_files: The list of mcap files to populate the dataset with.
        mcap_versions: The list of mcap versions corresponding to the mcap files.
        episodes: The list of episodes to populate the dataset with.
        image_size: The size of the images to resize to.
        generate_vel: Whether to generate velocity data.
        record_mcap_path: Whether to record mcap path in the dataset.
        filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
    """
    if episodes is None:
        episodes = range(len(mcap_files))

    mcap_data_loader = McapDataLoader(
        mcap_files=mcap_files,
        mcap_versions=mcap_versions,
        cam_keys=cam_keys,
        image_size=image_size,
        generate_vel=generate_vel,
        chunk_size=chunk_size,
        robot_type=robot_type,
        record_mcap_path=record_mcap_path,
        filter_action_types=filter_action_types,  # Pass HIL filter
    )
    populate_dataset_from_raw_loader(
        dataset=dataset,
        raw_episode_loader=mcap_data_loader,
        cam_keys=cam_keys,
        cam_key_maps=cam_key_maps,
        task=task,
        generate_vel=generate_vel,
        chunk_size=chunk_size,
        record_mcap_path=record_mcap_path,
    )


def convert_mcap_to_lerobot(
    repo_id: str,
    task: str,
    mcap_files: list[str],
    mcap_versions: list[str],
    robot_type: str,
    fps: int,
    episodes: list[int] | None = None,
    push_to_hub: bool = False,
    mode: str = "video",
    image_size: tuple[int, int] = (320, 180),
    robot_config: DualPiperConfig = DualPiperConfig(),
    dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
    generate_vel: bool = False,
    chunk_size: int = 1000,
    record_mcap_path: bool = False,
    filter_action_types: set[str] | None = None,  # HIL: action types to keep
    **kwargs
):
    if (HF_LEROBOT_HOME / repo_id).exists():
        shutil.rmtree(HF_LEROBOT_HOME / repo_id)

    dataset = create_empty_dataset(
        repo_id,
        robot_type=robot_type,
        mode=mode,
        dataset_config=dataset_config,
        fps=fps,
        image_size=image_size,
        cam_key_maps=robot_config.cam_key_maps,
        motors=robot_config.motors,
        generate_vel=generate_vel,
        record_mcap_path=record_mcap_path,
    )

    dataset = populate_dataset_from_mcap(
        task=task,
        dataset=dataset,
        mcap_files=mcap_files,
        mcap_versions=mcap_versions,
        episodes=episodes,
        image_size=image_size,
        cam_keys=robot_config.camera_keys,
        cam_key_maps=robot_config.cam_key_maps,
        arm_joint_idx=robot_config.arm_joint_idx,
        generate_vel=generate_vel,
        chunk_size=chunk_size,
        robot_type=robot_type,
        record_mcap_path=record_mcap_path,
        filter_action_types=filter_action_types,  # Pass HIL filter
    )
    if push_to_hub:
        dataset.push_to_hub()


def process_worker(
    process_id: int,
    process_episodes: list[int],
    repo_id: str,
    task: str,
    mcap_files: list[str],
    mcap_versions: list[str],
    robot_type: str,
    fps: int,
    mode: str,
    image_size: tuple[int, int],
    dataset_config: DatasetConfig,
    generate_vel: bool,
    chunk_size: int,
    record_mcap_path: bool,
    filter_action_types: set[str] | None = None,  # HIL: action types to keep
):
    temp_repo_id = f"{repo_id}_{process_id}"

    process_mcap_files = [mcap_files[i] for i in process_episodes]
    process_mcap_versions = [mcap_versions[i] for i in process_episodes]

    # Create and populate dataset for this process
    convert_mcap_to_lerobot(
        repo_id=temp_repo_id,
        task=task,
        mcap_files=process_mcap_files,
        mcap_versions=process_mcap_versions,
        robot_type=robot_type,
        fps=fps,
        episodes=process_episodes,
        push_to_hub=False,
        mode=mode,
        image_size=image_size,
        dataset_config=dataset_config,
        generate_vel=generate_vel,
        chunk_size=chunk_size,
        record_mcap_path=record_mcap_path,
        filter_action_types=filter_action_types,  # Pass HIL filter
    )
    return temp_repo_id

def convert_mcap_to_lerobot_multiple_process(
    repo_id: str,
    task: str,
    mcap_files: list[str],
    mcap_versions: list[str],
    num_processes: int = 4,
    robot_type: str = "piper",
    fps: int = 60,
    episodes: list[int] | None = None,
    mode: Literal["video", "image"] = "video",
    image_size: tuple[int, int] = (320, 180),
    robot_config=DualPiperConfig(),
    dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
    generate_vel: bool = False,
    chunk_size: int = 1000,
    push_to_hub: bool = False,
    record_mcap_path: bool = False,
    filter_action_types: set[str] | None = None,  # HIL: action types to keep
) -> list[str]:
    """
    Convert MCAP files to LeRobot format using multiple processes.
    Each process processes a subset of episodes and saves to a temporary repo.
    Returns a list of temporary repo_ids that need to be merged.

    Args:
        repo_id: Base repo_id for the dataset
        task: Task name
        mcap_files: List of MCAP file paths
        mcap_versions: List of MCAP versions
        num_processes: Number of processes to use
        fps: Frames per second
        episodes: List of episode indices to process
        mode: Dataset mode (video or image)
        image_size: Size of images
        dataset_config: Dataset configuration
        generate_vel: Whether to generate velocity data
        filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).

    Returns:
        List of temporary repo_ids that need to be merged
    """
    if episodes is None:
        episodes = list(range(len(mcap_files)))

    # Split episodes among processes
    episodes_per_process = len(episodes) // num_processes
    remaining_episodes = len(episodes) % num_processes

    process_episodes = []
    start_idx = 0
    for i in range(num_processes):
        # Distribute remaining episodes among processes
        extra = 1 if i < remaining_episodes else 0
        end_idx = start_idx + episodes_per_process + extra
        process_episodes.append(episodes[start_idx:end_idx])
        start_idx = end_idx

    temp_repo_ids = []

    # Create and start processes using ProcessPoolExecutor
    with ProcessPoolExecutor(max_workers=num_processes) as executor:
        futures = []
        for i in range(num_processes):
            future = executor.submit(
                process_worker,
                i,
                process_episodes[i],
                repo_id,
                task,
                mcap_files,
                mcap_versions,
                robot_type,
                fps,
                mode,
                image_size,
                dataset_config,
                generate_vel,
                chunk_size,
                record_mcap_path,
                filter_action_types,  # Pass HIL filter
            )
            futures.append(future)

        # Wait for all processes to complete and collect results
        for future in futures:
            temp_repo_ids.append(future.result())

    return temp_repo_ids


############################################# Convert Task to LeRobot #############################################
def convert_task_to_lerobot(
    task_name: str,
    repo_id: str | None = None,
    robot_type: str = "piper",
    fps: int = 60,
    mode: str = "video",
    image_size: tuple[int, int] = (320, 180),
    robot_config: DualArmConfig | None = None,
    dataset_config: DatasetConfig = DEFAULT_DATASET_CONFIG,
    generate_vel: bool = False,
    chunk_size: int = 1000,
    num_processes: int = 1,
    push_to_hub: bool = False,
    tasks_json_path: str = TASKS_JSON_PATH,
    dataset_root: str = DATASET_ROOT,
    filter_action_types: set[str] | None = None,  # HIL: action types to keep,
    final_dataset_repo_root: str | Path = "we_d900",
):
    """
    Convert all mcap files for a specific task to a single LeRobot dataset.

    Args:
        task_name: The task name from tasks_merged.json
        repo_id: Repository ID for the dataset (default: task_name with spaces replaced by underscores)
        robot_type: Type of robot ("piper" or "arx")
        fps: Frames per second
        mode: Dataset mode ("video" or "image")
        image_size: Size of images to resize to
        robot_config: Robot configuration (auto-selected based on robot_type if None)
        dataset_config: Dataset configuration
        generate_vel: Whether to generate velocity data
        chunk_size: Process data in chunks
        num_processes: Number of processes for parallel processing
        push_to_hub: Whether to push to Hugging Face Hub
        tasks_json_path: Path to tasks_merged.json
        dataset_root: Root directory containing the dataset folders
        filter_action_types: Set of action types to keep (e.g., {"inference", "teleoperation"}).
                            Default is None (keep all). For HIL data, use DEFAULT_HIL_ACTION_TYPES.
    """
    # Load folders for the task
    folders = load_task_folders(task_name, tasks_json_path)
    print(f"Found {len(folders)} folders for task '{task_name}'")

    # Collect mcap files and versions
    mcap_files = []
    mcap_versions = []
    for folder in tqdm.tqdm(folders, desc="Collecting mcap files"):
        if os.path.exists(folder):
            folder_path = folder
        elif os.path.exists(os.path.join(dataset_root, folder)):
            folder_path = os.path.join(dataset_root, folder)
        elif os.path.exists(os.path.join(dataset_root, task_name, folder)):
            folder_path = os.path.join(dataset_root, task_name, folder)
        else:
            raise FileNotFoundError(f"Folder {folder} not found in dataset_root {dataset_root}")
        mcap_path, mcap_version = get_mcap_info_from_folder(folder_path)
        if mcap_path:
            mcap_files.append(mcap_path)
            mcap_versions.append(mcap_version)

    print(f"Found {len(mcap_files)} mcap files")

    if not mcap_files:
        print("No mcap files found, exiting")
        return

    # Set default repo_id
    if repo_id is None:
        repo_id = f"worldengine/{task_name.replace(' ', '_').lower()}"

    # Set default robot_config based on robot_type
    if robot_config is None:
        if robot_type == "arx":
            robot_config = DualArxConfig()
        else:
            robot_config = DualPiperConfig()

    # Log HIL filtering info
    if filter_action_types is not None:
        print(f"HIL filtering enabled: keeping action_types {filter_action_types}")

    # Convert to LeRobot dataset
    config = {
        "mcap_files": mcap_files,
        "mcap_versions": mcap_versions,
        "robot_type": robot_type,
        "fps": fps,
        "mode": mode,
        "num_processes": num_processes,
        "image_size": image_size,
        "robot_config": robot_config,
        "dataset_config": dataset_config,
        "generate_vel": generate_vel,
        "chunk_size": chunk_size,
        "repo_id": repo_id,
        "task": task_name,
        "episodes": None,
        "push_to_hub": push_to_hub,
        "record_mcap_path": True,  # Always record mcap path
        "filter_action_types": filter_action_types,  # HIL filter
    }

    if num_processes > 1:
        temp_repo_ids = convert_mcap_to_lerobot_multiple_process(**config)
        if not isinstance(temp_repo_ids, list):
            temp_repo_ids = [temp_repo_ids]

        # Filter out empty temp datasets (workers that produced 0 episodes have no tasks.parquet)
        non_empty_repo_ids = []
        for tmp_id in temp_repo_ids:
            tasks_parquet = Path(HF_LEROBOT_HOME) / tmp_id / "meta" / "tasks.parquet"
            if tasks_parquet.exists():
                non_empty_repo_ids.append(tmp_id)
            else:
                print(f"  Skipping empty temp dataset (0 episodes): {tmp_id}")
        if not non_empty_repo_ids:
            print("All worker datasets are empty — no episodes to merge. Aborting.")
            return
        print(f"Merging {len(non_empty_repo_ids)}/{len(temp_repo_ids)} non-empty temporary datasets...")
        repo_ids_str = json.dumps(non_empty_repo_ids)

        cmd = [
            "python", "-m", "lerobot.scripts.lerobot_edit_dataset",
            "--repo_id", f"{final_dataset_repo_root}/{task_name}",
            "--operation.type", "merge",
            "--operation.repo_ids", repo_ids_str,
            "--data_files_size_in_mb", "0",
            "--video_files_size_in_mb", "0"
        ]

        try:
            result = subprocess.run(
                cmd,
                check=True,
                capture_output=True,
                text=True
            )
            print("Command executed successfully!")
            print("STDOUT:", result.stdout)
            return result
        except subprocess.CalledProcessError as e:
            print(f"Error executing command: {e}")
            print("STDERR:", e.stderr)
            raise
        finally:
            # Delete all temp datasets (including empty ones)
            for repo_id in temp_repo_ids:
                tmp_path = Path(HF_LEROBOT_HOME) / repo_id
                if tmp_path.exists():
                    shutil.rmtree(tmp_path)

    else:
        convert_mcap_to_lerobot(**config)

    print(f"Dataset saved to {HF_LEROBOT_HOME / repo_id}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Convert MCAP files to LeRobot format (with HIL support).")
    parser.add_argument("--task", type=str, default=None, required=True, help="Task name from tasks_merged.json to convert")
    parser.add_argument("--num_process", type=int, default=1, help="Number of processes to use")
    parser.add_argument("--robot_type", type=str, default="piper", help="Type of robot (e.g., 'arx', 'piper')")
    parser.add_argument("--repo_id", type=str, default=None, help="Repository ID for the dataset")
    parser.add_argument("--fps", type=int, default=60, help="Frames per second")
    parser.add_argument("--tasks_json_path", type=str, default=TASKS_JSON_PATH, help="The json path to store the raw data directories of each task")
    parser.add_argument("--dataset_root", type=str, default=DATASET_ROOT, help="the dataset root of the raw mcap data")
    parser.add_argument("--final_dataset_repo_root", type=str, default="we_d900", help="The final dataset repo root to save the merged dataset")
    parser.add_argument(
        "--hil_filter",
        action="store_true",
        help="Enable HIL filtering: only keep 'inference' and 'teleoperation' action types"
    )
    parser.add_argument(
        "--action_types",
        type=str,
        nargs="+",
        default=None,
        help="Custom action types to keep (e.g., --action_types inference teleoperation). Overrides --hil_filter."
    )
    args = parser.parse_args()

    # Determine action types filter
    filter_action_types = None
    if args.action_types:
        filter_action_types = set(args.action_types)
    elif args.hil_filter:
        filter_action_types = DEFAULT_HIL_ACTION_TYPES

    convert_task_to_lerobot(
        task_name=args.task,
        repo_id=args.repo_id,
        robot_type=args.robot_type,
        fps=args.fps,
        num_processes=args.num_process,
        tasks_json_path=args.tasks_json_path,
        dataset_root=args.dataset_root,
        filter_action_types=filter_action_types,
        final_dataset_repo_root=args.final_dataset_repo_root
    )