KillzoneCCO commited on
Commit
ea06a51
·
verified ·
1 Parent(s): e7e1a33

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -126
app.py CHANGED
@@ -6,10 +6,7 @@ from PIL import Image as PILImage
6
  import numpy as np
7
  import matplotlib.pyplot as plt
8
  import io
9
- import time
10
- import os
11
- import tempfile
12
- import imageio.v3 as iio # Импортируем imageio.v3
13
 
14
  # --- Настройки вашего датасета ---
15
  DATASET_REPO_ID = "KillzoneCCO/my-ainex-robot-dataset" # Убедитесь, что это ваш ID репозитория
@@ -19,7 +16,6 @@ DATASET_SPLIT = "train"
19
  my_episodes = None
20
  dataset_features = None
21
  playback_active = False # Флаг для управления воспроизведением
22
- current_video_path = None # Для отслеживания текущего временного видеофайла
23
 
24
  # --- Функция загрузки и подготовки данных ---
25
  def load_and_prepare_dataset():
@@ -70,21 +66,27 @@ def load_and_prepare_dataset():
70
  def display_step_data(selected_episode_idx, step_idx):
71
  global my_episodes
72
 
 
73
  if selected_episode_idx is None:
74
  return "", None, {}, {}
75
 
76
  if not my_episodes or selected_episode_idx not in my_episodes:
 
77
  return "Данные эпизода не найдены.", None, {}, {}
78
 
79
  episode_steps = my_episodes.get(selected_episode_idx)
80
  if not episode_steps:
 
81
  return "Данные эпизода пусты.", None, {}, {}
82
 
 
83
  if not (0 <= step_idx < len(episode_steps)):
 
84
  return "Неверный номер шага или шаг вне диапазона.", None, {}, {}
85
 
86
  step_data = episode_steps[step_idx]
87
 
 
88
  step_info = (
89
  f"Эпизод: {step_data.get('episode_index', 'N/A')}, "
90
  f"Шаг: {step_idx}/{len(episode_steps)-1}, "
@@ -94,6 +96,7 @@ def display_step_data(selected_episode_idx, step_idx):
94
  f"Timestamp: {step_data.get('timestamp', 0.0):.2f}"
95
  )
96
 
 
97
  image_pil = None
98
  if 'observation.camera_image_left' in step_data:
99
  img_data = step_data['observation.camera_image_left']
@@ -106,26 +109,45 @@ def display_step_data(selected_episode_idx, step_idx):
106
  print(f"Error opening image from bytes: {e}")
107
  elif img_data is not None:
108
  print(f"Unexpected image format type: {type(img_data)}")
109
-
110
- # Возвращаем None для видео, так как это статичное отображение шага
111
- return step_info, image_pil, {}, {}
112
 
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  # --- Функция для обновления информации об эпизоде при выборе ---
115
  def update_episode_info(selected_episode_idx):
116
  global my_episodes
117
  if not my_episodes or selected_episode_idx is None:
118
- return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}, None # Добавлен None для video_output
119
 
120
  episode_steps = my_episodes.get(selected_episode_idx)
121
  if not episode_steps:
122
- return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}, None # Добавлен None для video_output
123
 
124
  num_steps = len(episode_steps)
125
  if num_steps == 0:
126
- return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}, None # Добавлен None для video_output
127
 
128
- # Для первого шага отобразим изображение и данные (видео будет загружен�� по кнопке)
129
  step_info, image_pil, observation_data, action_data = display_step_data(selected_episode_idx, 0)
130
 
131
  return (
@@ -134,100 +156,9 @@ def update_episode_info(selected_episode_idx):
134
  step_info,
135
  image_pil,
136
  observation_data,
137
- action_data,
138
- None # При переключении эпизода сбрасываем видео
139
  )
140
 
