KillzoneCC commited on
Commit ·
67c146f
1
Parent(s): 1353d99
Амбец
Browse files- collect_and_upload.py +210 -404
collect_and_upload.py
CHANGED
|
@@ -1,18 +1,16 @@
|
|
| 1 |
import os
|
| 2 |
-
import time
|
| 3 |
-
import json
|
| 4 |
-
import base64
|
| 5 |
-
import signal
|
| 6 |
import threading
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
import pandas as pd
|
|
|
|
| 10 |
import pyarrow as pa
|
| 11 |
import pyarrow.parquet as pq
|
| 12 |
-
import
|
| 13 |
import roslibpy
|
| 14 |
-
from huggingface_hub import HfApi, create_repo
|
| 15 |
-
import wandb
|
| 16 |
|
| 17 |
# --- Глобальный флаг для управления основным циклом ---
|
| 18 |
running = True
|
|
@@ -20,49 +18,37 @@ running = True
|
|
| 20 |
# --- Обработчик сигнала для корректного завершения (Ctrl+C) ---
|
| 21 |
def signal_handler(sig, frame):
|
| 22 |
global running
|
| 23 |
-
print("\nПолучен сигнал завершения
|
| 24 |
running = False
|
| 25 |
|
| 26 |
signal.signal(signal.SIGINT, signal_handler)
|
| 27 |
|
| 28 |
-
# --- Настройки ---
|
| 29 |
-
ROSBRIDGE_IP = "192.168.20.97"
|
| 30 |
ROSBRIDGE_PORT = 9090
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
REPO_ID = "KillzoneCCO/Ainex" # Замените на ваше имя пользователя/репозиторий
|
| 34 |
-
LOCAL_ROOT_DIR = Path("./ainex_dataset_lerobot_format_v2") # Новая папка для нового формата
|
| 35 |
|
| 36 |
# --- ROS Топики и типы сообщений для сбора данных ---
|
| 37 |
-
# Observation topics (то, что мы наблюдаем)
|
| 38 |
OBSERVATION_TOPICS = {
|
| 39 |
-
"
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
},
|
| 43 |
-
"imu": {
|
| 44 |
-
"topic": "/imu",
|
| 45 |
-
"msg_type": "sensor_msgs/Imu"
|
| 46 |
-
},
|
| 47 |
-
# observation.state (например, /joint_states) НЕ собираем, так как нет топика
|
| 48 |
}
|
| 49 |
|
| 50 |
-
# Action topics (то, что мы отправляем)
|
| 51 |
ACTION_TOPICS = {
|
| 52 |
-
"
|
| 53 |
-
|
| 54 |
-
"msg_type": "ros_robot_controller/SetBusServosPosition"
|
| 55 |
-
},
|
| 56 |
-
# Добавляем joy, если он используется
|
| 57 |
-
# "joy": {
|
| 58 |
-
# "topic": "/joy",
|
| 59 |
-
# "msg_type": "sensor_msgs/Joy"
|
| 60 |
-
# },
|
| 61 |
}
|
| 62 |
|
| 63 |
# --- Глобальные переменные для хранения последних данных ---
|
| 64 |
-
latest_data = {
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
data_lock = threading.Lock()
|
| 67 |
|
| 68 |
# --- Менеджер соединения ROSBridge ---
|
|
@@ -74,26 +60,19 @@ class ROSBridgeManager:
|
|
| 74 |
self.connected = False
|
| 75 |
self._subscriptions = []
|
| 76 |
|
| 77 |
-
def connect(self
|
| 78 |
-
print(
|
| 79 |
try:
|
| 80 |
-
self.client.run(
|
| 81 |
self.connected = True
|
| 82 |
print('ROSBridge: Подключено!')
|
| 83 |
return True
|
| 84 |
-
except roslibpy.core.RosTimeoutError as e:
|
| 85 |
-
print(f"ROSBridge: Таймаут подключения: {e}")
|
| 86 |
-
self.connected = False
|
| 87 |
-
return False
|
| 88 |
except Exception as e:
|
| 89 |
print(f"ROSBridge: Ошибка подключения: {e}")
|
| 90 |
self.connected = False
|
| 91 |
return False
|
| 92 |
|
| 93 |
def subscribe(self, topic_name, message_type, callback):
|
| 94 |
-
if not self.connected:
|
| 95 |
-
print(f"Предупреждение: Невозможно подписаться на {topic_name}, клиент не подключен.")
|
| 96 |
-
return
|
| 97 |
listener = roslibpy.Topic(self.client, topic_name, message_type)
|
| 98 |
listener.subscribe(callback)
|
| 99 |
print(f"Подписан на {topic_name} ({message_type})")
|
|
@@ -112,210 +91,200 @@ class ROSBridgeManager:
|
|
| 112 |
self.client.terminate()
|
| 113 |
self.connected = False
|
| 114 |
|
| 115 |
-
# --- Callback-функции ��ля получения данных ---
|
| 116 |
def create_image_callback(camera_key):
|
| 117 |
def callback(message):
|
| 118 |
-
global latest_data, latest_timestamp
|
| 119 |
with data_lock:
|
| 120 |
try:
|
| 121 |
-
|
| 122 |
-
np_arr = np.frombuffer(base64.b64decode(message['data']), np.uint8)
|
| 123 |
-
else: # Предполагаем bytes
|
| 124 |
-
np_arr = np.frombuffer(message['data'], np.uint8)
|
| 125 |
-
|
| 126 |
channels = 3 if 'rgb' in message['encoding'] or 'bgr' in message['encoding'] else 1
|
| 127 |
img_np = np_arr.reshape((message['height'], message['width'], channels))
|
| 128 |
if 'bgr' in message['encoding']:
|
| 129 |
img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
|
| 130 |
|
| 131 |
-
# PIL Image ожидает uint8
|
| 132 |
-
if img_np.dtype != np.uint8:
|
| 133 |
-
if img_np.dtype == np.uint16:
|
| 134 |
-
img_np = (img_np / 256).astype(np.uint8)
|
| 135 |
-
else:
|
| 136 |
-
img_min, img_max = img_np.min(), img_np.max()
|
| 137 |
-
if img_max > img_min:
|
| 138 |
-
img_np = ((img_np - img_min) / (img_max - img_min) * 255).astype(np.uint8)
|
| 139 |
-
else:
|
| 140 |
-
img_np = np.zeros_like(img_np, dtype=np.uint8)
|
| 141 |
-
|
| 142 |
latest_data[camera_key] = (img_np, time.time())
|
| 143 |
-
latest_timestamp = time.time()
|
| 144 |
except Exception as e:
|
| 145 |
print(f"DEBUG: Ошибка обработки изображения с {camera_key}: {e}")
|
| 146 |
latest_data[camera_key] = None
|
| 147 |
-
latest_timestamp = time.time()
|
| 148 |
return callback
|
| 149 |
|
| 150 |
def imu_callback(message):
|
| 151 |
-
global latest_data, latest_timestamp
|
| 152 |
with data_lock:
|
| 153 |
try:
|
| 154 |
-
# Предполагаем, что IMU имеет стандартную структуру sensor_msgs/Imu
|
| 155 |
imu_data = np.array([
|
| 156 |
message['orientation']['x'], message['orientation']['y'], message['orientation']['z'], message['orientation']['w'],
|
| 157 |
message['angular_velocity']['x'], message['angular_velocity']['y'], message['angular_velocity']['z'],
|
| 158 |
message['linear_acceleration']['x'], message['linear_acceleration']['y'], message['linear_acceleration']['z']
|
| 159 |
], dtype=np.float32)
|
| 160 |
latest_data["imu"] = (imu_data, time.time())
|
| 161 |
-
latest_timestamp = time.time()
|
| 162 |
except Exception as e:
|
| 163 |
print(f"DEBUG: Ошибка обработки IMU: {e}")
|
| 164 |
latest_data["imu"] = None
|
| 165 |
-
latest_timestamp = time.time()
|
| 166 |
|
| 167 |
-
|
| 168 |
-
def joint_positions_action_callback(message):
|
| 169 |
-
global latest_data, latest_timestamp
|
| 170 |
with data_lock:
|
| 171 |
try:
|
| 172 |
-
# Предполагаем, что сообщение имеет структуру ros_robot_controller/SetBusServosPosition
|
| 173 |
-
# с полем "position", содержащим список словарей {"id": int, "position": float}
|
| 174 |
if "position" in message and isinstance(message["position"], list):
|
| 175 |
-
temp_joint_positions = np.array([0.0] * 26, dtype=np.float32)
|
| 176 |
for item in message["position"]:
|
| 177 |
if isinstance(item, dict) and "id" in item and "position" in item:
|
| 178 |
servo_id = int(item["id"])
|
| 179 |
-
# Проверяем, что ID сервопривода находится в допустимом диапазоне
|
| 180 |
if 1 <= servo_id <= 26:
|
| 181 |
temp_joint_positions[servo_id - 1] = float(item["position"])
|
| 182 |
-
latest_data["
|
| 183 |
-
latest_timestamp = time.time()
|
| 184 |
-
else:
|
| 185 |
-
print(f"DEBUG_CALLBACK: Неожиданный формат сообщения команд сервоприводов: {message}")
|
| 186 |
except Exception as e:
|
| 187 |
-
print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения
|
| 188 |
-
latest_data["
|
| 189 |
-
latest_timestamp = time.time()
|
| 190 |
-
|
| 191 |
-
# --- Функции для создания мета-файлов ---
|
| 192 |
-
def create_info_file(META_DIR, info):
|
| 193 |
-
"""Создает или обновляет meta/info.json."""
|
| 194 |
-
info_path = META_DIR / "info.json"
|
| 195 |
-
with open(info_path, 'w') as f:
|
| 196 |
-
json.dump(info, f, indent=2)
|
| 197 |
-
print(f"Создан/обновлен файл {info_path}")
|
| 198 |
-
|
| 199 |
-
def create_config_file(META_DIR, repo_id):
|
| 200 |
-
"""Создает meta/config.yaml, соответствующий структуре данных."""
|
| 201 |
-
config_path = META_DIR / "config.yaml"
|
| 202 |
-
dataset_name = repo_id.split('/')[1] if '/' in repo_id else repo_id
|
| 203 |
-
# Конфигурация для загрузчика видео
|
| 204 |
-
config_content = f"""\
|
| 205 |
-
task_name: ainex-robot-collection
|
| 206 |
-
dataset_id: {dataset_name}
|
| 207 |
-
features:
|
| 208 |
-
observation.images.generic:
|
| 209 |
-
video_loader:
|
| 210 |
-
_target_: lerobot.common.datasets.video_utils.VideoLoader
|
| 211 |
-
framerate: 30
|
| 212 |
-
"""
|
| 213 |
-
with open(config_path, 'w') as f:
|
| 214 |
-
f.write(config_content.strip())
|
| 215 |
-
print(f"Создан файл {config_path} с настройками video_loader.")
|
| 216 |
|
| 217 |
-
def
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
def create_readme(repo_id, info, root_dir):
|
| 233 |
-
"""Создает базовый README.md."""
|
| 234 |
readme_path = os.path.join(root_dir, "README.md")
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
-
|
| 246 |
-
- `observation.images.generic`: Camera feed (video)
|
| 247 |
-
- `observation.imu`: Inertial Measurement Unit data
|
| 248 |
-
- `observation.joint_positions`: Joint positions (from actions)
|
| 249 |
-
- `action.servo_commands`: Servo commands sent to the robot
|
| 250 |
-
- `timestamp`: Timestamp of the observation/action
|
| 251 |
-
- `frame_index`: Index of the frame within the episode
|
| 252 |
-
- `episode_index`: Index of the episode
|
| 253 |
|
| 254 |
-
**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
"""
|
| 256 |
-
with open(readme_path, 'w') as f:
|
| 257 |
-
f.write(
|
| 258 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
# --- Основная функция сбора данных ---
|
| 261 |
def collect_data_and_save():
|
| 262 |
-
global running
|
| 263 |
-
|
| 264 |
-
# Инициализация WandB
|
| 265 |
-
print("Инициализация WandB...")
|
| 266 |
-
wandb.init(project="ainex-robot-data-collection", name=f"run-{int(time.time())}")
|
| 267 |
|
| 268 |
-
# Создание
|
| 269 |
-
os.makedirs(LOCAL_ROOT_DIR, exist_ok=True)
|
| 270 |
META_DIR = LOCAL_ROOT_DIR / "meta"
|
| 271 |
-
DATA_DIR = LOCAL_ROOT_DIR / "data"
|
| 272 |
-
VIDEOS_DIR = LOCAL_ROOT_DIR / "videos"
|
|
|
|
| 273 |
os.makedirs(META_DIR, exist_ok=True)
|
| 274 |
os.makedirs(DATA_DIR, exist_ok=True)
|
| 275 |
os.makedirs(VIDEOS_DIR, exist_ok=True)
|
| 276 |
-
|
| 277 |
-
# --- Инициализация мета-информации ---
|
| 278 |
info_path = META_DIR / "info.json"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
if info_path.exists():
|
| 280 |
try:
|
| 281 |
with open(info_path, 'r') as f:
|
| 282 |
info = json.load(f)
|
| 283 |
-
|
|
|
|
|
|
|
| 284 |
except json.JSONDecodeError:
|
| 285 |
print(f"Предупреждение: Файл '{info_path}' поврежден или пуст. Создаю новый.")
|
| 286 |
if info_path.exists():
|
| 287 |
os.remove(info_path)
|
| 288 |
-
|
| 289 |
-
else:
|
| 290 |
-
info = None
|
| 291 |
-
|
| 292 |
if not info:
|
| 293 |
-
#
|
| 294 |
info = {
|
| 295 |
-
"codebase_version": "v1.
|
| 296 |
"total_frames": 0,
|
| 297 |
"total_episodes": 0,
|
| 298 |
"episode_lengths": [],
|
| 299 |
"fps": 30,
|
| 300 |
-
"robot_type": "
|
| 301 |
-
|
| 302 |
-
"
|
| 303 |
-
"video_path": "videos/episode_{episode_index:06d}.mp4",
|
| 304 |
-
# Описание структуры данных (features)
|
| 305 |
"features": {
|
| 306 |
"action": {
|
| 307 |
"servo_commands": { "dtype": "float32", "shape": [26] },
|
| 308 |
-
# "joy": { "dtype": "float32", "shape": [10] } # Раскомментируйте, если добавите joy
|
| 309 |
},
|
| 310 |
"observation": {
|
| 311 |
-
"
|
|
|
|
|
|
|
| 312 |
"dtype": "video",
|
| 313 |
"media_type": "video/mp4",
|
| 314 |
-
"path_format": "videos/episode_{episode_index:06d}.mp4",
|
| 315 |
-
"shape": [480, 640, 3]
|
| 316 |
-
}
|
| 317 |
-
"joint_positions": { "dtype": "float32", "shape": [26] }, # Используем action как proxy
|
| 318 |
-
"imu": { "dtype": "float32", "shape": [10] }
|
| 319 |
},
|
| 320 |
"timestamp": { "dtype": "float64" },
|
| 321 |
"frame_index": { "dtype": "int64" },
|
|
@@ -323,295 +292,132 @@ def collect_data_and_save():
|
|
| 323 |
}
|
| 324 |
}
|
| 325 |
|
| 326 |
-
# Загрузка списка эпизодов
|
| 327 |
-
episodes_jsonl_path = META_DIR / "episodes.jsonl"
|
| 328 |
-
episodes_data = []
|
| 329 |
if episodes_jsonl_path.exists():
|
| 330 |
try:
|
| 331 |
with open(episodes_jsonl_path, 'r', encoding='utf-8') as f:
|
| 332 |
for line in f:
|
| 333 |
episodes_data.append(json.loads(line))
|
| 334 |
-
print(f"Загружен список эпизодов из {episodes_jsonl_path}")
|
| 335 |
except json.JSONDecodeError:
|
| 336 |
print(f"Предупреждение: Файл '{episodes_jsonl_path}' поврежден или пуст. Создаю новый.")
|
| 337 |
episodes_data = []
|
| 338 |
if episodes_jsonl_path.exists():
|
| 339 |
os.remove(episodes_jsonl_path)
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
# --- Подключение к ROS и подписка на топики ---
|
| 350 |
ws_manager = ROSBridgeManager(ROSBRIDGE_IP, ROSBRIDGE_PORT)
|
| 351 |
if not ws_manager.connect():
|
| 352 |
print("ROSBridge: Невозможно продолжить без подключения. Завершение работы.")
|
| 353 |
-
wandb.finish()
|
| 354 |
return
|
| 355 |
|
| 356 |
print("Установка подписок...")
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
ws_manager.subscribe(obs_info["topic"], obs_info["msg_type"], imu_callback)
|
| 363 |
-
# observation.state не подписываемся, так как топика нет
|
| 364 |
-
|
| 365 |
-
# Подписываемся на топики действий
|
| 366 |
-
for act_key, act_info in ACTION_TOPICS.items():
|
| 367 |
-
if act_key == "servo_commands":
|
| 368 |
-
ws_manager.subscribe(act_info["topic"], act_info["msg_type"], joint_positions_action_callback)
|
| 369 |
-
# elif act_key == "joy":
|
| 370 |
-
# ws_manager.subscribe(act_info["topic"], act_info["msg_type"], joy_callback)
|
| 371 |
-
|
| 372 |
print("Подписки установлены.")
|
| 373 |
-
print("Сбор данных запущен. Выпо
|
| 374 |
print("Нажмите 'Ctrl+C' для завершения и сохранения датасета.")
|
| 375 |
-
|
| 376 |
-
# --- Параметры сбора ---
|
| 377 |
-
episode_duration_seconds = 5.0 # Длительность одного эпизода в секундах
|
| 378 |
current_episode_start_time = time.time()
|
| 379 |
-
|
| 380 |
-
# --- Списки для накопления данных текущего эпизода ---
|
| 381 |
all_images_generic = []
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
|
|
|
| 385 |
all_timestamps = []
|
| 386 |
all_frame_indices = []
|
| 387 |
-
|
| 388 |
total_frames_collected = 0
|
| 389 |
-
total_episodes_saved = 0
|
| 390 |
-
|
| 391 |
try:
|
| 392 |
while running:
|
| 393 |
with data_lock:
|
| 394 |
-
|
| 395 |
-
new_image_generic_data = latest_data.get("images.generic")
|
| 396 |
-
|
| 397 |
if new_image_generic_data is not None:
|
| 398 |
img_generic, img_timestamp = new_image_generic_data
|
| 399 |
|
| 400 |
-
# Получение д
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
joint_positions_action_data = joint_positions_action_tuple[0] if joint_positions_action_tuple is not None else np.array([0.0]*26, dtype=np.float32)
|
| 406 |
-
|
| 407 |
-
# joy_data_tuple = latest_data.get("joy")
|
| 408 |
-
# joy_data = joy_data_tuple[0] if joy_data_tuple is not None else np.array([0.0]*10, dtype=np.float32) # Пример
|
| 409 |
-
|
| 410 |
-
# Накапливаем данные
|
| 411 |
all_images_generic.append(img_generic)
|
|
|
|
| 412 |
all_imu_data.append(imu_data.tolist())
|
| 413 |
all_joint_positions_action.append(joint_positions_action_data.tolist())
|
| 414 |
-
# all_joy_data.append(joy_data.tolist()) # Если добавите joy
|
| 415 |
all_timestamps.append(img_timestamp)
|
| 416 |
all_frame_indices.append(len(all_images_generic) - 1)
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
latest_data["images.generic"] = None
|
| 420 |
total_frames_collected += 1
|
| 421 |
-
|
| 422 |
-
# Проверяем, пора ли завершить текущий эпизод
|
| 423 |
if (time.time() - current_episode_start_time) >= episode_duration_seconds:
|
| 424 |
if len(all_images_generic) > 0:
|
| 425 |
-
print(f"
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
video_path = VIDEOS_DIR / f"episode_{episode_idx:06d}.mp4"
|
| 429 |
-
if all_images_generic:
|
| 430 |
-
# Определяем размеры из первого кадра
|
| 431 |
-
frame_height, frame_width, _ = all_images_generic[0].shape
|
| 432 |
-
# Создаем видео писатель
|
| 433 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 434 |
-
fps = info["fps"]
|
| 435 |
-
video_writer = cv2.VideoWriter(str(video_path), fourcc, fps, (frame_width, frame_height))
|
| 436 |
-
if not video_writer.isOpened():
|
| 437 |
-
print(f"Ошибка: Не удалось создать видеофайл {video_path}")
|
| 438 |
-
else:
|
| 439 |
-
for frame in all_images_generic:
|
| 440 |
-
# OpenCV ожидает BGR
|
| 441 |
-
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
| 442 |
-
video_writer.write(frame_bgr)
|
| 443 |
-
video_writer.release()
|
| 444 |
-
print(f"Видео {video_path.name} успешно создано.")
|
| 445 |
-
else:
|
| 446 |
-
print(f"Предупреждение: Эпизод {episode_idx} не содержит изображений, видео не создано.")
|
| 447 |
-
|
| 448 |
-
# --- 2. Создание Parquet-файла ---
|
| 449 |
-
# В Parquet мы сохраняем путь к видео, а не сами изображения
|
| 450 |
-
video_path_str = f"videos/episode_{episode_idx:06d}.mp4" # Относительный путь
|
| 451 |
|
|
|
|
| 452 |
df = pd.DataFrame({
|
| 453 |
-
'observation.images.generic': [
|
| 454 |
-
'observation.joint_positions':
|
| 455 |
'observation.imu': all_imu_data,
|
| 456 |
-
'action.servo_commands': all_joint_positions_action,
|
| 457 |
-
# 'action.joy': all_joy_data, # Если добавите joy
|
| 458 |
'timestamp': all_timestamps,
|
| 459 |
'frame_index': all_frame_indices,
|
| 460 |
'episode_index': [episode_idx] * len(all_images_generic),
|
| 461 |
})
|
| 462 |
-
|
| 463 |
-
# Явно указываем схему PyArrow для соответствия features в info.json
|
| 464 |
-
# Это помогает избежать ошибок каста
|
| 465 |
-
schema = pa.schema([
|
| 466 |
-
('observation.images.generic', pa.string()), # Путь к видео
|
| 467 |
-
('observation.joint_positions', pa.list_(pa.float32(), 26)), # Список из 26 float32
|
| 468 |
-
('observation.imu', pa.list_(pa.float32(), 10)), # Список из 10 float32
|
| 469 |
-
('action.servo_commands', pa.list_(pa.float32(), 26)), # Список из 26 float32
|
| 470 |
-
# ('action.joy', pa.list_(pa.float32(), 10)), # Если добавите joy
|
| 471 |
-
('timestamp', pa.float64()),
|
| 472 |
-
('frame_index', pa.int64()),
|
| 473 |
-
('episode_index', pa.int64()),
|
| 474 |
-
])
|
| 475 |
|
| 476 |
-
|
| 477 |
-
table = pa.Table.from_pandas(df, schema=schema)
|
| 478 |
-
except pa.lib.ArrowInvalid as e:
|
| 479 |
-
print(f"Ошибка при создании таблицы PyArrow с явной схемой: {e}")
|
| 480 |
-
print("Попытка создания таблицы без явной схемы...")
|
| 481 |
-
table = pa.Table.from_pandas(df) # fallback
|
| 482 |
-
|
| 483 |
parquet_path = DATA_DIR / f"episode_{episode_idx:06d}.parquet"
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
print(f"Ошибка при записи Parquet-файла {parquet_path}: {e}")
|
| 489 |
-
# Продолжаем, чтобы не потерять другие данные
|
| 490 |
-
|
| 491 |
-
# --- 3. Обновление мета-информации ---
|
| 492 |
-
info['total_episodes'] = episode_idx + 1
|
| 493 |
info['total_frames'] += len(all_images_generic)
|
| 494 |
info['episode_lengths'].append(len(all_images_generic))
|
| 495 |
|
|
|
|
|
|
|
|
|
|
| 496 |
episodes_data.append({
|
| 497 |
"episode_index": episode_idx,
|
| 498 |
-
"
|
| 499 |
-
"
|
| 500 |
})
|
| 501 |
-
|
| 502 |
-
# Сохраняем мета-файлы
|
| 503 |
-
create_info_file(META_DIR, info)
|
| 504 |
create_episodes_file(META_DIR, episodes_data)
|
| 505 |
-
|
| 506 |
-
create_tasks_file(META_DIR, tasks_list)
|
| 507 |
-
|
| 508 |
-
total_episodes_saved += 1
|
| 509 |
-
episode_idx += 1
|
| 510 |
-
current_episode_start_time = time.time()
|
| 511 |
-
|
| 512 |
-
# Очищаем списки для следующего эпизода
|
| 513 |
all_images_generic = []
|
|
|
|
| 514 |
all_imu_data = []
|
| 515 |
all_joint_positions_action = []
|
| 516 |
-
|
| 517 |
all_timestamps = []
|
| 518 |
all_frame_indices = []
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
|
|
|
| 523 |
|
| 524 |
except Exception as e:
|
| 525 |
-
print(f"Произошла
|
| 526 |
-
import traceback
|
| 527 |
-
traceback.print_exc()
|
| 528 |
-
|
| 529 |
finally:
|
| 530 |
-
print("\n
|
| 531 |
-
# Сохраняем незавершенный эпизод, если он содержит данные
|
| 532 |
-
if len(all_images_generic) > 0:
|
| 533 |
-
print(f"Сохраняю незавершенный эпизод {episode_idx} с {len(all_images_generic)} кадрами...")
|
| 534 |
-
# --- 1. Создание видео для незавершенного эпизода ---
|
| 535 |
-
video_path = VIDEOS_DIR / f"episode_{episode_idx:06d}.mp4"
|
| 536 |
-
if all_images_generic:
|
| 537 |
-
frame_height, frame_width, _ = all_images_generic[0].shape
|
| 538 |
-
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 539 |
-
fps = info["fps"]
|
| 540 |
-
video_writer = cv2.VideoWriter(str(video_path), fourcc, fps, (frame_width, frame_height))
|
| 541 |
-
if video_writer.isOpened():
|
| 542 |
-
for frame in all_images_generic:
|
| 543 |
-
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
| 544 |
-
video_writer.write(frame_bgr)
|
| 545 |
-
video_writer.release()
|
| 546 |
-
print(f"Видео {video_path.name} для незавершенного эпизода успешно создано.")
|
| 547 |
-
else:
|
| 548 |
-
print(f"Ошибка: Не удалось создать видеофайл {video_path} для незавершенного эпизода.")
|
| 549 |
-
|
| 550 |
-
# --- 2. Создание Parquet-файла для незавершенного эпизода ---
|
| 551 |
-
video_path_str = f"videos/episode_{episode_idx:06d}.mp4"
|
| 552 |
-
df = pd.DataFrame({
|
| 553 |
-
'observation.images.generic': [video_path_str] * len(all_images_generic),
|
| 554 |
-
'observation.joint_positions': all_joint_positions_action,
|
| 555 |
-
'observation.imu': all_imu_data,
|
| 556 |
-
'action.servo_commands': all_joint_positions_action,
|
| 557 |
-
# 'action.joy': all_joy_data, # Если добавите joy
|
| 558 |
-
'timestamp': all_timestamps,
|
| 559 |
-
'frame_index': all_frame_indices,
|
| 560 |
-
'episode_index': [episode_idx] * len(all_images_generic),
|
| 561 |
-
})
|
| 562 |
-
|
| 563 |
-
schema = pa.schema([
|
| 564 |
-
('observation.images.generic', pa.string()),
|
| 565 |
-
('observation.joint_positions', pa.list_(pa.float32(), 26)),
|
| 566 |
-
('observation.imu', pa.list_(pa.float32(), 10)),
|
| 567 |
-
('action.servo_commands', pa.list_(pa.float32(), 26)),
|
| 568 |
-
# ('action.joy', pa.list_(pa.float32(), 10)), # Если добавите joy
|
| 569 |
-
('timestamp', pa.float64()),
|
| 570 |
-
('frame_index', pa.int64()),
|
| 571 |
-
('episode_index', pa.int64()),
|
| 572 |
-
])
|
| 573 |
-
|
| 574 |
-
try:
|
| 575 |
-
table = pa.Table.from_pandas(df, schema=schema)
|
| 576 |
-
except pa.lib.ArrowInvalid as e:
|
| 577 |
-
print(f"Ошибка при создании таблицы PyArrow для незавершенного эпизода: {e}")
|
| 578 |
-
table = pa.Table.from_pandas(df)
|
| 579 |
-
|
| 580 |
-
parquet_path = DATA_DIR / f"episode_{episode_idx:06d}.parquet"
|
| 581 |
-
try:
|
| 582 |
-
pq.write_table(table, str(parquet_path))
|
| 583 |
-
print(f"Parquet-файл {parquet_path.name} для незавершенного эпизода успешно создан.")
|
| 584 |
-
except Exception as e:
|
| 585 |
-
print(f"Ошибка при записи Parquet-файла {parquet_path} для незавершенного эпизода: {e}")
|
| 586 |
-
|
| 587 |
-
# --- 3. Обновление мета-информации для незавершенного эпизода ---
|
| 588 |
-
info['total_episodes'] = episode_idx + 1
|
| 589 |
-
info['total_frames'] += len(all_images_generic)
|
| 590 |
-
info['episode_lengths'].append(len(all_images_generic))
|
| 591 |
-
|
| 592 |
-
episodes_data.append({
|
| 593 |
-
"episode_index": episode_idx,
|
| 594 |
-
"tasks": [{"task_index": 0}],
|
| 595 |
-
"length": len(all_images_generic)
|
| 596 |
-
})
|
| 597 |
-
|
| 598 |
-
create_info_file(META_DIR, info)
|
| 599 |
-
create_episodes_file(META_DIR, episodes_data)
|
| 600 |
-
create_readme(REPO_ID, info, LOCAL_ROOT_DIR)
|
| 601 |
-
create_tasks_file(META_DIR, tasks_list)
|
| 602 |
-
total_episodes_saved += 1
|
| 603 |
-
print(f"Незавершенный эпизод {episode_idx} сохранен.")
|
| 604 |
-
|
| 605 |
-
# Завершаем подключение к ROS
|
| 606 |
ws_manager.terminate()
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
if total_episodes_saved > 0:
|
| 610 |
-
print(f"Сбор данных завершен. Сохранено {total_episodes_saved} эпизодов в '{LOCAL_ROOT_DIR}'.")
|
| 611 |
-
print("Теперь вы можете загрузить их на Hugging Face Hub вручную или с помощью скрипта.")
|
| 612 |
-
else:
|
| 613 |
-
print("Данные не были собраны или сохранены.")
|
| 614 |
-
|
| 615 |
|
| 616 |
if __name__ == "__main__":
|
| 617 |
collect_data_and_save()
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import threading
|
| 3 |
+
import signal
|
| 4 |
+
import base64
|
| 5 |
+
import cv2
|
| 6 |
+
import time
|
| 7 |
import numpy as np
|
| 8 |
import pandas as pd
|
| 9 |
+
import json
|
| 10 |
import pyarrow as pa
|
| 11 |
import pyarrow.parquet as pq
|
| 12 |
+
from pathlib import Path
|
| 13 |
import roslibpy
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# --- Глобальный флаг для управления основным циклом ---
|
| 16 |
running = True
|
|
|
|
| 18 |
# --- Обработчик сигнала для корректного завершения (Ctrl+C) ---
|
| 19 |
def signal_handler(sig, frame):
|
| 20 |
global running
|
| 21 |
+
print("\nПолучен сигнал завершения. Завершаю сбор данных...")
|
| 22 |
running = False
|
| 23 |
|
| 24 |
signal.signal(signal.SIGINT, signal_handler)
|
| 25 |
|
| 26 |
+
# --- Настройки ROSBridge ---
|
| 27 |
+
ROSBRIDGE_IP = "192.168.20.97"
|
| 28 |
ROSBRIDGE_PORT = 9090
|
| 29 |
+
REPO_ID = "KillzoneCCO/Ainex"
|
| 30 |
+
LOCAL_ROOT_DIR = Path("./")
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# --- ROS Топики и типы сообщений для сбора данных ---
|
|
|
|
| 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_obs": {"topic": "/ros_robot_controller/bus_servo/get_position", "msg_type": "ros_robot_controller/GetBusServosPosition"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
}
|
| 38 |
|
|
|
|
| 39 |
ACTION_TOPICS = {
|
| 40 |
+
"joint_positions_action": {"topic": "/ros_robot_controller/bus_servo/set_position", "msg_type": "ros_robot_controller/SetBusServosPosition"},
|
| 41 |
+
"joy": {"topic": "/joy", "msg_type": "sensor_msgs/Joy"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
|
| 44 |
# --- Глобальные переменные для хранения последних данных ---
|
| 45 |
+
latest_data = {
|
| 46 |
+
"camera_generic": None,
|
| 47 |
+
"imu": None,
|
| 48 |
+
"joint_positions_obs": None,
|
| 49 |
+
"joint_positions_action": None,
|
| 50 |
+
"joy": None,
|
| 51 |
+
}
|
| 52 |
data_lock = threading.Lock()
|
| 53 |
|
| 54 |
# --- Менеджер соединения ROSBridge ---
|
|
|
|
| 60 |
self.connected = False
|
| 61 |
self._subscriptions = []
|
| 62 |
|
| 63 |
+
def connect(self):
|
| 64 |
+
print('ROSBridge: Попытка подключения...')
|
| 65 |
try:
|
| 66 |
+
self.client.run()
|
| 67 |
self.connected = True
|
| 68 |
print('ROSBridge: Подключено!')
|
| 69 |
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
except Exception as e:
|
| 71 |
print(f"ROSBridge: Ошибка подключения: {e}")
|
| 72 |
self.connected = False
|
| 73 |
return False
|
| 74 |
|
| 75 |
def subscribe(self, topic_name, message_type, callback):
|
|
|
|
|
|
|
|
|
|
| 76 |
listener = roslibpy.Topic(self.client, topic_name, message_type)
|
| 77 |
listener.subscribe(callback)
|
| 78 |
print(f"Подписан на {topic_name} ({message_type})")
|
|
|
|
| 91 |
self.client.terminate()
|
| 92 |
self.connected = False
|
| 93 |
|
|
|
|
| 94 |
def create_image_callback(camera_key):
|
| 95 |
def callback(message):
|
|
|
|
| 96 |
with data_lock:
|
| 97 |
try:
|
| 98 |
+
np_arr = np.frombuffer(base64.b64decode(message['data']), np.uint8)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
channels = 3 if 'rgb' in message['encoding'] or 'bgr' in message['encoding'] else 1
|
| 100 |
img_np = np_arr.reshape((message['height'], message['width'], channels))
|
| 101 |
if 'bgr' in message['encoding']:
|
| 102 |
img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
latest_data[camera_key] = (img_np, time.time())
|
|
|
|
| 105 |
except Exception as e:
|
| 106 |
print(f"DEBUG: Ошибка обработки изображения с {camera_key}: {e}")
|
| 107 |
latest_data[camera_key] = None
|
|
|
|
| 108 |
return callback
|
| 109 |
|
| 110 |
def imu_callback(message):
|
|
|
|
| 111 |
with data_lock:
|
| 112 |
try:
|
|
|
|
| 113 |
imu_data = np.array([
|
| 114 |
message['orientation']['x'], message['orientation']['y'], message['orientation']['z'], message['orientation']['w'],
|
| 115 |
message['angular_velocity']['x'], message['angular_velocity']['y'], message['angular_velocity']['z'],
|
| 116 |
message['linear_acceleration']['x'], message['linear_acceleration']['y'], message['linear_acceleration']['z']
|
| 117 |
], dtype=np.float32)
|
| 118 |
latest_data["imu"] = (imu_data, time.time())
|
|
|
|
| 119 |
except Exception as e:
|
| 120 |
print(f"DEBUG: Ошибка обработки IMU: {e}")
|
| 121 |
latest_data["imu"] = None
|
|
|
|
| 122 |
|
| 123 |
+
def joint_positions_obs_callback(message):
|
|
|
|
|
|
|
| 124 |
with data_lock:
|
| 125 |
try:
|
|
|
|
|
|
|
| 126 |
if "position" in message and isinstance(message["position"], list):
|
| 127 |
+
temp_joint_positions = np.array([0.0] * 26, dtype=np.float32)
|
| 128 |
for item in message["position"]:
|
| 129 |
if isinstance(item, dict) and "id" in item and "position" in item:
|
| 130 |
servo_id = int(item["id"])
|
|
|
|
| 131 |
if 1 <= servo_id <= 26:
|
| 132 |
temp_joint_positions[servo_id - 1] = float(item["position"])
|
| 133 |
+
latest_data["joint_positions_obs"] = (temp_joint_positions, time.time())
|
|
|
|
|
|
|
|
|
|
| 134 |
except Exception as e:
|
| 135 |
+
print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")
|
| 136 |
+
latest_data["joint_positions_obs"] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
def joint_positions_action_callback(message):
|
| 139 |
+
with data_lock:
|
| 140 |
+
try:
|
| 141 |
+
if "position" in message and isinstance(message["position"], list):
|
| 142 |
+
temp_joint_positions = np.array([0.0] * 26, dtype=np.float32)
|
| 143 |
+
for item in message["position"]:
|
| 144 |
+
if isinstance(item, dict) and "id" in item and "position" in item:
|
| 145 |
+
servo_id = int(item["id"])
|
| 146 |
+
if 1 <= servo_id <= 26:
|
| 147 |
+
temp_joint_positions[servo_id - 1] = float(item["position"])
|
| 148 |
+
latest_data["joint_positions_action"] = (temp_joint_positions, time.time())
|
| 149 |
+
except Exception as e:
|
| 150 |
+
print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")
|
| 151 |
+
latest_data["joint_positions_action"] = None
|
| 152 |
+
|
| 153 |
+
def joy_callback(message):
|
| 154 |
+
with data_lock:
|
| 155 |
+
try:
|
| 156 |
+
joy_data = np.array(message['axes'] + message['buttons'], dtype=np.float32)
|
| 157 |
+
latest_data["joy"] = (joy_data, time.time())
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print(f"DEBUG: Ошибка обработки Joy: {e}")
|
| 160 |
+
latest_data["joy"] = None
|
| 161 |
|
| 162 |
def create_readme(repo_id, info, root_dir):
|
|
|
|
| 163 |
readme_path = os.path.join(root_dir, "README.md")
|
| 164 |
+
total_episodes = info.get("total_episodes", 0)
|
| 165 |
+
total_frames = info.get("total_frames", 0)
|
| 166 |
+
robot_type = info.get("robot_type", "unknown")
|
| 167 |
+
fps = info.get("fps", 0)
|
| 168 |
+
|
| 169 |
+
readme_content = f"""---
|
| 170 |
+
license: apache-2.0
|
| 171 |
+
task_categories:
|
| 172 |
+
- robotics
|
| 173 |
+
tags:
|
| 174 |
+
- LeRobot
|
| 175 |
+
configs:
|
| 176 |
+
- config_name: default
|
| 177 |
+
data_files: data/*/*.parquet
|
| 178 |
+
---
|
| 179 |
|
| 180 |
+
# Ainex Robot Dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
+
Этот датасет был собран с помощью робота **Ainex** для демонстрации его возможностей в рамках LeRobot.
|
| 183 |
+
## Статистика датасета
|
| 184 |
+
- **Общее количество эпизодов**: {total_episodes}
|
| 185 |
+
- **Общее количество кадров**: {total_frames}
|
| 186 |
+
- **Тип робота**: {robot_type}
|
| 187 |
+
- **Кадров в секунду (FPS)**: {fps}
|
| 188 |
+
|
| 189 |
+
## Структура датасета
|
| 190 |
+
- [meta/info.json](meta/info.json)
|
| 191 |
+
- [meta/config.yaml](meta/config.yaml)
|
| 192 |
+
- [meta/episodes.jsonl](meta/episodes.jsonl)
|
| 193 |
+
- [meta/tasks.jsonl](meta/tasks.jsonl)
|
| 194 |
"""
|
| 195 |
+
with open(readme_path, 'w', encoding='utf-8') as f:
|
| 196 |
+
f.write(readme_content)
|
| 197 |
+
print("Создан/обновлен файл README.md в корневой директории.")
|
| 198 |
+
|
| 199 |
+
def create_tasks_file(meta_dir, tasks_list):
|
| 200 |
+
tasks_path = os.path.join(meta_dir, "tasks.jsonl")
|
| 201 |
+
with open(tasks_path, 'w', encoding='utf-8') as f:
|
| 202 |
+
for i, task_desc in enumerate(tasks_list):
|
| 203 |
+
f.write(json.dumps({"task_index": i, "task": task_desc}, ensure_ascii=False) + '\n')
|
| 204 |
+
print("Создан/обновлен файл meta/tasks.jsonl.")
|
| 205 |
+
|
| 206 |
+
def create_episodes_file(meta_dir, episodes_list):
|
| 207 |
+
episodes_path = os.path.join(meta_dir, "episodes.jsonl")
|
| 208 |
+
with open(episodes_path, 'w', encoding='utf-8') as f:
|
| 209 |
+
for episode in episodes_list:
|
| 210 |
+
f.write(json.dumps(episode, ensure_ascii=False) + '\n')
|
| 211 |
+
print("Создан/обновлен файл meta/episodes.jsonl.")
|
| 212 |
+
|
| 213 |
+
def create_video(frames, video_path):
|
| 214 |
+
if not frames: return
|
| 215 |
+
height, width, layers = frames[0].shape
|
| 216 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 217 |
+
video_writer = cv2.VideoWriter(str(video_path), fourcc, 30.0, (width, height))
|
| 218 |
+
for img in frames:
|
| 219 |
+
img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
| 220 |
+
video_writer.write(img_bgr)
|
| 221 |
+
video_writer.release()
|
| 222 |
+
print(f"Видеофайл успешно создан: {video_path}")
|
| 223 |
|
|
|
|
| 224 |
def collect_data_and_save():
|
| 225 |
+
global running
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
+
# --- Создание папок в правильном порядке ---
|
|
|
|
| 228 |
META_DIR = LOCAL_ROOT_DIR / "meta"
|
| 229 |
+
DATA_DIR = LOCAL_ROOT_DIR / "data" / "chunk-000"
|
| 230 |
+
VIDEOS_DIR = LOCAL_ROOT_DIR / "videos" / "chunk-000" / "observation.images.generic"
|
| 231 |
+
|
| 232 |
os.makedirs(META_DIR, exist_ok=True)
|
| 233 |
os.makedirs(DATA_DIR, exist_ok=True)
|
| 234 |
os.makedirs(VIDEOS_DIR, exist_ok=True)
|
| 235 |
+
|
|
|
|
| 236 |
info_path = META_DIR / "info.json"
|
| 237 |
+
episodes_jsonl_path = META_DIR / "episodes.jsonl"
|
| 238 |
+
|
| 239 |
+
episode_idx = 0
|
| 240 |
+
episodes_data = []
|
| 241 |
+
|
| 242 |
+
# --- Определение задач (пример) ---
|
| 243 |
+
tasks_list = [
|
| 244 |
+
"Переместить предмет А из точки X в точку Y.",
|
| 245 |
+
"Поднять предмет B и опустить его в ящик.",
|
| 246 |
+
"Перемещение руки"
|
| 247 |
+
]
|
| 248 |
+
create_tasks_file(META_DIR, tasks_list)
|
| 249 |
+
|
| 250 |
+
# --- Загрузка существующих метаданных, если они есть ---
|
| 251 |
+
info = {}
|
| 252 |
if info_path.exists():
|
| 253 |
try:
|
| 254 |
with open(info_path, 'r') as f:
|
| 255 |
info = json.load(f)
|
| 256 |
+
episode_idx = info.get("total_episodes", 0)
|
| 257 |
+
if 'episode_lengths' not in info:
|
| 258 |
+
info['episode_lengths'] = []
|
| 259 |
except json.JSONDecodeError:
|
| 260 |
print(f"Предупреждение: Файл '{info_path}' поврежден или пуст. Создаю новый.")
|
| 261 |
if info_path.exists():
|
| 262 |
os.remove(info_path)
|
| 263 |
+
|
|
|
|
|
|
|
|
|
|
| 264 |
if not info:
|
| 265 |
+
# Обновленная структура info, чтобы она соответствовала ожидаемой схеме
|
| 266 |
info = {
|
| 267 |
+
"codebase_version": "v1.1",
|
| 268 |
"total_frames": 0,
|
| 269 |
"total_episodes": 0,
|
| 270 |
"episode_lengths": [],
|
| 271 |
"fps": 30,
|
| 272 |
+
"robot_type": "ainex_robot",
|
| 273 |
+
"data_path": "data/chunk-000/episode_{episode_index:06d}.parquet",
|
| 274 |
+
"video_path": "videos/chunk-000/observation.images.generic/episode_{episode_index:06d}.mp4",
|
|
|
|
|
|
|
| 275 |
"features": {
|
| 276 |
"action": {
|
| 277 |
"servo_commands": { "dtype": "float32", "shape": [26] },
|
|
|
|
| 278 |
},
|
| 279 |
"observation": {
|
| 280 |
+
"joint_positions": { "dtype": "float32", "shape": [26] },
|
| 281 |
+
"imu": { "dtype": "float32", "shape": [10] },
|
| 282 |
+
"images.generic": {
|
| 283 |
"dtype": "video",
|
| 284 |
"media_type": "video/mp4",
|
| 285 |
+
"path_format": "videos/chunk-000/observation.images.generic/episode_{episode_index:06d}.mp4",
|
| 286 |
+
"shape": [480, 640, 3]
|
| 287 |
+
}
|
|
|
|
|
|
|
| 288 |
},
|
| 289 |
"timestamp": { "dtype": "float64" },
|
| 290 |
"frame_index": { "dtype": "int64" },
|
|
|
|
| 292 |
}
|
| 293 |
}
|
| 294 |
|
|
|
|
|
|
|
|
|
|
| 295 |
if episodes_jsonl_path.exists():
|
| 296 |
try:
|
| 297 |
with open(episodes_jsonl_path, 'r', encoding='utf-8') as f:
|
| 298 |
for line in f:
|
| 299 |
episodes_data.append(json.loads(line))
|
|
|
|
| 300 |
except json.JSONDecodeError:
|
| 301 |
print(f"Предупреждение: Файл '{episodes_jsonl_path}' поврежден или пуст. Создаю новый.")
|
| 302 |
episodes_data = []
|
| 303 |
if episodes_jsonl_path.exists():
|
| 304 |
os.remove(episodes_jsonl_path)
|
| 305 |
+
|
| 306 |
+
config_path = META_DIR / "config.yaml"
|
| 307 |
+
config_content = f"""
|
| 308 |
+
task_name: ainex-robot-collection
|
| 309 |
+
dataset_id: {REPO_ID.split('/')[1]}
|
| 310 |
+
features:
|
| 311 |
+
observation.images.generic:
|
| 312 |
+
video_loader:
|
| 313 |
+
_target_: lerobot.common.datasets.video_utils.VideoLoader
|
| 314 |
+
framerate: 30
|
| 315 |
+
"""
|
| 316 |
+
with open(config_path, 'w') as f:
|
| 317 |
+
f.write(config_content.strip())
|
| 318 |
+
print("Создан файл meta/config.yaml с правильным video_loader.")
|
| 319 |
|
|
|
|
| 320 |
ws_manager = ROSBridgeManager(ROSBRIDGE_IP, ROSBRIDGE_PORT)
|
| 321 |
if not ws_manager.connect():
|
| 322 |
print("ROSBridge: Невозможно продолжить без подключения. Завершение работы.")
|
|
|
|
| 323 |
return
|
| 324 |
|
| 325 |
print("Установка подписок...")
|
| 326 |
+
ws_manager.subscribe(OBSERVATION_TOPICS["camera_generic"]["topic"], OBSERVATION_TOPICS["camera_generic"]["msg_type"], create_image_callback("camera_generic"))
|
| 327 |
+
ws_manager.subscribe(OBSERVATION_TOPICS["imu"]["topic"], OBSERVATION_TOPICS["imu"]["msg_type"], imu_callback)
|
| 328 |
+
ws_manager.subscribe(OBSERVATION_TOPICS["joint_positions_obs"]["topic"], OBSERVATION_TOPICS["joint_positions_obs"]["msg_type"], joint_positions_obs_callback)
|
| 329 |
+
ws_manager.subscribe(ACTION_TOPICS["joint_positions_action"]["topic"], ACTION_TOPICS["joint_positions_action"]["msg_type"], joint_positions_action_callback)
|
| 330 |
+
ws_manager.subscribe(ACTION_TOPICS["joy"]["topic"], ACTION_TOPICS["joy"]["msg_type"], joy_callback)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
print("Подписки установлены.")
|
| 332 |
+
print("\nСбор данных запущен. Выполняйте движения роботом.")
|
| 333 |
print("Нажмите 'Ctrl+C' для завершения и сохранения датасета.")
|
| 334 |
+
episode_duration_seconds = 2.0
|
|
|
|
|
|
|
| 335 |
current_episode_start_time = time.time()
|
|
|
|
|
|
|
| 336 |
all_images_generic = []
|
| 337 |
+
all_joint_positions_obs = [] # Новый список для joint_positions
|
| 338 |
+
all_imu_data = [] # Новый список для imu
|
| 339 |
+
all_joint_positions_action = [] # Новый список для joint_positions_action
|
| 340 |
+
all_joy_data = [] # Новый список для joy
|
| 341 |
all_timestamps = []
|
| 342 |
all_frame_indices = []
|
|
|
|
| 343 |
total_frames_collected = 0
|
|
|
|
|
|
|
| 344 |
try:
|
| 345 |
while running:
|
| 346 |
with data_lock:
|
| 347 |
+
new_image_generic_data = latest_data["camera_generic"]
|
|
|
|
|
|
|
| 348 |
if new_image_generic_data is not None:
|
| 349 |
img_generic, img_timestamp = new_image_generic_data
|
| 350 |
|
| 351 |
+
# Получение отдельных компонентов наблюдения и действия
|
| 352 |
+
imu_data = latest_data["imu"][0] if latest_data["imu"] is not None else np.array([0.0]*10, dtype=np.float32)
|
| 353 |
+
joint_positions_obs_data = latest_data["joint_positions_obs"][0] if latest_data["joint_positions_obs"] is not None else np.array([0.0]*26, dtype=np.float32)
|
| 354 |
+
joint_positions_action_data = latest_data["joint_positions_action"][0] if latest_data["joint_positions_action"] is not None else np.array([0.0]*26, dtype=np.float32)
|
| 355 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
all_images_generic.append(img_generic)
|
| 357 |
+
all_joint_positions_obs.append(joint_positions_obs_data.tolist())
|
| 358 |
all_imu_data.append(imu_data.tolist())
|
| 359 |
all_joint_positions_action.append(joint_positions_action_data.tolist())
|
|
|
|
| 360 |
all_timestamps.append(img_timestamp)
|
| 361 |
all_frame_indices.append(len(all_images_generic) - 1)
|
| 362 |
+
|
| 363 |
+
latest_data["camera_generic"] = None
|
|
|
|
| 364 |
total_frames_collected += 1
|
| 365 |
+
|
|
|
|
| 366 |
if (time.time() - current_episode_start_time) >= episode_duration_seconds:
|
| 367 |
if len(all_images_generic) > 0:
|
| 368 |
+
print(f"Собрано {len(all_images_generic)} шагов для эпизода {episode_idx:06d}. Сохраняю...")
|
| 369 |
+
video_path_generic = VIDEOS_DIR / f"episode_{episode_idx:06d}.mp4"
|
| 370 |
+
create_video(all_images_generic, video_path_generic)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
|
| 372 |
+
# --- Исправленный DataFrame ---
|
| 373 |
df = pd.DataFrame({
|
| 374 |
+
'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
|
| 375 |
+
'observation.joint_positions': all_joint_positions_obs,
|
| 376 |
'observation.imu': all_imu_data,
|
| 377 |
+
'action.servo_commands': all_joint_positions_action,
|
|
|
|
| 378 |
'timestamp': all_timestamps,
|
| 379 |
'frame_index': all_frame_indices,
|
| 380 |
'episode_index': [episode_idx] * len(all_images_generic),
|
| 381 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
+
table = pa.Table.from_pandas(df)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
parquet_path = DATA_DIR / f"episode_{episode_idx:06d}.parquet"
|
| 385 |
+
pq.write_table(table, str(parquet_path))
|
| 386 |
+
print(f"Parquet-файл {parquet_path.name} успешно создан.")
|
| 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 |
+
with open(info_path, 'w') as f:
|
| 393 |
+
json.dump(info, f, indent=4, ensure_ascii=False)
|
| 394 |
+
|
| 395 |
episodes_data.append({
|
| 396 |
"episode_index": episode_idx,
|
| 397 |
+
"task_index": 0,
|
| 398 |
+
"episode_length": len(all_images_generic)
|
| 399 |
})
|
|
|
|
|
|
|
|
|
|
| 400 |
create_episodes_file(META_DIR, episodes_data)
|
| 401 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
all_images_generic = []
|
| 403 |
+
all_joint_positions_obs = []
|
| 404 |
all_imu_data = []
|
| 405 |
all_joint_positions_action = []
|
| 406 |
+
all_joy_data = []
|
| 407 |
all_timestamps = []
|
| 408 |
all_frame_indices = []
|
| 409 |
+
|
| 410 |
+
current_episode_start_time = time.time()
|
| 411 |
+
episode_idx += 1
|
| 412 |
+
|
| 413 |
+
time.sleep(0.01) # Небольшая задержка, чтобы не загружать процессор
|
| 414 |
|
| 415 |
except Exception as e:
|
| 416 |
+
print(f"Произошла ошибка во время сбора данных: {e}")
|
|
|
|
|
|
|
|
|
|
| 417 |
finally:
|
| 418 |
+
print("\nСохранение завершено.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
ws_manager.terminate()
|
| 420 |
+
create_readme(REPO_ID, info, LOCAL_ROOT_DIR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
|
| 422 |
if __name__ == "__main__":
|
| 423 |
collect_data_and_save()
|