KillzoneCCO commited on
Commit
073aeea
·
verified ·
1 Parent(s): 4836425

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -199
app.py CHANGED
@@ -9,7 +9,7 @@ import io
9
 
10
  # --- Настройки вашего датасета ---
11
  DATASET_REPO_ID = "KillzoneCCO/my-ainex-robot-dataset"
12
- DATASET_SPLIT = "train"
13
 
14
  # Глобальная переменная для хранения загруженного и сгруппированного датасета
15
  my_episodes = None
@@ -36,244 +36,232 @@ def load_and_prepare_dataset():
36
  row["episode_index"] = 0
37
  print(f"Warning: 'episode_index' not found for row {i}, defaulting to 0.")
38
 
39
- # ИСПРАВЛЕНО: Используем 1-индексированный номер эпизода для ключа
40
- episode_idx_display = episode_idx_raw + 1
41
-
42
  if episode_idx_display not in episodes_data:
43
  episodes_data[episode_idx_display] = []
44
  episodes_data[episode_idx_display].append(row)
45
 
46
- sorted_episodes = dict(sorted(episodes_data.items()))
47
- my_episodes = sorted_episodes
48
- print(f"Dataset loaded and prepared. Number of episodes: {len(my_episodes)}")
49
-
50
- episode_keys = list(my_episodes.keys())
51
- # Если эпизоды есть, выбираем первый для инициализации (теперь это 1-индексированный ключ)
52
- initial_episode_value = episode_keys[0] if episode_keys else None
53
-
54
- return "Данные успешно загружены!", gr.update(choices=episode_keys, value=initial_episode_value)
55
- except Exception as e:
56
- error_msg = f"Ошибка при загрузке или обработке датасета: {e}"
57
- print(error_msg)
58
- my_episodes = error_msg
59
- return error_msg, gr.update(choices=[], value=None)
60
-
61
- # --- Функции для Gradio интерфейса ---
62
-
63
- def get_num_steps_in_episode(episode_idx):
64
- """Возвращает количество шагов в выбранном эпизоде."""
65
- if isinstance(my_episodes, str) or not my_episodes:
66
- return 0
67
- return len(my_episodes.get(episode_idx, []))
68
-
69
- def update_episode_info(episode_idx):
70
- """Обновляет информацию при выборе нового эпизода."""
71
- print(f"update_episode_info called with episode_idx: {episode_idx}")
72
- if isinstance(my_episodes, str):
73
- return my_episodes, 0, 0, "", None, "", ""
74
-
75
- # Если episode_idx не выбран (например, при первом запуске) или список пуст
76
- if episode_idx is None:
77
- if my_episodes:
78
- # ИСПРАВЛЕНО: Берем первый 1-индексированный ключ из my_episodes
79
- episode_idx = list(my_episodes.keys())[0]
80
- print(f"Defaulting to first episode: {episode_idx}")
81
- else:
82
- print("No episodes available to select in update_episode_info.")
83
- return gr.update(maximum=0, value=0), 0, 0, "Нет доступных данных.", None, "", ""
84
-
85
- num_steps = get_num_steps_in_episode(episode_idx)
86
-
87
- step_slider_update = gr.update(minimum=0, maximum=max(0, num_steps - 1), value=0)
88
-
89
- step_info, image, obs_text, action_text = display_step_data(episode_idx, 0)
90
-
91
- return step_slider_update, num_steps, 0, step_info, image, obs_text, action_text
92
 
 
 
 
93
 
94
- def display_step_data(episode_idx, step_idx):
95
- """Отображает данные для конкретного шага в эпизоде."""
96
- print(f"display_step_data called with episode_idx: {episode_idx}, step_idx: {step_idx}")
97
- if isinstance(my_episodes, str):
98
- return my_episodes, None, "", ""
99
 