141
- # --- НОВАЯ ФУНКЦИЯ: Создание видео из кадров с использованием imageio ---
142
- def create_video_from_frames(frames, fps=10):
143
- """
144
- Создает временный видеофайл MP4 из списка PIL-изображений с использованием imageio.
145
- :param frames: Список PIL.Image объектов.
146
- :param fps: Кадров в секунду для видео.
147
- :return: Путь к созданному временному видеофайлу.
148
- """
149
- if not frames:
150
- return None
151
-
152
- # Преобразуем PIL изображения в numpy массивы (RGB)
153
- # iio.imwrite ожидает список numpy массивов
154
- numpy_frames = [np.array(frame.convert("RGB")) for frame in frames if frame is not None]
155
-
156
- if not numpy_frames:
157
- return None
158
-
159
- # Создаем временный файл
160
- temp_dir = tempfile.gettempdir()
161
- video_path = os.path.join(temp_dir, f"episode_video_{int(time.time())}.mp4")
162
-
163
- print(f"Creating video using imageio: {video_path} with {len(numpy_frames)} frames at {fps} fps.")
164
- try:
165
- # Используем imageio.mimsave для сохранения последовательности изображений в видео
166
- iio.imwrite(video_path, numpy_frames, fps=fps, codec='libx264', macro_block_size=8, quality=8)
167
- print(f"Video created successfully by imageio at {video_path}")
168
- return video_path
169
- except Exception as e:
170
- print(f"Error creating video with imageio: {e}")
171
- return None
172
-
173
- # --- НОВАЯ ФУНКЦИЯ: Очистка временного видеофайла ---
174
- def clear_temp_video():
175
- global current_video_path
176
- if current_video_path and os.path.exists(current_video_path):
177
- try:
178
- os.remove(current_video_path)
179
- print(f"Removed temporary video: {current_video_path}")
180
- except Exception as e:
181
- print(f"Error removing temporary video {current_video_path}: {e}")
182
- current_video_path = None
183
-
184
-
185
- # --- Функция воспроизведения шагов (теперь генерирует видео) ---
186
- def play_steps_as_video(selected_episode_idx):
187
- global my_episodes, playback_active, current_video_path
188
-
189
- clear_temp_video() # Удаляем предыдущее видео перед созданием нового
190
-
191
- if selected_episode_idx is None or selected_episode_idx not in my_episodes or not my_episodes[selected_episode_idx]:
192
- print("Cannot play video: No episode selected or episode data missing.")
193
- return None # Возвращаем None для video_output
194
-
195
- episode_steps = my_episodes.get(selected_episode_idx)
196
- if not episode_steps:
197
- print(f"Episode {selected_episode_idx} has no steps to play.")
198
- return None
199
-
200
- all_frames = []
201
- for step_data in episode_steps:
202
- if 'observation.camera_image_left' in step_data:
203
- img_data = step_data['observation.camera_image_left']
204
- image_pil = None
205
- if isinstance(img_data, PILImage.Image):
206
- image_pil = img_data
207
- elif isinstance(img_data, dict) and 'bytes' in img_data:
208
- try:
209
- image_pil = PILImage.open(io.BytesIO(img_data['bytes']))
210
- except Exception as e:
211
- print(f"Error opening image from bytes during video frame collection: {e}")
212
-
213
- if image_pil:
214
- all_frames.append(image_pil)
215
-
216
- if not all_frames:
217
- print("No valid image frames found for video creation.")
218
- return None
219
-
220
- print(f"Collected {len(all_frames)} frames for video creation.")
221
-
222
- # Создаем видеофайл
223
- video_path = create_video_from_frames(all_frames, fps=10) # Вы можете настроить FPS
224
-
225
- if video_path:
226
- current_video_path = video_path
227
- return video_path # Возвращаем путь к видео для gr.Video
228
- else:
229
- return None
230
-
231
 
232
  # --- Функция для анализа данных (гистограммы положений суставов) ---
233
  def analyze_data():
@@ -307,6 +238,51 @@ def plot_actions_for_episode(selected_episode_idx):
307
  return fig
308
 
309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  # --- Gradio интерфейс ---
311
  with gr.Blocks() as demo:
312
  gr.Markdown("# Интерактивный просмотр датасета робота Ainex")
@@ -320,10 +296,10 @@ with gr.Blocks() as demo:
320
  episode_selector = gr.Dropdown(label="Выберите эпизод (1-индексированный)", choices=[], interactive=True)
321
  num_steps_in_episode_output = gr.Textbox(label="Всего шагов в эпизоде", interactive=False)
322
 
