KillzoneCC commited on
Commit
fe9f854
·
1 Parent(s): c82e679

Порядок в столбцах и удаление лишнего

Browse files
Files changed (1) hide show
  1. collect_and_upload.py +67 -66
collect_and_upload.py CHANGED
@@ -33,8 +33,9 @@ LOCAL_ROOT_DIR = Path("./")
33
  OBSERVATION_TOPICS = {
34
  "camera_generic": {"topic": "/camera/image_raw", "msg_type": "sensor_msgs/Image"},
35
  "imu": {"topic": "/imu", "msg_type": "sensor_msgs/Imu"},
36
- "joint_positions": {"topic": "/ros_robot_controller/bus_servo/set_position", "msg_type": "ros_robot_controller/SetBusServosPosition"},
37
  "joy": {"topic": "/joy", "msg_type": "sensor_msgs/Joy"},
 
38
  }
39
 
40
  # --- Глобальные переменные для хранения последних данных ---
@@ -125,6 +126,21 @@ def joint_positions_callback(message):
125
  print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")
126
  latest_data["joint_positions"] = None
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  def joy_callback(message):
129
  with data_lock:
130
  try:
@@ -142,7 +158,6 @@ def create_readme(repo_id, info, root_dir):
142
  robot_type = info.get("robot_type", "unknown")
143
  fps = info.get("fps", 0)
144
 