100
- episode = my_episodes.get(episode_idx)
101
- if not episode or not (0 <= step_idx < len(episode)):
102
- print(f"Error: Invalid episode_idx ({episode_idx}) or step_idx ({step_idx}). Episode length: {len(episode) if episode else 0}")
103
- return "Неверный эпизод или индекс шага.", None, "", ""
 
104
 
105
- record = episode[step_idx]
 
106
 
107
- # --- Подготовка изображения ---
108
- image_to_display = None
109
- if "observation.camera_image_left" in record and record["observation.camera_image_left"] is not None:
110
- image_data = record["observation.camera_image_left"]
111
- try:
112
- if isinstance(image_data, PILImage.Image):
113
- image_to_display = image_data
114
- elif isinstance(image_data, np.ndarray):
115
- if image_data.ndim == 2:
116
- image_data = np.stack([image_data]*3, axis=-1)
117
- image_to_display = PILImage.fromarray(image_data.astype(np.uint8))
118
- else:
119
- print(f"Warning: Unknown image format (type: {type(image_data)}). Could not display.")
120
- except Exception as img_e:
121
- print(f"Error processing image: {img_e}")
122
- else:
123
- print("Image 'observation.camera_image_left' not found or is None.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
- # --- Подготовка текстовых наблюдений ---
126
  observation_text = ""
127
- for key, value in record.items():
128
- if key.startswith("observation.") and not key.endswith("camera_image_left"):
129
- observation_text += f"{key.replace('observation.', '')}: {value}\n"
 
 
 
 
 
 
 
130
 
131
- # --- Подготовка текстовых действий ---
132
  action_text = ""
133
- for key, value in record.items():
134
- if key.startswith("action."):
135
- action_text += f"{key.replace('action.', '')}: {value}\n"
136
-
137
- # --- Подготовка общей информации о шаге ---
138
- step_info_text = f"Шаг: {step_idx}\n"
139
- step_info_text += f"Вознаграждение (reward): {record.get('reward', 'N/A')}\n"
140
- step_info_text += f"Завершено (terminated): {record.get('terminated', 'N/A')}\n"
141
- step_info_text += f"Сокращено (truncated): {record.get('truncated', 'N/A')}\n"
142
- step_info_text += f"Временная метка (timestamp): {record.get('timestamp', 'N/A')}\n"
143
 
144
- return step_info_text, image_to_display, observation_text, action_text
145
 
 
146
  def analyze_dataset_stats():
147
- """Выполняет базовый статистический анализ датасета."""
148
- print("analyze_dataset_stats called.")
149
- if isinstance(my_episodes, str):
150
- return my_episodes, None
151
  if not my_episodes:
152
- return "Нет загруженных данных для анализа.", None
 
 
 
 
 
 
 
153
 
154
  all_rewards = []
155
  all_x = []
156
  all_y = []
157
  all_angle = []
158
- all_action_axes_0 = []
159
- all_action_axes_1 = []
 
160
 
161
  for episode_idx in my_episodes:
162
  for record in my_episodes[episode_idx]:
163
- all_rewards.append(record.get('reward', 0.0))
164
- if 'observation.x' in record:
 
165
  all_x.append(record['observation.x'])
166
- if 'observation.y' in record:
167
  all_y.append(record['observation.y'])
168
- if 'observation.angle' in record:
169
  all_angle.append(record['observation.angle'])
 
 
 
 
170
 
171
- if 'action.axes' in record and isinstance(record['action.axes'], list):
172
- if len(record['action.axes']) > 0:
173
- all_action_axes_0.append(record['action.axes'][0])
174
- else:
175
- all_action_axes_0.append(0.0)
176
- if len(record['action.axes']) > 1:
177
- all_action_axes_1.append(record['action.axes'][1])
178
- else:
179
- all_action_axes_1.append(0.0)
180
- elif 'action.axes' in record and isinstance(record['action.axes'], (int, float)):
181
- all_action_axes_0.append(record['action.axes'])
182
- all_action_axes_1.append(0.0)
183
-
184
- stats_output = "### Статистика по наградам:\n"
185
  if all_rewards:
186
- stats_output += f"Средняя награда: {np.mean(all_rewards):.2f}\n"
187
- stats_output += f"Медиана награды: {np.median(all_rewards):.2f}\n"
188
- stats_output += f"Стандартное отклонение награды: {np.std(all_rewards):.2f}\n"
189
- stats_output += f"Минимальная награда: {np.min(all_rewards):.2f}\n"
190
- stats_output += f"Максимальная награда: {np.max(all_rewards):.2f}\n\n"
191
  else:
192
- stats_output += "Нет данных по наградам.\n\n"
193
 
194
- stats_output += "### Статистика по наблюдениям (x, y, angle):\n"
 
 
 
 
 
 
 
 
 
 
 
 
195
  if all_x:
196
- stats_output += f"Среднее X: {np.mean(all_x):.2f}, Среднее Y: {np.mean(all_y):.2f}, Средний угол: {np.mean(all_angle):.2f}\n"
197
- stats_output += f"Стд. откл. X: {np.std(all_x):.2f}, Стд. откл. Y: {np.std(all_y):.2f}, Стд. откл. угла: {np.std(all_angle):.2f}\n\n"
198
  else:
199
- stats_output += "Нет данных для X, Y, Angle.\n\n"
200
-
201
- stats_output += "### Статистика по действиям (axes):\n"
202
- if all_action_axes_0:
203
- stats_output += f"Среднее action.axes[0]: {np.mean(all_action_axes_0):.2f}, Среднее action.axes[1]: {np.mean(all_action_axes_1):.2f}\n"
204
- stats_output += f"Стд. откл. action.axes[0]: {np.std(all_action_axes_0):.2f}, Стд. откл. action.axes[1]: {np.std(all_action_axes_1):.2f}\n"
 
 
205
  else:
206
- stats_output += "Нет данных для action.axes.\n"
207
-
208
- plt.figure(figsize=(10, 6))
209
- if all_rewards:
210
- plt.plot(all_rewards)
211
- plt.title("Награда по шагам")
212
- plt.xlabel("Шаг")
213
- plt.ylabel("Награда")
214
- plt.grid(True)
215
  else:
216
- plt.text(0.5, 0.5, "Нет данных для построения графика награды", horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes)
217
- plt.title("График награды")
 
 
 
 
 
 
 
 
 
 
 
218
 
219
- buf = io.BytesIO()
220
- plt.savefig(buf, format='png')
221
- buf.seek(0)
222
- plt.close()
223
-
224
- return stats_output, PILImage.open(buf)
225
 
226
- # --- Создаем Gradio интерфейс ---
227
- with gr.Blocks() as demo:
228
- gr.Markdown(f"# Визуализация и анализ датасета `{DATASET_REPO_ID}`")
229
- gr.Markdown("Здесь вы можете просмотреть информацию о вашем собранном датасете робота, сгруппированную по эпизодам, а также выполнить базовый анализ.")
 
 
 
 
230
 
231
- refresh_button = gr.Button("Обновить данные с Hugging Face Hub")
232
- refresh_status = gr.Textbox(label="Статус обновления", interactive=False)
 
 
 
 
 
233
 
234
- with gr.Tab("Просмотр данных"):
235
  with gr.Row():
236
- with gr.Column(scale=1):
237
- gr.Markdown("### Выбор эпизода")
238
- episode_selector = gr.Dropdown(
239
- label="Выберите эпизод",
240
- choices=[],
241
- value=None,
242
- interactive=True
243
- )
244
- num_steps_in_episode_output = gr.Number(label="Всего шагов в эпизоде", value=0, precision=0, interactive=False)
245
-
246
- gr.Markdown("### Навигация по шагам")
247
- step_slider = gr.Slider(
248
- minimum=0,
249
- maximum=0,
250
- value=0,
251
- step=1,
252
- label="Шаг в эпизоде",
253
- interactive=True
254
- )
255
-
256
- step_info_output = gr.Textbox(label="Информация о шаге", lines=5, interactive=False)
257
-
258
- with gr.Column(scale=2):
259
- gr.Markdown("### Визуализация")
260
- image_output = gr.Image(label="Изображение с камеры", type="pil", height=400, show_label=True)
261
-
262
- with gr.Row():
263
- observation_output = gr.Textbox(label="Наблюдения", lines=10, interactive=False)
264
- action_output = gr.Textbox(label="Действия", lines=10, interactive=False)
265
-
266
- with gr.Tab("Анализ данных"):
267
- gr.Markdown("### Статистический анализ и графики")
268
- analyze_button = gr.Button("Выполнить анализ")
269
- stats_output = gr.Textbox(label="Статистика датасета", lines=20, interactive=False)
270
- reward_plot = gr.Plot(label="График награды по шагам")
271
 
272
- analyze_button.click(
273
- analyze_dataset_stats,
274
- inputs=None,
275
- outputs=[stats_output, reward_plot]
276
- )
 
 
 
277
 
278
  # --- Логика взаимодействия ---
279
  demo.load(
@@ -308,6 +296,10 @@ with gr.Blocks() as demo:
308
  outputs=[step_slider, num_steps_in_episode_output, step_slider, step_info_output, image_output, observation_output, action_output]
309
  )
310
 
311
- # Запуск приложения Gradio
312
- demo.launch()
 
 
 
313
 
 
 
9
 
10
  # --- Настройки вашего датасета ---
11
  DATASET_REPO_ID = "KillzoneCCO/my-ainex-robot-dataset"
12
+ DATASET_SPLIT = "train"
13
 
14
  # Глобальная переменная для хранения загруженного и сгруппированного датасета
15
  my_episodes = None
 
36
  row["episode_index"] = 0
37
  print(f"Warning: 'episode_index' not found for row {i}, defaulting to 0.")
38
 
39
+ # Используем 1-индексированный номер эпизода для ключа
40
+ episode_idx_display = int(episode_idx_raw) + 1
 
41
  if episode_idx_display not in episodes_data:
42
  episodes_data[episode_idx_display] = []
43
  episodes_data[episode_idx_display].append(row)
44
 
45
+ # Сортируем шаги внутри каждого эпизода по времени, если timestamp доступен
46
+ for ep_id in episodes_data:
47
+ episodes_data[ep_id] = sorted(episodes_data[ep_id], key=lambda x: x.get('timestamp', 0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ my_episodes = episodes_data
50
+ print(f"Датасет загружен. Всего эпизодов: {len(my_episodes)}")
51
+ return f"Датасет '{DATASET_REPO_ID}' успешно загружен.", sorted(list(my_episodes.keys()))
52
 
53
+ except Exception as e:
54
+ error_msg = f"Ошибка при загрузке датасета: {e}. Проверьте ID репозитория или ваше интернет-соединение."
55
+ print(error_msg)
56
+ my_episodes = {}
57
+ return error_msg, []
58
 
59
+ # --- Функция для обновления информации об эпизоде и слайдере шагов ---
60
+ def update_episode_info(episode_index_display):
61
+ global my_episodes
62
+ if not my_episodes or episode_index_display not in my_episodes:
63
+ return 0, "0", 0, "", None, "", "" # Сброс всех полей
64
 
65
+ episode_data = my_episodes[episode_index_display]
66
+ num_steps = len(episode_data)
67
 
68
+ # Сброс слайдера до 0 и вызов display_step_data для первого шага
69
+ initial_step_index = 0
70
+ step_info, image_out, obs_out, act_out = display_step_data(episode_index_display, initial_step_index)
71
+
72
+ return gr.Slider(minimum=0, maximum=num_steps-1, value=initial_step_index, step=1, label=f"Шаг в эпизоде {episode_index_display}"), \
73
+ str(num_steps), \
74
+ initial_step_index, \
75
+ step_info, image_out, obs_out, act_out
76
+
77
+ # --- Функция для отображения данных конкретного шага ---
78
+ def display_step_data(episode_index_display, step_index):
79
+ global my_episodes
80
+ if not my_episodes or episode_index_display not in my_episodes:
81
+ return "Нет данных для выбранного эпизода.", None, "",""
82
+
83
+ episode_data = my_episodes[episode_index_display]
84
+ if not (0 <= step_index < len(episode_data)):
85
+ return "Неверный индекс шага.", None, "",""
86
+
87
+ record = episode_data[step_index]
88
+
89
+ step_info = f"Эпизод: {record.get('episode_index', 'N/A') + 1}, Шаг: {step_index}\n"
90
+ step_info += f"Timestamp: {record.get('timestamp', 'N/A'):.2f}\n"
91
+ step_info += f"Награда: {record.get('reward', 'N/A'):.2f}\n"
92
+ step_info += f"Завершено: {record.get('terminated', 'N/A')}\n"
93
+ step_info += f"Усечено: {record.get('truncated', 'N/A')}"
94
+
95
+ # Отображение изображения
96
+ image_out = None
97
+ if 'observation.camera_image_left' in record and record['observation.camera_image_left'] is not None:
98
+ if isinstance(record['observation.camera_image_left'], PILImage.Image):
99
+ image_out = record['observation.camera_image_left']
100
+ elif isinstance(record['observation.camera_image_left'], dict) and 'bytes' in record['observation.camera_image_left']:
101
+ # Обработка случая, когда изображение загружается как объект Image из datasets
102
+ image_bytes = record['observation.camera_image_left']['bytes']
103
+ try:
104
+ image_out = PILImage.open(io.BytesIO(image_bytes))
105
+ except Exception as e:
106
+ print(f"Error opening image bytes: {e}")
107
+ image_out = None
108
 
109
+ # Отображение наблюдений
110
  observation_text = ""
111
+ if 'observation.x' in record and record['observation.x'] is not None:
112
+ observation_text += f"Позиция X: {record['observation.x']:.2f}\n"
113
+ if 'observation.y' in record and record['observation.y'] is not None:
114
+ observation_text += f"Позиция Y: {record['observation.y']:.2f}\n"
115
+ if 'observation.angle' in record and record['observation.angle'] is not None:
116
+ observation_text += f"Угол: {np.degrees(record['observation.angle']):.2f}°\n"
117
+ if 'observation.is_walking' in record and record['observation.is_walking'] is not None:
118
+ observation_text += f"Робот идет: {record['observation.is_walking']}\n"
119
+ if 'observation.button_state' in record and record['observation.button_state'] is not None:
120
+ observation_text += f"Состояние кнопок: {record['observation.button_state']}\n"
121
 
122
+ # Отображение действий (сервоприводов)
123
  action_text = ""
124
+ if "action.servo_positions" in record and record["action.servo_positions"] is not None:
125
+ action_text += "Позиции сервоприводов (ID 1-25):\n"
126
+ # Для удобства можно вывести первые несколько и последние несколько, или всю строку
127
+ servo_pos_list = record["action.servo_positions"]
128
+ action_text += f"{[f'{p:.2f}' for p in servo_pos_list]}" # Выводим все 25 значений
 
 
 
 
 
129
 
130
+ return step_info, image_out, observation_text, action_text
131
 
132
+ # --- Функция для анализа и отображения общей статистики датасета ---
133
  def analyze_dataset_stats():
134
+ global my_episodes
 
 
 
135
  if not my_episodes:
136
+ return "Датасет не загружен.", None
137
+
138
+ stats_output = ""
139
+
140
+ total_steps = sum(len(ep) for ep in my_episodes.values())
141
+ stats_output += f"## Общая статистика датасета\n"
142
+ stats_output += f"- Всего эпизодов: {len(my_episodes)}\n"
143
+ stats_output += f"- Всего шагов: {total_steps}\n\n"
144
 
145
  all_rewards = []
146
  all_x = []
147
  all_y = []
148
  all_angle = []
149
+ all_is_walking = []
150
+ all_button_state = []
151
+ all_servo_positions = [[] for _ in range(25)] # Список списков для каждого сервопривода
152
 
153
  for episode_idx in my_episodes:
154
  for record in my_episodes[episode_idx]:
155
+ if 'reward' in record and record['reward'] is not None:
156
+ all_rewards.append(record['reward'])
157
+ if 'observation.x' in record and record['observation.x'] is not None:
158
  all_x.append(record['observation.x'])
159
+ if 'observation.y' in record and record['observation.y'] is not None:
160
  all_y.append(record['observation.y'])
161
+ if 'observation.angle' in record and record['observation.angle'] is not None:
162
  all_angle.append(record['observation.angle'])
163
+ if 'observation.is_walking' in record and record['observation.is_walking'] is not None:
164
+ all_is_walking.append(record['observation.is_walking'])
165
+ if 'observation.button_state' in record and record['observation.button_state'] is not None:
166
+ all_button_state.append(record['observation.button_state'])
167
 
168
+ if 'action.servo_positions' in record and isinstance(record['action.servo_positions'], list):
169
+ for i, pos in enumerate(record['action.servo_positions']):
170
+ if i < 25: # Убедимся, что не выходим за пределы
171
+ all_servo_positions[i].append(pos)
172
+
173
+ # Статистика по наградам
174
+ stats_output += "### Статистика по наградам\n"
 
 
 
 
 
 
 
175
  if all_rewards:
176
+ stats_output += f"- Средняя награда: {np.mean(all_rewards):.2f}\n"
177
+ stats_output += f"- Минимальная награда: {np.min(all_rewards):.2f}\n"
178
+ stats_output += f"- Максимальная награда: {np.max(all_rewards):.2f}\n"
179
+ stats_output += f"- Стандартное отклонение награды: {np.std(all_rewards):.2f}\n\n"
 
180
  else:
181
+ stats_output += "- Нет данных по наградам.\n\n"
182
 
183
+ # Гистограмма награды
184
+ fig_reward, ax_reward = plt.subplots()
185
+ if all_rewards:
186
+ ax_reward.hist(all_rewards, bins=20, edgecolor='black')
187
+ ax_reward.set_title('Распределение награды')
188
+ ax_reward.set_xlabel('Награда')
189
+ ax_reward.set_ylabel('Частота')
190
+ else:
191
+ ax_reward.text(0.5, 0.5, 'Нет данных по наградам для построения графика',
192
+ horizontalalignment='center', verticalalignment='center', transform=ax_reward.transAxes)
193
+
194
+ # Статистика по положению робота
195
+ stats_output += "### Статистика по положению робота (X, Y, Angle)\n"
196
  if all_x:
197
+ stats_output += f"- Среднее X: {np.mean(all_x):.2f}, Среднее Y: {np.mean(all_y):.2f}\n"
198
+ stats_output += f"- Средний угол: {np.degrees(np.mean(all_angle)):.2f}°\n\n"
199
  else:
200
+ stats_output += "- Нет данных по положению робота.\n\n"
201
+
202
+ # Статистика по состоянию ходьбы
203
+ stats_output += "### Статистика по состоянию ходьбы\n"
204
+ if all_is_walking:
205
+ walking_counts = pd.Series(all_is_walking).value_counts(normalize=True) * 100
206
+ stats_output += f"- Процент времени в состоянии 'идет': {walking_counts.get(True, 0):.2f}%\n"
207
+ stats_output += f"- Процент времени в состоянии 'не идет': {walking_counts.get(False, 0):.2f}%\n\n"
208
  else:
209
+ stats_output += "- Нет данных по состоянию ходьбы.\n\n"
210
+
211
+ # Статистика по состоянию кнопок
212
+ stats_output += "### Статистика по состоянию кнопок\n"
213
+ if all_button_state:
214
+ button_counts = pd.Series(all_button_state).value_counts(normalize=True) * 100
215
+ for state, percentage in button_counts.items():
216
+ stats_output += f"- Состояние '{state}': {percentage:.2f}%\n"
217
+ stats_output += "\n"
218
  else:
219
+ stats_output += "- Нет данных по состоянию кнопок.\n\n"
220
+
221
+ # Статистика по позициям сервоприводов
222
+ stats_output += "### Статистика по действиям (Servo Positions)\n"
223
+ if all_servo_positions[0]: # Если есть данные хотя бы для первого сервопривода
224
+ for i in range(25):
225
+ if all_servo_positions[i]:
226
+ stats_output += f"- Сервопривод {i+1} (среднее/std): {np.mean(all_servo_positions[i]):.2f} / {np.std(all_servo_positions[i]):.2f}\n"
227
+ else:
228
+ stats_output += f"- Сервопривод {i+1}: Нет данных\n"
229
+ stats_output += "\n"
230
+ else:
231
+ stats_output += "Нет данных для позиций сервоприводов.\n\n"
232
 
233
+ return stats_output, fig_reward
 
 
 
 
 
234
 
235
+ # --- Интерфейс Gradio ---
236
+ with gr.Blocks(title="Визуализация данных робота AiNex") as demo:
237
+ gr.Markdown("# 🤖 Визуализация данных робота AiNex 🤖")
238
+ gr.Markdown(
239
+ "Этот Space позволяет просматривать данные, собранные с вашего робота AiNex "
240
+ "и загруженные в датасет на Hugging Face Hub: "
241
+ f"[`{DATASET_REPO_ID}`](https://huggingface.co/datasets/{DATASET_REPO_ID})."
242
+ )
243
 
244
+ with gr.Tab("Общая информация и Анализ"):
245
+ refresh_status = gr.Textbox(label="Статус загрузки датасета", interactive=False)
246
+ refresh_button = gr.Button("Обновить/Загрузить датасет")
247
+
248
+ analyze_button = gr.Button("Проанализировать датасет")
249
+ stats_output = gr.Textbox(label="Статистика датасета", lines=20, interactive=False)
250
+ reward_plot = gr.Plot(label="График распределения награды")
251
 
252
+ with gr.Tab("Просмотр записей по индексу"):
253
  with gr.Row():
254
+ episode_selector = gr.Dropdown(label="Выберите эпизод", choices=[], interactive=True)
255
+ num_steps_in_episode_output = gr.Textbox(label="Всего шагов в эпизоде", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
 
257
+ step_slider = gr.Slider(minimum=0, maximum=0, value=0, step=1, label="Шаг в эпизоде", interactive=True)
258
+ step_info_output = gr.Textbox(label="Информация о шаге", lines=5, interactive=False)
259
+
260
+ with gr.Row():
261
+ image_output = gr.Image(label="Изображение с камеры", type="pil")
262
+ with gr.Row():
263
+ observation_output = gr.Textbox(label="Наблюдения (Позиция, Состояние ходьбы, Кнопки)", interactive=False, lines=5)
264
+ action_output = gr.Textbox(label="Действия (Позиции сервоприводов)", interactive=False, lines=5)
265
 
266
  # --- Логика взаимодействия ---
267
  demo.load(
 
296
  outputs=[step_slider, num_steps_in_episode_output, step_slider, step_info_output, image_output, observation_output, action_output]
297
  )
298
 
299
+ analyze_button.click(
300
+ analyze_dataset_stats,
301
+ inputs=None,
302
+ outputs=[stats_output, reward_plot]
303
+ )
304
 
305
+ demo.launch()