KillzoneCCO commited on
Commit
73c0ea2
·
verified ·
1 Parent(s): a7f830e

Загрузка эпизода 000000

Browse files
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
2
+ *.parquet filter=lfs diff=lfs merge=lfs -text
collect_and_upload.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-{episode_idx:03d}"
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": "data/{chunk_name}/data.parquet",
245
+ "video_path": "videos/{chunk_name}/observation.images.{camera_name}/episode_{episode_index:06d}.mp4",
246
+ "features": {
247
+ "action": { "dtype": "float32", "shape": [26] },
248
+ "observation": {
249
+ "joint_positions": { "dtype": "float32", "shape": [26] },
250
+ "imu": { "dtype": "float32", "shape": [10] },
251
+ # Обновлены ключи для одной камеры
252
+ "images.generic": {
253
+ "dtype": "video",
254
+ "media_type": "video/mp4",
255
+ "path_format": "videos/{chunk_name}/observation.images.generic/episode_{episode_index:06d}.mp4",
256
+ "shape": [480, 640, 3]
257
+ }
258
+ },
259
+ "timestamp": { "dtype": "float64" },
260
+ "frame_index": { "dtype": "int64" },
261
+ "episode_index": { "dtype": "int64" }
262
+ }
263
+ }
264
+
265
+ if episodes_jsonl_path.exists():
266
+ try:
267
+ with open(episodes_jsonl_path, 'r', encoding='utf-8') as f:
268
+ for line in f:
269
+ episodes_data.append(json.loads(line))
270
+ except json.JSONDecodeError:
271
+ print(f"Предупреждение: Файл '{episodes_jsonl_path}' поврежден или пуст. Создаю новый.")
272
+ episodes_data = []
273
+ if episodes_jsonl_path.exists():
274
+ os.remove(episodes_jsonl_path)
275
+
276
+ config_path = META_DIR / "config.yaml"
277
+ config_content = f"""
278
+ task_name: ainex-robot-collection
279
+ dataset_id: {REPO_ID.split('/')[1]}
280
+ features:
281
+ observation.images.generic:
282
+ video_loader:
283
+ _target_: lerobot.common.datasets.video_utils.VideoLoader
284
+ framerate: 30
285
+ """
286
+ with open(config_path, 'w') as f:
287
+ f.write(config_content.strip())
288
+ print("Создан файл meta/config.yaml с правильным video_loader.")
289
+
290
+ ws_manager = ROSBridgeManager(ROSBRIDGE_IP, ROSBRIDGE_PORT)
291
+ if not ws_manager.connect():
292
+ print("ROSBridge: Невозможно продолжить без подключения. Завершение работы.")
293
+ return
294
+
295
+ print("Установка подписок...")
296
+ ws_manager.subscribe(OBSERVATION_TOPICS["camera_generic"]["topic"], OBSERVATION_TOPICS["camera_generic"]["msg_type"], create_image_callback("camera_generic"))
297
+ ws_manager.subscribe(OBSERVATION_TOPICS["imu"]["topic"], OBSERVATION_TOPICS["imu"]["msg_type"], imu_callback)
298
+ ws_manager.subscribe(OBSERVATION_TOPICS["joint_positions"]["topic"], OBSERVATION_TOPICS["joint_positions"]["msg_type"], joint_positions_callback)
299
+ print("Подписки установлены.")
300
+
301
+ print("\nСбор данных запущен. Выполняйте движения роботом.")
302
+ print("Нажмите 'Ctrl+C' для завершения и сохранения датасета.")
303
+
304
+ all_images_generic = []
305
+ all_joint_positions = []
306
+ all_imu_data = []
307
+ all_timestamps = []
308
+ all_actions = []
309
+
310
+ try:
311
+ while running:
312
+ with data_lock:
313
+ new_image_generic_data = latest_data["camera_generic"]
314
+
315
+ # Код теперь ждет данные от одной камеры
316
+ if new_image_generic_data is not None:
317
+ img_generic, img_timestamp = new_image_generic_data
318
+
319
+ imu_data = latest_data["imu"][0] if latest_data["imu"] is not None else np.array([0.0]*10, dtype=np.float32)
320
+ 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)
321
+
322
+ all_images_generic.append(img_generic)
323
+ all_joint_positions.append(joint_positions_data.tolist())
324
+ all_imu_data.append(imu_data.tolist())
325
+ all_actions.append([0.0] * 26)
326
+ all_timestamps.append(img_timestamp)
327
+
328
+ latest_data["camera_generic"] = None
329
+
330
+ time.sleep(0.01)
331
+ except Exception as e:
332
+ print(f"Произошла непредвиденная ошибка в основном цикле: {e}")
333
+ finally:
334
+ print("\nЗавершение сбора данных...")
335
+ ws_manager.terminate()
336
+
337
+ if len(all_images_generic) == 0:
338
+ print("Данные не были собраны. Выход.")
339
+ return
340
+
341
+ episode_length = len(all_images_generic)
342
+ print(f"Собрано {episode_length} шагов. Сохраняю датасет...")
343
+
344
+ # --- Создание структуры папок для видео ---
345
+ chunk_video_dir = VIDEOS_DIR / chunk_name
346
+ generic_video_dir = chunk_video_dir / "observation.images.generic"
347
+ os.makedirs(generic_video_dir, exist_ok=True)
348
+
349
+ def create_video(frames, video_path):
350
+ if not frames: return
351
+ height, width, layers = frames[0].shape
352
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
353
+ video_writer = cv2.VideoWriter(str(video_path), fourcc, 30.0, (width, height))
354
+ for img in frames:
355
+ img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
356
+ video_writer.write(img_bgr)
357
+ video_writer.release()
358
+ print(f"Видеофайл успешно создан: {video_path}")
359
+
360
+ try:
361
+ video_path_generic = generic_video_dir / f"episode_{episode_idx:06d}.mp4"
362
+ create_video(all_images_generic, video_path_generic)
363
+ except Exception as e:
364
+ print(f"Ошибка при создании видеофайла: {e}")
365
+ return
366
+
367
+ try:
368
+ episode_data_dir = DATA_DIR / chunk_name
369
+ os.makedirs(episode_data_dir, exist_ok=True)
370
+
371
+ df = pd.DataFrame({
372
+ 'observation.images.generic': [f"../../videos/{chunk_name}/observation.images.generic/episode_{episode_idx:06d}.mp4"] * episode_length,
373
+ 'observation.joint_positions': all_joint_positions,
374
+ 'observation.imu': all_imu_data,
375
+ 'action.servo_commands': all_actions,
376
+ 'timestamp': all_timestamps,
377
+ 'frame_index': list(range(episode_length)),
378
+ 'episode_index': [episode_idx] * episode_length,
379
+ })
380
+
381
+ table = pa.Table.from_pandas(df)
382
+ parquet_path = episode_data_dir / "data.parquet"
383
+ pq.write_table(table, str(parquet_path))
384
+ print("Parquet-файл успешно создан.")
385
+ except Exception as e:
386
+ print(f"Ошибка при сохранении данных в Parquet: {e}")
387
+ return
388
+
389
+ # --- Обновление всех метаданных ---
390
+ info['total_episodes'] += 1
391
+ info['total_frames'] += episode_length
392
+ info['episode_lengths'].append(episode_length)
393
+ with open(info_path, 'w') as f:
394
+ json.dump(info, f, indent=2)
395
+ print("info.json успешно обновлен.")
396
+
397
+ create_tasks_file(META_DIR, tasks_list)
398
+
399
+ episodes_data.append({
400
+ "episode_index": episode_idx,
401
+ "tasks": [tasks_list[0]],
402
+ "length": episode_length
403
+ })
404
+ create_episodes_file(META_DIR, episodes_data)
405
+
406
+ create_readme(REPO_ID, info, META_DIR)
407
+
408
+ # --- Загрузка всех файлов на Hugging Face Hub ---
409
+ try:
410
+ token = HfFolder.get_token()
411
+ if token is None:
412
+ print("Пожалуйста, выполните команду 'huggingface-cli login' для аутентификации.")
413
+ return
414
+
415
+ api = HfApi()
416
+
417
+ create_repo(REPO_ID, repo_type="dataset", exist_ok=True)
418
+
419
+ print(f"Загрузка локальной директории (meta, data, videos) на Hugging Face Hub...")
420
+
421
+ api.upload_folder(
422
+ folder_path=str(LOCAL_ROOT_DIR),
423
+ repo_id=REPO_ID,
424
+ repo_type="dataset",
425
+ commit_message=f"Загрузка эпизода {episode_idx:06d}",
426
+ ignore_patterns=["__pycache__", "*.pyc", ".git"]
427
+ )
428
+
429
+ print(f"Данные успешно загружены: https://huggingface.co/datasets/{REPO_ID}")
430
+ except Exception as e:
431
+ print(f"Ошибка при загрузке данных: {e}")
432
+
433
+ if __name__ == "__main__":
434
+ collect_data_and_save()
config.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # C:\Programirovanie\Робот\datasets\ainex_robot\config.py
2
+ from dataclasses import dataclass, field
3
+ from typing import List
4
+
5
+ @dataclass
6
+ class RobotConfig:
7
+ motor_keys: List[str] = field(default_factory=lambda: [
8
+ "Head_Yaw", "Head_Pitch", "L_Shoulder_Pitch", "L_Shoulder_Roll", "L_Elbow_Roll",
9
+ "L_Elbow_Yaw", "L_Wrist_Roll", "L_Wrist_Yaw", "L_Hand", "R_Shoulder_Pitch",
10
+ "R_Shoulder_Roll", "R_Elbow_Roll", "R_Elbow_Yaw", "R_Wrist_Roll", "R_Wrist_Yaw",
11
+ "R_Hand", "L_Hip_Roll", "L_Hip_Pitch", "L_Knee_Pitch", "L_Ankle_Pitch",
12
+ "L_Ankle_Roll", "R_Hip_Roll", "R_Hip_Pitch", "R_Knee_Pitch", "R_Ankle_Pitch",
13
+ "R_Ankle_Roll"
14
+ ])
15
+
16
+ motor_ids: List[int] = field(default_factory=lambda: [
17
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
18
+ 21, 22, 23, 24, 25, 26
19
+ ])
data/chunk-000/data.parquet ADDED
Binary file (12.5 kB). View file
 