323
- # Слайдер для навигации по шагам теперь нужен только для просмотра статических данных, не для воспроизведения видео
324
- step_slider = gr.Slider(minimum=0, maximum=0, value=0, label="Выберите шаг (0-индексированный)", step=1, interactive=True, scale=4)
325
- # Кнопка воспроизведения теперь запускает создание и отображение видео
326
- play_video_button = gr.Button("▶️ Воспроизвести видео", scale=1)
327
 
328
  analyze_button = gr.Button("Анализ данных (Гистограмма Joint Positions)")
329
  plot_actions_button = gr.Button("Показать график действий")
@@ -331,7 +307,7 @@ with gr.Blocks() as demo:
331
 
332
  with gr.Column(scale=2):
333
  step_info_output = gr.Textbox(label="Информация о шаге", interactive=False)
334
- video_output = gr.Video(label="Видео с камеры робота", height=480, autoplay=False) # Новый компонент Video
335
 
336
  with gr.Accordion("Детальные данные", open=True):
337
  observation_output = gr.Json(label="Наблюдения (observation)")
@@ -352,20 +328,19 @@ with gr.Blocks() as demo:
352
  ).then(
353
  update_episode_info,
354
  inputs=episode_selector,
355
- outputs=[step_slider, num_steps_in_episode_output, step_info_output, video_output, observation_output, action_output, video_output] # Обновлено для video_output
356
  )
357
 
358
  episode_selector.change(
359
  update_episode_info,
360
  inputs=episode_selector,
361
- outputs=[step_slider, num_steps_in_episode_output, step_info_output, video_output, observation_output, action_output, video_output] # Обновлено для video_output
362
  )
363
 
364
- # При изменении слайдера (вручную) по-прежнему показываем статичное изображение и данные
365
  step_slider.change(
366
  display_step_data,
367
  inputs=[episode_selector, step_slider],
368
- outputs=[step_info_output, video_output, observation_output, action_output] # Обновлено для video_output, video_output будет показывать кадр
369
  )
370
 
371
  refresh_button.click(
@@ -375,7 +350,7 @@ with gr.Blocks() as demo:
375
  ).then(
376
  update_episode_info,
377
  inputs=episode_selector,
378
- outputs=[step_slider, num_steps_in_episode_output, step_info_output, video_output, observation_output, action_output, video_output] # Обновлено для video_output
379
  )
380
 
381
  analyze_button.click(
@@ -384,15 +359,19 @@ with gr.Blocks() as demo:
384
  outputs=[analysis_text_output, analysis_plot_output]
385
  )
386
 
387
- # --- НОВОЕ: Кнопка воспроизведения видео ---
388
- play_video_button.click(
389
- play_steps_as_video,
390
- inputs=[episode_selector],
391
- outputs=[video_output],
392
- queue=False # Важно, чтобы не блокировать UI
393
- ).then(
394
- lambda: gr.update(value=0), # Сбросить слайдер на 0 после загрузки видео
395
- outputs=[step_slider]
 
 
 
 
396
  )
397
 
398
  plot_actions_button.click(
@@ -401,7 +380,4 @@ with gr.Blocks() as demo:
401
  outputs=action_plot_output
402
  )
403
 
404
- # Хук для удаления временного видеофайла при завершении работы Gradio
405
- demo.on_close(clear_temp_video)
406
-
407
  demo.launch(debug=True)
 
6
  import numpy as np
7
  import matplotlib.pyplot as plt
8
  import io
9
+ import time
 
 
 
10
 
11
  # --- Настройки вашего датасета ---
12
  DATASET_REPO_ID = "KillzoneCCO/my-ainex-robot-dataset" # Убедитесь, что это ваш ID репозитория
 
16
  my_episodes = None
17
  dataset_features = None
18
  playback_active = False # Флаг для управления воспроизведением
 
19
 
20
  # --- Функция загрузки и подготовки данных ---
21
  def load_and_prepare_dataset():
 
66
  def display_step_data(selected_episode_idx, step_idx):
67
  global my_episodes
68
 
69
+ # Убедимся, что selected_episode_idx не None
70
  if selected_episode_idx is None:
71
  return "", None, {}, {}
72
 
73
  if not my_episodes or selected_episode_idx not in my_episodes:
