KillzoneCC commited on
Commit ·
fe9f854
1
Parent(s): c82e679
Порядок в столбцах и удаление лишнего
Browse files32 unmodified lines333435363738394084 unmodified lines12512612712812913011 unmodified lines14214314414514614714853 unmodified lines2022032042052062072084 unmodified lines21321421521621721821922022122222322422522622722822923011 unmodified lines2422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722736 unmodified lines2802812822832842852862872882892902912922932942952962976 unmodified lines3043053063073083093105 unmodified lines31631731831932032132221 unmodified lines3443453463473483493 unmodified lines3533543553563573583593603613623633647 unmodified lines3723733743753763773783793803813823833843853863873886 unmodified lines3953963973983994004014024034044054064074084097 unmodified lines4174184194204214224232 unmodified lines4264274284294304314324334344354364377 unmodified lines4454464474484494504514524534544554564574584597 unmodified lines46746846947047147247332 unmodified linesOBSERVATION_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"},"joy": {"topic": "/joy", "msg_type": "sensor_msgs/Joy"},}# --- Глобальные переменные для хранения последних данных ---84 unmodified linesprint(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")latest_data["joint_positions"] = Nonedef joy_callback(message):with data_lock:try:11 unmodified linesrobot_type = info.get("robot_type", "unknown")fps = info.get("fps", 0)# Исправленное форматирование YAMLreadme_content = f"""---license: apache-2.0task_categories:53 unmodified linesdef collect_data_and_save():global running# --- Создание папок в правильном порядке ---META_DIR = LOCAL_ROOT_DIR / "meta"DATA_DIR = LOCAL_ROOT_DIR / "data" / "chunk-000"VIDEOS_DIR = LOCAL_ROOT_DIR / "videos" / "chunk-000" / "observation.images.generic"4 unmodified linesinfo_path = META_DIR / "info.json"episodes_jsonl_path = META_DIR / "episodes.jsonl"# Создаем список имен для 26 сервоприводовjoint_names = [f"servo_{i+1}" for i in range(26)]# --- Определение задач (пример) ---tasks_list = ["Переместить предмет А из точки X в точку Y.","Поднять предмет B и опустить его в ящик.","Перемещение руки"]# --- Шаблон для info.json с полным набором полей ---base_info = {"codebase_version": "v2.2","robot_type": "ainex_robot",11 unmodified lines"video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4","features": {"action": {"servo_commands": {"dtype": "float32","shape": [26],"names": joint_names},"joystick": {"axes": {"dtype": "float32","shape": [8],},"buttons": {"dtype": "int32","shape": [11],}}},"observation": {"joint_positions": {"dtype": "float32","shape": [26],"names": joint_names},"imu": {"dtype": "float32","shape": [10],"names": ["orientation.x", "orientation.y", "orientation.z", "orientation.w", "angular_velocity.x", "angular_velocity.y", "angular_velocity.z", "linear_acceleration.x", "linear_acceleration.y", "linear_acceleration.z"]},"images": {"generic": {6 unmodified lines},"timestamp": { "dtype": "float64", "shape": [1] },"frame_index": { "dtype": "int64", "shape": [1] },"episode_index": { "dtype": "int64", "shape": [1] }}}# --- Загрузка существующих метаданных, если они есть ---info = base_infoepisode_idx = 0if info_path.exists():try:with open(info_path, 'r') as f:existing_info = json.load(f)# Обновляем только числовые данные, сохраняя структуруinfo['total_episodes'] = existing_info.get('total_episodes', 0)info['total_frames'] = existing_info.get('total_frames', 0)info['total_videos'] = existing_info.get('total_videos', 0)6 unmodified linesif info_path.exists():os.remove(info_path)# --- Загрузка существующих эпизодов ---episodes_data = []if episodes_jsonl_path.exists():try:5 unmodified linesif episodes_jsonl_path.exists():os.remove(episodes_jsonl_path)# --- Создание файла tasks.jsonl и README.md только один раз ---create_tasks_file(META_DIR, tasks_list)create_readme(REPO_ID, info, LOCAL_ROOT_DIR)21 unmodified linesws_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)ws_manager.subscribe(OBSERVATION_TOPICS["joy"]["topic"], OBSERVATION_TOPICS["joy"]["msg_type"], joy_callback)print("Подписки установлены.")print("\nСбор данных запущен. Выполняйте движения роботом.")3 unmodified linescurrent_episode_start_time = time.time()all_images_generic = []all_joint_positions = []all_imu_data = []all_timestamps = []all_actions = []all_joy_axes = []all_joy_buttons = []total_frames_collected = 07 unmodified linesimu_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)joy_data = latest_data["joy"][0] if latest_data["joy"] is not None else ([], [])joy_axes = joy_data[0] if joy_data[0] else [0.0] * 8joy_buttons = joy_data[1] if joy_data[1] else [0] * 11all_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)all_joy_axes.append(joy_axes)all_joy_buttons.append(joy_buttons)latest_data["camera_generic"] = Nonetotal_frames_collected += 16 unmodified linescreate_video(all_images_generic, video_path_generic)df = pd.DataFrame({'observation.images.generic': [f"../../videos/chunk-000/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,'action.joystick.axes': all_joy_axes,'action.joystick.buttons': all_joy_buttons,'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)7 unmodified linesepisodes_data.append({"episode_index": episode_idx,"tasks": tasks_list,"length": len(all_images_generic)})create_episodes_file(META_DIR, episodes_data)2 unmodified linesepisode_idx += 1current_episode_start_time = time.time()all_images_generic = []all_joint_positions = []all_imu_data = []all_timestamps = []all_actions = []all_joy_axes = []all_joy_buttons = []time.sleep(0.01)except Exception as e:7 unmodified linescreate_video(all_images_generic, video_path_generic)df = pd.DataFrame({'observation.images.generic': [f"../../videos/chunk-000/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,'action.joystick.axes': all_joy_axes,'action.joystick.buttons': all_joy_buttons,'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)7 unmodified linesepisodes_data.append({"episode_index": episode_idx,"tasks": tasks_list,"length": len(all_images_generic)})create_episodes_file(META_DIR, episodes_data)32 unmodified lines33343536373839404184 unmodified lines12612712812913013113213313413513613713813914014114214314414514611 unmodified lines15815916016116216353 unmodified lines2172182192202212224 unmodified lines22722822923023123223323423523623723823924024111 unmodified lines2532542552562572582592602612622632642652662676 unmodified lines2742752762772782792802812822832842852862872882892902916 unmodified lines2982993003013023035 unmodified lines30931031131231331421 unmodified lines3363373383393403413423 unmodified lines3463473483493503513523533543553563573587 unmodified lines3663673683693703713723733743753763773783793803813823833843853863873883893906 unmodified lines3973983994004014024034044054064074084094107 unmodified lines4184194204214224234242 unmodified lines4274284294304314324334344354364374384397 unmodified lines4474484494504514524534544554564574584594607 unmodified lines46846947047147247347432 unmodified linesOBSERVATION_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/get_position", "msg_type": "ros_robot_controller/SetBusServosPosition"},"joy": {"topic": "/joy", "msg_type": "sensor_msgs/Joy"},"action_commands": {"topic": "/ros_robot_controller/bus_servo/set_position", "msg_type": "ros_robot_controller/SetBusServosPosition"}}# --- Глобальные переменные для хранения последних данных ---84 unmodified linesprint(f"DEBUG_CALLBACK: Ошибка при обработке сообщения состояний сервоприводов: {e}. Сообщение: {message}")latest_data["joint_positions"] = Nonedef action_commands_callback(message):with data_lock:try:if "position" in message and isinstance(message["position"], list):temp_actions = 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_actions[servo_id - 1] = float(item["position"])latest_data["action_commands"] = (temp_actions, time.time())except Exception as e:print(f"DEBUG_CALLBACK: Ошибка при обработке сообщения команд сервоприводов: {e}. Сообщение: {message}")latest_data["action_commands"] = Nonedef joy_callback(message):with data_lock:try:11 unmodified linesrobot_type = info.get("robot_type", "unknown")fps = info.get("fps", 0)readme_content = f"""---license: apache-2.0task_categories:53 unmodified linesdef collect_data_and_save():global runningMETA_DIR = LOCAL_ROOT_DIR / "meta"DATA_DIR = LOCAL_ROOT_DIR / "data" / "chunk-000"VIDEOS_DIR = LOCAL_ROOT_DIR / "videos" / "chunk-000" / "observation.images.generic"4 unmodified linesinfo_path = META_DIR / "info.json"episodes_jsonl_path = META_DIR / "episodes.jsonl"joint_names = [f"servo_{i+1}" for i in range(26)]tasks_list = ["Переместить предмет А из точки X в точку Y.","Поднять предмет B и опустить его в ящик.","Перемещение руки"]base_info = {"codebase_version": "v2.2","robot_type": "ainex_robot",11 unmodified lines"video_path": "videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4","features": {"action": {"dtype": "float32","shape": [37], # 26 servo commands + 8 axes + 3 buttons (or 11 buttons)"names": joint_names + ["joy_axis_" + str(i) for i in range(8)] + ["joy_button_" + str(i) for i in range(11)]},"observation": {"state": {"dtype": "float32","shape": [36], # 26 joint_positions + 10 imu"names": joint_names + ["imu_orientation.x", "imu_orientation.y", "imu_orientation.z", "imu_orientation.w", "imu_angular_velocity.x", "imu_angular_velocity.y", "imu_angular_velocity.z", "imu_linear_acceleration.x", "imu_linear_acceleration.y", "imu_linear_acceleration.z"]},"images": {"generic": {6 unmodified lines},"timestamp": { "dtype": "float64", "shape": [1] },"frame_index": { "dtype": "int64", "shape": [1] },"episode_index": { "dtype": "int64", "shape": [1] },"index": { "dtype": "int64", "shape": [1] },"task_index": { "dtype": "int64", "shape": [1] }}}info = base_infoepisode_idx = 0if info_path.exists():try:with open(info_path, 'r') as f:existing_info = json.load(f)info['total_episodes'] = existing_info.get('total_episodes', 0)info['total_frames'] = existing_info.get('total_frames', 0)info['total_videos'] = existing_info.get('total_videos', 0)6 unmodified linesif info_path.exists():os.remove(info_path)episodes_data = []if episodes_jsonl_path.exists():try:5 unmodified linesif episodes_jsonl_path.exists():os.remove(episodes_jsonl_path)create_tasks_file(META_DIR, tasks_list)create_readme(REPO_ID, info, LOCAL_ROOT_DIR)21 unmodified linesws_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)ws_manager.subscribe(OBSERVATION_TOPICS["joy"]["topic"], OBSERVATION_TOPICS["joy"]["msg_type"], joy_callback)ws_manager.subscribe(OBSERVATION_TOPICS["action_commands"]["topic"], OBSERVATION_TOPICS["action_commands"]["msg_type"], action_commands_callback)print("Подписки установлены.")print("\nСбор данных запущен. Выполняйте движения роботом.")3 unmodified linescurrent_episode_start_time = time.time()all_images_generic = []all_observation_states = []all_actions = []all_timestamps = []all_frame_indices = []all_episode_indices = []all_indices = []all_task_indices = []total_frames_collected = 07 unmodified linesimu_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)action_commands_data = latest_data["action_commands"][0] if latest_data["action_commands"] is not None else np.array([0.0]*26, dtype=np.float32)joy_data = latest_data["joy"][0] if latest_data["joy"] is not None else ([], [])joy_axes = joy_data[0] if joy_data[0] else [0.0] * 8joy_buttons = joy_data[1] if joy_data[1] else [0] * 11# Формируем объединенное состояние наблюденияcombined_observation_state = np.concatenate((joint_positions_data, imu_data)).tolist()all_observation_states.append(combined_observation_state)# Формируем объединенное действиеcombined_action = np.concatenate((action_commands_data, np.array(joy_axes), np.array(joy_buttons, dtype=np.float32))).tolist()all_actions.append(combined_action)all_images_generic.append(img_generic)all_timestamps.append(img_timestamp)all_frame_indices.append(total_frames_collected)all_episode_indices.append(episode_idx)all_indices.append(info['total_frames'] + total_frames_collected)all_task_indices.append(0) # Пример, можно настроитьlatest_data["camera_generic"] = Nonetotal_frames_collected += 16 unmodified linescreate_video(all_images_generic, video_path_generic)df = pd.DataFrame({'action': all_actions,'observation.state': all_observation_states,'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),'timestamp': all_timestamps,'frame_index': all_frame_indices,'episode_index': all_episode_indices,'index': all_indices,'task_index': all_task_indices})table = pa.Table.from_pandas(df)7 unmodified linesepisodes_data.append({"episode_index": episode_idx,"tasks": [0],"length": len(all_images_generic)})create_episodes_file(META_DIR, episodes_data)2 unmodified linesepisode_idx += 1current_episode_start_time = time.time()all_images_generic = []all_observation_states = []all_actions = []all_timestamps = []all_frame_indices = []all_episode_indices = []all_indices = []all_task_indices = []time.sleep(0.01)except Exception as e:7 unmodified linescreate_video(all_images_generic, video_path_generic)df = pd.DataFrame({'action': all_actions,'observation.state': all_observation_states,'observation.images.generic': [f"../../videos/chunk-000/observation.images.generic/episode_{episode_idx:06d}.mp4"] * len(all_images_generic),'timestamp': all_timestamps,'frame_index': all_frame_indices,'episode_index': all_episode_indices,'index': all_indices,'task_index': all_task_indices})table = pa.Table.from_pandas(df)7 unmodified linesepisodes_data.append({"episode_index": episode_idx,"tasks": [0],"length": len(all_images_generic)})create_episodes_file(META_DIR, episodes_data)
collect_and_upload.py+67-66