145
- # Исправленное форматирование YAML
146
  readme_content = f"""---
147
  license: apache-2.0
148
  task_categories:
@@ -202,7 +217,6 @@ def create_video(frames, video_path):
202
  def collect_data_and_save():
203
  global running
204
 
205
- # --- Создание папок в правильном порядке ---
206
  META_DIR = LOCAL_ROOT_DIR / "meta"
207
  DATA_DIR = LOCAL_ROOT_DIR / "data" / "chunk-000"
208
  VIDEOS_DIR = LOCAL_ROOT_DIR / "videos" / "chunk-000" / "observation.images.generic"
@@ -213,18 +227,15 @@ def collect_data_and_save():
213
 
214
  info_path = META_DIR / "info.json"
215
  episodes_jsonl_path = META_DIR / "episodes.jsonl"
216
-
217
- # Создаем список имен для 26 сервоприводов
218
  joint_names = [f"servo_{i+1}" for i in range(26)]
219
 
220
- # --- Определение задач (пример) ---
221
  tasks_list = [
222
  "Переместить предмет А из точки X в точку Y.",
223
  "Поднять предмет B и опустить его в ящик.",
224
  "Перемещение руки"
225
  ]
226
 
227
- # --- Шаблон для info.json с полным набором полей ---
228
  base_info = {
229
  "codebase_version": "v2.2",
230
  "robot_type": "ainex_robot",
@@ -242,32 +253,15 @@ def collect_data_and_save():
242
  "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
243
  "features": {
244
  "action": {
245
- "servo_commands": {
246
- "dtype": "float32",
247
- "shape": [26],
248
- "names": joint_names
249
- },
250
- "joystick": {
251
- "axes": {
252
- "dtype": "float32",
253
- "shape": [8],
254
- },
255
- "buttons": {
256
- "dtype": "int32",
257
- "shape": [11],
258
- }
259
- }
260
  },
261
  "observation": {
262
- "joint_positions": {
263
  "dtype": "float32",
264
- "shape": [26],
265
- "names": joint_names
266
- },
267
- "imu": {
268
- "dtype": "float32",
269
- "shape": [10],
270
- "names": ["orientation.x", "orientation.y", "orientation.z", "orientation.w", "angular_velocity.x", "angular_velocity.y", "angular_velocity.z", "linear_acceleration.x", "linear_acceleration.y", "linear_acceleration.z"]
271
  },
272
  "images": {
273
  "generic": {
@@ -280,18 +274,18 @@ def collect_data_and_save():
280
  },
281
  "timestamp": { "dtype": "float64", "shape": [1] },
282
  "frame_index": { "dtype": "int64", "shape": [1] },
283
- "episode_index": { "dtype": "int64", "shape": [1] }
 
 
284
  }
285
  }
286
 
287
- # --- Загрузка существующих метаданных, если они есть ---
288
  info = base_info
289
  episode_idx = 0
290
  if info_path.exists():
291
  try:
292
  with open(info_path, 'r') as f:
293
  existing_info = json.load(f)
294
- # Обновляем только числовые данные, сохраняя структуру
295
  info['total_episodes'] = existing_info.get('total_episodes', 0)
296
  info['total_frames'] = existing_info.get('total_frames', 0)
297
  info['total_videos'] = existing_info.get('total_videos', 0)
@@ -304,7 +298,6 @@ def collect_data_and_save():
304
  if info_path.exists():
305
  os.remove(info_path)
306
 
307
- # --- Загрузка существующих эпизодов ---
308
  episodes_data = []
309
  if episodes_jsonl_path.exists():
310
  try:
@@ -316,7 +309,6 @@ def collect_data_and_save():
316
  if episodes_jsonl_path.exists():
317
  os.remove(episodes_jsonl_path)
318
 
319
- # --- Создание файла tasks.jsonl и README.md только один раз ---
320
  create_tasks_file(META_DIR, tasks_list)
321
  create_readme(REPO_ID, info, LOCAL_ROOT_DIR)
322
 
@@ -344,6 +336,7 @@ features:
344
  ws_manager.subscribe(OBSERVATION_TOPICS["imu"]["topic"], OBSERVATION_TOPICS["imu"]["msg_type"], imu_callback)
345
  ws_manager.subscribe(OBSERVATION_TOPICS["joint_positions"]["topic"], OBSERVATION_TOPICS["joint_positions"]["msg_type"], joint_positions_callback)
346
  ws_manager.subscribe(OBSERVATION_TOPICS["joy"]["topic"], OBSERVATION_TOPICS["joy"]["msg_type"], joy_callback)
 
347
  print("Подписки установлены.")
348
 
349
  print("\nСбор данных запущен. Выполняйте движения роботом.")
@@ -353,12 +346,13 @@ features:
353
  current_episode_start_time = time.time()
354
 
355
  all_images_generic = []
356
- all_joint_positions = []
357
- all_imu_data = []
358
- all_timestamps = []
359
  all_actions = []
360
- all_joy_axes = []
361
- all_joy_buttons = []
 
 
 
362
 
363
  total_frames_collected = 0
364
 
@@ -372,17 +366,25 @@ features:
372
 
373
  imu_data = latest_data["imu"][0] if latest_data["imu"] is not None else np.array([0.0]*10, dtype=np.float32)
374
  joint_positions_data = latest_data["joint_positions"][0] if latest_data["joint_positions"] is not None else np.array([0.0]*26, dtype=np.float32)
 
375
  joy_data = latest_data["joy"][0] if latest_data["joy"] is not None else ([], [])
376
  joy_axes = joy_data[0] if joy_data[0] else [0.0] * 8
377
  joy_buttons = joy_data[1] if joy_data[1] else [0] * 11
378
 
 
 
 
 
 
 
 
 
379
  all_images_generic.append(img_generic)
380
- all_joint_positions.append(joint_positions_data.tolist())
381
- all_imu_data.append(imu_data.tolist())
382
- all_actions.append([0.0] * 26)
383
  all_timestamps.append(img_timestamp)
384
- all_joy_axes.append(joy_axes)
385
- all_joy_buttons.append(joy_buttons)
 
 
386
 
387
  latest_data["camera_generic"] = None
388
  total_frames_collected += 1
@@ -395,15 +397,14 @@ features:
395
  create_video(all_images_generic, video_path_generic)
396
 
397
  df = pd.DataFrame({
 
 
398
  'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
399
- 'observation.joint_positions': all_joint_positions,
400
- 'observation.imu': all_imu_data,
401
- 'action.servo_commands': all_actions,
402
- 'action.joystick.axes': all_joy_axes,
403
- 'action.joystick.buttons': all_joy_buttons,
404
  'timestamp': all_timestamps,
405
- 'frame_index': list(range(len(all_images_generic))),
406
- 'episode_index': [episode_idx] * len(all_images_generic),
 
 
407
  })
408
 
409
  table = pa.Table.from_pandas(df)
@@ -417,7 +418,7 @@ features:
417
 
418
  episodes_data.append({
419
  "episode_index": episode_idx,
420
- "tasks": tasks_list,
421
  "length": len(all_images_generic)
422
  })
423
  create_episodes_file(META_DIR, episodes_data)
@@ -426,12 +427,13 @@ features:
426
  episode_idx += 1
427
  current_episode_start_time = time.time()
428
  all_images_generic = []
429
- all_joint_positions = []
430
- all_imu_data = []
431
- all_timestamps = []
432
  all_actions = []
433
- all_joy_axes = []
434
- all_joy_buttons = []
 
 
 
435
 
436
  time.sleep(0.01)
437
  except Exception as e:
@@ -445,15 +447,14 @@ features:
445
  create_video(all_images_generic, video_path_generic)
446
 
447
  df = pd.DataFrame({
 
 
448
  'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
449
- 'observation.joint_positions': all_joint_positions,
450
- 'observation.imu': all_imu_data,
451
- 'action.servo_commands': all_actions,
452
- 'action.joystick.axes': all_joy_axes,
453
- 'action.joystick.buttons': all_joy_buttons,
454
  'timestamp': all_timestamps,
455
- 'frame_index': list(range(len(all_images_generic))),
456
- 'episode_index': [episode_idx] * len(all_images_generic),
 
 
457
  })
458
 
459
  table = pa.Table.from_pandas(df)
@@ -467,7 +468,7 @@ features:
467
 
468
  episodes_data.append({
469
  "episode_index": episode_idx,
470
- "tasks": tasks_list,
471
  "length": len(all_images_generic)
472
  })
473
  create_episodes_file(META_DIR, episodes_data)
 
33
  OBSERVATION_TOPICS = {
34
  "camera_generic": {"topic": "/camera/image_raw", "msg_type": "sensor_msgs/Image"},
35
  "imu": {"topic": "/imu", "msg_type": "sensor_msgs/Imu"},
36
+ "joint_positions": {"topic": "/ros_robot_controller/bus_servo/get_position", "msg_type": "ros_robot_controller/SetBusServosPosition"},
37
  "joy": {"topic": "/joy", "msg_type": "sensor_msgs/Joy"},
38
+ "action_commands": {"topic": "/ros_robot_controller/bus_servo/set_position", "msg_type": "ros_robot_controller/SetBusServosPosition"}
39
  }
40
 
41
  # --- Глобальные переменные для хранения последних данных ---
 
126
  print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")
127
  latest_data["joint_positions"] = None
128
 
129
+ def action_commands_callback(message):
130
+ with data_lock:
131
+ try:
132
+ if "position" in message and isinstance(message["position"], list):
133
+ temp_actions = np.array([0.0] * 26, dtype=np.float32)
134
+ for item in message["position"]:
135
+ if isinstance(item, dict) and "id" in item and "position" in item:
136
+ servo_id = int(item["id"])
137
+ if 1 <= servo_id <= 26:
138
+ temp_actions[servo_id - 1] = float(item["position"])
139
+ latest_data["action_commands"] = (temp_actions, time.time())
140
+ except Exception as e:
141
+ print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения команд сервоприводов: {e}. Сообщение: {message}")
142
+ latest_data["action_commands"] = None
143
+
144
  def joy_callback(message):
145
  with data_lock:
146
  try:
 
158
  robot_type = info.get("robot_type", "unknown")
159
  fps = info.get("fps", 0)
160
 
 
161
  readme_content = f"""---
