Spaces:
Runtime error
Runtime error
Download app.py from KillzoneCCO/robot: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/spaces/KillzoneCCO/robot/resolve/main/app.py
- Command line
-
hf download hf://spaces/KillzoneCCO/robot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/KillzoneCCO/robot/resolve/main/app.py
23.3 kB
| # app.py | |
| from datasets import load_dataset, Dataset, Image as DatasetImage, Value, Array2D, Features | |
| import gradio as gr | |
| import pandas as pd | |
| from PIL import Image as PILImage | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import io | |
| import time | |
| import imageio # Добавляем для создания видео | |
| import os # Для работы с файловой системой (временные файлы) | |
| # --- Настройки вашего датасета --- | |
| DATASET_REPO_ID = "KillzoneCCO/my-ainex-robot-dataset" # Убедитесь, что это ваш ID репозитория | |
| DATASET_SPLIT = "train" | |
| # Глобальная переменная для хранения загруженного и сгруппированного датасета | |
| my_episodes = None | |
| dataset_features = None | |
| # --- Функция загрузки и подготовки данных --- | |
| def load_and_prepare_dataset(): | |
| """Загружает датасет с Hugging Face Hub и группирует по эпизодам.""" | |
| global my_episodes, dataset_features | |
| print("Attempting to load dataset...") | |
| try: | |
| dataset = load_dataset(DATASET_REPO_ID, split=DATASET_SPLIT) | |
| dataset_features = dataset.features # Сохраняем фичи датасета | |
| if len(dataset) == 0: | |
| error_msg = "Датасет пуст. Нет данных для отображения." | |
| print(error_msg) | |
| my_episodes = {} | |
| # Возвращаем также пустой список для чекбоксов | |
| return error_msg, gr.update(choices=[], value=None), gr.update(choices=[], value=[]) | |
| episodes_data = {} | |
| for i, row in enumerate(dataset): | |
| episode_idx_raw = row.get("episode_index") | |
| if episode_idx_raw is None: | |
| episode_idx_raw = 0 | |
| row["episode_index"] = 0 | |
| print(f"Warning: 'episode_index' not found for row {i}. Setting to 0.") | |
| # Используем 1-индексированный номер эпизода для ключа, чтобы совпадать с отображением | |
| episode_idx = int(episode_idx_raw) + 1 | |
| if episode_idx not in episodes_data: | |
| episodes_data[episode_idx] = [] | |
| episodes_data[episode_idx].append(row) | |
| # Сортируем шаги внутри каждого эпизода по временной метке, если есть | |
| for episode_idx in episodes_data: | |
| episodes_data[episode_idx].sort(key=lambda x: x.get("timestamp", 0)) | |
| my_episodes = episodes_data | |
| print(f"Dataset loaded. Found {len(my_episodes)} episodes.") | |
| episode_options = sorted(list(my_episodes.keys())) | |
| # Определяем опции для чекбоксов сервоприводов | |
| servo_options = [f"Servo_{i+1}" for i in range(25)] # Предполагаем 25 сервоприводов | |
| # Возвращаем также опции для чекбоксов | |
| return f"Датасет '{DATASET_REPO_ID}' загружен. Найдено {len(my_episodes)} эпизодов.", \ | |
| gr.update(choices=episode_options, value=episode_options[0] if episode_options else None), \ | |
| gr.update(choices=servo_options, value=servo_options) # Все выбраны по умолчанию | |
| except Exception as e: | |
| error_msg = f"Ошибка при загрузке или подготовке датасета: {e}" | |
| print(error_msg) | |
| my_episodes = {} | |
| return error_msg, gr.update(choices=[], value=None), gr.update(choices=[], value=[]) | |
| # --- Функция для отображения данных конкретного шага --- | |
| def display_step_data(selected_episode_idx, step_idx): | |
| global my_episodes | |
| # Убедимся, что selected_episode_idx не None | |
| if selected_episode_idx is None: | |
| return "", None, {}, {}, 0.0 # Добавляем timestamp | |
| if not my_episodes or selected_episode_idx not in my_episodes: | |
| return "Данные эпизода не найдены.", None, {}, {}, 0.0 # Добавляем timestamp | |
| episode_steps = my_episodes.get(selected_episode_idx) | |
| if not episode_steps: | |
| return "Данные эпизода пусты.", None, {}, {}, 0.0 # Добавляем timestamp | |
| # Убежимся, что step_idx находится в допустимых границах | |
| if not (0 <= step_idx < len(episode_steps)): | |
| return "Неверный номер шага или шаг вне диапазона.", None, {}, {}, 0.0 # Добавляем timestamp | |
| step_data = episode_steps[step_idx] | |
| # Подготовьте информацию о шаге | |
| step_info = ( | |
| f"Эпизод: {step_data.get('episode_index', 'N/A')}, " | |
| f"Шаг: {step_idx}/{len(episode_steps)-1}, " | |
| f"Вознаграждение: {step_data.get('reward', 0.0):.2f}, " | |
| f"Завершено: {step_data.get('terminated', False)}, " | |
| f"Усечено: {step_data.get('truncated', False)}, " | |
| f"Timestamp: {step_data.get('timestamp', 0.0):.2f}" | |
| ) | |
| # Обработка изображения | |
| image_pil = None | |
| if 'observation.camera_image_left' in step_data: | |
| img_data = step_data['observation.camera_image_left'] | |
| if isinstance(img_data, PILImage.Image): | |
| image_pil = img_data | |
| elif isinstance(img_data, dict) and 'bytes' in img_data: | |
| try: | |
| image_pil = PILImage.open(io.BytesIO(img_data['bytes'])) | |
| except Exception as e: | |
| print(f"Error opening image from bytes: {e}") | |
| elif img_data is not None: | |
| print(f"Unexpected image format type: {type(img_data)}") | |
| # Обработка наблюдений (исключаем image, так как он уже обработан) | |
| observation_data = {} | |
| for k, v in step_data.items(): | |
| if k.startswith("observation.") and k != "observation.camera_image_left": | |
| clean_key = k[len("observation."):] | |
| if isinstance(v, np.ndarray): | |
| observation_data[clean_key] = v.squeeze().tolist() | |
| else: | |
| observation_data[clean_key] = v | |
| # Обработка действий | |
| action_data = {} | |
| for k, v in step_data.items(): | |
| if k.startswith("action."): | |
| clean_key = k[len("action."):] | |
| if isinstance(v, np.ndarray): | |
| action_data[clean_key] = v.squeeze().tolist() | |
| else: | |
| action_data[clean_key] = v | |
| # Возвращаем timestamp для синхронизации видео | |
| current_timestamp = step_data.get('timestamp', 0.0) | |
| return step_info, image_pil, observation_data, action_data, current_timestamp | |
| # --- Функция для построения графика начальной позиции --- | |
| def plot_initial_pose(initial_pose_data): | |
| if not initial_pose_data: | |
| return None | |
| # Сортируем ключи, чтобы порядок сервоприводов был правильным | |
| sorted_keys = sorted(initial_pose_data.keys(), key=lambda x: int(x.split('_')[1])) | |
| servo_ids = [int(k.split('_')[1]) for k in sorted_keys] | |
| positions = [initial_pose_data[k] for k in sorted_keys] | |
| fig, ax = plt.subplots(figsize=(10, 5)) | |
| ax.bar(servo_ids, positions, color='skyblue') | |
| ax.set_title('Начальная позиция сервоприводов', fontsize=14, fontweight='bold') | |
| ax.set_xlabel('ID Сервопривода', fontsize=12) | |
| ax.set_ylabel('Позиция', fontsize=12) | |
| ax.set_xticks(servo_ids) # Убедимся, что все ID сервоприводов отображаются | |
| ax.grid(axis='y', linestyle='--', alpha=0.7) | |
| plt.tight_layout() | |
| return fig | |
| # --- Функция для обновления информации об эпизоде при выборе --- | |
| def update_episode_info(selected_episode_idx): | |
| global my_episodes | |
| if not my_episodes or selected_episode_idx is None: | |
| # Добавляем пустой список для initial_servo_checkboxes | |
| return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}, None, gr.update(choices=[], value=[]) | |
| episode_steps = my_episodes.get(selected_episode_idx) | |
| if not episode_steps: | |
| return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}, None, gr.update(choices=[], value=[]) | |
| num_steps = len(episode_steps) | |
| if num_steps == 0: | |
| return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}, None, gr.update(choices=[], value=[]) | |
| # Получаем данные для первого шага, чтобы инициализировать UI | |
| step_info, image_pil, observation_data, action_data, _ = display_step_data(selected_episode_idx, 0) # timestamp не нужен здесь | |
| # Извлекаем начальную позицию сервоприводов (observation.joint_positions первого шага) | |
| initial_joint_positions_dict = {} | |
| if 'joint_positions' in observation_data and observation_data['joint_positions']: | |
| # observation_data['joint_positions'] может быть списком списков, берем первый элемент | |
| flat_positions = np.array(observation_data['joint_positions']).flatten().tolist() | |
| initial_joint_positions_dict = {f"Servo_{i+1}": pos for i, pos in enumerate(flat_positions)} | |
| # Создаем график начальной позиции | |
| initial_pose_plot = plot_initial_pose(initial_joint_positions_dict) | |
| # Определяем опции для чекбоксов сервоприводов для графика действий | |
| servo_options = [f"Servo_{i+1}" for i in range(25)] | |
| return ( | |
| gr.update(maximum=num_steps - 1, value=0), | |
| str(num_steps), | |
| step_info, | |
| image_pil, | |
| observation_data, | |
| action_data, | |
| initial_pose_plot, # Возвращаем график начальной позиции | |
| gr.update(choices=servo_options, value=servo_options) # Все выбраны по умолчанию | |
| ) | |
| # --- Функция для построения графика действий с выбором линий --- | |
| def plot_actions_for_episode(selected_episode_idx, selected_servos): | |
| global my_episodes | |
| if not my_episodes or selected_episode_idx is None: | |
| return None | |
| if not selected_servos: # Если ничего не выбрано, возвращаем пустой график | |
| fig, ax = plt.subplots(figsize=(12, 7)) | |
| ax.set_title(f'Выберите сервоприводы для отображения', fontsize=14, fontweight='bold') | |
| ax.set_xlabel('Шаг (Step)', fontsize=12) | |
| ax.set_ylabel('Значение команды сервопривода', fontsize=12) | |
| plt.tight_layout() | |
| return fig | |
| episode_steps = my_episodes.get(selected_episode_idx) | |
| if not episode_steps: | |
| return None | |
| actions_data = [] | |
| for step in episode_steps: | |
| servo_commands = step.get('action.servo_commands') | |
| if servo_commands is not None: | |
| actions_data.append(np.array(servo_commands).flatten().tolist()) | |
| if not actions_data: | |
| return None | |
| df_data = [] | |
| for step_actions in actions_data: | |
| if step_actions: | |
| row = {f'Servo_{i+1}': val for i, val in enumerate(step_actions)} | |
| df_data.append(row) | |
| else: | |
| df_data.append({}) | |
| if not df_data: | |
| return None | |
| df_actions = pd.DataFrame(df_data) | |
| fig, ax = plt.subplots(figsize=(12, 7)) | |
| for col in selected_servos: # Итерируем только по выбранным сервоприводам | |
| if col in df_actions.columns: | |
| ax.plot(df_actions.index, df_actions[col], label=col, linewidth=1, alpha=0.8) | |
| ax.set_title(f'Динамика команд сервоприводов для эпизода {selected_episode_idx}', fontsize=14, fontweight='bold') | |
| ax.set_xlabel('Шаг (Step)', fontsize=12) | |
| ax.set_ylabel('Значение команды сервопривода', fontsize=12) | |
| ax.legend(title='Сервопривод', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=10) | |
| plt.grid(True, linestyle='--', alpha=0.6) | |
| plt.tight_layout(rect=[0, 0, 0.9, 1]) | |
| return fig | |
| # --- Функция для создания видео из изображений эпизода --- | |
| def create_video_from_episode(selected_episode_idx, fps=10): | |
| """ | |
| Создает временный MP4 файл из изображений выбранного эпизода. | |
| Возвращает путь к файлу. | |
| """ | |
| global my_episodes | |
| if selected_episode_idx is None or selected_episode_idx not in my_episodes or not my_episodes[selected_episode_idx]: | |
| return None | |
| episode_steps = my_episodes.get(selected_episode_idx) | |
| if not episode_steps: | |
| return None | |
| images_for_video = [] | |
| for step_data in episode_steps: | |
| image_pil = None | |
| if 'observation.camera_image_left' in step_data: | |
| img_data = step_data['observation.camera_image_left'] | |
| if isinstance(img_data, PILImage.Image): | |
| image_pil = img_data | |
| elif isinstance(img_data, dict) and 'bytes' in img_data: | |
| try: | |
| image_pil = PILImage.open(io.BytesIO(img_data['bytes'])) | |
| except Exception as e: | |
| print(f"Error opening image from bytes: {e}") | |
| elif img_data is not None: | |
| print(f"Unexpected image format type: {type(img_data)}") | |
| if image_pil: | |
| images_for_video.append(np.array(image_pil)) # Преобразуем PIL Image в NumPy array | |
| if not images_for_video: | |
| print(f"No images found for episode {selected_episode_idx} to create video.") | |
| return None | |
| # Создаем временный файл MP4 | |
| # Hugging Face Spaces обычно имеют доступ к /tmp/ | |
| temp_video_path = f"/tmp/episode_{selected_episode_idx}_{int(time.time())}.mp4" | |
| try: | |
| # imageio.mimsave требует список NumPy массивов | |
| imageio.mimsave(temp_video_path, images_for_video, fps=fps, codec='libx264', quality=8) | |
| print(f"Video created at: {temp_video_path}") | |
| return temp_video_path | |
| except Exception as e: | |
| print(f"Ошибка при создании видео: {e}") | |
| # Если произошла ошибка, попытаемся удалить недосозданный файл | |
| if os.path.exists(temp_video_path): | |
| os.remove(temp_video_path) | |
| return None | |
| # --- Функция для синхронизации видео по времени шага --- | |
| def seek_video_to_step_time(selected_episode_idx, step_idx): | |
| global my_episodes | |
| if selected_episode_idx is None or selected_episode_idx not in my_episodes or not my_episodes[selected_episode_idx]: | |
| return None # Не можем перемотать, если нет данных | |
| episode_steps = my_episodes.get(selected_episode_idx) | |
| if not episode_steps or not (0 <= step_idx < len(episode_steps)): | |
| return None | |
| # Получаем timestamp первого шага эпизода, чтобы отсчитывать смещение | |
| first_timestamp = episode_steps[0].get('timestamp', 0.0) | |
| current_timestamp = episode_steps[step_idx].get('timestamp', 0.0) | |
| # Вычисляем относительное время в секундах от начала эпизода | |
| seek_time = current_timestamp - first_timestamp | |
| # Возвращаем объект gr.Video.update с новой позицией перемотки | |
| # Gradio автоматически обработает это для перемотки видео | |
| return gr.Video(value=None, seek=seek_time) # value=None, чтобы не менять источник видео, только перемотать | |
| # --- Gradio интерфейс --- | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Интерактивный просмотр датасета робота Ainex") | |
| gr.Markdown("Загрузите ваш датасет с Hugging Face Hub и исследуйте собранные данные. Нажмите 'Обновить датасет', чтобы загрузить последние данные.") | |
| with gr.Row(): | |
| with gr.Column(scale=1): # Левая колонка | |
| refresh_button = gr.Button("Обновить датасет") | |
| refresh_status = gr.Textbox(label="Статус загрузки датасета", value="Нажмите 'Обновить датасет' для начала.") | |
| episode_selector = gr.Dropdown(label="Выберите эпизод (1-индексированный)", choices=[], interactive=True) | |
| num_steps_in_episode_output = gr.Textbox(label="Всего шагов в эпизоде", interactive=False) | |
| with gr.Row(): | |
| step_slider = gr.Slider(minimum=0, maximum=0, value=0, label="Выберите шаг (0-индексированный)", step=1, interactive=True, scale=4) | |
| play_video_button = gr.Button("▶️ Воспроизвести видео", scale=1) | |
| video_fps_slider = gr.Slider(minimum=1, maximum=30, value=10, label="FPS видео", step=1, interactive=True) | |
| # График начальной позиции робота | |
| initial_pose_plot_output = gr.Plot(label="Начальная позиция сервоприводов") | |
| # Чекбоксы для выбора сервоприводов на графике действий | |
| servo_checkboxes = gr.CheckboxGroup( | |
| label="Выбрать сервоприводы для графика действий", | |
| choices=[f"Servo_{i+1}" for i in range(25)], | |
| value=[f"Servo_{i+1}" for i in range(25)], | |
| interactive=True, | |
| elem_id="servo_checkboxes" | |
| ) | |
| # Кнопка для отображения графика действий (остается в левой колонке) | |
| plot_actions_button = gr.Button("Показать график действий") | |
| with gr.Column(scale=2): # Правая колонка | |
| step_info_output = gr.Textbox(label="Информация о шаге", interactive=False) | |
| video_output = gr.Video(label="Воспроизведение эпизода", height=480, autoplay=False) | |
| single_image_output = gr.Image(label="Текущий кадр (для слайдера)", type="pil", height=480) | |
| # Перемещенный график команд сервоприводов (теперь выше) | |
| action_plot_output = gr.Plot(label="График команд сервоприводов") | |
| # Перемещенные детальные данные (теперь ниже) | |
| with gr.Accordion("Детальные данные", open=True): | |
| observation_output = gr.Json(label="Наблюдения (observation)") | |
| action_output = gr.Json(label="Действия (action)") | |
| # Удалена нижняя строка с анализом данных | |
| # with gr.Row(): | |
| # with gr.Column(): | |
| # analysis_text_output = gr.Textbox(label="Результаты анализа", interactive=False) | |
| # analysis_plot_output = gr.Plot(label="Гистограмма положений суставов") | |
| # with gr.Column(): | |
| # action_plot_output = gr.Plot(label="График команд сервоприводов") # Это было здесь | |
| # --- Логика взаимодействия --- | |
| demo.load( | |
| load_and_prepare_dataset, | |
| inputs=None, | |
| outputs=[refresh_status, episode_selector, servo_checkboxes] | |
| ).then( | |
| update_episode_info, | |
| inputs=episode_selector, | |
| outputs=[step_slider, num_steps_in_episode_output, step_info_output, single_image_output, observation_output, action_output, initial_pose_plot_output, servo_checkboxes] | |
| ).then( | |
| # Перерисовываем график действий при смене эпизода | |
| plot_actions_for_episode, | |
| inputs=[episode_selector, servo_checkboxes], | |
| outputs=action_plot_output | |
| ) | |
| episode_selector.change( | |
| update_episode_info, | |
| inputs=episode_selector, | |
| outputs=[step_slider, num_steps_in_episode_output, step_info_output, single_image_output, observation_output, action_output, initial_pose_plot_output, servo_checkboxes] | |
| ).then( | |
| # Перерисовываем график действий при смене эпизода | |
| plot_actions_for_episode, | |
| inputs=[episode_selector, servo_checkboxes], | |
| outputs=action_plot_output | |
| ) | |
| step_slider.change( | |
| display_step_data, | |
| inputs=[episode_selector, step_slider], | |
| outputs=[step_info_output, single_image_output, observation_output, action_output, gr.State()] | |
| ).then( | |
| # Синхронизация видео с ползунком шагов | |
| seek_video_to_step_time, | |
| inputs=[episode_selector, step_slider], | |
| outputs=video_output | |
| ) | |
| refresh_button.click( | |
| load_and_prepare_dataset, | |
| inputs=None, | |
| outputs=[refresh_status, episode_selector, servo_checkboxes] | |
| ).then( | |
| update_episode_info, | |
| inputs=episode_selector, | |
| outputs=[step_slider, num_steps_in_episode_output, step_info_output, single_image_output, observation_output, action_output, initial_pose_plot_output, servo_checkboxes] | |
| ).then( | |
| # Перерисовываем график действий при обновлении датасета | |
| plot_actions_for_episode, | |
| inputs=[episode_selector, servo_checkboxes], | |
| outputs=action_plot_output | |
| ) | |
| # analyze_button.click удален | |
| # analyze_button.click( | |
| # analyze_data, | |
| # inputs=None, | |
| # outputs=[analysis_text_output, analysis_plot_output] | |
| # ) | |
| play_video_button.click( | |
| create_video_from_episode, | |
| inputs=[episode_selector, video_fps_slider], | |
| outputs=[video_output], | |
| queue=False | |
| ) | |
| plot_actions_button.click( | |
| plot_actions_for_episode, | |
| inputs=[episode_selector, servo_checkboxes], | |
| outputs=action_plot_output | |
| ) | |
| # Логика для чекбоксов сервоприводов | |
| servo_checkboxes.change( | |
| plot_actions_for_episode, | |
| inputs=[episode_selector, servo_checkboxes], | |
| outputs=action_plot_output | |
| ) | |
| demo.launch(debug=True) | |