74
+ #print(f"DEBUG: No episodes loaded or selected_episode_idx {selected_episode_idx} not in my_episodes.")
75
  return "Данные эпизода не найдены.", None, {}, {}
76
 
77
  episode_steps = my_episodes.get(selected_episode_idx)
78
  if not episode_steps:
79
+ #print(f"DEBUG: Episode {selected_episode_idx} is empty.")
80
  return "Данные эпизода пусты.", None, {}, {}
81
 
82
+ # Убедимся, что step_idx находится в допустимых границах
83
  if not (0 <= step_idx < len(episode_steps)):
84
+ #print(f"DEBUG: Invalid step_idx {step_idx} for episode {selected_episode_idx} with {len(episode_steps)} steps.")
85
  return "Неверный номер шага или шаг вне диапазона.", None, {}, {}
86
 
87
  step_data = episode_steps[step_idx]
88
 
89
+ # Подготовьте информацию о шаге
90
  step_info = (
91
  f"Эпизод: {step_data.get('episode_index', 'N/A')}, "
92
  f"Шаг: {step_idx}/{len(episode_steps)-1}, "
 
96
  f"Timestamp: {step_data.get('timestamp', 0.0):.2f}"
97
  )
98
 
99
+ # Обработка изображения
100
  image_pil = None
101
  if 'observation.camera_image_left' in step_data:
102
  img_data = step_data['observation.camera_image_left']
 
109
  print(f"Error opening image from bytes: {e}")
110
  elif img_data is not None:
111
  print(f"Unexpected image format type: {type(img_data)}")
 
 
 
112
 
113
 
114
+ # Обработка наблюдений (исключаем image, так как он уже обработан)
115
+ observation_data = {}
116
+ for k, v in step_data.items():
117
+ if k.startswith("observation.") and k != "observation.camera_image_left":
118
+ clean_key = k[len("observation."):]
119
+ if isinstance(v, np.ndarray):
120
+ observation_data[clean_key] = v.squeeze().tolist()
121
+ else:
122
+ observation_data[clean_key] = v
123
+
124
+
125
+ # Обработка действий
126
+ action_data = {}
127
+ for k, v in step_data.items():
128
+ if k.startswith("action."):
129
+ clean_key = k[len("action."):]
130
+ if isinstance(v, np.ndarray):
131
+ action_data[clean_key] = v.squeeze().tolist()
132
+ else:
133
+ action_data[clean_key] = v
134
+
135
+ return step_info, image_pil, observation_data, action_data
136
+
137
  # --- Функция для обновления информации об эпизоде при выборе ---
138
  def update_episode_info(selected_episode_idx):
139
  global my_episodes
140
  if not my_episodes or selected_episode_idx is None:
141
+ return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}
142
 
143
  episode_steps = my_episodes.get(selected_episode_idx)
144
  if not episode_steps:
145
+ return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}
146
 
147
  num_steps = len(episode_steps)
148
  if num_steps == 0:
149
+ return gr.update(maximum=0, value=0), "0", "Нет данных", None, {}, {}
150
 
 
151
  step_info, image_pil, observation_data, action_data = display_step_data(selected_episode_idx, 0)
152
 
153
  return (
 
156
  step_info,
157
  image_pil,
158
  observation_data,
159
+ action_data
 
160
  )
161
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
 
163
  # --- Функция для анализа данных (гистограммы положений суставов) ---
164
  def analyze_data():
 
238
  return fig
239
 
240
 