162
  license: apache-2.0
163
  task_categories:
 
217
  def collect_data_and_save():
218
  global running
219
 
 
220
  META_DIR = LOCAL_ROOT_DIR / "meta"
221
  DATA_DIR = LOCAL_ROOT_DIR / "data" / "chunk-000"
222
  VIDEOS_DIR = LOCAL_ROOT_DIR / "videos" / "chunk-000" / "observation.images.generic"
 
227
 
228
  info_path = META_DIR / "info.json"
229
  episodes_jsonl_path = META_DIR / "episodes.jsonl"
230
+
 
231
  joint_names = [f"servo_{i+1}" for i in range(26)]
232
 
 
233
  tasks_list = [
234
  "Переместить предмет А из точки X в точку Y.",
235
  "Поднять предмет B и опустить его в ящик.",
236
  "Перемещение руки"
237
  ]
238
 
 
239
  base_info = {
240
  "codebase_version": "v2.2",
241
  "robot_type": "ainex_robot",
 
253
  "video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
254
  "features": {
255
  "action": {
256
+ "dtype": "float32",
257
+ "shape": [37], # 26 servo commands + 8 axes + 3 buttons (or 11 buttons)
258
+ "names": joint_names + ["joy_axis_" + str(i) for i in range(8)] + ["joy_button_" + str(i) for i in range(11)]
 
 
 
 
 
 
 
 
 
 
 
 
259
  },
260
  "observation": {
261
+ "state": {
262
  "dtype": "float32",
263
+ "shape": [36], # 26 joint_positions + 10 imu
264
+ "names": joint_names + ["imu_orientation.x", "imu_orientation.y", "imu_orientation.z", "imu_orientation.w", "imu_angular_velocity.x", "imu_angular_velocity.y", "imu_angular_velocity.z", "imu_linear_acceleration.x", "imu_linear_acceleration.y", "imu_linear_acceleration.z"]
 
 
 
 
 
265
  },
266
  "images": {
267
  "generic": {
 
274
  },
275
  "timestamp": { "dtype": "float64", "shape": [1] },
276
  "frame_index": { "dtype": "int64", "shape": [1] },
277
+ "episode_index": { "dtype": "int64", "shape": [1] },
278
+ "index": { "dtype": "int64", "shape": [1] },
279
+ "task_index": { "dtype": "int64", "shape": [1] }
280
  }
281
  }
282
 
 
283
  info = base_info
284
  episode_idx = 0
285
  if info_path.exists():
286
  try:
287
  with open(info_path, 'r') as f:
288
  existing_info = json.load(f)
 
289
  info['total_episodes'] = existing_info.get('total_episodes', 0)
290
  info['total_frames'] = existing_info.get('total_frames', 0)
291
  info['total_videos'] = existing_info.get('total_videos', 0)
 
298
  if info_path.exists():
299
  os.remove(info_path)
300
 
 
301
  episodes_data = []
302
  if episodes_jsonl_path.exists():
303
  try:
 
309
  if episodes_jsonl_path.exists():
310
  os.remove(episodes_jsonl_path)
311
 
 
312
  create_tasks_file(META_DIR, tasks_list)
313
  create_readme(REPO_ID, info, LOCAL_ROOT_DIR)
314
 
 
336
  ws_manager.subscribe(OBSERVATION_TOPICS["imu"]["topic"], OBSERVATION_TOPICS["imu"]["msg_type"], imu_callback)
337
  ws_manager.subscribe(OBSERVATION_TOPICS["joint_positions"]["topic"], OBSERVATION_TOPICS["joint_positions"]["msg_type"], joint_positions_callback)
338
  ws_manager.subscribe(OBSERVATION_TOPICS["joy"]["topic"], OBSERVATION_TOPICS["joy"]["msg_type"], joy_callback)
339
+ ws_manager.subscribe(OBSERVATION_TOPICS["action_commands"]["topic"], OBSERVATION_TOPICS["action_commands"]["msg_type"], action_commands_callback)
340
  print("Подписки установлены.")
341
 
342
  print("\nСбор данных запущен. Выполняйте движения роботом.")
 
346
  current_episode_start_time = time.time()
347
 
348
  all_images_generic = []
349
+ all_observation_states = []
 
 
350
  all_actions = []
351
+ all_timestamps = []
352
+ all_frame_indices = []
353
+ all_episode_indices = []
354
+ all_indices = []
355
+ all_task_indices = []
356
 
357
  total_frames_collected = 0
358
 
 
366
 
367
  imu_data = latest_data["imu"][0] if latest_data["imu"] is not None else np.array([0.0]*10, dtype=np.float32)
368
  joint_positions_data = latest_data["joint_positions"][0] if latest_data["joint_positions"] is not None else np.array([0.0]*26, dtype=np.float32)
369
+ action_commands_data = latest_data["action_commands"][0] if latest_data["action_commands"] is not None else np.array([0.0]*26, dtype=np.float32)
370
  joy_data = latest_data["joy"][0] if latest_data["joy"] is not None else ([], [])
371
  joy_axes = joy_data[0] if joy_data[0] else [0.0] * 8
372
  joy_buttons = joy_data[1] if joy_data[1] else [0] * 11
373
 
374
+ # Формируем объединенное состояние наблюдения
375
+ combined_observation_state = np.concatenate((joint_positions_data, imu_data)).tolist()
376
+ all_observation_states.append(combined_observation_state)
377
+
378
+ # Формируем объединенное действие
379
+ combined_action = np.concatenate((action_commands_data, np.array(joy_axes), np.array(joy_buttons, dtype=np.float32))).tolist()
380
+ all_actions.append(combined_action)
381
+
382
  all_images_generic.append(img_generic)
 
 
 
383
  all_timestamps.append(img_timestamp)
384
+ all_frame_indices.append(total_frames_collected)
385
+ all_episode_indices.append(episode_idx)
386
+ all_indices.append(info['total_frames'] + total_frames_collected)
387
+ all_task_indices.append(0) # Пример, можно настроить
388
 
389
  latest_data["camera_generic"] = None
390
  total_frames_collected += 1
 
397
  create_video(all_images_generic, video_path_generic)
398
 
399
  df = pd.DataFrame({
400
+ 'action': all_actions,
401
+ 'observation.state': all_observation_states,
402
  'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
 
 
 
 
 
403
  'timestamp': all_timestamps,
404
+ 'frame_index': all_frame_indices,
405
+ 'episode_index': all_episode_indices,
406
+ 'index': all_indices,
407
+ 'task_index': all_task_indices
408
  })
409
 
410
  table = pa.Table.from_pandas(df)
 
418
 
419
  episodes_data.append({
420
  "episode_index": episode_idx,
421
+ "tasks": [0],
422
  "length": len(all_images_generic)
423
  })
424
  create_episodes_file(META_DIR, episodes_data)
 
427
  episode_idx += 1
428
  current_episode_start_time = time.time()
429
  all_images_generic = []
430
+ all_observation_states = []
 
 
431
  all_actions = []
432
+ all_timestamps = []
433
+ all_frame_indices = []
434
+ all_episode_indices = []
435
+ all_indices = []
436
+ all_task_indices = []
437
 
438
  time.sleep(0.01)
439
  except Exception as e:
 
447
  create_video(all_images_generic, video_path_generic)
448
 
449
  df = pd.DataFrame({
450
+ 'action': all_actions,
451
+ 'observation.state': all_observation_states,
452
  'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
 
 
 
 
 
453
  'timestamp': all_timestamps,
454
+ 'frame_index': all_frame_indices,
455
+ 'episode_index': all_episode_indices,
456
+ 'index': all_indices,
457
+ 'task_index': all_task_indices
458
  })
459
 
460
  table = pa.Table.from_pandas(df)
 
468
 
469
  episodes_data.append({
470
  "episode_index": episode_idx,
471
+ "tasks": [0],
472
  "length": len(all_images_generic)
473
  })
474
  create_episodes_file(META_DIR, episodes_data)