-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathagilex_openpi_dagger_collect.py
More file actions
2398 lines (2134 loc) · 92.9 KB
/
agilex_openpi_dagger_collect.py
File metadata and controls
2398 lines (2134 loc) · 92.9 KB
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
# -- coding: UTF-8
"""
#!/usr/bin/python3
"""
import argparse
import threading
import time
from collections import deque
import sys
import termios
import tty
import select
import cv2
import numpy as np
import rospy
import torch
from cv_bridge import CvBridge
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from openpi_client import image_tools, websocket_client_policy
from piper_msgs.msg import PosCmd
from sensor_msgs.msg import Image, JointState
from std_msgs.msg import Header, Bool, String, Int32
from pynput import keyboard
import os
import h5py
import dm_env
import collections
from collect_data import save_data, create_video_from_images, CollectOperator
CAMERA_NAMES = ["cam_high", "cam_right_wrist", "cam_left_wrist"]
observation_window = None
# smoothing globals
stream_buffer = None
# DAgger mode control
dagger_mode_active = False
dagger_mode_lock = threading.Lock()
save_data_requested = False
save_data_lock = threading.Lock()
collection_active = False
collection_lock = threading.Lock()
delete_data_requested = False
delete_data_lock = threading.Lock()
waiting_for_user_confirm = False
last_saved_episode_path = None
last_saved_episode_idx = None
last_saved_camera_names = None
lang_embeddings = "fold the cloth"
RIGHT_OFFSET = 0.003
timesteps, actions = [], []
process_thread = None
result_container = {}
class SimpleDAggerCollector:
"""DAgger collector using save_data from collect_data."""
def __init__(self, camera_names, dataset_dir="./home/agilex/data", task_name=None):
self.camera_names = camera_names
self.dataset_dir = dataset_dir
self.task_name = task_name
self.is_collecting = False
self.timesteps = []
self.actions = []
self.frame_count = 0
self.episode_idx = 0
self.full_dataset_dir = None
def _find_next_episode_idx(self):
"""Find next available episode index."""
if self.full_dataset_dir is None or not os.path.exists(self.full_dataset_dir):
self.episode_idx = 0
print(f"Next episode index: {self.episode_idx}")
return
existing_episodes = [
f for f in os.listdir(self.full_dataset_dir)
if f.startswith('episode_') and f.endswith('.hdf5')
]
if existing_episodes:
indices = [int(f.split('_')[1].split('.')[0]) for f in existing_episodes]
self.episode_idx = max(indices) + 1
else:
self.episode_idx = 0
print(f"Next episode index: {self.episode_idx}")
def start_collection(self):
"""Start collecting data."""
self.is_collecting = True
self.timesteps = []
self.actions = []
self.frame_count = 0
print("\n" + "="*70)
print("Data collection started.")
print("="*70)
print(f"Data will be saved to: {self.full_dataset_dir}")
print(f"Current episode: {self.episode_idx}")
print("Press 's' to save current data")
print("="*70 + "\n")
def stop_collection(self):
"""Stop collecting."""
self.is_collecting = False
if self.has_data():
print(f"\nWarning: {len(self.actions)} frames not saved. Press 's' to save or ignore.")
else:
print("\nDAgger collection stopped.")
def add_frame(self, observation, action):
"""Add one frame (same logic as collect_data)."""
if not self.is_collecting:
return
self.frame_count += 1
if self.frame_count == 1:
timestep = dm_env.TimeStep(
step_type=dm_env.StepType.FIRST,
reward=None,
discount=None,
observation=observation
)
self.timesteps.append(timestep)
else:
timestep = dm_env.TimeStep(
step_type=dm_env.StepType.MID,
reward=None,
discount=None,
observation=observation
)
self.timesteps.append(timestep)
self.actions.append(action)
if self.frame_count % 50 == 0:
print(f"Collected {self.frame_count} frames (actions: {len(self.actions)})")
def save_current_episode(self, export_video=True, video_fps=30,
video_codec='libx264', video_quality=23):
"""Save current episode and end collection."""
if len(self.actions) == 0:
print("\033[31mNo data to save.\033[0m")
return False
dataset_path = os.path.join(self.full_dataset_dir, f"episode_{self.episode_idx}")
print(f"\nSaving Episode {self.episode_idx}...")
print(f" Frames: {len(self.actions)}")
class Args:
def __init__(self, camera_names, export_video, video_fps, video_codec, video_quality):
self.camera_names = camera_names
self.export_video = export_video
self.video_fps = video_fps
self.video_codec = video_codec
self.video_quality = video_quality
self.use_robot_base = False
args = Args(self.camera_names, export_video, video_fps, video_codec, video_quality)
try:
save_data(args, self.timesteps, self.actions, dataset_path)
print(f"\n\033[32mEpisode {self.episode_idx} saved.\033[0m")
global waiting_for_user_confirm, last_saved_episode_path, last_saved_episode_idx, last_saved_camera_names
global delete_data_requested, delete_data_lock
with delete_data_lock:
waiting_for_user_confirm = True
last_saved_episode_path = dataset_path
last_saved_episode_idx = self.episode_idx
last_saved_camera_names = self.camera_names
print("\n" + "="*70)
print("Is this capture correct?")
print(" If not, press 'w' to delete this save.")
print(" If yes, press any other key to continue.")
print("="*70)
print("Waiting for input (10s timeout)...")
import time
max_wait_time = 10.0
wait_start = time.time()
should_delete = False
while time.time() - wait_start < max_wait_time:
with delete_data_lock:
if delete_data_requested:
should_delete = True
delete_data_requested = False
break
if not waiting_for_user_confirm:
break
time.sleep(0.1)
with delete_data_lock:
waiting_for_user_confirm = False
if should_delete:
hdf5_file = dataset_path + '.hdf5'
if os.path.exists(hdf5_file):
try:
os.remove(hdf5_file)
print(f"\n\033[33mDeleted: {hdf5_file}\033[0m")
except Exception as e:
print(f"\n\033[31mFailed to delete hdf5: {e}\033[0m")
video_dir = os.path.join(os.path.dirname(dataset_path), "video")
if os.path.exists(video_dir):
episode_idx_str = str(self.episode_idx)
for cam_name in self.camera_names:
cam_video_dir = os.path.join(video_dir, cam_name)
video_file = os.path.join(cam_video_dir, f"episode_{episode_idx_str}.mp4")
if os.path.exists(video_file):
try:
os.remove(video_file)
print(f"\n\033[33mDeleted video: {video_file}\033[0m")
except Exception as e:
print(f"\n\033[31mFailed to delete video: {e}\033[0m")
try:
for cam_name in self.camera_names:
cam_video_dir = os.path.join(video_dir, cam_name)
if os.path.exists(cam_video_dir) and not os.listdir(cam_video_dir):
os.rmdir(cam_video_dir)
except Exception:
pass
print("\n\033[32mData deleted.\033[0m")
self.timesteps = []
self.actions = []
self.frame_count = 0
self.is_collecting = False
else:
# 数据正确,继续正常流程
# 🆕 保存后停止采集,清空数据
self.episode_idx += 1
self.timesteps = []
self.actions = []
self.frame_count = 0
self.is_collecting = False
print("\n" + "="*70)
print("Save done. Collection ended.")
print("Press 'r' to exit DAgger and resume inference.")
print("Or press 'd' + Space to start a new collection.")
print("="*70 + "\n")
return True
except Exception as e:
print(f"\033[31mSave failed: {e}\033[0m")
import traceback
traceback.print_exc()
return False
def get_frame_count(self):
return self.frame_count
def has_data(self):
return len(self.actions) > 0
def keyboard_monitor_thread():
"""Monitor keyboard input for Ctrl+Q to activate DAgger mode and 'r' to resume"""
global dagger_mode_active, save_data_requested, collection_active
global delete_data_requested, waiting_for_user_confirm
# Save terminal settings
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
while not rospy.is_shutdown():
if select.select([sys.stdin], [], [], 0.1)[0]:
char = sys.stdin.read(1)
with delete_data_lock:
is_waiting_confirm = waiting_for_user_confirm
if is_waiting_confirm:
if char.lower() == 'w':
with delete_data_lock:
delete_data_requested = True
waiting_for_user_confirm = False
print("\nDelete requested. Deleting data...\n")
else:
with delete_data_lock:
waiting_for_user_confirm = False
print("\nData confirmed.\n")
continue
# Check for Ctrl+Q (ASCII 17)
if ord(char) == 17:
with dagger_mode_lock:
if not dagger_mode_active:
dagger_mode_active = True
print("\n" + "🎯"*35)
print("🎯 DAgger mode ACTIVATED! Pausing inference...")
print("🎯"*35 + "\n")
else:
print("\n⚠️ DAgger mode already active\n")
# 'd' key to activate DAgger mode
elif char.lower() == 'd':
with dagger_mode_lock:
if not dagger_mode_active:
dagger_mode_active = True
print("\n" + "🎯"*35)
print("🎯 DAgger mode ACTIVATED! Pausing inference...")
print("🎯"*35 + "\n")
else:
print("\n⚠️ DAgger mode already active\n")
# 'r' key to resume inference mode
elif char.lower() == 'r':
with dagger_mode_lock:
if dagger_mode_active:
dagger_mode_active = False
print("\n" + "▶️"*35)
print("▶️ Resuming inference mode...")
print("▶️"*35 + "\n")
else:
print("\n⚠️ Already in inference mode\n")
elif char.lower() == 's':
with dagger_mode_lock:
if dagger_mode_active:
with save_data_lock:
save_data_requested = True
print("\n" + "💾"*35)
print("💾 Save requested - will save at next opportunity...")
print("💾"*35 + "\n")
else:
print("\n⚠️ Not in DAgger mode, cannot save data\n")
elif char == ' ':
with dagger_mode_lock:
if dagger_mode_active:
with collection_lock:
if not collection_active:
print("\nStarting data collection...\n")
collection_active = True
print("\n" + "="*70)
print("Data collection started.")
print("="*70 + "\n")
else:
print("\nAlready collecting.\n")
else:
print("\nEnter DAgger mode first (press 'd').\n")
finally:
# Restore terminal settings
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
class StreamActionBuffer:
"""
Maintains action chunk queue and smoothed execution sequence.
integrate_new_chunk supports latency trim and linear overlap blending (same as smooth).
"""
def __init__(self, max_chunks=10, decay_alpha=0.25, state_dim=14, smooth_method="temporal"):
self.chunks = deque()
self.max_chunks = max_chunks
self.lock = threading.Lock()
self.decay_alpha = float(decay_alpha)
self.state_dim = state_dim
self.smooth_method = smooth_method
self.cur_chunk = deque()
self.k = 0
self.last_action = None
def integrate_new_chunk(self, actions_chunk: np.ndarray, max_k: int, min_m: int = 8):
with self.lock:
if actions_chunk is None or len(actions_chunk) == 0:
return
max_k = max(0, int(max_k))
min_m = max(1, int(min_m))
drop_n = min(self.k, max_k)
if drop_n >= len(actions_chunk):
return
new_chunk = [a.copy() for a in actions_chunk[drop_n:]]
if len(self.cur_chunk) == 0 and self.last_action is not None:
old_list = [np.asarray(self.last_action, dtype=float).copy() for _ in range(min_m)]
self.last_action = None
else:
old_list = list(self.cur_chunk)
if len(old_list) > 0 and len(old_list) < min_m:
tail = np.asarray(old_list[-1], dtype=float).copy()
old_list.extend([tail.copy() for _ in range(min_m - len(old_list))])
elif len(old_list) == 0:
self.cur_chunk = deque(new_chunk, maxlen=None)
self.k = 0
return
new_list = list(new_chunk)
overlap_len = min(len(old_list), len(new_list))
if overlap_len <= 0:
self.cur_chunk = deque(new_list, maxlen=None)
self.k = 0
return
if len(old_list) > len(new_list):
old_list = old_list[:len(new_list)]
overlap_len = len(new_list)
if overlap_len == 1:
w_old = np.array([1.0], dtype=float)
else:
w_old = np.linspace(1.0, 0.0, overlap_len, dtype=float)
w_new = 1.0 - w_old
smoothed = [
(w_old[i] * np.asarray(old_list[i], dtype=float) +
w_new[i] * np.asarray(new_list[i], dtype=float))
for i in range(overlap_len)
]
combined = smoothed + new_list[overlap_len:]
self.cur_chunk = deque([a.copy() for a in combined], maxlen=None)
self.k = 0
def pop_next_action(self) -> np.ndarray | None:
with self.lock:
if len(self.cur_chunk) == 0:
return None
if len(self.cur_chunk) == 1:
self.last_action = np.asarray(self.cur_chunk[0], dtype=float).copy()
act = np.asarray(self.cur_chunk.popleft(), dtype=float)
self.k += 1
return act
def start_inference_thread(args, config, policy, ros_operator):
th = threading.Thread(target=inference_fn_non_blocking_fast, args=(args, config, policy, ros_operator))
th.daemon = True
th.start()
def inference_fn_non_blocking_fast(args, config, policy, ros_operator):
global stream_buffer
rate = rospy.Rate(getattr(args, "inference_rate", 4))
while not rospy.is_shutdown():
try:
# Pause inference in DAgger mode
if dagger_mode_active:
try:
rate.sleep()
except Exception:
time.sleep(0.01)
continue
# Update observation
update_observation_window(args, config, ros_operator)
latest_obs = observation_window[-1]
imgs = [
latest_obs["images"][config["camera_names"][0]],
latest_obs["images"][config["camera_names"][1]],
latest_obs["images"][config["camera_names"][2]],
]
imgs = [cv2.cvtColor(im, cv2.COLOR_BGR2RGB) for im in imgs]
imgs = image_tools.resize_with_pad(np.array(imgs), 224, 224)
proprio = latest_obs["qpos"]
payload = {
"state": proprio,
"images": {
"top_head": imgs[0].transpose(2, 0, 1),
"hand_right": imgs[1].transpose(2, 0, 1),
"hand_left": imgs[2].transpose(2, 0, 1),
},
"prompt": lang_embeddings,
}
actions = policy.infer(payload)["actions"]
if actions is not None and len(actions) > 0:
max_k = int(getattr(args, "latency_k", 0))
min_m = int(getattr(args, "min_smooth_steps", 8))
stream_buffer.integrate_new_chunk(actions, max_k=max_k, min_m=min_m)
try:
rate.sleep()
except Exception:
pass
except Exception as e:
try:
rate.sleep()
except Exception:
time.sleep(0.005)
continue
def set_seed(seed):
torch.manual_seed(seed)
np.random.seed(seed)
class SimpleKalmanFilter:
def __init__(self, process_variance=1e-6, measurement_variance=1e-7, initial_value=None):
self.process_variance = process_variance
self.measurement_variance = measurement_variance
self.estimate = initial_value
self.error_estimate = 1.0
def update(self, measurement):
if self.estimate is None:
self.estimate = measurement.copy()
return self.estimate
# Compute Kalman gain
kalman_gain = self.error_estimate / (self.error_estimate + self.measurement_variance)
# Update estimate
self.estimate = self.estimate + kalman_gain * (measurement - self.estimate)
# Update the error estimate
self.error_estimate = (1 - kalman_gain) * self.error_estimate + abs(self.estimate - measurement) * self.process_variance
return self.estimate
# Interpolate the actions to make the robot move smoothly
def interpolate_action(args, prev_action, cur_action):
steps = np.concatenate((np.array(args.arm_steps_length), np.array(args.arm_steps_length)), axis=0)
diff = np.abs(cur_action - prev_action)
step = np.ceil(diff / steps).astype(int)
step = np.max(step)
if step <= 1:
return cur_action[np.newaxis, :]
new_actions = np.linspace(prev_action, cur_action, step + 1)
return new_actions[1:]
def minimum_jerk_interpolation(args, prev_action, cur_action):
num_steps = args.jerk_num_steps
t_normalized = np.linspace(0, 1, num_steps + 1)[1:]
trajectory = []
for tau in t_normalized:
factor = 10 * (tau ** 3) - 15 * (tau ** 4) + 6 * (tau ** 5)
trajectory.append(prev_action + factor * (cur_action - prev_action))
return np.array(trajectory)
def get_config(args):
config = {
"episode_len": args.max_publish_step,
"state_dim": 14,
"chunk_size": args.chunk_size,
"camera_names": CAMERA_NAMES,
}
return config
# Get the observation from the ROS topic
def get_ros_observation(args, ros_operator):
rate = rospy.Rate(args.publish_rate)
print_flag = True
# Max wait; use cached frame if timeout to avoid blocking
max_wait_s = 0.6
start_t = time.time()
while True and not rospy.is_shutdown():
# Non-destructive snapshot to avoid blocking
result = ros_operator.get_frame_peek()
if not result:
# On timeout, try cached frame if any
if (time.time() - start_t) > max_wait_s and ros_operator.last_frame_cache is not None:
if print_flag:
print("syn timeout, using last cached frame in get_ros_observation")
print_flag = False
(
img_front,
img_left,
img_right,
img_front_depth,
img_left_depth,
img_right_depth,
puppet_arm_left,
puppet_arm_right,
robot_base,
) = ros_operator.last_frame_cache
return (img_front, img_left, img_right, puppet_arm_left, puppet_arm_right)
if print_flag:
print("syn fail when get_ros_observation")
print_flag = False
rate.sleep()
continue
print_flag = True
(
img_front,
img_left,
img_right,
img_front_depth,
img_left_depth,
img_right_depth,
puppet_arm_left,
puppet_arm_right,
robot_base,
) = result
return (img_front, img_left, img_right, puppet_arm_left, puppet_arm_right)
# Update the observation window buffer
def update_observation_window(args, config, ros_operator):
# JPEG transformation
# Align with training
def jpeg_mapping(img):
img = cv2.imencode(".jpg", img)[1].tobytes()
img = cv2.imdecode(np.frombuffer(img, np.uint8), cv2.IMREAD_COLOR)
return img
global observation_window
if observation_window is None:
observation_window = deque(maxlen=2)
# Append the first dummy image
observation_window.append(
{
"qpos": None,
"images": {
config["camera_names"][0]: None,
config["camera_names"][1]: None,
config["camera_names"][2]: None,
},
}
)
img_front, img_left, img_right, puppet_arm_left, puppet_arm_right = get_ros_observation(args, ros_operator)
img_front = jpeg_mapping(img_front)
img_left = jpeg_mapping(img_left)
img_right = jpeg_mapping(img_right)
qpos = np.concatenate(
(np.array(puppet_arm_left.position), np.array(puppet_arm_right.position)),
axis=0,
)
observation_window.append(
{
"qpos": qpos,
"images": {
config["camera_names"][0]: img_front,
config["camera_names"][1]: img_right,
config["camera_names"][2]: img_left,
},
}
)
def inference_fn(args, config, policy):
global observation_window
global lang_embeddings
# print(f"Start inference_thread_fn: t={t}")
while True and not rospy.is_shutdown():
time1 = time.time()
# fetch images in sequence [front, right, left]
image_arrs = [
observation_window[-1]["images"][config["camera_names"][0]],
observation_window[-1]["images"][config["camera_names"][1]],
observation_window[-1]["images"][config["camera_names"][2]],
]
# convert bgr ro rgb
image_arrs = [cv2.cvtColor(img, cv2.COLOR_BGR2RGB) for img in image_arrs]
image_arrs = image_tools.resize_with_pad(np.array(image_arrs), 224, 224)
# get last qpos in shape [14, ]
proprio = observation_window[-1]["qpos"]
payload = {
"state": proprio,
"images": {
"top_head": image_arrs[0].transpose(2, 0, 1),
"hand_right": image_arrs[1].transpose(2, 0, 1),
"hand_left": image_arrs[2].transpose(2, 0, 1),
},
"prompt": lang_embeddings,
}
# actions shaped as [64, 14] in format [left, right]
actions = policy.infer(payload)["actions"]
print(f"Model inference time: {(time.time() - time1)*1000:.3f} ms")
return actions
# Main loop for the manipulation task
def model_inference(args, config, ros_operator, keyboard_thread_started=False):
global lang_embeddings
global dagger_mode_active
global save_data_requested
global collection_active
# Load client
policy = websocket_client_policy.WebsocketClientPolicy(
args.host,
args.port,
)
kalman_filters = [SimpleKalmanFilter() for _ in range(config["state_dim"])]
print(f"Server metadata: {policy.get_server_metadata()}")
max_publish_step = config["episode_len"]
chunk_size = config["chunk_size"]
# Initialize position of the puppet arm
left0 = [0, 0.32, -0.36, 0, 0.24, 0, 0.07]
right0 = [0, 0.32, -0.36, 0, 0.24, 0, 0.07]
ros_operator.puppet_arm_publish_continuous(left0, right0)
# input("Press enter to continue")
# ros_operator.puppet_arm_publish_continuous(left0, right0)
# Start keyboard monitor thread AFTER input() to avoid terminal conflicts
if not keyboard_thread_started:
keyboard_thread = threading.Thread(target=keyboard_monitor_thread, daemon=True)
keyboard_thread.start()
print("\n" + "="*70)
print("✅ Keyboard monitor thread started")
print("🎹 DAgger Mode Controls:")
print(" Press 'd' key → Activate DAgger mode (pause inference)")
print(" Press 'r' key → Resume inference mode")
print("="*70 + "\n")
time.sleep(0.3) # Give user time to read
# Initialize the previous action to be the initial robot state
pre_action = np.zeros(config["state_dim"])
action = None
# Track if we've entered DAgger mode
dagger_mode_entered = False
# Inference loop
with torch.inference_mode():
while True and not rospy.is_shutdown():
# The current time step
t = 0
rate = rospy.Rate(args.publish_rate)
action_buffer = np.zeros([chunk_size, config["state_dim"]])
last_stream_act = None
while t < max_publish_step and not rospy.is_shutdown():
# Check if DAgger mode is activated
with dagger_mode_lock:
if dagger_mode_active and not dagger_mode_entered:
print("\n" + "="*70)
print("⏸️ INFERENCE PAUSED - ENTERING DAGGER MODE")
print("="*70 + "\n")
ros_operator.enter_dagger_mode()
dagger_mode_entered = True
elif not dagger_mode_active and dagger_mode_entered:
print("\n" + "="*70)
print("▶️ DAGGER MODE DEACTIVATED - RESUMING INFERENCE")
print("="*70 + "\n")
# Stop data collection
ros_operator.data_collector.stop_collection()
dagger_mode_entered = False
# Check save request
with save_data_lock:
if save_data_requested and dagger_mode_active:
if ros_operator.data_collector.has_data():
ros_operator.data_collector.save_current_episode(
export_video=getattr(args, 'export_video', True),
video_fps=getattr(args, 'video_fps', 30),
video_codec=getattr(args, 'video_codec', 'libx264'),
video_quality=getattr(args, 'video_quality', 23)
)
# Stop after save
with collection_lock:
collection_active = False
else:
print("\nNo data to save.\n")
save_data_requested = False
# Check if starting collection
with collection_lock:
if collection_active and not ros_operator.data_collector.is_collecting:
ros_operator.data_collector.start_collection()
# If in DAgger mode, skip inference and collect demonstration data
if dagger_mode_active:
# Collect using time-synced get_synced_frame
synced_data = ros_operator.get_synced_frame()
if synced_data is not None:
try:
# Unpack synced data
(front_img, left_img, right_img,
puppet_left, puppet_right,
master_left, master_right) = synced_data
# Build observation (same as collect_data)
camera_names = ['cam_high', 'cam_left_wrist', 'cam_right_wrist']
image_dict = {
camera_names[0]: front_img, # cam_high
camera_names[1]: left_img, # cam_left_wrist
camera_names[2]: right_img # cam_right_wrist
}
observation = collections.OrderedDict()
observation['images'] = image_dict
observation['qpos'] = np.concatenate((puppet_left.position, puppet_right.position))
observation['qvel'] = np.concatenate((puppet_left.velocity, puppet_right.velocity))
observation['effort'] = np.concatenate((puppet_left.effort, puppet_right.effort))
observation['base_vel'] = [0.0, 0.0]
# Build action (same as collect_data): slave 6 joints + master gripper
left_action = puppet_left.position[:7]
right_action = puppet_right.position[:7]
action = np.concatenate((left_action, right_action))
# Add to collector
ros_operator.data_collector.add_frame(observation, action)
except Exception as e:
print(f"Collection error: {e}")
rate.sleep()
continue
# Temporal smoothing execution path
if args.use_temporal_smoothing:
global stream_buffer
if stream_buffer is None:
stream_buffer = StreamActionBuffer(
max_chunks=args.buffer_max_chunks,
decay_alpha=args.exp_decay_alpha,
state_dim=config["state_dim"],
smooth_method="temporal",
)
start_inference_thread(args, config, policy, ros_operator)
act = stream_buffer.pop_next_action()
if act is not None:
if args.ctrl_type == "joint":
left_action = act[:7].copy()
right_action = act[7:14].copy()
left_action[6] = max(0.0, left_action[6]-RIGHT_OFFSET)
right_action[6] = max(0.0, right_action[6]-RIGHT_OFFSET)
ros_operator.puppet_arm_publish(left_action, right_action)
elif args.ctrl_type == "eef":
left_action = act[:7]
right_action = act[7:14]
ros_operator.endpose_publish(left_action, right_action)
last_stream_act = act.copy()
else:
if last_stream_act is not None:
if args.ctrl_type == "joint":
left_action = last_stream_act[:7]
right_action = last_stream_act[7:14]
ros_operator.puppet_arm_publish(left_action, right_action)
elif args.ctrl_type == "eef":
left_action = last_stream_act[:7]
right_action = last_stream_act[7:14]
ros_operator.endpose_publish(left_action, right_action)
else:
pass
rate.sleep()
t += 1
continue
# Update observation window (blocking-chunk mode)
update_observation_window(args, config, ros_operator)
# When coming to the end of the action chunk
if t % chunk_size == 0:
# Start inference
action_buffer = inference_fn(args, config, policy).copy()
raw_action = action_buffer[t % chunk_size]
# Kalman filter for action smoothing
if args.use_kalman_filter:
action = np.array([kf.update(raw_action[i]) for i, kf in enumerate(kalman_filters)])
else:
action = raw_action
# Interpolate the original action sequence
if args.use_actions_interpolation:
# print(f"Time {t}, pre {pre_action}, act {action}")
if args.interpolate_method == "linear":
interp_actions = interpolate_action(args, pre_action, action)
elif args.interpolate_method == "minimum_jerk":
interp_actions = minimum_jerk_interpolation(args, pre_action, action)
else:
raise NotImplementedError
else:
interp_actions = action[np.newaxis, :]
# Execute the interpolated actions one by one
for act in interp_actions:
if args.ctrl_type == "joint":
left_action = act[:7]
right_action = act[7:14]
# Gripper thresholding
if args.gripper_threshold:
if left_action[-1] < 0.03:
left_action[-1] = 0
if right_action[-1] < 0.03:
right_action[-1] = 0
# ros_operator.puppet_arm_publish(right_action, left_action)
ros_operator.puppet_arm_publish(left_action, right_action)
elif args.ctrl_type == "eef":
left_action = act[:7]
right_action = act[7:14]
ros_operator.endpose_publish(left_action, right_action)
if args.use_robot_base:
vel_action = act[14:16]
ros_operator.robot_base_publish(vel_action)
rate.sleep()
t += 1
# Print step info less frequently to avoid cluttering terminal
if t % 50 == 0: # Print every 50 steps
print(f"Published Step {t} | Press 'd' for DAgger mode, 'r' to resume")
pre_action = action.copy()
# ROS operator class
class RosOperator:
def __init__(self, args):
self.robot_base_deque = None
self.puppet_arm_right_deque = None
self.puppet_arm_left_deque = None
self.img_front_deque = None
self.img_right_deque = None
self.img_left_deque = None
self.img_front_depth_deque = None
self.img_right_depth_deque = None
self.img_left_depth_deque = None
self.bridge = None
self.puppet_arm_left_publisher = None
self.puppet_arm_right_publisher = None
self.endpose_left_publisher = None
self.endpose_right_publisher = None
self.robot_base_publisher = None
self.puppet_arm_publish_thread = None
self.puppet_arm_publish_lock = None
self.args = args
self.stop_flag = False
# DAgger mode - master arm control
self.master_arm_left_deque = None
self.master_arm_right_deque = None
self.master_left_enable_pub = None
self.master_right_enable_pub = None
self.master_left_config_pub = None
self.master_right_config_pub = None
self.master_left_teach_mode_pub = None
self.master_right_teach_mode_pub = None
self.master_left_joint_pub = None
self.master_right_joint_pub = None
self.last_frame_cache = None
self.args = args
self.stop_flag = False
# Dataset path: use dataset_name (strip _dagger/_inference suffix)
dataset_base = getattr(self.args, "dataset_name", "flat_1107_27_35_mixed1.0")
dataset_base = dataset_base.replace("_dagger_hdf5", "").replace("_inference_hdf5", "")
base_data_dir = "/home/agilex/data"
# DAgger data dir
dagger_dir = os.path.join(base_data_dir, f"{dataset_base}_dagger_hdf5", "aloha_mobile_dummy")
os.makedirs(dagger_dir, exist_ok=True)
# Inference data dir
inference_dir = os.path.join(base_data_dir, f"{dataset_base}_inference_hdf5", "aloha_mobile_dummy")
os.makedirs(inference_dir, exist_ok=True)
# Init collector
self.data_collector = SimpleDAggerCollector(
camera_names=['cam_high', 'cam_left_wrist', 'cam_right_wrist'],
dataset_dir=base_data_dir,
task_name=dataset_base
)
# Set collector DAgger save dir
self.data_collector.full_dataset_dir = dagger_dir
if hasattr(self.data_collector, "_find_next_episode_idx"):
self.data_collector._find_next_episode_idx()
# Keep inference dir for export
self.inference_dataset_dir = inference_dir
self.dataset_base = dataset_base
# Init ROS etc.
self.init()
self.init_ros()
# def __init__(self, args):
# self.robot_base_deque = None
# self.puppet_arm_right_deque = None
# self.puppet_arm_left_deque = None
# self.img_front_deque = None
# self.img_right_deque = None
# self.img_left_deque = None
# self.img_front_depth_deque = None
# self.img_right_depth_deque = None
# self.img_left_depth_deque = None
# self.bridge = None
# self.puppet_arm_left_publisher = None
# self.puppet_arm_right_publisher = None
# self.endpose_left_publisher = None
# self.endpose_right_publisher = None
# self.robot_base_publisher = None
# self.puppet_arm_publish_thread = None
# self.puppet_arm_publish_lock = None
# self.args = args
# self.stop_flag = False
# # DAgger mode - master arm control
# self.master_arm_left_deque = None
# self.master_arm_right_deque = None
# self.master_left_enable_pub = None
# self.master_right_enable_pub = None
# self.master_left_config_pub = None
# self.master_right_config_pub = None
# self.master_left_teach_mode_pub = None
# self.master_right_teach_mode_pub = None
# self.master_left_joint_pub = None
# self.master_right_joint_pub = None