241
+ # --- Функция воспроизведения шагов ---
242
+ def play_steps(selected_episode_idx, current_step, step_slider_max):
243
+ global my_episodes, playback_active
244
+
245
+ # Если уже активно, не запускаем повторно
246
+ if playback_active:
247
+ return current_step # Возвращаем текущее значение, не меняем
248
+
249
+ # Проверка на выбранный эпизод и наличие данных
250
+ if selected_episode_idx is None or selected_episode_idx not in my_episodes or not my_episodes[selected_episode_idx]:
251
+ # Возвращаем текущий шаг, если данных нет
252
+ return current_step
253
+
254
+ episode_steps = my_episodes.get(selected_episode_idx)
255
+ num_steps = len(episode_steps)
256
+
257
+ # Убедимся, что num_steps корректен
258
+ if num_steps == 0:
259
+ return current_step
260
+
261
+ playback_active = True
262
+
263
+ # Начинаем воспроизведение с текущего шага
264
+ # Если текущий шаг больше максимального или отрицательный, начинаем с 0
265
+ start_step = current_step if 0 <= current_step < num_steps else 0
266
+
267
+ for i in range(start_step, num_steps):
268
+ if not playback_active: # Проверка флага остановки
269
+ print("Воспроизведение остановлено.")
270
+ break
271
+
272
+ yield i # Возвращаем новое значение для слайдера
273
+ time.sleep(0.1) # Задержка между шагами (можно настроить)
274
+
275
+ playback_active = False # Воспроизведение завершено
276
+ # После завершения воспроизведения, установить слайдер на последний шаг (или 0, если пустой)
277
+ yield num_steps - 1 if num_steps > 0 else 0
278
+
279
+
280
+ def stop_playback(current_step): # Добавляем current_step как вход
281
+ global playback_active
282
+ playback_active = False
283
+ return "Воспроизведение остановлено.", current_step # Возвращаем сообщение и текущий шаг
284
+
285
+
286
  # --- Gradio интерфейс ---
287
  with gr.Blocks() as demo:
288
  gr.Markdown("# Интерактивный просмотр датасета робота Ainex")
 
296
  episode_selector = gr.Dropdown(label="Выберите эпизод (1-индексированный)", choices=[], interactive=True)
297
  num_steps_in_episode_output = gr.Textbox(label="Всего шагов в эпизоде", interactive=False)
298
 
299
+ with gr.Row():
300
+ step_slider = gr.Slider(minimum=0, maximum=0, value=0, label="Выберите шаг (0-индексированный)", step=1, interactive=True, scale=4)
301
+ play_button = gr.Button("▶️ Воспроизвести", scale=1)
302
+ stop_button = gr.Button("⏸️ Остановить", scale=1)
303
 
304
  analyze_button = gr.Button("Анализ данных (Гистограмма Joint Positions)")
305
  plot_actions_button = gr.Button("Показать график действий")
 
307
 
308
  with gr.Column(scale=2):
309
  step_info_output = gr.Textbox(label="Информация о шаге", interactive=False)
310
+ image_output = gr.Image(label="Изображение с камеры робота", type="pil", height=480)
311
 
312
  with gr.Accordion("Детальные данные", open=True):
313
  observation_output = gr.Json(label="Наблюдения (observation)")
 
328
  ).then(
329
  update_episode_info,
330
  inputs=episode_selector,
331
+ outputs=[step_slider, num_steps_in_episode_output, step_info_output, image_output, observation_output, action_output]
332
  )
333
 
334
  episode_selector.change(
335
  update_episode_info,
336
  inputs=episode_selector,
337
+ outputs=[step_slider, num_steps_in_episode_output, step_info_output, image_output, observation_output, action_output]
338
  )
339
 
 
340
  step_slider.change(
341
  display_step_data,
342
  inputs=[episode_selector, step_slider],
343
+ outputs=[step_info_output, image_output, observation_output, action_output]
344
  )
345
 
346
  refresh_button.click(
 
350
  ).then(
351
  update_episode_info,
352
  inputs=episode_selector,
353
+ outputs=[step_slider, num_steps_in_episode_output, step_info_output, image_output, observation_output, action_output]
354
  )
355
 
356
  analyze_button.click(
 
359
  outputs=[analysis_text_output, analysis_plot_output]
360
  )
361
 
362
+ # --- ИСПРАВЛЕНИЕ КНОПОК PLAY/STOP ---
363
+ play_button.click(
364
+ play_steps,
365
+ inputs=[episode_selector, step_slider, step_slider], # Добавляем step_slider как вход для его свойства maximum
366
+ outputs=[step_slider],
367
+ queue=False
368
+ )
369
+
370
+ stop_button.click(
371
+ stop_playback,
372
+ inputs=[step_slider], # Добавляем step_slider как вход
373
+ outputs=[refresh_status, step_slider], # Обновляем статус и текущий шаг слайдера
374
+ queue=False
375
  )
376
 
377
  plot_actions_button.click(
 
380
  outputs=action_plot_output
381
  )
382
 
 
 
 
383
  demo.launch(debug=True)