Spaces:
Runtime error
Runtime error
File size: 23,292 Bytes
fc36443 89eb6ab fc36443 e2601b3 ba5e9ab 4f100b1 ba5e9ab da83c30 fc36443 89eb6ab da83c30 fc36443 4f100b1 89eb6ab 4f100b1 fc36443 e2601b3 89eb6ab ba5e9ab fc36443 89eb6ab 6f65cf4 4836425 81e8460 6f65cf4 e2601b3 4836425 da83c30 89eb6ab 8e6e374 2baa2d9 da83c30 89eb6ab da83c30 89eb6ab da83c30 89eb6ab 81e8460 073aeea 89eb6ab 073aeea 89eb6ab 81e8460 fc36443 b40dc32 89eb6ab da83c30 ea06a51 3a1e584 81e8460 3a1e584 81e8460 3a1e584 2baa2d9 81e8460 2baa2d9 b40dc32 89eb6ab 81e8460 89eb6ab ea06a51 89eb6ab da83c30 89eb6ab 2baa2d9 89eb6ab 49b2fa7 ea06a51 2baa2d9 da83c30 2baa2d9 ea06a51 81e8460 ea06a51 81e8460 ea06a51 b40dc32 89eb6ab 81e8460 89eb6ab 2baa2d9 81e8460 2baa2d9 89eb6ab 81e8460 89eb6ab da83c30 81e8460 da83c30 b40dc32 81e8460 89eb6ab da83c30 b40dc32 81e8460 89eb6ab 073aeea 81e8460 89eb6ab 81e8460 89eb6ab 2baa2d9 89eb6ab 2baa2d9 da83c30 89eb6ab da83c30 89eb6ab da83c30 81e8460 da83c30 89eb6ab da83c30 89eb6ab 81e8460 89eb6ab 5e044a9 da83c30 ea06a51 da83c30 ea06a51 da83c30 ea06a51 da83c30 ea06a51 da83c30 ea06a51 da83c30 ea06a51 81e8460 8403e19 a7b083b 8403e19 da83c30 8403e19 da83c30 ea06a51 b40dc32 da83c30 81e8460 b40dc32 81e8460 a7b083b 81e8460 a7b083b 81e8460 a7b083b 8403e19 a7b083b 8403e19 b7868e2 da83c30 a7b083b 8403e19 a7b083b 8403e19 a7b083b 8403e19 81e8460 a7b083b 8403e19 81e8460 8403e19 a7b083b 81e8460 a7b083b 8403e19 a7b083b 8403e19 81e8460 8403e19 da83c30 a7b083b 8403e19 da83c30 b40dc32 8403e19 a7b083b 81e8460 8403e19 cc35701 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | # 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)
|