Delete collect_and_upload.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506import roslibpy
import threading
import signal
import base64
import cv2
import time
import numpy as np
import os
import pandas as pd
import json
from huggingface_hub import HfApi, HfFolder, create_repo
import pyarrow as pa
import pyarrow.parquet as pq
from pathlib import Path
# --- Глобальный флаг для управления основным циклом ---
running = True
# --- Обработчик сигнала для корректного завершения (Ctrl+C) ---
def signal_handler(sig, frame):
global running
print("\nПолучен сигнал завершения. Завершаю сбор данных...")
running = False
signal.signal(signal.SIGINT, signal_handler)
# --- Настройки ROSBridge ---
ROSBRIDGE_IP = "192.168.20.97"
ROSBRIDGE_PORT = 9090
REPO_ID = "KillzoneCCO/Ainex"
LOCAL_ROOT_DIR = Path("./")
# --- ROS Топики и типы сообщений для сбора данных (наблюдения) ---
# Только один топик для камеры, как и было указано
OBSERVATION_TOPICS = {
"camera_generic": {"topic": "/camera/image_raw", "msg_type": "sensor_msgs/Image"},
"imu": {"topic": "/imu", "msg_type": "sensor_msgs/Imu"},
"joint_positions": {"topic": "/ros_robot_controller/bus_servo/set_position", "msg_type": "ros_robot_controller/SetBusServosPosition"},
}
# --- Глобальные переменные для хранения последних данных ---
latest_data = {key: None for key in OBSERVATION_TOPICS.keys()}
data_lock = threading.Lock()
# --- Менеджер соединения ROSBridge ---
class ROSBridgeManager:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.client = roslibpy.Ros(host=self.ip, port=self.port)
self.connected = False
self._subscriptions = []
def connect(self):
print('ROSBridge: Попытка подключения...')
try:
self.client.run()
self.connected = True
print('ROSBridge: Подключено!')
return True
except Exception as e:
print(f"ROSBridge: Ошибка подключения: {e}")
self.connected = False
return False
def subscribe(self, topic_name, message_type, callback):
listener = roslibpy.Topic(self.client, topic_name, message_type)
listener.subscribe(callback)
print(f"Подписан на {topic_name} ({message_type})")
self._subscriptions.append(listener)
def terminate(self):
if self.client:
for sub in self._subscriptions:
try:
sub.unsubscribe()
except Exception as e:
print(f"Ошибка при отписке от {sub.name}: {e}")
self._subscriptions.clear()
if self.client.is_connected:
print("ROSBridge: Завершение соединения...")
self.client.terminate()
self.connected = False
def create_image_callback(camera_key):
def callback(message):
with data_lock:
try:
np_arr = np.frombuffer(base64.b64decode(message['data']), np.uint8)
channels = 3 if 'rgb' in message['encoding'] or 'bgr' in message['encoding'] else 1
img_np = np_arr.reshape((message['height'], message['width'], channels))
if 'bgr' in message['encoding']:
img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
latest_data[camera_key] = (img_np, time.time())
except Exception as e:
print(f"DEBUG: Ошибка обработки изображения с {camera_key}: {e}")
latest_data[camera_key] = None
return callback
def imu_callback(message):
with data_lock:
try:
imu_data = np.array([
message['orientation']['x'],
message['orientation']['y'],
message['orientation']['z'],
message['orientation']['w'],
message['angular_velocity']['x'],
message['angular_velocity']['y'],
message['angular_velocity']['z'],
message['linear_acceleration']['x'],
message['linear_acceleration']['y'],
message['linear_acceleration']['z']
], dtype=np.float32)
latest_data["imu"] = (imu_data, time.time())
except Exception as e:
print(f"DEBUG: Ошибка обработки IMU: {e}")
latest_data["imu"] = None
def joint_positions_callback(message):
with data_lock:
try:
if "position" in message and isinstance(message["position"], list):
temp_joint_positions = np.array([0.0] * 26, dtype=np.float32)
for item in message["position"]:
if isinstance(item, dict) and "id" in item and "position" in item:
servo_id = int(item["id"])
if 1 <= servo_id <= 26:
temp_joint_positions[servo_id - 1] = float(item["position"])
latest_data["joint_positions"] = (temp_joint_positions, time.time())
except Exception as e:
print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")
latest_data["joint_positions"] = None
def create_readme(repo_id, info, meta_dir):
readme_path = os.path.join(meta_dir, "README.md")
total_episodes = info.get("total_episodes", 0)
total_frames = info.get("total_frames", 0)
robot_type = info.get("robot_type", "unknown")
fps = info.get("fps", 0)
readme_content = f"""---
license: apache-2.0
task_categories:
- robotics
tags:
- LeRobot
configs:
- config_name: default
data_files: data/*/*.parquet
---
# Ainex Robot Dataset
Этот датасет был собран с помощью робота **Ainex** для демонстрации его возможностей в рамках LeRobot.
## Статистика датасета
- **Общее количество эпизодов**: {total_episodes}
- **Общее количество кадров**: {total_frames}
- **Тип робота**: {robot_type}
- **Кадров в секунду (FPS)**: {fps}
## Структура датасета
- [meta/info.json](meta/info.json)
- [meta/config.yaml](meta/config.yaml)
- [meta/episodes.jsonl](meta/episodes.jsonl)
- [meta/tasks.jsonl](meta/tasks.jsonl)
"""
with open(readme_path, 'w', encoding='utf-8') as f:
f.write(readme_content)
print("Создан файл meta/README.md.")
def create_tasks_file(meta_dir, tasks_list):
tasks_path = os.path.join(meta_dir, "tasks.jsonl")
with open(tasks_path, 'w', encoding='utf-8') as f:
for i, task_desc in enumerate(tasks_list):
f.write(json.dumps({"task_index": i, "task": task_desc}, ensure_ascii=False) + '\n')
print("Создан файл meta/tasks.jsonl.")
def create_episodes_file(meta_dir, episodes_list):
episodes_path = os.path.join(meta_dir, "episodes.jsonl")
with open(episodes_path, 'w', encoding='utf-8') as f:
for episode in episodes_list:
f.write(json.dumps(episode, ensure_ascii=False) + '\n')
print("Создан файл meta/episodes.jsonl.")
def create_gitattributes(root_dir):
git_lfs_content = "*.mp4 filter=lfs diff=lfs merge=lfs -text\n*.parquet filter=lfs diff=lfs merge=lfs -text\n"
git_attributes_path = os.path.join(root_dir, ".gitattributes")
with open(git_attributes_path, 'w') as f:
f.write(git_lfs_content)
print("Создан файл .gitattributes для отслеживания LFS-файлов.")
def collect_data_and_save():
global running, latest_data
# --- Создание папок в правильном порядке ---
META_DIR = LOCAL_ROOT_DIR / "meta"
DATA_DIR = LOCAL_ROOT_DIR / "data"
VIDEOS_DIR = LOCAL_ROOT_DIR / "videos"
os.makedirs(META_DIR, exist_ok=True)
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(VIDEOS_DIR, exist_ok=True)
create_gitattributes(LOCAL_ROOT_DIR)
info_path = META_DIR / "info.json"
episodes_jsonl_path = META_DIR / "episodes.jsonl"
episode_idx = 0
episodes_data = []
# Имя директории для эпизода (chunk-000, chunk-001 и т.д.)
chunk_name = f"chunk-000"
# --- Определение задач (пример) ---
tasks_list = [
"Переместить предмет А из точки X в точку Y.",
"Поднять предмет B и опустить его в ящик."
]
# --- Загрузка существующих метаданных, если они есть ---
if info_path.exists():
try:
with open(info_path, 'r') as f:
info = json.load(f)
episode_idx = info.get("total_episodes", 0)
except json.JSONDecodeError:
print(f"Предупреждение: Файл '{info_path}' поврежден или пуст. Создаю новый.")
info = {}
if info_path.exists():
os.remove(info_path)
if not info_path.exists():
info = {
"codebase_version": "v1.1",
"total_frames": 0,
"total_episodes": 0,
"episode_lengths": [],
"fps": 30,
"robot_type": "ainex_robot",
# Обновлены пути к данным для одной камеры
# Теперь data_path ссылается на конкретный файл эпизода
"data_path": "data/{chunk_name}/episode_{episode_index:06d}.parquet",
"video_path": "videos/{chunk_name}/observation.images.{camera_name}/episode_{episode_index:06d}.mp4",
"features": {
"action": { "dtype": "float32", "shape": [26] },
"observation": {
"joint_positions": { "dtype": "float32", "shape": [26] },
"imu": { "dtype": "float32", "shape": [10] },
# Обновлены ключи для одной камеры
"images.generic": {
"dtype": "video",
"media_type": "video/mp4",
"path_format": "videos/{chunk_name}/observation.images.generic/episode_{episode_index:06d}.mp4",
"shape": [480, 640, 3]
}
},
"timestamp": { "dtype": "float64" },
"frame_index": { "dtype": "int64" },
"episode_index": { "dtype": "int64" }
}
}
if episodes_jsonl_path.exists():
try:
with open(episodes_jsonl_path, 'r', encoding='utf-8') as f:
for line in f:
episodes_data.append(json.loads(line))
except json.JSONDecodeError:
print(f"Предупреждение: Файл '{episodes_jsonl_path}' поврежден или пуст. Создаю новый.")
episodes_data = []
if episodes_jsonl_path.exists():
os.remove(episodes_jsonl_path)
config_path = META_DIR / "config.yaml"
config_content = f"""
task_name: ainex-robot-collection
dataset_id: {REPO_ID.split('/')[1]}
features:
observation.images.generic:
video_loader:
_target_: lerobot.common.datasets.video_utils.VideoLoader
framerate: 30
"""
with open(config_path, 'w') as f:
f.write(config_content.strip())
print("Создан файл meta/config.yaml с правильным video_loader.")
ws_manager = ROSBridgeManager(ROSBRIDGE_IP, ROSBRIDGE_PORT)
if not ws_manager.connect():
print("ROSBridge: Невозможно продолжить без подключения. Завершение работы.")
return
print("Установка подписок...")
ws_manager.subscribe(OBSERVATION_TOPICS["camera_generic"]["topic"], OBSERVATION_TOPICS["camera_generic"]["msg_type"], create_image_callback("camera_generic"))
ws_manager.subscribe(OBSERVATION_TOPICS["imu"]["topic"], OBSERVATION_TOPICS["imu"]["msg_type"], imu_callback)
ws_manager.subscribe(OBSERVATION_TOPICS["joint_positions"]["topic"], OBSERVATION_TOPICS["joint_positions"]["msg_type"], joint_positions_callback)
print("Подписки установлены.")
print("\nСбор данных запущен. Выполняйте движения роботом.")
print("Нажмите 'Ctrl+C' для завершения и сохранения датасета.")
# --- Новые переменные для разбиения на эпизоды по времени ---
episode_duration_seconds = 2.0 # Длительность одного эпизода в секундах
current_episode_start_time = time.time()
all_images_generic = []
all_joint_positions = []
all_imu_data = []
all_timestamps = []
all_actions = []
total_frames_collected = 0
try:
while running:
with data_lock:
new_image_generic_data = latest_data["camera_generic"]
if new_image_generic_data is not None:
img_generic, img_timestamp = new_image_generic_data
imu_data = latest_data["imu"][0] if latest_data["imu"] is not None else np.array([0.0]*10, dtype=np.float32)
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)
all_images_generic.append(img_generic)
all_joint_positions.append(joint_positions_data.tolist())
all_imu_data.append(imu_data.tolist())
all_actions.append([0.0] * 26)
all_timestamps.append(img_timestamp)
latest_data["camera_generic"] = None
total_frames_collected += 1
# Проверка, пора ли завершить текущий эпизод
if (time.time() - current_episode_start_time) >= episode_duration_seconds:
if len(all_images_generic) > 0:
print(f"Собрано {len(all_images_generic)} шагов для эпизода {episode_idx:06d}. Сохраняю...")
# --- Создание структуры папок для видео ---
chunk_video_dir = VIDEOS_DIR / chunk_name
generic_video_dir = chunk_video_dir / "observation.images.generic"
os.makedirs(generic_video_dir, exist_ok=True)
def create_video(frames, video_path):
if not frames: return
height, width, layers = frames[0].shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(str(video_path), fourcc, 30.0, (width, height))
for img in frames:
img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
video_writer.write(img_bgr)
video_writer.release()
print(f"Видеофайл успешно создан: {video_path}")
try:
video_path_generic = generic_video_dir / f"episode_{episode_idx:06d}.mp4"
create_video(all_images_generic, video_path_generic)
except Exception as e:
print(f"Ошибка при создании видеофайла: {e}")
return
try:
episode_data_dir = DATA_DIR / chunk_name
os.makedirs(episode_data_dir, exist_ok=True)
df = pd.DataFrame({
'observation.images.generic': [f"../../videos/{chunk_name}/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
'observation.joint_positions': all_joint_positions,
'observation.imu': all_imu_data,
'action.servo_commands': all_actions,
'timestamp': all_timestamps,
'frame_index': list(range(len(all_images_generic))),
'episode_index': [episode_idx] * len(all_images_generic),
})
table = pa.Table.from_pandas(df)
parquet_path = episode_data_dir / f"episode_{episode_idx:06d}.parquet"
pq.write_table(table, str(parquet_path))
print(f"Parquet-файл {parquet_path.name} успешно создан.")
except Exception as e:
print(f"Ошибка при сохранении данных в Parquet: {e}")
return
# --- Обновление метаданных ---
info['total_episodes'] += 1
info['total_frames'] += len(all_images_generic)
info['episode_lengths'].append(len(all_images_generic))
episodes_data.append({
"episode_index": episode_idx,
"tasks": [tasks_list[0]],
"length": len(all_images_generic)
})
create_episodes_file(META_DIR, episodes_data)
create_readme(REPO_ID, info, META_DIR)
# Подготовка к новому эпизоду
episode_idx += 1
current_episode_start_time = time.time()
all_images_generic = []
all_joint_positions = []
all_imu_data = []
all_timestamps = []
all_actions = []
time.sleep(0.01) # Небольшая задержка, чтобы не нагружать процессор
except Exception as e:
print(f"Произошла непредвиденная ошибка в основном цикле: {e}")
finally:
print("\nЗавершение сбора данных...")
# Сохранение последнего незавершенного эпизода
if len(all_images_generic) > 0:
print(f"Собрано {len(all_images_generic)} шагов для последнего эпизода {episode_idx:06d}. Сохраняю...")
chunk_video_dir = VIDEOS_DIR / chunk_name
generic_video_dir = chunk_video_dir / "observation.images.generic"
os.makedirs(generic_video_dir, exist_ok=True)
video_path_generic = generic_video_dir / f"episode_{episode_idx:06d}.mp4"
def create_video(frames, video_path):
if not frames: return
height, width, layers = frames[0].shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(str(video_path), fourcc, 30.0, (width, height))
for img in frames:
img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
video_writer.write(img_bgr)
video_writer.release()
print(f"Видеофайл успешно создан: {video_path}")
create_video(all_images_generic, video_path_generic)
episode_data_dir = DATA_DIR / chunk_name
os.makedirs(episode_data_dir, exist_ok=True)
df = pd.DataFrame({
'observation.images.generic': [f"../../videos/{chunk_name}/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),
'observation.joint_positions': all_joint_positions,
'observation.imu': all_imu_data,
'action.servo_commands': all_actions,
'timestamp': all_timestamps,
'frame_index': list(range(len(all_images_generic))),
'episode_index': [episode_idx] * len(all_images_generic),
})
table = pa.Table.from_pandas(df)
parquet_path = episode_data_dir / f"episode_{episode_idx:06d}.parquet"
pq.write_table(table, str(parquet_path))
print(f"Parquet-файл {parquet_path.name} успешно создан.")
info['total_episodes'] += 1
info['total_frames'] += len(all_images_generic)
info['episode_lengths'].append(len(all_images_generic))
episodes_data.append({
"episode_index": episode_idx,
"tasks": [tasks_list[0]],
"length": len(all_images_generic)
})
create_episodes_file(META_DIR, episodes_data)
ws_manager.terminate()
# Обновление финальных метаданных
with open(info_path, 'w') as f:
json.dump(info, f, indent=2)
print("info.json успешно обновлен.")
create_readme(REPO_ID, info, META_DIR)
if info["total_frames"] == 0:
print("Данные не были собраны. Выход.")
return
# --- Загрузка всех файлов на Hugging Face Hub ---
try:
token = HfFolder.get_token()
if token is None:
print("Пожалуйста, выполните команду 'huggingface-cli login' для аутентификации.")
return
api = HfApi()
create_repo(REPO_ID, repo_type="dataset", exist_ok=True)
print(f"Загрузка локальной директории (meta, data, videos) на Hugging Face Hub...")
api.upload_folder(
folder_path=str(LOCAL_ROOT_DIR),
repo_id=REPO_ID,
repo_type="dataset",
commit_message=f"Загрузка {info['total_episodes']} эпизодов",
ignore_patterns=["__pycache__", "*.pyc", ".git"]
)
print(f"Данные успешно загружены: https://huggingface.co/datasets/{REPO_ID}")
except Exception as e:
print(f"Ошибка при загрузке данных: {e}")
if __name__ == "__main__":
collect_data_and_save()collect_and_upload.pyDeleted-506