meta/README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ task_categories:
4
+ - robotics
5
+ tags:
6
+ - LeRobot
7
+ configs:
8
+ - config_name: default
9
+ data_files: data/*/*.parquet
10
+ ---
11
+
12
+ # Ainex Robot Dataset
13
+
14
+ Этот датасет был собран с помощью робота **Ainex** для демонстрации его возможностей в рамках LeRobot.
15
+
16
+ ## Статистика датасета
17
+ - **Общее количество эпизодов**: 1
18
+ - **Общее количество кадров**: 61
19
+ - **Тип робота**: ainex_robot
20
+ - **Кадров в секунду (FPS)**: 30
21
+
22
+ ## Структура датасета
23
+ - [meta/info.json](meta/info.json)
24
+ - [meta/config.yaml](meta/config.yaml)
25
+ - [meta/episodes.jsonl](meta/episodes.jsonl)
26
+ - [meta/tasks.jsonl](meta/tasks.jsonl)
meta/config.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ task_name: ainex-robot-collection
2
+ dataset_id: Ainex
3
+ features:
4
+ observation.images.generic:
5
+ video_loader:
6
+ _target_: lerobot.common.datasets.video_utils.VideoLoader
7
+ framerate: 30
meta/episodes.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"episode_index": 0, "tasks": ["Переместить предмет А из точки X в точку Y."], "length": 61}
meta/info.json ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "codebase_version": "v1.1",
3
+ "total_frames": 61,
4
+ "total_episodes": 1,
5
+ "episode_lengths": [
6
+ 61
7
+ ],
8
+ "fps": 30,
9
+ "robot_type": "ainex_robot",
10
+ "data_path": "data/{chunk_name}/data.parquet",
11
+ "video_path": "videos/{chunk_name}/observation.images.{camera_name}/episode_{episode_index:06d}.mp4",
12
+ "features": {
13
+ "action": {
14
+ "dtype": "float32",
15
+ "shape": [
16
+ 26
17
+ ]
18
+ },
19
+ "observation": {
20
+ "joint_positions": {
21
+ "dtype": "float32",
22
+ "shape": [
23
+ 26
24
+ ]
25
+ },
26
+ "imu": {
27
+ "dtype": "float32",
28
+ "shape": [
29
+ 10
30
+ ]
31
+ },
32
+ "images.generic": {
33
+ "dtype": "video",
34
+ "media_type": "video/mp4",
35
+ "path_format": "videos/{chunk_name}/observation.images.generic/episode_{episode_index:06d}.mp4",
36
+ "shape": [
37
+ 480,
38
+ 640,
39
+ 3
40
+ ]
41
+ }
42
+ },
43
+ "timestamp": {
44
+ "dtype": "float64"
45
+ },
46
+ "frame_index": {
47
+ "dtype": "int64"
48
+ },
49
+ "episode_index": {
50
+ "dtype": "int64"
51
+ }
52
+ }
53
+ }
meta/tasks.jsonl ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"task_index": 0, "task": "Переместить предмет А из точки X в точку Y."}
2
+ {"task_index": 1, "task": "Поднять предмет B и опустить его в ящик."}
motor_controller.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # C:\Programirovanie\Робот\datasets\ainex_robot\motor_controller.py
2
+ import roslibpy
3
+ from typing import List
4
+ from .config import RobotConfig
5
+
6
+ class MotorController:
7
+ def __init__(self, config: RobotConfig):
8
+ self.config = config
9
+ self.client = roslibpy.Ros(host='192.168.20.97', port=9090)
10
+ self.topic = roslibpy.Topic(
11
+ self.client,
12
+ '/ros_robot_controller/bus_servo/set_position',
13
+ 'ros_robot_controller/SetBusServosPosition'
14
+ )
15
+
16
+ def connect(self):
17
+ self.client.run()
18
+ print("Подключено к ROS.")
19
+
20
+ def close(self):
21
+ self.client.terminate()
22
+ print("Соединение с ROS завершено.")
23
+
24
+ def set_joint_positions(self, positions: List[float]):
25
+ """
26
+ Отправляет команды для установки позиций суставов.
27
+ """
28
+ message = roslibpy.Message({
29
+ 'positions': [
30
+ {'id': motor_id, 'position': pos}
31
+ for motor_id, pos in zip(self.config.motor_ids, positions)
32
+ ]
33
+ })
34
+ self.topic.publish(message)
videos/chunk-000/observation.images.generic/episode_000000.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cdaff4f970ebdd49f5329ef8bb7c52f35bed7a258fb98bc7fe54c95ce9601373
3
+ size 953786