KillzoneCCO commited on
Commit
01d3880
·
verified ·
1 Parent(s): 4301b80

Delete collect_and_upload.py

Browse files
Files changed (1) hide show
  1. collect_and_upload.py +0 -506
collect_and_upload.py DELETED
@@ -1,506 +0,0 @@
1
- import roslibpy
2
- import threading
3
- import signal
4
- import base64
5
- import cv2
6
- import time
7
- import numpy as np
8
- import os
9
- import pandas as pd
10
- import json
11
- from huggingface_hub import HfApi, HfFolder, create_repo
12
- import pyarrow as pa
13
- import pyarrow.parquet as pq
14
- from pathlib import Path
15
-
16
- # --- Глобальный флаг для управления основным циклом ---
17
- running = True
18
-
19
- # --- Обработчик сигнала для корректного завершения (Ctrl+C) ---
20
- def signal_handler(sig, frame):
21
- global running
22
- print("\nПолучен сигнал завершения. Завершаю сбор данных...")
23
- running = False
24
-
25
- signal.signal(signal.SIGINT, signal_handler)
26
-
27
- # --- Настройки ROSBridge ---
28
- ROSBRIDGE_IP = "192.168.20.97"
29
- ROSBRIDGE_PORT = 9090
30
- REPO_ID = "KillzoneCCO/Ainex"
31
- LOCAL_ROOT_DIR = Path("./")
32
-
33
- # --- ROS Топики и типы сообщений для сбора данных (наблюдения) ---
34
- # Только один топик для камеры, как и было указано
35
- OBSERVATION_TOPICS = {
36
- "camera_generic": {"topic": "/camera/image_raw", "msg_type": "sensor_msgs/Image"},
37
- "imu": {"topic": "/imu", "msg_type": "sensor_msgs/Imu"},
38
- "joint_positions": {"topic": "/ros_robot_controller/bus_servo/set_position", "msg_type": "ros_robot_controller/SetBusServosPosition"},
39
- }
40
-
41
- # --- Глобальные переменные для хранения последних данных ---
42
- latest_data = {key: None for key in OBSERVATION_TOPICS.keys()}
43
- data_lock = threading.Lock()
44
-
45
- # --- Менеджер соединения ROSBridge ---
46
- class ROSBridgeManager:
47
- def __init__(self, ip, port):
48
- self.ip = ip
49
- self.port = port
50
- self.client = roslibpy.Ros(host=self.ip, port=self.port)
51
- self.connected = False
52
- self._subscriptions = []
53
-
54
- def connect(self):
55
- print('ROSBridge: Попытка подключения...')
56
- try:
57
- self.client.run()
58
- self.connected = True
59
- print('ROSBridge: Подключено!')
60
- return True
61
- except Exception as e:
62
- print(f"ROSBridge: Ошибка подключения: {e}")
63
- self.connected = False
64
- return False
65
-
66
- def subscribe(self, topic_name, message_type, callback):
67
- listener = roslibpy.Topic(self.client, topic_name, message_type)
68
- listener.subscribe(callback)
69
- print(f"Подписан на {topic_name} ({message_type})")
70
- self._subscriptions.append(listener)
71
-
72
- def terminate(self):
73
- if self.client:
74
- for sub in self._subscriptions:
75
- try:
76
- sub.unsubscribe()
77
- except Exception as e:
78
- print(f"Ошибка при отписке от {sub.name}: {e}")
79
- self._subscriptions.clear()
80
- if self.client.is_connected:
81
- print("ROSBridge: Завершение соединения...")
82
- self.client.terminate()
83
- self.connected = False
84
-
85
- def create_image_callback(camera_key):
86
- def callback(message):
87
- with data_lock:
88
- try:
89
- np_arr = np.frombuffer(base64.b64decode(message['data']), np.uint8)
90
- channels = 3 if 'rgb' in message['encoding'] or 'bgr' in message['encoding'] else 1
91
- img_np = np_arr.reshape((message['height'], message['width'], channels))
92
- if 'bgr' in message['encoding']:
93
- img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
94
-
95
- latest_data[camera_key] = (img_np, time.time())
96
- except Exception as e:
97
- print(f"DEBUG: Ошибка обработки изображения с {camera_key}: {e}")
98
- latest_data[camera_key] = None
99
- return callback
100
-
101
- def imu_callback(message):
102
- with data_lock:
103
- try:
104
- imu_data = np.array([
105
- message['orientation']['x'],
106
- message['orientation']['y'],
107
- message['orientation']['z'],
108
- message['orientation']['w'],
109
- message['angular_velocity']['x'],
110
- message['angular_velocity']['y'],
111
- message['angular_velocity']['z'],
112
- message['linear_acceleration']['x'],
113
- message['linear_acceleration']['y'],
114
- message['linear_acceleration']['z']
115
- ], dtype=np.float32)
116
- latest_data["imu"] = (imu_data, time.time())
117
- except Exception as e:
118
- print(f"DEBUG: Ошибка обработки IMU: {e}")
119
- latest_data["imu"] = None
120
-
121
- def joint_positions_callback(message):
122
- with data_lock:
123
- try:
124
- if "position" in message and isinstance(message["position"], list):
125
- temp_joint_positions = np.array([0.0] * 26, dtype=np.float32)
126
- for item in message["position"]:
127
- if isinstance(item, dict) and "id" in item and "position" in item:
128
- servo_id = int(item["id"])
129
- if 1 <= servo_id <= 26:
130
- temp_joint_positions[servo_id - 1] = float(item["position"])
131
- latest_data["joint_positions"] = (temp_joint_positions, time.time())
132
- except Exception as e:
133
- print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")
134
- latest_data["joint_positions"] = None
135
-
136
- def create_readme(repo_id, info, meta_dir):
137
- readme_path = os.path.join(meta_dir, "README.md")
138
- total_episodes = info.get("total_episodes", 0)
139
- total_frames = info.get("total_frames", 0)
140
- robot_type = info.get("robot_type", "unknown")
141
- fps = info.get("fps", 0)
142
-
143
- readme_content = f"""---
144
- license: apache-2.0
145
- task_categories:
146
- - robotics
147
- tags:
148
- - LeRobot
149
- configs:
150
- - config_name: default
151
- data_files: data/*/*.parquet
152
- ---
153
-
154
- # Ainex Robot Dataset
155
-
156
- Этот датасет был собран с помощью робота **Ainex** для демонстрации его возможностей в рамках LeRobot.
157
-
158
- ## Статистика датасета
159
- - **Общее количество эпизодов**: {total_episodes}
160
- - **Общее количество кадров**: {total_frames}
161
- - **Тип робота**: {robot_type}
162
- - **Кадров в секунду (FPS)**: {fps}
163
-
164
- ## Структура датасета
165
- - [meta/info.json](meta/info.json)
166
- - [meta/config.yaml](meta/config.yaml)
167
- - [meta/episodes.jsonl](meta/episodes.jsonl)
168
- - [meta/tasks.jsonl](meta/tasks.jsonl)
169
- """
170
- with open(readme_path, 'w', encoding='utf-8') as f:
171
- f.write(readme_content)
172
- print("Создан файл meta/README.md.")
173
-
174
- def create_tasks_file(meta_dir, tasks_list):
175
- tasks_path = os.path.join(meta_dir, "tasks.jsonl")
176
- with open(tasks_path, 'w', encoding='utf-8') as f:
177
- for i, task_desc in enumerate(tasks_list):
178
- f.write(json.dumps({"task_index": i, "task": task_desc}, ensure_ascii=False) + '\n')
179
- print("Создан файл meta/tasks.jsonl.")
180
-
181
- def create_episodes_file(meta_dir, episodes_list):
182
- episodes_path = os.path.join(meta_dir, "episodes.jsonl")
183
- with open(episodes_path, 'w', encoding='utf-8') as f:
184
- for episode in episodes_list:
185
- f.write(json.dumps(episode, ensure_ascii=False) + '\n')
186
- print("Создан файл meta/episodes.jsonl.")
187
-
188
- def create_gitattributes(root_dir):
189
- git_lfs_content = "*.mp4 filter=lfs diff=lfs merge=lfs -text\n*.parquet filter=lfs diff=lfs merge=lfs -text\n"
190
- git_attributes_path = os.path.join(root_dir, ".gitattributes")
191
- with open(git_attributes_path, 'w') as f:
192
- f.write(git_lfs_content)
193
- print("Создан файл .gitattributes для отслеживания LFS-файлов.")
194
-
195
- def collect_data_and_save():
196
- global running, latest_data
197
-
198
- # --- Создание папок в правильном порядке ---
199
- META_DIR = LOCAL_ROOT_DIR / "meta"
200
- DATA_DIR = LOCAL_ROOT_DIR / "data"
201
- VIDEOS_DIR = LOCAL_ROOT_DIR / "videos"
202
-
203
- os.makedirs(META_DIR, exist_ok=True)
204
- os.makedirs(DATA_DIR, exist_ok=True)
205
- os.makedirs(VIDEOS_DIR, exist_ok=True)
206
-
207
- create_gitattributes(LOCAL_ROOT_DIR)
208
-
209
- info_path = META_DIR / "info.json"
210
- episodes_jsonl_path = META_DIR / "episodes.jsonl"
211
-
212
- episode_idx = 0
213
- episodes_data = []
214
-
215
- # Имя директории для эпизода (chunk-000, chunk-001 и т.д.)
216
- chunk_name = f"chunk-000"
217
-
218
- # --- Определение задач (пример) ---
219
- tasks_list = [
220
- "Переместить предмет А из точки X в точку Y.",
221
- "Поднять предмет B и опустить его в ящик."
222
- ]
223
-
224
- # --- Загрузка существующих метаданных, если они есть ---
225
- if info_path.exists():
226
- try:
227
- with open(info_path, 'r') as f:
228
- info = json.load(f)
229
- episode_idx = info.get("total_episodes", 0)
230
- except json.JSONDecodeError:
231
- print(f"Предупреждение: Файл '{info_path}' поврежден или пуст. Создаю новый.")
232
- info = {}
233
- if info_path.exists():
234
- os.remove(info_path)
235
- if not info_path.exists():
236
- info = {
237
- "codebase_version": "v1.1",
238
- "total_frames": 0,
239
- "total_episodes": 0,
240
- "episode_lengths": [],
241
- "fps": 30,
242
- "robot_type": "ainex_robot",
243
- # Обновлены пути к данным для одной камеры
244
- # Теперь data_path ссылается на конкретный файл эпизода
245
- "data_path": "data/{chunk_name}/episode_{episode_index:06d}.parquet",
246
- "video_path": "videos/{chunk_name}/observation.images.{camera_name}/episode_{episode_index:06d}.mp4",
247
- "features": {
248
- "action": { "dtype": "float32", "shape": [26] },
249
- "observation": {
250
- "joint_positions": { "dtype": "float32", "shape": [26] },
251
- "imu": { "dtype": "float32", "shape": [10] },
252
- # Обновлены ключи для одной камеры
253
- "images.generic": {
254
- "dtype": "video",
255
- "media_type": "video/mp4",
256
- "path_format": "videos/{chunk_name}/observation.images.generic/episode_{episode_index:06d}.mp4",
257
- "shape": [480, 640, 3]
258
- }
259
- },
260
- "timestamp": { "dtype": "float64" },
261
- "frame_index": { "dtype": "int64" },
262
- "episode_index": { "dtype": "int64" }
263
- }
264
- }
265
-
266
- if episodes_jsonl_path.exists():
267
- try:
268
- with open(episodes_jsonl_path, 'r', encoding='utf-8') as f:
269
- for line in f:
270
- episodes_data.append(json.loads(line))
271
- except json.JSONDecodeError:
272
- print(f"Предупреждение: Файл '{episodes_jsonl_path}' поврежден или пуст. Создаю новый.")
273
- episodes_data = []
274
- if episodes_jsonl_path.exists():
275
- os.remove(episodes_jsonl_path)
276
-
277
- config_path = META_DIR / "config.yaml"
278
- config_content = f"""
279
- task_name: ainex-robot-collection
280
- dataset_id: {REPO_ID.split('/')[1]}
281
- features:
282
- observation.images.generic:
283
- video_loader:
284
- _target_: lerobot.common.datasets.video_utils.VideoLoader
285
- framerate: 30
286
- """
287
- with open(config_path, 'w') as f:
288
- f.write(config_content.strip())
289
- print("Создан файл meta/config.yaml с правильным video_loader.")
290
-
291
- ws_manager = ROSBridgeManager(ROSBRIDGE_IP, ROSBRIDGE_PORT)
292
- if not ws_manager.connect():
293
- print("ROSBridge: Невозможно продолжить без подключения. Завершение работы.")
294
- return
295
-
296
- print("Установка подписок...")
297
- ws_manager.subscribe(OBSERVATION_TOPICS["camera_generic"]["topic"], OBSERVATION_TOPICS["camera_generic"]["msg_type"], create_image_callback("camera_generic"))
298
- ws_manager.subscribe(OBSERVATION_TOPICS["imu"]["topic"], OBSERVATION_TOPICS["imu"]["msg_type"], imu_callback)
299
- ws_manager.subscribe(OBSERVATION_TOPICS["joint_positions"]["topic"], OBSERVATION_TOPICS["joint_positions"]["msg_type"], joint_positions_callback)
300
- print("Подписки установлены.")
301
-
302
- print("\nСбор данных запущен. Выполняйте движения роботом.")
303
- print("Нажмите 'Ctrl+C' для завершения и сохранения датасета.")
304
-
305
- # --- Новые переменные для разбиения на эпизоды по времени ---
306
- episode_duration_seconds = 2.0 # Длительность одного эпизода в секундах
307
- current_episode_start_time = time.time()
308
-
309
- all_images_generic = []
310
- all_joint_positions = []
311
- all_imu_data = []
312
- all_timestamps = []
313
- all_actions = []
314
-
315
- total_frames_collected = 0
316
-
317
- try:
318
- while running:
319
- with data_lock:
320
- new_image_generic_data = latest_data["camera_generic"]
321
-
322
- if new_image_generic_data is not None:
323
- img_generic, img_timestamp = new_image_generic_data
324
-
325
- imu_data = latest_data["imu"][0] if latest_data["imu"] is not None else np.array([0.0]*10, dtype=np.float32)
326
- 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)
327
-
328
- all_images_generic.append(img_generic)
329
- all_joint_positions.append(joint_positions_data.tolist())
330
- all_imu_data.append(imu_data.tolist())
331
- all_actions.append([0.0] * 26)
332
- all_timestamps.append(img_timestamp)
333
-
334
- latest_data["camera_generic"] = None
335
- total_frames_collected += 1
336
-
337
- # Проверка, пора ли завершить текущий эпизод
338
- if (time.time() - current_episode_start_time) >= episode_duration_seconds:
339
- if len(all_images_generic) > 0:
340
- print(f"Собрано {len(all_images_generic)} шагов для эпизода {episode_idx:06d}. Сохраняю...")
341
-
342
- # --- Создание структуры папок для видео ---
343
- chunk_video_dir = VIDEOS_DIR / chunk_name
344
- generic_video_dir = chunk_video_dir / "observation.images.generic"
345
- os.makedirs(generic_video_dir, exist_ok=True)
346
-
347
- def create_video(frames, video_path):
348
- if not frames: return
349
- height, width, layers = frames[0].shape
350
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
351
- video_writer = cv2.VideoWriter(str(video_path), fourcc, 30.0, (width, height))
352
- for img in frames:
353
- img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
354
- video_writer.write(img_bgr)
355
- video_writer.release()
356
- print(f"Видеофайл успешно создан: {video_path}")
357
-
358
- try:
359
- video_path_generic = generic_video_dir / f"episode_{episode_idx:06d}.mp4"
360
- create_video(all_images_generic, video_path_generic)
361
- except Exception as e:
362
- print(f"Ошибка при создании видеофайла: {e}")
363
- return
364
-
365
- try:
366
- episode_data_dir = DATA_DIR / chunk_name
367
- os.makedirs(episode_data_dir, exist_ok=True)
368
-
369
- df = pd.DataFrame({
370
- 'observation.images.generic': [f"../../videos/{chunk_name}/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
371
- 'observation.joint_positions': all_joint_positions,
372
- 'observation.imu': all_imu_data,
373
- 'action.servo_commands': all_actions,
374
- 'timestamp': all_timestamps,
375
- 'frame_index': list(range(len(all_images_generic))),
376
- 'episode_index': [episode_idx] * len(all_images_generic),
377
- })
378
-
379
- table = pa.Table.from_pandas(df)
380
- parquet_path = episode_data_dir / f"episode_{episode_idx:06d}.parquet"
381
- pq.write_table(table, str(parquet_path))
382
- print(f"Parquet-файл {parquet_path.name} успешно создан.")
383
- except Exception as e:
384
- print(f"Ошибка при сохранении данных в Parquet: {e}")
385
- return
386
-
387
- # --- Обновление метаданных ---
388
- info['total_episodes'] += 1
389
- info['total_frames'] += len(all_images_generic)
390
- info['episode_lengths'].append(len(all_images_generic))
391
-
392
- episodes_data.append({
393
- "episode_index": episode_idx,
394
- "tasks": [tasks_list[0]],
395
- "length": len(all_images_generic)
396
- })
397
- create_episodes_file(META_DIR, episodes_data)
398
-
399
- create_readme(REPO_ID, info, META_DIR)
400
-
401
- # Подготовка к новому эпизоду
402
- episode_idx += 1
403
- current_episode_start_time = time.time()
404
- all_images_generic = []
405
- all_joint_positions = []
406
- all_imu_data = []
407
- all_timestamps = []
408
- all_actions = []
409
-
410
- time.sleep(0.01) # Небольшая задержка, чтобы не нагружать процессор
411
- except Exception as e:
412
- print(f"Произошла непредвиденная ошибка в основном цикле: {e}")
413
- finally:
414
- print("\nЗавершение сбора данных...")
415
-
416
- # Сохранение последнего незавершенного эпизода
417
- if len(all_images_generic) > 0:
418
- print(f"Собрано {len(all_images_generic)} шагов для последнего эпизода {episode_idx:06d}. Сохраняю...")
419
-
420
- chunk_video_dir = VIDEOS_DIR / chunk_name
421
- generic_video_dir = chunk_video_dir / "observation.images.generic"
422
- os.makedirs(generic_video_dir, exist_ok=True)
423
- video_path_generic = generic_video_dir / f"episode_{episode_idx:06d}.mp4"
424
-
425
- def create_video(frames, video_path):
426
- if not frames: return
427
- height, width, layers = frames[0].shape
428
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
429
- video_writer = cv2.VideoWriter(str(video_path), fourcc, 30.0, (width, height))
430
- for img in frames:
431
- img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
432
- video_writer.write(img_bgr)
433
- video_writer.release()
434
- print(f"Видеофайл успешно создан: {video_path}")
435
-
436
- create_video(all_images_generic, video_path_generic)
437
-
438
- episode_data_dir = DATA_DIR / chunk_name
439
- os.makedirs(episode_data_dir, exist_ok=True)
440
-
441
- df = pd.DataFrame({
442
- 'observation.images.generic': [f"../../videos/{chunk_name}/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
443
- 'observation.joint_positions': all_joint_positions,
444
- 'observation.imu': all_imu_data,
445
- 'action.servo_commands': all_actions,
446
- 'timestamp': all_timestamps,
447
- 'frame_index': list(range(len(all_images_generic))),
448
- 'episode_index': [episode_idx] * len(all_images_generic),
449
- })
450
-
451
- table = pa.Table.from_pandas(df)
452
- parquet_path = episode_data_dir / f"episode_{episode_idx:06d}.parquet"
453
- pq.write_table(table, str(parquet_path))
454
- print(f"Parquet-файл {parquet_path.name} успешно создан.")
455
-
456
- info['total_episodes'] += 1
457
- info['total_frames'] += len(all_images_generic)
458
- info['episode_lengths'].append(len(all_images_generic))
459
-
460
- episodes_data.append({
461
- "episode_index": episode_idx,
462
- "tasks": [tasks_list[0]],
463
- "length": len(all_images_generic)
464
- })
465
- create_episodes_file(META_DIR, episodes_data)
466
-
467
- ws_manager.terminate()
468
-
469
- # Обновление финальных метаданных
470
- with open(info_path, 'w') as f:
471
- json.dump(info, f, indent=2)
472
- print("info.json успешно обновлен.")
473
-
474
- create_readme(REPO_ID, info, META_DIR)
475
-
476
- if info["total_frames"] == 0:
477
- print("Данные не были собраны. Выход.")
478
- return
479
-
480
- # --- Загрузка всех файлов на Hugging Face Hub ---
481
- try:
482
- token = HfFolder.get_token()
483
- if token is None:
484
- print("Пожалуйста, выполните команду 'huggingface-cli login' для аутентификации.")
485
- return
486
-
487
- api = HfApi()
488
-
489
- create_repo(REPO_ID, repo_type="dataset", exist_ok=True)
490
-
491
- print(f"Загрузка локальной директории (meta, data, videos) на Hugging Face Hub...")
492
-
493
- api.upload_folder(
494
- folder_path=str(LOCAL_ROOT_DIR),
495
- repo_id=REPO_ID,
496
- repo_type="dataset",
497
- commit_message=f"Загрузка {info['total_episodes']} эпизодов",
498
- ignore_patterns=["__pycache__", "*.pyc", ".git"]
499
- )
500
-
501
- print(f"Данные успешно загружены: https://huggingface.co/datasets/{REPO_ID}")
502
- except Exception as e:
503
- print(f"Ошибка при загрузке данных: {e}")
504
-
505
- if __name__ == "__main__":
506
- collect_data_and_save()